package pier import ( "context" "errors" "net/http" "os" "path/filepath" "slices" "sync/atomic" "testing" "time" "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/compass" "git.golem15.com/golem15/summercms/modules/pact" ) // grantTableVerifier answers the grant stored under each raw token. type grantTableVerifier map[string]pact.MCPGrant func (v grantTableVerifier) MCPVerifyToken(_ context.Context, raw string) (pact.MCPGrant, error) { if g, ok := v[raw]; ok { return g, nil } return pact.MCPGrant{}, pact.ErrMCPTokenInvalid } func (grantTableVerifier) MCPResource() string { return "http://acme.test/mcp" } // countingLinks is a pact.MCPLinkedBackendResolver that links every // frontend user to admin and counts its calls. type countingLinks struct { admin uint calls atomic.Int64 } func (c *countingLinks) LinkedBackendUser(context.Context, uint) (pact.LinkedBackendUser, bool, error) { c.calls.Add(1) return pact.LinkedBackendUser{ID: c.admin, Login: "linked"}, true, nil } // grantApp is an app without a database that publishes verifier and links. func grantApp(t *testing.T, verifier pact.MCPTokenVerifier, links pact.MCPLinkedBackendResolver) *backpack.App { t.Helper() dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: acme\nurl: http://acme.test\n"), 0o644); err != nil { t.Fatal(err) } cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development"}}) if err != nil { t.Fatal(err) } app := backpack.New(cfg) if err := app.Publish[pact.MCPTokenVerifier](verifier); err != nil { t.Fatal(err) } if links != nil { if err := app.Publish[pact.MCPLinkedBackendResolver](links); err != nil { t.Fatal(err) } } return app } // TestBackendOnlyGrant locks how pier resolves an administrator-only OAuth // grant (SC-2, D-01, D-09): no frontend subject even with a frontend guard // registered, no linked-backend lookup, a binding per client and // administrator that never collides with a user grant's, the read/write // ceiling off, a ScopeLimited backend subject, refusal of malformed backend // grants, and a fingerprint that changes when only ScopeLimited does. func TestBackendOnlyGrant(t *testing.T) { exp := time.Now().Add(time.Hour) backend := func(client string, admin uint, scopes ...string) pact.MCPGrant { return pact.MCPGrant{Subject: pact.MCPGrantSubjectBackend, BackendUserID: admin, ClientID: client, TokenID: 3, Scopes: scopes, ExpiresAt: exp} } verifier := grantTableVerifier{ "oas_at_c1_7": backend("c1", 7, "admin:read"), "oas_at_c1_8": backend("c1", 8, "admin:read"), "oas_at_c2_7": backend("c2", 7, "*"), "oas_at_user_too": {Subject: pact.MCPGrantSubjectBackend, UserID: 5, BackendUserID: 7, ClientID: "c1", TokenID: 4, Scopes: []string{"admin:read"}, ExpiresAt: exp}, "oas_at_no_admin": {Subject: pact.MCPGrantSubjectBackend, ClientID: "c1", TokenID: 5, Scopes: []string{"admin:read"}, ExpiresAt: exp}, "oas_at_linked_user": {UserID: 7, BackendUserID: 42, ClientID: "c1", TokenID: 6, Scopes: []string{"read", "backend"}, ExpiresAt: exp}, "oas_at_no_subject_0": {BackendUserID: 7, ClientID: "c1", TokenID: 7, Scopes: []string{"admin:read"}, ExpiresAt: exp}, } links := &countingLinks{admin: 42} r := newIdentityResolver(grantApp(t, verifier, links), Config{}, "user") ctx := context.Background() id, err := r.resolve(ctx, "oas_at_c1_7") if err != nil { t.Fatalf("resolve: %v", err) } if id.Frontend != nil { t.Fatalf("an administrator-only grant got a frontend subject %+v", id.Frontend) } if n := links.calls.Load(); n != 0 { t.Fatalf("the linked-backend resolver was called %d times", n) } if id.Binding != "oauth:backend:c1:7" || id.TokenKind != TokenKindOAuth || !id.ExpiresAt.Equal(exp) { t.Fatalf("identity %+v", id) } if id.ceiling || !id.writes() { t.Fatalf("ceiling %v writes %v, want the ceiling off", id.ceiling, id.writes()) } want := pact.MCPSubject{Guard: BackendGuard, UserID: 7, Scopes: []string{"admin:read"}, ClientID: "c1", TokenID: 3, ScopeLimited: true} if id.Backend == nil || id.Backend.Guard != want.Guard || id.Backend.UserID != want.UserID || id.Backend.ClientID != want.ClientID || id.Backend.TokenID != want.TokenID || !id.Backend.ScopeLimited || !slices.Equal(id.Backend.Scopes, want.Scopes) { t.Fatalf("backend subject %+v, want %+v", id.Backend, want) } if !slices.Equal(id.Scopes, []string{"admin:read"}) { t.Fatalf("scopes %v", id.Scopes) } // The scopes are copies: changing the identity's never reaches the // subject's. id.Scopes[0] = "changed" if id.Backend.Scopes[0] != "admin:read" { t.Fatal("identity and subject share their scopes slice") } other, err := r.resolve(ctx, "oas_at_c1_8") if err != nil || other.Binding != "oauth:backend:c1:8" || other.Binding == id.Binding { t.Fatalf("second administrator of c1: %q %v", other.Binding, err) } if c2, err := r.resolve(ctx, "oas_at_c2_7"); err != nil || c2.Binding != "oauth:backend:c2:7" { t.Fatalf("same administrator on c2: %q %v", c2.Binding, err) } if n := links.calls.Load(); n != 0 { t.Fatalf("the linked-backend resolver was called %d times", n) } for _, raw := range []string{"oas_at_user_too", "oas_at_no_admin", "oas_at_no_subject_0", "oas_at_unknown"} { if _, err := r.resolve(ctx, raw); !errors.Is(err, ErrUnauthorized) { t.Fatalf("%s: err = %v, want ErrUnauthorized", raw, err) } } t.Run("a linked user grant still looks the link up and never collides", func(t *testing.T) { linked, err := r.resolve(ctx, "oas_at_linked_user") if err != nil { t.Fatal(err) } if links.calls.Load() != 1 { t.Fatalf("link lookups = %d, want 1", links.calls.Load()) } if linked.Binding != "oauth:c1:7" || linked.Binding == id.Binding || !linked.ceiling { t.Fatalf("linked identity %+v", linked) } if linked.Frontend == nil || linked.Backend == nil || linked.Backend.ScopeLimited || linked.Backend.UserID != 42 { t.Fatalf("linked subjects %+v %+v", linked.Frontend, linked.Backend) } }) t.Run("the fingerprint changes with ScopeLimited alone", func(t *testing.T) { a, err := r.resolve(ctx, "oas_at_c1_7") if err != nil { t.Fatal(err) } b := a limited := *a.Backend limited.ScopeLimited = false b.Backend = &limited if a.fingerprint() == b.fingerprint() { t.Fatalf("fingerprint %q ignores ScopeLimited", a.fingerprint()) } again, _ := r.resolve(ctx, "oas_at_c1_7") if again.fingerprint() != a.fingerprint() { t.Fatal("the fingerprint of one grant is not stable") } }) } // TestLinkedGrantNoScopeLimit locks the user-mode regression next to the // backend-only branch (SC-2, D-08): a user grant carrying the backend scope // whose link names the consented administrator reaches the real backend // guard with principal.Scope nil, as before the phase, while the same // administrator through an administrator-only grant is scope-limited. // Needs Docker; skips under -short. func TestLinkedGrantNoScopeLimit(t *testing.T) { if testing.Short() { t.Skip("requires testcontainers postgres") } app, db := scopeApp(t) admin := seedScopeAdmin(t, db, "linked-admin", true) exp := time.Now().Add(time.Hour) verifier := grantTableVerifier{ "oas_at_linked": {UserID: 9, BackendUserID: admin, ClientID: "c1", TokenID: 1, Scopes: []string{"read", "backend"}, ExpiresAt: exp}, "oas_at_admin": {Subject: pact.MCPGrantSubjectBackend, BackendUserID: admin, ClientID: "c1", TokenID: 2, Scopes: []string{"admin:read"}, ExpiresAt: exp}, } if err := app.Publish[pact.MCPTokenVerifier](verifier); err != nil { t.Fatal(err) } links := &countingLinks{admin: admin} if err := app.Publish[pact.MCPLinkedBackendResolver](links); err != nil { t.Fatal(err) } r := newIdentityResolver(app, Config{}, "user") g := backendGuard{app: app} ctx := context.Background() linked, err := r.resolve(ctx, "oas_at_linked") if err != nil { t.Fatal(err) } if linked.Backend == nil || linked.Backend.UserID != admin || linked.Backend.ScopeLimited || linked.Backend.ClientID != "c1" { t.Fatalf("linked backend subject %+v", linked.Backend) } for _, method := range []string{http.MethodGet, http.MethodPost} { principal, err := g.principal(ctx, *linked.Backend, method) if err != nil || principal == nil { t.Fatalf("%s principal = %v, %v", method, principal, err) } if principal.Scope != nil { t.Fatalf("%s: a linked user grant got scope limit %+v", method, principal.Scope) } } only, err := r.resolve(ctx, "oas_at_admin") if err != nil || only.Backend == nil { t.Fatalf("administrator-only grant: %+v %v", only.Backend, err) } principal, err := g.principal(ctx, *only.Backend, http.MethodGet) if err != nil || principal == nil || principal.Scope == nil { t.Fatalf("administrator-only principal = %+v, %v, want a scope limit", principal, err) } // admin:read has no POST: the write method gets the empty limit. post, err := g.principal(ctx, *only.Backend, http.MethodPost) if err != nil || post == nil || post.Scope == nil || post.Scope.Full || len(post.Scope.Scopes) != 0 { t.Fatalf("administrator-only POST principal = %+v, %v, want an empty scope limit", post, err) } }