Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 50da92c1fb | |||
| 0428093d33 | |||
| 98924041c9 | |||
| ebe408f542 | |||
| 9730110d55 | |||
| b929ba9f33 | |||
| 92676ba14e | |||
| 30f7a01d3d | |||
| 38551a4104 | |||
| e3c164fdf0 | |||
| 25b9f2e35c | |||
|
|
f20a8d3b98 | ||
|
|
ee5c096d0d | ||
|
|
970719ce75 | ||
|
|
32f92591d6 | ||
|
|
72de822a84 |
54
README.md
54
README.md
@@ -23,12 +23,12 @@ It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_ap
|
||||
- **Login throttling.** Failed logins are counted per user and client address in `user_throttle` (`CheckAndRecordLogin`, `RejectIfThrottled`) and suspend the account for a configured time. The client address is `surf.ClientIP` with the framework's `http.trusted_proxies`, as for the `/register` IP limit and the `user-api` rate limit: behind a listed reverse proxy it is the `X-Forwarded-For` client, otherwise the connection address, and an `X-Forwarded-For` header from any other peer is ignored. A deployment behind a proxy lists the proxy's address in `http.trusted_proxies`; otherwise every visitor shares the proxy's counter.
|
||||
- **Rate limiting.** Every route runs behind the `user-api` bucket: 120 requests a minute per authenticated user, or per client IP for anonymous calls.
|
||||
- **Profile.** `POST /update`, `POST /marketing-consent`, `POST /avatar` and `POST /avatar/remove` (the avatar is stored through the framework's attachment storage).
|
||||
- **Deactivation and bans.** Deactivation is self-service and reversible: a password login or a `golem15.sociallogin` sign-in restores a deactivated account and sends the reactivate mail, and an administrator can restore it too. It ends every earlier session JWT and personal API token of the user (`RevokeUserAccess` stamps `tokens_valid_after` and revokes the `user_api_tokens` rows), so the user signs in again and gets a fresh token, while the old API tokens stay revoked. A ban is the lock: password login, social sign-in and `POST /refresh` refuse a banned user, and banning revokes the user's sessions and API tokens. Neither unban nor restore revives a token. Activation gates login, deactivation does not: while `require_activation` is on, an account that is both deactivated and not activated is refused and stays deactivated, with no reactivate mail. Upgrade note: accounts deactivated or banned before this version keep their API tokens until they are deactivated or banned again (both actions are idempotent) or `RevokeUserAccess` runs for them.
|
||||
- **Organisations.** The `Organisation` model and the `organisation_id` and `organisation_role` user columns, as a foreign-key target for other plugins. An organisation has a name, a slug (filled from the name by `Slugify` when it is left empty), a description, an avatar and its members: the users whose `organisation_id` points at it. `organisation_role` belongs to that membership: the admin clears it whenever a user's organisation changes (see the Organisations screen), and an application that sets `organisation_id` itself sets or clears the role with it.
|
||||
- **Deactivation and bans.** Deactivation is self-service and reversible: a password login or a `golem15.sociallogin` sign-in restores a deactivated account and sends the reactivate mail, and an administrator can restore it too. It ends every earlier session JWT and personal API token of the user (`RevokeUserAccess` stamps `tokens_valid_after` and revokes the `user_api_tokens` rows), so the user signs in again and gets a fresh token, while the old API tokens stay revoked. A ban is the lock: password login, social sign-in and `POST /refresh` refuse a banned user, and banning revokes the user's sessions and API tokens. A banned user's account link answers no administrator (`LinkedBackendUser`). Neither unban nor restore revives a token. Activation gates login, deactivation does not: while `require_activation` is on, an account that is both deactivated and not activated is refused and stays deactivated, with no reactivate mail. Upgrade note: accounts deactivated or banned before this version keep their API tokens until they are deactivated or banned again (both actions are idempotent) or `RevokeUserAccess` runs for them.
|
||||
- **Organisations.** The `Organisation` model and the `organisation_id` and `organisation_role` user columns, as a foreign-key target for other plugins. An organisation has a name, a slug (filled from the name by `Slugify` when it is left empty), a description, an avatar, a logo and its members: the users whose `organisation_id` points at it. The logo is a second public image attachment (`logo`, `models.OrganisationLogoField`), kept in `system_files` like the avatar. The plugin serves no frontend organisation payload, so applications that build one add the logo with `classes.OrganisationLogoFields(ctx, app, org)`, which answers `has_logo` (bool), `logo` (the attachment's disk name, or null) and `logo_url` (a 256 px thumbnail URL, `classes.OrganisationLogoSize`, or null), the keys the user payload uses for its avatar; `classes.OrganisationLogoURL(ctx, app, org, size)` answers the URL at any size (the thumbnail, or the original file's public URL when the thumbnail fails, as `AvatarURL` does) and false when there is no logo or no file bucket. `organisation_role` belongs to that membership: the admin clears it whenever a user's organisation changes (see the Organisations screen), and an application that sets `organisation_id` itself sets or clears the role with it.
|
||||
- **User groups.** The `user_groups` table (seeded with the `guest` and `registered` groups, as in PHP) and the `users_groups` membership pivot, the `UserGroup` model and the `User.Groups` relation, which is never serialized. `UserGroupCodes` and `HasGroupCode` let other plugins check membership server-side, for example a site-admin check on the group code `admin`. No user API route reads or writes groups, and the user payload still answers `"groups":[]`. Membership is written in one place only: the `groups` field of the admin user form. Apart from that, rows leave `users_groups` only when a user or a group is deleted for good. The admin Users list can filter by group.
|
||||
- **Admin screens.** The plugin registers the Users screen with the framework's admin (`pact.HasAdminControllers`, controller ID `golem15.user.users`), the port of the WinterCMS `Users` controller: a list with search, the group, registration date and activated filters and row states (deactivated, banned, not activated); a read-only preview with a status hint; and a form with name, email, a password with confirmation, an optional invitation mail, the user's groups, the organisation, the avatar and the user's frontend permissions. Bulk actions activate, deactivate, restore, ban and unban users; the preview offers activate, unban and unsuspend while they apply. Deactivating is the soft delete, and deactivate and ban both end the user's earlier sessions and personal API tokens (see Deactivation and bans); the delete button and the bulk delete remove a user for good, together with the throttle rows, group memberships and attachments. A user created in the admin starts not activated. There is no impersonation and no guest account.
|
||||
- **User Groups screen.** Controller ID `golem15.user.usergroups`, the port of the WinterCMS `UserGroups` controller, behind `golem15.users.access_groups`: a list with the name, code, creation date and number of members, and a form with the name, the code (letters, digits, underscore and hyphen; unique), a description and the group's frontend permissions as checkboxes, stored in `user_groups.permissions` as a JSON object of code to `1`. A group can be deleted from its form; its memberships go with it and its members stay. The screen never changes who is in a group.
|
||||
- **Organisations screen.** Controller ID `golem15.user.organisations`, the port of the WinterCMS `Organisations` controller, behind `golem15.users.access_users`: a list and a form with the name, slug, description and avatar, and on an existing organisation the Members tab. Adding a member sets that user's `organisation_id` and removing one clears it; both also clear the user's `organisation_role`, so a role never moves to another organisation or outlives the membership. A user is never deleted. Only users without an organisation can be added, so a user moves by being removed from one organisation and added to the other (or through the organisation field of the user form, where a save that changes the organisation, to another one or to none, clears `organisation_role` unless the same save writes it). Deleting an organisation clears `organisation_id` and `organisation_role` of its members first.
|
||||
- **Organisations screen.** Controller ID `golem15.user.organisations`, the port of the WinterCMS `Organisations` controller, behind `golem15.users.access_users`: a list and a form with the name, slug, description, avatar and logo (an image upload), and on an existing organisation the Members tab. Adding a member sets that user's `organisation_id` and removing one clears it; both also clear the user's `organisation_role`, so a role never moves to another organisation or outlives the membership. A user is never deleted. Only users without an organisation can be added, so a user moves by being removed from one organisation and added to the other (or through the organisation field of the user form, where a save that changes the organisation, to another one or to none, clears `organisation_role` unless the same save writes it). Deleting an organisation clears `organisation_id` and `organisation_role` of its members first, and removes its avatar and logo attachments with it (the files once the delete commits).
|
||||
- **Privileged groups.** The groups whose code is listed in `golem15.user.privileged_groups` (default `admin`) are privileged: an application may treat their members as site administrators. Three things therefore need the backend permission `golem15.users.manage_privileged_groups` on top of the screen's own permission, and answer 403 without it, saving nothing. First, membership: adding a privileged group to a user or removing it, on create and on update of the user form. An administrator without the permission sees those groups locked in the field and can still change the user's other groups. Second, the code: creating a group with a privileged code, changing a group's code to or from a privileged one, and deleting a privileged group. Its name, description and frontend permissions need only `golem15.users.access_groups`. Codes compare case-sensitively, and a group without a code is never privileged. Third, the member's account, which is protected against takeover: changing that user's email or password, and deleting them for good, needs the backend permission `golem15.users.manage_privileged_groups` on top of `golem15.users.access_users`. Without it the request answers 403 and nothing is saved; a bulk delete that contains such a user deletes none of the selected users. Everything else on such a user (name, organisation, avatar, frontend permissions, activate, deactivate, restore, ban, unban, unsuspend) needs only `golem15.users.access_users`. `PrivilegedGroupCodes`, `IsPrivilegedCode`, `PrivilegedGroupIDs` and `IsPrivilegedMember` expose the rule to other code.
|
||||
- **Frontend permissions.** `golem15_user_frontend_permissions` is the catalogue of permissions a site defines for its users (rows come from the application's migrations or seeds). A user's own choices are stored in `users.permissions` and a group's in `user_groups.permissions`, as a JSON object of code to `1` (allow) or `-1` (deny). `MergedPermissions` combines them as PHP `getMergedPermissions` does: among a user's groups the most positive value wins, then the user's own value replaces the groups'. `HasPermission` and `UserHasPermission` answer whether a code is held: only at exactly `1`, with Winter's `*` wildcards. Neither value appears in the user payload, whose `permissions` key stays `null`.
|
||||
- **Last seen.** `users.last_seen` is stamped by `POST /login` and a successful `POST /refresh` through `TouchLastSeen`, at most once per five minutes per user. A failed write is logged and never fails authentication. It is shown in the admin list and is not part of any user payload.
|
||||
@@ -36,13 +36,26 @@ It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_ap
|
||||
- **Handle.** `users.handle` is a unique nullable `VARCHAR(255)` generated on create (`classes.HandleGenerator`, charset `[a-z0-9._-]`, length 2–255). It is omitted from the user JSON payload (`json:"-"`). `user:backfill-handles` fills existing rows that still have none.
|
||||
- **User lighthouse authorizer.** Boot calls `classes.RegisterUserAuthorizer`: `lighthouse.From` then `Registry.Register("user", …)` if the namespace is free. `classes.AuthorizeUser` allows only `user:{id}` for that user (`lighthouse.ChannelID` on the two-segment name).
|
||||
- **Shared API tokens.** `user_api_tokens` stores one hashed personal/OAuth credential per user for the whole application. The `user.api_token` guard authenticates it for any plugin; `user.scope:<scope>` limits delegated access and `user.permission:<code>` checks the user's current group permissions. `POST/GET/DELETE /tokens` manage personal tokens, and `user:token:create`, `user:token:list` and `user:token:revoke` provide the CLI equivalent. A raw secret is shown only when created.
|
||||
- **Member token scopes.** A member personal token (`usr_`) carries the built-in scopes `read`, `write` and `ai`, plus any scope another plugin declares with `pact.HasFrontendTokenScopes`:
|
||||
|
||||
```go
|
||||
func (Plugin) FrontendTokenScopes() []pact.FrontendTokenScope {
|
||||
return []pact.FrontendTokenScope{
|
||||
{Name: "inventory:read", Label: "acme.inventory::lang.scopes.read", Description: "acme.inventory::lang.scopes.read_description"},
|
||||
{Name: "inventory:write", Label: "acme.inventory::lang.scopes.write", Description: "acme.inventory::lang.scopes.write_description"},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Boot compiles the catalog from the activated plugins (`classes.CompileAPITokenScopes`, published as `*classes.APITokenScopeCatalog`) and fails on a name that does not pass `pact.ValidTokenScopeName`, a built-in redeclared, a name two plugins declare (the error names both), an empty label or description, or a label or description phrase key (containing `::`) that the translator does not have. `POST /tokens` and `classes.MintAPITokenFor(app, …)` accept the scopes of the application's own catalog (`classes.APITokenScopesFor(app)`) and answer an undeclared one with the usual 422 `The selected scope is invalid.`; the console's `user:token:create` uses `MintAPITokenFor` too. Applications mint with `MintAPITokenFor`. The older `classes.MintAPIToken` is deprecated; it keeps its signature and accepts the built-ins plus every scope a catalog compiled in the same process declared, a fallback for existing callers; production runs one application per process, so that is the application's own catalog, while a test binary that boots several applications shares it (`classes.ResetDeclaredAPITokenScopes` clears it, for tests only). `user.scope:<name>`, `middleware.Scope` and `APIToken.HasScope` check a declared scope like a built-in, and `GET /tokens` lists it in `scopes`. `GET /tokens/scopes` (`jwt.auth`) answers `{"data":[{"name","label","description","built_in"}]}`, the built-ins first, then the declared scopes in activation order, with phrase-key labels and descriptions translated for the request locale. The admin `g15_` token catalog never shows these scopes (it reads `pact.HasTokenScopes` only). `classes.AllowedAPITokenScopes` stays the built-in list.
|
||||
- **Mail templates.** Activation, reset, reactivation and invitation mails in Polish and English (`golem15.user::mail.*`, layout `golem15.user::mail.layouts.user`); the locale follows the user (`ResolveMailLocale`). The invitation (`golem15.user::mail.invite`) is sent when an administrator creates a user with "Send invitation by email" set; it carries the user's login and an activation link, never the password.
|
||||
- **Extension events.** `RegisterEvent` fires after a user row is created; its `Payload` is a copy of the register input (extra keys a client sent included, `password` and `password_confirmation` never), so it is untrusted client input. `CreatedEvent` (`classes.CreatedEventName` `user.Created`) fires from API register and admin create. `/register` logs a failing `RegisterEvent` or `CreatedEvent` listener at Error level and continues: a committed registration is never undone or failed by a listener. `DeletingEvent` (`classes.DeletingEventName` `user.Deleting`) fires from `FormAfterDelete` before `ForceDeleteCleanup` / unscoped delete, inside the same transaction. `GetApiArrayEvent` lets other plugins merge keys into the user payload.
|
||||
- **Registration for other plugins.** `RegisterUser`, `FireRegisterEvent`, `IssueToken` and `APIArray` are the steps `POST /register` runs, exported so another plugin (a first-run setup endpoint, for example) creates a user with the same validation, hashing, event, token and payload.
|
||||
- **OAuth providers.** `GET /oauth-providers` lists the social sign-in providers a social-login plugin has enabled, read on every request from its published `classes.OAuthProviderSource`. Without one it answers the empty list, as before.
|
||||
- **Frontend account link for administrators.** A backend administrator's account can be linked to one frontend user, and a frontend user to one administrator (`golem15_user_backend_links`, unique on both sides). The administrator starts it on My account (section `frontend_account`, action `link`): the plugin stores a one-shot request (32 random bytes as hex, kept only as its SHA-256, valid `golem15.user.backend_links.request_ttl`) and answers the site URL `golem15.user.frontend_url` (else `app.url`) + `/link-admin?code=<code>`, which the admin opens in a new tab. The site page reads `GET /backend-link/{code}` (the administrator's login and display name and the expiry, nothing else), has the person sign in on the site as the frontend user, and posts the code to `POST /backend-link/confirm` behind `jwt.auth`. The link is written only there, in one transaction with the request row locked, and only when the session token was issued at or after the request was created (compared in whole seconds), so a browser that was already signed in must sign in again; password, social login and any login gate apply as usual. A code works once; a used, expired or unknown code answers 404. No link is ever made by matching emails. The administrator removes it on My account (`unlink`), and an administrator holding `golem15.users.manage_backend_links` links or unlinks another administrator on the Administrators screen (see Admin). Deleting or deactivating the frontend user removes the link in the same transaction; deleting an administrator removes it through the foreign key, and a deactivated or soft-deleted administrator is not answered by the resolver. Boot publishes `*classes.BackendLinks` and the same value as `pact.MCPLinkedBackendResolver` (`LinkedBackendUser`, one query per call), which the framework's MCP endpoint uses to give a frontend user the linked administrator's backend tools. `BackendLinkedEvent` and `BackendUnlinkedEvent` fire inside the write transaction.
|
||||
- **Frontend account link for administrators.** A backend administrator's account can be linked to one frontend user, and a frontend user to one administrator (`golem15_user_backend_links`, unique on both sides). The administrator starts it on My account (section `frontend_account`, action `link`): the plugin stores a one-shot request (32 random bytes as hex, kept only as its SHA-256, valid `golem15.user.backend_links.request_ttl`) and answers the site URL `golem15.user.frontend_url` (else `app.url`) + `golem15.user.backend_links.page_path` (default `/link-admin`, `classes.BackendLinkPagePath`) + `#code=<code>`, which the admin opens in a new tab. The code travels in the URL fragment, which browsers never send to a server, so it stays out of access logs. The site page reads the fragment, keeps the code in the browser (for example `sessionStorage`) across the sign-in, shows the request through `POST /backend-link/show` with `{"code":…}` in the body (the administrator's login and display name and the expiry, nothing else), shows which frontend account is signed in, and posts the code to `POST /backend-link/confirm` behind `jwt.auth`. Both POST routes read the code from the body only (JSON, or a form body), never from the query string. `GET /backend-link/{code}` answers the same as the POST show route and stays for compatibility; it is deprecated, because its path puts the code in access logs, so pages use POST. The link is written only by the confirm, in one transaction with the request row locked, and only when the session was signed in at or after the request was created: the proof is the session token's `auth_time` claim (`bouncer.VerifyAuthTime`), the time of the sign-in itself, compared in whole seconds with the request. `POST /refresh` copies `auth_time` and never renews it, so a refreshed old session does not pass, and a browser that was already signed in must sign in again; password, social login and any login gate apply as usual. Upgrade note: session tokens issued before the framework stamped `auth_time` (SummerCMS v0.5.0) carry no `auth_time`, and a refresh carries that absence forward, so a frontend user signed in before the upgrade gets `stale_session` and must sign in again before linking. A code works once; a used, expired or unknown code answers 404. No link is ever made by matching emails. The administrator removes it on My account (`unlink`), and an administrator holding `golem15.users.manage_backend_links` links or unlinks another administrator on the Administrators screen (see Admin). Deleting or deactivating the frontend user removes the link in the same transaction; deleting an administrator removes it through the foreign key, and a deactivated or soft-deleted administrator is not answered by the resolver. Boot publishes `*classes.BackendLinks` and the same value as `pact.MCPLinkedBackendResolver` (`LinkedBackendUser`, one query per call), which the framework's MCP endpoint uses to give a frontend user the linked administrator's backend tools. `BackendLinkedEvent` and `BackendUnlinkedEvent` fire inside the write transaction.
|
||||
- **Frontend permission codes from plugins.** Another plugin declares the frontend permission codes its routes check (`user.permission:<code>`) with `pact.HasFrontendPermissions`. The Users and User Groups permission editors offer the rows of `golem15_user_frontend_permissions` first, unchanged, then the declared codes of the activated plugins in activation order (`classes.FrontendPermissionCatalog`); a seeded row wins over a declared code with the same code, and the first declaring plugin wins over a later one. Nothing is written to the table; the stored permissions keep their shape.
|
||||
- **MCP guard and the `user_me` tool.** Boot registers `classes.MCPUserGuard` as the MCP guard provider `user` in the application's `*pact.MCPGuards` and publishes it as `pact.MCPPersonalTokenResolver`, so the framework's MCP endpoint (built with `-tags summercms_mcp`) can bind tools to routes behind `user.api_token`, `user.scope:<scope>` and `user.permission:<code>` and accept the plugin's personal API tokens (the `golem15.user.api_tokens.prefix`). The guard decides with the routes' own checks: every scope of the route must be granted to the MCP session, and every permission code must be granted by one of the user's groups, as `user.permission` checks it (a user's own permission override does not grant). A tool call runs the route with the user and an in-memory token credential carrying the session's scopes (ID 0, never saved). The plugin's one tool, `me` (exposed as `user_me`), runs `GET /token/me` and answers the signed-in user's payload. Revoking a personal token, saving a user on the Users screen, saving or deleting a group and the link changes fire `pact.MCPSubjectChanged` after they commit, so open MCP sessions re-list their tools or end.
|
||||
- **Access revocation.** Banning a user (the admin `ban` bulk action, for the users it newly bans), a password reset (`POST /reset-password`), an administrator setting a password on the Users screen and the user's own `POST /change-password` fire `classes.AccessRevokedEvent` (`user.AccessRevoked`: `UserIDs`, `Before`, `Reason`, `Tx`) through `classes.FireAccessRevoked`, inside the write's transaction (a listener error rolls the write back), and a "revoked" `pact.MCPSubjectChanged` per user after it commits, so the users' MCP sessions end. `Before` is the untruncated instant of the revocation for every reason, the self-service change included, so the event ends every OAuth grant of the user however recently its client refreshed it. `tokens_valid_after` keeps its whole-second value: the second of `Before` for a ban, a reset or an administrator's password, and for the self-service change the start of the calling session's `iat` second, so the calling session and the session tokens issued since that second survive. `Reason` is `ban`, `password_reset`, `password_set_by_admin` or `password_changed` (`AccessRevokedBan`, `AccessRevokedPasswordReset`, `AccessRevokedPasswordSetByAdmin`, `AccessRevokedPasswordChanged`). Listeners revoke what such a user still holds elsewhere: `golem15.oauthserver` revokes the users' OAuth access and refresh tokens created before `Before`. `RevokeUserAccess`, `BanUsers` and `DeactivateUsers` keep their behaviour and fire nothing: an application that calls `RevokeUserAccess` or `BanUsers` directly calls `FireAccessRevoked` in the same transaction too. Deactivation and deletion keep their own events (`DeactivatingEvent`, `DeletingEvent`).
|
||||
- **MCP guard and the `user_me` tool.** Boot registers `classes.MCPUserGuard` as the MCP guard provider `user` in the application's `*pact.MCPGuards` and publishes it as `pact.MCPPersonalTokenResolver`, so the framework's MCP endpoint (built with `-tags summercms_mcp`) can bind tools to routes behind `user.api_token`, `user.scope:<scope>` and `user.permission:<code>` and accept the plugin's personal API tokens (the `golem15.user.api_tokens.prefix`). The guard decides with the routes' own checks: every scope of the route must be granted to the MCP session, and every permission code must be granted by one of the user's groups, as `user.permission` checks it (a user's own permission override does not grant). A tool call runs the route with the user and an in-memory token credential carrying the session's scopes (ID 0, never saved). The plugin's one tool, `me` (exposed as `user_me`), runs `GET /token/me` and answers the signed-in user's payload. A personal token used at the MCP endpoint gets `last_used_at` stamped, and `last_used_ip` when the endpoint passes the client address (`towel.ClientIP`), as the `user.api_token` guard does. Revoking a personal token, saving a user on the Users screen, saving or deleting a group and the link changes fire `pact.MCPSubjectChanged` after they commit, so open MCP sessions re-list their tools or end; revoking a personal token (`DELETE /tokens/{id}`) carries the token's id (`TokenID`), so only the sessions that token opened end. `BackendLinkedEvent` and `BackendUnlinkedEvent`, with `Link.UserID` set, fire on every link and unlink: the confirmation, the Administrators screen, My account and the deletion or deactivation of the frontend user. Deleting an administrator removes the link through the foreign key and fires nothing.
|
||||
- **Sign-in helpers for social login.** `RegisterOptions.PasswordLess`, `FinishLogin`, `RegistrationSettings`, `RegistrationsFromIP`, `RefreshTTL` and `RemoteIP` let a social-login plugin create accounts and finish logins with the user plugin's own rules instead of copies.
|
||||
|
||||
## Usage
|
||||
@@ -109,8 +122,10 @@ All routes are mounted under `/_user/api/v1` with the `throttle:user-api` middle
|
||||
| `POST /avatar/remove` | `controllers.RemoveAvatar` |
|
||||
| `POST /tokens` | `controllers.APITokenStore` (`jwt.auth`) |
|
||||
| `GET /tokens` | `controllers.APITokenIndex` (`jwt.auth`) |
|
||||
| `GET /tokens/scopes` | `controllers.APITokenScopes` (`jwt.auth`) |
|
||||
| `DELETE /tokens/{id}` | `controllers.APITokenDestroy` (`jwt.auth`) |
|
||||
| `GET /backend-link/{code}` | `controllers.BackendLinkShow` |
|
||||
| `GET /backend-link/{code}` | `controllers.BackendLinkShow` (deprecated: the code is in the logged path; use the POST route) |
|
||||
| `POST /backend-link/show` | `controllers.BackendLinkShowPost` |
|
||||
| `POST /backend-link/confirm` | `controllers.BackendLinkConfirm` (`jwt.auth`) |
|
||||
| `GET /token/me` | `controllers.TokenMe` (`user.api_token`, `user.scope:read`) |
|
||||
|
||||
@@ -118,7 +133,7 @@ All routes are mounted under `/_user/api/v1` with the `throttle:user-api` middle
|
||||
|
||||
With `golem15.user.password.public_routes` false the `/login`, `/forgot-password` and `/reset-password` rows are not registered.
|
||||
|
||||
`GET /backend-link/{code}` (`code` is 64 lower-case hex characters) answers `{"data":{"admin":{"login":…,"name":…},"expires_at":"<RFC 3339>"}}` for a usable request and `404 {"error":"not_found"}` for an unknown, used or expired one or when the administrator was deactivated since. `POST /backend-link/confirm` takes `{"code":…}` from the signed-in frontend user and answers `200 {"data":{"backend_user":{"login":…,"name":…}}}`; `409 {"error":"stale_session"}` when the session token was issued before the request (sign in again), `409 {"error":"already_linked"}` when the user or the administrator is already linked, and `404 {"error":"not_found"}` as the show route. `GET /token/me` answers the `{"user": …}` body of `/fetch` to a personal API token with the `read` scope (401 `{"error":true,"message":"Invalid token."}` from the guard, 403 `Missing required scope: read` from the scope check); it is the target of the MCP tool `user_me`.
|
||||
`POST /backend-link/show` takes `{"code":…}` (64 lower-case hex characters) and, like the deprecated `GET /backend-link/{code}`, answers `{"data":{"admin":{"login":…,"name":…},"expires_at":"<RFC 3339>"}}` for a usable request and `404 {"error":"not_found"}` for an unknown, used or expired one or when the administrator was deactivated since. `POST /backend-link/confirm` takes `{"code":…}` from the signed-in frontend user and answers `200 {"data":{"backend_user":{"login":…,"name":…}}}`; `409 {"error":"stale_session"}` when the session's `auth_time` is before the request or the token carries no `auth_time` (sign in again), `409 {"error":"already_linked"}` when the user or the administrator is already linked, and `404 {"error":"not_found"}` as the show route. Both show routes send `Cache-Control: no-store, private`. `GET /token/me` answers the `{"user": …}` body of `/fetch` to a personal API token with the `read` scope (401 `{"error":true,"message":"Invalid token."}` from the guard, 403 `Missing required scope: read` from the scope check); it is the target of the MCP tool `user_me`.
|
||||
|
||||
### Host-mounted OAuth identities
|
||||
|
||||
@@ -198,27 +213,29 @@ Packages:
|
||||
- `FireDeletingEvent(ctx, app, user, tx)` fires `DeletingEvent` (`user.Deleting`) inside the delete transaction.
|
||||
- `FireDeactivatingEvent(ctx, app, user, tx)` fires `DeactivatingEvent` (`user.Deactivating`) inside the deactivation transaction. The admin deactivate bulk action fires it after `DeactivateUsers` (so the user's sessions and API tokens are already revoked) for every selected user that was not deactivated yet; a listener error rolls the action back.
|
||||
- `IssueToken(app, user, r)` mints the session JWT as `/register` and `/login` do.
|
||||
- `BackendLinkShow`, `BackendLinkConfirm` and `TokenMe`, the handlers of the account link and `/token/me` routes.
|
||||
- `BackendLinkShow`, `BackendLinkShowPost`, `BackendLinkConfirm` and `TokenMe`, the handlers of the account link and `/token/me` routes.
|
||||
- `APIArray(ctx, app, user)` builds the user payload, extended by `GetApiArrayEvent` listeners.
|
||||
- `FinishLogin(ctx, app, db, user, ip)` runs the steps `POST /login` takes after authentication, for a caller that authenticated the user another way (a social sign-in): it restores a soft-deleted account and sends the reactivate mail, records `ip` as `last_ip_address` and touches `last_seen` (a failure there is only logged). It checks no password, throttle, activation or ban and fires no event; the caller does those checks.
|
||||
- `RegistrationSettings(app)` returns `allow_registration`, `use_register_throttle`, `activate_mode` and `require_activation` with their defaults (`true`, `true`, `auto`, `true`), and `RegistrationsFromIP(ctx, db, ip)` counts the accounts created from an IP in the last 60 minutes (`/register` refuses at 3 with the throttle on).
|
||||
- `RefreshTTL(app)` is the refresh window, `golem15.user.jwt.refresh_ttl` minutes (default 20160), and `RemoteIP(r)` the host part of `r.RemoteAddr`, with no proxy handling (`/login` and `/register` use `surf.ClientIP` with `http.trusted_proxies`).
|
||||
- `classes`: `JWTSecret`, `GormUsers` (the `bouncer.UserProvider`), `LookupByEmail`, `UserPermissionGrants`, `UserGroupCodes`, `HasGroupCode`, `APITokenPrefix`, `MintAPIToken`, `HashAPIToken` and `RevokeAPIToken`, plus the activation/reset, throttle, mail locale and event helpers. `RegisterEvent` carries `User` and `Payload map[string]any`, a read-only copy of the register input without the password keys. For the admin and for other plugins it also has:
|
||||
- `classes`: `JWTSecret`, `GormUsers` (the `bouncer.UserProvider`), `LookupByEmail`, `UserPermissionGrants`, `UserGroupCodes`, `HasGroupCode`, `APITokenPrefix`, `MintAPIToken`, `MintAPITokenFor`, `HashAPIToken` and `RevokeAPIToken`, the member token scope catalog `APITokenScope`, `APITokenScopeCatalog` (`Scopes`, `Allowed`), `CompileAPITokenScopes`, `APITokenScopesFor` and the test seam `ResetDeclaredAPITokenScopes`, plus the activation/reset, throttle, mail locale and event helpers. `RegisterEvent` carries `User` and `Payload map[string]any`, a read-only copy of the register input without the password keys. For the admin and for other plugins it also has:
|
||||
- `MergedPermissions(ctx, db, userID)`, `HasPermission(merged, code)` and `UserHasPermission(ctx, db, userID, code)`, the frontend permission resolver, and `FrontendPermissionOptions(ctx, db)`, the catalogue by tab and code.
|
||||
- `PermissionManagePrivilegedGroups`, `PrivilegedGroupCodes(cfg)`, `IsPrivilegedCode(codes, code)`, `PrivilegedGroupIDs(ctx, db, codes)` and `IsPrivilegedMember(ctx, db, codes, userID)`, the privileged-group rule.
|
||||
- `ActivateUsers`, `DeactivateUsers`, `RestoreUsers`, `BanUsers`, `UnbanUsers`, `UnsuspendUser`, `ThrottleStates` and `ForceDeleteCleanup`, the user actions the admin runs. Each takes the handle of the caller's transaction.
|
||||
- `RevokeUserAccess(ctx, db, userIDs)` ends every session JWT issued before the current second (it stamps `users.tokens_valid_after`, deactivated rows included) and revokes every personal API token of the users. `DeactivateUsers` and `BanUsers` call it; an application may call it for its own offboarding and after writing a ban directly to `user_throttle`.
|
||||
- `RevokeUserAccess(ctx, db, userIDs)` ends every session JWT issued before the current second (it stamps `users.tokens_valid_after`, deactivated rows included) and revokes every personal API token of the users. `DeactivateUsers` and `BanUsers` call it; an application may call it for its own offboarding and after writing a ban directly to `user_throttle`. Neither fires `AccessRevokedEvent`: such an application calls `FireAccessRevoked` in the same transaction, so OAuth grants are revoked too.
|
||||
- `TouchLastSeen(ctx, db, userID)`.
|
||||
- `OAuthProvider` (`Name`, `Label`) and `OAuthProviderSource` (`EnabledOAuthProviders(ctx)`, `KnownOAuthProviders()`), the seam a social-login plugin publishes with an explicit type argument, `app.Publish[classes.OAuthProviderSource](src)`, so the lookup finds it. `GET /oauth-providers` lists its enabled providers in order; the unlink routes accept its known names.
|
||||
- `EndSession(ctx, app, w, r)` is what `POST /logout` runs: it blacklists every session JWT the request carries (bearer header, `token` and `auth_token` cookies) that verifies, an expired one too while its refresh window is open, until that window closes, writes the forget cookies described under JWT sessions, and returns the subject of the token the guard would read (`""` when there is none or it does not verify); only a failing blacklist write is an error.
|
||||
- `SessionToken(r)`, the session JWT the `jwt` guard reads from a request (bearer header, then the `token` and `auth_token` cookies; `""` when there is none); `SessionTokenCookie(r)`, the name of the session cookie that supplied that token (`""` when the bearer header did or there is none), which `POST /refresh` uses to rewrite the `auth.cookie` cookie; and `SessionCookieNames()`, a copy of that cookie list to pass to `bouncer.NewJWTGuard`, so a handler's own guard reads the same token.
|
||||
- `RequestUser(ctx, app, r)` and `EndRequestSession(ctx, app, w, r)`, for handlers that serve signed-in and anonymous browsers on one route (an OAuth provider's authorize page). `RequestUser` reads and checks the session JWT exactly as the `jwt` guard does (bearer header, then the `token` and `auth_token` cookies, the blacklist, `tokens_valid_after`) and returns the user, or `nil` for an anonymous, invalid, expired or blacklisted request and for a soft-deleted user; only an infrastructure failure is an error. `EndRequestSession` is the best-effort `EndSession`: it revokes and forgets the same way (the forget cookie of `bouncer.LoadCookieConfig`), but a blacklist failure is logged, never returned.
|
||||
- `AvatarURL(ctx, app, user, size)`, the display picture rule of the user payload at any size: the avatar thumbnail (size by size, mode auto) when the user has an avatar and a file bucket is published, the file path when the thumbnail fails, otherwise the gravatar URL. The URL may be protocol-relative or relative. The payload's `avatar_url` comes from it at 128.
|
||||
- `BackendLinks` (`CreateLinkRequest`, `LinkRequestByCode`, `ConfirmLinkRequest`, `SetLink`, `RemoveLink`, `LinkFor`, `LinkOf`, `LinkedBackendUser`, `RegisterBackendLinkListeners`), its errors `ErrLinkRequestNotFound`, `ErrLinkRequestUsed`, `ErrLinkRequestExpired`, `ErrStaleSession`, `ErrAlreadyLinked`, `ErrBackendUserUnavailable` and `ErrFrontendUserUnavailable`, the events `BackendLinkedEvent` / `BackendLinkedEventName` and `BackendUnlinkedEvent` / `BackendUnlinkedEventName`, `BackendLinkRequestTTL(app)`, `DefaultBackendLinkRequestTTL`, `FrontendURL(app)` and `BackendDisplayName(admin)`.
|
||||
- `PermissionManageBackendLinks`, `FrontendPermissionCatalog(ctx, app, db)`, `MCPUserGuard`, `FireSubjectChanged(ctx, app, guard, userID, kind)` and `FireSubjectChangedAfterCommit(ctx, app, tx, guard, userID, kind)` with the guard names `SubjectGuardUser` and `SubjectGuardBackend`.
|
||||
- `OrganisationLogoURL(ctx, app, org, size)`, `OrganisationLogoFields(ctx, app, org)` and `OrganisationLogoSize`, the organisation logo for an application's organisation payloads (see Organisations).
|
||||
- `AvatarURL(ctx, app, user, size)`, the display picture rule of the user payload at any size: the avatar thumbnail (size by size, mode auto) when the user has an avatar and a file bucket is published, the original file's public URL (`attach.File.URL`, which follows `storage.uploads.public_path_prefix` and `public_url`) when the thumbnail fails, otherwise the gravatar URL. The URL may be protocol-relative or relative. The payload's `avatar_url` comes from it at 128.
|
||||
- `BackendLinks` (`CreateLinkRequest`, `LinkRequestByCode`, `ConfirmLinkRequest`, `SetLink`, `RemoveLink`, `LinkFor`, `LinkOf`, `LinkedBackendUser`, `RegisterBackendLinkListeners`), its errors `ErrLinkRequestNotFound`, `ErrLinkRequestUsed`, `ErrLinkRequestExpired`, `ErrStaleSession`, `ErrAlreadyLinked`, `ErrBackendUserUnavailable` and `ErrFrontendUserUnavailable`, the events `BackendLinkedEvent` / `BackendLinkedEventName` and `BackendUnlinkedEvent` / `BackendUnlinkedEventName`, `BackendLinkRequestTTL(app)`, `DefaultBackendLinkRequestTTL`, `FrontendURL(app)`, `BackendLinkPagePath(app)`, `DefaultBackendLinkPagePath`, `BackendLinksFor(app)` (the published service, or one over the app) and `BackendDisplayName(admin)`.
|
||||
- `PermissionManageBackendLinks`, `FrontendPermissionCatalog(ctx, app, db)`, `MCPUserGuard`, `FireSubjectChanged(ctx, app, guard, userID, kind)` and `FireSubjectChangedAfterCommit(ctx, app, tx, guard, userID, kind)` with the guard names `SubjectGuardUser` and `SubjectGuardBackend`, and `FireSubjectEvent(ctx, app, ev)` and `FireSubjectEventAfterCommit(ctx, app, tx, ev)`, which fire a whole `pact.MCPSubjectChanged` (with `TokenID` or `ClientID` to end only one token's or one client's sessions).
|
||||
- `AccessRevokedEvent` / `AccessRevokedEventName` and `FireAccessRevoked(ctx, app, tx, userIDs, before, reason)` (see Access revocation).
|
||||
- `HandleGenerator`, `AssignHandle(ctx, db, user)`, `CreatedEvent` / `CreatedEventName`, `DeletingEvent` / `DeletingEventName`, `DeactivatingEvent` / `DeactivatingEventName`, `AuthorizeUser` and `RegisterUserAuthorizer`.
|
||||
- `middleware`: `APITokenGuard`, `Scope`, `Permission` and `BearerToken`.
|
||||
- `models`: `User`, `Throttle`, `Organisation`, `UserGroup`, `UsersGroup` (the `users_groups` pivot), `APIToken`, `OAuthIdentity`, `FrontendPermission`, `BackendLink`, `BackendLinkRequest` and `PermissionSet`. `PermissionSet` reads a stored permission column tolerantly (NULL, an empty string, `[]`, numeric strings) and writes a JSON object of integers; `ParsePermissionSet` and `PermissionSet.Text` do the same for a column that is a plain string on its model. `UserGroup.UsersCount` is filled only by a query that selects `users_count` (the admin list does). `Organisation.Members` is the relation behind the members manager, `Organisation.AttachRelations` declares its avatar (`OrganisationAvatarField`), and `Slugify` is the slug rule. `User.FilterScope` answers the admin list scope `FilterByGroup`, and `User.AttachRelations` declares the avatar (`AvatarField`). `User.RegisterFillable` is the registration allow-list; `User.Fillable` is the wider mass-assignment backstop of the admin Users form (cabana intersects it with the form's fields) and of trusted application code.
|
||||
- `models`: `User`, `Throttle`, `Organisation`, `UserGroup`, `UsersGroup` (the `users_groups` pivot), `APIToken`, `OAuthIdentity`, `FrontendPermission`, `BackendLink`, `BackendLinkRequest` and `PermissionSet`. `PermissionSet` reads a stored permission column tolerantly (NULL, an empty string, `[]`, numeric strings) and writes a JSON object of integers; `ParsePermissionSet` and `PermissionSet.Text` do the same for a column that is a plain string on its model. `UserGroup.UsersCount` is filled only by a query that selects `users_count` (the admin list does). `Organisation.Members` is the relation behind the members manager, `Organisation.AttachRelations` declares its avatar (`OrganisationAvatarField`) and its logo (`OrganisationLogoField`), and `Slugify` is the slug rule. `User.FilterScope` answers the admin list scope `FilterByGroup`, and `User.AttachRelations` declares the avatar (`AvatarField`). `User.RegisterFillable` is the registration allow-list; `User.Fillable` is the wider mass-assignment backstop of the admin Users form (cabana intersects it with the form's fields) and of trusted application code.
|
||||
- `updates`: the gormigrate migrations, returned by `updates.All()`.
|
||||
- `console`: `RequirePasswordChange`, `BackfillHandles` and `APITokenCommands`.
|
||||
|
||||
@@ -249,7 +266,8 @@ Defaults live in `config/config.yaml` and are merged under `golem15.user.*`. Any
|
||||
| `golem15.user.password.public_routes` | `true` | When `false`, `POST /login`, `POST /forgot-password` and `POST /reset-password` are not registered and answer 404 like any unknown path; `POST /register` (still gated by `allow_registration` and guarded by `golem15.user.turnstile`) and every other route stay. It is read when the routes are built, so a change needs a restart. It takes `true` or `false`, also as a string (`SUMMER_GOLEM15__USER__PASSWORD__PUBLIC_ROUTES=false`); an empty value means `true`; any other value fails boot. |
|
||||
| `golem15.user.api_tokens.prefix` | `usr_` | Prefix for newly minted and accepted shared API-token secrets. Override an existing application's legacy prefix without creating a plugin-specific token table. |
|
||||
| `golem15.user.privileged_groups` | `[admin]` | Codes of the privileged user groups. Membership of such a group, the group's code and its delete, and the email, password and permanent delete of its members need `golem15.users.manage_privileged_groups`. Read on every request. An empty list protects no group. |
|
||||
| `golem15.user.frontend_url` | `""` | The site the plugin's own links point to: the account link page is this URL + `/link-admin?code=<code>`. Empty falls back to `app.url`; a trailing slash is dropped. |
|
||||
| `golem15.user.frontend_url` | `""` | The site the plugin's own links point to: the account link page is this URL + `backend_links.page_path` + `#code=<code>`. Empty falls back to `app.url`; a trailing slash is dropped. |
|
||||
| `golem15.user.backend_links.page_path` | `/link-admin` | The site page that confirms an account link. A value without a leading `/` gets one. |
|
||||
| `golem15.user.backend_links.request_ttl` | `10m` | How long a link request an administrator starts on My account stays usable (a Go duration). A value that does not parse or is not positive fails boot. |
|
||||
| `golem15.user.turnstile` | `""` | Cloudflare Turnstile on `POST /login` and `POST /register` (only `/register` while `golem15.user.password.public_routes` is false). Empty adds nothing; `open` or `closed` appends the framework's `turnstile:open` or `turnstile:closed` middleware to those two routes only (summercms v0.3.0 and later; secret in `turnstile.secret`, token in the `turnstile_token` field). `open` lets requests pass when Cloudflare is unreachable, `closed` refuses them. Any other value fails boot. |
|
||||
|
||||
@@ -267,7 +285,7 @@ Each command uses the database the serve command published or, run from the cons
|
||||
|
||||
## Dependencies
|
||||
|
||||
- The SummerCMS framework v0.4.4, `git.golem15.com/golem15/summercms` (modules `backpack`, `bonfire`, `bouncer`, `diary`, `pact`, `party`, `surf` and others).
|
||||
- The SummerCMS framework v0.5.0, `git.golem15.com/golem15/summercms` (modules `backpack`, `bonfire`, `bouncer`, `diary`, `pact`, `party`, `surf` and others).
|
||||
- The organisation role cleanup of the admin (members manager and user form) uses cabana's `ClearOnChange`, added in SummerCMS v0.4.3.
|
||||
- gormigrate, GORM, golang-jwt and gocloud.dev, as pinned in `go.mod`.
|
||||
- testcontainers-go for the Postgres-backed tests.
|
||||
@@ -305,6 +323,8 @@ go test ./... # full run, starts Postgres with testcontainers (needs D
|
||||
|
||||
`TestAdminOrganisationMembershipClearsRole` checks that the members manager's unlink and link and a Users form save that changes the organisation clear `organisation_role`, that a save keeping the organisation keeps it, and that deleting an organisation clears both columns.
|
||||
|
||||
`TestBackendLinkSmoke` runs the account link end to end: My account offers `link`, the action answers the site URL with a 64-hex code, the show route answers the administrator's login and expiry, a session older than the request gets `stale_session`, a fresh one links (the published resolver answers the administrator), the code is one-shot, a second frontend user gets `already_linked`, an expired code is 404, unlink and deleting the frontend user remove the link, and the subject events fire. `TestBackendLinkAdminSmoke` covers the Administrators screen actions: offered only as they apply and only with `golem15.users.manage_backend_links`, the case-insensitive email match, `linked_by`, `BackendLinkedEvent`, the 422 refusals and the unlink. `TestUserMCPGuardSmoke` covers the `user` guard provider (requirements, the scope and group-permission checks, the dispatch credential, personal token resolution), `GET /token/me` and the revoke, group and user subject events. `TestFrontendPermissionCatalogSmoke` boots a test plugin that declares frontend permission codes and checks both editors' options. All four need Docker.
|
||||
`TestBackendLinkSmoke` runs the account link end to end: My account offers `link`, the action answers the site URL with a 64-hex code, the show route answers the administrator's login and expiry, a session older than the request gets `stale_session`, a fresh one links (the published resolver answers the administrator), the code is one-shot, a second frontend user gets `already_linked`, an expired code is 404, unlink and deleting the frontend user remove the link, and the subject events fire. `TestBackendLinkAuthTimeSmoke` checks the `auth_time` proof: a session signed in before the request and refreshed after it gets `stale_session`, a sign-in after the request links, `POST /backend-link/show` answers for the code in the body, and My account's URL carries the code in the fragment. `TestBackendLinkAdminSmoke` covers the Administrators screen actions: offered only as they apply and only with `golem15.users.manage_backend_links`, the case-insensitive email match, `linked_by`, `BackendLinkedEvent`, the 422 refusals and the unlink. `TestUserMCPGuardSmoke` covers the `user` guard provider (requirements, the scope and group-permission checks, the dispatch credential, personal token resolution), `GET /token/me` and the revoke, group and user subject events. `TestFrontendPermissionCatalogSmoke` boots a test plugin that declares frontend permission codes and checks both editors' options. `TestMemberTokenScopesSmoke` checks the member token scope catalog (duplicate, built-in and bad names fail) and, with Docker, minting, the scope check, the list, `GET /tokens/scopes` and a second application refusing the scope. The others need Docker.
|
||||
|
||||
`TestMemberTokenScopesBoot` (no Docker) checks that the scope Boot step fails for a name two plugins declare (naming both), for a redeclared `read`, `write` or `ai`, for a bad name, an empty label and a missing phrase key. With Docker: `TestMemberTokenScopes` walks the member token scope acceptance list item by item (mint and `middleware.Scope`, the 403 message, the 422 for an undeclared scope, the list, discovery in en and pl, the per-application catalog and the legacy fallback); `TestBackendLinkAuthTime` checks the link proof against login, request, refresh and re-login orders, a token without `auth_time` and another user's session token; `TestBackendLinkShowPost` checks that `POST /backend-link/show` answers like the GET route with `Cache-Control: no-store, private`, the fragment URL and `backend_links.page_path`; `TestAccessRevocation` checks `AccessRevokedEvent` from the ban action, the password reset, the password change and an administrator setting a password (ids, `Before`, reason, the transaction, the subject event after commit, the rollback on a failing listener) and that a banned user loses the backend link until unbanned; `TestUserMCPGuardClientIP` checks `last_used_ip` on the MCP personal-token path; `TestAPITokenRevokeEvent` checks the token-specific revoked event of `DELETE /tokens/{id}`; `TestOrganisationLogo` checks the logo field, the upload, `OrganisationLogoFields` with and without a logo, the URL fallback when the thumbnail fails, and that deleting an organisation removes its avatar and logo attachments, the rows and, once the delete commits, the blobs and thumbnails.
|
||||
|
||||
The admin tests (`TestAdmin*`) boot the plugin with the admin API mounted on a database of their own and sign in backend administrators with a chosen permission set; the helpers are in `admin_harness_test.go`.
|
||||
|
||||
234
access_revocation_test.go
Normal file
234
access_revocation_test.go
Normal file
@@ -0,0 +1,234 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// revokedSeen is one AccessRevokedEvent as a listener saw it, with what was
|
||||
// already visible at that moment.
|
||||
type revokedSeen struct {
|
||||
ev classes.AccessRevokedEvent
|
||||
// stored is tokens_valid_after of the first user read through ev.Tx.
|
||||
stored *time.Time
|
||||
// subjectEarly reports whether a revoked subject event for the first
|
||||
// user had already fired (it must wait for the commit).
|
||||
subjectEarly bool
|
||||
}
|
||||
|
||||
// revocationProbe records every AccessRevokedEvent of an app and can make
|
||||
// the listener fail.
|
||||
type revocationProbe struct {
|
||||
mu sync.Mutex
|
||||
seen []revokedSeen
|
||||
fail atomic.Bool
|
||||
}
|
||||
|
||||
func (p *revocationProbe) take() []revokedSeen {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
out := p.seen
|
||||
p.seen = nil
|
||||
return out
|
||||
}
|
||||
|
||||
func listenRevocations(env *adminEnv, spy *subjectSpy) *revocationProbe {
|
||||
probe := &revocationProbe{}
|
||||
env.app.Events.Listen("test.access_revoked", func(ctx context.Context, ev *classes.AccessRevokedEvent) error {
|
||||
if probe.fail.Load() {
|
||||
return errors.New("listener refused")
|
||||
}
|
||||
seen := revokedSeen{ev: *ev}
|
||||
if ev.Tx != nil && len(ev.UserIDs) > 0 {
|
||||
var row struct{ TokensValidAfter *time.Time }
|
||||
if err := ev.Tx.WithContext(ctx).Raw(`SELECT tokens_valid_after FROM users WHERE id = ?`, ev.UserIDs[0]).Scan(&row).Error; err == nil {
|
||||
seen.stored = row.TokensValidAfter
|
||||
}
|
||||
seen.subjectEarly = spy.has(classes.SubjectGuardUser, ev.UserIDs[0], pact.MCPSubjectRevoked)
|
||||
}
|
||||
probe.mu.Lock()
|
||||
probe.seen = append(probe.seen, seen)
|
||||
probe.mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
return probe
|
||||
}
|
||||
|
||||
// one asserts exactly one event naming id for reason, fired in a
|
||||
// transaction before the user's revoked subject event.
|
||||
func one(t *testing.T, probe *revocationProbe, spy *subjectSpy, id uint, reason string) revokedSeen {
|
||||
t.Helper()
|
||||
seen := probe.take()
|
||||
if len(seen) != 1 {
|
||||
t.Fatalf("%s fired %d access-revoked events, want 1: %+v", reason, len(seen), seen)
|
||||
}
|
||||
got := seen[0]
|
||||
if got.ev.Reason != reason || len(got.ev.UserIDs) != 1 || got.ev.UserIDs[0] != id || got.ev.Tx == nil {
|
||||
t.Fatalf("%s event = %+v, want user %d in a transaction", reason, got.ev, id)
|
||||
}
|
||||
if got.subjectEarly {
|
||||
t.Fatalf("%s: the revoked subject event fired before the commit", reason)
|
||||
}
|
||||
if !spy.has(classes.SubjectGuardUser, id, pact.MCPSubjectRevoked) {
|
||||
t.Fatalf("%s: no revoked subject event for user %d after the commit", reason, id)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
// wholeSecondsUntruncated checks the stored cutoff has whole seconds and
|
||||
// Before is the untruncated instant of the same second.
|
||||
func wholeSecondsUntruncated(t *testing.T, env *adminEnv, id uint, before time.Time) {
|
||||
t.Helper()
|
||||
stored := env.reload(t, id).TokensValidAfter
|
||||
if stored == nil || stored.Nanosecond() != 0 {
|
||||
t.Fatalf("stored tokens_valid_after = %v, want whole seconds", stored)
|
||||
}
|
||||
if before.Before(*stored) || !before.Truncate(time.Second).Equal(stored.Truncate(time.Second)) {
|
||||
t.Fatalf("Before %s is not the untruncated instant of the stored cutoff %s", before, stored)
|
||||
}
|
||||
if before.Nanosecond() == 0 {
|
||||
t.Logf("the clock answered a whole second (%s); the sub-second part is not observable this run", before)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccessRevocation pins plan 08's revocation chain on the user side
|
||||
// (C-CR-01, RC-CR-01, P-35): the ban bulk action, ResetPassword,
|
||||
// ChangePassword and an administrator setting a password each fire one
|
||||
// AccessRevokedEvent in the write's transaction with the right ids, Before
|
||||
// and Reason (for ChangePassword the instant of the request, never the
|
||||
// calling session's older iat, while the session itself survives), then one
|
||||
// revoked subject event per user after the commit; the ban fires only for
|
||||
// newly banned users; a failing listener rolls a password reset back; and
|
||||
// a banned linked user loses the backend link until unbanned. Postgres
|
||||
// only: skipped under -short.
|
||||
func TestAccessRevocation(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres")
|
||||
}
|
||||
env := newAdminEnv(t)
|
||||
spy := env.spySubjects()
|
||||
probe := listenRevocations(env, spy)
|
||||
admin := env.superAdmin(t)
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("the ban bulk action fires for newly banned users only", func(t *testing.T) {
|
||||
already := env.seedUser(t, "rv-already", nil)
|
||||
env.seedThrottle(t, already, "203.0.113.20", true, nil)
|
||||
fresh := env.seedUser(t, "rv-ban", nil)
|
||||
probe.take()
|
||||
spy.reset()
|
||||
started := time.Now()
|
||||
env.expect(t, http.StatusOK, http.MethodPost, adminAPI(adminUsersPath+"/bulk/ban"), admin, map[string]any{"ids": []uint{already.ID, fresh.ID}})
|
||||
got := one(t, probe, spy, fresh.ID, classes.AccessRevokedBan)
|
||||
if got.ev.Before.Before(started) || got.ev.Before.After(time.Now()) {
|
||||
t.Fatalf("ban Before %s outside the request", got.ev.Before)
|
||||
}
|
||||
if spy.has(classes.SubjectGuardUser, already.ID, pact.MCPSubjectRevoked) {
|
||||
t.Fatal("the already banned user got a revoked event")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ResetPassword fires with the untruncated instant", func(t *testing.T) {
|
||||
user := env.seedUser(t, "rv-reset", nil)
|
||||
code, err := classes.IssueResetCode(ctx, env.gdb, user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
probe.take()
|
||||
spy.reset()
|
||||
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
|
||||
env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/reset-password", "", map[string]string{"code": packed, "password": "rv-new-password", "password_confirmation": "rv-new-password"})
|
||||
got := one(t, probe, spy, user.ID, classes.AccessRevokedPasswordReset)
|
||||
if got.stored == nil {
|
||||
t.Fatal("the listener did not see the new cutoff inside the reset's transaction")
|
||||
}
|
||||
wholeSecondsUntruncated(t, env, user.ID, got.ev.Before)
|
||||
})
|
||||
|
||||
t.Run("ChangePassword revokes as of the request and keeps the calling session", func(t *testing.T) {
|
||||
user := env.seedUser(t, "rv-change", func(u *models.User) { u.HasSelfSetPassword = true })
|
||||
// A session last refreshed twenty minutes ago: an OAuth grant its
|
||||
// client rotated since then is newer than the session, and must
|
||||
// still end (RC-CR-01).
|
||||
iat := time.Now().Add(-20 * time.Minute)
|
||||
session := craftToken(t, strconv.FormatUint(uint64(user.ID), 10), "rv-change-"+strconv.FormatInt(time.Now().UnixNano(), 10), iat, time.Now().Add(time.Hour))
|
||||
probe.take()
|
||||
spy.reset()
|
||||
started := time.Now()
|
||||
env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/change-password", session, map[string]string{"current_password": "correct-horse", "password": "rv-changed-password", "password_confirmation": "rv-changed-password"})
|
||||
got := one(t, probe, spy, user.ID, classes.AccessRevokedPasswordChanged)
|
||||
if got.ev.Before.Before(started) || got.ev.Before.After(time.Now()) {
|
||||
t.Fatalf("Before %s is not the instant of the request (started %s): grants refreshed after the session's iat %s would survive", got.ev.Before, started, iat)
|
||||
}
|
||||
stored := env.reload(t, user.ID).TokensValidAfter
|
||||
if want := time.Unix(iat.Unix(), 0).Add(-time.Second); stored == nil || !stored.Equal(want) {
|
||||
t.Fatalf("stored cutoff %v, want the session's iat second minus one (%s)", stored, want)
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/fetch", session, nil)
|
||||
})
|
||||
|
||||
t.Run("an administrator setting a password fires with the untruncated instant", func(t *testing.T) {
|
||||
user := env.seedUser(t, "rv-admin-set", nil)
|
||||
probe.take()
|
||||
spy.reset()
|
||||
const set = "rv-admin-password"
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), admin, map[string]any{"name": user.Name, "email": user.Email, "password": set, "password_confirmation": set})
|
||||
got := one(t, probe, spy, user.ID, classes.AccessRevokedPasswordSetByAdmin)
|
||||
wholeSecondsUntruncated(t, env, user.ID, got.ev.Before)
|
||||
})
|
||||
|
||||
t.Run("a failing listener rolls the password reset back", func(t *testing.T) {
|
||||
user := env.seedUser(t, "rv-rollback", nil)
|
||||
code, err := classes.IssueResetCode(ctx, env.gdb, user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spy.reset()
|
||||
probe.fail.Store(true)
|
||||
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
|
||||
rec := env.call(t, http.MethodPost, "/_user/api/v1/reset-password", "", map[string]string{"code": packed, "password": "rv-never-set", "password_confirmation": "rv-never-set"})
|
||||
probe.fail.Store(false)
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("reset with a failing listener = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if status, _ := env.userLogin(t, user.Email, "correct-horse"); status != http.StatusOK {
|
||||
t.Fatalf("the old password stopped working (%d): the reset was not rolled back", status)
|
||||
}
|
||||
if status, _ := env.userLogin(t, user.Email, "rv-never-set"); status == http.StatusOK {
|
||||
t.Fatal("the new password works: the reset was not rolled back")
|
||||
}
|
||||
if spy.has(classes.SubjectGuardUser, user.ID, pact.MCPSubjectRevoked) {
|
||||
t.Fatal("a rolled-back reset fired a revoked subject event")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a banned linked user loses the backend link until unbanned", func(t *testing.T) {
|
||||
user := env.seedUser(t, "rv-linked", nil)
|
||||
code := env.startLink(t, env.admin(t))
|
||||
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusOK {
|
||||
t.Fatalf("link = %d %s", status, body)
|
||||
}
|
||||
links, _ := env.app.Lookup[*classes.BackendLinks]()
|
||||
if _, ok, err := links.LinkedBackendUser(ctx, user.ID); err != nil || !ok {
|
||||
t.Fatalf("linked before the ban = %v, %v", ok, err)
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodPost, adminAPI(adminUsersPath+"/bulk/ban"), admin, map[string]any{"ids": []uint{user.ID}})
|
||||
if _, ok, err := links.LinkedBackendUser(ctx, user.ID); err != nil || ok {
|
||||
t.Fatalf("linked while banned = %v, %v", ok, err)
|
||||
}
|
||||
env.expect(t, http.StatusOK, http.MethodPost, adminAPI(adminUsersPath+"/bulk/unban"), admin, map[string]any{"ids": []uint{user.ID}})
|
||||
if _, ok, err := links.LinkedBackendUser(ctx, user.ID); err != nil || !ok {
|
||||
t.Fatalf("linked after the unban = %v, %v", ok, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -55,12 +55,7 @@ func (p *Plugin) AccountContributions() []pact.AccountContribution {
|
||||
|
||||
// backendLinks returns the published link service, or one over the app.
|
||||
func (p *Plugin) backendLinks() *classes.BackendLinks {
|
||||
if p.app != nil {
|
||||
if links, ok := p.app.Lookup[*classes.BackendLinks](); ok && links != nil {
|
||||
return links
|
||||
}
|
||||
}
|
||||
return &classes.BackendLinks{App: p.app}
|
||||
return classes.BackendLinksFor(p.app)
|
||||
}
|
||||
|
||||
// frontendAccountStatus answers "Linked to <email>" or "Not linked" in the
|
||||
@@ -110,8 +105,11 @@ func (p *Plugin) frontendEmail(ctx context.Context, userID uint) (string, error)
|
||||
}
|
||||
|
||||
// startFrontendLink creates a link request for the signed-in administrator
|
||||
// and answers the site page that confirms it:
|
||||
// golem15.user.frontend_url (else app.url) + /link-admin?code=<code>.
|
||||
// and answers the site page that confirms it: golem15.user.frontend_url
|
||||
// (else app.url), then golem15.user.backend_links.page_path (default
|
||||
// /link-admin), then the code in the URL fragment. Browsers never send a
|
||||
// fragment to a server, so the code stays out of access logs; the page reads
|
||||
// it in the browser and posts it to /_user/api/v1/backend-link/show.
|
||||
func (p *Plugin) startFrontendLink(ctx context.Context, in pact.AccountActionInput) (pact.AccountActionResult, error) {
|
||||
plain, _, err := p.backendLinks().CreateLinkRequest(ctx, in.AdminID)
|
||||
if err != nil {
|
||||
@@ -119,7 +117,7 @@ func (p *Plugin) startFrontendLink(ctx context.Context, in pact.AccountActionInp
|
||||
}
|
||||
return pact.AccountActionResult{
|
||||
Message: backendLinkLang + "link_started",
|
||||
URL: classes.FrontendURL(p.app) + "/link-admin?code=" + plain,
|
||||
URL: classes.FrontendURL(p.app) + classes.BackendLinkPagePath(p.app) + "#code=" + plain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -156,13 +156,17 @@ func TestAdminOrganisations(t *testing.T) {
|
||||
if field.Mode != "image" || field.ImageWidth != 120 || field.ImageHeight != 120 {
|
||||
t.Fatalf("avatar field = %+v", field)
|
||||
}
|
||||
case "logo":
|
||||
if field.Mode != "image" || field.ImageWidth != 240 || field.ImageHeight != 120 {
|
||||
t.Fatalf("logo field = %+v", field)
|
||||
}
|
||||
case "members":
|
||||
if field.Context != "update" || field.Tab != "Members" {
|
||||
t.Fatalf("members field = %+v", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
if want := []string{"name:text", "slug:text", "description:textarea", "avatar:fileupload", "members:relation-manager"}; !reflect.DeepEqual(names, want) {
|
||||
if want := []string{"name:text", "slug:text", "description:textarea", "avatar:fileupload", "logo:fileupload", "members:relation-manager"}; !reflect.DeepEqual(names, want) {
|
||||
t.Fatalf("form fields = %v, want %v", names, want)
|
||||
}
|
||||
if len(form.Preview) != 0 && string(form.Preview) != "null" {
|
||||
|
||||
37
api_token_events_test.go
Normal file
37
api_token_events_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// TestAPITokenRevokeEvent pins plan 08's token-specific MCP revocation
|
||||
// (C-IN-02, user side): DELETE /tokens/{id} fires exactly one revoked
|
||||
// subject event for the user carrying that TokenID, so only the sessions of
|
||||
// that token end. Postgres only: skipped under -short.
|
||||
func TestAPITokenRevokeEvent(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres")
|
||||
}
|
||||
env := newAdminEnv(t)
|
||||
spy := env.spySubjects()
|
||||
user := env.seedUser(t, "token-revoke", nil)
|
||||
_, kept := env.mintUserToken(t, user, "read")
|
||||
_, gone := env.mintUserToken(t, user, "read")
|
||||
spy.reset()
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, "/_user/api/v1/tokens/"+strconv.FormatUint(uint64(gone.ID), 10), freshUserToken(t, user), nil)
|
||||
spy.mu.Lock()
|
||||
events := append([]pact.MCPSubjectChanged(nil), spy.events...)
|
||||
spy.mu.Unlock()
|
||||
want := pact.MCPSubjectChanged{Guard: classes.SubjectGuardUser, UserID: user.ID, Kind: pact.MCPSubjectRevoked, TokenID: gone.ID}
|
||||
if len(events) != 1 || events[0] != want {
|
||||
t.Fatalf("events = %+v, want exactly %+v", events, want)
|
||||
}
|
||||
if spy.hasEvent(pact.MCPSubjectChanged{Guard: classes.SubjectGuardUser, UserID: user.ID, Kind: pact.MCPSubjectRevoked, TokenID: kept.ID}) {
|
||||
t.Fatal("the kept token was revoked too")
|
||||
}
|
||||
}
|
||||
@@ -104,8 +104,13 @@ func TestAvatarURL(t *testing.T) {
|
||||
if err := attach.Publish(failing, closed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := classes.AvatarURL(ctx, failing, withFile, 128); err != nil || got != "/"+attach.BlobKey(row.DiskName) {
|
||||
t.Fatalf("failing thumbnail = %q %v, want /%s", got, err, attach.BlobKey(row.DiskName))
|
||||
// The file's public URL follows storage.uploads.public_path_prefix
|
||||
// (RC-IN-03), never a bare /<key>.
|
||||
if want := attach.PublicURL(attach.BlobKey(row.DiskName)); want == "/"+attach.BlobKey(row.DiskName) {
|
||||
t.Fatalf("the public path prefix is empty (%q): the fallback is not observable", attach.PublicPathPrefix())
|
||||
}
|
||||
if got, err := classes.AvatarURL(ctx, failing, withFile, 128); err != nil || got != attach.PublicURL(attach.BlobKey(row.DiskName)) {
|
||||
t.Fatalf("failing thumbnail = %q %v, want %s", got, err, attach.PublicURL(attach.BlobKey(row.DiskName)))
|
||||
}
|
||||
|
||||
// A failing lookup is the only error.
|
||||
|
||||
103
backend_link_auth_time_smoke_test.go
Normal file
103
backend_link_auth_time_smoke_test.go
Normal file
@@ -0,0 +1,103 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// craftSignInToken is craftToken with an auth_time claim: a session token
|
||||
// issued at iat for a sign-in at authTime.
|
||||
func craftSignInToken(t *testing.T, sub, jti string, iat, authTime time.Time) string {
|
||||
t.Helper()
|
||||
claims := jwt.MapClaims{
|
||||
"sub": sub,
|
||||
"iss": "http://example.com/_user/api/v1/login",
|
||||
"iat": iat.Unix(),
|
||||
"nbf": iat.Unix(),
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
"jti": jti,
|
||||
"prv": prvHash,
|
||||
bouncer.ClaimAuthTime: authTime.Unix(),
|
||||
}
|
||||
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(sessionSecret))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return signed
|
||||
}
|
||||
|
||||
// TestBackendLinkAuthTimeSmoke: the account link proof is the sign-in time.
|
||||
// A session signed in before the request and refreshed after it is refused
|
||||
// with stale_session, a sign-in after the request confirms, POST show
|
||||
// answers the administrator for the code in the body, and My account's URL
|
||||
// carries the code in the fragment, never in a query string. Skips under
|
||||
// -short.
|
||||
func TestBackendLinkAuthTimeSmoke(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
user := env.seedUser(t, "auth-time", nil)
|
||||
sub := strconv.FormatUint(uint64(user.ID), 10)
|
||||
admin := env.admin(t)
|
||||
login := env.adminLogin(t, adminID(t, admin))
|
||||
|
||||
// 1. The user signed in an hour ago.
|
||||
old := craftSignInToken(t, sub, "auth-time-old-"+adminStamp(), time.Now().Add(-time.Hour), time.Now().Add(-time.Hour))
|
||||
|
||||
// 2. The administrator starts a link; 6. its URL holds the code in the
|
||||
// fragment only.
|
||||
var started struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/link"), admin, map[string]any{}), &started)
|
||||
if !strings.Contains(started.URL, "/link-admin#code=") || strings.Contains(started.URL, "?") {
|
||||
t.Fatalf("link URL = %q", started.URL)
|
||||
}
|
||||
m := linkURL.FindStringSubmatch(started.URL)
|
||||
if m == nil {
|
||||
t.Fatalf("link URL = %q", started.URL)
|
||||
}
|
||||
code := m[1]
|
||||
|
||||
// 5. POST show answers the administrator for the code in the body.
|
||||
rec := env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/backend-link/show", "", map[string]string{"code": code})
|
||||
var shown struct {
|
||||
Data struct {
|
||||
Admin map[string]any `json:"admin"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &shown); err != nil || shown.Data.Admin["login"] != login {
|
||||
t.Fatalf("POST show = %s (%v)", rec.Body.String(), err)
|
||||
}
|
||||
if got := rec.Header().Get("Cache-Control"); got != "no-store, private" {
|
||||
t.Fatalf("POST show Cache-Control = %q", got)
|
||||
}
|
||||
env.expect(t, http.StatusNotFound, http.MethodPost, "/_user/api/v1/backend-link/show", "", map[string]string{"code": strings.Repeat("0", 64)})
|
||||
|
||||
// 3. Refreshing the old session after the request does not make it a
|
||||
// fresh sign-in.
|
||||
rec = env.refresh(t, old)
|
||||
var refreshed struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &refreshed); rec.Code != http.StatusOK || err != nil || refreshed.Token == "" {
|
||||
t.Fatalf("refresh = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if status, body := env.confirmLink(t, refreshed.Token, code); status != http.StatusConflict || !strings.Contains(body, `"stale_session"`) {
|
||||
t.Fatalf("refreshed confirm = %d %s", status, body)
|
||||
}
|
||||
|
||||
// 4. A sign-in after the request confirms.
|
||||
status, fresh := env.userLogin(t, user.Email, "correct-horse")
|
||||
if status != http.StatusOK || fresh == "" {
|
||||
t.Fatalf("login = %d", status)
|
||||
}
|
||||
if status, body := env.confirmLink(t, fresh, code); status != http.StatusOK || !strings.Contains(body, `"login":"`+login+`"`) {
|
||||
t.Fatalf("fresh confirm = %d %s", status, body)
|
||||
}
|
||||
}
|
||||
114
backend_link_auth_time_test.go
Normal file
114
backend_link_auth_time_test.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
)
|
||||
|
||||
// TestBackendLinkAuthTime pins the account link proof of plan 08 (C-CR-02,
|
||||
// P-34): confirming a link needs a sign-in at or after the request, read
|
||||
// from the session's auth_time, which refresh copies and never renews. A
|
||||
// session signed in before the request stays stale through a refresh, a
|
||||
// sign-in after the request confirms (also after a refresh), a token
|
||||
// without auth_time is stale, and a session token of another user than the
|
||||
// authenticated one is 401. Postgres only: skipped under -short.
|
||||
func TestBackendLinkAuthTime(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres")
|
||||
}
|
||||
env := newAdminEnv(t)
|
||||
login := func(t *testing.T, user *models.User) string {
|
||||
t.Helper()
|
||||
status, token := env.userLogin(t, user.Email, "correct-horse")
|
||||
if status != http.StatusOK || token == "" {
|
||||
t.Fatalf("login = %d", status)
|
||||
}
|
||||
return token
|
||||
}
|
||||
refresh := func(t *testing.T, token string) string {
|
||||
t.Helper()
|
||||
rec := env.refresh(t, token)
|
||||
var body struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); rec.Code != http.StatusOK || err != nil || body.Token == "" {
|
||||
t.Fatalf("refresh = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
return body.Token
|
||||
}
|
||||
// signInEarlier waits past the second of the sign-in, so a request
|
||||
// created next is strictly later (auth_time has whole seconds).
|
||||
signInEarlier := func() { time.Sleep(1100 * time.Millisecond) }
|
||||
expect := func(t *testing.T, token, code string, status int, contains string) {
|
||||
t.Helper()
|
||||
got, body := env.confirmLink(t, token, code)
|
||||
if got != status || !strings.Contains(body, contains) {
|
||||
t.Fatalf("confirm = %d %s, want %d with %q", got, body, status, contains)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("login, request, refresh, confirm is stale", func(t *testing.T) {
|
||||
user := env.seedUser(t, "at-refresh", nil)
|
||||
session := login(t, user)
|
||||
signInEarlier()
|
||||
code := env.startLink(t, env.admin(t))
|
||||
expect(t, refresh(t, session), code, http.StatusConflict, `"stale_session"`)
|
||||
})
|
||||
|
||||
t.Run("request, login, confirm links", func(t *testing.T) {
|
||||
user := env.seedUser(t, "at-after", nil)
|
||||
code := env.startLink(t, env.admin(t))
|
||||
expect(t, login(t, user), code, http.StatusOK, `"backend_user"`)
|
||||
})
|
||||
|
||||
t.Run("login, request, login again, confirm links", func(t *testing.T) {
|
||||
user := env.seedUser(t, "at-again", nil)
|
||||
first := login(t, user)
|
||||
signInEarlier()
|
||||
code := env.startLink(t, env.admin(t))
|
||||
expect(t, first, code, http.StatusConflict, `"stale_session"`)
|
||||
expect(t, login(t, user), code, http.StatusOK, `"backend_user"`)
|
||||
})
|
||||
|
||||
t.Run("a hand-made token without auth_time is stale", func(t *testing.T) {
|
||||
user := env.seedUser(t, "at-legacy", nil)
|
||||
code := env.startLink(t, env.admin(t))
|
||||
legacy := craftToken(t, strconv.FormatUint(uint64(user.ID), 10), "at-legacy-"+adminStamp(), time.Now(), time.Now().Add(time.Hour))
|
||||
expect(t, legacy, code, http.StatusConflict, `"stale_session"`)
|
||||
})
|
||||
|
||||
t.Run("a refreshed session of a post-request sign-in keeps working", func(t *testing.T) {
|
||||
user := env.seedUser(t, "at-carried", nil)
|
||||
code := env.startLink(t, env.admin(t))
|
||||
session := login(t, user)
|
||||
expect(t, refresh(t, refresh(t, session)), code, http.StatusOK, `"backend_user"`)
|
||||
})
|
||||
|
||||
t.Run("another user's session token is 401", func(t *testing.T) {
|
||||
user := env.seedUser(t, "at-owner", nil)
|
||||
other := env.seedUser(t, "at-other", nil)
|
||||
code := env.startLink(t, env.admin(t))
|
||||
// jwt.auth authenticated user, but the session token the handler
|
||||
// reads again for its sign-in time belongs to other.
|
||||
req := httptest.NewRequest(http.MethodPost, "/_user/api/v1/backend-link/confirm", strings.NewReader(`{"code":"`+code+`"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+login(t, other))
|
||||
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: user.ID}))
|
||||
rec := httptest.NewRecorder()
|
||||
controllers.BackendLinkConfirm(env.app)(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("mismatched session token = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// The code is still usable by its rightful user.
|
||||
expect(t, login(t, user), code, http.StatusOK, `"backend_user"`)
|
||||
})
|
||||
}
|
||||
141
backend_link_show_test.go
Normal file
141
backend_link_show_test.go
Normal file
@@ -0,0 +1,141 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
)
|
||||
|
||||
// TestBackendLinkShowPost pins plan 08's link code transport (C-WR-01,
|
||||
// C-IN-06): POST /backend-link/show answers exactly like the GET route (the
|
||||
// data for a live code, 404 for an unknown, a used or an expired one), both
|
||||
// with Cache-Control no-store, private; a code in the query string of the
|
||||
// show or confirm POST is ignored (RC-IN-01); My account answers the link as
|
||||
// <frontend_url>/link-admin#code=<64 hex> with no query string;
|
||||
// golem15.user.backend_links.page_path changes the path, and a value
|
||||
// without a leading slash gets one. Postgres only: skipped under
|
||||
// -short.
|
||||
func TestBackendLinkShowPost(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres")
|
||||
}
|
||||
env := newAdminEnv(t)
|
||||
show := func(t *testing.T, code string) (get, post *struct {
|
||||
status int
|
||||
body string
|
||||
cache string
|
||||
}) {
|
||||
t.Helper()
|
||||
g := env.call(t, http.MethodGet, "/_user/api/v1/backend-link/"+code, "", nil)
|
||||
p := env.call(t, http.MethodPost, "/_user/api/v1/backend-link/show", "", map[string]string{"code": code})
|
||||
return &struct {
|
||||
status int
|
||||
body string
|
||||
cache string
|
||||
}{g.Code, g.Body.String(), g.Header().Get("Cache-Control")}, &struct {
|
||||
status int
|
||||
body string
|
||||
cache string
|
||||
}{p.Code, p.Body.String(), p.Header().Get("Cache-Control")}
|
||||
}
|
||||
same := func(t *testing.T, code string, status int) {
|
||||
t.Helper()
|
||||
get, post := show(t, code)
|
||||
if get.status != status || post.status != status {
|
||||
t.Fatalf("show %s: GET %d, POST %d, want %d", code[:8], get.status, post.status, status)
|
||||
}
|
||||
if !bytes.Equal([]byte(get.body), []byte(post.body)) {
|
||||
t.Fatalf("POST show differs from GET:\nGET %s\nPOST %s", get.body, post.body)
|
||||
}
|
||||
if get.cache != "no-store, private" || post.cache != "no-store, private" {
|
||||
t.Fatalf("Cache-Control: GET %q, POST %q", get.cache, post.cache)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("POST show answers like GET", func(t *testing.T) {
|
||||
token := env.admin(t)
|
||||
live := env.startLink(t, token)
|
||||
same(t, live, http.StatusOK)
|
||||
if _, post := show(t, live); !strings.Contains(post.body, `"admin"`) || !strings.Contains(post.body, `"expires_at"`) {
|
||||
t.Fatalf("POST show data = %s", post.body)
|
||||
}
|
||||
same(t, strings.Repeat("a", 64), http.StatusNotFound)
|
||||
|
||||
used := env.startLink(t, env.admin(t))
|
||||
if status, body := env.confirmLink(t, freshUserToken(t, env.seedUser(t, "show-used", nil)), used); status != http.StatusOK {
|
||||
t.Fatalf("confirm = %d %s", status, body)
|
||||
}
|
||||
same(t, used, http.StatusNotFound)
|
||||
|
||||
expiring := env.admin(t)
|
||||
expired := env.startLink(t, expiring)
|
||||
if err := env.gdb.Model(&models.BackendLinkRequest{}).Where("backend_user_id = ?", adminID(t, expiring)).
|
||||
Update("expires_at", time.Now().Add(-time.Minute)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
same(t, expired, http.StatusNotFound)
|
||||
})
|
||||
|
||||
t.Run("a code in the query string is ignored", func(t *testing.T) {
|
||||
live := env.startLink(t, env.admin(t))
|
||||
path := "/_user/api/v1/backend-link/show?code=" + live
|
||||
for name, send := range map[string]func() *httptest.ResponseRecorder{
|
||||
"no body": func() *httptest.ResponseRecorder { return env.send(t, http.MethodPost, path, "", nil, "", nil) },
|
||||
"a JSON body without a code": func() *httptest.ResponseRecorder { return env.call(t, http.MethodPost, path, "", map[string]string{}) },
|
||||
"a form body without a code": func() *httptest.ResponseRecorder {
|
||||
return env.send(t, http.MethodPost, path, "", []byte("other=1"), "application/x-www-form-urlencoded", nil)
|
||||
},
|
||||
} {
|
||||
if got := send(); got.Code != http.StatusNotFound {
|
||||
t.Fatalf("show with ?code= and %s = %d %s, want 404", name, got.Code, got.Body.String())
|
||||
}
|
||||
}
|
||||
user := env.seedUser(t, "show-query", nil)
|
||||
rec := env.send(t, http.MethodPost, "/_user/api/v1/backend-link/confirm?code="+live, freshUserToken(t, user), []byte("other=1"), "application/x-www-form-urlencoded", nil)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("confirm with ?code= = %d %s, want 404", rec.Code, rec.Body.String())
|
||||
}
|
||||
// A form body still carries the code, and the query string never did.
|
||||
form := env.send(t, http.MethodPost, "/_user/api/v1/backend-link/show", "", []byte("code="+live), "application/x-www-form-urlencoded", nil)
|
||||
if form.Code != http.StatusOK {
|
||||
t.Fatalf("show with the code in a form body = %d %s", form.Code, form.Body.String())
|
||||
}
|
||||
if status, body := env.confirmLink(t, freshUserToken(t, user), live); status != http.StatusOK {
|
||||
t.Fatalf("confirm with the code in the body after the refusals = %d %s", status, body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the My account URL carries the code in the fragment only", func(t *testing.T) {
|
||||
var out struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
adminInto(t, env.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/link"), env.admin(t), map[string]any{}), &out)
|
||||
if !regexp.MustCompile(`^https://app\.example\.test/link-admin#code=[a-f0-9]{64}$`).MatchString(out.URL) || strings.Contains(out.URL, "?") {
|
||||
t.Fatalf("link URL = %q", out.URL)
|
||||
}
|
||||
})
|
||||
|
||||
for _, c := range []struct{ value, want string }{{"/pl/polacz", "/pl/polacz"}, {"pl/polacz", "/pl/polacz"}} {
|
||||
t.Run("page_path "+c.value, func(t *testing.T) {
|
||||
custom := newAdminEnv(t, func(cfg *compass.Config) {
|
||||
if err := cfg.Set("golem15.user.backend_links.page_path", c.value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
var out struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
adminInto(t, custom.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/link"), custom.admin(t), map[string]any{}), &out)
|
||||
if !regexp.MustCompile(`^https://app\.example\.test` + regexp.QuoteMeta(c.want) + `#code=[a-f0-9]{64}$`).MatchString(out.URL) {
|
||||
t.Fatalf("link URL with page_path %q = %q", c.value, out.URL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,13 @@ func (s *subjectSpy) has(guard string, id uint, kind string) bool {
|
||||
return slices.Contains(s.events, pact.MCPSubjectChanged{Guard: guard, UserID: id, Kind: kind})
|
||||
}
|
||||
|
||||
// hasEvent reports whether ev, with its TokenID and ClientID, was fired.
|
||||
func (s *subjectSpy) hasEvent(ev pact.MCPSubjectChanged) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return slices.Contains(s.events, ev)
|
||||
}
|
||||
|
||||
func (s *subjectSpy) reset() {
|
||||
s.mu.Lock()
|
||||
s.events = nil
|
||||
@@ -113,7 +120,7 @@ func (e *adminEnv) frontendSection(t *testing.T, token string) accountSection {
|
||||
return accountSection{}
|
||||
}
|
||||
|
||||
var linkURL = regexp.MustCompile(`^https://app\.example\.test/link-admin\?code=([a-f0-9]{64})$`)
|
||||
var linkURL = regexp.MustCompile(`^https://app\.example\.test/link-admin#code=([a-f0-9]{64})$`)
|
||||
|
||||
// startLink runs My account's link action and returns the code in its URL.
|
||||
func (e *adminEnv) startLink(t *testing.T, token string) string {
|
||||
|
||||
217
backend_link_test.go
Normal file
217
backend_link_test.go
Normal file
@@ -0,0 +1,217 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/controllers"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// requestCreatedAt reads when the administrator's open link request was
|
||||
// created.
|
||||
func (e *adminEnv) requestCreatedAt(t *testing.T, adminID uint) time.Time {
|
||||
t.Helper()
|
||||
var created time.Time
|
||||
if err := e.gdb.Raw(`SELECT created_at FROM golem15_user_backend_link_requests WHERE backend_user_id = ? AND used_at IS NULL ORDER BY id DESC LIMIT 1`, adminID).Scan(&created).Error; err != nil || created.IsZero() {
|
||||
t.Fatalf("link request created_at = %v, %v", created, err)
|
||||
}
|
||||
return created
|
||||
}
|
||||
|
||||
// TestBackendLink (D-03..D-08) extends the link smokes: the fresh sign-in
|
||||
// rule at the second (an auth_time equal to the request's created_at
|
||||
// confirms, one second earlier is stale_session, and a token without
|
||||
// auth_time is stale_session whatever its iat); 1:1 on the frontend side too (a
|
||||
// linked user cannot confirm another administrator's request); the show
|
||||
// route exposes the administrator's login and name and the expiry only;
|
||||
// SetLink records linked_by and fires BackendLinkedEvent and both subject
|
||||
// events after commit, nothing on rollback; RemoveLink fires
|
||||
// BackendUnlinkedEvent and both subject events; LinkedBackendUser answers
|
||||
// false for a deactivated or soft-deleted administrator; deactivating the
|
||||
// frontend user removes the link and fires deleted. Skips under -short.
|
||||
func TestBackendLink(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
spy := env.spySubjects()
|
||||
links, _ := env.app.Lookup[*classes.BackendLinks]()
|
||||
resolver, _ := env.app.Lookup[pact.MCPLinkedBackendResolver]()
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("fresh sign-in at the second", func(t *testing.T) {
|
||||
token := env.admin(t)
|
||||
admin := adminID(t, token)
|
||||
user := env.seedUser(t, "iat", nil)
|
||||
sub := strconv.FormatUint(uint64(user.ID), 10)
|
||||
code := env.startLink(t, token)
|
||||
created := env.requestCreatedAt(t, admin).Truncate(time.Second)
|
||||
early := craftSignInToken(t, sub, "early-"+adminStamp(), time.Now(), created.Add(-time.Second))
|
||||
if status, body := env.confirmLink(t, early, code); status != http.StatusConflict || !strings.Contains(body, `"stale_session"`) {
|
||||
t.Fatalf("auth_time one second early = %d %s", status, body)
|
||||
}
|
||||
noAuthTime := craftToken(t, sub, "legacy-"+adminStamp(), time.Now(), time.Now().Add(time.Hour))
|
||||
if status, body := env.confirmLink(t, noAuthTime, code); status != http.StatusConflict || !strings.Contains(body, `"stale_session"`) {
|
||||
t.Fatalf("no auth_time = %d %s", status, body)
|
||||
}
|
||||
exact := craftSignInToken(t, sub, "exact-"+adminStamp(), created, created)
|
||||
if status, body := env.confirmLink(t, exact, code); status != http.StatusOK {
|
||||
t.Fatalf("auth_time equal to created_at = %d %s", status, body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a linked frontend user cannot take a second administrator", func(t *testing.T) {
|
||||
first, second := env.admin(t), env.admin(t)
|
||||
user := env.seedUser(t, "one-to-one", nil)
|
||||
code := env.startLink(t, first)
|
||||
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusOK {
|
||||
t.Fatalf("first link = %d %s", status, body)
|
||||
}
|
||||
code = env.startLink(t, second)
|
||||
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusConflict || !strings.Contains(body, `"already_linked"`) {
|
||||
t.Fatalf("second administrator = %d %s", status, body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("show exposes login, name and expiry only", func(t *testing.T) {
|
||||
token := env.admin(t)
|
||||
code := env.startLink(t, token)
|
||||
rec := env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/backend-link/"+code, "", nil)
|
||||
var shown map[string]map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &shown); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys := func(m map[string]any) []string {
|
||||
var out []string
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
admin, _ := shown["data"]["admin"].(map[string]any)
|
||||
if len(shown) != 1 || !slices.Equal(keys(shown["data"]), []string{"admin", "expires_at"}) || !slices.Equal(keys(admin), []string{"login", "name"}) {
|
||||
t.Fatalf("show = %s", rec.Body.String())
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "@") || strings.Contains(rec.Body.String(), code) {
|
||||
t.Fatalf("show leaks an email or the code: %s", rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("SetLink and RemoveLink events", func(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var linked, unlinked int
|
||||
env.app.Events.Listen("test.link_events", func(context.Context, *classes.BackendLinkedEvent) error {
|
||||
mu.Lock()
|
||||
linked++
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
env.app.Events.Listen("test.link_events", func(context.Context, *classes.BackendUnlinkedEvent) error {
|
||||
mu.Lock()
|
||||
unlinked++
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
setter := adminID(t, env.admin(t))
|
||||
target := adminID(t, env.admin(t))
|
||||
user := env.seedUser(t, "set-link", nil)
|
||||
|
||||
// A rolled-back SetLink fires no subject event.
|
||||
spy.reset()
|
||||
_ = lagoon.Transaction(ctx, env.gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||
if _, err := links.SetLink(ctx, tx, user.ID, target, setter); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return context.Canceled
|
||||
})
|
||||
if spy.has("user", user.ID, pact.MCPSubjectLink) || spy.has("backend", target, pact.MCPSubjectLink) {
|
||||
t.Fatalf("a rolled-back SetLink fired %+v", spy.events)
|
||||
}
|
||||
|
||||
var link *models.BackendLink
|
||||
if err := lagoon.Transaction(ctx, env.gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||
var err error
|
||||
link, err = links.SetLink(ctx, tx, user.ID, target, setter)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if link.LinkedBy == nil || *link.LinkedBy != setter {
|
||||
t.Fatalf("linked_by = %v, want %d", link.LinkedBy, setter)
|
||||
}
|
||||
if !spy.has("user", user.ID, pact.MCPSubjectLink) || !spy.has("backend", target, pact.MCPSubjectLink) {
|
||||
t.Fatalf("SetLink fired %+v", spy.events)
|
||||
}
|
||||
spy.reset()
|
||||
if err := lagoon.Transaction(ctx, env.gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||
return links.RemoveLink(ctx, tx, link)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !spy.has("user", user.ID, pact.MCPSubjectLink) || !spy.has("backend", target, pact.MCPSubjectLink) {
|
||||
t.Fatalf("RemoveLink fired %+v", spy.events)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
// The rolled-back SetLink fired BackendLinkedEvent inside its
|
||||
// transaction too (listeners run with the transaction).
|
||||
if linked != 2 || unlinked != 1 {
|
||||
t.Fatalf("BackendLinkedEvent %d, BackendUnlinkedEvent %d", linked, unlinked)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("deactivated or deleted administrator", func(t *testing.T) {
|
||||
token := env.admin(t)
|
||||
admin := adminID(t, token)
|
||||
user := env.seedUser(t, "admin-gone", nil)
|
||||
code := env.startLink(t, token) // the request first: the sign-in must not predate it
|
||||
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusOK {
|
||||
t.Fatalf("link = %d %s", status, body)
|
||||
}
|
||||
check := func(want bool, why string) {
|
||||
t.Helper()
|
||||
if _, found, err := resolver.LinkedBackendUser(ctx, user.ID); err != nil || found != want {
|
||||
t.Fatalf("%s: found = %v, %v", why, found, err)
|
||||
}
|
||||
}
|
||||
check(true, "active")
|
||||
env.gdb.Exec(`UPDATE backend_users SET is_activated = FALSE WHERE id = ?`, admin)
|
||||
check(false, "deactivated administrator")
|
||||
env.gdb.Exec(`UPDATE backend_users SET is_activated = TRUE, deleted_at = NOW() WHERE id = ?`, admin)
|
||||
check(false, "soft-deleted administrator")
|
||||
env.gdb.Exec(`UPDATE backend_users SET deleted_at = NULL WHERE id = ?`, admin)
|
||||
check(true, "restored administrator")
|
||||
})
|
||||
|
||||
t.Run("deactivating the frontend user removes the link", func(t *testing.T) {
|
||||
token := env.admin(t)
|
||||
admin := adminID(t, token)
|
||||
user := env.seedUser(t, "deactivated", nil)
|
||||
code := env.startLink(t, token) // the request first: the sign-in must not predate it
|
||||
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusOK {
|
||||
t.Fatalf("link = %d %s", status, body)
|
||||
}
|
||||
spy.reset()
|
||||
if err := lagoon.Transaction(ctx, env.gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||
return controllers.FireDeactivatingEvent(ctx, env.app, user, tx)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if link, err := links.LinkOf(ctx, user.ID); err != nil || link != nil {
|
||||
t.Fatalf("link after deactivation = %+v, %v", link, err)
|
||||
}
|
||||
if !spy.has("user", user.ID, pact.MCPSubjectDeleted) || !spy.has("backend", admin, pact.MCPSubjectLink) {
|
||||
t.Fatalf("deactivation fired %+v", spy.events)
|
||||
}
|
||||
})
|
||||
}
|
||||
57
classes/access_revoked.go
Normal file
57
classes/access_revoked.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Reasons FireAccessRevoked is called with by this plugin.
|
||||
const (
|
||||
AccessRevokedBan = "ban"
|
||||
AccessRevokedPasswordReset = "password_reset"
|
||||
AccessRevokedPasswordSetByAdmin = "password_set_by_admin"
|
||||
AccessRevokedPasswordChanged = "password_changed"
|
||||
)
|
||||
|
||||
// FireAccessRevoked tells the application that userIDs lost every
|
||||
// credential issued before before (reason names why: a ban, a password reset
|
||||
// or change). It fires *AccessRevokedEvent in tx at once, so a listener
|
||||
// error is returned and the caller's transaction rolls back, and then one
|
||||
// "revoked" *pact.MCPSubjectChanged per user once tx commits, so MCP
|
||||
// sessions of those users end on every instance. A nil app or bus, or an
|
||||
// empty id list, does nothing. A nil tx fires the subject events at once.
|
||||
//
|
||||
// The plugin calls it from the ban action, the password reset, an
|
||||
// administrator setting a password and the self-service password change.
|
||||
// RevokeUserAccess, BanUsers and DeactivateUsers do not fire it: an
|
||||
// application that calls RevokeUserAccess or BanUsers directly calls
|
||||
// FireAccessRevoked too, in the same transaction.
|
||||
func FireAccessRevoked(ctx context.Context, app *backpack.App, tx *gorm.DB, userIDs []uint, before time.Time, reason string) error {
|
||||
if app == nil || app.Events == nil || len(userIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
ids := make([]uint, 0, len(userIDs))
|
||||
for _, id := range userIDs {
|
||||
if id != 0 {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := app.Events.Fire(ctx, &AccessRevokedEvent{UserIDs: ids, Before: before, Reason: reason, Tx: tx}); err != nil {
|
||||
return fmt.Errorf("%s: %w", AccessRevokedEventName, err)
|
||||
}
|
||||
for _, id := range ids {
|
||||
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardUser, id, pact.MCPSubjectRevoked)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
176
classes/api_token_scopes.go
Normal file
176
classes/api_token_scopes.go
Normal file
@@ -0,0 +1,176 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
)
|
||||
|
||||
// APITokenScope is one scope a member personal API token (usr_) may carry:
|
||||
// a built-in (read, write, ai) or one a plugin declared through
|
||||
// pact.HasFrontendTokenScopes. Label and Description are phrase keys
|
||||
// (containing "::") or literal text; PluginID is the declaring plugin, empty
|
||||
// for a built-in.
|
||||
type APITokenScope struct {
|
||||
Name string
|
||||
Label string
|
||||
Description string
|
||||
PluginID string
|
||||
BuiltIn bool
|
||||
}
|
||||
|
||||
// APITokenScopeCatalog is the compiled list of member token scopes of one
|
||||
// application: the built-ins first, then the declared scopes in activation
|
||||
// order. Boot publishes it; APITokenScopesFor reads it.
|
||||
type APITokenScopeCatalog struct {
|
||||
scopes []APITokenScope
|
||||
byName map[string]int
|
||||
}
|
||||
|
||||
// Scopes returns a copy of the catalog, built-ins first.
|
||||
func (c *APITokenScopeCatalog) Scopes() []APITokenScope {
|
||||
if c == nil {
|
||||
return builtInAPITokenScopes()
|
||||
}
|
||||
return slices.Clone(c.scopes)
|
||||
}
|
||||
|
||||
// Allowed reports whether a member token may carry name in this catalog.
|
||||
func (c *APITokenScopeCatalog) Allowed(name string) bool {
|
||||
if c == nil {
|
||||
return slices.Contains(AllowedAPITokenScopes, name)
|
||||
}
|
||||
_, ok := c.byName[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// builtInAPITokenScopeKeys are the label and description phrase keys of
|
||||
// the built-in scopes, in AllowedAPITokenScopes order.
|
||||
var builtInAPITokenScopeKeys = map[string][2]string{
|
||||
"read": {"golem15.user::lang.api_tokens.scope_read", "golem15.user::lang.api_tokens.scope_read_description"},
|
||||
"write": {"golem15.user::lang.api_tokens.scope_write", "golem15.user::lang.api_tokens.scope_write_description"},
|
||||
"ai": {"golem15.user::lang.api_tokens.scope_ai", "golem15.user::lang.api_tokens.scope_ai_description"},
|
||||
}
|
||||
|
||||
// builtInAPITokenScopes are AllowedAPITokenScopes with their phrase keys.
|
||||
func builtInAPITokenScopes() []APITokenScope {
|
||||
out := make([]APITokenScope, 0, len(AllowedAPITokenScopes))
|
||||
for _, name := range AllowedAPITokenScopes {
|
||||
keys := builtInAPITokenScopeKeys[name]
|
||||
out = append(out, APITokenScope{Name: name, Label: keys[0], Description: keys[1], BuiltIn: true})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func newAPITokenScopeCatalog(scopes []APITokenScope) *APITokenScopeCatalog {
|
||||
c := &APITokenScopeCatalog{scopes: scopes, byName: make(map[string]int, len(scopes))}
|
||||
for i, scope := range scopes {
|
||||
c.byName[scope.Name] = i
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// CompileAPITokenScopes builds the member token scope catalog from the
|
||||
// built-ins and every plugin that implements pact.HasFrontendTokenScopes, in
|
||||
// the order given (party.Activated). A declared name is trimmed and must
|
||||
// pass pact.ValidTokenScopeName, must not be a built-in (read, write, ai)
|
||||
// and must not repeat a name another plugin (or the same one) declared; its
|
||||
// label and description must not be empty. Any violation is an error, which
|
||||
// fails boot. Phrase keys are checked against the translator by Boot. Every
|
||||
// name of a catalog that compiles is added to the process-wide set the
|
||||
// legacy MintAPIToken accepts.
|
||||
func CompileAPITokenScopes(plugins []party.Plugin) (*APITokenScopeCatalog, error) {
|
||||
scopes := builtInAPITokenScopes()
|
||||
owner := map[string]string{}
|
||||
for _, scope := range scopes {
|
||||
owner[scope.Name] = ""
|
||||
}
|
||||
var declared []string
|
||||
for _, plugin := range plugins {
|
||||
if plugin == nil {
|
||||
continue
|
||||
}
|
||||
src, ok := plugin.(pact.HasFrontendTokenScopes)
|
||||
if !ok || src == nil {
|
||||
continue
|
||||
}
|
||||
id := plugin.ID()
|
||||
for _, scope := range src.FrontendTokenScopes() {
|
||||
name := strings.TrimSpace(scope.Name)
|
||||
if name == "" || !pact.ValidTokenScopeName(name) {
|
||||
return nil, fmt.Errorf("golem15.user: plugin %s declared invalid member token scope name %q", id, scope.Name)
|
||||
}
|
||||
if other, taken := owner[name]; taken {
|
||||
if other == "" {
|
||||
return nil, fmt.Errorf("golem15.user: plugin %s declared the built-in member token scope %q", id, name)
|
||||
}
|
||||
return nil, fmt.Errorf("golem15.user: duplicate member token scope %q declared by %s and %s", name, other, id)
|
||||
}
|
||||
if strings.TrimSpace(scope.Label) == "" {
|
||||
return nil, fmt.Errorf("golem15.user: plugin %s member token scope %s has an empty label", id, name)
|
||||
}
|
||||
if strings.TrimSpace(scope.Description) == "" {
|
||||
return nil, fmt.Errorf("golem15.user: plugin %s member token scope %s has an empty description", id, name)
|
||||
}
|
||||
owner[name] = id
|
||||
scopes = append(scopes, APITokenScope{Name: name, Label: scope.Label, Description: scope.Description, PluginID: id})
|
||||
declared = append(declared, name)
|
||||
}
|
||||
}
|
||||
declaredScopes.add(declared)
|
||||
return newAPITokenScopeCatalog(scopes), nil
|
||||
}
|
||||
|
||||
// APITokenScopesFor returns the catalog Boot published on app, or the
|
||||
// built-ins alone when none is published.
|
||||
func APITokenScopesFor(app *backpack.App) *APITokenScopeCatalog {
|
||||
if app != nil {
|
||||
if catalog, ok := app.Lookup[*APITokenScopeCatalog](); ok && catalog != nil {
|
||||
return catalog
|
||||
}
|
||||
}
|
||||
return newAPITokenScopeCatalog(builtInAPITokenScopes())
|
||||
}
|
||||
|
||||
// declaredScopes is the process-wide set of every member token scope name a
|
||||
// compiled catalog declared, the legacy MintAPIToken's fallback. Production
|
||||
// runs one application per process, so it equals that application's
|
||||
// declared scopes.
|
||||
var declaredScopes = &scopeSet{names: map[string]bool{}}
|
||||
|
||||
type scopeSet struct {
|
||||
mu sync.RWMutex
|
||||
names map[string]bool
|
||||
}
|
||||
|
||||
func (s *scopeSet) add(names []string) {
|
||||
if len(names) == 0 {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, name := range names {
|
||||
s.names[name] = true
|
||||
}
|
||||
}
|
||||
|
||||
func (s *scopeSet) has(name string) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.names[name]
|
||||
}
|
||||
|
||||
// ResetDeclaredAPITokenScopes clears the process-wide set of declared member
|
||||
// token scopes that the legacy MintAPIToken accepts. It is a test seam for
|
||||
// tests outside this package that compile catalogs; production never calls
|
||||
// it.
|
||||
func ResetDeclaredAPITokenScopes() {
|
||||
declaredScopes.mu.Lock()
|
||||
defer declaredScopes.mu.Unlock()
|
||||
declaredScopes.names = map[string]bool{}
|
||||
}
|
||||
@@ -18,6 +18,9 @@ import (
|
||||
|
||||
const DefaultAPITokenPrefix = "usr_"
|
||||
|
||||
// DefaultAPITokenScopes is what a token minted without scopes carries, and
|
||||
// AllowedAPITokenScopes are the built-in member token scopes. Plugins add
|
||||
// their own through pact.HasFrontendTokenScopes (APITokenScopeCatalog).
|
||||
var (
|
||||
DefaultAPITokenScopes = []string{"read"}
|
||||
AllowedAPITokenScopes = []string{"read", "write", "ai"}
|
||||
@@ -44,8 +47,31 @@ func APITokenPrefix(app *backpack.App) (string, error) {
|
||||
}
|
||||
|
||||
// MintAPIToken builds a token record and returns its one-time clear-text
|
||||
// secret. A nil scopes slice receives DefaultAPITokenScopes.
|
||||
// secret. A nil scopes slice receives DefaultAPITokenScopes. It accepts the
|
||||
// built-in scopes (AllowedAPITokenScopes) and, as a fallback for existing
|
||||
// callers, every member token scope a catalog compiled in this process
|
||||
// declared (CompileAPITokenScopes). New code calls MintAPITokenFor, which
|
||||
// checks the scopes against the application's own catalog.
|
||||
//
|
||||
// Deprecated: the declared-scope fallback is process-wide, so in a process
|
||||
// that boots several applications it accepts another application's scopes.
|
||||
// Use MintAPITokenFor.
|
||||
func MintAPIToken(prefix string, userID uint, name string, scopes []string, expiresAt *time.Time, collectionIDs []uint) (string, *models.APIToken, error) {
|
||||
return mintAPIToken(prefix, userID, name, scopes, expiresAt, collectionIDs, func(scope string) bool {
|
||||
return slices.Contains(AllowedAPITokenScopes, scope) || declaredScopes.has(scope)
|
||||
})
|
||||
}
|
||||
|
||||
// MintAPITokenFor is MintAPIToken with the scopes checked against app's
|
||||
// member token scope catalog (APITokenScopesFor): the built-ins and the
|
||||
// scopes app's activated plugins declared through
|
||||
// pact.HasFrontendTokenScopes. A scope another application in the same
|
||||
// process declared is refused.
|
||||
func MintAPITokenFor(app *backpack.App, prefix string, userID uint, name string, scopes []string, expiresAt *time.Time, collectionIDs []uint) (string, *models.APIToken, error) {
|
||||
return mintAPIToken(prefix, userID, name, scopes, expiresAt, collectionIDs, APITokenScopesFor(app).Allowed)
|
||||
}
|
||||
|
||||
func mintAPIToken(prefix string, userID uint, name string, scopes []string, expiresAt *time.Time, collectionIDs []uint, allowed func(string) bool) (string, *models.APIToken, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if userID == 0 || name == "" || len(name) > 255 {
|
||||
return "", nil, fmt.Errorf("a user and token name of 1 to 255 characters are required")
|
||||
@@ -59,7 +85,7 @@ func MintAPIToken(prefix string, userID uint, name string, scopes []string, expi
|
||||
scopes = slices.Clone(scopes)
|
||||
}
|
||||
for _, scope := range scopes {
|
||||
if !slices.Contains(AllowedAPITokenScopes, scope) {
|
||||
if !allowed(scope) {
|
||||
return "", nil, fmt.Errorf("scope %q is not allowed", scope)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,8 +18,9 @@ import (
|
||||
// AvatarURL returns the display picture URL of user at size pixels, the
|
||||
// rule the user API payload follows: the thumbnail (size by size, mode
|
||||
// auto) of the user's avatar attachment when there is one and a file
|
||||
// bucket is published, the attachment's file path when the thumbnail
|
||||
// fails (logged), and otherwise the gravatar URL
|
||||
// bucket is published, the original file's public URL (attach.File.URL,
|
||||
// following storage.uploads.public_path_prefix and public_url) when the
|
||||
// thumbnail fails (logged), and otherwise the gravatar URL
|
||||
// //www.gravatar.com/avatar/{md5 of the email}?s={size}&d=mm. The URL may
|
||||
// be protocol-relative or relative; a caller that needs an absolute URL
|
||||
// resolves it. Only a failing database lookup is an error.
|
||||
@@ -52,7 +53,7 @@ func AvatarURL(ctx context.Context, app *backpack.App, user *models.User, size i
|
||||
url, err := f.Thumb(ctx, bucket, size, size, "auto")
|
||||
if err != nil {
|
||||
pluginLog.Error("golem15.user: avatar thumb", "err", err)
|
||||
return "/" + attach.BlobKey(f.DiskName), nil
|
||||
return f.URL(), nil
|
||||
}
|
||||
return url, nil
|
||||
}
|
||||
|
||||
@@ -52,6 +52,17 @@ type BackendLinks struct {
|
||||
App *backpack.App
|
||||
}
|
||||
|
||||
// BackendLinksFor returns the link service Boot published on app, or one
|
||||
// over app when none is published.
|
||||
func BackendLinksFor(app *backpack.App) *BackendLinks {
|
||||
if app != nil {
|
||||
if links, ok := app.Lookup[*BackendLinks](); ok && links != nil {
|
||||
return links
|
||||
}
|
||||
}
|
||||
return &BackendLinks{App: app}
|
||||
}
|
||||
|
||||
// BackendLinkRequestTTL reads golem15.user.backend_links.request_ttl, a Go
|
||||
// duration (10m by default). A value that does not parse or is not positive
|
||||
// is an error, so a typo fails the boot instead of silently changing the
|
||||
@@ -71,6 +82,27 @@ func BackendLinkRequestTTL(app *backpack.App) (time.Duration, error) {
|
||||
return ttl, nil
|
||||
}
|
||||
|
||||
// DefaultBackendLinkPagePath is the site page the account link points to when
|
||||
// golem15.user.backend_links.page_path is not set.
|
||||
const DefaultBackendLinkPagePath = "/link-admin"
|
||||
|
||||
// BackendLinkPagePath reads golem15.user.backend_links.page_path, the path of
|
||||
// the site page that confirms an account link (default /link-admin). A value
|
||||
// without a leading slash gets one.
|
||||
func BackendLinkPagePath(app *backpack.App) string {
|
||||
if app == nil || app.Config == nil {
|
||||
return DefaultBackendLinkPagePath
|
||||
}
|
||||
path := strings.TrimSpace(app.Config.String("golem15.user.backend_links.page_path"))
|
||||
if path == "" {
|
||||
return DefaultBackendLinkPagePath
|
||||
}
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// FrontendURL is the site the plugin sends people to for pages it does not
|
||||
// serve itself (the account link page): golem15.user.frontend_url, falling
|
||||
// back to app.url, without a trailing slash. Empty when neither is set.
|
||||
@@ -190,27 +222,37 @@ func (s *BackendLinks) LinkRequestByCode(ctx context.Context, plain string) (*mo
|
||||
return req, admin, nil
|
||||
}
|
||||
|
||||
// requestUsable answers why a request cannot be used (used or expired), or
|
||||
// nil when req.IsUsableAt(now).
|
||||
func requestUsable(req *models.BackendLinkRequest, now time.Time) error {
|
||||
if req.IsUsableAt(now) {
|
||||
return nil
|
||||
}
|
||||
if req.UsedAt != nil {
|
||||
return ErrLinkRequestUsed
|
||||
}
|
||||
if !req.ExpiresAt.After(now) {
|
||||
return ErrLinkRequestExpired
|
||||
}
|
||||
return nil
|
||||
return ErrLinkRequestExpired
|
||||
}
|
||||
|
||||
// ConfirmLinkRequest stores the link between the signed-in frontend user and
|
||||
// the administrator who created the request, in one transaction: the request
|
||||
// row is locked, must be unused and unexpired, and the session must have
|
||||
// been signed in at or after the request was created (sessionIssuedAt is
|
||||
// the JWT iat, compared in whole seconds because iat has no fraction), so a
|
||||
// browser that was already signed in has to sign in again (D-05). Neither
|
||||
// been signed in at or after the request was created, so a browser that was
|
||||
// already signed in has to sign in again (D-05). sessionAuthTime is the
|
||||
// session token's auth_time claim (bouncer.VerifyAuthTime): the time of the
|
||||
// sign-in itself, which a refresh copies and never renews. It is compared in
|
||||
// whole seconds with the request's created_at because the claim has no
|
||||
// fraction, which leaves a one-second blind spot: a sign-in earlier in the
|
||||
// same second as the request, but before it, counts as fresh. Telling the
|
||||
// two apart would need a sub-second claim; refusing that whole second
|
||||
// instead would make a sign-in in the request's own second sign in once
|
||||
// more. The window is accepted (it needs a sign-in in the very second the
|
||||
// administrator starts the link). A zero time is ErrStaleSession. Neither
|
||||
// account may be linked already (ErrAlreadyLinked) and the administrator
|
||||
// must still be activated (ErrBackendUserUnavailable). The request is used
|
||||
// up with the link; BackendLinkedEvent fires inside the transaction and the
|
||||
// two pact.MCPSubjectChanged events after it commits.
|
||||
func (s *BackendLinks) ConfirmLinkRequest(ctx context.Context, plain string, frontendUserID uint, sessionIssuedAt time.Time) (*models.BackendLink, error) {
|
||||
func (s *BackendLinks) ConfirmLinkRequest(ctx context.Context, plain string, frontendUserID uint, sessionAuthTime time.Time) (*models.BackendLink, error) {
|
||||
if !validLinkCode(plain) {
|
||||
return nil, ErrLinkRequestNotFound
|
||||
}
|
||||
@@ -236,7 +278,8 @@ func (s *BackendLinks) ConfirmLinkRequest(ctx context.Context, plain string, fro
|
||||
if err := requestUsable(req, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if sessionIssuedAt.IsZero() || sessionIssuedAt.Before(req.CreatedAt.Truncate(time.Second)) {
|
||||
// Whole seconds on both sides: see the blind spot above.
|
||||
if sessionAuthTime.IsZero() || sessionAuthTime.Before(req.CreatedAt.Truncate(time.Second)) {
|
||||
return ErrStaleSession
|
||||
}
|
||||
if _, err := activeBackendUser(ctx, tx, req.BackendUserID); err != nil {
|
||||
@@ -289,7 +332,9 @@ func (s *BackendLinks) SetLink(ctx context.Context, tx *gorm.DB, frontendUserID,
|
||||
|
||||
// insertLink writes one link in tx after checking both sides are free; a
|
||||
// concurrent writer that wins the unique index also ends in
|
||||
// ErrAlreadyLinked.
|
||||
// ErrAlreadyLinked. It is the one write path of a link (ConfirmLinkRequest
|
||||
// and SetLink), so BackendLinkedEvent, with Link.UserID set, fires on every
|
||||
// link; RemoveLink is the one removal path and fires BackendUnlinkedEvent.
|
||||
func (s *BackendLinks) insertLink(ctx context.Context, tx *gorm.DB, frontendUserID, backendUserID uint, linkedBy *uint) (*models.BackendLink, error) {
|
||||
var taken int64
|
||||
if err := fresh(ctx, tx).Model(&models.BackendLink{}).
|
||||
@@ -319,7 +364,8 @@ func (s *BackendLinks) insertLink(ctx context.Context, tx *gorm.DB, frontendUser
|
||||
return link, nil
|
||||
}
|
||||
|
||||
// RemoveLink deletes link in tx, fires BackendUnlinkedEvent there and the
|
||||
// RemoveLink deletes link in tx, fires BackendUnlinkedEvent (Link.UserID
|
||||
// set) there and the
|
||||
// two pact.MCPSubjectChanged link events after tx commits. A link that is
|
||||
// already gone is not an error and fires nothing.
|
||||
func (s *BackendLinks) RemoveLink(ctx context.Context, tx *gorm.DB, link *models.BackendLink) error {
|
||||
@@ -378,7 +424,8 @@ func (s *BackendLinks) linkWhere(ctx context.Context, where string, id uint) (*m
|
||||
// LinkedBackendUser implements pact.MCPLinkedBackendResolver with one
|
||||
// indexed query per call (no cache): the administrator linked to the
|
||||
// frontend user, false when there is no link, when the frontend user is
|
||||
// deactivated, or when the administrator is deactivated or deleted.
|
||||
// deactivated or banned (user_throttle.is_banned on any of their rows), or
|
||||
// when the administrator is deactivated or deleted.
|
||||
func (s *BackendLinks) LinkedBackendUser(ctx context.Context, frontendUserID uint) (pact.LinkedBackendUser, bool, error) {
|
||||
if frontendUserID == 0 {
|
||||
return pact.LinkedBackendUser{}, false, nil
|
||||
@@ -398,6 +445,7 @@ FROM golem15_user_backend_links l
|
||||
JOIN backend_users b ON b.id = l.backend_user_id
|
||||
JOIN users u ON u.id = l.user_id
|
||||
WHERE l.user_id = ? AND b.deleted_at IS NULL AND b.is_activated = TRUE AND u.deleted_at IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM user_throttle t WHERE t.user_id = l.user_id AND t.is_banned)
|
||||
LIMIT 1`, frontendUserID).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return pact.LinkedBackendUser{}, false, err
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -20,6 +22,9 @@ const BackendLinkedEventName = "user.BackendLinked"
|
||||
// BackendUnlinkedEventName is the festival name of BackendUnlinkedEvent.
|
||||
const BackendUnlinkedEventName = "user.BackendUnlinked"
|
||||
|
||||
// AccessRevokedEventName is the festival name of AccessRevokedEvent.
|
||||
const AccessRevokedEventName = "user.AccessRevoked"
|
||||
|
||||
// GetApiArrayEvent is the fire-and-collect payload other plugins extend.
|
||||
type GetApiArrayEvent struct {
|
||||
User *models.User
|
||||
@@ -90,3 +95,19 @@ type BackendUnlinkedEvent struct {
|
||||
Link *models.BackendLink
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
// AccessRevokedEvent fires inside the write transaction when users lose
|
||||
// every credential issued before Before: a ban, a password reset, a password
|
||||
// an administrator set, or the user's own password change (FireAccessRevoked;
|
||||
// Reason names which). Listeners revoke what such a credential still holds
|
||||
// elsewhere, for example OAuth access and refresh tokens created before
|
||||
// Before. Before is the untruncated instant of the revocation, while the
|
||||
// users' tokens_valid_after keeps its whole-second value. A listener error
|
||||
// rolls the write back. Deactivation and deletion keep their own events
|
||||
// (DeactivatingEvent, DeletingEvent).
|
||||
type AccessRevokedEvent struct {
|
||||
UserIDs []uint
|
||||
Before time.Time
|
||||
Reason string
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -139,7 +140,9 @@ func (g *MCPUserGuard) MCPDispatch(ctx context.Context, subject pact.MCPSubject,
|
||||
// an MCP subject with the token's own scopes. A token without the configured
|
||||
// prefix answers false; one with it that is unknown, revoked, expired or
|
||||
// whose user is gone answers pact.ErrMCPTokenInvalid. A usable token gets
|
||||
// its last_used_at stamped, as the api_token guard does.
|
||||
// its last_used_at stamped, and its last_used_ip when the context carries
|
||||
// the client address (towel.ClientIP, which the MCP endpoint sets), as the
|
||||
// api_token guard does.
|
||||
func (g *MCPUserGuard) MCPResolvePersonalToken(ctx context.Context, raw string) (pact.MCPSubject, bool, error) {
|
||||
prefix, err := APITokenPrefix(g.app())
|
||||
if err != nil || !strings.HasPrefix(raw, prefix) {
|
||||
@@ -166,7 +169,11 @@ func (g *MCPUserGuard) MCPResolvePersonalToken(ctx context.Context, raw string)
|
||||
if principal == nil {
|
||||
return pact.MCPSubject{}, true, pact.ErrMCPTokenInvalid
|
||||
}
|
||||
if err := db.Model(&models.APIToken{}).Where("id = ?", token.ID).UpdateColumn("last_used_at", now).Error; err != nil {
|
||||
used := map[string]any{"last_used_at": now}
|
||||
if ip, ok := towel.ClientIP(ctx); ok && strings.TrimSpace(ip) != "" {
|
||||
used["last_used_ip"] = strings.TrimSpace(ip)
|
||||
}
|
||||
if err := db.Model(&models.APIToken{}).Where("id = ?", token.ID).UpdateColumns(used).Error; err != nil {
|
||||
return pact.MCPSubject{}, true, err
|
||||
}
|
||||
return pact.MCPSubject{Guard: SubjectGuardUser, UserID: token.UserID, Scopes: slices.Clone(token.Scopes.Get()), TokenID: token.ID}, true, nil
|
||||
|
||||
91
classes/organisation_logo.go
Normal file
91
classes/organisation_logo.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OrganisationLogoSize is the edge in pixels of the logo thumbnail
|
||||
// OrganisationLogoFields answers.
|
||||
const OrganisationLogoSize = 256
|
||||
|
||||
// organisationLogo loads the organisation's logo attachment, or nil.
|
||||
func organisationLogo(ctx context.Context, app *backpack.App, org *models.Organisation) (*attach.File, error) {
|
||||
if app == nil || org == nil || org.ID == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
gdb, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || gdb == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var f attach.File
|
||||
err := gdb.WithContext(ctx).
|
||||
Where("attachment_type = ? AND attachment_id = ? AND field = ?", org.MorphName(), strconv.FormatUint(uint64(org.ID), 10), models.OrganisationLogoField).
|
||||
Take(&f).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &f, nil
|
||||
}
|
||||
|
||||
// OrganisationLogoURL returns the URL of the organisation's logo at size
|
||||
// pixels, the way AvatarURL serves a user's picture: the thumbnail (size by
|
||||
// size, mode auto) of the logo attachment, or the original file's public
|
||||
// URL (attach.File.URL, which follows storage.uploads.public_path_prefix and
|
||||
// public_url) when the thumbnail fails (logged). It answers false when the organisation
|
||||
// has no logo or no file bucket is published. The URL may be relative; a
|
||||
// caller that needs an absolute URL resolves it. Only a failing database
|
||||
// lookup is an error.
|
||||
func OrganisationLogoURL(ctx context.Context, app *backpack.App, org *models.Organisation, size int) (string, bool, error) {
|
||||
f, err := organisationLogo(ctx, app, org)
|
||||
if err != nil || f == nil {
|
||||
return "", false, err
|
||||
}
|
||||
bucket, ok := app.Lookup[*blob.Bucket]()
|
||||
if !ok || bucket == nil {
|
||||
return "", false, nil
|
||||
}
|
||||
url, err := f.Thumb(ctx, bucket, size, size, "auto")
|
||||
if err != nil {
|
||||
pluginLog.Error("golem15.user: organisation logo thumb", "err", err)
|
||||
return f.URL(), true, nil
|
||||
}
|
||||
return url, true, nil
|
||||
}
|
||||
|
||||
// OrganisationLogoFields answers the logo keys an application adds to its
|
||||
// own organisation payloads, named like the user payload's avatar keys:
|
||||
// has_logo (bool), logo (the attachment's disk name, or nil) and logo_url
|
||||
// (the OrganisationLogoSize thumbnail URL, or nil). An organisation without
|
||||
// a logo answers false, nil and nil. Only a failing database lookup is an
|
||||
// error.
|
||||
func OrganisationLogoFields(ctx context.Context, app *backpack.App, org *models.Organisation) (map[string]any, error) {
|
||||
out := map[string]any{"has_logo": false, "logo": nil, "logo_url": nil}
|
||||
f, err := organisationLogo(ctx, app, org)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f == nil {
|
||||
return out, nil
|
||||
}
|
||||
out["has_logo"] = true
|
||||
out["logo"] = f.DiskName
|
||||
url, ok, err := OrganisationLogoURL(ctx, app, org, OrganisationLogoSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok && url != "" {
|
||||
out["logo_url"] = url
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -17,39 +17,53 @@ const (
|
||||
SubjectGuardBackend = "backend"
|
||||
)
|
||||
|
||||
// FireSubjectChanged fires one *pact.MCPSubjectChanged (guard, user id,
|
||||
// kind) through the application's event bus at once, so the MCP endpoint
|
||||
// re-lists the subject's tools or ends its sessions. A missing application
|
||||
// or bus, or a zero id, is a no-op; a listener's error is logged and never
|
||||
// returned, so the write that caused the event never fails because of it
|
||||
// (every MCP request re-checks anyway).
|
||||
func FireSubjectChanged(ctx context.Context, app *backpack.App, guard string, userID uint, kind string) {
|
||||
if app == nil || app.Events == nil || userID == 0 || kind == "" {
|
||||
// FireSubjectEvent fires ev through the application's event bus at once, so
|
||||
// the MCP endpoint re-lists the subject's tools or ends its sessions. A
|
||||
// revoked event may carry TokenID (only the sessions one personal token
|
||||
// opened end) or ClientID with UserID (only that OAuth client's sessions
|
||||
// end). A missing application or bus, a zero UserID or an empty Kind is a
|
||||
// no-op; a listener's error is logged and never returned, so the write that
|
||||
// caused the event never fails because of it (every MCP request re-checks
|
||||
// anyway).
|
||||
func FireSubjectEvent(ctx context.Context, app *backpack.App, ev pact.MCPSubjectChanged) {
|
||||
if app == nil || app.Events == nil || ev.UserID == 0 || ev.Kind == "" {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
event := &pact.MCPSubjectChanged{Guard: guard, UserID: userID, Kind: kind}
|
||||
if err := app.Events.Fire(ctx, event); err != nil {
|
||||
pluginLog.WarnContext(ctx, "golem15.user: subject changed listener failed", "guard", guard, "user_id", userID, "kind", kind, "err", err)
|
||||
event := ev
|
||||
if err := app.Events.Fire(ctx, &event); err != nil {
|
||||
pluginLog.WarnContext(ctx, "golem15.user: subject changed listener failed", "guard", ev.Guard, "user_id", ev.UserID, "kind", ev.Kind, "token_id", ev.TokenID, "client_id", ev.ClientID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// FireSubjectChangedAfterCommit is FireSubjectChanged once the write
|
||||
// FireSubjectEventAfterCommit is FireSubjectEvent once the write
|
||||
// transaction tx commits (lagoon.AfterCommit), so a listener that reads the
|
||||
// database sees the change; nothing is fired when the transaction rolls
|
||||
// back. A nil tx fires at once. ctx must be the context the transaction
|
||||
// runs under (the one cabana hands a hook or an action).
|
||||
func FireSubjectChangedAfterCommit(ctx context.Context, app *backpack.App, tx *gorm.DB, guard string, userID uint, kind string) {
|
||||
if app == nil || app.Events == nil || userID == 0 || kind == "" {
|
||||
func FireSubjectEventAfterCommit(ctx context.Context, app *backpack.App, tx *gorm.DB, ev pact.MCPSubjectChanged) {
|
||||
if app == nil || app.Events == nil || ev.UserID == 0 || ev.Kind == "" {
|
||||
return
|
||||
}
|
||||
if tx == nil {
|
||||
FireSubjectChanged(ctx, app, guard, userID, kind)
|
||||
FireSubjectEvent(ctx, app, ev)
|
||||
return
|
||||
}
|
||||
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
|
||||
FireSubjectChanged(ctx, app, guard, userID, kind)
|
||||
FireSubjectEvent(ctx, app, ev)
|
||||
})
|
||||
}
|
||||
|
||||
// FireSubjectChanged fires one *pact.MCPSubjectChanged (guard, user id,
|
||||
// kind) at once: FireSubjectEvent for the whole subject.
|
||||
func FireSubjectChanged(ctx context.Context, app *backpack.App, guard string, userID uint, kind string) {
|
||||
FireSubjectEvent(ctx, app, pact.MCPSubjectChanged{Guard: guard, UserID: userID, Kind: kind})
|
||||
}
|
||||
|
||||
// FireSubjectChangedAfterCommit is FireSubjectChanged once the write
|
||||
// transaction tx commits: FireSubjectEventAfterCommit for the whole subject.
|
||||
func FireSubjectChangedAfterCommit(ctx context.Context, app *backpack.App, tx *gorm.DB, guard string, userID uint, kind string) {
|
||||
FireSubjectEventAfterCommit(ctx, app, tx, pact.MCPSubjectChanged{Guard: guard, UserID: userID, Kind: kind})
|
||||
}
|
||||
|
||||
@@ -38,10 +38,15 @@ privileged_groups:
|
||||
# refuses them. The turnstile:* middleware comes from the framework (summercms
|
||||
# v0.3.0 and later); its secret is turnstile.secret (SUMMER_TURNSTILE__SECRET).
|
||||
turnstile: ""
|
||||
# The site this plugin's links point to (the account link page
|
||||
# /link-admin?code=...). Empty falls back to app.url.
|
||||
# The site this plugin's links point to (the account link page,
|
||||
# <frontend_url><backend_links.page_path>#code=...). Empty falls back to
|
||||
# app.url.
|
||||
frontend_url: ""
|
||||
backend_links:
|
||||
# How long a link request an administrator starts on My account stays
|
||||
# usable (a Go duration). The code is one-shot.
|
||||
request_ttl: 10m
|
||||
# The site page that confirms a link. My account sends the administrator
|
||||
# to <frontend_url><page_path>#code=<code>; the code is in the fragment,
|
||||
# which browsers never send to a server.
|
||||
page_path: /link-admin
|
||||
|
||||
@@ -79,7 +79,7 @@ Revoke a token with user:token:revoke and list them with user:token:list.`,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
secret, token, err := classes.MintAPIToken(prefix, user.ID, name, scopes, expiresAt, nil)
|
||||
secret, token, err := classes.MintAPITokenFor(app, prefix, user.ID, name, scopes, expiresAt, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("user:token:create: %w", err)
|
||||
}
|
||||
|
||||
@@ -447,13 +447,21 @@ func ResetPassword(app *backpack.App) http.HandlerFunc {
|
||||
// address (D-27). A reset that fails here records nothing. The
|
||||
// session cutoff is truncated to whole seconds, as in
|
||||
// RevokeUserAccess, because JWT iat has whole-second precision, so
|
||||
// the login that follows the reset is not refused.
|
||||
// the login that follows the reset is not refused. The same
|
||||
// transaction fires the access-revoked event with the untruncated
|
||||
// instant, so OAuth grants created before the reset are revoked
|
||||
// with the password change or not at all.
|
||||
now := time.Now()
|
||||
if err := gdb.WithContext(r.Context()).Model(&models.User{}).Where("id = ?", user.ID).Updates(map[string]any{
|
||||
"password": hashed,
|
||||
"tokens_valid_after": now.Truncate(time.Second),
|
||||
"email_verified_at": now,
|
||||
}).Error; err != nil {
|
||||
if err := lagoon.Transaction(r.Context(), gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||
if err := tx.WithContext(ctx).Model(&models.User{}).Where("id = ?", user.ID).Updates(map[string]any{
|
||||
"password": hashed,
|
||||
"tokens_valid_after": now.Truncate(time.Second),
|
||||
"email_verified_at": now,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return classes.FireAccessRevoked(ctx, app, tx, []uint{user.ID}, now, classes.AccessRevokedPasswordReset)
|
||||
}); err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
@@ -707,13 +715,24 @@ func ChangePassword(app *backpack.App) http.HandlerFunc {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
// The cutoff keeps the current session (issued at iat) and every
|
||||
// session token issued since that second. OAuth grants are revoked
|
||||
// as of now, whatever their age: the request needs none, and a
|
||||
// grant its client refreshed after iat would otherwise survive the
|
||||
// change (its rotated tokens are newer than the session).
|
||||
cutoff := iat.Add(-time.Second)
|
||||
if err := gdb.WithContext(r.Context()).Model(&user).Updates(map[string]any{
|
||||
"password": hashed,
|
||||
"must_change_password": false,
|
||||
"has_self_set_password": true,
|
||||
"tokens_valid_after": cutoff,
|
||||
}).Error; err != nil {
|
||||
revokedAt := time.Now()
|
||||
if err := lagoon.Transaction(r.Context(), gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||
if err := tx.WithContext(ctx).Model(&user).Updates(map[string]any{
|
||||
"password": hashed,
|
||||
"must_change_password": false,
|
||||
"has_self_set_password": true,
|
||||
"tokens_valid_after": cutoff,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return classes.FireAccessRevoked(ctx, app, tx, []uint{user.ID}, revokedAt, classes.AccessRevokedPasswordChanged)
|
||||
}); err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
@@ -1146,6 +1165,26 @@ func activationLink(app *backpack.App, id uint, code string) string {
|
||||
return base + "?" + q.Encode()
|
||||
}
|
||||
|
||||
// readBodyFields is readFields without the query string: a JSON body, or a
|
||||
// form-encoded body read from r.PostForm. The routes that carry a secret in
|
||||
// a field use it, so the secret is never taken from a URL that access logs
|
||||
// record.
|
||||
func readBodyFields(r *http.Request) (map[string]any, error) {
|
||||
if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
|
||||
return readFields(r)
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields := map[string]any{}
|
||||
for k, v := range r.PostForm {
|
||||
if len(v) > 0 {
|
||||
fields[k] = v[0]
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
func readFields(r *http.Request) (map[string]any, error) {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if strings.Contains(ct, "application/json") {
|
||||
|
||||
@@ -3,7 +3,6 @@ package controllers
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -35,7 +34,8 @@ func APITokenStore(app *backpack.App) http.HandlerFunc {
|
||||
writeValidation(w, map[string][]string{"name": {"The name field is required and may not be longer than 255 characters."}})
|
||||
return
|
||||
}
|
||||
scopes, err := apiTokenScopes(fields["scopes"])
|
||||
catalog := classes.APITokenScopesFor(app)
|
||||
scopes, err := apiTokenScopes(catalog, fields["scopes"])
|
||||
if err != nil {
|
||||
writeValidation(w, map[string][]string{"scopes": {err.Error()}})
|
||||
return
|
||||
@@ -54,7 +54,7 @@ func APITokenStore(app *backpack.App) http.HandlerFunc {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
secret, token, err := classes.MintAPIToken(prefix, user.ID, name, scopes, expiresAt, nil)
|
||||
secret, token, err := classes.MintAPITokenFor(app, prefix, user.ID, name, scopes, expiresAt, nil)
|
||||
if err != nil || db.WithContext(r.Context()).Create(token).Error != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
@@ -63,6 +63,37 @@ func APITokenStore(app *backpack.App) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// APITokenScopes serves GET /_user/api/v1/tokens/scopes behind jwt.auth:
|
||||
// the member token scopes the caller may mint, {"data":[{"name","label",
|
||||
// "description","built_in"}]}, the built-ins first, then the scopes the
|
||||
// application's plugins declared. Phrase-key labels and descriptions are
|
||||
// translated for the request locale.
|
||||
func APITokenScopes(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := bouncer.User(r.Context())
|
||||
if !ok || user == nil || user.ID == 0 {
|
||||
writeUnauthorized(w)
|
||||
return
|
||||
}
|
||||
tr := appTranslator(app)
|
||||
text := func(s string) string {
|
||||
if tr == nil || !strings.Contains(s, "::") {
|
||||
return s
|
||||
}
|
||||
return tr.Get(r.Context(), s, nil)
|
||||
}
|
||||
scopes := classes.APITokenScopesFor(app).Scopes()
|
||||
data := make([]map[string]any, 0, len(scopes))
|
||||
for _, scope := range scopes {
|
||||
data = append(data, map[string]any{
|
||||
"name": scope.Name, "label": text(scope.Label),
|
||||
"description": text(scope.Description), "built_in": scope.BuiltIn,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": wire.Slice(data)})
|
||||
}
|
||||
}
|
||||
|
||||
// APITokenIndex lists the caller's live personal tokens without hashes.
|
||||
func APITokenIndex(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -107,8 +138,8 @@ func APITokenDestroy(app *backpack.App) http.HandlerFunc {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
// An MCP session opened with this token ends.
|
||||
classes.FireSubjectChanged(r.Context(), app, classes.SubjectGuardUser, user.ID, pact.MCPSubjectRevoked)
|
||||
// Only the MCP sessions opened with this token end.
|
||||
classes.FireSubjectEvent(r.Context(), app, pact.MCPSubjectChanged{Guard: classes.SubjectGuardUser, UserID: user.ID, Kind: pact.MCPSubjectRevoked, TokenID: token.ID})
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"revoked": true}})
|
||||
}
|
||||
}
|
||||
@@ -131,7 +162,9 @@ func apiTokenDeps(w http.ResponseWriter, r *http.Request, app *backpack.App) (*g
|
||||
return db, user, true
|
||||
}
|
||||
|
||||
func apiTokenScopes(raw any) ([]string, error) {
|
||||
// apiTokenScopes reads the scopes field: nil, or an array of names the
|
||||
// catalog allows.
|
||||
func apiTokenScopes(catalog *classes.APITokenScopeCatalog, raw any) ([]string, error) {
|
||||
if raw == nil {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -142,7 +175,7 @@ func apiTokenScopes(raw any) ([]string, error) {
|
||||
out := make([]string, 0, len(values))
|
||||
for _, rawScope := range values {
|
||||
scope, ok := rawScope.(string)
|
||||
if !ok || !slices.Contains(classes.AllowedAPITokenScopes, scope) {
|
||||
if !ok || !catalog.Allowed(scope) {
|
||||
return nil, errors.New("The selected scope is invalid.")
|
||||
}
|
||||
out = append(out, scope)
|
||||
|
||||
@@ -9,16 +9,12 @@ import (
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/wire"
|
||||
)
|
||||
|
||||
// backendLinks returns the published link service, or one over app.
|
||||
func backendLinks(app *backpack.App) *classes.BackendLinks {
|
||||
if app != nil {
|
||||
if links, ok := app.Lookup[*classes.BackendLinks](); ok && links != nil {
|
||||
return links
|
||||
}
|
||||
}
|
||||
return &classes.BackendLinks{App: app}
|
||||
return classes.BackendLinksFor(app)
|
||||
}
|
||||
|
||||
// linkNotFound is the one answer for an unknown, used or expired code and
|
||||
@@ -33,30 +29,64 @@ func linkNotFound(w http.ResponseWriter) {
|
||||
// and display name and when the code expires, nothing else. Anyone holding
|
||||
// the code may read it; a code that is unknown, used or expired, or whose
|
||||
// administrator was deactivated, answers 404.
|
||||
//
|
||||
// Deprecated: the code sits in the request path, which access logs record.
|
||||
// Pages call BackendLinkShowPost (POST /_user/api/v1/backend-link/show with
|
||||
// the code in the body); this route stays for compatibility.
|
||||
func BackendLinkShow(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
req, admin, err := backendLinks(app).LinkRequestByCode(r.Context(), r.PathValue("code"))
|
||||
showLinkRequest(w, r, app, r.PathValue("code"))
|
||||
}
|
||||
}
|
||||
|
||||
// BackendLinkShowPost serves POST /_user/api/v1/backend-link/show: body
|
||||
// {"code": ...}, the same answers as BackendLinkShow. The code travels in
|
||||
// the body, so it stays out of the URLs servers and proxies log; a code in
|
||||
// the query string is ignored.
|
||||
func BackendLinkShowPost(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
fields, err := readBodyFields(r)
|
||||
if err != nil {
|
||||
if isLinkGone(err) {
|
||||
linkNotFound(w)
|
||||
return
|
||||
}
|
||||
writeOpaque500(w)
|
||||
writeNoStoreJSON(w, http.StatusNotFound, map[string]any{"error": "not_found"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"admin": map[string]any{"login": admin.Login, "name": classes.BackendDisplayName(admin)},
|
||||
"expires_at": req.ExpiresAt.UTC().Format(time.RFC3339),
|
||||
}})
|
||||
showLinkRequest(w, r, app, strField(fields, "code"))
|
||||
}
|
||||
}
|
||||
|
||||
// showLinkRequest answers the link request behind code. Both show routes
|
||||
// mark every answer as not storable, since it is keyed by a secret.
|
||||
func showLinkRequest(w http.ResponseWriter, r *http.Request, app *backpack.App, code string) {
|
||||
req, admin, err := backendLinks(app).LinkRequestByCode(r.Context(), code)
|
||||
if err != nil {
|
||||
if isLinkGone(err) {
|
||||
writeNoStoreJSON(w, http.StatusNotFound, map[string]any{"error": "not_found"})
|
||||
return
|
||||
}
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeNoStoreJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"admin": map[string]any{"login": admin.Login, "name": classes.BackendDisplayName(admin)},
|
||||
"expires_at": req.ExpiresAt.UTC().Format(time.RFC3339),
|
||||
}})
|
||||
}
|
||||
|
||||
// writeNoStoreJSON is writeJSON with Cache-Control: no-store, private.
|
||||
func writeNoStoreJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Cache-Control", "no-store, private")
|
||||
wire.WriteJSON(w, status, v)
|
||||
}
|
||||
|
||||
// BackendLinkConfirm serves POST /_user/api/v1/backend-link/confirm behind
|
||||
// jwt.auth: body {"code": ...}. The signed-in frontend user is linked to the
|
||||
// administrator who created the code, only when the session token was
|
||||
// issued at or after the request (the user signed in fresh for it): an
|
||||
// older session answers 409 with the stale-session error, an account already linked on
|
||||
// either side 409 already_linked, an unknown, used or expired code 404.
|
||||
// administrator who created the code, only when the session was signed in at
|
||||
// or after the request: the token's auth_time (bouncer.VerifyAuthTime), which
|
||||
// a refresh copies and never renews, is the proof. An older sign-in, or a
|
||||
// token without auth_time (minted before auth_time existed, or refreshed from
|
||||
// one), answers 409 with the stale-session error, an account already linked
|
||||
// on either side 409 already_linked, an unknown, used or expired code 404.
|
||||
// The code is read from the body only; one in the query string is ignored.
|
||||
func BackendLinkConfirm(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
principal, ok := bouncer.User(r.Context())
|
||||
@@ -70,19 +100,23 @@ func BackendLinkConfirm(app *backpack.App) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
// The token jwt.auth accepted (bearer header, then the session
|
||||
// cookies), read again for its iat.
|
||||
sub, iat, _, _, err := bouncer.VerifyClaims(classes.SessionToken(r), secret)
|
||||
// cookies), read again for its sign-in time.
|
||||
sub, authTime, signedIn, err := bouncer.VerifyAuthTime(classes.SessionToken(r), secret, bouncer.AudienceUser)
|
||||
if err != nil || sub != strconv.FormatUint(uint64(principal.ID), 10) {
|
||||
writeUnauthorized(w)
|
||||
return
|
||||
}
|
||||
fields, err := readFields(r)
|
||||
if !signedIn {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": "stale_session"})
|
||||
return
|
||||
}
|
||||
fields, err := readBodyFields(r)
|
||||
if err != nil {
|
||||
linkNotFound(w)
|
||||
return
|
||||
}
|
||||
links := backendLinks(app)
|
||||
_, err = links.ConfirmLinkRequest(r.Context(), strField(fields, "code"), principal.ID, iat)
|
||||
_, err = links.ConfirmLinkRequest(r.Context(), strField(fields, "code"), principal.ID, authTime)
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, classes.ErrStaleSession):
|
||||
|
||||
@@ -4,9 +4,13 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -119,3 +123,50 @@ func (organisationsAdminController) FormBeforeDelete(ctx context.Context, model
|
||||
Model(&models.User{}).Where("organisation_id = ?", organisation.ID).
|
||||
Updates(map[string]any{"organisation_id": nil, "organisation_role": nil}).Error
|
||||
}
|
||||
|
||||
// FormAfterDelete deletes the organisation's attachments (avatar and logo)
|
||||
// in the delete's transaction, and their blobs once it commits, so no
|
||||
// system_files row outlives the organisation row.
|
||||
func (c organisationsAdminController) FormAfterDelete(ctx context.Context, model any) error {
|
||||
organisation, ok := model.(*models.Organisation)
|
||||
if !ok || organisation == nil {
|
||||
return errors.New("organisations admin: form model is not an organisation")
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return errors.New("organisations admin: a delete needs its transaction")
|
||||
}
|
||||
var keys []string
|
||||
if err := attach.DeleteForOwner(tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx), organisation, strconv.FormatUint(uint64(organisation.ID), 10), func(blobKeys []string) error {
|
||||
keys = append(keys, blobKeys...)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
bucket := c.bucket()
|
||||
if bucket == nil || len(keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
id := organisation.ID
|
||||
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
|
||||
// The rows are gone by now, so a blob that cannot be removed is
|
||||
// orphaned, not lost data: log it and carry on.
|
||||
if err := attach.DeleteKeys(ctx, bucket, keys); err != nil {
|
||||
pluginLog.Warn("golem15.user: remove attachment blobs of a deleted organisation", "organisation_id", id, "err", err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// bucket is the application's blob bucket, or nil when none is published.
|
||||
func (c organisationsAdminController) bucket() *blob.Bucket {
|
||||
app := c.app.application()
|
||||
if app == nil {
|
||||
return nil
|
||||
}
|
||||
bucket, ok := app.Lookup[*blob.Bucket]()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return bucket
|
||||
}
|
||||
|
||||
@@ -244,8 +244,15 @@ func (c usersAdminController) FormBeforeUpdate(ctx context.Context, model any) e
|
||||
// user's own change-password does. The cutoff is truncated to whole
|
||||
// seconds, as in RevokeUserAccess, because JWT iat has whole-second
|
||||
// precision, so the user's next login in that second is not refused.
|
||||
now := time.Now().Truncate(time.Second)
|
||||
// OAuth grants created before the untruncated instant are revoked in
|
||||
// the save's transaction (the access-revoked event).
|
||||
at := time.Now()
|
||||
now := at.Truncate(time.Second)
|
||||
user.TokensValidAfter = &now
|
||||
tx, _ := cabana.TxFromContext(ctx)
|
||||
if err := classes.FireAccessRevoked(ctx, c.application(), tx, []uint{user.ID}, at, classes.AccessRevokedPasswordSetByAdmin); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -631,11 +638,50 @@ func (c usersAdminController) AdminBulkActions() []pact.AdminBulkAction {
|
||||
bulk("activate", classes.ActivateUsers),
|
||||
bulk("deactivate", c.deactivateUsers),
|
||||
bulk("restore", classes.RestoreUsers),
|
||||
bulk("ban", classes.BanUsers),
|
||||
bulk("ban", c.banUsers),
|
||||
bulk("unban", classes.UnbanUsers),
|
||||
}
|
||||
}
|
||||
|
||||
// banUsers runs classes.BanUsers unchanged in the action's transaction and
|
||||
// fires the access-revoked event there for the users it newly banned (banned
|
||||
// after, not before), so their OAuth grants are revoked with the ban and
|
||||
// their MCP sessions end once it commits. A listener error rolls the action
|
||||
// back.
|
||||
func (c usersAdminController) banUsers(ctx context.Context, tx *gorm.DB, users []*models.User) (int, error) {
|
||||
ids := make([]uint, 0, len(users))
|
||||
for _, user := range users {
|
||||
if user != nil && user.ID != 0 {
|
||||
ids = append(ids, user.ID)
|
||||
}
|
||||
}
|
||||
before, _, err := classes.ThrottleStates(ctx, tx, ids)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
at := time.Now()
|
||||
changed, err := classes.BanUsers(ctx, tx, users)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
after, _, err := classes.ThrottleStates(ctx, tx, ids)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
newly := make([]uint, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if after[id] && !before[id] {
|
||||
newly = append(newly, id)
|
||||
}
|
||||
}
|
||||
if len(newly) > 0 {
|
||||
if err := classes.FireAccessRevoked(ctx, c.application(), tx, newly, at, classes.AccessRevokedBan); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// deactivateUsers runs classes.DeactivateUsers unchanged and then fires
|
||||
// user.Deactivating, in the action's transaction, for every selected user
|
||||
// that was not deactivated before. A listener error rolls the action back.
|
||||
|
||||
95
frontend_permission_catalog_test.go
Normal file
95
frontend_permission_catalog_test.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
)
|
||||
|
||||
const acmeShopOrders = "acme.shop.orders"
|
||||
|
||||
// acmeShopPermissions declares a code of its own and acme.blog's manage code
|
||||
// again, under another label: activated after acme.blog, its duplicate is
|
||||
// dropped.
|
||||
type acmeShopPermissions struct{}
|
||||
|
||||
func (acmeShopPermissions) ID() string { return "acme.shop" }
|
||||
func (acmeShopPermissions) Requires() []string { return nil }
|
||||
func (acmeShopPermissions) Register(*backpack.App) error { return nil }
|
||||
func (acmeShopPermissions) Boot(*backpack.App) error { return nil }
|
||||
func (acmeShopPermissions) FrontendPermissions() []pact.FrontendPermission {
|
||||
return []pact.FrontendPermission{
|
||||
{Code: acmeBlogManage, Label: "Shop's copy", Tab: "Shop"},
|
||||
{Code: acmeShopOrders, Label: "Manage orders", Tab: "Shop"},
|
||||
{Code: " ", Label: "Empty code", Tab: "Shop"},
|
||||
}
|
||||
}
|
||||
|
||||
func init() { party.Register(acmeShopPermissions{}) }
|
||||
|
||||
// TestFrontendPermissionCatalog (D-09) extends the smoke: with two declaring
|
||||
// plugins the editors offer the seeded rows, then the first plugin's codes,
|
||||
// then the second's, a code the first already declared and an empty code
|
||||
// left out; a group saved with a declared code keeps it, and the member's
|
||||
// grants (what user.permission checks) include it. Skips under -short.
|
||||
func TestFrontendPermissionCatalog(t *testing.T) {
|
||||
env := newAdminEnvWith(t, []string{"acme.blog", "acme.shop"})
|
||||
if err := env.gdb.Exec(`INSERT INTO golem15_user_frontend_permissions (code, label, tab) VALUES (?, 'Seeded label', 'Blog') ON CONFLICT (code) DO NOTHING`, acmeBlogSeeded).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var seeded int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM golem15_user_frontend_permissions`).Scan(&seeded).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token := env.admin(t, permAccessUsers, permAccessGroups)
|
||||
|
||||
t.Run("second plugin's duplicate dropped", func(t *testing.T) {
|
||||
for _, path := range []string{adminUsersPath, adminGroupsPath} {
|
||||
options := env.permissionOptions(t, token, path)
|
||||
declared := options[seeded:]
|
||||
var codes []string
|
||||
for _, o := range declared {
|
||||
codes = append(codes, o.Code)
|
||||
}
|
||||
if len(declared) != 2 || declared[len(declared)-2].Code != acmeBlogManage || declared[len(declared)-2].Label != "Manage blog posts" ||
|
||||
declared[len(declared)-1] != (offeredPermission{Code: acmeShopOrders, Label: "Manage orders", Tab: "Shop"}) {
|
||||
t.Fatalf("%s declared options = %+v", path, declared)
|
||||
}
|
||||
seen := map[string]int{}
|
||||
for _, o := range options {
|
||||
seen[o.Code]++
|
||||
if o.Code == "" || o.Code == " " {
|
||||
t.Fatalf("%s offers an empty code", path)
|
||||
}
|
||||
}
|
||||
if seen[acmeBlogManage] != 1 || seen[acmeShopOrders] != 1 {
|
||||
t.Fatalf("%s codes offered %v (declared %v)", path, seen, codes)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("group saved with a declared code grants it", func(t *testing.T) {
|
||||
stamp := adminStamp()
|
||||
group := env.seedGroup(t, "Orders "+stamp, "orders-"+stamp)
|
||||
member := env.seedUser(t, "orders", nil)
|
||||
env.join(t, member, group)
|
||||
env.expect(t, http.StatusOK, http.MethodPut, groupPath(group.ID), token, map[string]any{
|
||||
"name": group.Name, "code": *group.Code, "permissions": map[string]int{acmeShopOrders: 1},
|
||||
})
|
||||
var saved models.UserGroup
|
||||
if err := env.gdb.First(&saved, group.ID).Error; err != nil || saved.Permissions == nil || !strings.Contains(*saved.Permissions, `"`+acmeShopOrders+`"`) {
|
||||
t.Fatalf("saved permissions = %v, %v", saved.Permissions, err)
|
||||
}
|
||||
grants, err := classes.UserPermissionGrants(context.Background(), env.gdb, member.ID)
|
||||
if err != nil || !grants[acmeShopOrders] {
|
||||
t.Fatalf("member grants = %v, %v", grants, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
2
go.mod
2
go.mod
@@ -3,7 +3,7 @@ module git.golem15.com/golem15/sm-user-plugin
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
git.golem15.com/golem15/summercms v0.4.4
|
||||
git.golem15.com/golem15/summercms v0.5.0
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
|
||||
@@ -106,6 +106,8 @@ organisation:
|
||||
slug_invalid: The slug may only contain letters, numbers, dashes and underscores.
|
||||
description: Description
|
||||
avatar: Avatar
|
||||
logo: Logo
|
||||
logo_comment: Shown wherever the site displays the organisation.
|
||||
members: Members
|
||||
new: New Organisation
|
||||
list_empty: No organisations yet. Create the first one with New Organisation.
|
||||
@@ -136,3 +138,10 @@ backend_link:
|
||||
remove_success: The frontend account is unlinked.
|
||||
unknown_user: No active frontend user has this email.
|
||||
already_linked: This administrator or this frontend user is already linked.
|
||||
api_tokens:
|
||||
scope_read: Read
|
||||
scope_read_description: Read your account and the data the site lets you see.
|
||||
scope_write: Write
|
||||
scope_write_description: Change your account and the data the site lets you edit.
|
||||
scope_ai: AI
|
||||
scope_ai_description: Use the site's AI features on your behalf.
|
||||
|
||||
@@ -106,6 +106,8 @@ organisation:
|
||||
slug_invalid: Identyfikator może zawierać tylko litery, cyfry, myślniki i podkreślenia.
|
||||
description: Opis
|
||||
avatar: Awatar
|
||||
logo: Logo
|
||||
logo_comment: Wyświetlane wszędzie, gdzie strona pokazuje organizację.
|
||||
members: Członkowie
|
||||
new: Nowa organizacja
|
||||
list_empty: Brak organizacji. Utwórz pierwszą przyciskiem Nowa organizacja.
|
||||
@@ -136,3 +138,10 @@ backend_link:
|
||||
remove_success: Konto na stronie zostało odłączone.
|
||||
unknown_user: Żaden aktywny użytkownik strony nie ma tego emaila.
|
||||
already_linked: Ten administrator albo ten użytkownik strony jest już połączony.
|
||||
api_tokens:
|
||||
scope_read: Odczyt
|
||||
scope_read_description: Odczyt Twojego konta i danych, które strona pozwala Ci oglądać.
|
||||
scope_write: Zapis
|
||||
scope_write_description: Zmiany na Twoim koncie i w danych, które strona pozwala Ci edytować.
|
||||
scope_ai: AI
|
||||
scope_ai_description: Korzystanie w Twoim imieniu z funkcji AI strony.
|
||||
|
||||
61
mcp_guard_client_ip_test.go
Normal file
61
mcp_guard_client_ip_test.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
)
|
||||
|
||||
// TestUserMCPGuardClientIP pins plan 08's client address on the MCP
|
||||
// personal-token path (C-IN-04): MCPResolvePersonalToken stamps
|
||||
// last_used_ip from towel.ClientIP, as the api_token guard does, and leaves
|
||||
// the column as it was when the context carries no address. Postgres only:
|
||||
// skipped under -short.
|
||||
func TestUserMCPGuardClientIP(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres")
|
||||
}
|
||||
env := newAdminEnv(t)
|
||||
resolver, ok := env.app.Lookup[pact.MCPPersonalTokenResolver]()
|
||||
if !ok {
|
||||
t.Fatal("no personal token resolver published")
|
||||
}
|
||||
user := env.seedUser(t, "mcp-ip", nil)
|
||||
secret, token := env.mintUserToken(t, user, "read")
|
||||
lastIP := func(t *testing.T) *string {
|
||||
t.Helper()
|
||||
var row models.APIToken
|
||||
if err := env.gdb.Where("id = ?", token.ID).First(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return row.LastUsedIP
|
||||
}
|
||||
|
||||
t.Run("an address on the context is stamped", func(t *testing.T) {
|
||||
subject, matched, err := resolver.MCPResolvePersonalToken(towel.WithClientIP(context.Background(), "203.0.113.44"), secret)
|
||||
if err != nil || !matched || subject.TokenID != token.ID {
|
||||
t.Fatalf("resolve = %+v, %v, %v", subject, matched, err)
|
||||
}
|
||||
if ip := lastIP(t); ip == nil || *ip != "203.0.113.44" {
|
||||
t.Fatalf("last_used_ip = %v, want 203.0.113.44", ip)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no address leaves the column as it was", func(t *testing.T) {
|
||||
if _, matched, err := resolver.MCPResolvePersonalToken(context.Background(), secret); err != nil || !matched {
|
||||
t.Fatalf("resolve = %v, %v", matched, err)
|
||||
}
|
||||
if ip := lastIP(t); ip == nil || *ip != "203.0.113.44" {
|
||||
t.Fatalf("last_used_ip after a resolve without an address = %v, want it unchanged", ip)
|
||||
}
|
||||
if _, _, err := resolver.MCPResolvePersonalToken(towel.WithClientIP(context.Background(), " "), secret); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ip := lastIP(t); ip == nil || *ip != "203.0.113.44" {
|
||||
t.Fatalf("last_used_ip after a blank address = %v, want it unchanged", ip)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -153,11 +153,11 @@ func TestUserMCPGuardSmoke(t *testing.T) {
|
||||
}
|
||||
env.expect(t, http.StatusUnauthorized, http.MethodGet, "/_user/api/v1/token/me", freshUserToken(t, user), nil)
|
||||
|
||||
// Revoking the token through the API fires revoked; the resolver then
|
||||
// refuses it.
|
||||
// Revoking the token through the API fires revoked for that token only
|
||||
// (TokenID); the resolver then refuses it.
|
||||
spy.reset()
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, "/_user/api/v1/tokens/"+strconv.FormatUint(uint64(readToken.ID), 10), freshUserToken(t, user), nil)
|
||||
if !spy.has("user", user.ID, pact.MCPSubjectRevoked) {
|
||||
if !spy.hasEvent(pact.MCPSubjectChanged{Guard: "user", UserID: user.ID, Kind: pact.MCPSubjectRevoked, TokenID: readToken.ID}) {
|
||||
t.Fatalf("revoke fired %+v", spy.events)
|
||||
}
|
||||
if _, matched, err := resolver.MCPResolvePersonalToken(ctx, readSecret); !matched || !errors.Is(err, pact.ErrMCPTokenInvalid) {
|
||||
|
||||
117
mcp_guard_test.go
Normal file
117
mcp_guard_test.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// TestUserMCPGuard (D-15, D-16, D-35) extends TestUserMCPGuardSmoke: the
|
||||
// requirement parser refuses a user.* middleware it does not know and a
|
||||
// scope or permission middleware without its name; a soft-deleted user is
|
||||
// neither allowed nor dispatched and its personal tokens stop resolving, as
|
||||
// do expired ones; and the in-memory credential MCPDispatch builds passes
|
||||
// the route's own user.scope:read middleware when the subject was granted
|
||||
// read and is refused (403) when it was not, through the plugin's real
|
||||
// route chain in-process. Skips under -short.
|
||||
func TestUserMCPGuard(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
ctx := context.Background()
|
||||
guards, _ := env.app.Lookup[*pact.MCPGuards]()
|
||||
guard, ok := guards.Lookup("user")
|
||||
if !ok {
|
||||
t.Fatal("no user guard")
|
||||
}
|
||||
resolver, _ := env.app.Lookup[pact.MCPPersonalTokenResolver]()
|
||||
|
||||
t.Run("requirement parser refusals", func(t *testing.T) {
|
||||
for _, mw := range [][]string{{"user.api_token", "user.unknown"}, {"user.api_token", "user.scope:"}, {"user.api_token", "user.permission:"}} {
|
||||
if _, err := guard.MCPRequirements(mw); err == nil {
|
||||
t.Fatalf("%v accepted", mw)
|
||||
}
|
||||
}
|
||||
if req, err := guard.MCPRequirements([]string{"throttle:user-api", "user.api_token", "user.scope:read", "user.scope:read"}); err != nil || len(req.Scopes) != 1 {
|
||||
t.Fatalf("duplicate scope = %+v, %v", req, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("soft-deleted user", func(t *testing.T) {
|
||||
user := env.seedUser(t, "mcp-gone", nil)
|
||||
secret, _ := env.mintUserToken(t, user, "read")
|
||||
subject := pact.MCPSubject{Guard: "user", UserID: user.ID, Scopes: []string{"read"}}
|
||||
if ok, err := guard.MCPAllows(ctx, subject, pact.MCPRequirements{}, nil); err != nil || !ok {
|
||||
t.Fatalf("before deletion = %v, %v", ok, err)
|
||||
}
|
||||
if err := env.gdb.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, user.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, err := guard.MCPAllows(ctx, subject, pact.MCPRequirements{}, nil); err != nil || ok {
|
||||
t.Fatalf("after deletion Allows = %v, %v", ok, err)
|
||||
}
|
||||
if _, err := guard.MCPDispatch(ctx, subject, http.MethodGet); err == nil {
|
||||
t.Fatal("a deleted user was dispatched")
|
||||
}
|
||||
if _, matched, err := resolver.MCPResolvePersonalToken(ctx, secret); !matched || !errors.Is(err, pact.ErrMCPTokenInvalid) {
|
||||
t.Fatalf("a deleted user's token = %v, %v", matched, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("expired token", func(t *testing.T) {
|
||||
user := env.seedUser(t, "mcp-expired", nil)
|
||||
secret, token := env.mintUserToken(t, user, "read")
|
||||
if err := env.gdb.Model(&models.APIToken{}).Where("id = ?", token.ID).Update("expires_at", time.Now().Add(-time.Minute)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, matched, err := resolver.MCPResolvePersonalToken(ctx, secret); !matched || !errors.Is(err, pact.ErrMCPTokenInvalid) {
|
||||
t.Fatalf("an expired token = %v, %v", matched, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dispatch credential against user.scope", func(t *testing.T) {
|
||||
user := env.seedUser(t, "mcp-scope", nil)
|
||||
me := func(scopes ...string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
d, err := guard.MCPDispatch(ctx, pact.MCPSubject{Guard: "user", UserID: user.ID, Scopes: scopes}, http.MethodGet)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
principal, _ := d.Principal.(*bouncer.Principal)
|
||||
req := httptest.NewRequest(http.MethodGet, "/_user/api/v1/token/me", nil)
|
||||
req = req.WithContext(bouncer.WithDispatch(req.Context(), &bouncer.Dispatch{Guards: d.Guards, Principal: principal, Credential: d.Credential}))
|
||||
rec := httptest.NewRecorder()
|
||||
env.h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
if rec := me("read"); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"email":"`+user.Email+`"`) {
|
||||
t.Fatalf("read subject = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := me("write"); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "Missing required scope: read") {
|
||||
t.Fatalf("write-only subject = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, isToken := mustDispatchCredential(t, guard, user.ID).(*models.APIToken); !isToken {
|
||||
t.Fatal("the dispatch credential is not an in-memory API token")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// mustDispatchCredential returns the credential MCPDispatch builds for a
|
||||
// read subject; it is never saved (ID 0).
|
||||
func mustDispatchCredential(t *testing.T, guard pact.MCPGuard, userID uint) any {
|
||||
t.Helper()
|
||||
d, err := guard.MCPDispatch(context.Background(), pact.MCPSubject{Guard: "user", UserID: userID, Scopes: []string{"read"}}, http.MethodGet)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tok, ok := d.Credential.(*models.APIToken); !ok || tok.ID != 0 {
|
||||
t.Fatalf("credential = %+v", d.Credential)
|
||||
}
|
||||
return d.Credential
|
||||
}
|
||||
166
member_token_scopes_smoke_test.go
Normal file
166
member_token_scopes_smoke_test.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/wire"
|
||||
)
|
||||
|
||||
// scopeDeclarer is a plugin value that only declares member token scopes,
|
||||
// for CompileAPITokenScopes; it is never registered.
|
||||
type scopeDeclarer struct {
|
||||
id string
|
||||
scopes []pact.FrontendTokenScope
|
||||
}
|
||||
|
||||
func (d scopeDeclarer) ID() string { return d.id }
|
||||
func (d scopeDeclarer) Requires() []string { return nil }
|
||||
func (d scopeDeclarer) Register(*backpack.App) error { return nil }
|
||||
func (d scopeDeclarer) Boot(*backpack.App) error { return nil }
|
||||
func (d scopeDeclarer) FrontendTokenScopes() []pact.FrontendTokenScope { return d.scopes }
|
||||
|
||||
// acmeServers declares the member token scope servers:write and serves a
|
||||
// route behind user.api_token and user.scope:servers:write. It is
|
||||
// registered for the test binary and activated only by the tests that name
|
||||
// it.
|
||||
type acmeServers struct{}
|
||||
|
||||
func (acmeServers) ID() string { return "acme.servers" }
|
||||
func (acmeServers) Requires() []string { return []string{"golem15.user"} }
|
||||
func (acmeServers) Register(*backpack.App) error { return nil }
|
||||
func (acmeServers) Boot(*backpack.App) error { return nil }
|
||||
|
||||
func (acmeServers) FrontendTokenScopes() []pact.FrontendTokenScope {
|
||||
return []pact.FrontendTokenScope{{Name: "servers:write", Label: "Write servers", Description: "Report server components."}}
|
||||
}
|
||||
|
||||
func (acmeServers) Routes(r pact.Router) error {
|
||||
r.Get("/_servers/api/v1/ping", func(w http.ResponseWriter, _ *http.Request) {
|
||||
wire.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}, "user.api_token", "user.scope:servers:write")
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() { party.Register(acmeServers{}) }
|
||||
|
||||
// TestMemberTokenScopesSmoke (E-2): a duplicate, a redeclared built-in and a
|
||||
// bad name fail the catalog; with a plugin declaring servers:write, POST
|
||||
// /tokens mints it, a route behind user.scope:servers:write accepts it and
|
||||
// refuses a read token, an undeclared scope answers 422, GET /tokens/scopes
|
||||
// lists the built-ins and the declared scope with labels, and a second
|
||||
// application without the plugin refuses the scope over HTTP and through
|
||||
// MintAPITokenFor. The Postgres part skips under -short.
|
||||
func TestMemberTokenScopesSmoke(t *testing.T) {
|
||||
t.Cleanup(classes.ResetDeclaredAPITokenScopes)
|
||||
|
||||
t.Run("catalog validation", func(t *testing.T) {
|
||||
scope := func(name string) []pact.FrontendTokenScope {
|
||||
return []pact.FrontendTokenScope{{Name: name, Label: "Label", Description: "Description"}}
|
||||
}
|
||||
for name, plugins := range map[string][]party.Plugin{
|
||||
"duplicate": {scopeDeclarer{"acme.a", scope("acme:dup")}, scopeDeclarer{"acme.b", scope("acme:dup")}},
|
||||
"built-in": {scopeDeclarer{"acme.a", scope("write")}},
|
||||
"bad name": {scopeDeclarer{"acme.a", scope("Bad Name")}},
|
||||
"empty label": {scopeDeclarer{"acme.a", []pact.FrontendTokenScope{{Name: "acme:x", Description: "Description"}}}},
|
||||
} {
|
||||
if _, err := classes.CompileAPITokenScopes(plugins); err == nil {
|
||||
t.Fatalf("%s: CompileAPITokenScopes succeeded", name)
|
||||
}
|
||||
}
|
||||
catalog, err := classes.CompileAPITokenScopes([]party.Plugin{scopeDeclarer{"acme.a", scope("acme:ok")}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var names []string
|
||||
for _, s := range catalog.Scopes() {
|
||||
names = append(names, s.Name)
|
||||
}
|
||||
if !slices.Equal(names, []string{"read", "write", "ai", "acme:ok"}) || !catalog.Allowed("acme:ok") || catalog.Allowed("acme:dup") {
|
||||
t.Fatalf("catalog = %v", names)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("mint, check, list and discovery", func(t *testing.T) {
|
||||
env := newAdminEnvWith(t, []string{"acme.servers"})
|
||||
user := env.seedUser(t, "member-scopes", nil)
|
||||
session := freshUserToken(t, user)
|
||||
|
||||
mint := func(e *adminEnv, scopes ...string) *http.Response {
|
||||
t.Helper()
|
||||
rec := e.call(t, http.MethodPost, "/_user/api/v1/tokens", session, map[string]any{"name": "agent " + adminStamp(), "scopes": scopes})
|
||||
return rec.Result()
|
||||
}
|
||||
secretOf := func(res *http.Response) string {
|
||||
t.Helper()
|
||||
var body struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if res.StatusCode != http.StatusCreated || json.NewDecoder(res.Body).Decode(&body) != nil || body.Token == "" {
|
||||
t.Fatalf("mint = %d", res.StatusCode)
|
||||
}
|
||||
return body.Token
|
||||
}
|
||||
|
||||
agent := secretOf(mint(env, "servers:write"))
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/_servers/api/v1/ping", agent, nil)
|
||||
reader := secretOf(mint(env, "read"))
|
||||
rec := env.expect(t, http.StatusForbidden, http.MethodGet, "/_servers/api/v1/ping", reader, nil)
|
||||
if !strings.Contains(rec.Body.String(), "Missing required scope: servers:write") {
|
||||
t.Fatalf("read token at the servers route = %s", rec.Body.String())
|
||||
}
|
||||
rec = env.call(t, http.MethodPost, "/_user/api/v1/tokens", session, map[string]any{"name": "nope", "scopes": []string{"servers:nope"}})
|
||||
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "The selected scope is invalid.") {
|
||||
t.Fatalf("undeclared scope = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
rec = env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/tokens", session, nil)
|
||||
if !strings.Contains(rec.Body.String(), `"servers:write"`) {
|
||||
t.Fatalf("token list = %s", rec.Body.String())
|
||||
}
|
||||
|
||||
rec = env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/tokens/scopes", session, nil)
|
||||
var listed struct {
|
||||
Data []struct {
|
||||
Name string `json:"name"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
BuiltIn bool `json:"built_in"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &listed); err != nil || len(listed.Data) != 4 {
|
||||
t.Fatalf("scopes = %s (%v)", rec.Body.String(), err)
|
||||
}
|
||||
want := []struct {
|
||||
name, label string
|
||||
builtIn bool
|
||||
}{{"read", "Read", true}, {"write", "Write", true}, {"ai", "AI", true}, {"servers:write", "Write servers", false}}
|
||||
for i, w := range want {
|
||||
got := listed.Data[i]
|
||||
if got.Name != w.name || got.Label != w.label || got.BuiltIn != w.builtIn || got.Description == "" || strings.Contains(got.Description, "::") {
|
||||
t.Fatalf("scope %d = %+v, want %+v", i, got, w)
|
||||
}
|
||||
}
|
||||
env.expect(t, http.StatusUnauthorized, http.MethodGet, "/_user/api/v1/tokens/scopes", "", nil)
|
||||
|
||||
// A second application without the declaring plugin refuses it.
|
||||
other := newAdminEnv(t)
|
||||
rec = other.call(t, http.MethodPost, "/_user/api/v1/tokens", session, map[string]any{"name": "other", "scopes": []string{"servers:write"}})
|
||||
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "The selected scope is invalid.") {
|
||||
t.Fatalf("second application = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, _, err := classes.MintAPITokenFor(other.app, "", user.ID, "other", []string{"servers:write"}, nil, nil); err == nil {
|
||||
t.Fatal("MintAPITokenFor accepted another application's scope")
|
||||
}
|
||||
if _, _, err := classes.MintAPITokenFor(env.app, "", user.ID, "declaring", []string{"servers:write"}, nil, nil); err != nil {
|
||||
t.Fatalf("MintAPITokenFor in the declaring application: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
280
member_token_scopes_test.go
Normal file
280
member_token_scopes_test.go
Normal file
@@ -0,0 +1,280 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
usermiddleware "git.golem15.com/golem15/sm-user-plugin/middleware"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/wire"
|
||||
)
|
||||
|
||||
// acmeInventory declares the member token scopes servers:read and
|
||||
// servers:write (E-2's acceptance values) and serves the agent's report
|
||||
// route behind the api token guard and middleware.Scope("servers:write").
|
||||
// It is registered for the test binary and activated only by
|
||||
// TestMemberTokenScopes.
|
||||
type acmeInventory struct{}
|
||||
|
||||
func (acmeInventory) ID() string { return "acme.inventory" }
|
||||
func (acmeInventory) Requires() []string { return []string{"golem15.user"} }
|
||||
func (acmeInventory) Register(*backpack.App) error { return nil }
|
||||
func (acmeInventory) Boot(*backpack.App) error { return nil }
|
||||
|
||||
func (acmeInventory) FrontendTokenScopes() []pact.FrontendTokenScope {
|
||||
return []pact.FrontendTokenScope{
|
||||
{Name: "servers:read", Label: "Read servers", Description: "Look servers up by host and port."},
|
||||
{Name: "servers:write", Label: "Report servers", Description: "Report the components of a server."},
|
||||
}
|
||||
}
|
||||
|
||||
func (acmeInventory) Routes(r pact.Router) error {
|
||||
report := usermiddleware.Scope("servers:write")(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
wire.WriteJSON(w, http.StatusOK, map[string]any{"server": req.PathValue("id"), "reported": true})
|
||||
}))
|
||||
r.Put("/_test/servers/{id}/components/report", report.ServeHTTP, "user.api_token")
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() { party.Register(acmeInventory{}) }
|
||||
|
||||
// scopeList is the GET /_user/api/v1/tokens/scopes answer.
|
||||
type scopeList struct {
|
||||
Data []struct {
|
||||
Name string `json:"name"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
BuiltIn bool `json:"built_in"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// TestMemberTokenScopes pins E-2's acceptance list item by item (each
|
||||
// subtest quotes it) with a plugin declaring servers:read and servers:write,
|
||||
// plus the per-application catalog and the legacy MintAPIToken fallback.
|
||||
// Postgres only: skipped under -short.
|
||||
func TestMemberTokenScopes(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres")
|
||||
}
|
||||
t.Cleanup(classes.ResetDeclaredAPITokenScopes)
|
||||
env := newAdminEnvWith(t, []string{"acme.inventory"})
|
||||
member := env.seedUser(t, "e2-member", nil)
|
||||
session := freshUserToken(t, member)
|
||||
mint := func(t *testing.T, scopes ...string) *http.Response {
|
||||
t.Helper()
|
||||
return env.call(t, http.MethodPost, "/_user/api/v1/tokens", session, map[string]any{"name": "agent " + adminStamp(), "scopes": scopes}).Result()
|
||||
}
|
||||
secretOf := func(t *testing.T, res *http.Response) string {
|
||||
t.Helper()
|
||||
var body struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if res.StatusCode != http.StatusCreated || json.NewDecoder(res.Body).Decode(&body) != nil || !strings.HasPrefix(body.Token, "usr_") {
|
||||
t.Fatalf("mint = %d, token %q", res.StatusCode, body.Token)
|
||||
}
|
||||
return body.Token
|
||||
}
|
||||
const report = "/_test/servers/1/components/report"
|
||||
|
||||
t.Run(`A plugin that declares servers:write can mint a usr_ token with that scope through POST /tokens, and a route with middleware.Scope("servers:write") accepts it`, func(t *testing.T) {
|
||||
agent := secretOf(t, mint(t, "servers:write"))
|
||||
rec := env.expect(t, http.StatusOK, http.MethodPut, report, agent, map[string]any{"components": []string{"cpu"}})
|
||||
if !strings.Contains(rec.Body.String(), `"reported":true`) {
|
||||
t.Fatalf("report = %s", rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run(`A token without the scope gets 403 "Missing required scope: servers:write"`, func(t *testing.T) {
|
||||
reader := secretOf(t, mint(t, "read"))
|
||||
rec := env.expect(t, http.StatusForbidden, http.MethodPut, report, reader, map[string]any{})
|
||||
var body struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Message != "Missing required scope: servers:write" {
|
||||
t.Fatalf("403 body = %s", rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An undeclared scope still answers 422 at mint time", func(t *testing.T) {
|
||||
rec := env.call(t, http.MethodPost, "/_user/api/v1/tokens", session, map[string]any{"name": "nope", "scopes": []string{"servers:delete"}})
|
||||
var body struct {
|
||||
Errors map[string][]string `json:"errors"`
|
||||
}
|
||||
if rec.Code != http.StatusUnprocessableEntity || json.Unmarshal(rec.Body.Bytes(), &body) != nil {
|
||||
t.Fatalf("undeclared scope = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := body.Errors["scopes"]; len(got) != 1 || got[0] != "The selected scope is invalid." {
|
||||
t.Fatalf("scopes errors = %v (%s)", got, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Listing returns them in scopes", func(t *testing.T) {
|
||||
name := "listed " + adminStamp()
|
||||
rec := env.call(t, http.MethodPost, "/_user/api/v1/tokens", session, map[string]any{"name": name, "scopes": []string{"servers:write"}})
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("mint = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rec = env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/tokens", session, nil)
|
||||
var listed struct {
|
||||
Data []struct {
|
||||
Name string `json:"name"`
|
||||
Scopes []string `json:"scopes"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &listed); err != nil {
|
||||
t.Fatalf("list = %s (%v)", rec.Body.String(), err)
|
||||
}
|
||||
found := false
|
||||
for _, tok := range listed.Data {
|
||||
if tok.Name == name {
|
||||
found = true
|
||||
if len(tok.Scopes) != 1 || tok.Scopes[0] != "servers:write" {
|
||||
t.Fatalf("listed scopes = %v", tok.Scopes)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("token %q not listed: %s", name, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The discovery answer lists the built-ins and the declared scopes with labels", func(t *testing.T) {
|
||||
for locale, builtIn := range map[string][3]string{"en": {"Read", "Write", "AI"}, "pl": {"Odczyt", "Zapis", "AI"}} {
|
||||
rec := env.send(t, http.MethodGet, "/_user/api/v1/tokens/scopes", session, nil, "application/json", map[string]string{"Accept-Language": locale})
|
||||
var got scopeList
|
||||
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &got) != nil || len(got.Data) != 5 {
|
||||
t.Fatalf("%s: scopes = %d %s", locale, rec.Code, rec.Body.String())
|
||||
}
|
||||
want := []struct {
|
||||
name, label string
|
||||
builtIn bool
|
||||
}{
|
||||
{"read", builtIn[0], true}, {"write", builtIn[1], true}, {"ai", builtIn[2], true},
|
||||
{"servers:read", "Read servers", false}, {"servers:write", "Report servers", false},
|
||||
}
|
||||
for i, w := range want {
|
||||
s := got.Data[i]
|
||||
if s.Name != w.name || s.Label != w.label || s.BuiltIn != w.builtIn || s.Description == "" || strings.Contains(s.Description, "::") {
|
||||
t.Fatalf("%s: scope %d = %+v, want %+v", locale, i, s, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
env.expect(t, http.StatusUnauthorized, http.MethodGet, "/_user/api/v1/tokens/scopes", "", nil)
|
||||
})
|
||||
|
||||
t.Run("Scopes are scoped to the application", func(t *testing.T) {
|
||||
appB := newAdminEnv(t)
|
||||
rec := appB.call(t, http.MethodPost, "/_user/api/v1/tokens", session, map[string]any{"name": "app b", "scopes": []string{"servers:write"}})
|
||||
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "The selected scope is invalid.") {
|
||||
t.Fatalf("app B POST /tokens = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, _, err := classes.MintAPITokenFor(appB.app, "", member.ID, "app b", []string{"servers:write"}, nil, nil); err == nil {
|
||||
t.Fatal("MintAPITokenFor(appB) accepted a scope only app A declares")
|
||||
}
|
||||
if _, _, err := classes.MintAPITokenFor(env.app, "", member.ID, "app a", []string{"servers:write"}, nil, nil); err != nil {
|
||||
t.Fatalf("MintAPITokenFor(appA): %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The legacy MintAPIToken uses the process-wide fallback", func(t *testing.T) {
|
||||
if _, _, err := classes.MintAPIToken("", member.ID, "legacy", []string{"servers:write"}, nil, nil); err != nil {
|
||||
t.Fatalf("MintAPIToken(servers:write) after a boot declared it: %v", err)
|
||||
}
|
||||
if _, _, err := classes.MintAPIToken("", member.ID, "legacy", []string{"servers:never"}, nil, nil); err == nil {
|
||||
t.Fatal("MintAPIToken accepted a never-declared scope")
|
||||
}
|
||||
classes.ResetDeclaredAPITokenScopes()
|
||||
if _, _, err := classes.MintAPIToken("", member.ID, "legacy", []string{"servers:write"}, nil, nil); err == nil {
|
||||
t.Fatal("MintAPIToken accepted servers:write after ResetDeclaredAPITokenScopes")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// scopeBootApp is an application with the user plugin's phrase catalog and
|
||||
// the given plugins as the activated list, for the scope Boot step alone.
|
||||
func scopeBootApp(t *testing.T, plugins ...party.Plugin) *backpack.App {
|
||||
t.Helper()
|
||||
app := backpack.New(nil)
|
||||
all := append([]party.Plugin{&Plugin{}}, plugins...)
|
||||
if err := phrasebook.Activate(app, all); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := app.Publish(party.Activated(all)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return app
|
||||
}
|
||||
|
||||
// TestMemberTokenScopesBoot pins the boot refusals of E-2 without a
|
||||
// database: the scope Boot step (bootAPITokenScopes, which Plugin.Boot
|
||||
// runs) fails for a name two plugins declare, naming both, for a plugin
|
||||
// redeclaring a built-in, for a bad name or an empty label, and for a
|
||||
// label naming a missing phrase key; a good declaration publishes the
|
||||
// catalog.
|
||||
func TestMemberTokenScopesBoot(t *testing.T) {
|
||||
t.Cleanup(classes.ResetDeclaredAPITokenScopes)
|
||||
scope := func(name string) []pact.FrontendTokenScope {
|
||||
return []pact.FrontendTokenScope{{Name: name, Label: "Label", Description: "Description"}}
|
||||
}
|
||||
boot := func(plugins ...party.Plugin) error {
|
||||
return (&Plugin{}).bootAPITokenScopes(scopeBootApp(t, plugins...))
|
||||
}
|
||||
|
||||
t.Run("Two plugins declaring the same scope name fails boot", func(t *testing.T) {
|
||||
err := boot(scopeDeclarer{"acme.first", scope("servers:write")}, scopeDeclarer{"acme.second", scope("servers:write")})
|
||||
if err == nil || !strings.Contains(err.Error(), "acme.first") || !strings.Contains(err.Error(), "acme.second") || !strings.Contains(err.Error(), "servers:write") {
|
||||
t.Fatalf("err = %v, want both plugin ids and the name", err)
|
||||
}
|
||||
})
|
||||
for _, builtIn := range []string{"read", "write", "ai"} {
|
||||
t.Run("a plugin redeclaring "+builtIn+" fails boot", func(t *testing.T) {
|
||||
err := boot(scopeDeclarer{"acme.redeclare", scope(builtIn)})
|
||||
if err == nil || !strings.Contains(err.Error(), "built-in") || !strings.Contains(err.Error(), `"`+builtIn+`"`) {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("a bad name fails boot", func(t *testing.T) {
|
||||
for _, name := range []string{"Servers", "servers:", "a:b:c", "with space", ""} {
|
||||
if err := boot(scopeDeclarer{"acme.bad", scope(name)}); err == nil {
|
||||
t.Fatalf("%q booted", name)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("an empty label fails boot", func(t *testing.T) {
|
||||
err := boot(scopeDeclarer{"acme.bad", []pact.FrontendTokenScope{{Name: "servers:write", Label: " ", Description: "Description"}}})
|
||||
if err == nil || !strings.Contains(err.Error(), "empty label") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("a label naming a missing phrase key fails at Boot", func(t *testing.T) {
|
||||
err := boot(scopeDeclarer{"acme.keys", []pact.FrontendTokenScope{{Name: "servers:write", Label: "acme.keys::lang.missing", Description: "Description"}}})
|
||||
if err == nil || !strings.Contains(err.Error(), "missing phrase key acme.keys::lang.missing") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("a declared phrase key and a good declaration boot", func(t *testing.T) {
|
||||
app := scopeBootApp(t, langDeclarer{scopeDeclarer{"acme.keys", []pact.FrontendTokenScope{{Name: "servers:write", Label: "acme.keys::lang.servers_write", Description: "Description"}}}})
|
||||
if err := (&Plugin{}).bootAPITokenScopes(app); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !classes.APITokenScopesFor(app).Allowed("servers:write") {
|
||||
t.Fatal("the published catalog does not allow the declared scope")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// langDeclarer is a scopeDeclarer that also ships a phrase catalog.
|
||||
type langDeclarer struct{ scopeDeclarer }
|
||||
|
||||
func (langDeclarer) LangFS() fs.FS {
|
||||
return fstest.MapFS{"lang/en/lang.yaml": {Data: []byte("servers_write: Report servers\n")}}
|
||||
}
|
||||
@@ -53,9 +53,9 @@ func TestAdminModelContracts(t *testing.T) {
|
||||
if (User{}).MorphName() != `Golem15\User\Models\User` || (Organisation{}).MorphName() != `Golem15\User\Models\Organisation` {
|
||||
t.Fatalf("morph names = %q / %q", (User{}).MorphName(), (Organisation{}).MorphName())
|
||||
}
|
||||
for name, relations := range map[string]int{"user": len((User{}).AttachRelations()), "organisation": len((Organisation{}).AttachRelations())} {
|
||||
if relations != 1 {
|
||||
t.Fatalf("%s attach relations = %d", name, relations)
|
||||
for name, want := range map[string][2]int{"user": {len((User{}).AttachRelations()), 1}, "organisation": {len((Organisation{}).AttachRelations()), 2}} {
|
||||
if want[0] != want[1] {
|
||||
t.Fatalf("%s attach relations = %d, want %d", name, want[0], want[1])
|
||||
}
|
||||
}
|
||||
if rel := (User{}).AttachRelations()[0]; AvatarField != "avatar" || rel.Name != AvatarField || !rel.Public {
|
||||
@@ -64,6 +64,9 @@ func TestAdminModelContracts(t *testing.T) {
|
||||
if rel := (Organisation{}).AttachRelations()[0]; rel.Name != OrganisationAvatarField || !rel.Public {
|
||||
t.Fatalf("organisation avatar relation = %+v", rel)
|
||||
}
|
||||
if rel := (Organisation{}).AttachRelations()[1]; OrganisationLogoField != "logo" || rel.Name != OrganisationLogoField || !rel.Public {
|
||||
t.Fatalf("organisation logo relation = %+v", rel)
|
||||
}
|
||||
|
||||
if got := (User{}).FilterScopes(); !reflect.DeepEqual(got, []string{FilterByGroup}) || FilterByGroup != "filterByGroup" {
|
||||
t.Fatalf("User.FilterScopes = %v", got)
|
||||
|
||||
@@ -34,9 +34,15 @@ func (Organisation) MorphName() string { return `Golem15\User\Models\Organisatio
|
||||
// organisation's picture.
|
||||
const OrganisationAvatarField = "avatar"
|
||||
|
||||
// AttachRelations declares the public attachOne avatar (PHP $attachOne).
|
||||
// OrganisationLogoField is the attachOne relation name of the
|
||||
// organisation's logo, the image a site shows wherever it displays the
|
||||
// organisation.
|
||||
const OrganisationLogoField = "logo"
|
||||
|
||||
// AttachRelations declares the public attachOne avatar (PHP $attachOne) and
|
||||
// the public attachOne logo.
|
||||
func (Organisation) AttachRelations() []attach.Relation {
|
||||
return []attach.Relation{{Name: OrganisationAvatarField, Public: true}}
|
||||
return []attach.Relation{{Name: OrganisationAvatarField, Public: true}, {Name: OrganisationLogoField, Public: true}}
|
||||
}
|
||||
|
||||
// Fillable is the PHP $fillable list.
|
||||
|
||||
@@ -22,6 +22,13 @@ fields:
|
||||
mode: image
|
||||
imageWidth: 120
|
||||
imageHeight: 120
|
||||
logo:
|
||||
label: golem15.user::lang.organisation.logo
|
||||
comment: golem15.user::lang.organisation.logo_comment
|
||||
type: fileupload
|
||||
mode: image
|
||||
imageWidth: 240
|
||||
imageHeight: 120
|
||||
members:
|
||||
type: relation-manager
|
||||
relation: members
|
||||
|
||||
211
organisation_logo_test.go
Normal file
211
organisation_logo_test.go
Normal file
@@ -0,0 +1,211 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob"
|
||||
"gocloud.dev/blob/memblob"
|
||||
)
|
||||
|
||||
// uploadOrganisationFile posts an image to an organisation form's file
|
||||
// field under a form session key.
|
||||
func (e *adminEnv) uploadOrganisationFile(t *testing.T, token string, id uint, field, name, sessionKey string) {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
part, err := mw.CreateFormFile("file_data", name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := part.Write(jpegBytes(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := mw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if up := e.send(t, http.MethodPost, organisationPath(id, "/files/"+field), token, buf.Bytes(), mw.FormDataContentType(), map[string]string{cabana.SessionKeyHeader: sessionKey}); up.Code != http.StatusCreated && up.Code != http.StatusOK {
|
||||
t.Fatalf("%s upload = %d %s", field, up.Code, up.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// blobKeysUnder lists the bucket's keys under prefix.
|
||||
func (e *adminEnv) blobKeysUnder(t *testing.T, prefix string) []string {
|
||||
t.Helper()
|
||||
var keys []string
|
||||
it := e.bucket.List(&blob.ListOptions{Prefix: prefix})
|
||||
for {
|
||||
obj, err := it.Next(t.Context())
|
||||
if errors.Is(err, io.EOF) {
|
||||
return keys
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys = append(keys, obj.Key)
|
||||
}
|
||||
}
|
||||
|
||||
// organisationFiles counts an organisation's system_files rows of field.
|
||||
func (e *adminEnv) organisationFiles(t *testing.T, id uint, field string) int64 {
|
||||
t.Helper()
|
||||
var n int64
|
||||
if err := e.gdb.Raw(`SELECT COUNT(*) FROM system_files WHERE attachment_type = ? AND attachment_id = ? AND field = ?`,
|
||||
(models.Organisation{}).MorphName(), strconv.FormatUint(uint64(id), 10), field).Scan(&n).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// TestOrganisationLogo pins E-1 (P-38): the Organisations form has a logo
|
||||
// fileupload right after the avatar; a logo uploaded through the admin form
|
||||
// API is stored as a system_files row with field logo; OrganisationLogoFields
|
||||
// answers has_logo, the disk name and a URL, or false and nils without a
|
||||
// logo, falling back to the original's public URL when the thumbnail fails;
|
||||
// the avatar keeps working beside it; and deleting the organisation
|
||||
// removes the logo attachment as it does the avatar, rows and blobs.
|
||||
// Postgres only.
|
||||
func TestOrganisationLogo(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Postgres")
|
||||
}
|
||||
env := newAdminEnv(t)
|
||||
token := env.admin(t, permAccessUsers)
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("the form has a logo fileupload next to the avatar", func(t *testing.T) {
|
||||
rec := env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath+"/schema/form"), token, nil)
|
||||
var schema struct {
|
||||
Data struct {
|
||||
Fields []struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
} `json:"fields"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &schema); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := -1
|
||||
for i, f := range schema.Data.Fields {
|
||||
if f.Name == "avatar" {
|
||||
at = i
|
||||
}
|
||||
}
|
||||
if at < 0 || at+1 >= len(schema.Data.Fields) || schema.Data.Fields[at+1].Name != models.OrganisationLogoField || schema.Data.Fields[at+1].Type != "fileupload" {
|
||||
t.Fatalf("form fields = %+v, want logo:fileupload right after avatar", schema.Data.Fields)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("without a logo the fields answer false and nils", func(t *testing.T) {
|
||||
org := env.seedOrganisation(t, "No Logo "+adminStamp())
|
||||
fields, err := classes.OrganisationLogoFields(ctx, env.app, org)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fields["has_logo"] != false || fields["logo"] != nil || fields["logo_url"] != nil {
|
||||
t.Fatalf("fields = %+v", fields)
|
||||
}
|
||||
if _, ok, err := classes.OrganisationLogoURL(ctx, env.app, org, 64); err != nil || ok {
|
||||
t.Fatalf("OrganisationLogoURL = %v, %v", ok, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("upload, payload fields, the avatar beside it and the delete", func(t *testing.T) {
|
||||
name := "Logo Org " + adminStamp()
|
||||
org := env.seedOrganisation(t, name)
|
||||
key := adminSessionKey(t)
|
||||
env.uploadOrganisationFile(t, token, org.ID, "avatar", "avatar.jpg", key)
|
||||
env.uploadOrganisationFile(t, token, org.ID, models.OrganisationLogoField, "logo.jpg", key)
|
||||
body, err := json.Marshal(map[string]any{"name": name, "slug": org.Slug})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if saved := env.send(t, http.MethodPut, organisationPath(org.ID, ""), token, body, "application/json", map[string]string{cabana.SessionKeyHeader: key}); saved.Code != http.StatusOK {
|
||||
t.Fatalf("save = %d %s", saved.Code, saved.Body.String())
|
||||
}
|
||||
if logos, avatars := env.organisationFiles(t, org.ID, "logo"), env.organisationFiles(t, org.ID, "avatar"); logos != 1 || avatars != 1 {
|
||||
t.Fatalf("system_files rows: logo %d, avatar %d, want 1 and 1", logos, avatars)
|
||||
}
|
||||
|
||||
fields, err := classes.OrganisationLogoFields(ctx, env.app, env.organisation(t, org.ID))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disk, _ := fields["logo"].(string)
|
||||
url, _ := fields["logo_url"].(string)
|
||||
if fields["has_logo"] != true || disk == "" || url == "" {
|
||||
t.Fatalf("fields = %+v", fields)
|
||||
}
|
||||
var logoDisk, avatarDisk string
|
||||
if err := env.gdb.Raw(`SELECT disk_name FROM system_files WHERE attachment_type = ? AND attachment_id = ? AND field = 'logo'`,
|
||||
(models.Organisation{}).MorphName(), strconv.FormatUint(uint64(org.ID), 10)).Scan(&logoDisk).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := env.gdb.Raw(`SELECT disk_name FROM system_files WHERE attachment_type = ? AND attachment_id = ? AND field = 'avatar'`,
|
||||
(models.Organisation{}).MorphName(), strconv.FormatUint(uint64(org.ID), 10)).Scan(&avatarDisk).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if disk != logoDisk || disk == avatarDisk {
|
||||
t.Fatalf("logo disk name %q, stored logo %q, avatar %q", disk, logoDisk, avatarDisk)
|
||||
}
|
||||
if strings.Contains(url, avatarDisk) {
|
||||
t.Fatalf("logo URL %q points at the avatar", url)
|
||||
}
|
||||
|
||||
// A thumbnail that cannot be made (the storage fails) falls back to
|
||||
// the original's public URL, under the public path prefix
|
||||
// (RC-IN-03).
|
||||
closed := memblob.OpenBucket(nil)
|
||||
_ = closed.Close()
|
||||
failing := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)
|
||||
if err := failing.Publish(env.gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := attach.Publish(failing, closed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, ok, err := classes.OrganisationLogoURL(ctx, failing, env.organisation(t, org.ID), 64); err != nil || !ok || got != attach.PublicURL(attach.BlobKey(logoDisk)) {
|
||||
t.Fatalf("failing logo thumbnail = %q %v %v, want %s", got, ok, err, attach.PublicURL(attach.BlobKey(logoDisk)))
|
||||
}
|
||||
|
||||
for _, disk := range []string{logoDisk, avatarDisk} {
|
||||
if keys := env.blobKeysUnder(t, attach.PartitionDirectory(disk)); len(keys) == 0 {
|
||||
t.Fatalf("no blob stored for %s before the delete", disk)
|
||||
}
|
||||
}
|
||||
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, organisationPath(org.ID, ""), token, nil)
|
||||
if logos, avatars := env.organisationFiles(t, org.ID, "logo"), env.organisationFiles(t, org.ID, "avatar"); logos != 0 || avatars != 0 {
|
||||
t.Fatalf("after the delete: logo rows %d, avatar rows %d, want none", logos, avatars)
|
||||
}
|
||||
// The blobs (originals and thumbnails) go once the delete commits
|
||||
// (RC-IN-05).
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for _, disk := range []string{logoDisk, avatarDisk} {
|
||||
for {
|
||||
keys := env.blobKeysUnder(t, attach.PartitionDirectory(disk))
|
||||
if len(keys) == 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("blobs left after the delete: %v", keys)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -95,10 +95,11 @@ func TestPasswordPublicRoutes(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("unset: Routes error %v", err)
|
||||
}
|
||||
// 18 routes up to v0.1.9, plus GET /backend-link/{code} and POST
|
||||
// /backend-link/confirm (the account link) and GET /token/me.
|
||||
if len(base) != 21 {
|
||||
t.Fatalf("unset: %d routes, want 21", len(base))
|
||||
// 18 routes up to v0.1.9, plus GET /backend-link/{code}, POST
|
||||
// /backend-link/show and POST /backend-link/confirm (the account link),
|
||||
// GET /token/me and GET /tokens/scopes.
|
||||
if len(base) != 23 {
|
||||
t.Fatalf("unset: %d routes, want 23", len(base))
|
||||
}
|
||||
seen := 0
|
||||
for _, route := range base {
|
||||
@@ -110,8 +111,8 @@ func TestPasswordPublicRoutes(t *testing.T) {
|
||||
t.Fatalf("unset: found %d of the password routes, want %d", seen, len(passwordRouteKeys))
|
||||
}
|
||||
off := withoutPasswordRoutes(base)
|
||||
if len(off) != 18 {
|
||||
t.Fatalf("base without the password routes has %d routes, want 18", len(off))
|
||||
if len(off) != 20 {
|
||||
t.Fatalf("base without the password routes has %d routes, want 20", len(off))
|
||||
}
|
||||
|
||||
for _, c := range []struct {
|
||||
|
||||
29
plugin.go
29
plugin.go
@@ -21,6 +21,7 @@ import (
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
@@ -110,12 +111,40 @@ func (p *Plugin) Boot(app *backpack.App) error {
|
||||
if err := p.bootBackendLinks(app); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.bootAPITokenScopes(app); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.bootMCPGuard(app); err != nil {
|
||||
return err
|
||||
}
|
||||
return classes.RegisterUserAuthorizer(app)
|
||||
}
|
||||
|
||||
// bootAPITokenScopes compiles the member token scope catalog from the
|
||||
// activated plugins (pact.HasFrontendTokenScopes), checks that every phrase
|
||||
// key it names exists, and publishes it. A bad declaration fails boot.
|
||||
func (p *Plugin) bootAPITokenScopes(app *backpack.App) error {
|
||||
activated, _ := app.Lookup[party.Activated]()
|
||||
catalog, err := classes.CompileAPITokenScopes(activated)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tr, ok := app.Lookup[*phrasebook.Translator](); ok && tr != nil {
|
||||
for _, scope := range catalog.Scopes() {
|
||||
for _, text := range []string{scope.Label, scope.Description} {
|
||||
if strings.Contains(text, "::") && !tr.Has(text) {
|
||||
who := scope.PluginID
|
||||
if who == "" {
|
||||
who = "golem15.user"
|
||||
}
|
||||
return fmt.Errorf("golem15.user: member token scope %s (%s) names missing phrase key %s", scope.Name, who, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return app.Publish(catalog)
|
||||
}
|
||||
|
||||
// bootMCPGuard registers the "user" MCP guard provider in the application's
|
||||
// *pact.MCPGuards (publishing the registry when no one did yet) and
|
||||
// publishes the same value as pact.MCPPersonalTokenResolver for the
|
||||
|
||||
@@ -40,10 +40,12 @@ func (p *Plugin) Routes(r pact.Router) error {
|
||||
g.Post("/avatar/remove", controllers.RemoveAvatar(p.app))
|
||||
g.Post("/tokens", controllers.APITokenStore(p.app), "jwt.auth")
|
||||
g.Get("/tokens", controllers.APITokenIndex(p.app), "jwt.auth")
|
||||
g.Get("/tokens/scopes", controllers.APITokenScopes(p.app), "jwt.auth")
|
||||
g.Delete("/tokens/{id}", controllers.APITokenDestroy(p.app), "jwt.auth")
|
||||
g.Where("id", "[0-9]+")
|
||||
g.Get("/backend-link/{code}", controllers.BackendLinkShow(p.app))
|
||||
g.Where("code", "[a-f0-9]{64}")
|
||||
g.Post("/backend-link/show", controllers.BackendLinkShowPost(p.app))
|
||||
g.Post("/backend-link/confirm", controllers.BackendLinkConfirm(p.app), "jwt.auth")
|
||||
g.Get("/token/me", controllers.TokenMe(p.app), "user.api_token", "user.scope:read")
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user