fix(pier): end only the revoked token's or client's MCP sessions and log the client address (B-WR-04, B-IN-04)

- pact.MCPSubjectChanged and pier.Event gain TokenID and ClientID; a
  narrowed revoked event closes only matching sessions and stateless servers
- cabana fires the admin token revoke with the token row id
- towel.WithClientIP/ClientIP; pier puts the address (surf applies
  http.trusted_proxies) on the resolve context and ResolveBackendToken logs it
This commit is contained in:
Jakub Zych
2026-10-23 16:21:37 +02:00
parent 0ec00f7f69
commit 24cf6cd931
16 changed files with 158 additions and 31 deletions

View File

@@ -60,7 +60,7 @@ Use cases:
- Danger record actions: `pact.AdminRecordAction.Danger` is served as `danger` on the record response's `cabana.RecordAction` (absent when false, so existing payloads are unchanged); the admin's confirm dialog then uses its danger variant.
- Prompted record actions: a `pact.AdminRecordAction` with a `Prompt` (`pact.AdminActionPrompt`) asks the administrator for one text value in its confirm dialog. The record response serves it as `prompt` on the action's `cabana.RecordAction` (absent for every other action, so existing payloads are unchanged), and the action route accepts the body key `payload`, a JSON string, only for such an action: trimmed, not empty and at most `max_length` runes (422 on `payload` with `backend::lang.form.action_prompt_required` or `action_prompt_too_long`, "The payload must be a string." for another JSON type), then handed to `Run` as `pact.AdminRecordActionInput.Value`. Every other record action keeps refusing `record_id`, `values` and `payload`. A prompt without a label fails boot, owned or contributed.
- 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. Names are generic: cabana never names the contributing plugin. 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.
- 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 listener's error is logged and never fails the save.
- 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. A listener's error is logged and never fails the save.
- 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.
@@ -246,7 +246,7 @@ func (p *Plugin) AdminFS() fs.FS { return adminFS }
| `cabana.APITokenPrefix` | The `g15_` prefix of a personal API token plaintext. |
| `cabana.ResolveBackend` | Authenticates a request outside the admin middleware from the Authorization Bearer header only (admin JWT or `g15_` token, never the admin cookie), with an optional scope cover check. A request whose context carries a `bouncer.Dispatch` marker for the `backend` guard (an in-process dispatch; no HTTP request can set one) is answered from the marker: its principal must be a backend one, a frontend marker is `cabana.ErrUnauthenticated`, and a scoped principal must still cover every cover code. |
| `cabana.ErrUnauthenticated` / `cabana.ErrTokenScope` | Sentinel errors from `cabana.ResolveBackend`. |
| `cabana.ResolveBackendToken` | Resolves a `g15_` token outside any request (same hash lookup, usability window, admin load and `last_used_at` stamp as the guard) without the request-method scope filter; returns the principal, the token row and the stored scope names. For an in-process dispatcher that opens a session with a personal token. |
| `cabana.ResolveBackendToken` | Resolves a `g15_` token outside any request (same hash lookup, usability window, admin load and `last_used_at` stamp as the guard) without the request-method scope filter; returns the principal, the token row and the stored scope names. For an in-process dispatcher that opens a session with a personal token. Each attempt is logged as `admin.auth` with the client address the caller put on the context (`towel.ClientIP`). |
| `cabana.ScopeLimitFor` | Filters stored scope names by one HTTP method into the `bouncer.ScopeLimit` the guard would set for a request with that method, with the known and method-allowed counts. |
| `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. |

View File

@@ -7,7 +7,6 @@ import (
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/phrasebook"
)
@@ -163,8 +162,9 @@ func (s *service) accountTokenRevoke(w http.ResponseWriter, r *http.Request) {
WriteError(w, http.StatusNotFound, "not_found", msgNotFound)
return
}
// A revoked token ends what it opened elsewhere (an MCP session).
fireSubjectChanged(r.Context(), s.app, pact.MCPSubjectRevoked, principal.ID)
// A revoked token ends the MCP sessions opened with this token only; the
// admin's sessions through another token or an OAuth grant stay open.
fireTokenRevoked(r.Context(), s.app, principal.ID, row.ID)
WriteData(w, http.StatusOK, mapAdminAPIToken(r.Context(), s.translator(), s.reg, row, time.Now().UTC()), nil)
}
@@ -305,4 +305,4 @@ func resolveScopePhrase(ctx context.Context, tr *phrasebook.Translator, key, fal
}
}
return fallback
}
}

View File

@@ -42,3 +42,24 @@ func fireSubjectChanged(ctx context.Context, app *backpack.App, kind string, adm
}
})
}
// fireTokenRevoked fires one pact.MCPSubjectRevoked for an administrator's
// personal token, narrowed to that token with TokenID: the MCP endpoint ends
// only the sessions opened with this token, not the admin's other sessions
// (another token, or an OAuth grant acting as the linked admin). It fires
// after the commit like fireSubjectChanged and never fails the revoke.
func fireTokenRevoked(ctx context.Context, app *backpack.App, adminID, tokenID uint) {
if app == nil || app.Events == nil || adminID == 0 || tokenID == 0 {
return
}
if ctx == nil {
ctx = context.Background()
}
tx, _ := TxFromContext(ctx)
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
event := &pact.MCPSubjectChanged{Guard: backendSubjectGuard, UserID: adminID, Kind: pact.MCPSubjectRevoked, TokenID: tokenID}
if err := app.Events.Fire(ctx, event); err != nil {
moduleLog.WarnContext(ctx, "cabana: subject changed listener failed", "kind", pact.MCPSubjectRevoked, "admin_id", adminID, "token_id", tokenID, "error", err)
}
})
}

View File

@@ -7,6 +7,7 @@ import (
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/towel"
)
// resolverTokenPath is the path logTokenAuthAt records for a token check that
@@ -23,32 +24,35 @@ const resolverTokenPath = "mcp"
// admin and an application without cabana activated all answer
// ErrUnauthenticated; the audit line is logged under path "mcp".
func ResolveBackendToken(ctx context.Context, app *backpack.App, raw string) (*bouncer.Principal, *BackendAPIToken, []string, error) {
// The caller's client address, when it put one on the context (pier
// does), so a failed attempt is traceable to an address.
remote, _ := towel.ClientIP(ctx)
if ctx == nil {
ctx = context.Background()
}
guard := publishedResolverGuard(app)
if guard == nil || !wellFormedAPIToken(raw) || guard.store == nil {
logTokenAuthAt("", resolverTokenPath, "", "failed", 0, 0)
logTokenAuthAt("", resolverTokenPath, remote, "failed", 0, 0)
return nil, nil, nil, ErrUnauthenticated
}
now := time.Now().UTC()
hash := hashAPIToken(raw)
row, err := guard.store.FindUsableByHash(ctx, hash, now)
if err != nil || row == nil {
logTokenAuthAt("", resolverTokenPath, "", "failed", 0, 0)
logTokenAuthAt("", resolverTokenPath, remote, "failed", 0, 0)
return nil, nil, nil, ErrUnauthenticated
}
if subtle.ConstantTimeCompare([]byte(row.TokenHash), []byte(hash)) != 1 {
logTokenAuthAt("", resolverTokenPath, "", "failed", 0, row.ID)
logTokenAuthAt("", resolverTokenPath, remote, "failed", 0, row.ID)
return nil, nil, nil, ErrUnauthenticated
}
if guard.users == nil {
logTokenAuthAt("", resolverTokenPath, "", "failed", 0, row.ID)
logTokenAuthAt("", resolverTokenPath, remote, "failed", 0, row.ID)
return nil, nil, nil, ErrUnauthenticated
}
principal, err := guard.users.FindByID(ctx, row.BackendUserID)
if err != nil || principal == nil {
logTokenAuthAt("", resolverTokenPath, "", "failed", row.BackendUserID, row.ID)
logTokenAuthAt("", resolverTokenPath, remote, "failed", row.BackendUserID, row.ID)
return nil, nil, nil, ErrUnauthenticated
}
stored := row.Scopes.Get()
@@ -58,7 +62,7 @@ func ResolveBackendToken(ctx context.Context, app *backpack.App, raw string) (*b
// Personal API tokens keep the request locale (see authenticateToken).
principal.PreferredLocale = ""
stampLastUsed(ctx, guard.stamps, guard.store, row.ID, now)
logTokenAuthAt("", resolverTokenPath, "", "success", principal.ID, row.ID)
logTokenAuthAt("", resolverTokenPath, remote, "success", principal.ID, row.ID)
return principal, row, append([]string(nil), stored...), nil
}