feat(32.2-01): per-item rows and item actions on My account contributions

- pact: AccountContribution.Items/ItemActions/ItemsEmpty, AccountItem,
  AccountItemAction, AccountItemActionInput, ErrAccountItemNotFound
- cabana: the list sends items (null without Items), permitted item actions
  and the empty line; boot refuses item actions without Items
- cabana: POST {api}/account/contribution-items/{name}/{item}/actions/{action}
  runs only for an item the administrator's own Items listed, in a transaction
  (path outside /account/contributions/ to avoid a ServeMux overlap)
- swag views; admin.json and schema.d.ts regenerated; route inventories
This commit is contained in:
Jakub Zych
2026-11-21 00:22:13 +01:00
parent 97d7ee0586
commit 3f7ce6020d
16 changed files with 706 additions and 30 deletions

File diff suppressed because one or more lines are too long

View File

@@ -24,17 +24,19 @@ type accountContributionCatalog struct {
// compiledAccountContribution is one contributed section with its owner.
type compiledAccountContribution struct {
pluginID string
section pact.AccountContribution
actions map[string]pact.AccountAction
pluginID string
section pact.AccountContribution
actions map[string]pact.AccountAction
itemActions map[string]pact.AccountItemAction
}
// compileAccountContributions collects pact.HasAccountContributions from
// plugins into reg, in activation order. Every failure stops boot with a
// message naming the plugin and the section: a name that is not an
// identifier, a name another plugin already contributed, an empty label, an
// action whose name is not an identifier or repeats within the section, a
// nil Run or an empty action label.
// action or item action whose name is not an identifier or repeats within
// the section, a nil Run, an empty action label, or item actions without an
// Items func.
func compileAccountContributions(reg *Registry, plugins []party.Plugin) error {
if reg == nil {
return fmt.Errorf("cabana: registry is nil")
@@ -60,7 +62,7 @@ func compileAccountContributions(reg *Registry, plugins []party.Plugin) error {
if strings.TrimSpace(section.Label) == "" {
return fmt.Errorf("%s: it needs a label", prefix)
}
compiled := &compiledAccountContribution{pluginID: pluginID, section: section, actions: map[string]pact.AccountAction{}}
compiled := &compiledAccountContribution{pluginID: pluginID, section: section, actions: map[string]pact.AccountAction{}, itemActions: map[string]pact.AccountItemAction{}}
for _, action := range section.Actions {
if !identifier(action.Name) {
return fmt.Errorf("%s: action name %q is not an identifier", prefix, action.Name)
@@ -76,6 +78,24 @@ func compileAccountContributions(reg *Registry, plugins []party.Plugin) error {
}
compiled.actions[action.Name] = action
}
if len(section.ItemActions) > 0 && section.Items == nil {
return fmt.Errorf("%s: it has item actions but no Items function", prefix)
}
for _, action := range section.ItemActions {
if !identifier(action.Name) {
return fmt.Errorf("%s: item action name %q is not an identifier", prefix, action.Name)
}
if _, dup := compiled.itemActions[action.Name]; dup {
return fmt.Errorf("%s: duplicate item action %q", prefix, action.Name)
}
if action.Run == nil {
return fmt.Errorf("%s: item action %q has no Run function", prefix, action.Name)
}
if strings.TrimSpace(action.Label) == "" {
return fmt.Errorf("%s: item action %q needs a label", prefix, action.Name)
}
compiled.itemActions[action.Name] = action
}
cat.ordered = append(cat.ordered, *compiled)
cat.byName[section.Name] = &cat.ordered[len(cat.ordered)-1]
}
@@ -91,10 +111,13 @@ func compileAccountContributions(reg *Registry, plugins []party.Plugin) error {
// accountContributionsList serves GET /account/contributions: every
// contributed section with its status for the signed-in administrator and
// the actions they may run that apply to them, labels translated. A
// section whose Status fails is sent with Error set and no status, and an
// action whose Applies fails is left out and sets Error on its section (the
// admin sees why a button is missing), both logged: one plugin's error never
// answers 500 for the list.
// section with Items also carries the administrator's rows (an array,
// possibly empty), the item actions they hold the permissions for and the
// empty line; a section without Items sends items null. A section whose
// Status or Items fails is sent with Error set (no status, items null), and
// an action whose Applies fails is left out and sets Error on its section
// (the admin sees why a button is missing), all logged: one plugin's error
// never answers 500 for the list.
func (s *service) accountContributionsList(w http.ResponseWriter, r *http.Request) {
principal := accountPrincipal(w, r)
if principal == nil {
@@ -146,6 +169,34 @@ func (s *service) accountContributionsList(w http.ResponseWriter, r *http.Reques
Danger: action.Danger,
})
}
if item.section.Items != nil {
view.ItemsEmpty = translateKey(ctx, tr, item.section.ItemsEmpty)
view.ItemActions = []AccountContributionActionView{}
for _, action := range item.section.ItemActions {
if !Allows(principal, action.Permissions) {
continue
}
view.ItemActions = append(view.ItemActions, AccountContributionActionView{
Name: action.Name,
Label: translateKey(ctx, tr, action.Label),
Confirm: translateKey(ctx, tr, action.Confirm),
Danger: action.Danger,
})
}
rows, err := item.section.Items(ctx, principal.ID)
if err != nil {
// Items stay null and the section says so; the other
// sections are still answered.
moduleLog.ErrorContext(ctx, "cabana: account contribution items failed", "section", item.section.Name, "plugin", item.pluginID, "error", err)
view.Error = true
} else {
view.Items = make([]AccountItemView, 0, len(rows))
for _, row := range rows {
meta := append([]string{}, row.Meta...)
view.Items = append(view.Items, AccountItemView{ID: row.ID, Title: row.Title, Subtitle: row.Subtitle, Meta: meta})
}
}
}
out = append(out, view)
}
}
@@ -227,6 +278,94 @@ func (s *service) accountContributionAction(w http.ResponseWriter, r *http.Reque
}, nil)
}
// accountContributionItemAction serves
// POST /account/contribution-items/{name}/{item}/actions/{action}: an
// unknown section or item action is 404, a missing permission 403; then the
// section's Items is read for the signed-in administrator and an item ID it
// does not list is 404, so an administrator never acts on someone else's
// row; then Run runs inside a transaction carried by the context, as for
// section actions. pact.ErrAccountItemNotFound from Run is 404.
func (s *service) accountContributionItemAction(w http.ResponseWriter, r *http.Request) {
principal := accountPrincipal(w, r)
if principal == nil {
return
}
var item *compiledAccountContribution
if s.reg != nil && s.reg.accountContributions != nil {
item = s.reg.accountContributions.byName[r.PathValue("name")]
}
if item == nil || item.section.Items == nil {
WriteError(w, http.StatusNotFound, "not_found", msgNotFound)
return
}
action, ok := item.itemActions[r.PathValue("action")]
if !ok {
WriteError(w, http.StatusNotFound, "not_found", msgNotFound)
return
}
if !s.allowAction(w, r, action.Permissions) {
return
}
tr := s.translator()
ctx := towel.WithLocale(r.Context(), schemaLocale(r.Context(), tr))
itemID := r.PathValue("item")
listed := func(ctx context.Context) (bool, error) {
rows, err := item.section.Items(ctx, principal.ID)
if err != nil {
return false, err
}
for _, row := range rows {
if row.ID == itemID {
return true, nil
}
}
return false, nil
}
run := func(ctx context.Context) (pact.AccountActionResult, error) {
ok, err := listed(ctx)
if err != nil {
return pact.AccountActionResult{}, err
}
if !ok {
return pact.AccountActionResult{}, pact.ErrAccountItemNotFound
}
return action.Run(ctx, pact.AccountItemActionInput{AdminID: principal.ID, ItemID: itemID})
}
var result pact.AccountActionResult
var err error
if db, dbErr := s.db(); dbErr == nil {
err = lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
result, err = run(withTx(ctx, tx))
return err
})
} else {
result, err = run(ctx)
}
if errors.Is(err, pact.ErrAccountItemNotFound) {
WriteError(w, http.StatusNotFound, "not_found", msgNotFound)
return
}
if err != nil {
var stale actionConflict
var refused *ForbiddenError
var invalid *ValidationError
if !errors.As(err, &stale) && !errors.As(err, &refused) && !errors.As(err, &invalid) {
moduleLog.ErrorContext(ctx, "cabana: account contribution item action failed", "section", item.section.Name, "action", action.Name, "plugin", item.pluginID, "error", err)
}
writeCRUDError(w, localizeControllerError(ctx, tr, err))
return
}
moduleLog.InfoContext(ctx, "cabana: account contribution item action", "admin_id", principal.ID, "section", item.section.Name, "action", action.Name)
if result.URL != "" && !safeAccountActionURL(result.URL) {
moduleLog.ErrorContext(ctx, "cabana: account contribution item action answered a non-http URL", "section", item.section.Name, "action", action.Name, "plugin", item.pluginID)
result.URL = ""
}
WriteData(w, http.StatusOK, AccountActionResultView{
Message: translateKey(ctx, tr, result.Message),
URL: result.URL,
}, nil)
}
// safeAccountActionURL reports whether an account action's URL may be handed
// to the admin's browser, which renders it as a link and opens it: an
// absolute http or https URL with a host, or a same-origin relative path

