Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 50da92c1fb | |||
| 0428093d33 | |||
| 98924041c9 | |||
| ebe408f542 | |||
| 9730110d55 | |||
| b929ba9f33 | |||
| 92676ba14e | |||
| 30f7a01d3d | |||
| 38551a4104 | |||
| e3c164fdf0 | |||
| 25b9f2e35c | |||
|
|
f20a8d3b98 | ||
|
|
ee5c096d0d | ||
|
|
970719ce75 | ||
|
|
32f92591d6 | ||
|
|
72de822a84 | ||
|
|
bfcfea4ed7 | ||
|
|
59cc3bde2e | ||
|
|
dbb3d33b48 | ||
|
|
6f1cb1a774 | ||
|
|
0f545f5c81 | ||
|
|
7ac80c9aea |
64
README.md
64
README.md
@@ -12,7 +12,7 @@ Module `git.golem15.com/golem15/sm-user-plugin`, package `user`, plugin ID `gole
|
||||
|
||||
The plugin is a compiled SummerCMS plugin. Its `init` registers it with the framework, so an application loads it by listing it in `summer.yaml`; `summer build` then emits the blank import above into the application's `plugins.gen.go`.
|
||||
|
||||
It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_api_tokens`, `golem15_user_oauth_identities`, `golem15_user_organisations`, `user_groups`, `users_groups` and `golem15_user_frontend_permissions`, the JSON API under `/_user/api/v1`, and the Users, User Groups and Organisations screens of the admin. It is a core plugin shared by several applications, so its routes, payloads, table names, migration IDs, permission codes and config keys are a contract: change them only in a backwards-compatible way.
|
||||
It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_api_tokens`, `golem15_user_oauth_identities`, `golem15_user_organisations`, `user_groups`, `users_groups`, `golem15_user_frontend_permissions`, `golem15_user_backend_links` and `golem15_user_backend_link_requests`, the JSON API under `/_user/api/v1`, and the Users, User Groups and Organisations screens of the admin. It is a core plugin shared by several applications, so its routes, payloads, table names, migration IDs, permission codes and config keys are a contract: change them only in a backwards-compatible way.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -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,10 +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`) + `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.
|
||||
- **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
|
||||
@@ -106,12 +122,19 @@ 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` (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`) |
|
||||
|
||||
`/fetch`, `/refresh`, `/update`, `/change-password`, `/activate`, `/marketing-consent`, `/avatar`, `/avatar/remove` and the `jwt.auth` routes read the session token from the bearer header, then the `token` and `auth_token` cookies.
|
||||
|
||||
With `golem15.user.password.public_routes` false the `/login`, `/forgot-password` and `/reset-password` rows are not registered.
|
||||
|
||||
`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
|
||||
|
||||
The host application mounts these constructors on a path it chooses. They are not registered under `/_user/api/v1`. `OAuthIdentitiesOptions.WriteNotFound` is the host's 404 writer so missing, foreign and unknown providers share one body. `OAuthIdentitiesOptions.Providers` is the unlink allow-list; when empty it is read on every request from a published `classes.OAuthProviderSource` (its `KnownOAuthProviders`), else it is `google`, `facebook`, `github` and `microsoft`. Unlinking follows the PHP rule: it succeeds when the user has a self-set password (`has_self_set_password`) or another identity remains, and otherwise answers 409 with the phrase `golem15.user::lang.oauth.last_method_blocked` (body unchanged). The guarded delete runs in a transaction that first locks the user's `users` row, so two concurrent unlinks never remove the last sign-in method.
|
||||
@@ -133,6 +156,10 @@ The three screens are served by the framework's generic admin API under `<admin
|
||||
| Relation manager | `members` on `golem15.user.organisations` (link and unlink) |
|
||||
| Bulk actions (Users) | `activate`, `deactivate`, `restore`, `ban`, `unban`, and the built-in delete; `deactivate` and `ban` also revoke the selected users' sessions and personal API tokens |
|
||||
| Record actions (Users) | `activate`, `unban`, `unsuspend` |
|
||||
| Record actions (Administrators, `summercms.cabana.users`) | `link_frontend_account` (asks for the frontend user's email) and `unlink_frontend_account` (danger), both behind `golem15.users.manage_backend_links`, from `AdminActionExtensions` |
|
||||
| My account section | `frontend_account` with the actions `link` and `unlink`, from `AccountContributions` |
|
||||
|
||||
On the Administrators screen, `link_frontend_account` links the activated, not deactivated frontend user whose email equals the typed value (letter case and surrounding spaces ignored; no search and no list) to the administrator shown, and records the caller in `linked_by`. An unknown email or an account that is already linked answers 422 on the input. It is offered only while the administrator has no link, and `unlink_frontend_account` only while it has one. The admin's own rule that an administrator cannot act on one whose grants exceed theirs runs first. These two actions skip the frontend user's sign-in proof, which is why their permission has no default role; the My account path always requires it.
|
||||
|
||||
Backend permissions, all on the tab `golem15.user::lang.plugin.tab`:
|
||||
|
||||
@@ -143,6 +170,7 @@ Backend permissions, all on the tab `golem15.user::lang.plugin.tab`:
|
||||
| `golem15.users.access_settings` | `developer` | Registered for roles that already name it; no screen uses it yet. |
|
||||
| `golem15.users.impersonate_user` | `developer` | Registered for roles that already name it; impersonation is not available. |
|
||||
| `golem15.users.manage_privileged_groups` | none | Adding a privileged group to a user or removing it; creating, re-coding or deleting a privileged group; changing the email or password of a privileged-group member, and deleting one for good. Only a superuser or a role that was granted it holds it. |
|
||||
| `golem15.users.manage_backend_links` | none | Linking a frontend account to another administrator, and unlinking one, on the Administrators screen. Only a superuser or a role that was granted it holds it. |
|
||||
|
||||
Migrations added for the admin, all additive:
|
||||
|
||||
@@ -170,6 +198,12 @@ Migrations added for address proof, all additive:
|
||||
|----|------|
|
||||
| `202610210001_add_users_email_verified_at` | `users.email_verified_at` (`TIMESTAMPTZ` NULL, `ADD COLUMN IF NOT EXISTS`, no backfill; rollback is a no-op) |
|
||||
|
||||
Migrations added for the frontend account link, all additive:
|
||||
|
||||
| ID | Adds |
|
||||
|----|------|
|
||||
| `202610220001_create_golem15_user_backend_links` | the tables `golem15_user_backend_links` (`user_id` unique, cascade FK to `users`; `backend_user_id` unique, cascade FK to `backend_users`; `linked_by` FK to `backend_users`, set null on delete; `created_at`) and `golem15_user_backend_link_requests` (`code_hash` `CHAR(64)` unique, `backend_user_id` cascade FK, `expires_at`, `used_at`, `created_at`). The `backend_users` keys are added when that table exists, which it does whenever the application migrates through `lagoon.Migrate`. |
|
||||
|
||||
Packages:
|
||||
|
||||
- `controllers`: the route handlers above, `AdminControllers` (the admin controller list), `PermissionAccessUsers` and `PermissionAccessGroups`, plus the registration steps `POST /register` runs, for other plugins:
|
||||
@@ -179,24 +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`, `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.
|
||||
- `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` 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`.
|
||||
|
||||
@@ -227,6 +266,9 @@ 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 + `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. |
|
||||
|
||||
## CLI commands
|
||||
@@ -243,7 +285,7 @@ Each command uses the database the serve command published or, run from the cons
|
||||
|
||||
## Dependencies
|
||||
|
||||
- The SummerCMS framework v0.4.3, `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.
|
||||
@@ -281,4 +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. `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)
|
||||
}
|
||||
})
|
||||
}
|
||||
140
account_contributions.go
Normal file
140
account_contributions.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"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/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var _ pact.HasAccountContributions = (*Plugin)(nil)
|
||||
|
||||
// backendLinkLang prefixes the phrase keys of the account link.
|
||||
const backendLinkLang = "golem15.user::lang.backend_link."
|
||||
|
||||
// AccountContributions adds the "Frontend account" section to the admin's
|
||||
// My account page (D-04): its status names the linked frontend account,
|
||||
// "link" starts a link request and answers the site URL the administrator
|
||||
// opens to sign in there as the frontend user and confirm (D-05; the link is
|
||||
// written only by that confirmation), and "unlink" removes the link.
|
||||
func (p *Plugin) AccountContributions() []pact.AccountContribution {
|
||||
return []pact.AccountContribution{{
|
||||
Name: "frontend_account",
|
||||
Label: backendLinkLang + "section",
|
||||
Description: backendLinkLang + "section_comment",
|
||||
Status: p.frontendAccountStatus,
|
||||
Actions: []pact.AccountAction{
|
||||
{
|
||||
Name: "link",
|
||||
Label: backendLinkLang + "link",
|
||||
Applies: func(ctx context.Context, adminID uint) (bool, error) {
|
||||
link, err := p.backendLinks().LinkFor(ctx, adminID)
|
||||
return link == nil, err
|
||||
},
|
||||
Run: p.startFrontendLink,
|
||||
},
|
||||
{
|
||||
Name: "unlink",
|
||||
Label: backendLinkLang + "unlink",
|
||||
Confirm: backendLinkLang + "unlink_confirm",
|
||||
Danger: true,
|
||||
Applies: func(ctx context.Context, adminID uint) (bool, error) {
|
||||
link, err := p.backendLinks().LinkFor(ctx, adminID)
|
||||
return link != nil, err
|
||||
},
|
||||
Run: p.unlinkOwnFrontendAccount,
|
||||
},
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// backendLinks returns the published link service, or one over the app.
|
||||
func (p *Plugin) backendLinks() *classes.BackendLinks {
|
||||
return classes.BackendLinksFor(p.app)
|
||||
}
|
||||
|
||||
// frontendAccountStatus answers "Linked to <email>" or "Not linked" in the
|
||||
// request locale for the signed-in administrator.
|
||||
func (p *Plugin) frontendAccountStatus(ctx context.Context, adminID uint) (string, error) {
|
||||
link, err := p.backendLinks().LinkFor(ctx, adminID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if link == nil {
|
||||
return backendLinkLang + "status_unlinked", nil
|
||||
}
|
||||
email, err := p.frontendEmail(ctx, link.UserID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
const key = backendLinkLang + "status_linked"
|
||||
if p.app != nil {
|
||||
if tr, ok := p.app.Lookup[*phrasebook.Translator](); ok && tr != nil {
|
||||
if text := tr.Get(ctx, key, map[string]string{"email": email}); text != "" && text != key {
|
||||
return text, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "Linked to " + email, nil
|
||||
}
|
||||
|
||||
// frontendEmail reads the email of a frontend user, deactivated or not.
|
||||
func (p *Plugin) frontendEmail(ctx context.Context, userID uint) (string, error) {
|
||||
var db *gorm.DB
|
||||
if tx, ok := cabana.TxFromContext(ctx); ok {
|
||||
db = tx.Session(&gorm.Session{NewDB: true})
|
||||
} else if p.app != nil {
|
||||
db, _ = p.app.Lookup[*gorm.DB]()
|
||||
}
|
||||
if db == nil {
|
||||
return "", errors.New("golem15.user: gorm handle is missing")
|
||||
}
|
||||
var emails []string
|
||||
if err := db.WithContext(ctx).Unscoped().Model(&models.User{}).Where("id = ?", userID).Pluck("email", &emails).Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(emails) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
return emails[0], nil
|
||||
}
|
||||
|
||||
// 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), 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 {
|
||||
return pact.AccountActionResult{}, err
|
||||
}
|
||||
return pact.AccountActionResult{
|
||||
Message: backendLinkLang + "link_started",
|
||||
URL: classes.FrontendURL(p.app) + classes.BackendLinkPagePath(p.app) + "#code=" + plain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// unlinkOwnFrontendAccount removes the signed-in administrator's link in
|
||||
// the action's transaction.
|
||||
func (p *Plugin) unlinkOwnFrontendAccount(ctx context.Context, in pact.AccountActionInput) (pact.AccountActionResult, error) {
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return pact.AccountActionResult{}, errors.New("golem15.user: unlinking needs the action's transaction")
|
||||
}
|
||||
links := p.backendLinks()
|
||||
link, err := links.LinkFor(ctx, in.AdminID)
|
||||
if err != nil {
|
||||
return pact.AccountActionResult{}, err
|
||||
}
|
||||
if err := links.RemoveLink(ctx, tx, link); err != nil {
|
||||
return pact.AccountActionResult{}, err
|
||||
}
|
||||
return pact.AccountActionResult{Message: backendLinkLang + "unlinked"}, nil
|
||||
}
|
||||
@@ -163,6 +163,13 @@ func adminEnvConfig(t *testing.T) *compass.Config {
|
||||
// newAdminEnv boots the plugin alone with the admin API mounted. configure
|
||||
// functions adjust the config before the plugin is activated.
|
||||
func newAdminEnv(t *testing.T, configure ...func(*compass.Config)) *adminEnv {
|
||||
t.Helper()
|
||||
return newAdminEnvWith(t, nil, configure...)
|
||||
}
|
||||
|
||||
// newAdminEnvWith is newAdminEnv with more registered plugins activated
|
||||
// after golem15.user, by ID.
|
||||
func newAdminEnvWith(t *testing.T, extra []string, configure ...func(*compass.Config)) *adminEnv {
|
||||
t.Helper()
|
||||
gdb, sqlDB := adminHarnessDB(t)
|
||||
app := backpack.New(adminEnvConfig(t))
|
||||
@@ -180,7 +187,7 @@ func newAdminEnv(t *testing.T, configure ...func(*compass.Config)) *adminEnv {
|
||||
}
|
||||
// The registered plugin value is shared by every boot in this binary;
|
||||
// its blacklist sweep is started at most once and is harmless here.
|
||||
plugins, err := party.Activate(app, []string{"golem15.user"})
|
||||
plugins, err := party.Activate(app, append([]string{"golem15.user"}, extra...))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -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" {
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
package user
|
||||
|
||||
import "git.golem15.com/golem15/summercms/modules/pact"
|
||||
import (
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
const userPermissionTab = "golem15.user::lang.plugin.tab"
|
||||
|
||||
// Permissions is the plugin's Winter registerPermissions() catalog plus one
|
||||
// code of its own. The four PHP codes default to the developer role;
|
||||
// Permissions is the plugin's Winter registerPermissions() catalog plus two
|
||||
// codes of its own. The four PHP codes default to the developer role;
|
||||
// impersonate_user is registered so imported backend roles that name it stay
|
||||
// valid, although no screen uses it. The fifth code
|
||||
// (classes.PermissionManagePrivilegedGroups) has no default role: only a
|
||||
// superuser, or a role that was granted it explicitly, may change the email
|
||||
// or password of a privileged-group member or delete one.
|
||||
// or password of a privileged-group member or delete one. The sixth
|
||||
// (classes.PermissionManageBackendLinks) has no default role either: it
|
||||
// links and unlinks another administrator's frontend account on the
|
||||
// Administrators screen.
|
||||
func (*Plugin) Permissions() []pact.Permission {
|
||||
return []pact.Permission{
|
||||
{
|
||||
@@ -42,5 +48,10 @@ func (*Plugin) Permissions() []pact.Permission {
|
||||
Tab: userPermissionTab,
|
||||
Label: "golem15.user::lang.plugin.manage_privileged_groups",
|
||||
},
|
||||
{
|
||||
Code: classes.PermissionManageBackendLinks,
|
||||
Tab: userPermissionTab,
|
||||
Label: "golem15.user::lang.plugin.manage_backend_links",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ var langKey = regexp.MustCompile(`golem15\.user::lang\.[a-z0-9_]+(\.[a-z0-9_]+)+
|
||||
func TestAdminRegistration(t *testing.T) {
|
||||
plugin := &Plugin{}
|
||||
|
||||
// The five permission codes, each on the plugin's tab.
|
||||
// The six permission codes, each on the plugin's tab.
|
||||
var codes []string
|
||||
for _, permission := range plugin.Permissions() {
|
||||
codes = append(codes, permission.Code)
|
||||
@@ -40,14 +40,15 @@ func TestAdminRegistration(t *testing.T) {
|
||||
wantCodes := []string{
|
||||
"golem15.users.access_users", "golem15.users.access_groups", "golem15.users.access_settings",
|
||||
"golem15.users.impersonate_user", "golem15.users.manage_privileged_groups",
|
||||
"golem15.users.manage_backend_links",
|
||||
}
|
||||
if !reflect.DeepEqual(codes, wantCodes) {
|
||||
t.Fatalf("permission codes = %v, want %v", codes, wantCodes)
|
||||
}
|
||||
// The privileged-groups permission has no default role: nobody holds it
|
||||
// until it is granted on purpose.
|
||||
// The privileged-groups and backend-links permissions have no default
|
||||
// role: nobody holds them until they are granted on purpose.
|
||||
for _, permission := range plugin.Permissions() {
|
||||
if privileged := permission.Code == permManagePrivileged; privileged != (len(permission.Roles) == 0) {
|
||||
if privileged := permission.Code == permManagePrivileged || permission.Code == permManageBackendLinks; privileged != (len(permission.Roles) == 0) {
|
||||
t.Fatalf("permission %s has roles %v", permission.Code, permission.Roles)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ func TestAdminUsersTracer(t *testing.T) {
|
||||
if want := []string{
|
||||
"golem15.users.access_users@developer", "golem15.users.access_groups@developer",
|
||||
"golem15.users.access_settings@developer", "golem15.users.impersonate_user@developer",
|
||||
classes.PermissionManagePrivilegedGroups + "@-",
|
||||
classes.PermissionManagePrivilegedGroups + "@-", classes.PermissionManageBackendLinks + "@-",
|
||||
}; !reflect.DeepEqual(codes, want) || classes.PermissionManagePrivilegedGroups != permManagePrivileged {
|
||||
t.Fatalf("permissions = %v", codes)
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
151
backend_link_admin_smoke_test.go
Normal file
151
backend_link_admin_smoke_test.go
Normal file
@@ -0,0 +1,151 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"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/pact"
|
||||
)
|
||||
|
||||
const permManageBackendLinks = "golem15.users.manage_backend_links"
|
||||
|
||||
// administratorPath is the admin API path of one administrator on the
|
||||
// Administrators screen, with an optional suffix.
|
||||
func administratorPath(id uint, suffix string) string {
|
||||
return adminAPI("/summercms/cabana/users/" + strconv.FormatUint(uint64(id), 10) + suffix)
|
||||
}
|
||||
|
||||
// superAdmin is admin with the superuser flag set.
|
||||
func (e *adminEnv) superAdmin(t *testing.T) string {
|
||||
t.Helper()
|
||||
token := e.admin(t)
|
||||
if err := e.gdb.Exec(`UPDATE backend_users SET is_superuser = TRUE WHERE id = ?`, adminID(t, token)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
// administratorActions returns the record actions the Administrators screen
|
||||
// offers on an administrator.
|
||||
func (e *adminEnv) administratorActions(t *testing.T, token string, id uint) []string {
|
||||
t.Helper()
|
||||
rec := e.expect(t, http.StatusOK, http.MethodGet, administratorPath(id, ""), token, nil)
|
||||
var meta struct {
|
||||
Actions []struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"actions"`
|
||||
}
|
||||
if err := json.Unmarshal(adminDecode(t, rec).Meta, &meta); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names := []string{}
|
||||
for _, action := range meta.Actions {
|
||||
if strings.HasSuffix(action.Name, "frontend_account") {
|
||||
names = append(names, action.Name)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// TestBackendLinkAdminSmoke: on the Administrators screen an administrator
|
||||
// with golem15.users.manage_backend_links links a frontend account to
|
||||
// another administrator by its exact email (any letter case) and unlinks
|
||||
// it; linked_by records the caller, the event fires, a taken or unknown
|
||||
// account is a 422 on the prompt, and an administrator without the
|
||||
// permission is neither offered the actions nor allowed to run them.
|
||||
func TestBackendLinkAdminSmoke(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
var mu sync.Mutex
|
||||
var linked []models.BackendLink
|
||||
env.app.Events.Listen("test.backend_linked", func(_ context.Context, e *classes.BackendLinkedEvent) error {
|
||||
mu.Lock()
|
||||
linked = append(linked, *e.Link)
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
stamp := adminStamp()
|
||||
editor := env.seedUser(t, "editor", func(u *models.User) { u.Email = "editor-" + stamp + "@example.test" })
|
||||
second := env.seedUser(t, "second", nil)
|
||||
targetToken := env.admin(t)
|
||||
target := adminID(t, targetToken)
|
||||
super := env.superAdmin(t)
|
||||
superID := adminID(t, super)
|
||||
resolver, _ := env.app.Lookup[pact.MCPLinkedBackendResolver]()
|
||||
|
||||
if got := env.administratorActions(t, super, target); !slices.Equal(got, []string{"link_frontend_account"}) {
|
||||
t.Fatalf("offered before the link = %v", got)
|
||||
}
|
||||
link := func(token, value string) *http.Response {
|
||||
t.Helper()
|
||||
rec := env.call(t, http.MethodPost, administratorPath(target, "/actions/link_frontend_account"), token, map[string]any{"payload": value})
|
||||
return rec.Result()
|
||||
}
|
||||
|
||||
// Unknown email: 422 on payload with the unknown_user text.
|
||||
rec := env.call(t, http.MethodPost, administratorPath(target, "/actions/link_frontend_account"), super, map[string]any{"payload": "nobody-" + stamp + "@example.test"})
|
||||
if rec.Code != http.StatusUnprocessableEntity || !slices.Contains(adminDecode(t, rec).Error.Details["payload"], "No active frontend user has this email.") {
|
||||
t.Fatalf("unknown email = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// The email matches whatever its letter case.
|
||||
if res := link(super, " Editor-"+stamp+"@Example.TEST "); res.StatusCode != http.StatusOK {
|
||||
t.Fatalf("set = %d", res.StatusCode)
|
||||
}
|
||||
var row models.BackendLink
|
||||
if err := env.gdb.Where("backend_user_id = ?", target).Take(&row).Error; err != nil || row.UserID != editor.ID || row.LinkedBy == nil || *row.LinkedBy != superID {
|
||||
t.Fatalf("link row = %+v %v", row, err)
|
||||
}
|
||||
if got, found, err := resolver.LinkedBackendUser(context.Background(), editor.ID); err != nil || !found || got.ID != target {
|
||||
t.Fatalf("LinkedBackendUser = %+v %v %v", got, found, err)
|
||||
}
|
||||
mu.Lock()
|
||||
if len(linked) != 1 || linked[0].UserID != editor.ID || linked[0].BackendUserID != target {
|
||||
t.Fatalf("BackendLinkedEvent saw %+v", linked)
|
||||
}
|
||||
mu.Unlock()
|
||||
if got := env.administratorActions(t, super, target); !slices.Equal(got, []string{"unlink_frontend_account"}) {
|
||||
t.Fatalf("offered after the link = %v", got)
|
||||
}
|
||||
|
||||
// The administrator is linked: a second set no longer applies (409),
|
||||
// and the same frontend user cannot be linked to another administrator.
|
||||
if res := link(super, second.Email); res.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("second set on a linked administrator = %d", res.StatusCode)
|
||||
}
|
||||
otherToken := env.admin(t)
|
||||
other := adminID(t, otherToken)
|
||||
rec = env.call(t, http.MethodPost, administratorPath(other, "/actions/link_frontend_account"), super, map[string]any{"payload": editor.Email})
|
||||
if rec.Code != http.StatusUnprocessableEntity || !slices.Contains(adminDecode(t, rec).Error.Details["payload"], "This administrator or this frontend user is already linked.") {
|
||||
t.Fatalf("frontend user linked twice = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Without the permission: not offered, and refused.
|
||||
limited := env.admin(t, cabana.PermissionManageUsers)
|
||||
if got := env.administratorActions(t, limited, target); len(got) != 0 {
|
||||
t.Fatalf("limited administrator is offered %v", got)
|
||||
}
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, administratorPath(target, "/actions/unlink_frontend_account"), limited, map[string]any{})
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, administratorPath(other, "/actions/link_frontend_account"), limited, map[string]any{"payload": second.Email})
|
||||
manager := env.admin(t, cabana.PermissionManageUsers, permManageBackendLinks)
|
||||
if got := env.administratorActions(t, manager, target); !slices.Equal(got, []string{"unlink_frontend_account"}) {
|
||||
t.Fatalf("manager is offered %v", got)
|
||||
}
|
||||
|
||||
// Unlink.
|
||||
env.expect(t, http.StatusOK, http.MethodPost, administratorPath(target, "/actions/unlink_frontend_account"), manager, map[string]any{})
|
||||
if _, found, err := resolver.LinkedBackendUser(context.Background(), editor.ID); err != nil || found {
|
||||
t.Fatalf("after unlink found=%v err=%v", found, err)
|
||||
}
|
||||
if got := env.administratorActions(t, super, target); !slices.Equal(got, []string{"link_frontend_account"}) {
|
||||
t.Fatalf("offered after the unlink = %v", got)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
279
backend_link_smoke_test.go
Normal file
279
backend_link_smoke_test.go
Normal file
@@ -0,0 +1,279 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// subjectSpy records the pact.MCPSubjectChanged events fired on an app.
|
||||
type subjectSpy struct {
|
||||
mu sync.Mutex
|
||||
events []pact.MCPSubjectChanged
|
||||
}
|
||||
|
||||
func (s *subjectSpy) has(guard string, id uint, kind string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
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
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// spySubjects listens for the subject events the plugin fires.
|
||||
func (e *adminEnv) spySubjects() *subjectSpy {
|
||||
spy := &subjectSpy{}
|
||||
e.app.Events.Listen("test.subjects", func(_ context.Context, ev *pact.MCPSubjectChanged) error {
|
||||
spy.mu.Lock()
|
||||
spy.events = append(spy.events, *ev)
|
||||
spy.mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
return spy
|
||||
}
|
||||
|
||||
// adminID is the backend user id inside an admin session token.
|
||||
func adminID(t *testing.T, token string) uint {
|
||||
t.Helper()
|
||||
sub, _, _, _, err := bouncer.VerifyClaimsAudience(token, adminHarnessSecret, bouncer.AudienceBackend)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := strconv.ParseUint(sub, 10, 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return uint(id)
|
||||
}
|
||||
|
||||
// adminLogin reads an administrator's login.
|
||||
func (e *adminEnv) adminLogin(t *testing.T, id uint) string {
|
||||
t.Helper()
|
||||
var login string
|
||||
if err := e.gdb.Raw(`SELECT login FROM backend_users WHERE id = ?`, id).Scan(&login).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return login
|
||||
}
|
||||
|
||||
// freshUserToken mints a frontend session token issued now.
|
||||
func freshUserToken(t *testing.T, user *models.User) string {
|
||||
t.Helper()
|
||||
token, _, err := bouncer.Mint(sessionSecret, strconv.FormatUint(uint64(user.ID), 10), "https://app.example.test", time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
// accountSection is one My account contribution as the admin API lists it.
|
||||
type accountSection struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Actions []struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"actions"`
|
||||
}
|
||||
|
||||
func (s accountSection) actions() []string {
|
||||
out := []string{}
|
||||
for _, a := range s.Actions {
|
||||
out = append(out, a.Name)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// frontendSection lists My account and returns the frontend_account section.
|
||||
func (e *adminEnv) frontendSection(t *testing.T, token string) accountSection {
|
||||
t.Helper()
|
||||
var sections []accountSection
|
||||
adminInto(t, e.expect(t, http.StatusOK, http.MethodGet, adminAPI("/account/contributions"), token, nil), §ions)
|
||||
for _, s := range sections {
|
||||
if s.Name == "frontend_account" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
t.Fatalf("My account has no frontend_account section: %+v", sections)
|
||||
return accountSection{}
|
||||
}
|
||||
|
||||
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 {
|
||||
t.Helper()
|
||||
var out struct {
|
||||
Message string `json:"message"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
adminInto(t, e.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/link"), token, map[string]any{}), &out)
|
||||
m := linkURL.FindStringSubmatch(out.URL)
|
||||
if m == nil || out.Message == "" {
|
||||
t.Fatalf("link action answered %+v", out)
|
||||
}
|
||||
return m[1]
|
||||
}
|
||||
|
||||
// confirmLink posts the code as the frontend session token.
|
||||
func (e *adminEnv) confirmLink(t *testing.T, userToken, code string) (int, string) {
|
||||
t.Helper()
|
||||
rec := e.call(t, http.MethodPost, "/_user/api/v1/backend-link/confirm", userToken, map[string]string{"code": code})
|
||||
return rec.Code, rec.Body.String()
|
||||
}
|
||||
|
||||
// TestBackendLinkSmoke: an administrator starts a link on My account, the
|
||||
// site shows who asked, a session older than the request is refused, a
|
||||
// fresh one links the accounts (the published resolver answers), the code is
|
||||
// one-shot, the 1:1 rule holds, unlink and deleting the frontend user remove
|
||||
// the link, and the subject events fire.
|
||||
func TestBackendLinkSmoke(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
spy := env.spySubjects()
|
||||
frontend := env.seedUser(t, "linker", nil)
|
||||
other := env.seedUser(t, "linker-other", nil)
|
||||
token := env.admin(t)
|
||||
id := adminID(t, token)
|
||||
login := env.adminLogin(t, id)
|
||||
links, ok := env.app.Lookup[*classes.BackendLinks]()
|
||||
if !ok || links == nil {
|
||||
t.Fatal("*classes.BackendLinks is not published")
|
||||
}
|
||||
resolver, ok := env.app.Lookup[pact.MCPLinkedBackendResolver]()
|
||||
if !ok || resolver == nil {
|
||||
t.Fatal("pact.MCPLinkedBackendResolver is not published")
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
section := env.frontendSection(t, token)
|
||||
if section.Status != "Not linked" || !slices.Equal(section.actions(), []string{"link"}) {
|
||||
t.Fatalf("unlinked section = %+v", section)
|
||||
}
|
||||
|
||||
code := env.startLink(t, token)
|
||||
rec := env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/backend-link/"+code, "", nil)
|
||||
var shown struct {
|
||||
Data struct {
|
||||
Admin map[string]any `json:"admin"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &shown); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if shown.Data.Admin["login"] != login || shown.Data.Admin["name"] != login || len(shown.Data.Admin) != 2 {
|
||||
t.Fatalf("show = %s", rec.Body.String())
|
||||
}
|
||||
if expires, err := time.Parse(time.RFC3339, shown.Data.ExpiresAt); err != nil || time.Until(expires) < 9*time.Minute || time.Until(expires) > 11*time.Minute {
|
||||
t.Fatalf("expires_at = %q (%v)", shown.Data.ExpiresAt, err)
|
||||
}
|
||||
env.expect(t, http.StatusNotFound, http.MethodGet, "/_user/api/v1/backend-link/"+strings.Repeat("0", 64), "", nil)
|
||||
|
||||
// A session signed in before the request is refused: sign in again.
|
||||
stale := craftToken(t, strconv.FormatUint(uint64(frontend.ID), 10), "stale-"+adminStamp(), time.Now().Add(-time.Hour), time.Now().Add(time.Hour))
|
||||
if status, body := env.confirmLink(t, stale, code); status != http.StatusConflict || !strings.Contains(body, `"stale_session"`) {
|
||||
t.Fatalf("stale confirm = %d %s", status, body)
|
||||
}
|
||||
if status, _ := env.confirmLink(t, "", code); status != http.StatusUnauthorized {
|
||||
t.Fatalf("anonymous confirm = %d", status)
|
||||
}
|
||||
|
||||
spy.reset()
|
||||
status, body := env.confirmLink(t, freshUserToken(t, frontend), code)
|
||||
if status != http.StatusOK || !strings.Contains(body, `"login":"`+login+`"`) {
|
||||
t.Fatalf("fresh confirm = %d %s", status, body)
|
||||
}
|
||||
linked, found, err := resolver.LinkedBackendUser(ctx, frontend.ID)
|
||||
if err != nil || !found || linked.ID != id || linked.Login != login || linked.DisplayName != login {
|
||||
t.Fatalf("LinkedBackendUser = %+v %v %v", linked, found, err)
|
||||
}
|
||||
if !spy.has("user", frontend.ID, pact.MCPSubjectLink) || !spy.has("backend", id, pact.MCPSubjectLink) {
|
||||
t.Fatalf("confirm fired %+v", spy.events)
|
||||
}
|
||||
var row models.BackendLink
|
||||
if err := env.gdb.Where("user_id = ?", frontend.ID).Take(&row).Error; err != nil || row.BackendUserID != id || row.LinkedBy != nil {
|
||||
t.Fatalf("link row = %+v %v", row, err)
|
||||
}
|
||||
section = env.frontendSection(t, token)
|
||||
if !strings.Contains(section.Status, frontend.Email) || !slices.Equal(section.actions(), []string{"unlink"}) {
|
||||
t.Fatalf("linked section = %+v", section)
|
||||
}
|
||||
|
||||
// The code is one-shot.
|
||||
if status, _ := env.confirmLink(t, freshUserToken(t, frontend), code); status != http.StatusNotFound {
|
||||
t.Fatalf("replayed confirm = %d", status)
|
||||
}
|
||||
env.expect(t, http.StatusNotFound, http.MethodGet, "/_user/api/v1/backend-link/"+code, "", nil)
|
||||
|
||||
// One link per administrator: another frontend user cannot take it.
|
||||
second, _, err := links.CreateLinkRequest(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status, body := env.confirmLink(t, freshUserToken(t, other), second); status != http.StatusConflict || !strings.Contains(body, `"already_linked"`) {
|
||||
t.Fatalf("second link = %d %s", status, body)
|
||||
}
|
||||
|
||||
// Unlink on My account.
|
||||
spy.reset()
|
||||
env.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/unlink"), token, map[string]any{})
|
||||
if _, found, err := resolver.LinkedBackendUser(ctx, frontend.ID); err != nil || found {
|
||||
t.Fatalf("after unlink LinkedBackendUser found=%v err=%v", found, err)
|
||||
}
|
||||
if !spy.has("user", frontend.ID, pact.MCPSubjectLink) || !spy.has("backend", id, pact.MCPSubjectLink) {
|
||||
t.Fatalf("unlink fired %+v", spy.events)
|
||||
}
|
||||
if section := env.frontendSection(t, token); !slices.Equal(section.actions(), []string{"link"}) {
|
||||
t.Fatalf("section after unlink = %+v", section)
|
||||
}
|
||||
|
||||
// An expired request answers 404 like an unknown one.
|
||||
expired, _, err := links.CreateLinkRequest(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := env.gdb.Exec(`UPDATE golem15_user_backend_link_requests SET expires_at = NOW() - INTERVAL '1 minute' WHERE backend_user_id = ? AND used_at IS NULL`, id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status, _ := env.confirmLink(t, freshUserToken(t, frontend), expired); status != http.StatusNotFound {
|
||||
t.Fatalf("expired confirm = %d", status)
|
||||
}
|
||||
|
||||
// Deleting the frontend user removes the link and ends its subject.
|
||||
code = env.startLink(t, token)
|
||||
if status, body := env.confirmLink(t, freshUserToken(t, frontend), code); status != http.StatusOK {
|
||||
t.Fatalf("relink = %d %s", status, body)
|
||||
}
|
||||
spy.reset()
|
||||
manager := env.admin(t, permAccessUsers)
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, userPath(frontend.ID, ""), manager, nil)
|
||||
var left int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM golem15_user_backend_links WHERE backend_user_id = ?`, id).Scan(&left).Error; err != nil || left != 0 {
|
||||
t.Fatalf("links left after delete = %d %v", left, err)
|
||||
}
|
||||
if !spy.has("user", frontend.ID, pact.MCPSubjectDeleted) || !spy.has("backend", id, pact.MCPSubjectLink) {
|
||||
t.Fatalf("delete fired %+v", spy.events)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
128
backend_links_admin.go
Normal file
128
backend_links_admin.go
Normal file
@@ -0,0 +1,128 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var _ pact.HasAdminActionExtensions = (*Plugin)(nil)
|
||||
|
||||
// AdminActionExtensions adds two record actions to the admin's
|
||||
// Administrators screen (D-07, D-34), both behind
|
||||
// golem15.users.manage_backend_links: link_frontend_account asks for the
|
||||
// email of an active frontend user and links that user to the
|
||||
// administrator shown (exact, case-insensitive match; no search and no
|
||||
// list), recording who set it; unlink_frontend_account removes the
|
||||
// administrator's link. cabana's outranking check runs before either.
|
||||
func (p *Plugin) AdminActionExtensions() []pact.AdminActionExtension {
|
||||
return []pact.AdminActionExtension{{
|
||||
Controller: cabana.AdministratorsControllerID,
|
||||
RecordActions: []pact.AdminRecordAction{
|
||||
{
|
||||
Name: "link_frontend_account",
|
||||
Label: backendLinkLang + "set",
|
||||
Confirm: backendLinkLang + "set_confirm",
|
||||
Permissions: []string{classes.PermissionManageBackendLinks},
|
||||
Prompt: &pact.AdminActionPrompt{
|
||||
Label: backendLinkLang + "prompt_email",
|
||||
Comment: backendLinkLang + "prompt_comment",
|
||||
MaxLength: 254,
|
||||
},
|
||||
Applies: func(ctx context.Context, record any) (bool, error) {
|
||||
link, err := p.adminRecordLink(ctx, record)
|
||||
return link == nil, err
|
||||
},
|
||||
Run: p.setFrontendLink,
|
||||
},
|
||||
{
|
||||
Name: "unlink_frontend_account",
|
||||
Label: backendLinkLang + "remove",
|
||||
Confirm: backendLinkLang + "remove_confirm",
|
||||
Danger: true,
|
||||
Permissions: []string{classes.PermissionManageBackendLinks},
|
||||
Applies: func(ctx context.Context, record any) (bool, error) {
|
||||
link, err := p.adminRecordLink(ctx, record)
|
||||
return link != nil, err
|
||||
},
|
||||
Run: p.removeFrontendLink,
|
||||
},
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// adminRecordLink returns the link of the administrator record, or nil.
|
||||
func (p *Plugin) adminRecordLink(ctx context.Context, record any) (*models.BackendLink, error) {
|
||||
admin, ok := record.(*cabana.BackendUser)
|
||||
if !ok || admin == nil {
|
||||
return nil, errors.New("golem15.user: the record is not an administrator")
|
||||
}
|
||||
return p.backendLinks().LinkFor(ctx, admin.ID)
|
||||
}
|
||||
|
||||
// payloadError is the 422 on the prompt's input.
|
||||
func payloadError(key string) error {
|
||||
return &cabana.ValidationError{Details: map[string]any{"payload": []string{backendLinkLang + key}}}
|
||||
}
|
||||
|
||||
// setFrontendLink links the active frontend user whose email is the prompt
|
||||
// value to the administrator record.
|
||||
func (p *Plugin) setFrontendLink(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
|
||||
admin, ok := in.Record.(*cabana.BackendUser)
|
||||
if !ok || admin == nil {
|
||||
return pact.AdminRecordActionResult{}, errors.New("golem15.user: the record is not an administrator")
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return pact.AdminRecordActionResult{}, errors.New("golem15.user: linking needs the action's transaction")
|
||||
}
|
||||
email := strings.TrimSpace(in.Value)
|
||||
var ids []uint
|
||||
if err := tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Model(&models.User{}).
|
||||
Where("lower(email) = lower(?) AND is_activated = TRUE", email).Limit(2).Pluck("id", &ids).Error; err != nil {
|
||||
return pact.AdminRecordActionResult{}, err
|
||||
}
|
||||
if email == "" || len(ids) != 1 {
|
||||
return pact.AdminRecordActionResult{}, payloadError("unknown_user")
|
||||
}
|
||||
var by uint
|
||||
if caller, ok := bouncer.User(ctx); ok && caller != nil {
|
||||
by = caller.ID
|
||||
}
|
||||
_, err := p.backendLinks().SetLink(ctx, tx, ids[0], admin.ID, by)
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, classes.ErrAlreadyLinked):
|
||||
return pact.AdminRecordActionResult{}, payloadError("already_linked")
|
||||
case errors.Is(err, classes.ErrFrontendUserUnavailable):
|
||||
return pact.AdminRecordActionResult{}, payloadError("unknown_user")
|
||||
case errors.Is(err, classes.ErrBackendUserUnavailable):
|
||||
return pact.AdminRecordActionResult{}, &cabana.ForbiddenError{}
|
||||
default:
|
||||
return pact.AdminRecordActionResult{}, err
|
||||
}
|
||||
return pact.AdminRecordActionResult{Message: backendLinkLang + "set_success"}, nil
|
||||
}
|
||||
|
||||
// removeFrontendLink removes the administrator record's link.
|
||||
func (p *Plugin) removeFrontendLink(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return pact.AdminRecordActionResult{}, errors.New("golem15.user: unlinking needs the action's transaction")
|
||||
}
|
||||
link, err := p.adminRecordLink(ctx, in.Record)
|
||||
if err != nil {
|
||||
return pact.AdminRecordActionResult{}, err
|
||||
}
|
||||
if err := p.backendLinks().RemoveLink(ctx, tx, link); err != nil {
|
||||
return pact.AdminRecordActionResult{}, err
|
||||
}
|
||||
return pact.AdminRecordActionResult{Message: backendLinkLang + "remove_success"}, nil
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
555
classes/backend_links.go
Normal file
555
classes/backend_links.go
Normal file
@@ -0,0 +1,555 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// Errors of the account link service. A request that is unknown, used or
|
||||
// expired is reported apart so callers can log the difference; the site
|
||||
// routes answer all three with the same 404.
|
||||
var (
|
||||
ErrLinkRequestNotFound = errors.New("golem15.user: backend link request not found")
|
||||
ErrLinkRequestUsed = errors.New("golem15.user: backend link request already used")
|
||||
ErrLinkRequestExpired = errors.New("golem15.user: backend link request expired")
|
||||
ErrStaleSession = errors.New("golem15.user: the session was signed in before the link request")
|
||||
ErrAlreadyLinked = errors.New("golem15.user: one of the accounts is already linked")
|
||||
ErrBackendUserUnavailable = errors.New("golem15.user: the administrator is missing or not activated")
|
||||
ErrFrontendUserUnavailable = errors.New("golem15.user: the frontend user is missing or deactivated")
|
||||
)
|
||||
|
||||
// DefaultBackendLinkRequestTTL is how long a link request stays usable when
|
||||
// golem15.user.backend_links.request_ttl is not set.
|
||||
const DefaultBackendLinkRequestTTL = 10 * time.Minute
|
||||
|
||||
var _ pact.MCPLinkedBackendResolver = (*BackendLinks)(nil)
|
||||
|
||||
// BackendLinks is the verified link between a frontend user and a backend
|
||||
// administrator (D-03): one link per account on each side, written either
|
||||
// after the frontend user proves the account with a fresh sign-in
|
||||
// (CreateLinkRequest, then ConfirmLinkRequest) or by an administrator with
|
||||
// golem15.users.manage_backend_links on the Administrators screen (SetLink).
|
||||
// Boot publishes it as *BackendLinks and as pact.MCPLinkedBackendResolver.
|
||||
//
|
||||
// Every read and write uses the transaction cabana runs a hook or an action
|
||||
// in when the context carries one (cabana.TxFromContext), else the
|
||||
// application's database.
|
||||
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
|
||||
// lifetime.
|
||||
func BackendLinkRequestTTL(app *backpack.App) (time.Duration, error) {
|
||||
if app == nil || app.Config == nil {
|
||||
return DefaultBackendLinkRequestTTL, nil
|
||||
}
|
||||
raw := strings.TrimSpace(app.Config.String("golem15.user.backend_links.request_ttl"))
|
||||
if raw == "" {
|
||||
return DefaultBackendLinkRequestTTL, nil
|
||||
}
|
||||
ttl, err := time.ParseDuration(raw)
|
||||
if err != nil || ttl <= 0 {
|
||||
return 0, fmt.Errorf("golem15.user: backend_links.request_ttl must be a positive duration such as 10m, got %q", raw)
|
||||
}
|
||||
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.
|
||||
func FrontendURL(app *backpack.App) string {
|
||||
if app == nil || app.Config == nil {
|
||||
return ""
|
||||
}
|
||||
base := strings.TrimSpace(app.Config.String("golem15.user.frontend_url"))
|
||||
if base == "" {
|
||||
base = strings.TrimSpace(app.Config.String("app.url"))
|
||||
}
|
||||
return strings.TrimRight(base, "/")
|
||||
}
|
||||
|
||||
// db returns the handle a call works on: the cabana transaction on ctx, or
|
||||
// the application's database.
|
||||
func (s *BackendLinks) db(ctx context.Context) (*gorm.DB, error) {
|
||||
if tx, ok := cabana.TxFromContext(ctx); ok {
|
||||
return fresh(ctx, tx), nil
|
||||
}
|
||||
if s == nil || s.App == nil {
|
||||
return nil, fmt.Errorf("golem15.user: app is nil")
|
||||
}
|
||||
gdb, ok := s.App.Lookup[*gorm.DB]()
|
||||
if !ok || gdb == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
return gdb.WithContext(ctx), nil
|
||||
}
|
||||
|
||||
// hashLinkCode is the only form of a link code that is stored.
|
||||
func hashLinkCode(plain string) string {
|
||||
sum := sha256.Sum256([]byte(plain))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// validLinkCode reports whether plain has the shape CreateLinkRequest
|
||||
// issues: 64 lower-case hex characters.
|
||||
func validLinkCode(plain string) bool {
|
||||
if len(plain) != 64 {
|
||||
return false
|
||||
}
|
||||
for _, r := range plain {
|
||||
if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// CreateLinkRequest starts a link for the administrator: a one-shot code
|
||||
// (32 random bytes, hex) valid for golem15.user.backend_links.request_ttl,
|
||||
// stored as its SHA-256. The administrator's earlier requests that were not
|
||||
// used are dropped, so only the newest code works. The plain code is
|
||||
// returned once, for the site URL.
|
||||
func (s *BackendLinks) CreateLinkRequest(ctx context.Context, backendUserID uint) (string, time.Time, error) {
|
||||
if backendUserID == 0 {
|
||||
return "", time.Time{}, ErrBackendUserUnavailable
|
||||
}
|
||||
ttl, err := BackendLinkRequestTTL(s.app())
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
db, err := s.db(ctx)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
plain, err := newCode()
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
now := time.Now()
|
||||
req := &models.BackendLinkRequest{
|
||||
CodeHash: hashLinkCode(plain),
|
||||
BackendUserID: backendUserID,
|
||||
ExpiresAt: now.Add(ttl),
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := fresh(ctx, db).Where("backend_user_id = ? AND used_at IS NULL", backendUserID).
|
||||
Delete(&models.BackendLinkRequest{}).Error; err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
if err := fresh(ctx, db).Create(req).Error; err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
return plain, req.ExpiresAt, nil
|
||||
}
|
||||
|
||||
// LinkRequestByCode returns a usable request and its administrator for the
|
||||
// site's link page. An unknown, used or expired code is
|
||||
// ErrLinkRequestNotFound, ErrLinkRequestUsed or ErrLinkRequestExpired; an
|
||||
// administrator who was deactivated or deleted since is
|
||||
// ErrBackendUserUnavailable.
|
||||
func (s *BackendLinks) LinkRequestByCode(ctx context.Context, plain string) (*models.BackendLinkRequest, *cabana.BackendUser, error) {
|
||||
if !validLinkCode(plain) {
|
||||
return nil, nil, ErrLinkRequestNotFound
|
||||
}
|
||||
db, err := s.db(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var rows []models.BackendLinkRequest
|
||||
if err := fresh(ctx, db).Where("code_hash = ?", hashLinkCode(plain)).Limit(1).Find(&rows).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil, nil, ErrLinkRequestNotFound
|
||||
}
|
||||
req := &rows[0]
|
||||
if err := requestUsable(req, time.Now()); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
admin, err := activeBackendUser(ctx, db, req.BackendUserID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
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
|
||||
}
|
||||
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, 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, sessionAuthTime time.Time) (*models.BackendLink, error) {
|
||||
if !validLinkCode(plain) {
|
||||
return nil, ErrLinkRequestNotFound
|
||||
}
|
||||
if frontendUserID == 0 {
|
||||
return nil, ErrFrontendUserUnavailable
|
||||
}
|
||||
gdb, err := s.pool()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var link *models.BackendLink
|
||||
err = lagoon.Transaction(ctx, gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||
var rows []models.BackendLinkRequest
|
||||
if err := fresh(ctx, tx).Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("code_hash = ?", hashLinkCode(plain)).Limit(1).Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return ErrLinkRequestNotFound
|
||||
}
|
||||
req := &rows[0]
|
||||
now := time.Now()
|
||||
if err := requestUsable(req, now); err != nil {
|
||||
return err
|
||||
}
|
||||
// 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 {
|
||||
return err
|
||||
}
|
||||
created, err := s.insertLink(ctx, tx, frontendUserID, req.BackendUserID, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fresh(ctx, tx).Model(&models.BackendLinkRequest{}).Where("id = ?", req.ID).
|
||||
Update("used_at", now).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
link = created
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return link, nil
|
||||
}
|
||||
|
||||
// SetLink stores a link an administrator sets on the Administrators screen
|
||||
// (D-07): the frontend user must exist and not be deactivated
|
||||
// (ErrFrontendUserUnavailable), the administrator must be activated
|
||||
// (ErrBackendUserUnavailable) and neither may be linked already
|
||||
// (ErrAlreadyLinked). linkedBy is recorded (0 records none). It runs in tx,
|
||||
// fires BackendLinkedEvent there and the two pact.MCPSubjectChanged events
|
||||
// after tx commits.
|
||||
func (s *BackendLinks) SetLink(ctx context.Context, tx *gorm.DB, frontendUserID, backendUserID, linkedBy uint) (*models.BackendLink, error) {
|
||||
if tx == nil {
|
||||
return nil, fmt.Errorf("golem15.user: setting a link needs a transaction")
|
||||
}
|
||||
var users []models.User
|
||||
if err := fresh(ctx, tx).Where("id = ?", frontendUserID).Limit(1).Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if frontendUserID == 0 || len(users) == 0 {
|
||||
return nil, ErrFrontendUserUnavailable
|
||||
}
|
||||
if _, err := activeBackendUser(ctx, tx, backendUserID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var by *uint
|
||||
if linkedBy != 0 {
|
||||
by = &linkedBy
|
||||
}
|
||||
return s.insertLink(ctx, tx, frontendUserID, backendUserID, by)
|
||||
}
|
||||
|
||||
// insertLink writes one link in tx after checking both sides are free; a
|
||||
// concurrent writer that wins the unique index also ends in
|
||||
// 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{}).
|
||||
Where("user_id = ? OR backend_user_id = ?", frontendUserID, backendUserID).
|
||||
Count(&taken).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if taken > 0 {
|
||||
return nil, ErrAlreadyLinked
|
||||
}
|
||||
link := &models.BackendLink{UserID: frontendUserID, BackendUserID: backendUserID, LinkedBy: linkedBy, CreatedAt: time.Now()}
|
||||
if err := fresh(ctx, tx).Create(link).Error; err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, ErrAlreadyLinked
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
app := s.app()
|
||||
if app != nil && app.Events != nil {
|
||||
if err := app.Events.Fire(ctx, &BackendLinkedEvent{Link: link, Tx: tx}); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", BackendLinkedEventName, err)
|
||||
}
|
||||
}
|
||||
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardUser, link.UserID, pact.MCPSubjectLink)
|
||||
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardBackend, link.BackendUserID, pact.MCPSubjectLink)
|
||||
return link, nil
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if link == nil || link.ID == 0 {
|
||||
return nil
|
||||
}
|
||||
if tx == nil {
|
||||
return fmt.Errorf("golem15.user: removing a link needs a transaction")
|
||||
}
|
||||
res := fresh(ctx, tx).Where("id = ?", link.ID).Delete(&models.BackendLink{})
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
app := s.app()
|
||||
if app != nil && app.Events != nil {
|
||||
if err := app.Events.Fire(ctx, &BackendUnlinkedEvent{Link: link, Tx: tx}); err != nil {
|
||||
return fmt.Errorf("%s: %w", BackendUnlinkedEventName, err)
|
||||
}
|
||||
}
|
||||
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardUser, link.UserID, pact.MCPSubjectLink)
|
||||
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardBackend, link.BackendUserID, pact.MCPSubjectLink)
|
||||
return nil
|
||||
}
|
||||
|
||||
// LinkFor returns the link of the administrator, or nil.
|
||||
func (s *BackendLinks) LinkFor(ctx context.Context, backendUserID uint) (*models.BackendLink, error) {
|
||||
return s.linkWhere(ctx, "backend_user_id = ?", backendUserID)
|
||||
}
|
||||
|
||||
// LinkOf returns the link of the frontend user, or nil.
|
||||
func (s *BackendLinks) LinkOf(ctx context.Context, frontendUserID uint) (*models.BackendLink, error) {
|
||||
return s.linkWhere(ctx, "user_id = ?", frontendUserID)
|
||||
}
|
||||
|
||||
func (s *BackendLinks) linkWhere(ctx context.Context, where string, id uint) (*models.BackendLink, error) {
|
||||
if id == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
db, err := s.db(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var rows []models.BackendLink
|
||||
if err := fresh(ctx, db).Where(where, id).Limit(1).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return &rows[0], nil
|
||||
}
|
||||
|
||||
// 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 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
|
||||
}
|
||||
db, err := s.db(ctx)
|
||||
if err != nil {
|
||||
return pact.LinkedBackendUser{}, false, err
|
||||
}
|
||||
var rows []struct {
|
||||
ID uint
|
||||
Login string
|
||||
FirstName *string
|
||||
LastName *string
|
||||
}
|
||||
err = fresh(ctx, db).Raw(`SELECT b.id, b.login, b.first_name, b.last_name
|
||||
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
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return pact.LinkedBackendUser{}, false, nil
|
||||
}
|
||||
row := rows[0]
|
||||
return pact.LinkedBackendUser{ID: row.ID, Login: row.Login, DisplayName: backendDisplayName(deref(row.FirstName), deref(row.LastName), row.Login)}, true, nil
|
||||
}
|
||||
|
||||
// BackendDisplayName is the name the link pages show for an administrator:
|
||||
// first and last name, else the login.
|
||||
func BackendDisplayName(admin *cabana.BackendUser) string {
|
||||
if admin == nil {
|
||||
return ""
|
||||
}
|
||||
return backendDisplayName(admin.FirstName, admin.LastName, admin.Login)
|
||||
}
|
||||
|
||||
func backendDisplayName(first, last, login string) string {
|
||||
if name := strings.TrimSpace(strings.TrimSpace(first) + " " + strings.TrimSpace(last)); name != "" {
|
||||
return name
|
||||
}
|
||||
return login
|
||||
}
|
||||
|
||||
func deref(s *string) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return *s
|
||||
}
|
||||
|
||||
// activeBackendUser loads an activated, not deleted administrator, else
|
||||
// ErrBackendUserUnavailable.
|
||||
func activeBackendUser(ctx context.Context, db *gorm.DB, id uint) (*cabana.BackendUser, error) {
|
||||
if id == 0 {
|
||||
return nil, ErrBackendUserUnavailable
|
||||
}
|
||||
var rows []cabana.BackendUser
|
||||
if err := fresh(ctx, db).Where("id = ? AND is_activated = TRUE", id).Limit(1).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil, ErrBackendUserUnavailable
|
||||
}
|
||||
return &rows[0], nil
|
||||
}
|
||||
|
||||
// RegisterBackendLinkListeners removes a frontend user's link inside the
|
||||
// transaction that deletes (DeletingEvent) or deactivates
|
||||
// (DeactivatingEvent) the user, and fires pact.MCPSubjectChanged deleted
|
||||
// for the user and link for the administrator after it commits.
|
||||
func (s *BackendLinks) RegisterBackendLinkListeners(app *backpack.App) {
|
||||
if app == nil || app.Events == nil {
|
||||
return
|
||||
}
|
||||
const owner = "golem15.user.backend_links"
|
||||
app.Events.Listen(owner, func(ctx context.Context, e *DeletingEvent) error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return s.dropUserLink(ctx, e.Tx, e.User)
|
||||
})
|
||||
app.Events.Listen(owner, func(ctx context.Context, e *DeactivatingEvent) error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return s.dropUserLink(ctx, e.Tx, e.User)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *BackendLinks) dropUserLink(ctx context.Context, tx *gorm.DB, user *models.User) error {
|
||||
if user == nil || user.ID == 0 || tx == nil {
|
||||
return nil
|
||||
}
|
||||
var rows []models.BackendLink
|
||||
if err := fresh(ctx, tx).Where("user_id = ?", user.ID).Limit(1).Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) > 0 {
|
||||
if err := s.RemoveLink(ctx, tx, &rows[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
FireSubjectChangedAfterCommit(ctx, s.app(), tx, SubjectGuardUser, user.ID, pact.MCPSubjectDeleted)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *BackendLinks) app() *backpack.App {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s.App
|
||||
}
|
||||
|
||||
func (s *BackendLinks) pool() (*gorm.DB, error) {
|
||||
if s == nil || s.App == nil {
|
||||
return nil, fmt.Errorf("golem15.user: app is nil")
|
||||
}
|
||||
gdb, ok := s.App.Lookup[*gorm.DB]()
|
||||
if !ok || gdb == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
return gdb, nil
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -14,6 +16,15 @@ const DeletingEventName = "user.Deleting"
|
||||
// DeactivatingEventName is the festival name of DeactivatingEvent.
|
||||
const DeactivatingEventName = "user.Deactivating"
|
||||
|
||||
// BackendLinkedEventName is the festival name of BackendLinkedEvent.
|
||||
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
|
||||
@@ -67,3 +78,36 @@ type DeactivatingEvent struct {
|
||||
User *models.User
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
// BackendLinkedEvent fires inside the write transaction after a link was
|
||||
// stored, by the frontend user's confirmation (Link.LinkedBy nil) or by an
|
||||
// administrator (Link.LinkedBy set). A listener error rolls the link back.
|
||||
type BackendLinkedEvent struct {
|
||||
Link *models.BackendLink
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
// BackendUnlinkedEvent fires inside the write transaction after a link was
|
||||
// removed, from My account, the Administrators screen or because one of the
|
||||
// accounts was deleted or deactivated. A listener error rolls the removal
|
||||
// back.
|
||||
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
|
||||
}
|
||||
|
||||
59
classes/frontend_permission_catalog.go
Normal file
59
classes/frontend_permission_catalog.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// FrontendPermissionCatalog is what the user and user group permission
|
||||
// editors offer (D-09): the rows of golem15_user_frontend_permissions first,
|
||||
// in FrontendPermissionOptions order and unchanged, then the codes activated
|
||||
// plugins declare through pact.HasFrontendPermissions, in activation order.
|
||||
// A declared code that a seeded row already has is skipped (the seeded row
|
||||
// wins), and so is a code an earlier plugin declared; an empty code is
|
||||
// skipped. The table, its rows and the stored permissions are never
|
||||
// written.
|
||||
func FrontendPermissionCatalog(ctx context.Context, app *backpack.App, db *gorm.DB) ([]cabana.PermissionOption, error) {
|
||||
rows, err := FrontendPermissionOptions(ctx, db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options := make([]cabana.PermissionOption, 0, len(rows))
|
||||
seen := make(map[string]bool, len(rows))
|
||||
for _, row := range rows {
|
||||
option := cabana.PermissionOption{Code: row.Code, Label: row.Label, Tab: row.Tab}
|
||||
if row.Comment != nil {
|
||||
option.Comment = *row.Comment
|
||||
}
|
||||
options = append(options, option)
|
||||
seen[row.Code] = true
|
||||
}
|
||||
if app == nil {
|
||||
return options, nil
|
||||
}
|
||||
activated, ok := app.Lookup[party.Activated]()
|
||||
if !ok {
|
||||
return options, nil
|
||||
}
|
||||
for _, plugin := range activated {
|
||||
declares, ok := plugin.(pact.HasFrontendPermissions)
|
||||
if !ok || declares == nil {
|
||||
continue
|
||||
}
|
||||
for _, perm := range declares.FrontendPermissions() {
|
||||
code := strings.TrimSpace(perm.Code)
|
||||
if code == "" || seen[code] {
|
||||
continue
|
||||
}
|
||||
seen[code] = true
|
||||
options = append(options, cabana.PermissionOption{Code: code, Label: perm.Label, Tab: perm.Tab, Comment: perm.Comment})
|
||||
}
|
||||
}
|
||||
return options, nil
|
||||
}
|
||||
199
classes/mcp_guard.go
Normal file
199
classes/mcp_guard.go
Normal file
@@ -0,0 +1,199 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"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"
|
||||
)
|
||||
|
||||
// The middleware names the guard provider reads on a route.
|
||||
const (
|
||||
mcpTokenMiddleware = "user.api_token"
|
||||
mcpScopeMiddleware = "user.scope:"
|
||||
mcpPermissionMiddleware = "user.permission:"
|
||||
)
|
||||
|
||||
var (
|
||||
_ pact.MCPGuard = (*MCPUserGuard)(nil)
|
||||
_ pact.MCPPersonalTokenResolver = (*MCPUserGuard)(nil)
|
||||
)
|
||||
|
||||
// MCPUserGuard is the plugin's MCP guard provider, named "user": MCP tools
|
||||
// bind to the plugin's token-guarded routes (user.api_token, user.scope:*,
|
||||
// user.permission:*) through it, and it resolves the plugin's personal API
|
||||
// tokens (the usr_ prefix, golem15.user.api_tokens.prefix) at the MCP
|
||||
// endpoint. Boot registers it in the application's *pact.MCPGuards and
|
||||
// publishes it as pact.MCPPersonalTokenResolver.
|
||||
//
|
||||
// Its checks are the ones the routes run: a scope must be granted to the
|
||||
// session (as user.scope checks the token), and a permission code must be
|
||||
// granted by one of the user's groups (as user.permission checks the
|
||||
// principal PrincipalByID loads; a user's own permission overrides do not
|
||||
// grant, D-35).
|
||||
type MCPUserGuard struct {
|
||||
App *backpack.App
|
||||
}
|
||||
|
||||
// MCPGuardName is "user".
|
||||
func (g *MCPUserGuard) MCPGuardName() string { return SubjectGuardUser }
|
||||
|
||||
// MCPTokenGuarded reports whether the route runs the user.api_token guard.
|
||||
func (g *MCPUserGuard) MCPTokenGuarded(middleware []string) bool {
|
||||
return slices.Contains(middleware, mcpTokenMiddleware)
|
||||
}
|
||||
|
||||
// MCPRequirements collects the scopes of user.scope:<scope> and the codes of
|
||||
// user.permission:<code>. Another user.* name than these and user.api_token
|
||||
// is an error, so a guard this provider does not understand cannot be
|
||||
// skipped silently.
|
||||
func (g *MCPUserGuard) MCPRequirements(middleware []string) (pact.MCPRequirements, error) {
|
||||
var req pact.MCPRequirements
|
||||
for _, name := range middleware {
|
||||
switch {
|
||||
case name == mcpTokenMiddleware:
|
||||
case strings.HasPrefix(name, mcpScopeMiddleware):
|
||||
scope := strings.TrimPrefix(name, mcpScopeMiddleware)
|
||||
if scope == "" {
|
||||
return pact.MCPRequirements{}, fmt.Errorf("golem15.user: middleware %q names no scope", name)
|
||||
}
|
||||
if !slices.Contains(req.Scopes, scope) {
|
||||
req.Scopes = append(req.Scopes, scope)
|
||||
}
|
||||
case strings.HasPrefix(name, mcpPermissionMiddleware):
|
||||
code := strings.TrimPrefix(name, mcpPermissionMiddleware)
|
||||
if code == "" {
|
||||
return pact.MCPRequirements{}, fmt.Errorf("golem15.user: middleware %q names no permission", name)
|
||||
}
|
||||
if !slices.Contains(req.Permissions, code) {
|
||||
req.Permissions = append(req.Permissions, code)
|
||||
}
|
||||
case strings.HasPrefix(name, "user."):
|
||||
return pact.MCPRequirements{}, fmt.Errorf("golem15.user: the MCP guard does not know middleware %q", name)
|
||||
}
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// MCPAllows requires every scope of req in the subject's scopes, then every
|
||||
// permission code of req and of the tool, one by one (the route runs one
|
||||
// user.permission middleware per code), granted to the user's groups.
|
||||
func (g *MCPUserGuard) MCPAllows(ctx context.Context, subject pact.MCPSubject, req pact.MCPRequirements, permissions []string) (bool, error) {
|
||||
for _, scope := range req.Scopes {
|
||||
if !slices.Contains(subject.Scopes, scope) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
db, err := g.db()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
principal, err := PrincipalByID(ctx, db.WithContext(ctx), subject.UserID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if principal == nil {
|
||||
return false, nil
|
||||
}
|
||||
for _, code := range append(slices.Clone(req.Permissions), permissions...) {
|
||||
if !cabana.Allows(principal, []string{code}) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// MCPDispatch builds the principal (the user with the group grants, as the
|
||||
// api_token guard loads it) and an in-memory token credential carrying the
|
||||
// session's scopes, so user.scope sees what the session was granted. The
|
||||
// credential has ID 0 and is never saved. The marker is honoured by the
|
||||
// api_token guard only.
|
||||
func (g *MCPUserGuard) MCPDispatch(ctx context.Context, subject pact.MCPSubject, _ string) (pact.MCPDispatch, error) {
|
||||
db, err := g.db()
|
||||
if err != nil {
|
||||
return pact.MCPDispatch{}, err
|
||||
}
|
||||
principal, err := PrincipalByID(ctx, db.WithContext(ctx), subject.UserID)
|
||||
if err != nil {
|
||||
return pact.MCPDispatch{}, err
|
||||
}
|
||||
if principal == nil {
|
||||
return pact.MCPDispatch{}, fmt.Errorf("golem15.user: user %d is gone", subject.UserID)
|
||||
}
|
||||
credential := &models.APIToken{
|
||||
UserID: subject.UserID,
|
||||
Scopes: lagoon.Jsonable[[]string]{Data: slices.Clone(subject.Scopes), Valid: true},
|
||||
}
|
||||
return pact.MCPDispatch{Principal: principal, Credential: credential, Guards: []string{"api_token"}}, nil
|
||||
}
|
||||
|
||||
// MCPResolvePersonalToken resolves a personal API token of this plugin into
|
||||
// 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, 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) {
|
||||
return pact.MCPSubject{}, false, nil
|
||||
}
|
||||
db, err := g.db()
|
||||
if err != nil {
|
||||
return pact.MCPSubject{}, true, err
|
||||
}
|
||||
db = db.WithContext(ctx)
|
||||
var token models.APIToken
|
||||
result := db.Where("token_hash = ?", HashAPIToken(raw)).Limit(1).Find(&token)
|
||||
if result.Error != nil {
|
||||
return pact.MCPSubject{}, true, result.Error
|
||||
}
|
||||
now := time.Now()
|
||||
if result.RowsAffected == 0 || !token.IsUsableAt(now) {
|
||||
return pact.MCPSubject{}, true, pact.ErrMCPTokenInvalid
|
||||
}
|
||||
principal, err := PrincipalByID(ctx, db, token.UserID)
|
||||
if err != nil {
|
||||
return pact.MCPSubject{}, true, err
|
||||
}
|
||||
if principal == nil {
|
||||
return pact.MCPSubject{}, true, pact.ErrMCPTokenInvalid
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
func (g *MCPUserGuard) app() *backpack.App {
|
||||
if g == nil {
|
||||
return nil
|
||||
}
|
||||
return g.App
|
||||
}
|
||||
|
||||
func (g *MCPUserGuard) db() (*gorm.DB, error) {
|
||||
app := g.app()
|
||||
if app == nil {
|
||||
return nil, fmt.Errorf("golem15.user: app is nil")
|
||||
}
|
||||
gdb, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || gdb == nil {
|
||||
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
|
||||
}
|
||||
return gdb, 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
|
||||
}
|
||||
@@ -15,6 +15,11 @@ import (
|
||||
// good.
|
||||
const PermissionManagePrivilegedGroups = "golem15.users.manage_privileged_groups"
|
||||
|
||||
// PermissionManageBackendLinks is the backend permission an administrator
|
||||
// needs to link a frontend account to another administrator, or to unlink
|
||||
// one, on the Administrators screen. No role has it by default.
|
||||
const PermissionManageBackendLinks = "golem15.users.manage_backend_links"
|
||||
|
||||
// privilegedGroupsKey is the config list of privileged group codes.
|
||||
const privilegedGroupsKey = "golem15.user.privileged_groups"
|
||||
|
||||
|
||||
69
classes/subject_events.go
Normal file
69
classes/subject_events.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Guard names the plugin's pact.MCPSubjectChanged events carry: the frontend
|
||||
// user guard this plugin provides and the admin's guard (for the backend
|
||||
// side of an account link).
|
||||
const (
|
||||
SubjectGuardUser = "user"
|
||||
SubjectGuardBackend = "backend"
|
||||
)
|
||||
|
||||
// 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 := 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 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 {
|
||||
FireSubjectEvent(ctx, app, ev)
|
||||
return
|
||||
}
|
||||
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
|
||||
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,3 +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,
|
||||
# <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"
|
||||
@@ -12,6 +11,7 @@ import (
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/wire"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -34,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
|
||||
@@ -53,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
|
||||
@@ -62,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) {
|
||||
@@ -106,6 +138,8 @@ func APITokenDestroy(app *backpack.App) http.HandlerFunc {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
// 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}})
|
||||
}
|
||||
}
|
||||
@@ -128,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
|
||||
}
|
||||
@@ -139,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)
|
||||
|
||||
152
controllers/backend_link_controller.go
Normal file
152
controllers/backend_link_controller.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"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 {
|
||||
return classes.BackendLinksFor(app)
|
||||
}
|
||||
|
||||
// linkNotFound is the one answer for an unknown, used or expired code and
|
||||
// for an administrator who is no longer available: the page cannot tell
|
||||
// them apart.
|
||||
func linkNotFound(w http.ResponseWriter) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]any{"error": "not_found"})
|
||||
}
|
||||
|
||||
// BackendLinkShow serves GET /_user/api/v1/backend-link/{code}, the site's
|
||||
// "link this account to the administrator?" page: the administrator's login
|
||||
// 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) {
|
||||
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 {
|
||||
writeNoStoreJSON(w, http.StatusNotFound, map[string]any{"error": "not_found"})
|
||||
return
|
||||
}
|
||||
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 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())
|
||||
if !ok || principal == nil || principal.ID == 0 {
|
||||
writeUnauthorized(w)
|
||||
return
|
||||
}
|
||||
secret, err := classes.JWTSecret(app)
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
// The token jwt.auth accepted (bearer header, then the session
|
||||
// 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
|
||||
}
|
||||
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, authTime)
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, classes.ErrStaleSession):
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": "stale_session"})
|
||||
return
|
||||
case errors.Is(err, classes.ErrAlreadyLinked):
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": "already_linked"})
|
||||
return
|
||||
case isLinkGone(err):
|
||||
linkNotFound(w)
|
||||
return
|
||||
default:
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
linked, found, err := links.LinkedBackendUser(r.Context(), principal.ID)
|
||||
if err != nil || !found {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
|
||||
"backend_user": map[string]any{"login": linked.Login, "name": linked.DisplayName},
|
||||
}})
|
||||
}
|
||||
}
|
||||
|
||||
func isLinkGone(err error) bool {
|
||||
return errors.Is(err, classes.ErrLinkRequestNotFound) ||
|
||||
errors.Is(err, classes.ErrLinkRequestUsed) ||
|
||||
errors.Is(err, classes.ErrLinkRequestExpired) ||
|
||||
errors.Is(err, classes.ErrBackendUserUnavailable) ||
|
||||
errors.Is(err, classes.ErrFrontendUserUnavailable)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
39
controllers/token_me.go
Normal file
39
controllers/token_me.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
)
|
||||
|
||||
// TokenMe serves GET /_user/api/v1/token/me behind user.api_token and
|
||||
// user.scope:read: the token owner's user payload, the same {"user": ...}
|
||||
// body GET /fetch answers for a session. It is the target of the MCP tool
|
||||
// user_me. The guard answers 401 for a missing or unusable token and the
|
||||
// scope middleware 403 for a token without read.
|
||||
func TokenMe(app *backpack.App) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
principal, ok := bouncer.User(r.Context())
|
||||
if !ok || principal == nil || principal.ID == 0 {
|
||||
writeUnauthorized(w)
|
||||
return
|
||||
}
|
||||
gdb, _, ok := sessionDeps(w, app)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var user models.User
|
||||
if err := gdb.WithContext(r.Context()).Where("id = ?", principal.ID).Take(&user).Error; err != nil {
|
||||
writeUnauthorized(w)
|
||||
return
|
||||
}
|
||||
payload, err := apiArray(r.Context(), app, &user)
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": payload})
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -119,16 +121,30 @@ func (c usergroupsAdminController) FormBeforeUpdate(ctx context.Context, model a
|
||||
// FormBeforeDelete refuses the delete of a privileged group without
|
||||
// golem15.users.manage_privileged_groups: it would take the privilege from
|
||||
// every member. The record is the stored row, loaded in the delete's
|
||||
// transaction.
|
||||
// transaction. A delete that goes ahead reads the members there; each gets
|
||||
// a pact.MCPSubjectChanged permissions event after the delete commits,
|
||||
// since the group's grants are gone (FormAfterDelete removes the
|
||||
// memberships).
|
||||
func (c usergroupsAdminController) FormBeforeDelete(ctx context.Context, model any) error {
|
||||
group, ok := model.(*models.UserGroup)
|
||||
if !ok || group == nil {
|
||||
return errors.New("user groups admin: form model is not a user group")
|
||||
}
|
||||
if !classes.IsPrivilegedCode(classes.PrivilegedGroupCodes(c.app.config()), group.Code) {
|
||||
if classes.IsPrivilegedCode(classes.PrivilegedGroupCodes(c.app.config()), group.Code) {
|
||||
if err := c.requirePrivilegedPermission(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return c.requirePrivilegedPermission(ctx)
|
||||
members, err := groupMemberIDs(ctx, tx, group.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.permissionsChanged(ctx, tx, members)
|
||||
return nil
|
||||
}
|
||||
|
||||
// FormAfterDelete removes the memberships of the deleted group in the same
|
||||
@@ -147,6 +163,49 @@ func (usergroupsAdminController) FormAfterDelete(ctx context.Context, model any)
|
||||
Where("user_group_id = ?", group.ID).Delete(&models.UsersGroup{}).Error
|
||||
}
|
||||
|
||||
// FormAfterUpdate tells the MCP endpoint that the members of the group may
|
||||
// do something else now (the form saves the group's permissions): one
|
||||
// pact.MCPSubjectChanged permissions event per member, the members read in
|
||||
// the save's transaction and the events fired after it commits.
|
||||
func (c usergroupsAdminController) FormAfterUpdate(ctx context.Context, model any) error {
|
||||
group, ok := model.(*models.UserGroup)
|
||||
if !ok || group == nil {
|
||||
return errors.New("user groups admin: form model is not a user group")
|
||||
}
|
||||
tx, ok := cabana.TxFromContext(ctx)
|
||||
if !ok {
|
||||
return errors.New("user groups admin: an update needs its transaction")
|
||||
}
|
||||
members, err := groupMemberIDs(ctx, tx, group.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.permissionsChanged(ctx, tx, members)
|
||||
return nil
|
||||
}
|
||||
|
||||
// permissionsChanged fires one permissions subject event per user after tx
|
||||
// commits.
|
||||
func (c usergroupsAdminController) permissionsChanged(ctx context.Context, tx *gorm.DB, userIDs []uint) {
|
||||
if len(userIDs) == 0 {
|
||||
return
|
||||
}
|
||||
app := c.app.application()
|
||||
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
|
||||
for _, id := range userIDs {
|
||||
classes.FireSubjectChanged(ctx, app, classes.SubjectGuardUser, id, pact.MCPSubjectPermissions)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// groupMemberIDs reads the ids of the group's members through tx.
|
||||
func groupMemberIDs(ctx context.Context, tx *gorm.DB, groupID uint) ([]uint, error) {
|
||||
ids := []uint{}
|
||||
err := tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).
|
||||
Model(&models.UsersGroup{}).Where("user_group_id = ?", groupID).Order("user_id").Pluck("user_id", &ids).Error
|
||||
return ids, err
|
||||
}
|
||||
|
||||
// requirePrivilegedPermission answers nil when the administrator on ctx
|
||||
// holds golem15.users.manage_privileged_groups, else the 403 of the screen.
|
||||
// A context without a principal is refused.
|
||||
@@ -184,7 +243,9 @@ func sameCode(a, b *string) bool {
|
||||
}
|
||||
|
||||
// AdminPermissionOptions offers the rows of
|
||||
// golem15_user_frontend_permissions, by tab and code. None is locked.
|
||||
// golem15_user_frontend_permissions, by tab and code, then the frontend
|
||||
// permission codes activated plugins declare (classes.FrontendPermissionCatalog).
|
||||
// None is locked.
|
||||
func (c usergroupsAdminController) AdminPermissionOptions(ctx context.Context, field string) ([]cabana.PermissionOption, error) {
|
||||
if field != permissionsField {
|
||||
return nil, fmt.Errorf("user groups admin: unknown permission field %q", field)
|
||||
@@ -193,19 +254,7 @@ func (c usergroupsAdminController) AdminPermissionOptions(ctx context.Context, f
|
||||
if db == nil {
|
||||
return nil, errors.New("user groups admin: gorm handle is missing")
|
||||
}
|
||||
rows, err := classes.FrontendPermissionOptions(ctx, db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options := make([]cabana.PermissionOption, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
option := cabana.PermissionOption{Code: row.Code, Label: row.Label, Tab: row.Tab}
|
||||
if row.Comment != nil {
|
||||
option.Comment = *row.Comment
|
||||
}
|
||||
options = append(options, option)
|
||||
}
|
||||
return options, nil
|
||||
return classes.FrontendPermissionCatalog(ctx, c.app.application(), db)
|
||||
}
|
||||
|
||||
// AdminPermissionValues returns the group's stored permissions, read with
|
||||
|
||||
@@ -244,12 +244,37 @@ 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
|
||||
}
|
||||
|
||||
// FormAfterUpdate tells the MCP endpoint that what the user may do may have
|
||||
// changed (their permissions or group memberships are saved by this form):
|
||||
// one pact.MCPSubjectChanged permissions event for the user, fired after the
|
||||
// save commits. Every MCP call re-checks anyway; the event only refreshes
|
||||
// the tool list sooner.
|
||||
func (c usersAdminController) FormAfterUpdate(ctx context.Context, model any) error {
|
||||
user, ok := model.(*models.User)
|
||||
if !ok || user == nil {
|
||||
return errors.New("users admin: form model is not a user")
|
||||
}
|
||||
tx, _ := cabana.TxFromContext(ctx)
|
||||
app := c.application()
|
||||
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
|
||||
classes.FireSubjectChanged(ctx, app, classes.SubjectGuardUser, user.ID, pact.MCPSubjectPermissions)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// FormBeforeCreate checks the email against deactivated users too and stores
|
||||
// the hash of the submitted password. A user created here starts not
|
||||
// activated: is_activated is never written from the form, and only the
|
||||
@@ -427,7 +452,9 @@ func (c usersAdminController) AdminRelationLocks(ctx context.Context, field stri
|
||||
const permissionsField = "permissions"
|
||||
|
||||
// AdminPermissionOptions offers the rows of
|
||||
// golem15_user_frontend_permissions, by tab and code. None is locked.
|
||||
// golem15_user_frontend_permissions, by tab and code, then the frontend
|
||||
// permission codes activated plugins declare (classes.FrontendPermissionCatalog).
|
||||
// None is locked.
|
||||
func (c usersAdminController) AdminPermissionOptions(ctx context.Context, field string) ([]cabana.PermissionOption, error) {
|
||||
if field != permissionsField {
|
||||
return nil, fmt.Errorf("users admin: unknown permission field %q", field)
|
||||
@@ -436,19 +463,7 @@ func (c usersAdminController) AdminPermissionOptions(ctx context.Context, field
|
||||
if db == nil {
|
||||
return nil, errors.New("users admin: gorm handle is missing")
|
||||
}
|
||||
rows, err := classes.FrontendPermissionOptions(ctx, db)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options := make([]cabana.PermissionOption, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
option := cabana.PermissionOption{Code: row.Code, Label: row.Label, Tab: row.Tab}
|
||||
if row.Comment != nil {
|
||||
option.Comment = *row.Comment
|
||||
}
|
||||
options = append(options, option)
|
||||
}
|
||||
return options, nil
|
||||
return classes.FrontendPermissionCatalog(ctx, c.application(), db)
|
||||
}
|
||||
|
||||
// AdminPermissionValues returns the user's own stored permissions.
|
||||
@@ -623,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.
|
||||
|
||||
112
frontend_permission_catalog_smoke_test.go
Normal file
112
frontend_permission_catalog_smoke_test.go
Normal file
@@ -0,0 +1,112 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
)
|
||||
|
||||
// The frontend permission codes the acmeBlogPermissions test plugin declares.
|
||||
const (
|
||||
acmeBlogManage = "acme.blog.manage"
|
||||
// acmeBlogSeeded is also a seeded row of golem15_user_frontend_permissions
|
||||
// in the smoke, with another label: the seeded row wins.
|
||||
acmeBlogSeeded = "acme.blog.seeded"
|
||||
)
|
||||
|
||||
// acmeBlogPermissions is a plugin that only declares frontend permission
|
||||
// codes (pact.HasFrontendPermissions). It is registered for the test binary
|
||||
// and activated only by the tests that name it.
|
||||
type acmeBlogPermissions struct{}
|
||||
|
||||
func (acmeBlogPermissions) ID() string { return "acme.blog" }
|
||||
func (acmeBlogPermissions) Requires() []string { return nil }
|
||||
func (acmeBlogPermissions) Register(*backpack.App) error { return nil }
|
||||
func (acmeBlogPermissions) Boot(*backpack.App) error { return nil }
|
||||
|
||||
func (acmeBlogPermissions) FrontendPermissions() []pact.FrontendPermission {
|
||||
return []pact.FrontendPermission{
|
||||
{Code: acmeBlogManage, Label: "Manage blog posts", Tab: "Blog", Comment: "Create, edit and delete posts."},
|
||||
{Code: acmeBlogSeeded, Label: "Plugin label", Tab: "Blog"},
|
||||
{Code: acmeBlogManage, Label: "Declared twice", Tab: "Blog"},
|
||||
}
|
||||
}
|
||||
|
||||
func init() { party.Register(acmeBlogPermissions{}) }
|
||||
|
||||
type offeredPermission struct {
|
||||
Code string `json:"code"`
|
||||
Label string `json:"label"`
|
||||
Tab string `json:"tab"`
|
||||
Comment string `json:"comment"`
|
||||
}
|
||||
|
||||
// permissionOptions reads the options of the permissions field of a form
|
||||
// schema.
|
||||
func (e *adminEnv) permissionOptions(t *testing.T, token, path string) []offeredPermission {
|
||||
t.Helper()
|
||||
var form struct {
|
||||
Fields []struct {
|
||||
Name string `json:"name"`
|
||||
Options []offeredPermission `json:"permissionOptions"`
|
||||
} `json:"fields"`
|
||||
}
|
||||
adminInto(t, e.expect(t, http.StatusOK, http.MethodGet, adminAPI(path+"/schema/form"), token, nil), &form)
|
||||
for _, field := range form.Fields {
|
||||
if field.Name == "permissions" {
|
||||
return field.Options
|
||||
}
|
||||
}
|
||||
t.Fatalf("%s has no permissions field", path)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestFrontendPermissionCatalogSmoke: both permission editors offer the
|
||||
// seeded rows first, then the codes an activated plugin declares; a seeded
|
||||
// row wins over a declared code and a code is offered once.
|
||||
func TestFrontendPermissionCatalogSmoke(t *testing.T) {
|
||||
env := newAdminEnvWith(t, []string{"acme.blog"})
|
||||
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)
|
||||
for _, path := range []string{adminUsersPath, adminGroupsPath} {
|
||||
options := env.permissionOptions(t, token, path)
|
||||
if int64(len(options)) != seeded+1 {
|
||||
t.Fatalf("%s offers %d options, want the %d seeded rows and one declared code: %+v", path, len(options), seeded, options)
|
||||
}
|
||||
last := options[len(options)-1]
|
||||
if last != (offeredPermission{Code: acmeBlogManage, Label: "Manage blog posts", Tab: "Blog", Comment: "Create, edit and delete posts."}) {
|
||||
t.Fatalf("%s: last option = %+v, want the declared acme.blog.manage", path, last)
|
||||
}
|
||||
found := 0
|
||||
for _, option := range options[:len(options)-1] {
|
||||
if option.Code == acmeBlogManage {
|
||||
t.Fatalf("%s offers %s twice", path, acmeBlogManage)
|
||||
}
|
||||
if option.Code == acmeBlogSeeded {
|
||||
found++
|
||||
if option.Label != "Seeded label" {
|
||||
t.Fatalf("%s: duplicate code label = %q, want the seeded row's", path, option.Label)
|
||||
}
|
||||
}
|
||||
}
|
||||
if found != 1 {
|
||||
t.Fatalf("%s offers %s %d times", path, acmeBlogSeeded, found)
|
||||
}
|
||||
}
|
||||
|
||||
// Without the declaring plugin the editors offer the seeded rows only.
|
||||
plain := newAdminEnv(t)
|
||||
plainToken := plain.admin(t, permAccessUsers)
|
||||
if options := plain.permissionOptions(t, plainToken, adminUsersPath); int64(len(options)) != seeded {
|
||||
t.Fatalf("without acme.blog: %d options, want %d", len(options), seeded)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
9
go.mod
9
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.3
|
||||
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
|
||||
@@ -80,6 +80,7 @@ require (
|
||||
github.com/go-playground/validator/v10 v10.30.4 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/google/wire v0.7.0 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.19.0 // indirect
|
||||
@@ -117,6 +118,7 @@ require (
|
||||
github.com/moby/sys/user v0.4.0 // indirect
|
||||
github.com/moby/sys/userns v0.1.0 // indirect
|
||||
github.com/moby/term v0.5.2 // indirect
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/muesli/mango v0.1.0 // indirect
|
||||
github.com/muesli/mango-cobra v1.2.0 // indirect
|
||||
@@ -134,6 +136,8 @@ require (
|
||||
github.com/riverqueue/river/rivershared v0.47.0 // indirect
|
||||
github.com/riverqueue/river/rivertype v0.47.0 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/shirou/gopsutil/v4 v4.26.6 // indirect
|
||||
github.com/sirupsen/logrus v1.9.4 // indirect
|
||||
github.com/spf13/cobra v1.10.2 // indirect
|
||||
@@ -147,6 +151,7 @@ require (
|
||||
github.com/tklauser/numcpus v0.12.0 // indirect
|
||||
github.com/wneessen/go-mail v0.8.1 // indirect
|
||||
github.com/xo/terminfo v1.0.0 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
github.com/yuin/goldmark v1.8.6 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
@@ -161,10 +166,12 @@ require (
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/image v0.46.0 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/term v0.46.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
||||
google.golang.org/api v0.272.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect
|
||||
|
||||
12
go.sum
12
go.sum
@@ -203,6 +203,8 @@ github.com/google/go-replayers/grpcreplay v1.3.0 h1:1Keyy0m1sIpqstQmgz307zhiJ1pV
|
||||
github.com/google/go-replayers/grpcreplay v1.3.0/go.mod h1:v6NgKtkijC0d3e3RW8il6Sy5sqRVUwoQa4mHOGEy8DI=
|
||||
github.com/google/go-replayers/httpreplay v1.2.0 h1:VM1wEyyjaoU53BwrOnaf9VhAyQQEEioJvFYxYcLRKzk=
|
||||
github.com/google/go-replayers/httpreplay v1.2.0/go.mod h1:WahEFFZZ7a1P4VM1qEeHy+tME4bwyqPcwWbNlUI1Mcg=
|
||||
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
|
||||
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc=
|
||||
github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0=
|
||||
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
|
||||
@@ -293,6 +295,8 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g
|
||||
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
|
||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||
github.com/muesli/mango v0.1.0 h1:DZQK45d2gGbql1arsYA4vfg4d7I9Hfx5rX/GCmzsAvI=
|
||||
@@ -333,6 +337,10 @@ github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
|
||||
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
|
||||
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=
|
||||
github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
|
||||
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
||||
@@ -373,6 +381,8 @@ github.com/wneessen/go-mail v0.8.1 h1:tVcncj02/QySVFw3zr/kXOzZcuFQqBNT6K+Rbgm/pc
|
||||
github.com/wneessen/go-mail v0.8.1/go.mod h1:dWZ61zadzCIyvB4y1/YzC5O7MrbbzBfPkARmbosdf8w=
|
||||
github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY=
|
||||
github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
github.com/yuin/goldmark v1.8.6 h1:d0VcaP1sx9GkFVkoW+KtggpGi2KZ965i14b0+bDQST4=
|
||||
github.com/yuin/goldmark v1.8.6/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
@@ -436,6 +446,8 @@ golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
|
||||
@@ -8,6 +8,7 @@ plugin:
|
||||
access_settings: Manage User Settings
|
||||
impersonate_user: Impersonate Users
|
||||
manage_privileged_groups: Manage privileged group membership
|
||||
manage_backend_links: Link frontend accounts to administrators
|
||||
users:
|
||||
menu_label: Users
|
||||
new_user: New User
|
||||
@@ -105,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.
|
||||
@@ -115,3 +118,30 @@ organisation:
|
||||
empty_organisation: — No organisation —
|
||||
oauth:
|
||||
last_method_blocked: This is the only remaining way to sign in. Link another method before disconnecting this one.
|
||||
backend_link:
|
||||
section: Frontend account
|
||||
section_comment: Link your administrator account to your account on the site, so tools you use there can act as this administrator. You sign in on the site to prove the account is yours.
|
||||
status_linked: "Linked to :email"
|
||||
status_unlinked: Not linked
|
||||
link: Link frontend account
|
||||
link_started: Open the link and sign in on the site with the account to link. The link works once, for a few minutes.
|
||||
unlink: Unlink frontend account
|
||||
unlink_confirm: Unlink your frontend account? Tools used through it will no longer act as this administrator.
|
||||
unlinked: The frontend account is unlinked.
|
||||
prompt_email: Frontend account email
|
||||
prompt_comment: The exact email of the frontend user to link to this administrator.
|
||||
set: Link frontend account
|
||||
set_confirm: Link a frontend account to this administrator? Tools that user runs will act as this administrator.
|
||||
set_success: The frontend account is linked.
|
||||
remove: Unlink frontend account
|
||||
remove_confirm: Unlink the frontend account from this administrator?
|
||||
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.
|
||||
|
||||
@@ -8,6 +8,7 @@ plugin:
|
||||
access_settings: Zarządzaj ustawieniami użytkownika
|
||||
impersonate_user: Wcielaj się w użytkowników
|
||||
manage_privileged_groups: Zarządzaj członkostwem w grupach uprzywilejowanych
|
||||
manage_backend_links: Łącz konta na stronie z administratorami
|
||||
users:
|
||||
menu_label: Użytkownicy
|
||||
new_user: Nowy użytkownik
|
||||
@@ -105,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.
|
||||
@@ -115,3 +118,30 @@ organisation:
|
||||
empty_organisation: — Brak organizacji —
|
||||
oauth:
|
||||
last_method_blocked: To jedyna droga logowania na to konto. Najpierw podłącz inną, zanim odetniesz tę.
|
||||
backend_link:
|
||||
section: Konto na stronie
|
||||
section_comment: Połącz konto administratora ze swoim kontem na stronie, aby narzędzia używane tam mogły działać jako ten administrator. Aby potwierdzić, że konto jest Twoje, zaloguj się na stronie.
|
||||
status_linked: "Połączone z :email"
|
||||
status_unlinked: Niepołączone
|
||||
link: Połącz konto na stronie
|
||||
link_started: Otwórz link i zaloguj się na stronie kontem, które chcesz połączyć. Link działa raz, przez kilka minut.
|
||||
unlink: Odłącz konto na stronie
|
||||
unlink_confirm: Odłączyć konto na stronie? Narzędzia używane przez nie przestaną działać jako ten administrator.
|
||||
unlinked: Konto na stronie zostało odłączone.
|
||||
prompt_email: Email konta na stronie
|
||||
prompt_comment: Dokładny email użytkownika strony, którego połączyć z tym administratorem.
|
||||
set: Połącz konto na stronie
|
||||
set_confirm: Połączyć konto na stronie z tym administratorem? Narzędzia uruchamiane przez tego użytkownika będą działać jako ten administrator.
|
||||
set_success: Konto na stronie zostało połączone.
|
||||
remove: Odłącz konto na stronie
|
||||
remove_confirm: Odłączyć konto na stronie od tego administratora?
|
||||
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.
|
||||
|
||||
24
mcp.go
Normal file
24
mcp.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
var _ pact.HasMCP = (*Plugin)(nil)
|
||||
|
||||
// MCP declares the plugin's MCP tools (D-18). me (exposed as user_me) runs
|
||||
// GET /_user/api/v1/token/me as the signed-in frontend user under the
|
||||
// "user" guard and answers the user payload.
|
||||
func (p *Plugin) MCP() pact.MCP {
|
||||
return pact.MCP{Tools: []pact.MCPTool{{
|
||||
Name: "me",
|
||||
Title: "Current user",
|
||||
Description: "Returns the profile of the signed-in frontend user.",
|
||||
Guard: "user",
|
||||
Method: http.MethodGet,
|
||||
Path: "/_user/api/v1/token/me",
|
||||
Input: struct{}{},
|
||||
}}}
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
191
mcp_guard_smoke_test.go
Normal file
191
mcp_guard_smoke_test.go
Normal file
@@ -0,0 +1,191 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// mintUserToken stores a personal API token of the user with the scopes and
|
||||
// returns its secret and row.
|
||||
func (e *adminEnv) mintUserToken(t *testing.T, user *models.User, scopes ...string) (string, *models.APIToken) {
|
||||
t.Helper()
|
||||
secret, token, err := classes.MintAPIToken(classes.DefaultAPITokenPrefix, user.ID, "mcp "+adminStamp(), scopes, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.gdb.Create(token).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return secret, token
|
||||
}
|
||||
|
||||
// grantGroup stores the codes as the group's permissions.
|
||||
func (e *adminEnv) grantGroup(t *testing.T, group *models.UserGroup, codes ...string) {
|
||||
t.Helper()
|
||||
parts := make([]string, 0, len(codes))
|
||||
for _, code := range codes {
|
||||
parts = append(parts, strconv.Quote(code)+":1")
|
||||
}
|
||||
if err := e.gdb.Exec(`UPDATE user_groups SET permissions = ? WHERE id = ?`, "{"+strings.Join(parts, ",")+"}", group.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUserMCPGuardSmoke: the "user" guard provider is registered and
|
||||
// published as the personal token resolver; it reads the plugin's route
|
||||
// middleware, allows a tool with exactly the checks the routes run (scopes
|
||||
// from the session, permission codes from the user's groups, every code
|
||||
// required), dispatches with the group grants and an in-memory token
|
||||
// credential, and resolves usr_ tokens. GET /token/me, the user_me target,
|
||||
// answers the user payload to a read token only, and revoking a token fires
|
||||
// the revoked subject event.
|
||||
func TestUserMCPGuardSmoke(t *testing.T) {
|
||||
env := newAdminEnv(t)
|
||||
spy := env.spySubjects()
|
||||
ctx := context.Background()
|
||||
guards, ok := env.app.Lookup[*pact.MCPGuards]()
|
||||
if !ok || guards == nil {
|
||||
t.Fatal("*pact.MCPGuards is not published")
|
||||
}
|
||||
guard, ok := guards.Lookup("user")
|
||||
if !ok || guard.MCPGuardName() != "user" {
|
||||
t.Fatalf("user guard = %v %v", guard, ok)
|
||||
}
|
||||
resolver, ok := env.app.Lookup[pact.MCPPersonalTokenResolver]()
|
||||
if !ok || resolver == nil {
|
||||
t.Fatal("pact.MCPPersonalTokenResolver is not published")
|
||||
}
|
||||
|
||||
if !guard.MCPTokenGuarded([]string{"throttle:user-api", "user.api_token", "user.scope:read"}) || guard.MCPTokenGuarded([]string{"throttle:user-api", "jwt.auth"}) {
|
||||
t.Fatal("MCPTokenGuarded must answer true only with user.api_token")
|
||||
}
|
||||
req, err := guard.MCPRequirements([]string{"throttle:user-api", "user.api_token", "user.scope:read", "user.scope:write", "user.permission:acme.posts.edit"})
|
||||
if err != nil || !slices.Equal(req.Scopes, []string{"read", "write"}) || !slices.Equal(req.Permissions, []string{"acme.posts.edit"}) {
|
||||
t.Fatalf("MCPRequirements = %+v %v", req, err)
|
||||
}
|
||||
if _, err := guard.MCPRequirements([]string{"user.api_token", "user.bogus"}); err == nil {
|
||||
t.Fatal("an unknown user.* middleware must be an error")
|
||||
}
|
||||
|
||||
stamp := adminStamp()
|
||||
codeA, codeB, codeOwn := "mcp."+stamp+".a", "mcp."+stamp+".b", "mcp."+stamp+".own"
|
||||
user := env.seedUser(t, "mcp", func(u *models.User) { u.Permissions = models.PermissionSet{codeOwn: 1} })
|
||||
groupA, groupB := env.seedGroup(t, "MCP A "+stamp, "mcp-a-"+stamp), env.seedGroup(t, "MCP B "+stamp, "mcp-b-"+stamp)
|
||||
env.grantGroup(t, groupA, codeA)
|
||||
env.grantGroup(t, groupB, codeB)
|
||||
env.join(t, user, groupA, groupB)
|
||||
subject := pact.MCPSubject{Guard: "user", UserID: user.ID, Scopes: []string{"read"}}
|
||||
allows := func(req pact.MCPRequirements, perms ...string) bool {
|
||||
t.Helper()
|
||||
ok, err := guard.MCPAllows(ctx, subject, req, perms)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
if allows(pact.MCPRequirements{Scopes: []string{"read", "write"}}) {
|
||||
t.Fatal("a scope the session lacks must refuse")
|
||||
}
|
||||
if !allows(pact.MCPRequirements{Scopes: []string{"read"}, Permissions: []string{codeA}}, codeB) {
|
||||
t.Fatal("codes granted by the user's groups must allow")
|
||||
}
|
||||
if allows(pact.MCPRequirements{Scopes: []string{"read"}, Permissions: []string{codeA, "mcp." + stamp + ".missing"}}) {
|
||||
t.Fatal("every code is required: one missing code must refuse")
|
||||
}
|
||||
if allows(pact.MCPRequirements{Scopes: []string{"read"}}, codeOwn) {
|
||||
t.Fatal("a user-level permission alone must not grant (the route checks group grants)")
|
||||
}
|
||||
if ok, err := guard.MCPAllows(ctx, pact.MCPSubject{Guard: "user", UserID: user.ID + 1_000_000, Scopes: []string{"read"}}, pact.MCPRequirements{}, nil); err != nil || ok {
|
||||
t.Fatalf("an unknown user = %v %v", ok, err)
|
||||
}
|
||||
|
||||
dispatch, err := guard.MCPDispatch(ctx, subject, http.MethodGet)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
principal, ok := dispatch.Principal.(*bouncer.Principal)
|
||||
if !ok || principal.ID != user.ID || !principal.PermissionGrants[codeA] || !principal.PermissionGrants[codeB] || principal.PermissionGrants[codeOwn] {
|
||||
t.Fatalf("dispatch principal = %+v", dispatch.Principal)
|
||||
}
|
||||
credential, ok := dispatch.Credential.(*models.APIToken)
|
||||
if !ok || credential.ID != 0 || credential.UserID != user.ID || !credential.HasScope("read") || credential.HasScope("write") {
|
||||
t.Fatalf("dispatch credential = %+v", dispatch.Credential)
|
||||
}
|
||||
if !slices.Equal(dispatch.Guards, []string{"api_token"}) {
|
||||
t.Fatalf("dispatch guards = %v", dispatch.Guards)
|
||||
}
|
||||
|
||||
if _, matched, err := resolver.MCPResolvePersonalToken(ctx, "oas_at_x"); matched || err != nil {
|
||||
t.Fatalf("a foreign prefix = %v %v", matched, err)
|
||||
}
|
||||
readSecret, readToken := env.mintUserToken(t, user, "read", "ai")
|
||||
got, matched, err := resolver.MCPResolvePersonalToken(ctx, readSecret)
|
||||
if err != nil || !matched || got.Guard != "user" || got.UserID != user.ID || got.TokenID != readToken.ID || !slices.Equal(got.Scopes, []string{"read", "ai"}) {
|
||||
t.Fatalf("resolve = %+v %v %v", got, matched, err)
|
||||
}
|
||||
var stamped models.APIToken
|
||||
if err := env.gdb.First(&stamped, readToken.ID).Error; err != nil || stamped.LastUsedAt == nil {
|
||||
t.Fatalf("last_used_at not stamped: %+v %v", stamped, err)
|
||||
}
|
||||
if _, matched, err := resolver.MCPResolvePersonalToken(ctx, classes.DefaultAPITokenPrefix+"not-a-token"); !matched || !errors.Is(err, pact.ErrMCPTokenInvalid) {
|
||||
t.Fatalf("an unknown usr_ token = %v %v", matched, err)
|
||||
}
|
||||
|
||||
// GET /token/me: the user_me target.
|
||||
rec := env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/token/me", readSecret, nil)
|
||||
if !strings.Contains(rec.Body.String(), `"email":"`+user.Email+`"`) || !strings.HasPrefix(rec.Body.String(), `{"user":`) {
|
||||
t.Fatalf("token/me = %s", rec.Body.String())
|
||||
}
|
||||
writeSecret, _ := env.mintUserToken(t, user, "write")
|
||||
rec = env.expect(t, http.StatusForbidden, http.MethodGet, "/_user/api/v1/token/me", writeSecret, nil)
|
||||
if !strings.Contains(rec.Body.String(), "Missing required scope: read") {
|
||||
t.Fatalf("token/me with write = %s", rec.Body.String())
|
||||
}
|
||||
env.expect(t, http.StatusUnauthorized, http.MethodGet, "/_user/api/v1/token/me", freshUserToken(t, user), nil)
|
||||
|
||||
// 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.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) {
|
||||
t.Fatalf("a revoked token = %v %v", matched, err)
|
||||
}
|
||||
|
||||
// Saving a group's permissions on the admin screen fires permissions
|
||||
// for each member after the save commits.
|
||||
if err := env.gdb.Exec(`INSERT INTO golem15_user_frontend_permissions (code, label, tab) VALUES (?, 'A', 'MCP'), (?, 'B', 'MCP')`, codeA, codeB).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spy.reset()
|
||||
manager := env.admin(t, permAccessGroups)
|
||||
env.expect(t, http.StatusOK, http.MethodPut, groupPath(groupA.ID), manager, map[string]any{"name": groupA.Name, "code": *groupA.Code, "permissions": map[string]int{codeA: 1, codeB: 1}})
|
||||
if !spy.has("user", user.ID, pact.MCPSubjectPermissions) {
|
||||
t.Fatalf("group save fired %+v", spy.events)
|
||||
}
|
||||
// Deleting a group fires permissions for its members once it commits.
|
||||
spy.reset()
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, groupPath(groupB.ID), manager, nil)
|
||||
if !spy.has("user", user.ID, pact.MCPSubjectPermissions) {
|
||||
t.Fatalf("group delete fired %+v", spy.events)
|
||||
}
|
||||
// Saving the user on the Users screen fires permissions too.
|
||||
spy.reset()
|
||||
users := env.admin(t, permAccessUsers)
|
||||
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), users, map[string]any{"name": "MCP renamed", "email": user.Email})
|
||||
if !spy.has("user", user.ID, pact.MCPSubjectPermissions) {
|
||||
t.Fatalf("user save fired %+v", spy.events)
|
||||
}
|
||||
}
|
||||
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)
|
||||
|
||||
24
models/backend_link.go
Normal file
24
models/backend_link.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// BackendLink is the verified link between one frontend user and one backend
|
||||
// administrator (golem15_user_backend_links). Each side appears in at most
|
||||
// one link. LinkedBy is the administrator who set the link on the
|
||||
// Administrators screen; it is nil for a link the frontend user confirmed
|
||||
// themselves after the administrator started it on My account.
|
||||
type BackendLink struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
UserID uint `gorm:"column:user_id"`
|
||||
BackendUserID uint `gorm:"column:backend_user_id"`
|
||||
LinkedBy *uint `gorm:"column:linked_by"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
}
|
||||
|
||||
func (BackendLink) TableName() string { return "golem15_user_backend_links" }
|
||||
|
||||
func (BackendLink) Fillable() []string {
|
||||
return []string{"user_id", "backend_user_id", "linked_by"}
|
||||
}
|
||||
|
||||
func init() { Register(BackendLink{}) }
|
||||
31
models/backend_link_request.go
Normal file
31
models/backend_link_request.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// BackendLinkRequest is a one-shot request an administrator starts to link
|
||||
// their account to a frontend user (golem15_user_backend_link_requests).
|
||||
// Only the SHA-256 of the code is stored; the plain code travels once, in
|
||||
// the site URL the administrator opens.
|
||||
type BackendLinkRequest struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
CodeHash string `gorm:"column:code_hash" json:"-"`
|
||||
BackendUserID uint `gorm:"column:backend_user_id"`
|
||||
ExpiresAt time.Time `gorm:"column:expires_at"`
|
||||
UsedAt *time.Time `gorm:"column:used_at"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
}
|
||||
|
||||
func (BackendLinkRequest) TableName() string { return "golem15_user_backend_link_requests" }
|
||||
|
||||
func (BackendLinkRequest) Fillable() []string {
|
||||
return []string{"code_hash", "backend_user_id", "expires_at", "used_at"}
|
||||
}
|
||||
|
||||
func (BackendLinkRequest) Hidden() []string { return []string{"code_hash"} }
|
||||
|
||||
// IsUsableAt is false once the request was used or has expired.
|
||||
func (r BackendLinkRequest) IsUsableAt(now time.Time) bool {
|
||||
return r.UsedAt == nil && r.ExpiresAt.After(now)
|
||||
}
|
||||
|
||||
func init() { Register(BackendLinkRequest{}) }
|
||||
@@ -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,8 +95,11 @@ func TestPasswordPublicRoutes(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("unset: Routes error %v", err)
|
||||
}
|
||||
if len(base) != 18 {
|
||||
t.Fatalf("unset: %d routes, want 18", 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 {
|
||||
@@ -108,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) != 15 {
|
||||
t.Fatalf("base without the password routes has %d routes, want 15", len(off))
|
||||
if len(off) != 20 {
|
||||
t.Fatalf("base without the password routes has %d routes, want 20", len(off))
|
||||
}
|
||||
|
||||
for _, c := range []struct {
|
||||
|
||||
73
plugin.go
73
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"
|
||||
@@ -107,9 +108,81 @@ func (p *Plugin) Boot(app *backpack.App) error {
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
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
|
||||
// plugin's personal API tokens. Without the MCP module both stay unused.
|
||||
func (p *Plugin) bootMCPGuard(app *backpack.App) error {
|
||||
guards, ok := app.Lookup[*pact.MCPGuards]()
|
||||
if !ok || guards == nil {
|
||||
guards = pact.NewMCPGuards()
|
||||
if err := app.Publish(guards); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
guard := &classes.MCPUserGuard{App: app}
|
||||
if err := guards.Register(guard); err != nil {
|
||||
return err
|
||||
}
|
||||
return app.Publish[pact.MCPPersonalTokenResolver](guard)
|
||||
}
|
||||
|
||||
// bootBackendLinks publishes the account link service as *classes.BackendLinks
|
||||
// and as the MCP linked-backend resolver, and removes a frontend user's link
|
||||
// when the user is deleted or deactivated. The request lifetime is checked
|
||||
// here so a bad golem15.user.backend_links.request_ttl fails the boot.
|
||||
func (p *Plugin) bootBackendLinks(app *backpack.App) error {
|
||||
if _, err := classes.BackendLinkRequestTTL(app); err != nil {
|
||||
return err
|
||||
}
|
||||
links := &classes.BackendLinks{App: app}
|
||||
if err := app.Publish(links); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := app.Publish[pact.MCPLinkedBackendResolver](links); err != nil {
|
||||
return err
|
||||
}
|
||||
links.RegisterBackendLinkListeners(app)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) startBlacklistSweep(bl bouncer.BlacklistStore) {
|
||||
interval := 10 * time.Minute
|
||||
if p.app != nil && p.app.Config != nil {
|
||||
|
||||
@@ -40,8 +40,14 @@ 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")
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
60
updates/202610220001_create_backend_links.go
Normal file
60
updates/202610220001_create_backend_links.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// backendLinkMigrations create the verified frontend-to-backend account link
|
||||
// (one frontend user to one administrator, both sides unique) and the
|
||||
// one-shot link requests an administrator starts on My account. A request
|
||||
// stores only the SHA-256 of its code. Deleting either account removes its
|
||||
// link and requests; deleting the administrator who set a link keeps the
|
||||
// link and clears linked_by.
|
||||
//
|
||||
// The foreign keys to backend_users are added when that table exists, which
|
||||
// it always does when lagoon.Migrate runs the plugin (the admin's own
|
||||
// migrations run first); a run of the plugin's migrations alone, as some
|
||||
// tests do, creates the tables without them.
|
||||
var backendLinkMigrations = []*gormigrate.Migration{
|
||||
{
|
||||
ID: "202610220001_create_golem15_user_backend_links",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`CREATE TABLE golem15_user_backend_links (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||
backend_user_id INTEGER NOT NULL UNIQUE,
|
||||
linked_by INTEGER NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE TABLE golem15_user_backend_link_requests (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
code_hash CHAR(64) NOT NULL UNIQUE,
|
||||
backend_user_id INTEGER NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
used_at TIMESTAMPTZ NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX golem15_user_backend_link_requests_backend_user_id_index ON golem15_user_backend_link_requests (backend_user_id);
|
||||
DO $$
|
||||
BEGIN
|
||||
IF to_regclass('backend_users') IS NOT NULL THEN
|
||||
ALTER TABLE golem15_user_backend_links
|
||||
ADD CONSTRAINT golem15_user_backend_links_backend_user_id_foreign
|
||||
FOREIGN KEY (backend_user_id) REFERENCES backend_users(id) ON DELETE CASCADE,
|
||||
ADD CONSTRAINT golem15_user_backend_links_linked_by_foreign
|
||||
FOREIGN KEY (linked_by) REFERENCES backend_users(id) ON DELETE SET NULL;
|
||||
ALTER TABLE golem15_user_backend_link_requests
|
||||
ADD CONSTRAINT golem15_user_backend_link_requests_backend_user_id_foreign
|
||||
FOREIGN KEY (backend_user_id) REFERENCES backend_users(id) ON DELETE CASCADE;
|
||||
END IF;
|
||||
END
|
||||
$$`).Error
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec("DROP TABLE IF EXISTS golem15_user_backend_link_requests; DROP TABLE IF EXISTS golem15_user_backend_links").Error
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func init() { Register(backendLinkMigrations...) }
|
||||
@@ -52,6 +52,7 @@ func TestCreateOrganisationsMigration(t *testing.T) {
|
||||
"202610050001_create_oauth_identities",
|
||||
"202610160002_add_handle_to_users",
|
||||
"202610210001_add_users_email_verified_at",
|
||||
"202610220001_create_golem15_user_backend_links",
|
||||
}
|
||||
if len(ids) != len(want) {
|
||||
t.Fatalf("history = %v", ids)
|
||||
@@ -62,9 +63,9 @@ func TestCreateOrganisationsMigration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Email proof, handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist,
|
||||
// throttle, extend-users, then organisations.
|
||||
for range 12 {
|
||||
// Backend links, email proof, handle, OAuth identities, the three admin migrations, API tokens, user groups,
|
||||
// jwt blacklist, throttle, extend-users, then organisations.
|
||||
for range 13 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -54,8 +54,8 @@ func TestUserGroupsMigration(t *testing.T) {
|
||||
t.Fatalf("users_groups primary key = %q", pk)
|
||||
}
|
||||
|
||||
// Email verified at, handle, OAuth identities, frontend permissions, last seen, API tokens, user permissions, then user groups.
|
||||
for range 8 {
|
||||
// Backend links, email verified at, handle, OAuth identities, frontend permissions, last seen, API tokens, user permissions, then user groups.
|
||||
for range 9 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -47,9 +47,9 @@ func TestExtendUsersMigration(t *testing.T) {
|
||||
if !row.HasSelfSetPassword || row.IsActivated || row.MarketingConsent || row.IsOnboarded {
|
||||
t.Fatalf("defaults = %+v", row)
|
||||
}
|
||||
// Email verified at, handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist,
|
||||
// throttle, then extend-users.
|
||||
for range 11 {
|
||||
// Backend links, email verified at, handle, OAuth identities, the three admin migrations, API tokens, user groups,
|
||||
// jwt blacklist, throttle, then extend-users.
|
||||
for range 12 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -88,8 +88,8 @@ func TestCreateUserThrottleMigration(t *testing.T) {
|
||||
t.Fatalf("missing column %s", col)
|
||||
}
|
||||
}
|
||||
// Email verified at, handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist, then throttle.
|
||||
for range 10 {
|
||||
// Backend links, email verified at, handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist, then throttle.
|
||||
for range 11 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -120,8 +120,8 @@ func TestCreateJwtBlacklistMigration(t *testing.T) {
|
||||
t.Fatalf("missing column %s", col)
|
||||
}
|
||||
}
|
||||
// Email verified at, handle, OAuth identities, the three admin migrations, API tokens, user groups, then jwt blacklist.
|
||||
for range 9 {
|
||||
// Backend links, email verified at, handle, OAuth identities, the three admin migrations, API tokens, user groups, then jwt blacklist.
|
||||
for range 10 {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user