Files
summercms/modules/cabana/account_items_test.go
Jakub Zych 7ecfa6087d 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
2026-11-21 02:00:16 +01:00

350 lines
14 KiB
Go

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)
}
}
})
}