package cabana import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "slices" "strings" "sync" "testing" "time" "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/bouncer" "git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/party" ) // consentCall is one MCPAdminConsentDecide call the recording provider saw. type consentCall struct { admin uint request string decision pact.MCPAdminConsentDecision } // recordingAdminConsent is a pact.MCPAdminConsent with one pending request // "req1" whose scopes and offline flag the test sets; showErr and decideErr // replace the answers of Show and Decide while set. type recordingAdminConsent struct { mu sync.Mutex requested []string offline bool required bool showErr error decideErr error shows []consentCall calls []consentCall } func (f *recordingAdminConsent) set(fn func(*recordingAdminConsent)) { f.mu.Lock() defer f.mu.Unlock() fn(f) } func (f *recordingAdminConsent) MCPAdminConsentShow(_ context.Context, adminID uint, requestID string) (pact.MCPAdminConsentRequest, error) { f.mu.Lock() defer f.mu.Unlock() f.shows = append(f.shows, consentCall{admin: adminID, request: requestID}) if f.showErr != nil { return pact.MCPAdminConsentRequest{}, f.showErr } if requestID != "req1" { return pact.MCPAdminConsentRequest{}, pact.ErrMCPConsentNotFound } return pact.MCPAdminConsentRequest{ RequestID: "req1", ClientID: "oas_client", ClientName: "Agent", RedirectURI: "myagent:/callback?state=1#frag", Scopes: append([]string(nil), f.requested...), OfflineAccess: f.offline, ConsentRequired: f.required, }, nil } func (f *recordingAdminConsent) MCPAdminConsentDecide(_ context.Context, adminID uint, requestID string, decision pact.MCPAdminConsentDecision) (string, error) { f.mu.Lock() defer f.mu.Unlock() f.calls = append(f.calls, consentCall{admin: adminID, request: requestID, decision: decision}) if f.decideErr != nil { return "", f.decideErr } if requestID != "req1" { return "", pact.ErrMCPConsentNotFound } if !decision.Allow { return "myagent:/callback?error=access_denied", nil } return "myagent:/callback?code=c1", nil } func (f *recordingAdminConsent) lastCall(t *testing.T) consentCall { t.Helper() f.mu.Lock() defer f.mu.Unlock() if len(f.calls) == 0 { t.Fatal("Decide was never called") } return f.calls[len(f.calls)-1] } func (f *recordingAdminConsent) callCount() int { f.mu.Lock() defer f.mu.Unlock() return len(f.calls) } // TestMCPAdminConsent covers the admin consent endpoints over a recording // provider on Postgres (SC-1, D-03, D-09, D-11): 401 anonymous, 403 // interactive_only for a personal-token credential or bearer, 403 for a // POST without X-Requested-With, 404 without a provider and for // pact.ErrMCPConsentNotFound from Show or Decide, requested scopes the // administrator cannot grant and names outside the catalog hidden in // catalog order, the same dropped from an allow, the * collapse, 422 // no_grantable_scopes (also from the provider), deny with no scopes, // offline access only when requested and asked for, unknown body fields, // trailing data and the 16 KiB body cap refused, and the exact arguments // Decide gets. Needs Docker; skips under -short. func TestMCPAdminConsent(t *testing.T) { gdb := consentGorm(t) stamp := time.Now().UnixNano() seed := func(login, perms string, superuser bool) BackendUser { u := BackendUser{FirstName: "Ada", LastName: login, Login: login + "-" + time.Unix(0, stamp).Format("150405.000000000"), Email: login + "@consent.test", Password: "x", Permissions: perms, IsActivated: true, IsSuperuser: superuser} if err := gdb.Create(&u).Error; err != nil { t.Fatal(err) } return u } reader := seed("reader", `{"acme.items.read":1}`, false) writer := seed("writer", `{"acme.items.write":1}`, false) nobody := seed("nobody", `{}`, false) root := seed("root", `{}`, true) reg, err := compileTokenCatalog([]party.Plugin{consentScopesPlugin{}}) if err != nil { t.Fatal(err) } app := backpack.New(nil) if err := app.Publish(gdb); err != nil { t.Fatal(err) } svc := &service{app: app, reg: reg} principalOf := func(u BackendUser, grants ...string) *bouncer.Principal { g := map[string]bool{} for _, code := range grants { g[code] = true } return &bouncer.Principal{ID: u.ID, Backend: true, IsSuperuser: u.IsSuperuser, PermissionGrants: g} } readerP := principalOf(reader, "acme.items.read") writerP := principalOf(writer, "acme.items.write") nobodyP := principalOf(nobody) rootP := principalOf(root) request := func(method, id, body string, p *bouncer.Principal) *http.Request { req := httptest.NewRequest(method, "/mcp/consent/"+id, strings.NewReader(body)) req.Header.Set("X-Requested-With", "XMLHttpRequest") req.SetPathValue("request", id) if p != nil { req = req.WithContext(bouncer.WithUser(req.Context(), p)) } return req } show := func(id string, p *bouncer.Principal) *httptest.ResponseRecorder { rec := httptest.NewRecorder() interactiveOnly(svc.mcpConsentShow)(rec, request(http.MethodGet, id, "", p)) return rec } decideReq := func(req *http.Request) *httptest.ResponseRecorder { rec := httptest.NewRecorder() interactiveOnly(requireAjax(svc.mcpConsentDecide))(rec, req) return rec } decide := func(id, body string, p *bouncer.Principal) *httptest.ResponseRecorder { return decideReq(request(http.MethodPost, id, body, p)) } shownScopes := func(t *testing.T, rec *httptest.ResponseRecorder) ([]string, MCPConsentView) { t.Helper() if rec.Code != http.StatusOK { t.Fatalf("show = %d %s", rec.Code, rec.Body.String()) } var body struct { Data MCPConsentView `json:"data"` } if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatal(err) } names := []string{} for _, sc := range body.Data.Scopes { names = append(names, sc.Name) } return names, body.Data } errorCode := func(rec *httptest.ResponseRecorder) string { var body struct { Error struct { Code string `json:"code"` } `json:"error"` } _ = json.Unmarshal(rec.Body.Bytes(), &body) return body.Error.Code } // interactiveOnlyRefusal reports the 403 body of a personal-token request: // forbidden, details.reason interactive_only. interactiveOnlyRefusal := func(rec *httptest.ResponseRecorder) bool { var body struct { Error struct { Code string `json:"code"` Details struct { Reason string `json:"reason"` } `json:"details"` } `json:"error"` } _ = json.Unmarshal(rec.Body.Bytes(), &body) return rec.Code == http.StatusForbidden && body.Error.Code == "forbidden" && body.Error.Details.Reason == "interactive_only" } t.Run("404 without a provider", func(t *testing.T) { if rec := show("req1", readerP); rec.Code != http.StatusNotFound || errorCode(rec) != "request_not_found" { t.Fatalf("show = %d %s", rec.Code, rec.Body.String()) } if rec := decide("req1", `{"decision":"deny","scopes":[],"offline_access":false}`, readerP); rec.Code != http.StatusNotFound || errorCode(rec) != "request_not_found" { t.Fatalf("decide = %d %s", rec.Code, rec.Body.String()) } }) provider := &recordingAdminConsent{requested: []string{"acme:write", "ghost", "admin:read", "*"}, offline: true, required: true} if err := app.Publish[pact.MCPAdminConsent](provider); err != nil { t.Fatal(err) } t.Run("401 anonymous", func(t *testing.T) { if rec := show("req1", nil); rec.Code != http.StatusUnauthorized { t.Fatalf("show = %d %s", rec.Code, rec.Body.String()) } if rec := decide("req1", `{"decision":"deny"}`, nil); rec.Code != http.StatusUnauthorized { t.Fatalf("decide = %d %s", rec.Code, rec.Body.String()) } if provider.callCount() != 0 { t.Fatal("an anonymous request reached the provider") } }) t.Run("403 interactive_only for personal tokens", func(t *testing.T) { withCred := func(req *http.Request) *http.Request { return req.WithContext(bouncer.WithCredential(req.Context(), &BackendAPIToken{ID: 3})) } rec := httptest.NewRecorder() interactiveOnly(svc.mcpConsentShow)(rec, withCred(request(http.MethodGet, "req1", "", readerP))) if !interactiveOnlyRefusal(rec) { t.Fatalf("show with a token credential = %d %s", rec.Code, rec.Body.String()) } if rec := decideReq(withCred(request(http.MethodPost, "req1", `{"decision":"deny"}`, readerP))); !interactiveOnlyRefusal(rec) { t.Fatalf("decide with a token credential = %d %s", rec.Code, rec.Body.String()) } bearer := request(http.MethodPost, "req1", `{"decision":"deny"}`, readerP) bearer.Header.Set("Authorization", "Bearer "+APITokenPrefix+strings.Repeat("a", 40)) if rec := decideReq(bearer); !interactiveOnlyRefusal(rec) { t.Fatalf("decide with a g15_ bearer = %d %s", rec.Code, rec.Body.String()) } if provider.callCount() != 0 { t.Fatal("a personal-token request reached Decide") } }) t.Run("POST needs X-Requested-With", func(t *testing.T) { req := request(http.MethodPost, "req1", `{"decision":"deny"}`, readerP) req.Header.Del("X-Requested-With") if rec := decideReq(req); rec.Code != http.StatusForbidden { t.Fatalf("decide without X-Requested-With = %d %s", rec.Code, rec.Body.String()) } if provider.callCount() != 0 { t.Fatal("a POST without X-Requested-With reached Decide") } }) t.Run("show hides what the administrator cannot grant", func(t *testing.T) { cases := []struct { p *bouncer.Principal want []string }{ {readerP, []string{"*", "admin:read"}}, {writerP, []string{"*", "admin:read", "acme:write"}}, {rootP, []string{"*", "admin:read", "acme:write"}}, {nobodyP, []string{"*"}}, } for _, tc := range cases { names, view := shownScopes(t, show("req1", tc.p)) if !slices.Equal(names, tc.want) { t.Fatalf("admin %d sees %v, want %v (catalog order, no ghost)", tc.p.ID, names, tc.want) } if view.RequestID != "req1" || view.Client.ID != "oas_client" || view.Client.RedirectHost != "myagent:/callback" || !view.OfflineAccess || !view.ConsentRequired || view.ExpiresAt != "" || view.Admin.Login == "" { t.Fatalf("view = %+v", view) } } _, view := shownScopes(t, show("req1", readerP)) for _, sc := range view.Scopes { if sc.ReadOnly != (sc.Name == "admin:read") || sc.Label == "" { t.Fatalf("scope %+v: read_only must be set for admin:read only and the label filled", sc) } } provider.mu.Lock() last := provider.shows[len(provider.shows)-1] provider.mu.Unlock() if last.admin != reader.ID || last.request != "req1" { t.Fatalf("Show called with %+v", last) } }) t.Run("show 404 for an unknown request and 500 for a provider failure", func(t *testing.T) { if rec := show("nope", readerP); rec.Code != http.StatusNotFound || errorCode(rec) != "request_not_found" { t.Fatalf("unknown = %d %s", rec.Code, rec.Body.String()) } provider.set(func(f *recordingAdminConsent) { f.showErr = errors.New("database down") }) rec := show("req1", readerP) provider.set(func(f *recordingAdminConsent) { f.showErr = nil }) if rec.Code != http.StatusInternalServerError || strings.Contains(rec.Body.String(), "database down") { t.Fatalf("provider failure = %d %s", rec.Code, rec.Body.String()) } if rec := show("req1", &bouncer.Principal{ID: 999999, Backend: true}); rec.Code != http.StatusInternalServerError { t.Fatalf("an administrator missing from backend_users = %d %s", rec.Code, rec.Body.String()) } }) t.Run("allow drops unknown and ungrantable scopes", func(t *testing.T) { rec := decide("req1", `{"decision":"allow","scopes":["ghost","acme:write"," admin:read ","admin:read","nope"],"offline_access":true}`, readerP) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"redirect_uri":"myagent:/callback?code=c1"`) { t.Fatalf("allow = %d %s", rec.Code, rec.Body.String()) } got := provider.lastCall(t) want := consentCall{admin: reader.ID, request: "req1", decision: pact.MCPAdminConsentDecision{Allow: true, Scopes: []string{"admin:read"}, OfflineAccess: true}} if got.admin != want.admin || got.request != want.request || got.decision.Allow != true || !slices.Equal(got.decision.Scopes, want.decision.Scopes) || !got.decision.OfflineAccess { t.Fatalf("Decide got %+v, want %+v", got, want) } }) t.Run("a writer keeps the plugin scope", func(t *testing.T) { if rec := decide("req1", `{"decision":"allow","scopes":["acme:write","admin:read"],"offline_access":false}`, writerP); rec.Code != http.StatusOK { t.Fatalf("allow = %d %s", rec.Code, rec.Body.String()) } got := provider.lastCall(t) if got.admin != writer.ID || !slices.Contains(got.decision.Scopes, "acme:write") || !slices.Contains(got.decision.Scopes, "admin:read") || len(got.decision.Scopes) != 2 || got.decision.OfflineAccess { t.Fatalf("Decide got %+v", got) } }) t.Run("* collapses the grant", func(t *testing.T) { if rec := decide("req1", `{"decision":"allow","scopes":["admin:read","*","acme:write"],"offline_access":false}`, writerP); rec.Code != http.StatusOK { t.Fatalf("allow * = %d %s", rec.Code, rec.Body.String()) } if got := provider.lastCall(t); !slices.Equal(got.decision.Scopes, []string{"*"}) { t.Fatalf("Decide got scopes %v, want [*]", got.decision.Scopes) } }) t.Run("422 no_grantable_scopes", func(t *testing.T) { before := provider.callCount() for _, body := range []string{ `{"decision":"allow","scopes":["acme:write","ghost"],"offline_access":true}`, `{"decision":"allow","scopes":[],"offline_access":false}`, `{"decision":"allow"}`, } { if rec := decide("req1", body, readerP); rec.Code != http.StatusUnprocessableEntity || errorCode(rec) != "no_grantable_scopes" { t.Fatalf("%s = %d %s", body, rec.Code, rec.Body.String()) } } if provider.callCount() != before { t.Fatal("Decide was called for an allow with nothing grantable") } // The provider's own refusal maps to the same answer. provider.set(func(f *recordingAdminConsent) { f.decideErr = pact.ErrMCPConsentNoScopes }) rec := decide("req1", `{"decision":"allow","scopes":["admin:read"]}`, readerP) provider.set(func(f *recordingAdminConsent) { f.decideErr = nil }) if rec.Code != http.StatusUnprocessableEntity || errorCode(rec) != "no_grantable_scopes" { t.Fatalf("provider ErrMCPConsentNoScopes = %d %s", rec.Code, rec.Body.String()) } }) t.Run("deny passes no scopes and no offline access", func(t *testing.T) { rec := decide("req1", `{"decision":"deny","scopes":["admin:read"],"offline_access":true}`, readerP) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "access_denied") { t.Fatalf("deny = %d %s", rec.Code, rec.Body.String()) } got := provider.lastCall(t) if got.admin != reader.ID || got.request != "req1" || got.decision.Allow || len(got.decision.Scopes) != 0 || got.decision.OfflineAccess { t.Fatalf("Decide got %+v, want a bare deny", got) } // A deny never needs grantable scopes, even for an admin with none. if rec := decide("req1", `{"decision":"deny"}`, nobodyP); rec.Code != http.StatusOK { t.Fatalf("deny by an admin without grants = %d %s", rec.Code, rec.Body.String()) } }) t.Run("offline access only when requested and asked for", func(t *testing.T) { for _, tc := range []struct { requested, asked, want bool }{ {true, true, true}, {true, false, false}, {false, true, false}, {false, false, false}, } { provider.set(func(f *recordingAdminConsent) { f.offline = tc.requested }) body := `{"decision":"allow","scopes":["admin:read"],"offline_access":` + map[bool]string{true: "true", false: "false"}[tc.asked] + `}` if rec := decide("req1", body, readerP); rec.Code != http.StatusOK { t.Fatalf("%+v: %d %s", tc, rec.Code, rec.Body.String()) } if got := provider.lastCall(t).decision.OfflineAccess; got != tc.want { t.Fatalf("requested %v asked %v: OfflineAccess %v, want %v", tc.requested, tc.asked, got, tc.want) } } provider.set(func(f *recordingAdminConsent) { f.offline = true }) }) t.Run("404 for ErrMCPConsentNotFound and 500 for other provider errors", func(t *testing.T) { if rec := decide("nope", `{"decision":"allow","scopes":["admin:read"]}`, readerP); rec.Code != http.StatusNotFound || errorCode(rec) != "request_not_found" { t.Fatalf("allow of an unknown request = %d %s", rec.Code, rec.Body.String()) } if rec := decide("nope", `{"decision":"deny"}`, readerP); rec.Code != http.StatusNotFound || errorCode(rec) != "request_not_found" { t.Fatalf("deny of an unknown request = %d %s", rec.Code, rec.Body.String()) } if got := provider.lastCall(t); got.request != "nope" || got.decision.Allow { t.Fatalf("deny of an unknown request reached Decide with %+v", got) } provider.set(func(f *recordingAdminConsent) { f.decideErr = pact.ErrMCPConsentNotFound }) rec := decide("req1", `{"decision":"allow","scopes":["admin:read"]}`, readerP) provider.set(func(f *recordingAdminConsent) { f.decideErr = errors.New("lock timeout") }) failed := decide("req1", `{"decision":"deny"}`, readerP) provider.set(func(f *recordingAdminConsent) { f.decideErr = nil }) if rec.Code != http.StatusNotFound || errorCode(rec) != "request_not_found" { t.Fatalf("Decide ErrMCPConsentNotFound = %d %s", rec.Code, rec.Body.String()) } if failed.Code != http.StatusInternalServerError || strings.Contains(failed.Body.String(), "lock timeout") { t.Fatalf("Decide failure = %d %s", failed.Code, failed.Body.String()) } }) t.Run("malformed bodies and the body cap", func(t *testing.T) { before := provider.callCount() for _, body := range []string{ `{"decision":"allow","scopes":["admin:read"],"extra":1}`, `{"decision":"maybe"}`, `{"decision":""}`, `{}`, `not json`, `{"decision":"deny"}{"decision":"deny"}`, `{"decision":"allow","scopes":"admin:read"}`, `{"decision":"allow","scopes":["admin:read"],"offline_access":true,"pad":"` + strings.Repeat("x", 16<<10) + `"}`, `{"decision":"allow","scopes":["admin:read","` + strings.Repeat("y", 16<<10) + `"]}`, } { if rec := decide("req1", body, readerP); rec.Code != http.StatusBadRequest { short := body if len(short) > 80 { short = short[:80] + "…" } t.Fatalf("body %s = %d %s", short, rec.Code, rec.Body.String()) } } if provider.callCount() != before { t.Fatal("a malformed body reached Decide") } // Just under the cap is accepted. base := `{"decision":"allow","scopes":["admin:read"],"offline_access":false}` padded := base[:len(base)-1] + strings.Repeat(" ", (16<<10)-len(base)-1) + "}" if len(padded) >= 16<<10 { t.Fatalf("padded body is %d bytes", len(padded)) } if rec := decide("req1", padded, readerP); rec.Code != http.StatusOK { t.Fatalf("a body under the cap = %d %s", rec.Code, rec.Body.String()) } }) }