From a261a8fdfe19d4e6dd93d63c95ad12b64081db5e Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Sat, 21 Nov 2026 09:17:33 +0100 Subject: [PATCH] fix(32.2): WR-04 never fire BackendAccessRevokedEvent without the save's transaction fireBackendAccessRevoked refuses a nil tx before any listener runs, and the Administrators and Roles update hooks fail closed (like the delete hook) when the save carries no transaction, instead of firing with whatever TxFromContext answered. --- docs/services/events.md | 2 +- modules/cabana/README.md | 2 +- modules/cabana/admin_events.go | 13 +++- .../cabana/backend_access_revoked_tx_test.go | 60 +++++++++++++++++++ modules/cabana/backend_roles_admin.go | 7 ++- modules/cabana/backend_users_admin.go | 13 +++- 6 files changed, 90 insertions(+), 7 deletions(-) create mode 100644 modules/cabana/backend_access_revoked_tx_test.go diff --git a/docs/services/events.md b/docs/services/events.md index c21f0209..a52ee8d0 100644 --- a/docs/services/events.md +++ b/docs/services/events.md @@ -105,4 +105,4 @@ The framework fires these events of its own: | `pact.MCPSubjectChanged` | the admin, plugins | what a subject may do over MCP changed: permissions, a backend link, a revoked grant or token, a deleted or deactivated user | after the commit; a listener's error is logged and never fails the save | | `pact.RecordSaved` | the admin | a record was created or updated on an admin screen | after the commit | -Listen for `cabana.BackendAccessRevokedEvent` to revoke what is keyed on an administrator, such as OAuth grants they consented to, atomically with the change: write through `cabana.BackendAccessRevokedEvent.Tx` and do not open a transaction of your own. +Listen for `cabana.BackendAccessRevokedEvent` to revoke what is keyed on an administrator, such as OAuth grants they consented to, atomically with the change: write through `cabana.BackendAccessRevokedEvent.Tx` and do not open a transaction of your own. The event never fires with a nil `Tx`: a save that has no transaction to revoke in fails instead. diff --git a/modules/cabana/README.md b/modules/cabana/README.md index 609d80ee..066efac8 100644 --- a/modules/cabana/README.md +++ b/modules/cabana/README.md @@ -65,7 +65,7 @@ Use cases: - My account contributions: a plugin implementing `pact.HasAccountContributions` adds sections (`pact.AccountContribution`) to the administrator's own account page, each with a status line and buttons (`pact.AccountAction`). GET `/account/contributions` lists them for the signed-in administrator and POST `/account/contributions/{name}/actions/{action}` runs one for that administrator only, behind the interactive-only guard, the action's permissions and its `Applies` rule, inside a transaction; the answer may carry a URL the admin opens in a new tab. That URL is kept only when it is an absolute `http`/`https` URL with a host or a same-origin path (one leading `/`); anything else, `javascript:` and `data:` included, is dropped and logged without the URL. A section whose `Status` fails is listed with an empty status and `error: true`, and an action whose `Applies` fails is left out and marks its section `error: true` as well; both are logged and the other sections are answered as usual. A status is translated only when it is a phrase key. Names are generic: cabana never names the contributing plugin. A section may also list the administrator's own rows (`pact.AccountContribution.Items`) with per-row buttons (`pact.AccountItemAction`), run through POST `/account/contribution-items/{name}/{item}/actions/{action}` only for an item that administrator's `Items` listed; a section without `Items` sends `items` null and renders as before. The existing `/account*` and `/auth/me` payloads are unchanged. A non-identifier or duplicate section name, an empty label, a duplicate or non-identifier action name, a nil `Run` or an empty action label stops the boot. - Record events: every admin create and update fires `pact.RecordSaved` on the application's event bus after the commit, with the controller ID, the record's morph type, its id, the request locale, `Created` and the changed attributes with old and new values (column changes, then translated values per locale, read before the save writes them); a save that changed nothing fires with no changes. Delete and every row of a bulk delete fire `pact.RecordDeleted`; a tree reorder fires `pact.RecordSaved` for each moved record (parent and sort columns); relation-manager child writes fire both for the child, naming the controller that edits the child's model; a hasMany link or unlink, and the attach of a child created in an unsaved parent's form session, fire `pact.RecordSaved` for the child with its foreign key change, and a session-created child that is unlinked again fires `pact.RecordDeleted`. A rolled-back write fires nothing and a listener's error is logged, never returned. The same changes reach a form extension's `Save` in `pact.AdminFormSave.Changes`. Plugin code that writes records directly fires the same events with `cabana.EmitRecordSaved` and `cabana.EmitRecordDeleted`. - Backend subject events: a save on the Administrators screen that changed an administrator's role, permission overrides or superuser flag, a Roles save that changed a role's grants (one event per administrator holding it), a deactivation or deletion (record and bulk forms) and a revoked personal API token fire `pact.MCPSubjectChanged` on the application's event bus with guard `backend`, so a module acting on behalf of an administrator elsewhere (the MCP endpoint) re-lists what they may do or ends their sessions. A revoked token's event carries its `TokenID`, so only the sessions opened with that token end; the administrator's other sessions stay open. Only the My account revoke fires it: `admin:token:revoke` runs in its own process, where no MCP endpoint listens, so that token's sessions end when the token is next verified (the session's next request or its stream's periodic bearer re-check). A listener's error is logged and never fails the save. -- Backend access revoked: the same saves that end what an administrator may do also fire `cabana.BackendAccessRevokedEvent` synchronously inside their own transaction, before the commit, with `cabana.BackendAccessRevokedEvent.Tx` set: delete (`cabana.BackendAccessDeleted`), deactivate (`cabana.BackendAccessDeactivated`), an own password change on My account (`cabana.BackendAccessPasswordChanged`), a password another administrator sets (`cabana.BackendAccessPasswordSet`), `admin:reset-password` (`cabana.BackendAccessPasswordReset`), and a change of the administrator's role, own permissions or superuser flag or of the permissions of the role they hold (`cabana.BackendAccessPermissions`, one event naming every holder). A listener's error rolls the save back, so a plugin that revokes grants keyed on the administrator (OAuth grants they consented to, for example) commits together with the change; it writes through `Tx` and opens no transaction of its own. The after-commit `pact.MCPSubjectChanged` events are unchanged. Deleting a role fires nothing, because a role that any administrator holds cannot be deleted. cabana offers no "sign out everywhere" action, so there is no event for one. +- Backend access revoked: the same saves that end what an administrator may do also fire `cabana.BackendAccessRevokedEvent` synchronously inside their own transaction, before the commit, with `cabana.BackendAccessRevokedEvent.Tx` set: delete (`cabana.BackendAccessDeleted`), deactivate (`cabana.BackendAccessDeactivated`), an own password change on My account (`cabana.BackendAccessPasswordChanged`), a password another administrator sets (`cabana.BackendAccessPasswordSet`), `admin:reset-password` (`cabana.BackendAccessPasswordReset`), and a change of the administrator's role, own permissions or superuser flag or of the permissions of the role they hold (`cabana.BackendAccessPermissions`, one event naming every holder). A listener's error rolls the save back, so a plugin that revokes grants keyed on the administrator (OAuth grants they consented to, for example) commits together with the change; it writes through `Tx` and opens no transaction of its own. `Tx` is never nil: a save that would revoke without its transaction fails instead of firing. The after-commit `pact.MCPSubjectChanged` events are unchanged. Deleting a role fires nothing, because a role that any administrator holds cannot be deleted. cabana offers no "sign out everywhere" action, so there is no event for one. - Singleton settings screens declared with `pact.HasSettings`, read and saved by `cabana.SettingsService`. A `type: password` field on a settings form is a write-only secret on a `lagoon.Encrypted` column (any other column type fails boot naming the field): the GET omits it from `data` and reports `stored`, `env` or `empty` per field in `meta.secrets` (`cabana.SettingsMeta`; `env` when the column is empty and the model's `cabana.SecretFallbacks` config key resolves to a non-empty value); on PUT an absent key or an empty string keeps the stored value, JSON null clears it, a non-string is a 422 on the field, and the answer carries the new states, never a value. A `type: richeditor` on a settings form is sanitized on save exactly like a controller save, with the removals in `meta.notices`; `repeater` and `dependsOn` stay refused. Settings fields keep their `tab`. A `type: dropdown` whose `options` names a method takes its choices from the settings model, which must implement `pact.DropdownOptionsProvider` (boot fails naming the field otherwise); the settings schema serves them localized. A settings entry whose `Controller` field is set links to that admin controller instead: start-up fails when it also declares a model, form or model factory, or names an unknown controller; `GET /settings` lists it, with its `controller`, only to administrators who pass its permissions and may open the controller; and the singleton settings endpoints answer 404 for its code. - Backend navigation (`pact.HasNavigation`) and permissions (`pact.HasPermissions`), filtered per user by `cabana.Registry.Metadata`. An entry whose `pact.NavigationItem.Visible` func answers false for the request is left out like a denied one (a hidden main item with its side menu), and a main item whose controller is a side item hidden this way links to its first visible openable side item. An administrator's own `backend_users.permissions` are merged over the role's as in Winter (a `-1` denies a code the role grants). `cabana.Allows` implements the permission check with Winter's `hasAnyAccess` semantics for JWT sessions: superusers pass, a principal needs any one of the listed codes, and wildcards match on both sides (a grant ending in `.*` covers every code with that prefix, and a required code ending in `.*` is met by any grant under it). When the principal carries a non-full `bouncer.ScopeLimit` (a personal API token), the scope is checked first: one method-allowed scope must match every required code and the owner must hold a required code inside that scope; a superuser with a scoped token is limited to the scope, and an empty requirement list is refused unless the scope is full. - Admin authentication against WinterCMS's `backend_users` and `backend_user_roles` tables (`cabana.BackendUser`, `cabana.BackendUserRole`, `cabana.BackendUsers`): a composite `backend` guard (a guard another plugin already registered under that name fails `cabana.Activate`) that accepts an `Authorization: Bearer` personal API token (`cabana.APITokenPrefix` / `g15_…`) or, otherwise, the unchanged admin JWT path (Bearer JWT, then the admin cookie). Personal tokens never come from a cookie or the query string. Login throttling, token refresh and revocation, and the SPA cookie transport are unchanged. Cookie-authenticated requests that change state must carry `X-Requested-With: XMLHttpRequest`, which blocks cross-site request forgery. diff --git a/modules/cabana/admin_events.go b/modules/cabana/admin_events.go index bb28e530..db7ee762 100644 --- a/modules/cabana/admin_events.go +++ b/modules/cabana/admin_events.go @@ -2,6 +2,7 @@ package cabana import ( "context" + "errors" "git.golem15.com/golem15/summercms/modules/backpack" "gorm.io/gorm" @@ -20,7 +21,8 @@ import ( // commit, with that transaction in Tx. A listener's error is returned to the // save and rolls it back, so the change and the revocation commit together // or not at all. A listener must write through Tx and must not open its own -// transaction while Tx is set. The after-commit pact.MCPSubjectChanged +// transaction. Tx is never nil: a site without its save's transaction +// fails instead of firing. The after-commit pact.MCPSubjectChanged // events of the same saves are unchanged and still fire. type BackendAccessRevokedEvent struct { AdminIDs []uint @@ -51,7 +53,11 @@ const ( // fireBackendAccessRevoked fires one BackendAccessRevokedEvent for the // de-duplicated non-zero adminIDs with tx and returns the listeners' error, // which the caller returns so the save rolls back. A missing application or -// bus, or no id left, is a no-op answering nil. +// bus, or no id left, is a no-op answering nil. A nil tx with ids left is +// refused with an error before anything fires (fail closed): the event's +// contract is that listeners revoke inside the save's transaction, and a +// listener handed no transaction would revoke on its own connection while +// the save could still roll back. func fireBackendAccessRevoked(ctx context.Context, app *backpack.App, tx *gorm.DB, reason string, adminIDs ...uint) error { if app == nil || app.Events == nil { return nil @@ -71,5 +77,8 @@ func fireBackendAccessRevoked(ctx context.Context, app *backpack.App, tx *gorm.D if len(ids) == 0 { return nil } + if tx == nil { + return errors.New("cabana: BackendAccessRevokedEvent needs the save's transaction") + } return app.Events.Fire(ctx, &BackendAccessRevokedEvent{AdminIDs: ids, Reason: reason, Tx: tx}) } diff --git a/modules/cabana/backend_access_revoked_tx_test.go b/modules/cabana/backend_access_revoked_tx_test.go new file mode 100644 index 00000000..68cc6fb6 --- /dev/null +++ b/modules/cabana/backend_access_revoked_tx_test.go @@ -0,0 +1,60 @@ +package cabana + +import ( + "context" + "testing" + + "git.golem15.com/golem15/summercms/modules/backpack" + "gorm.io/gorm" +) + +// TestBackendAccessRevokedNeedsTransaction locks the fail-closed side of the +// BackendAccessRevokedEvent contract (32.2 WR-04): a revocation with no +// transaction to commit with is refused before any listener runs, both in +// the helper every site fires through and in the Administrators hook, which +// no longer fires with whatever TxFromContext answered. A save that changes +// nothing a revocation is about still needs no transaction. +func TestBackendAccessRevokedNeedsTransaction(t *testing.T) { + app := backpack.New(nil) + fired := 0 + app.Events.Listen("test", func(_ context.Context, ev *BackendAccessRevokedEvent) error { + fired++ + return nil + }) + ctx := context.Background() + + if err := fireBackendAccessRevoked(ctx, app, nil, BackendAccessPermissions, 7); err == nil { + t.Fatal("a revocation without a transaction answered nil") + } + if err := fireBackendAccessRevoked(ctx, app, nil, BackendAccessPermissions, 0); err != nil { + t.Fatalf("no id left: %v, want the no-op nil", err) + } + if err := fireBackendAccessRevoked(ctx, app, &gorm.DB{}, BackendAccessPermissions, 7); err != nil { + t.Fatalf("with a transaction: %v", err) + } + if fired != 1 { + t.Fatalf("listener ran %d times, want 1 (only with a transaction)", fired) + } + + users := usersAdmin{screens: &backendScreens{app: app}} + for name, user := range map[string]*BackendUser{ + "password set": {ID: 7, priorLoaded: true, passwordSetByOther: true}, + "superuser": {ID: 7, priorLoaded: true, IsSuperuser: true}, + } { + if err := users.FormAfterUpdate(ctx, user); err == nil { + t.Fatalf("%s: an update without its transaction answered nil", name) + } + } + if err := users.FormAfterUpdate(ctx, &BackendUser{ID: 7, priorLoaded: true}); err != nil { + t.Fatalf("an update that revokes nothing: %v", err) + } + if fired != 1 { + t.Fatalf("listener ran %d times after the hooks, want still 1", fired) + } + + roles := rolesAdmin{screens: &backendScreens{app: app}} + role := &BackendUserRole{ID: 3, priorLoaded: true, priorPermissions: `{"a":1}`, Permissions: `{"b":1}`} + if err := roles.FormAfterUpdate(ctx, role); err == nil { + t.Fatal("a role save without its transaction answered nil") + } +} diff --git a/modules/cabana/backend_roles_admin.go b/modules/cabana/backend_roles_admin.go index 88c2d2c6..ec2305e5 100644 --- a/modules/cabana/backend_roles_admin.go +++ b/modules/cabana/backend_roles_admin.go @@ -197,7 +197,12 @@ func (c rolesAdmin) FormAfterUpdate(ctx context.Context, model any) error { if err := db.Unscoped().Model(&BackendUser{}).Where("role_id = ?", role.ID).Pluck("id", &holders).Error; err != nil { return err } - tx, _ := TxFromContext(ctx) + // writeDB proved the save carries its transaction; the event gets that + // transaction itself, like every other site. + tx, ok := TxFromContext(ctx) + if !ok { + return errors.New("cabana: roles: a save needs its transaction") + } if err := fireBackendAccessRevoked(ctx, c.screens.application(), tx, BackendAccessPermissions, holders...); err != nil { return err } diff --git a/modules/cabana/backend_users_admin.go b/modules/cabana/backend_users_admin.go index 355cc724..74e3b55c 100644 --- a/modules/cabana/backend_users_admin.go +++ b/modules/cabana/backend_users_admin.go @@ -851,13 +851,22 @@ func (c usersAdmin) FormAfterUpdate(ctx context.Context, model any) error { if principal != nil && principal.ID == user.ID && !sameRoleID(user.priorRoleID, user.RoleID) { return &ForbiddenError{Message: usersLang + "self_privileged", Details: map[string]any{usersRoleField: []string{usersLang + "self_privileged"}}} } - tx, _ := TxFromContext(ctx) + privilegesChanged := !sameRoleID(user.priorRoleID, user.RoleID) || user.priorPermissions != user.Permissions || user.priorSuperuser != user.IsSuperuser + if !user.passwordSetByOther && !privilegesChanged { + return nil + } + // The revocation must commit with the save: fail closed, as the delete + // hook does, when the update carries no transaction. + tx, ok := TxFromContext(ctx) + if !ok { + return errors.New("cabana: administrators: an update needs its transaction") + } if user.passwordSetByOther { if err := fireBackendAccessRevoked(ctx, c.application(), tx, BackendAccessPasswordSet, user.ID); err != nil { return err } } - if !sameRoleID(user.priorRoleID, user.RoleID) || user.priorPermissions != user.Permissions || user.priorSuperuser != user.IsSuperuser { + if privilegesChanged { if err := fireBackendAccessRevoked(ctx, c.application(), tx, BackendAccessPermissions, user.ID); err != nil { return err }