View File

@@ -0,0 +1,170 @@
package cabana
import (
"context"
"encoding/json"
"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"
)
// TestAccountItemsSmoke covers per-item rows on My account contributions,
// on Postgres so item actions run in a real transaction: a section without
// Items still answers items null, a section with Items lists the
// administrator's rows and the item actions they may run, an item action on
// a listed id runs with the administrator and item ids inside a
// transaction, the same id posted by another administrator (whose Items
// list it not) is 404 without Run, Run answering pact.ErrAccountItemNotFound
// is 404, a missing permission is 403, and item actions without Items fail
// boot.
func TestAccountItemsSmoke(t *testing.T) {
gdb := consentGorm(t)
var mu sync.Mutex
type call struct {
admin uint
item string
tx bool
}
var calls []call
const adminA, adminB = 41, 42
rows := map[uint][]pact.AccountItem{
adminA: {
{ID: "c1", Title: "Agent one", Subtitle: "Full access", Meta: []string{"Connected 2026-11-20"}},
{ID: "gone", Title: "Agent two"},
},
}
revoke := pact.AccountItemAction{
Name: "revoke", Label: "acme::lang.revoke", Confirm: "Revoke :title?", Danger: true,
Run: func(ctx context.Context, in pact.AccountItemActionInput) (pact.AccountActionResult, error) {
_, tx := TxFromContext(ctx)
mu.Lock()
calls = append(calls, call{admin: in.AdminID, item: in.ItemID, tx: tx})
mu.Unlock()
if in.ItemID == "gone" {
return pact.AccountActionResult{}, pact.ErrAccountItemNotFound
}
return pact.AccountActionResult{Message: "acme::lang.revoked"}, nil
},
}
locked := pact.AccountItemAction{
Name: "rename", Label: "Rename", Permissions: []string{"acme.items.manage"},
Run: func(context.Context, pact.AccountItemActionInput) (pact.AccountActionResult, error) {
return pact.AccountActionResult{}, nil
},
}
sections := []pact.AccountContribution{
{Name: "plain", Label: "Plain section"},
{
Name: "connections", Label: "Connections", ItemsEmpty: "Nothing connected.",
Items: func(_ context.Context, adminID uint) ([]pact.AccountItem, error) {
return rows[adminID], nil
},
ItemActions: []pact.AccountItemAction{revoke, locked},
},
}
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) *bouncer.Principal { return &bouncer.Principal{ID: id, Backend: true} }
list := func(p *bouncer.Principal) []map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/account/contributions", nil)
req = req.WithContext(bouncer.WithUser(req.Context(), p))
rec := httptest.NewRecorder()
interactiveOnly(svc.accountContributionsList)(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("list = %d %s", rec.Code, rec.Body.String())
}
var body struct {
Data []map[string]any `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
return body.Data
}
act := func(p *bouncer.Principal, item, action string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/account/contribution-items/connections/"+item+"/actions/"+action, strings.NewReader("{}"))
req.Header.Set("X-Requested-With", "XMLHttpRequest")
req.SetPathValue("name", "connections")
req.SetPathValue("item", item)
req.SetPathValue("action", action)
req = req.WithContext(bouncer.WithUser(req.Context(), p))
rec := httptest.NewRecorder()
interactiveOnly(requireAjax(svc.accountContributionItemAction))(rec, req)
return rec
}
data := list(principal(adminA))
if len(data) != 2 {
t.Fatalf("sections = %+v", data)
}
if items, ok := data[0]["items"]; !ok || items != nil || data[0]["item_actions"] != nil {
t.Fatalf("section without Items = %+v, want items null", data[0])
}
items, _ := data[1]["items"].([]any)
if len(items) != 2 {
t.Fatalf("items = %+v", data[1]["items"])
}
first, _ := items[0].(map[string]any)
if first["id"] != "c1" || first["title"] != "Agent one" || first["subtitle"] != "Full access" {
t.Fatalf("first item = %+v", first)
}
actions, _ := data[1]["item_actions"].([]any)
if len(actions) != 1 || actions[0].(map[string]any)["name"] != "revoke" || actions[0].(map[string]any)["confirm"] != "Revoke :title?" || data[1]["items_empty"] != "Nothing connected." {
t.Fatalf("item actions = %+v empty=%v", data[1]["item_actions"], data[1]["items_empty"])
}
// Admin B has no rows: an empty array, never null.
if dataB := list(principal(adminB)); dataB[1]["items"] == nil {
t.Fatalf("admin B items = %+v, want []", dataB[1])
}
if rec := act(principal(adminA), "c1", "revoke"); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "acme::lang.revoked") {
t.Fatalf("revoke = %d %s", rec.Code, rec.Body.String())
}
if len(calls) != 1 || calls[0] != (call{admin: adminA, item: "c1", tx: true}) {
t.Fatalf("calls = %+v", calls)
}
// Admin B posts admin A's item id: 404 and Run is not called.
if rec := act(principal(adminB), "c1", "revoke"); rec.Code != http.StatusNotFound || len(calls) != 1 {
t.Fatalf("cross-admin = %d %s calls=%d", rec.Code, rec.Body.String(), len(calls))
}
// Run answering ErrAccountItemNotFound: 404.
if rec := act(principal(adminA), "gone", "revoke"); rec.Code != http.StatusNotFound || len(calls) != 2 {
t.Fatalf("gone item = %d %s calls=%d", rec.Code, rec.Body.String(), len(calls))
}
if rec := act(principal(adminA), "c1", "rename"); rec.Code != http.StatusForbidden {
t.Fatalf("missing permission = %d %s", rec.Code, rec.Body.String())
}
if rec := act(principal(adminA), "c1", "nope"); rec.Code != http.StatusNotFound {
t.Fatalf("unknown item action = %d %s", rec.Code, rec.Body.String())
}
// Boot refuses item actions without Items, and the other bad shapes.
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: sections[1].Items, ItemActions: []pact.AccountItemAction{{Name: "no!", Label: "x", Run: revoke.Run}}},
"duplicate item action": {Name: "x", Label: "x", Items: sections[1].Items, ItemActions: []pact.AccountItemAction{revoke, revoke}},
"nil item run": {Name: "x", Label: "x", Items: sections[1].Items, ItemActions: []pact.AccountItemAction{{Name: "a", Label: "x"}}},
"empty item label": {Name: "x", Label: "x", Items: sections[1].Items, ItemActions: []pact.AccountItemAction{{Name: "a", Run: revoke.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)
}
}
}

View File

@@ -341,11 +341,32 @@ type AccountContributionView struct {
// section has none or its status could not be loaded.
Status string `json:"status"`
Actions []AccountContributionActionView `json:"actions"`
// Error is true when the section's status or one of its actions could
// not be loaded (the plugin's Status or an action's Applies failed; that
// action is left out); the other sections are answered as usual. Absent
// otherwise.
// Error is true when the section's status, its items or one of its
// actions could not be loaded (the plugin's Status, Items or an action's
// Applies failed; that action is left out); the other sections are
// answered as usual. Absent otherwise.
Error bool `json:"error,omitempty"`
// Items are the signed-in admin's rows of a section with an Items
// function: an array, possibly empty. null for a section without Items
// and when the section's Items failed.
Items []AccountItemView `json:"items"`
// ItemActions are the buttons of each row the admin holds the
// permissions for; null for a section without Items. Confirm may hold
// :title, which the admin fills with the row's title.
ItemActions []AccountContributionActionView `json:"item_actions"`
// ItemsEmpty is the translated line for a section with no rows; "" means
// the admin's own empty line.
ItemsEmpty string `json:"items_empty"`
}
// AccountItemView is one row of a contributed section: the id the item
// action route names, a title, an optional subtitle and meta lines, all
// plain text.
type AccountItemView struct {
ID string `json:"id"`
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Meta []string `json:"meta"`
}
// AccountContributionActionView is one button of a contributed section: the
@@ -478,6 +499,24 @@ func AdminMCPConsentShow() {}
// @Router /mcp/consent/{request} [post]
func AdminMCPConsentDecide() {}
// AdminAccountContributionItemAction documents POST /account/contribution-items/{name}/{item}/actions/{action}.
//
// @Summary Run a My account item action
// @Description Runs one item action of a contributed section on one of the signed-in admin's rows. The action's permissions are checked (403); an item the section's Items does not list for this admin, or one that is gone, is 404. The answer is the action's message and an optional URL to open. Personal API tokens are refused (403 interactive_only).
// @Tags admin
// @Produce json
// @Security BackendBearer
// @Param name path string true "Section name"
// @Param item path string true "Item id"
// @Param action path string true "Item action name"
// @Success 200 {object} Envelope[AccountActionResultView]
// @Failure 401 {object} ErrorEnvelope
// @Failure 403 {object} ErrorEnvelope
// @Failure 404 {object} ErrorEnvelope
// @Failure 422 {object} ErrorEnvelope
// @Router /account/contribution-items/{name}/{item}/actions/{action} [post]
func AdminAccountContributionItemAction() {}
// AdminAccountTokenScopes documents GET /account/tokens/scopes.
//
// @Summary List available API token scopes

View File

@@ -348,6 +348,7 @@ func (s *service) mount(r pact.Router) {
// Sections plugins contribute to My account (pact.HasAccountContributions).
g.Get("/account/contributions", interactiveOnly(s.accountContributionsList))
g.Post("/account/contributions/{name}/actions/{action}", interactiveOnly(requireAjax(s.accountContributionAction)))
g.Post("/account/contribution-items/{name}/{item}/actions/{action}", interactiveOnly(requireAjax(s.accountContributionItemAction)))
// Consent of administrator-only MCP grants, served for the
// published pact.MCPAdminConsent (404 when none is published).
g.Get("/mcp/consent/{request}", interactiveOnly(s.mcpConsentShow))

View File

@@ -836,6 +836,9 @@ func conformCases() []conformCase {
{"POST /account/contributions/{name}/actions/{action}", 200, "cabana.Envelope-cabana_AccountActionResultView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder {
return e.send(t, http.MethodPost, "/account/contributions/conform_link/actions/open", nil, true)
}, into[cabana.Envelope[cabana.AccountActionResultView]](), nil},
{"POST /account/contribution-items/{name}/{item}/actions/{action}", 200, "cabana.Envelope-cabana_AccountActionResultView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder {
return e.send(t, http.MethodPost, "/account/contribution-items/conform_link/conform-item/actions/forget", nil, true)
}, into[cabana.Envelope[cabana.AccountActionResultView]](), nil},
{"GET /mcp/consent/{request}", 200, "cabana.Envelope-cabana_MCPConsentView", func(t *testing.T, e *conformEnv) *httptest.ResponseRecorder {
return e.send(t, http.MethodGet, "/mcp/consent/conform-request", nil, true)
}, into[cabana.Envelope[cabana.MCPConsentView]](), nil},
@@ -1298,6 +1301,16 @@ func (conformPlugin) AccountContributions() []pact.AccountContribution {
return pact.AccountActionResult{Message: "Opened", URL: "https://conform.example.test/link"}, nil
},
}},
Items: func(context.Context, uint) ([]pact.AccountItem, error) {
return []pact.AccountItem{{ID: "conform-item", Title: "Conform item", Subtitle: "A row", Meta: []string{"2026-11-21"}}}, nil
},
ItemActions: []pact.AccountItemAction{{
Name: "forget", Label: "Forget", Confirm: "Forget :title?", Danger: true,
Run: func(context.Context, pact.AccountItemActionInput) (pact.AccountActionResult, error) {
return pact.AccountActionResult{Message: "Forgotten"}, nil
},
}},
ItemsEmpty: "No rows.",
}}
}

View File

@@ -94,6 +94,7 @@ func TestPhase10Coverage(t *testing.T) {
"DELETE /{vendor}/{plugin}/{controller}/{id}/files/{field}/{file}",
"DELETE /{vendor}/{plugin}/{controller}/{id}/relations/{name}/records/{child}/files/{field}/{file}",
"POST /account/avatar",
"POST /account/contribution-items/{name}/{item}/actions/{action}",
"POST /account/contributions/{name}/actions/{action}",
"POST /account/tokens",
"POST /auth/login",

View File

@@ -73,9 +73,10 @@ func TestPhase10CSRF(t *testing.T) {
// caption, file remove, relation child create, update and delete, pivot
// update, child file upload, reorder, caption and remove, plugin field
// type upload, tree reorder save, account contribution action,
// mail image upload, mail preview, mail test-send, MCP consent decision
if unsafe != 39 {
t.Fatalf("walked %d state-changing routes, want 39: %v", unsafe, router.order)
// mail image upload, mail preview, mail test-send, MCP consent decision,
// account contribution item action
if unsafe != 40 {
t.Fatalf("walked %d state-changing routes, want 40: %v", unsafe, router.order)
}
loginHandler := router.handlers[login]

View File

@@ -50,6 +50,7 @@ var phase09Routes = []adminRoute{
{key: "DELETE /account/tokens/{id}"},
{key: "GET /account/contributions"},
{key: "POST /account/contributions/{name}/actions/{action}"},
{key: "POST /account/contribution-items/{name}/{item}/actions/{action}"},
{key: "GET /mcp/consent/{request}"},
{key: "POST /mcp/consent/{request}"},
{key: "GET /navigation"},

View File

@@ -45,8 +45,9 @@ var tokenRouteClasses = map[string]tokenRouteClass{
"DELETE /account/tokens/{id}": classInteractive,
"GET /account/contributions": classInteractive,
"POST /account/contributions/{name}/actions/{action}": classInteractive,
"GET /mcp/consent/{request}": classInteractive,
"POST /mcp/consent/{request}": classInteractive,
"POST /account/contribution-items/{name}/{item}/actions/{action}": classInteractive,
"GET /mcp/consent/{request}": classInteractive,
"POST /mcp/consent/{request}": classInteractive,
"GET /navigation": classAllowsNav,
"GET /field-types": classExplicitGate,