feat(32.2-01): in-transaction BackendAccessRevokedEvent at every admin access change
- cabana: BackendAccessRevokedEvent with reasons deleted, deactivated, password_changed, password_set, password_reset and permissions, fired synchronously inside the save's transaction; a listener error rolls back - fired on admin delete, deactivate, a password set by another admin, an own password change, admin:reset-password, a role/permissions/superuser change and a role's permission change (every holder); MCPSubjectChanged unchanged - role delete fires nothing (refused while the role has holders); no sign out everywhere action exists - smoke test TestBackendAccessRevokedSmoke (Postgres)
This commit is contained in:
@@ -186,6 +186,10 @@ Administrators are deactivated, deleted and restored, never removed:
|
||||
|
||||
When a refused row is part of a bulk selection, the whole selection is rolled back and the refusal is shown.
|
||||
|
||||
#### What ends an administrator's OAuth grants
|
||||
|
||||
A plugin that issues OAuth grants acting as an administrator (an MCP connector the administrator signed in to, for example) listens for `cabana.BackendAccessRevokedEvent` and revokes those grants in the same transaction as the change. The event fires when the administrator is deleted or deactivated, when they change their own password on My account, when another administrator sets their password, when `admin:reset-password` resets it, and when their role, own permission overrides or superuser flag change, or the permissions of the role they hold change. A listener that fails rolls the save back, so the change never commits while the grants survive. Each connection can also be revoked one by one where the plugin lists it. The admin has no "sign out everywhere" action.
|
||||
|
||||
Setting the password of another administrator ends that administrator's sessions at once, as `admin:reset-password` does: tokens issued before the change are refused. Their personal API tokens keep working, exactly as after `admin:reset-password`; revoke them with `admin:token:revoke` when they should stop too.
|
||||
|
||||
### The Roles screen
|
||||
|
||||
@@ -96,3 +96,13 @@ Here `acme.pages` listens at a higher priority, so it gets the first chance to c
|
||||
## Events and transactions
|
||||
|
||||
Listeners run where the event is fired, inside any transaction the caller has open. A listener that writes to the database joins that transaction when it uses the transaction handle the event carries. A listener with a side effect outside the database, such as a mail or a broadcast, should defer it with `lagoon.AfterCommit`, so it does not announce a write that rolls back. See [Transactions](../database/transactions.md).
|
||||
|
||||
The framework fires these events of its own:
|
||||
|
||||
| Event | Fired by | When | Transaction |
|
||||
|-------|----------|------|-------------|
|
||||
| `cabana.BackendAccessRevokedEvent` | the admin | an administrator is deleted (`cabana.BackendAccessDeleted`) or deactivated (`cabana.BackendAccessDeactivated`), changes their own password on My account (`cabana.BackendAccessPasswordChanged`), gets a password set by another administrator (`cabana.BackendAccessPasswordSet`) or reset with `admin:reset-password` (`cabana.BackendAccessPasswordReset`), or their role, own permissions or superuser flag change, or the permissions of the role they hold (`cabana.BackendAccessPermissions`) | inside the save's transaction, before the commit, with `cabana.BackendAccessRevokedEvent.Tx` set; a listener's error rolls the save back |
|
||||
| `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.
|
||||
|
||||
@@ -65,6 +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.
|
||||
- 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.
|
||||
@@ -285,6 +286,7 @@ func (p *BlogPlugin) AdminFS() fs.FS { return os.DirFS("testdata/docs") }
|
||||
| `cabana.TokenScopeNames` | The personal-token scope catalog names in catalog order (`*`, `admin:read`, then the plugins' `TokenScopes`), compiled from the activated plugins, so it works at plugin Boot before `cabana.Activate`. |
|
||||
| `cabana.TokenScopeLabels` | The translated label of each catalog scope name, the name itself for an unknown one, in input order. |
|
||||
| `cabana.MCPConsentView` / `cabana.MCPConsentClientView` / `cabana.MCPConsentAdminView` / `cabana.MCPConsentDecisionRequest` / `cabana.MCPConsentDecisionView` | JSON shapes of the MCP consent routes. `cabana.AdminMCPConsentShow` and `cabana.AdminMCPConsentDecide` carry their swag annotations. |
|
||||
| `cabana.BackendAccessRevokedEvent` | Fired inside the transaction of an admin save that ends an administrator's access (`AdminIDs`, `Reason`, `Tx`); a listener error rolls the save back. Reasons: `cabana.BackendAccessDeleted`, `cabana.BackendAccessDeactivated`, `cabana.BackendAccessPasswordChanged`, `cabana.BackendAccessPasswordSet`, `cabana.BackendAccessPasswordReset`, `cabana.BackendAccessPermissions`. |
|
||||
| `cabana.BackendPrincipal` | Loads an admin principal by id through the backend users provider (grants, superuser flag, backend kind set); nil, nil for a missing or deactivated admin. |
|
||||
| `cabana.AdminAPIToken` / `cabana.AdminAPITokenScope` / `cabana.AdminAPITokenCreated` / `cabana.AdminAPITokenRequest` | JSON shapes of the account token API. |
|
||||
| `cabana.AccountItemView` | One row of a contributed section on `cabana.AccountContributionView.Items` (null for a section without `Items`, next to `cabana.AccountContributionView.ItemActions` and `cabana.AccountContributionView.ItemsEmpty`). `cabana.AdminAccountContributionItemAction` carries the item action route's swag annotation. |
|
||||
@@ -462,6 +464,8 @@ The Phase 18.1 pieces (the taglist field and the flat reorder) are covered by Do
|
||||
|
||||
`ClearOnChange` is covered by `clear_on_change_field_test.go` (TestClearOnChangeFieldBoot, Docker-free, and TestClearOnChangeBelongsTo on Postgres: a changed, emptied, kept or co-submitted belongsTo key) and `clear_on_change_test.go` (TestClearOnChangeRelationBoot and, on Postgres, TestClearOnChangeHasMany: link, unlink and a deferred link committed by the parent's first save).
|
||||
|
||||
The in-transaction revocation event is covered by the Postgres test TestBackendAccessRevokedSmoke in `backend_access_revoked_smoke_test.go`: delete, deactivate, a password set by another administrator, a role change, a role's permission change and an own password change each fire one event with the matching reason, administrator and transaction, and a listener error rolls an own password change back.
|
||||
|
||||
Per-item rows of My account sections are covered by the Postgres test TestAccountItemsSmoke in `account_items_smoke_test.go`: items null without `Items`, the rows and permitted item actions, a run inside a transaction with the administrator and item ids, 404 for another administrator's item id without `Run`, 404 for `pact.ErrAccountItemNotFound`, 403 without the permission and the boot refusals.
|
||||
|
||||
The MCP consent routes are covered by the Postgres test TestMCPAdminConsentSmoke in `mcp_consent_smoke_test.go`, over a fake `pact.MCPAdminConsent`: hidden scopes, a dropped `*` that was not requested, a requested `*` collapsing the grant, offline access, deny, 400 for a bad body, 401 anonymous, 403 `interactive_only` for a `g15_` token and 404 without a provider or for an unknown request. TestTokenScopeNamesAndLabels covers the exported catalog names and labels.
|
||||
|
||||
@@ -394,6 +394,12 @@ func (s *service) accountUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
return err
|
||||
}
|
||||
if changePassword {
|
||||
// A listener's error rolls the password change back.
|
||||
if err := fireBackendAccessRevoked(ctx, s.app, tx, BackendAccessPasswordChanged, user.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
saved, err = lockAccount(ctx, tx, user.ID)
|
||||
return err
|
||||
})
|
||||
|
||||
75
modules/cabana/admin_events.go
Normal file
75
modules/cabana/admin_events.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package cabana
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// BackendAccessRevokedEvent is fired when administrators lose access that a
|
||||
// credential issued earlier still holds elsewhere: an administrator deleted
|
||||
// or deactivated, a password changed or set, or what an administrator may do
|
||||
// changed (role, own permissions, superuser flag, or the permissions of the
|
||||
// role they hold). Reason is one of the BackendAccess* constants. Listeners
|
||||
// revoke what is keyed on these administrators, for example OAuth grants an
|
||||
// administrator consented to.
|
||||
//
|
||||
// It is fired synchronously through app.Events.Fire as a
|
||||
// *BackendAccessRevokedEvent inside the transaction of the save, before the
|
||||
// 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
|
||||
// events of the same saves are unchanged and still fire.
|
||||
type BackendAccessRevokedEvent struct {
|
||||
AdminIDs []uint
|
||||
Reason string
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
// Reasons of a BackendAccessRevokedEvent.
|
||||
const (
|
||||
// BackendAccessDeleted: the administrator was deleted.
|
||||
BackendAccessDeleted = "deleted"
|
||||
// BackendAccessDeactivated: the administrator was deactivated.
|
||||
BackendAccessDeactivated = "deactivated"
|
||||
// BackendAccessPasswordChanged: the administrator changed their own
|
||||
// password on My account.
|
||||
BackendAccessPasswordChanged = "password_changed"
|
||||
// BackendAccessPasswordSet: another administrator set the password on
|
||||
// the Administrators screen.
|
||||
BackendAccessPasswordSet = "password_set"
|
||||
// BackendAccessPasswordReset: the password was reset with the
|
||||
// admin:reset-password command.
|
||||
BackendAccessPasswordReset = "password_reset"
|
||||
// BackendAccessPermissions: the administrator's role, own permissions or
|
||||
// superuser flag changed, or the permissions of the role they hold.
|
||||
BackendAccessPermissions = "permissions"
|
||||
)
|
||||
|
||||
// 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.
|
||||
func fireBackendAccessRevoked(ctx context.Context, app *backpack.App, tx *gorm.DB, reason string, adminIDs ...uint) error {
|
||||
if app == nil || app.Events == nil {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
seen := make(map[uint]bool, len(adminIDs))
|
||||
ids := make([]uint, 0, len(adminIDs))
|
||||
for _, id := range adminIDs {
|
||||
if id == 0 || seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return app.Events.Fire(ctx, &BackendAccessRevokedEvent{AdminIDs: ids, Reason: reason, Tx: tx})
|
||||
}
|
||||
129
modules/cabana/backend_access_revoked_smoke_test.go
Normal file
129
modules/cabana/backend_access_revoked_smoke_test.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package cabana_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
)
|
||||
|
||||
// revokedRecorder records every *cabana.BackendAccessRevokedEvent and, while
|
||||
// fail is set, answers an error so the save rolls back.
|
||||
type revokedRecorder struct {
|
||||
mu sync.Mutex
|
||||
events []cabana.BackendAccessRevokedEvent
|
||||
fail atomic.Bool
|
||||
}
|
||||
|
||||
func (r *revokedRecorder) take() []cabana.BackendAccessRevokedEvent {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
out := r.events
|
||||
r.events = nil
|
||||
return out
|
||||
}
|
||||
|
||||
// TestBackendAccessRevokedSmoke drives the D-13 sites over the admin API on
|
||||
// Postgres: deleting and deactivating an administrator, another
|
||||
// administrator setting a password, an own password change on PUT /account,
|
||||
// a role change and a role's permission change each fire one
|
||||
// cabana.BackendAccessRevokedEvent with the matching reason, the affected
|
||||
// administrator and the save's transaction; a listener error makes the
|
||||
// password change fail and leaves the stored hash unchanged.
|
||||
func TestBackendAccessRevokedSmoke(t *testing.T) {
|
||||
env := newScreensEnv(t)
|
||||
rec := &revokedRecorder{}
|
||||
env.app.Events.Listen("test", func(_ context.Context, ev *cabana.BackendAccessRevokedEvent) error {
|
||||
rec.mu.Lock()
|
||||
rec.events = append(rec.events, *ev)
|
||||
rec.mu.Unlock()
|
||||
if rec.fail.Load() {
|
||||
return errors.New("listener refused")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
_, rootToken := env.admin(t, "revoked-root", true, "")
|
||||
expectOne := func(t *testing.T, reason string, ids ...uint) {
|
||||
t.Helper()
|
||||
got := rec.take()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("%s: %d events, want 1: %+v", reason, len(got), got)
|
||||
}
|
||||
if got[0].Reason != reason || !slices.Equal(got[0].AdminIDs, ids) || got[0].Tx == nil {
|
||||
t.Fatalf("%s: event = %+v, want ids %v with a transaction", reason, got[0], ids)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("delete", func(t *testing.T) {
|
||||
gone, _ := env.admin(t, "revoked-gone", false, "")
|
||||
rec.take()
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, userURL(gone.ID), rootToken, nil)
|
||||
expectOne(t, cabana.BackendAccessDeleted, gone.ID)
|
||||
})
|
||||
|
||||
t.Run("deactivate", func(t *testing.T) {
|
||||
target, _ := env.admin(t, "revoked-off", false, "")
|
||||
rec.take()
|
||||
env.expect(t, http.StatusOK, http.MethodPost, userURL(target.ID, "actions", "deactivate"), rootToken, map[string]any{})
|
||||
expectOne(t, cabana.BackendAccessDeactivated, target.ID)
|
||||
})
|
||||
|
||||
t.Run("password set by another administrator", func(t *testing.T) {
|
||||
target, _ := env.admin(t, "revoked-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"})
|
||||
expectOne(t, cabana.BackendAccessPasswordSet, target.ID)
|
||||
})
|
||||
|
||||
t.Run("role change", func(t *testing.T) {
|
||||
target, _ := env.admin(t, "revoked-role", false, "")
|
||||
other := env.seedRole(t, roleSeed{Name: "revoked-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})
|
||||
expectOne(t, cabana.BackendAccessPermissions, target.ID)
|
||||
})
|
||||
|
||||
t.Run("role permission change", func(t *testing.T) {
|
||||
role := env.seedRole(t, roleSeed{Name: "revoked-perms", Permissions: map[string]int{"acme.demo.access": 1}})
|
||||
holder := env.seedAdmin(t, adminSeed{Name: "revoked-holder", Role: role.ID})
|
||||
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}}))
|
||||
expectOne(t, cabana.BackendAccessPermissions, holder.ID)
|
||||
})
|
||||
|
||||
t.Run("own password change", func(t *testing.T) {
|
||||
self, selfToken := env.admin(t, "revoked-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"})
|
||||
expectOne(t, cabana.BackendAccessPasswordChanged, self.ID)
|
||||
})
|
||||
|
||||
t.Run("a listener error rolls the password change back", func(t *testing.T) {
|
||||
self, selfToken := env.admin(t, "revoked-veto", false, "")
|
||||
before := env.storedUser(t, self.ID).Password
|
||||
rec.take()
|
||||
rec.fail.Store(true)
|
||||
defer rec.fail.Store(false)
|
||||
res := env.call(t, http.MethodPut, "/account", selfToken,
|
||||
map[string]any{"email": self.Email, "current_password": adminTestPassword, "password": "brand-new-secret", "password_confirmation": "brand-new-secret"})
|
||||
if res.Code >= 200 && res.Code < 300 {
|
||||
t.Fatalf("vetoed password change answered %d %s", res.Code, res.Body.String())
|
||||
}
|
||||
if after := env.storedUser(t, self.ID).Password; after != before {
|
||||
t.Fatal("a vetoed password change wrote the new hash")
|
||||
}
|
||||
if got := rec.take(); len(got) != 1 || got[0].Reason != cabana.BackendAccessPasswordChanged {
|
||||
t.Fatalf("vetoed change events = %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
@@ -176,9 +176,11 @@ func (rolesAdmin) AdminSetPermissionValues(_ context.Context, field string, reco
|
||||
return nil
|
||||
}
|
||||
|
||||
// FormAfterUpdate fires pact.MCPSubjectChanged (permissions) for every
|
||||
// administrator holding the role when its grants changed, their ids read
|
||||
// through the save's transaction. The save itself is unchanged.
|
||||
// FormAfterUpdate fires BackendAccessRevokedEvent (permissions) inside the
|
||||
// save's transaction and pact.MCPSubjectChanged (permissions) after the
|
||||
// commit for every administrator holding the role when its grants changed,
|
||||
// their ids read through the save's transaction. A listener error of the
|
||||
// first rolls the save back.
|
||||
func (c rolesAdmin) FormAfterUpdate(ctx context.Context, model any) error {
|
||||
role, err := asRole(model)
|
||||
if err != nil {
|
||||
@@ -195,6 +197,10 @@ 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)
|
||||
if err := fireBackendAccessRevoked(ctx, c.screens.application(), tx, BackendAccessPermissions, holders...); err != nil {
|
||||
return err
|
||||
}
|
||||
fireSubjectChanged(ctx, c.screens.application(), pact.MCPSubjectPermissions, holders...)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -211,8 +211,9 @@ func (c usersAdmin) FormBeforeDelete(ctx context.Context, model any) error {
|
||||
return guardLastSuperuser(ctx, user)
|
||||
}
|
||||
|
||||
// FormAfterDelete ends the deleted administrator's sessions (D-12). The
|
||||
// delete itself stays the framework's soft delete through deleted_at: a
|
||||
// FormAfterDelete ends the deleted administrator's sessions (D-12) and
|
||||
// fires BackendAccessRevokedEvent (deleted) inside the delete's transaction.
|
||||
// The delete itself stays the framework's soft delete through deleted_at: a
|
||||
// backend user is never hard-deleted, so tokens, linked_by references and
|
||||
// attachments keep valid foreign keys (D-10). Personal API tokens stop
|
||||
// because the guard refuses a deleted administrator.
|
||||
@@ -231,6 +232,9 @@ func (c usersAdmin) FormAfterDelete(ctx context.Context, model any) error {
|
||||
Update("tokens_valid_after", cutoff).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fireBackendAccessRevoked(ctx, c.application(), tx, BackendAccessDeleted, user.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
fireSubjectChanged(ctx, c.application(), pact.MCPSubjectDeleted, user.ID)
|
||||
return nil
|
||||
}
|
||||
@@ -284,6 +288,9 @@ func (c usersAdmin) lifecycles() []usersLifecycle {
|
||||
Updates(map[string]any{"is_activated": false, "tokens_valid_after": revocationCutoff()}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fireBackendAccessRevoked(ctx, c.application(), db, BackendAccessDeactivated, user.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
// A deactivated administrator can no longer act anywhere,
|
||||
// an MCP session included.
|
||||
fireSubjectChanged(ctx, c.application(), pact.MCPSubjectDeleted, user.ID)
|
||||
@@ -818,15 +825,20 @@ func (c usersAdmin) FormBeforeUpdate(ctx context.Context, model any) error {
|
||||
if changed {
|
||||
cutoff := revocationCutoff()
|
||||
user.TokensValidAfter = &cutoff
|
||||
// Your own password is refused above, so another administrator
|
||||
// set this one: FormAfterUpdate fires password_set.
|
||||
user.passwordSetByOther = true
|
||||
}
|
||||
return c.checkIdentity(ctx, user)
|
||||
}
|
||||
|
||||
// FormAfterUpdate refuses a change of the editor's own role (D-08). The
|
||||
// submitted role is assigned after FormBeforeUpdate, so it is compared here,
|
||||
// with the row written: the refusal rolls the save back. A save that changed
|
||||
// the administrator's role, own permissions or superuser flag then fires
|
||||
// pact.MCPSubjectChanged (permissions) for them.
|
||||
// with the row written: the refusal rolls the save back. A password another
|
||||
// administrator set fires BackendAccessRevokedEvent (password_set), and a
|
||||
// save that changed the administrator's role, own permissions or superuser
|
||||
// flag fires it (permissions) and pact.MCPSubjectChanged (permissions) for
|
||||
// them; the events' listener errors roll the save back.
|
||||
func (c usersAdmin) FormAfterUpdate(ctx context.Context, model any) error {
|
||||
user, err := asBackendUser(model)
|
||||
if err != nil {
|
||||
@@ -839,7 +851,16 @@ 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)
|
||||
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 err := fireBackendAccessRevoked(ctx, c.application(), tx, BackendAccessPermissions, user.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
fireSubjectChanged(ctx, c.application(), pact.MCPSubjectPermissions, user.ID)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -161,6 +161,9 @@ func adminResetPassword(ctx context.Context, app *backpack.App, in bonfire.Input
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fireBackendAccessRevoked(ctx, app, tx, BackendAccessPasswordReset, users[0].ID); err != nil {
|
||||
return err
|
||||
}
|
||||
out.Success(fmt.Sprintf("reset password for %s", users[0].Login))
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -91,6 +91,10 @@ type BackendUser struct {
|
||||
// administrator may do changed (pact.MCPSubjectChanged).
|
||||
priorPermissions string
|
||||
priorSuperuser bool
|
||||
// passwordSetByOther is set when the Administrators screen hashed a
|
||||
// password another administrator typed, so the save fires
|
||||
// BackendAccessRevokedEvent (password_set).
|
||||
passwordSetByOther bool
|
||||
}
|
||||
|
||||
func (BackendUser) TableName() string { return "backend_users" }
|
||||
|
||||
Reference in New Issue
Block a user