From 7ecfa6087dabb2ec565493b9087aa0755857ad5f Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Sat, 21 Nov 2026 02:00:16 +0100 Subject: [PATCH] test(32.2-05): unit tests for administrator MCP grants, admin consent, account items and access revocation - wristband: TestAuthorizeConsentPath, TestAuthorizeDefaultScopes - pier: TestBackendOnlyGrant, TestLinkedGrantNoScopeLimit (Docker) - cabana: TestTokenScopeNames, TestMCPAdminConsent, TestAccountContributionItems, TestBackendAccessRevokedEvent (Docker); export_test.go exposes the event helper for the de-duplication case --- modules/cabana/account_items_test.go | 349 +++++++++++++ modules/cabana/backend_access_revoked_test.go | 301 ++++++++++++ modules/cabana/export_test.go | 8 + modules/cabana/mcp_admin_consent_test.go | 458 ++++++++++++++++++ modules/cabana/token_scope_names_test.go | 124 +++++ modules/pier/backend_only_grant_test.go | 231 +++++++++ modules/wristband/consent_path_test.go | 204 ++++++++ 7 files changed, 1675 insertions(+) create mode 100644 modules/cabana/account_items_test.go create mode 100644 modules/cabana/backend_access_revoked_test.go create mode 100644 modules/cabana/mcp_admin_consent_test.go create mode 100644 modules/cabana/token_scope_names_test.go create mode 100644 modules/pier/backend_only_grant_test.go create mode 100644 modules/wristband/consent_path_test.go diff --git a/modules/cabana/account_items_test.go b/modules/cabana/account_items_test.go new file mode 100644 index 00000000..06f37f91 --- /dev/null +++ b/modules/cabana/account_items_test.go @@ -0,0 +1,349 @@ +package cabana + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "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" + "gorm.io/gorm" +) + +// TestAccountContributionItems locks per-item rows on My account (SC-3, +// D-12) on Postgres: a section without Items answers items and +// item_actions null exactly as before, a section with Items answers an +// array (empty, never null, for an administrator with no rows) and only the +// item actions the administrator holds the permissions for, an Items +// failure sets the section's error flag with items null and leaves the +// other sections answered, an item action runs inside a transaction Run +// sees through TxFromContext (rolled back when Run fails), answers 404 for +// an item the administrator's Items does not list (Run not called) and for +// Run's pact.ErrAccountItemNotFound, 403 without the permission, 404 for an +// unknown section, a section without Items and an unknown action, 500 when +// Items fails, and boot refuses malformed item sections. Needs Docker; +// skips under -short. +func TestAccountContributionItems(t *testing.T) { + gdb := consentGorm(t) + if err := gdb.Exec(`CREATE TABLE IF NOT EXISTS acme_item_probes (item text NOT NULL)`).Error; err != nil { + t.Fatal(err) + } + if err := gdb.Exec(`DELETE FROM acme_item_probes`).Error; err != nil { + t.Fatal(err) + } + const adminA, adminB, adminFail = 51, 52, 53 + var mu sync.Mutex + type runCall struct { + admin uint + item string + tx bool + } + var runs []runCall + recordRun := func(ctx context.Context, in pact.AccountItemActionInput) *gorm.DB { + tx, ok := TxFromContext(ctx) + mu.Lock() + runs = append(runs, runCall{admin: in.AdminID, item: in.ItemID, tx: ok && tx != nil}) + mu.Unlock() + return tx + } + runCount := func() int { + mu.Lock() + defer mu.Unlock() + return len(runs) + } + + rows := map[uint][]pact.AccountItem{ + adminA: { + {ID: "client:1", Title: "Agent one", Subtitle: "Full access", Meta: []string{"Connected 2026-11-20", "Last used 2026-11-21"}}, + {ID: "gone", Title: "Agent two"}, + {ID: "fails", Title: "Agent three"}, + }, + } + revoke := pact.AccountItemAction{ + Name: "revoke", Label: "Revoke", Confirm: "Revoke :title?", Danger: true, + Run: func(ctx context.Context, in pact.AccountItemActionInput) (pact.AccountActionResult, error) { + tx := recordRun(ctx, in) + if tx != nil { + if err := tx.Exec(`INSERT INTO acme_item_probes (item) VALUES (?)`, in.ItemID).Error; err != nil { + return pact.AccountActionResult{}, err + } + } + switch in.ItemID { + case "gone": + return pact.AccountActionResult{}, pact.ErrAccountItemNotFound + case "fails": + return pact.AccountActionResult{}, errors.New("plugin failure") + } + return pact.AccountActionResult{Message: "Revoked."}, nil + }, + } + rename := pact.AccountItemAction{ + Name: "rename", Label: "Rename", Permissions: []string{"acme.items.manage"}, + Run: func(ctx context.Context, in pact.AccountItemActionInput) (pact.AccountActionResult, error) { + recordRun(ctx, in) + return pact.AccountActionResult{Message: "Renamed."}, nil + }, + } + items := func(_ context.Context, adminID uint) ([]pact.AccountItem, error) { + if adminID == adminFail { + return nil, errors.New("items failed") + } + return rows[adminID], nil + } + sections := []pact.AccountContribution{ + {Name: "plain", Label: "Plain section", Status: func(context.Context, uint) (string, error) { return "Plain status", nil }}, + {Name: "connections", Label: "Connections", ItemsEmpty: "Nothing connected.", Items: items, ItemActions: []pact.AccountItemAction{revoke, rename}}, + {Name: "noactions", Label: "No actions", Items: items}, + } + reg := &Registry{byID: map[string]*CompiledController{}} + if err := compileAccountContributions(reg, []party.Plugin{contributor{id: "acme.links", sections: sections}}); 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} + principal := func(id uint, grants ...string) *bouncer.Principal { + g := map[string]bool{} + for _, code := range grants { + g[code] = true + } + return &bouncer.Principal{ID: id, Backend: true, PermissionGrants: g} + } + + list := func(t *testing.T, p *bouncer.Principal) (int, []map[string]any, string) { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/account/contributions", nil) + if p != nil { + req = req.WithContext(bouncer.WithUser(req.Context(), p)) + } + rec := httptest.NewRecorder() + interactiveOnly(svc.accountContributionsList)(rec, req) + var body struct { + Data []map[string]any `json:"data"` + } + if rec.Code == http.StatusOK { + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + } + return rec.Code, body.Data, rec.Body.String() + } + act := func(p *bouncer.Principal, section, item, action string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/account/contribution-items/"+section+"/"+item+"/actions/"+action, strings.NewReader("{}")) + req.Header.Set("X-Requested-With", "XMLHttpRequest") + req.SetPathValue("name", section) + req.SetPathValue("item", item) + req.SetPathValue("action", action) + if p != nil { + req = req.WithContext(bouncer.WithUser(req.Context(), p)) + } + rec := httptest.NewRecorder() + interactiveOnly(requireAjax(svc.accountContributionItemAction))(rec, req) + return rec + } + probes := func(t *testing.T) []string { + t.Helper() + var out []string + if err := gdb.Raw(`SELECT item FROM acme_item_probes ORDER BY item`).Scan(&out).Error; err != nil { + t.Fatal(err) + } + return out + } + + t.Run("a section without Items answers exactly as before", func(t *testing.T) { + status, data, raw := list(t, principal(adminA)) + if status != http.StatusOK || len(data) != 3 { + t.Fatalf("list = %d %s", status, raw) + } + plain := data[0] + if plain["name"] != "plain" || plain["status"] != "Plain status" { + t.Fatalf("plain section %+v", plain) + } + for _, key := range []string{"items", "item_actions"} { + if v, ok := plain[key]; !ok || v != nil { + t.Fatalf("plain section %s = %v (present %v), want null", key, v, ok) + } + } + if plain["items_empty"] != "" { + t.Fatalf("plain items_empty = %v", plain["items_empty"]) + } + if _, ok := plain["error"]; ok { + t.Fatalf("plain section carries error: %+v", plain) + } + }) + + t.Run("items, item actions filtered by permission and the empty array", func(t *testing.T) { + _, data, _ := list(t, principal(adminA)) + conn := data[1] + rowsOut, _ := conn["items"].([]any) + if len(rowsOut) != 3 { + t.Fatalf("items %+v", conn["items"]) + } + first, _ := rowsOut[0].(map[string]any) + meta, _ := first["meta"].([]any) + if first["id"] != "client:1" || first["title"] != "Agent one" || first["subtitle"] != "Full access" || len(meta) != 2 || meta[1] != "Last used 2026-11-21" { + t.Fatalf("first item %+v", first) + } + second, _ := rowsOut[1].(map[string]any) + if m, ok := second["meta"].([]any); !ok || len(m) != 0 { + t.Fatalf("an item without meta answers %v, want []", second["meta"]) + } + actions, _ := conn["item_actions"].([]any) + if len(actions) != 1 { + t.Fatalf("item actions without manage = %+v", conn["item_actions"]) + } + a, _ := actions[0].(map[string]any) + if a["name"] != "revoke" || a["label"] != "Revoke" || a["confirm"] != "Revoke :title?" || a["danger"] != true || conn["items_empty"] != "Nothing connected." { + t.Fatalf("revoke action %+v items_empty %v", a, conn["items_empty"]) + } + _, withManage, _ := list(t, principal(adminA, "acme.items.manage")) + if acts, _ := withManage[1]["item_actions"].([]any); len(acts) != 2 { + t.Fatalf("item actions with manage = %+v", withManage[1]["item_actions"]) + } + // A section with Items and no item actions answers [] actions. + if acts, ok := data[2]["item_actions"].([]any); !ok || len(acts) != 0 { + t.Fatalf("noactions item_actions = %v", data[2]["item_actions"]) + } + _, dataB, _ := list(t, principal(adminB)) + if itemsB, ok := dataB[1]["items"].([]any); !ok || len(itemsB) != 0 { + t.Fatalf("admin B items = %v, want []", dataB[1]["items"]) + } + if _, ok := dataB[1]["error"]; ok { + t.Fatalf("an empty section carries error: %+v", dataB[1]) + } + }) + + t.Run("an Items failure sets the error flag", func(t *testing.T) { + status, data, raw := list(t, principal(adminFail)) + if status != http.StatusOK || len(data) != 3 { + t.Fatalf("list = %d %s", status, raw) + } + conn := data[1] + if conn["error"] != true || conn["items"] != nil || strings.Contains(raw, "items failed") { + t.Fatalf("failed section %+v", conn) + } + if data[0]["status"] != "Plain status" { + t.Fatalf("the other sections must still answer: %+v", data[0]) + } + if acts, _ := conn["item_actions"].([]any); len(acts) != 1 { + t.Fatalf("item actions of a failed section = %v", conn["item_actions"]) + } + }) + + t.Run("an item action runs in a transaction", func(t *testing.T) { + rec := act(principal(adminA), "connections", "client:1", "revoke") + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"message":"Revoked."`) { + t.Fatalf("revoke = %d %s", rec.Code, rec.Body.String()) + } + mu.Lock() + last := runs[len(runs)-1] + mu.Unlock() + if last != (runCall{admin: adminA, item: "client:1", tx: true}) { + t.Fatalf("Run got %+v", last) + } + if got := probes(t); len(got) != 1 || got[0] != "client:1" { + t.Fatalf("probes = %v, want the committed client:1", got) + } + }) + + t.Run("both 404 paths", func(t *testing.T) { + before := runCount() + if rec := act(principal(adminB), "connections", "client:1", "revoke"); rec.Code != http.StatusNotFound { + t.Fatalf("cross-admin = %d %s", rec.Code, rec.Body.String()) + } + if runCount() != before { + t.Fatal("Run ran for an item the administrator's Items does not list") + } + if rec := act(principal(adminA), "connections", "gone", "revoke"); rec.Code != http.StatusNotFound { + t.Fatalf("ErrAccountItemNotFound = %d %s", rec.Code, rec.Body.String()) + } + if runCount() != before+1 { + t.Fatal("Run did not run for a listed item") + } + if got := probes(t); len(got) != 1 { + t.Fatalf("a 404 Run committed its write: %v", got) + } + }) + + t.Run("a Run failure rolls back and answers 500", func(t *testing.T) { + rec := act(principal(adminA), "connections", "fails", "revoke") + if rec.Code != http.StatusInternalServerError || strings.Contains(rec.Body.String(), "plugin failure") { + t.Fatalf("failing Run = %d %s", rec.Code, rec.Body.String()) + } + if got := probes(t); len(got) != 1 { + t.Fatalf("a failed Run committed its write: %v", got) + } + }) + + t.Run("403 without the permission", func(t *testing.T) { + before := runCount() + if rec := act(principal(adminA), "connections", "client:1", "rename"); rec.Code != http.StatusForbidden { + t.Fatalf("rename without manage = %d %s", rec.Code, rec.Body.String()) + } + if runCount() != before { + t.Fatal("Run ran without the permission") + } + if rec := act(principal(adminA, "acme.items.manage"), "connections", "client:1", "rename"); rec.Code != http.StatusOK { + t.Fatalf("rename with manage = %d %s", rec.Code, rec.Body.String()) + } + }) + + t.Run("unknown targets, Items failure and auth", func(t *testing.T) { + before := runCount() + for name, rec := range map[string]*httptest.ResponseRecorder{ + "unknown section": act(principal(adminA), "ghost", "client:1", "revoke"), + "section without Items": act(principal(adminA), "plain", "client:1", "revoke"), + "unknown action": act(principal(adminA), "connections", "client:1", "nope"), + "no item actions": act(principal(adminA), "noactions", "client:1", "revoke"), + } { + if rec.Code != http.StatusNotFound { + t.Fatalf("%s = %d %s", name, rec.Code, rec.Body.String()) + } + } + if rec := act(principal(adminFail), "connections", "client:1", "revoke"); rec.Code != http.StatusInternalServerError || strings.Contains(rec.Body.String(), "items failed") { + t.Fatalf("Items failure on an action = %d %s", rec.Code, rec.Body.String()) + } + if rec := act(nil, "connections", "client:1", "revoke"); rec.Code != http.StatusUnauthorized { + t.Fatalf("anonymous = %d %s", rec.Code, rec.Body.String()) + } + if runCount() != before { + t.Fatal("Run ran for a refused request") + } + }) + + t.Run("compile refusals", func(t *testing.T) { + run := revoke.Run + for name, bad := range map[string]pact.AccountContribution{ + "item actions without Items": {Name: "x", Label: "x", ItemActions: []pact.AccountItemAction{revoke}}, + "bad item action name": {Name: "x", Label: "x", Items: items, ItemActions: []pact.AccountItemAction{{Name: "no!", Label: "x", Run: run}}}, + "duplicate item action": {Name: "x", Label: "x", Items: items, ItemActions: []pact.AccountItemAction{revoke, revoke}}, + "nil item run": {Name: "x", Label: "x", Items: items, ItemActions: []pact.AccountItemAction{{Name: "a", Label: "x"}}}, + "empty item label": {Name: "x", Label: "x", Items: items, ItemActions: []pact.AccountItemAction{{Name: "a", Run: run}}}, + "blank item label": {Name: "x", Label: "x", Items: items, ItemActions: []pact.AccountItemAction{{Name: "a", Label: " ", Run: run}}}, + } { + err := compileAccountContributions(&Registry{}, []party.Plugin{contributor{id: "acme.bad", sections: []pact.AccountContribution{bad}}}) + if err == nil || !strings.HasPrefix(err.Error(), "cabana: plugin acme.bad contributes account section") { + t.Fatalf("%s: err = %v", name, err) + } + } + // A section with Items and no item actions, and one with only + // ItemsEmpty and no Items, compile. + for _, ok := range []pact.AccountContribution{ + {Name: "y", Label: "y", Items: items}, + {Name: "z", Label: "z", ItemsEmpty: "unused"}, + } { + if err := compileAccountContributions(&Registry{}, []party.Plugin{contributor{id: "acme.ok", sections: []pact.AccountContribution{ok}}}); err != nil { + t.Fatalf("%s: %v", ok.Name, err) + } + } + }) +} diff --git a/modules/cabana/backend_access_revoked_test.go b/modules/cabana/backend_access_revoked_test.go new file mode 100644 index 00000000..5003e417 --- /dev/null +++ b/modules/cabana/backend_access_revoked_test.go @@ -0,0 +1,301 @@ +package cabana_test + +import ( + "bytes" + "context" + "errors" + "net/http" + "slices" + "sync" + "sync/atomic" + "testing" + + "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/bonfire" + "git.golem15.com/golem15/summercms/modules/cabana" + "git.golem15.com/golem15/summercms/modules/pact" +) + +// accessEvents records the in-transaction BackendAccessRevokedEvents and +// the after-commit pact.MCPSubjectChanged events of one app; while fail is +// set the first listener answers an error, so the save rolls back. +type accessEvents struct { + mu sync.Mutex + revoked []cabana.BackendAccessRevokedEvent + subjects []pact.MCPSubjectChanged + fail atomic.Bool +} + +func listenAccessEvents(app *backpack.App) *accessEvents { + rec := &accessEvents{} + app.Events.Listen("test-revoked", func(_ context.Context, ev *cabana.BackendAccessRevokedEvent) error { + rec.mu.Lock() + rec.revoked = append(rec.revoked, *ev) + rec.mu.Unlock() + if rec.fail.Load() { + return errors.New("listener refused") + } + return nil + }) + app.Events.Listen("test-subjects", func(_ context.Context, ev *pact.MCPSubjectChanged) error { + rec.mu.Lock() + rec.subjects = append(rec.subjects, *ev) + rec.mu.Unlock() + return nil + }) + return rec +} + +// take answers and clears what was recorded. +func (r *accessEvents) take() ([]cabana.BackendAccessRevokedEvent, []pact.MCPSubjectChanged) { + r.mu.Lock() + defer r.mu.Unlock() + revoked, subjects := r.revoked, r.subjects + r.revoked, r.subjects = nil, nil + return revoked, subjects +} + +// sortedIDs answers ids sorted, for an order-free comparison. +func sortedIDs(ids []uint) []uint { + out := slices.Clone(ids) + slices.Sort(out) + return out +} + +// TestBackendAccessRevokedEvent locks every D-13 site of +// cabana.BackendAccessRevokedEvent on Postgres (SC-3, D-13): deleting, +// deactivating, another administrator setting a password, an own password +// change, admin:reset-password, a role, own-permissions or superuser change +// and a role's permission change (once, with every holder) each fire one +// event with the right reason, ids and a non-nil Tx; the helper +// de-duplicates ids; a listener error rolls the delete and the role save +// back; a name-only edit fires nothing; and the after-commit +// pact.MCPSubjectChanged emissions of the same saves still happen (none +// for a rolled-back save). Needs Docker; skips under -short. +func TestBackendAccessRevokedEvent(t *testing.T) { + env := newScreensEnv(t) + rec := listenAccessEvents(env.app) + _, rootToken := env.admin(t, "access-root", true, "") + expectRevoked := func(t *testing.T, reason string, ids ...uint) []pact.MCPSubjectChanged { + t.Helper() + revoked, subjects := rec.take() + if len(revoked) != 1 { + t.Fatalf("%s: %d BackendAccessRevokedEvents, want 1: %+v", reason, len(revoked), revoked) + } + ev := revoked[0] + if ev.Reason != reason || !slices.Equal(sortedIDs(ev.AdminIDs), sortedIDs(ids)) || ev.Tx == nil { + t.Fatalf("%s: event %+v, want ids %v with a transaction", reason, ev, ids) + } + return subjects + } + expectSubjects := func(t *testing.T, subjects []pact.MCPSubjectChanged, kind string, ids ...uint) { + t.Helper() + var got []uint + for _, s := range subjects { + if s.Guard != "backend" || s.Kind != kind { + t.Fatalf("MCPSubjectChanged %+v, want guard backend kind %s", s, kind) + } + got = append(got, s.UserID) + } + if !slices.Equal(sortedIDs(got), sortedIDs(ids)) { + t.Fatalf("MCPSubjectChanged ids %v, want %v", got, ids) + } + } + rec.take() + + t.Run("delete", func(t *testing.T) { + gone, _ := env.admin(t, "access-gone", false, "") + rec.take() + env.expect(t, http.StatusOK, http.MethodDelete, userURL(gone.ID), rootToken, nil) + expectSubjects(t, expectRevoked(t, cabana.BackendAccessDeleted, gone.ID), pact.MCPSubjectDeleted, gone.ID) + }) + + t.Run("deactivate", func(t *testing.T) { + target, _ := env.admin(t, "access-off", false, "") + rec.take() + env.expect(t, http.StatusOK, http.MethodPost, userURL(target.ID, "actions", "deactivate"), rootToken, map[string]any{}) + expectSubjects(t, expectRevoked(t, cabana.BackendAccessDeactivated, target.ID), pact.MCPSubjectDeleted, target.ID) + }) + + t.Run("password set by another administrator", func(t *testing.T) { + target, _ := env.admin(t, "access-pw", false, "") + rec.take() + env.expect(t, http.StatusOK, http.MethodPut, userURL(target.ID), rootToken, + map[string]any{"login": target.Login, "email": target.Email, "password": "pass-5678", "password_confirmation": "pass-5678"}) + expectRevoked(t, cabana.BackendAccessPasswordSet, target.ID) + }) + + t.Run("own password change", func(t *testing.T) { + self, selfToken := env.admin(t, "access-self", false, "") + rec.take() + env.expect(t, http.StatusOK, http.MethodPut, "/account", selfToken, + map[string]any{"email": self.Email, "current_password": adminTestPassword, "password": "brand-new-secret", "password_confirmation": "brand-new-secret"}) + expectRevoked(t, cabana.BackendAccessPasswordChanged, self.ID) + }) + + t.Run("admin:reset-password", func(t *testing.T) { + target, _ := env.admin(t, "access-reset", false, "") + rec.take() + reset := commandByName(t, cabana.RuntimeCommands(env.app), "admin:reset-password") + var buf bytes.Buffer + if err := reset.Run(context.Background(), flagInput{ + args: []string{target.Login}, + flags: map[string]string{"password": "reset-replacement-password"}, + }, bonfire.NewOutput(nil, &buf, &buf)); err != nil { + t.Fatalf("admin:reset-password: %v", err) + } + expectRevoked(t, cabana.BackendAccessPasswordReset, target.ID) + }) + + t.Run("admin:reset-password rolls back on a listener error", func(t *testing.T) { + target, _ := env.admin(t, "access-reset-veto", false, "") + before := env.storedUser(t, target.ID).Password + rec.take() + rec.fail.Store(true) + reset := commandByName(t, cabana.RuntimeCommands(env.app), "admin:reset-password") + var buf bytes.Buffer + err := reset.Run(context.Background(), flagInput{ + args: []string{target.Login}, + flags: map[string]string{"password": "reset-replacement-password"}, + }, bonfire.NewOutput(nil, &buf, &buf)) + rec.fail.Store(false) + if err == nil { + t.Fatal("a vetoed reset succeeded") + } + if env.storedUser(t, target.ID).Password != before { + t.Fatal("a vetoed reset wrote the new hash") + } + expectRevoked(t, cabana.BackendAccessPasswordReset, target.ID) + }) + + t.Run("role change", func(t *testing.T) { + target, _ := env.admin(t, "access-role", false, "") + other := env.seedRole(t, roleSeed{Name: "access-other"}) + rec.take() + env.expect(t, http.StatusOK, http.MethodPut, userURL(target.ID), rootToken, + map[string]any{"login": target.Login, "email": target.Email, "role": other.ID}) + expectSubjects(t, expectRevoked(t, cabana.BackendAccessPermissions, target.ID), pact.MCPSubjectPermissions, target.ID) + }) + + t.Run("own permissions change", func(t *testing.T) { + target, _ := env.admin(t, "access-perms", false, "") + rec.take() + env.expect(t, http.StatusOK, http.MethodPut, userURL(target.ID), rootToken, + map[string]any{"login": target.Login, "email": target.Email, "permissions": map[string]any{pingPermission: 1}}) + expectSubjects(t, expectRevoked(t, cabana.BackendAccessPermissions, target.ID), pact.MCPSubjectPermissions, target.ID) + }) + + t.Run("superuser change", func(t *testing.T) { + target, _ := env.admin(t, "access-super", false, "") + rec.take() + env.expect(t, http.StatusOK, http.MethodPut, userURL(target.ID), rootToken, + map[string]any{"login": target.Login, "email": target.Email, "is_superuser": true}) + expectSubjects(t, expectRevoked(t, cabana.BackendAccessPermissions, target.ID), pact.MCPSubjectPermissions, target.ID) + if !env.storedUser(t, target.ID).IsSuperuser { + t.Fatal("the superuser flag was not saved") + } + }) + + t.Run("a role's permission change fires once with every holder", func(t *testing.T) { + role := env.seedRole(t, roleSeed{Name: "access-shared", Permissions: map[string]int{"acme.demo.access": 1}}) + a := env.seedAdmin(t, adminSeed{Name: "access-holder-a", Role: role.ID}) + b := env.seedAdmin(t, adminSeed{Name: "access-holder-b", Role: role.ID}) + bystander := env.seedAdmin(t, adminSeed{Name: "access-bystander"}) + rec.take() + env.expect(t, http.StatusOK, http.MethodPut, roleURL(role.ID), rootToken, + roleBody(role, map[string]any{"permissions": map[string]any{"acme.demo.access": 1, pingPermission: 1}})) + subjects := expectRevoked(t, cabana.BackendAccessPermissions, a.ID, b.ID) + expectSubjects(t, subjects, pact.MCPSubjectPermissions, a.ID, b.ID) + for _, s := range subjects { + if s.UserID == bystander.ID { + t.Fatal("a bystander got a subject event") + } + } + }) + + t.Run("no event for unrelated edits", func(t *testing.T) { + target, _ := env.admin(t, "access-name", false, "") + role := env.seedRole(t, roleSeed{Name: "access-quiet", Permissions: map[string]int{"acme.demo.access": 1}}) + env.seedAdmin(t, adminSeed{Name: "access-quiet-holder", Role: role.ID}) + rec.take() + env.expect(t, http.StatusOK, http.MethodPut, userURL(target.ID), rootToken, + map[string]any{"login": target.Login, "email": target.Email, "first_name": "Renamed"}) + env.expect(t, http.StatusOK, http.MethodPut, roleURL(role.ID), rootToken, + roleBody(role, map[string]any{"description": "Only the description", "permissions": map[string]any{"acme.demo.access": 1}})) + if revoked, subjects := rec.take(); len(revoked) != 0 || len(subjects) != 0 { + t.Fatalf("unrelated edits fired %+v and %+v", revoked, subjects) + } + }) + + t.Run("a listener error rolls the delete back", func(t *testing.T) { + kept, _ := env.admin(t, "access-veto-delete", false, "") + rec.take() + rec.fail.Store(true) + res := env.call(t, http.MethodDelete, userURL(kept.ID), rootToken, nil) + rec.fail.Store(false) + if res.Code >= 200 && res.Code < 300 { + t.Fatalf("vetoed delete answered %d %s", res.Code, res.Body.String()) + } + if env.storedUser(t, kept.ID).DeletedAt.Valid { + t.Fatal("a vetoed delete deleted the administrator") + } + revoked, subjects := rec.take() + if len(revoked) != 1 || revoked[0].Reason != cabana.BackendAccessDeleted { + t.Fatalf("vetoed delete events %+v", revoked) + } + if len(subjects) != 0 { + t.Fatalf("a rolled-back delete fired MCPSubjectChanged %+v", subjects) + } + }) + + t.Run("a listener error rolls the role save back", func(t *testing.T) { + role := env.seedRole(t, roleSeed{Name: "access-veto-role", Permissions: map[string]int{"acme.demo.access": 1}}) + holder := env.seedAdmin(t, adminSeed{Name: "access-veto-holder", Role: role.ID}) + var before string + if err := env.gdb.Raw(`SELECT permissions FROM backend_user_roles WHERE id = ?`, role.ID).Scan(&before).Error; err != nil { + t.Fatal(err) + } + rec.take() + rec.fail.Store(true) + res := env.call(t, http.MethodPut, roleURL(role.ID), rootToken, + roleBody(role, map[string]any{"permissions": map[string]any{"acme.demo.access": 1, pingPermission: 1}})) + rec.fail.Store(false) + if res.Code >= 200 && res.Code < 300 { + t.Fatalf("vetoed role save answered %d %s", res.Code, res.Body.String()) + } + var after string + if err := env.gdb.Raw(`SELECT permissions FROM backend_user_roles WHERE id = ?`, role.ID).Scan(&after).Error; err != nil { + t.Fatal(err) + } + if after != before { + t.Fatalf("a vetoed role save wrote permissions %s (was %s)", after, before) + } + revoked, subjects := rec.take() + if len(revoked) != 1 || !slices.Equal(revoked[0].AdminIDs, []uint{holder.ID}) { + t.Fatalf("vetoed role save events %+v", revoked) + } + if len(subjects) != 0 { + t.Fatalf("a rolled-back role save fired MCPSubjectChanged %+v", subjects) + } + }) + + t.Run("the helper de-duplicates ids", func(t *testing.T) { + rec.take() + if err := cabana.FireBackendAccessRevokedForTest(context.Background(), env.app, env.gdb, cabana.BackendAccessPermissions, 7, 0, 7, 9, 9, 7); err != nil { + t.Fatal(err) + } + revoked, _ := rec.take() + if len(revoked) != 1 || !slices.Equal(revoked[0].AdminIDs, []uint{7, 9}) { + t.Fatalf("events %+v, want one with [7 9] in first-seen order", revoked) + } + if err := cabana.FireBackendAccessRevokedForTest(context.Background(), env.app, env.gdb, cabana.BackendAccessPermissions, 0); err != nil { + t.Fatal(err) + } + if err := cabana.FireBackendAccessRevokedForTest(context.Background(), nil, nil, cabana.BackendAccessPermissions, 7); err != nil { + t.Fatal(err) + } + if revoked, _ := rec.take(); len(revoked) != 0 { + t.Fatalf("no ids or no app fired %+v", revoked) + } + }) +} diff --git a/modules/cabana/export_test.go b/modules/cabana/export_test.go index ae15cefb..61585731 100644 --- a/modules/cabana/export_test.go +++ b/modules/cabana/export_test.go @@ -7,6 +7,7 @@ import ( "strings" "time" + "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/party" "git.golem15.com/golem15/summercms/modules/phrasebook" @@ -129,3 +130,10 @@ func LineDiffForTest(a, b []string, context int) string { } return strings.Join(out, "|") } + +// FireBackendAccessRevokedForTest is fireBackendAccessRevoked, the helper +// every D-13 site fires BackendAccessRevokedEvent through: it de-duplicates +// and drops zero ids, and fires nothing when no id is left. +func FireBackendAccessRevokedForTest(ctx context.Context, app *backpack.App, tx *gorm.DB, reason string, adminIDs ...uint) error { + return fireBackendAccessRevoked(ctx, app, tx, reason, adminIDs...) +} diff --git a/modules/cabana/mcp_admin_consent_test.go b/modules/cabana/mcp_admin_consent_test.go new file mode 100644 index 00000000..f5eaf92a --- /dev/null +++ b/modules/cabana/mcp_admin_consent_test.go @@ -0,0 +1,458 @@ +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()) + } + }) +} diff --git a/modules/cabana/token_scope_names_test.go b/modules/cabana/token_scope_names_test.go new file mode 100644 index 00000000..3db96629 --- /dev/null +++ b/modules/cabana/token_scope_names_test.go @@ -0,0 +1,124 @@ +package cabana + +import ( + "context" + "slices" + "strings" + "testing" + + "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/pact" + "git.golem15.com/golem15/summercms/modules/party" + "git.golem15.com/golem15/summercms/modules/phrasebook" + "git.golem15.com/golem15/summercms/modules/towel" +) + +// namedScopesPlugin declares the token scopes it is given, behind one +// permission of its own. +type namedScopesPlugin struct { + id string + scopes []pact.TokenScope +} + +func (p namedScopesPlugin) ID() string { return p.id } +func (namedScopesPlugin) Requires() []string { return nil } +func (namedScopesPlugin) Register(*backpack.App) error { return nil } +func (namedScopesPlugin) Boot(*backpack.App) error { return nil } +func (p namedScopesPlugin) TokenScopes() []pact.TokenScope { return p.scopes } +func (p namedScopesPlugin) Permissions() []pact.Permission { + return []pact.Permission{{Code: p.id + ".use", Tab: "Tab", Label: "Use"}} +} + +// TestTokenScopeNames locks the exported token-scope catalog (SC-1, D-09): +// TokenScopeNames answers *, admin:read, then every plugin's scopes in +// plugin order and each plugin's declaration order, from party.Activated +// alone (before cabana.Activate, as an OAuth server reads it at Boot); +// TokenScopeLabels translates phrase keys in the context's locale, keeps +// literal labels and passes unknown names through. +func TestTokenScopeNames(t *testing.T) { + scope := func(id, name, label string) pact.TokenScope { + return pact.TokenScope{Name: name, Label: label, Description: "Description of " + name, Permissions: []string{id + ".use"}, Methods: []string{"GET"}} + } + blog := namedScopesPlugin{id: "acme.blog", scopes: []pact.TokenScope{ + scope("acme.blog", "blog:write", "Blog write"), + scope("acme.blog", "blog", "Blog"), + }} + shop := namedScopesPlugin{id: "acme.shop", scopes: []pact.TokenScope{ + scope("acme.shop", "shop:read", "Shop read"), + }} + none := namedScopesPlugin{id: "acme.none"} + appWith := func(t *testing.T, plugins ...party.Plugin) *backpack.App { + t.Helper() + app := backpack.New(nil) + if err := app.Publish(party.Activated(plugins)); err != nil { + t.Fatal(err) + } + return app + } + + t.Run("catalog order before activation", func(t *testing.T) { + names, err := TokenScopeNames(appWith(t, shop, none, blog)) + if err != nil { + t.Fatal(err) + } + if want := []string{"*", "admin:read", "shop:read", "blog:write", "blog"}; !slices.Equal(names, want) { + t.Fatalf("names = %v, want %v", names, want) + } + names, err = TokenScopeNames(appWith(t, blog, shop)) + if err != nil || !slices.Equal(names, []string{"*", "admin:read", "blog:write", "blog", "shop:read"}) { + t.Fatalf("names in the other plugin order = %v, %v", names, err) + } + }) + + t.Run("framework scopes only", func(t *testing.T) { + for _, app := range []*backpack.App{backpack.New(nil), appWith(t), appWith(t, none), nil} { + names, err := TokenScopeNames(app) + if err != nil || !slices.Equal(names, []string{"*", "admin:read"}) { + t.Fatalf("names = %v, %v, want [* admin:read]", names, err) + } + } + }) + + t.Run("a catalog compile error is answered", func(t *testing.T) { + dup := namedScopesPlugin{id: "acme.dup", scopes: []pact.TokenScope{scope("acme.dup", "blog", "Again")}} + if names, err := TokenScopeNames(appWith(t, blog, dup)); err == nil || !strings.Contains(err.Error(), "duplicate token scope") { + t.Fatalf("duplicate scope: %v, %v", names, err) + } + reserved := namedScopesPlugin{id: "acme.bad", scopes: []pact.TokenScope{scope("acme.bad", "admin:write", "Bad")}} + if _, err := TokenScopeNames(appWith(t, reserved)); err == nil { + t.Fatal("a reserved scope name compiled") + } + }) + + t.Run("labels translate and pass unknown names through", func(t *testing.T) { + app := appWith(t, blog, shop) + if err := phrasebook.Activate(app, []party.Plugin{blog, shop}); err != nil { + t.Fatal(err) + } + names := []string{"*", "admin:read", "blog", "ghost", "shop:read", ""} + en := TokenScopeLabels(towel.WithLocale(context.Background(), "en"), app, names) + if want := []string{"Full access", "Read-only, whole admin", "Blog", "ghost", "Shop read", ""}; !slices.Equal(en, want) { + t.Fatalf("en labels = %q, want %q", en, want) + } + pl := TokenScopeLabels(towel.WithLocale(context.Background(), "pl"), app, names[:2]) + if want := []string{"Pełny dostęp", "Tylko odczyt, cały panel"}; !slices.Equal(pl, want) { + t.Fatalf("pl labels = %q, want %q", pl, want) + } + }) + + t.Run("labels without a translator or catalog", func(t *testing.T) { + // No translator: a phrase-key label falls back to the key itself. + labels := TokenScopeLabels(nil, appWith(t, blog), []string{"blog", "admin:read", "ghost"}) + if !slices.Equal(labels, []string{"Blog", "backend::lang.api_tokens.scope_admin_read", "ghost"}) { + t.Fatalf("labels without translator = %q", labels) + } + // A catalog that fails to compile: every name is its own label. + dup := namedScopesPlugin{id: "acme.dup", scopes: []pact.TokenScope{scope("acme.dup", "blog", "Again")}} + if labels := TokenScopeLabels(context.Background(), appWith(t, blog, dup), []string{"blog", "*"}); !slices.Equal(labels, []string{"blog", "*"}) { + t.Fatalf("labels of a broken catalog = %q", labels) + } + if labels := TokenScopeLabels(context.Background(), nil, nil); len(labels) != 0 { + t.Fatalf("labels of nothing = %q", labels) + } + }) +} diff --git a/modules/pier/backend_only_grant_test.go b/modules/pier/backend_only_grant_test.go new file mode 100644 index 00000000..94363073 --- /dev/null +++ b/modules/pier/backend_only_grant_test.go @@ -0,0 +1,231 @@ +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) + } +} diff --git a/modules/wristband/consent_path_test.go b/modules/wristband/consent_path_test.go new file mode 100644 index 00000000..04675e2b --- /dev/null +++ b/modules/wristband/consent_path_test.go @@ -0,0 +1,204 @@ +package wristband + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strings" + "testing" +) + +// consentPathServer builds a server on issuer with one public client "cli" +// at authorizeTestRedirect; mutate may change the options first. +func consentPathServer(t *testing.T, issuer string, mutate func(*Options)) *Server { + t.Helper() + backend := newMemoryBackend() + opts := DefaultOptions() + opts.Issuer = issuer + opts.Resource = issuer + "/mcp" + if mutate != nil { + mutate(&opts) + } + srv := NewServer(opts) + srv.SetBackend(backend) + insertAuthorizeTestClient(backend, "cli", []string{authorizeTestRedirect}, nil) + return srv +} + +// consentPathAuthorize runs one authorize request. scope nil sends no scope +// parameter; a non-nil scope (empty included) sends it as given. It answers +// the recorder of a 302. +func consentPathAuthorize(t *testing.T, srv *Server, scope *string) *httptest.ResponseRecorder { + t.Helper() + _, challenge := s256Pair(t) + q := url.Values{} + q.Set("client_id", "cli") + q.Set("redirect_uri", authorizeTestRedirect) + q.Set("response_type", "code") + q.Set("code_challenge", challenge) + q.Set("code_challenge_method", "S256") + if scope != nil { + q.Set("scope", *scope) + } + rec := httptest.NewRecorder() + srv.Authorize(rec, httptest.NewRequest(http.MethodGet, "/oauth/mcp/authorize?"+q.Encode(), nil)) + if rec.Code != http.StatusFound { + t.Fatalf("authorize status = %d %s, want 302", rec.Code, rec.Body.String()) + } + return rec +} + +// handoffRequest answers the request id of a handoff Location that must +// start with prefix and carry nothing but the escaped id after it. +func handoffRequest(t *testing.T, location, prefix string) string { + t.Helper() + if !strings.HasPrefix(location, prefix) { + t.Fatalf("Location = %q, want prefix %q", location, prefix) + } + escaped := strings.TrimPrefix(location, prefix) + id, err := url.QueryUnescape(escaped) + if err != nil || id == "" || strings.ContainsAny(escaped, "?&#/") { + t.Fatalf("Location = %q carries no plain request id", location) + } + if rfc3986Escape(id) != escaped { + t.Fatalf("request id %q is not RFC 3986 escaped in %q", id, location) + } + return id +} + +// TestAuthorizeConsentPath locks the authorize handoff (SC-1, D-04): with +// Options.ConsentPath empty the Location is byte for byte the PHP +// {issuer}/connect?request=, with the PHP headers; a +// set path replaces /connect on the same issuer; an issuer with a path +// segment keeps it in front of the consent path. +func TestAuthorizeConsentPath(t *testing.T) { + read := "read" + cases := []struct { + name, issuer, path, prefix string + }{ + {"empty path is the PHP /connect", "https://issuer.example.test", "", "https://issuer.example.test/connect?request="}, + {"a set path replaces /connect", "https://issuer.example.test", "/backend/connect", "https://issuer.example.test/backend/connect?request="}, + {"an issuer path segment is kept", "https://issuer.example.test/tenant", "", "https://issuer.example.test/tenant/connect?request="}, + {"an issuer path segment with a set path", "https://issuer.example.test/tenant", "/gfadmin/connect", "https://issuer.example.test/tenant/gfadmin/connect?request="}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + srv := consentPathServer(t, tc.issuer, func(o *Options) { o.ConsentPath = tc.path }) + rec := consentPathAuthorize(t, srv, &read) + location := rec.Header().Get("Location") + id := handoffRequest(t, location, tc.prefix) + if location != tc.issuer+srv.consentPath()+"?request="+rfc3986Escape(id) { + t.Fatalf("Location %q is not issuer + consent path + escaped id", location) + } + if got := rec.Header().Get("Cache-Control"); got != "no-store, private" { + t.Fatalf("Cache-Control = %q, want the PHP no-store, private", got) + } + if _, err := srv.PendingRequest(context.Background(), id, 1); err != nil { + t.Fatalf("the handed-off request is not pending: %v", err) + } + }) + } + + t.Run("the default options leave the path empty", func(t *testing.T) { + if DefaultOptions().ConsentPath != "" || len(DefaultOptions().DefaultScopes) != 0 { + t.Fatalf("DefaultOptions sets ConsentPath %q DefaultScopes %v", DefaultOptions().ConsentPath, DefaultOptions().DefaultScopes) + } + srv := consentPathServer(t, "https://issuer.example.test", nil) + if srv.consentPath() != "/connect" { + t.Fatalf("consentPath = %q, want /connect", srv.consentPath()) + } + }) + + t.Run("empty and explicit /connect answer the same bytes", func(t *testing.T) { + empty := consentPathServer(t, "https://issuer.example.test", nil) + explicit := consentPathServer(t, "https://issuer.example.test", func(o *Options) { o.ConsentPath = "/connect" }) + a := consentPathAuthorize(t, empty, &read) + b := consentPathAuthorize(t, explicit, &read) + idA := handoffRequest(t, a.Header().Get("Location"), "https://issuer.example.test/connect?request=") + idB := handoffRequest(t, b.Header().Get("Location"), "https://issuer.example.test/connect?request=") + bodyA := strings.ReplaceAll(a.Body.String(), rfc3986Escape(idA), "ID") + bodyB := strings.ReplaceAll(b.Body.String(), rfc3986Escape(idB), "ID") + if bodyA != bodyB || !strings.Contains(bodyA, "/connect?request=ID") { + t.Fatalf("redirect bodies differ:\n%s\n%s", bodyA, bodyB) + } + }) +} + +// TestAuthorizeDefaultScopes locks the scope fallback of an authorize +// request (SC-1, D-04): an absent, empty or identity-only scope value gets +// Options.DefaultScopes; entries outside the accepted set, identity scopes +// and repeats are dropped from it; empty DefaultScopes (or nothing left) +// keeps the PHP read; an explicit data scope is never replaced. +func TestAuthorizeDefaultScopes(t *testing.T) { + const issuer = "https://issuer.example.test" + str := func(s string) *string { return &s } + stored := func(t *testing.T, srv *Server, scope *string) []string { + t.Helper() + rec := consentPathAuthorize(t, srv, scope) + id := handoffRequest(t, rec.Header().Get("Location"), issuer+"/connect?request=") + view, err := srv.PendingRequest(context.Background(), id, 1) + if err != nil { + t.Fatal(err) + } + return view.ScopesRequested + } + withCatalog := func(defaults ...string) func(*Options) { + return func(o *Options) { + o.ScopesSupported = []string{"*", "admin:read", "acme", "acme:read", "offline_access"} + o.DefaultScopes = defaults + } + } + + t.Run("absent, empty and identity-only values get the default scopes", func(t *testing.T) { + srv := consentPathServer(t, issuer, withCatalog("*", "admin:read", "acme", "acme:read")) + for name, scope := range map[string]*string{ + "absent": nil, + "empty": str(""), + "blank": str(" "), + "identity only": str("openid profile email"), + } { + if got := stored(t, srv, scope); !slices.Equal(got, []string{"*", "admin:read", "acme", "acme:read"}) { + t.Fatalf("%s scope stored %v, want the default scopes in order", name, got) + } + } + }) + + t.Run("defaults outside the accepted set, identity scopes and repeats are dropped", func(t *testing.T) { + srv := consentPathServer(t, issuer, withCatalog(" acme ", "openid", "unknown", "acme", "", "acme:read")) + if got := stored(t, srv, nil); !slices.Equal(got, []string{"acme", "acme:read"}) { + t.Fatalf("stored %v, want [acme acme:read]", got) + } + }) + + t.Run("empty default scopes keep read", func(t *testing.T) { + srv := consentPathServer(t, issuer, nil) + for _, scope := range []*string{nil, str(""), str("openid")} { + if got := stored(t, srv, scope); !slices.Equal(got, []string{"read"}) { + t.Fatalf("stored %v, want [read]", got) + } + } + }) + + t.Run("defaults with nothing accepted keep read", func(t *testing.T) { + srv := consentPathServer(t, issuer, func(o *Options) { o.DefaultScopes = []string{"acme", "openid"} }) + if got := stored(t, srv, nil); !slices.Equal(got, []string{"read"}) { + t.Fatalf("stored %v, want [read]", got) + } + }) + + t.Run("an explicit scope is not replaced", func(t *testing.T) { + srv := consentPathServer(t, issuer, withCatalog("*", "acme")) + if got := stored(t, srv, str("acme:read")); !slices.Equal(got, []string{"acme:read"}) { + t.Fatalf("stored %v, want [acme:read]", got) + } + if got := stored(t, srv, str("openid acme:read")); !slices.Equal(got, []string{"acme:read"}) { + t.Fatalf("identity plus data scope stored %v, want [acme:read]", got) + } + plain := consentPathServer(t, issuer, func(o *Options) { o.DefaultScopes = []string{"write"} }) + if got := stored(t, plain, str("read")); !slices.Equal(got, []string{"read"}) { + t.Fatalf("explicit read stored %v, want [read]", got) + } + }) +}