5 Commits

Author SHA1 Message Date
Jakub Zych
c3712dc0d4 fix: deactivate and ban revoke sessions and API tokens, and /refresh refuses deactivated, banned and cut-off subjects
classes.RevokeUserAccess stamps users.tokens_valid_after (whole seconds) and
revokes the users' personal API tokens; DeactivateUsers and BanUsers call
it for every selected user. Restore and unban revive nothing, and a
deactivated user who signs in again gets a fresh working token.

POST /refresh now loads the token's subject after bouncer.Refresh and
refuses a missing, deactivated or banned user and a token issued before
tokens_valid_after with the existing 401 body; a refused refresh stamps no
last_seen. Suspension is deliberately not checked.
2026-10-22 03:11:32 +02:00
Jakub Zych
e0b5ffe20d fix: log /register listener failures instead of discarding them
A failing user.Register or user.Created listener is logged at Error level
with the user ID; the committed registration still succeeds.
2026-10-22 03:07:22 +02:00
Jakub Zych
b6b7ac7534 fix: registration fills only an explicit allow-list and never takes the IP columns from the body
User.RegisterFillable lists what a registration body may set: name,
surname, email, password, preferred_locale and marketing_consent.
RegisterUser fills from it instead of Fillable, so organisation_id,
organisation_role, is_onboarded and must_change_password can no longer be
mass-assigned through POST /register, and created_ip_address and
last_ip_address come only from RegisterOptions.IP. Fillable is unchanged
for the admin form and trusted application code.
2026-10-22 03:03:18 +02:00
Jakub Zych
499b6dc408 test: migration rollback counts include the email_verified_at migration
The rollback tests of user groups, extend-users, throttle and jwt blacklist
stopped one migration short since 202610210001 was added.
2026-10-22 03:02:08 +02:00
Jakub Zych
9986342c23 feat: console help, examples and named loggers (SummerCMS v0.4.0)
Every command gets long help and examples, descriptions in imperative
sentence case, and a warn-only TestCommandsDocumented over bonfire.CheckDocs.
The plugin logs through a diary component logger instead of the process
default logger. Requires SummerCMS v0.4.0; command names and flags unchanged.

user:token:create and user:token:list gain --json, user:backfill-handles a
progress bar; planning IDs leave the descriptions.
2026-10-21 18:03:50 +02:00
24 changed files with 964 additions and 90 deletions

View File

@@ -16,27 +16,28 @@ It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_ap
## Features
- **Registration and activation.** `POST /register`, `POST /activate`, `POST /activate-by-code`. Registration can be switched off and throttled; `activate_mode` is `auto`, `user` (a mailed code) or `admin`, with codes from `IssueActivationCode` and `VerifyActivationCode`.
- **JWT sessions.** `POST /login`, `GET /fetch`, `POST /refresh`, `POST /logout`. Boot registers the `jwt` guard with the framework's `bouncer.Registry` and exposes it as the `jwt.auth` middleware for other plugins. Logged-out tokens go to the Postgres `jwt_blacklist`, which a background sweep prunes.
- **Registration and activation.** `POST /register`, `POST /activate`, `POST /activate-by-code`. Registration can be switched off and throttled; `activate_mode` is `auto`, `user` (a mailed code) or `admin`, with codes from `IssueActivationCode` and `VerifyActivationCode`. A `/register` body sets only the `User.RegisterFillable` columns: `name`, `surname`, `email`, `password` (stored as its hash), `preferred_locale` and `marketing_consent`. It cannot set `organisation_id` or `organisation_role` (membership is the administrator's or the application's), `is_onboarded`, `must_change_password`, or the activation, reset, address proof, handle and permission columns; other keys are ignored (they still reach `RegisterEvent.Payload`). `created_ip_address` and `last_ip_address` are server-set from the client address only.
- **JWT sessions.** `POST /login`, `GET /fetch`, `POST /refresh`, `POST /logout`. Boot registers the `jwt` guard with the framework's `bouncer.Registry` and exposes it as the `jwt.auth` middleware for other plugins. Logged-out tokens go to the Postgres `jwt_blacklist`, which a background sweep prunes. `POST /refresh` loads the token's user and refuses (401, `Could not refresh token`, `User not found`) a deactivated or banned user and a token issued before the user's `tokens_valid_after`; a suspension alone does not stop a refresh.
- **Password reset and change.** `POST /forgot-password` answers the same body for known and unknown addresses; `POST /reset-password` consumes a code from `IssueResetCode`. `POST /change-password` requires the current password.
- **Must-change-password lock.** The `user:require-password-change` console command flags an account. The flag rides on the authenticated principal (`bouncer.Principal.MustChangePassword`) for guards and other plugins to act on, and a successful `POST /change-password` clears it.
- **Login throttling.** Failed logins are counted per user and IP in `user_throttle` (`CheckAndRecordLogin`, `RejectIfThrottled`) and suspend the account for a configured time.
- **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. 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.
- **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; 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.
- **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; 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). Deleting an organisation clears `organisation_id` and `organisation_role` of its members first.
- **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 `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.
- **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.
- **Address proof.** `users.email_verified_at` records when the account's owner proved control of the address (`User.EmailVerifiedAt`). Exactly two flows write it: the mailed activation code (`POST /activate`, `POST /activate-by-code` and the invitation link, through `VerifyActivationCode`) and a completed reset-code password reset (`POST /reset-password`). `POST /register` in `auto` or `admin` mode, `RegisterUser`, an administrator's create and the admin Activate action, `POST /change-password` and social sign-ins record none. The proof follows the address: an email change through `POST /update` or the admin Users form clears it, while a change of letter case only keeps it. The column is never mass-assigned and is in no user API payload, admin form or list. No migration or code path backfills it: accounts from before v0.1.5 have no proof. An application that trusts its imported addresses may set the column in its own data migration; this plugin does not. A social-login plugin links a verified provider's identity onto an existing account only when it is set.
- **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.
- **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). `CreatedEvent` (`classes.CreatedEventName` `user.Created`) fires from API register and admin create. `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.
- **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.
- **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.
@@ -126,7 +127,7 @@ The three screens are served by the framework's generic admin API under `<admin
| Admin controllers | `golem15.user.users`, `golem15.user.usergroups` and `golem15.user.organisations`, from `controllers.AdminControllers` |
| Navigation | main item `user` (order 555) with the side items `users`, `usergroups` and `organisations`, each shown to an administrator who holds its permission |
| Relation manager | `members` on `golem15.user.organisations` (link and unlink) |
| Bulk actions (Users) | `activate`, `deactivate`, `restore`, `ban`, `unban`, and the built-in delete |
| 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` |
Backend permissions, all on the tab `golem15.user::lang.plugin.tab`:
@@ -168,11 +169,11 @@ Migrations added for address proof, all additive:
Packages:
- `controllers`: the route handlers above, `AdminControllers` (the admin controller list), `PermissionAccessUsers` and `PermissionAccessGroups`, plus the registration steps `POST /register` runs, for other plugins:
- `RegisterUser(ctx, app, db, fields, RegisterOptions)` validates `fields` against the user model's rules, hashes the password with `golem15.user.password.bcrypt_cost` and creates the user on `db` (which may be a transaction). It returns the validation errors instead of writing a response and never modifies `fields`. `RegisterOptions.Activate` creates the account activated; `RegisterOptions.IP` records the client IP; `RegisterOptions.PasswordLess` stores `has_self_set_password=false` for an account whose random password the user never knew (a social sign-in), while the zero value keeps `true`.
- `FireRegisterEvent(ctx, app, user, fields)` fires `RegisterEvent` with `Payload` set to a copy of `fields` without `password` and `password_confirmation`, and returns the listeners' error (`/register` ignores it). Fire it after the user row is committed.
- `FireCreatedEvent(ctx, app, user)` fires `CreatedEvent` (`user.Created`). `/register` ignores that error.
- `RegisterUser(ctx, app, db, fields, RegisterOptions)` validates `fields` against the user model's rules, hashes the password with `golem15.user.password.bcrypt_cost` and creates the user on `db` (which may be a transaction). It fills only the `User.RegisterFillable` columns and ignores every other key of `fields`: an organisation membership and role are set with an explicit update after creation, as an application's onboarding does. It returns the validation errors instead of writing a response and never modifies `fields`. `RegisterOptions.Activate` creates the account activated; `RegisterOptions.IP` records the client IP and is the only source of `created_ip_address` and `last_ip_address` (both stay NULL without it, whatever `fields` says); `RegisterOptions.PasswordLess` stores `has_self_set_password=false` for an account whose random password the user never knew (a social sign-in), while the zero value keeps `true`.
- `FireRegisterEvent(ctx, app, user, fields)` fires `RegisterEvent` with `Payload` set to a copy of `fields` without `password` and `password_confirmation`, and returns the listeners' error (`/register` logs it and continues). `Payload` carries every extra key the client sent, so treat it as untrusted. Fire it after the user row is committed.
- `FireCreatedEvent(ctx, app, user)` fires `CreatedEvent` (`user.Created`) and returns the listeners' error; `/register` logs it and continues.
- `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` for every selected user that was not deactivated yet; a listener error rolls the action back.
- `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.
- `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.
@@ -182,13 +183,14 @@ Packages:
- `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`.
- `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.
- `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` blacklists the request's JWT until it expires (as `POST /logout` does) and writes the forget cookie of `bouncer.LoadCookieConfig`, best effort: 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.
- `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`).
- `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.
- `updates`: the gormigrate migrations, returned by `updates.All()`.
- `console`: `RequirePasswordChange`, `BackfillHandles` and `APITokenCommands`.
@@ -221,19 +223,19 @@ Defaults live in `config/config.yaml` and are merged under `golem15.user.*`. Any
## CLI commands
| Command | Purpose |
|---------|---------|
| `user:require-password-change <email>` | Flag an account so its next session must set a new password. |
| `user:backfill-handles` | Assign a unique handle to every user row that still has none. |
| `user:token:create <email> [--name api] [--scopes read,write] [--expires RFC3339]` | Create an application-wide API token and print its secret once. |
| `user:token:list` | List token metadata without secrets or hashes. |
| `user:token:revoke <id>` | Revoke a shared API token immediately. |
| Command | Purpose | Example |
|---------|---------|---------|
| `user:require-password-change <email>` | Flag an account so its next session must set a new password. Ends with `Password change required for <email>`. | `bin/<app> user:require-password-change jane@example.com` |
| `user:backfill-handles` | Assign a unique handle to every user row that still has none, with a progress bar. Ends with `Assigned handles to N user(s)`. | `bin/<app> user:backfill-handles` |
| `user:token:create <email> [--name api] [--scopes read,write] [--expires RFC3339] [--json]` | Create an application-wide API token and print its secret once (also under `-q`); `--json` prints the token and its details as one object. | `bin/<app> user:token:create jane@example.com --scopes read --json` |
| `user:token:list` | List token metadata without secrets or hashes; `--json` prints a JSON array with the expiry, revocation and last-use times. | `bin/<app> user:token:list --json` |
| `user:token:revoke <id>` | Revoke a shared API token immediately. | `bin/<app> user:token:revoke 12` |
Each command uses the database the serve command published or, run from the console, opens one from `database.dsn` (and loads the encryption keys from `app.key`) for its duration.
Each command uses the database the serve command published or, run from the console, opens one from `database.dsn` (and loads the encryption keys from `app.key`) for its duration. `bin/<app> help <command>` shows each command's long help and examples. The plugin logs through the component `user` (`log.components.user` in `config/log.yaml`).
## Dependencies
- The SummerCMS framework, `git.golem15.com/golem15/summercms` (modules `backpack`, `bonfire`, `bouncer`, `pact`, `party`, `surf` and others).
- The SummerCMS framework v0.4.0, `git.golem15.com/golem15/summercms` (modules `backpack`, `bonfire`, `bouncer`, `diary`, `pact`, `party`, `surf` and others).
- gormigrate, GORM, golang-jwt and gocloud.dev, as pinned in `go.mod`.
- testcontainers-go for the Postgres-backed tests.
@@ -246,4 +248,10 @@ go test ./... # full run, starts Postgres with testcontainers (needs D
`TestRegisterCORSPath` reads the host application's `config/http.yaml`, so run the tests inside an application checkout where the plugin is mounted at `plugins/golem15/user`.
`TestCommandsDocumented` (in `-short`) logs, without failing, each command whose help lacks a description, long help, examples or an option description (`bonfire.CheckDocs`).
`TestRegisterIgnoresProtectedFields` posts organisation, IP and account-flag keys to `/register` and `RegisterUser` and checks that only the allow-listed columns and the server-side IP are stored; `TestRegisterListenerErrors` checks that failing register and created listeners do not fail the registration.
`TestOffboarding` runs the admin deactivate and ban bulk actions and checks that the user's older session JWT and personal API token stop working, that a password login restores a deactivated account with a working token while the old credentials stay dead, and that unban revives nothing; `TestRefreshSubjectChecks` covers the `/refresh` subject checks; `TestRevokeUserAccess` (in `classes`) covers the revocation writes.
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`.

View File

@@ -3,7 +3,6 @@ package classes
import (
"context"
"fmt"
"log/slog"
"strconv"
"time"
@@ -91,8 +90,41 @@ func ActivateUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int,
return changed, nil
}
// RevokeUserAccess ends every session JWT issued before now and every
// personal API token of userIDs: it stamps users.tokens_valid_after with the
// current time truncated to whole seconds (soft-deleted rows included) and
// sets revoked_at on each of their user_api_tokens rows that is not revoked
// yet (earlier revoked_at values stay). The jwt guard, RequestUser and
// /refresh refuse a token whose iat precedes tokens_valid_after; the
// user.api_token guard refuses a revoked row. JWT iat has whole-second
// precision, so the cutoff is truncated: a token minted right after the
// revocation (a reactivating login) is valid, and so is one minted earlier
// within that same second. An empty list writes nothing. It takes the
// handle of the caller's transaction. DeactivateUsers and BanUsers call it;
// an application may call it for its own offboarding, and after writing a
// ban directly to user_throttle.
func RevokeUserAccess(ctx context.Context, db *gorm.DB, userIDs []uint) error {
if db == nil {
return fmt.Errorf("golem15.user: gorm handle is missing")
}
if len(userIDs) == 0 {
return nil
}
cutoff := time.Now().Truncate(time.Second)
if err := fresh(ctx, db).Unscoped().Model(&models.User{}).Where("id IN ?", userIDs).UpdateColumn("tokens_valid_after", cutoff).Error; err != nil {
return err
}
return fresh(ctx, db).Model(&models.APIToken{}).
Where("user_id IN ? AND revoked_at IS NULL", userIDs).
UpdateColumn("revoked_at", cutoff).Error
}
// DeactivateUsers soft-deletes the users that are not deactivated yet, the
// PHP $user->delete(), and returns how many it changed.
// PHP $user->delete(), and returns how many it changed. It then ends the
// sessions and personal API tokens of every selected user, already
// deactivated ones included (RevokeUserAccess), so a deactivated account
// keeps no working credential: its owner signs in again, which restores
// it, and gets a fresh token. Restoring revives no revoked token.
func DeactivateUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
if db == nil {
return 0, fmt.Errorf("golem15.user: gorm handle is missing")
@@ -110,6 +142,13 @@ func DeactivateUsers(ctx context.Context, db *gorm.DB, users []*models.User) (in
user.DeletedAt = gorm.DeletedAt{Time: now, Valid: true}
changed++
}
ids, err := userIDs(db, users)
if err != nil {
return 0, err
}
if err := RevokeUserAccess(ctx, db, ids); err != nil {
return 0, err
}
return changed, nil
}
@@ -137,7 +176,9 @@ func RestoreUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int,
// BanUsers bans the users and returns how many were not banned before. A ban
// is set on every user_throttle row of the user, and a row without an IP
// address is created when the user has none, so a login from any address is
// refused (RejectIfThrottled falls back to that row).
// refused (RejectIfThrottled falls back to that row). It then ends the
// sessions and personal API tokens of every selected user, already banned
// ones included (RevokeUserAccess); unbanning revives none of them.
func BanUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
ids, err := userIDs(db, users)
if err != nil {
@@ -165,6 +206,9 @@ func BanUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, erro
changed++
}
}
if err := RevokeUserAccess(ctx, db, ids); err != nil {
return 0, err
}
return changed, nil
}
@@ -241,7 +285,7 @@ func ForceDeleteCleanup(ctx context.Context, db *gorm.DB, bucket *blob.Bucket, u
// 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 {
slog.Default().Warn("golem15.user: remove attachment blobs of a deleted user", "user_id", userID, "err", err)
pluginLog.Warn("golem15.user: remove attachment blobs of a deleted user", "user_id", userID, "err", err)
}
})
return nil

View File

@@ -437,3 +437,126 @@ func TestAdminActions(t *testing.T) {
}
})
}
// TestRevokeUserAccess: the cutoff is stamped in whole seconds on active and
// deactivated users, every live API token of the users is revoked, earlier
// revocations keep their time, other users are untouched, and DeactivateUsers
// and BanUsers revoke for every selected user with unchanged counts.
func TestRevokeUserAccess(t *testing.T) {
ctx := t.Context()
db := throttleDB(t)
token := func(t *testing.T, user *models.User, revoked *time.Time) models.APIToken {
t.Helper()
row := models.APIToken{UserID: user.ID, TokenHash: "hash-" + strconv.FormatUint(uint64(user.ID), 10) + "-" + strconv.FormatInt(time.Now().UnixNano(), 10), RevokedAt: revoked}
if err := db.Create(&row).Error; err != nil {
t.Fatal(err)
}
return row
}
reloadToken := func(t *testing.T, id uint) models.APIToken {
t.Helper()
var row models.APIToken
if err := db.Take(&row, id).Error; err != nil {
t.Fatal(err)
}
return row
}
t.Run("a missing handle is an error and an empty list writes nothing", func(t *testing.T) {
if err := RevokeUserAccess(ctx, nil, []uint{1}); err == nil {
t.Fatal("nil handle accepted")
}
if err := RevokeUserAccess(ctx, db, nil); err != nil {
t.Fatal(err)
}
})
t.Run("stamps the cutoff and revokes live tokens only", func(t *testing.T) {
active := actionUser(t, db, "revoke-active", nil)
gone := actionUser(t, db, "revoke-gone", func(u *models.User) {
u.DeletedAt = gorm.DeletedAt{Time: time.Now(), Valid: true}
})
other := actionUser(t, db, "revoke-other", nil)
earlier := time.Now().Add(-time.Hour).Truncate(time.Microsecond)
live := token(t, active, nil)
old := token(t, active, &earlier)
goneTok := token(t, gone, nil)
otherTok := token(t, other, nil)
before := time.Now().Truncate(time.Second)
if err := RevokeUserAccess(ctx, db, []uint{active.ID, gone.ID}); err != nil {
t.Fatal(err)
}
after := time.Now()
for _, id := range []uint{active.ID, gone.ID} {
row := actionReload(t, db, id)
if row.TokensValidAfter == nil || row.TokensValidAfter.Before(before) || row.TokensValidAfter.After(after) ||
!row.TokensValidAfter.Equal(row.TokensValidAfter.Truncate(time.Second)) {
t.Fatalf("user %d tokens_valid_after = %v", id, row.TokensValidAfter)
}
}
if row := actionReload(t, db, other.ID); row.TokensValidAfter != nil {
t.Fatalf("other user stamped: %v", row.TokensValidAfter)
}
for _, id := range []uint{live.ID, goneTok.ID} {
if row := reloadToken(t, id); row.RevokedAt == nil {
t.Fatalf("token %d not revoked", id)
}
}
if row := reloadToken(t, old.ID); row.RevokedAt == nil || !row.RevokedAt.Equal(earlier) {
t.Fatalf("earlier revocation changed: %v want %v", row.RevokedAt, earlier)
}
if row := reloadToken(t, otherTok.ID); row.RevokedAt != nil {
t.Fatalf("other user's token revoked")
}
})
t.Run("deactivate and ban revoke for every selected user", func(t *testing.T) {
fresh := actionUser(t, db, "revoke-deactivate", nil)
already := actionUser(t, db, "revoke-already", func(u *models.User) {
u.DeletedAt = gorm.DeletedAt{Time: time.Now(), Valid: true}
})
a, b := token(t, fresh, nil), token(t, already, nil)
changed, err := DeactivateUsers(ctx, db, []*models.User{fresh, already})
if err != nil || changed != 1 {
t.Fatalf("DeactivateUsers = %d, %v", changed, err)
}
for _, id := range []uint{a.ID, b.ID} {
if row := reloadToken(t, id); row.RevokedAt == nil {
t.Fatalf("token %d survived deactivate", id)
}
}
for _, id := range []uint{fresh.ID, already.ID} {
if row := actionReload(t, db, id); row.TokensValidAfter == nil {
t.Fatalf("user %d not stamped by deactivate", id)
}
}
ban := actionUser(t, db, "revoke-ban", nil)
bannedBefore := actionUser(t, db, "revoke-banned-before", nil)
if err := db.Create(&models.Throttle{UserID: bannedBefore.ID, IsBanned: true}).Error; err != nil {
t.Fatal(err)
}
c, d := token(t, ban, nil), token(t, bannedBefore, nil)
changed, err = BanUsers(ContextWithThrottle(ctx, nil), db, []*models.User{ban, bannedBefore})
if err != nil || changed != 1 {
t.Fatalf("BanUsers = %d, %v", changed, err)
}
for _, id := range []uint{c.ID, d.ID} {
if row := reloadToken(t, id); row.RevokedAt == nil {
t.Fatalf("token %d survived ban", id)
}
}
// Unban and restore revive nothing.
if _, err := UnbanUsers(ctx, db, []*models.User{ban}); err != nil {
t.Fatal(err)
}
if _, err := RestoreUsers(ctx, db, []*models.User{fresh}); err != nil {
t.Fatal(err)
}
for _, id := range []uint{a.ID, c.ID} {
if row := reloadToken(t, id); row.RevokedAt == nil {
t.Fatalf("token %d revived", id)
}
}
})
}

View File

@@ -2,7 +2,6 @@ package classes
import (
"context"
"log/slog"
"strings"
"git.golem15.com/golem15/summercms/modules/backpack"
@@ -36,7 +35,7 @@ func AuthorizeUser() lighthouse.AuthorizerFunc {
func RegisterUserAuthorizer(app *backpack.App) error {
svc, err := lighthouse.From(app)
if err != nil {
slog.Default().Warn("golem15.user: lighthouse unavailable; user authorizer not registered", "err", err)
pluginLog.Warn("golem15.user: lighthouse unavailable; user authorizer not registered", "err", err)
return nil
}
if svc == nil || svc.Registry() == nil {

View File

@@ -5,7 +5,6 @@ import (
"crypto/md5"
"errors"
"fmt"
"log/slog"
"strconv"
"strings"
@@ -52,7 +51,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 {
slog.Default().Error("golem15.user: avatar thumb", "err", err)
pluginLog.Error("golem15.user: avatar thumb", "err", err)
return "/" + attach.BlobKey(f.DiskName), nil
}
return url, nil

View File

@@ -59,8 +59,10 @@ type DeletingEvent struct {
// DeactivatingEvent fires after a user is soft-deleted (deactivated, the
// PHP $user->delete()) by the admin deactivate action, inside the same
// transaction, so listeners can revoke what a deactivated account must not
// keep (OAuth grants, for example) while leaving what a restore needs. A
// listener error rolls the deactivation back.
// keep (OAuth grants, for example) while leaving what a restore needs. The
// user's session JWTs and personal API tokens are already revoked when it
// fires (DeactivateUsers calls RevokeUserAccess). A listener error rolls the
// deactivation back.
type DeactivatingEvent struct {
User *models.User
Tx *gorm.DB

7
classes/logger.go Normal file
View File

@@ -0,0 +1,7 @@
package classes
import "git.golem15.com/golem15/summercms/modules/diary"
// pluginLog is the plugin's logger: its records carry component=user, so
// config/log.yaml can raise or lower them (log.components.user).
var pluginLog = diary.For("user")

View File

@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
@@ -99,7 +98,7 @@ func EndRequestSession(ctx context.Context, app *backpack.App, w http.ResponseWr
if app != nil && app.Config != nil {
loaded, err := bouncer.LoadCookieConfig(app.Config)
if err != nil {
slog.Default().Warn("golem15.user: end session: cookie config", "err", err)
pluginLog.Warn("golem15.user: end session: cookie config", "err", err)
} else {
cfg = loaded
}
@@ -126,7 +125,7 @@ func revokeSessionToken(ctx context.Context, app *backpack.App, raw string) {
return
}
if err := bl.Add(ctx, jti, exp, time.Now()); err != nil {
slog.Default().Warn("golem15.user: end session: blacklist token", "err", err)
pluginLog.Warn("golem15.user: end session: blacklist token", "err", err)
}
}

View File

@@ -0,0 +1,21 @@
package user
import (
"testing"
"git.golem15.com/golem15/summercms/modules/bonfire"
)
// TestCommandsDocumented logs every console command whose help lacks a
// description, long help, examples or an option description
// (bonfire.CheckDocs). It only warns: the framework's own coverage test
// fails on a gap, plugin repositories report it.
func TestCommandsDocumented(t *testing.T) {
commands := (&Plugin{}).Commands()
if len(commands) == 0 {
t.Fatal("the plugin declares no commands")
}
for _, problem := range bonfire.CheckDocs(commands) {
t.Logf("%s", problem)
}
}

View File

@@ -2,6 +2,7 @@ package console
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
@@ -28,11 +29,25 @@ func APITokenCommands(app *backpack.App, withDB func(context.Context, func(*gorm
return []bonfire.Command{
{
Name: "user:token:create", Description: "Create one API token usable by application plugins",
Long: `Mints a personal API token that acts as the user with this e-mail, for
scripts and integrations that call the application's API. --scopes limits
what it may do (read, write, ai); --expires sets an RFC3339 expiry, and
without it the token does not expire. The secret is printed once, on its own
line (also under -q), and only its hash is stored, so keep it now; with
--json the token and its details are printed as one JSON object instead.
Revoke a token with user:token:revoke and list them with user:token:list.`,
Args: []bonfire.Arg{{Name: "email", Description: "E-mail of the user the token acts as", Required: true}},
Flags: []bonfire.Flag{
{Name: "name", Description: "What the token is for", Default: "api"},
{Name: "scopes", Description: "Comma-separated scopes: read, write, ai", Default: "read,write"},
{Name: "expires", Description: "RFC3339 expiry; empty means no expiry"},
{Name: "json", Description: "Print the token and its details as JSON", Bare: true},
},
Examples: []bonfire.Example{
{Command: "user:token:create jane@example.com --name backup-script --scopes read", Description: "A read-only token for a script"},
{Command: "user:token:create jane@example.com --expires 2027-01-01T00:00:00Z", Description: "A read and write token that expires"},
{Command: "user:token:create jane@example.com --json", Description: "Print the token and its details as JSON"},
},
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
email, _ := in.Argument("email")
@@ -71,6 +86,17 @@ func APITokenCommands(app *backpack.App, withDB func(context.Context, func(*gorm
if err := db.Create(token).Error; err != nil {
return fmt.Errorf("user:token:create: %w", err)
}
if flagOn(in, "json") {
return printJSON(out, map[string]any{
"id": token.ID,
"user_id": token.UserID,
"email": user.Email,
"name": token.Name,
"token": secret,
"scopes": token.Scopes.Get(),
"expires_at": token.ExpiresAt,
})
}
out.Printf("token %d for %s, scopes %s\n", token.ID, email, strings.Join(token.Scopes.Get(), ","))
out.Println(secret)
out.Success("user:token:create: store the secret now; it is not shown again")
@@ -80,13 +106,25 @@ func APITokenCommands(app *backpack.App, withDB func(context.Context, func(*gorm
},
{
Name: "user:token:list", Description: "List API tokens",
Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error {
Long: `Lists every personal API token: its id, the user it acts as, its name, its
scopes and its state (active, expired or revoked). Secrets are never shown;
only their hashes are stored. --json prints the tokens as a JSON array with
their expiry, revocation and last use times.`,
Flags: []bonfire.Flag{
{Name: "json", Description: "Print the tokens as JSON", Bare: true},
},
Examples: []bonfire.Example{
{Command: "user:token:list", Description: "Show every token as a table"},
{Command: "user:token:list --json", Description: "Print the tokens as JSON for a script"},
},
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
return open(ctx, func(db *gorm.DB) error {
var tokens []models.APIToken
if err := db.Order("id").Find(&tokens).Error; err != nil {
return fmt.Errorf("user:token:list: %w", err)
}
rows := make([][]string, 0, len(tokens))
list := make([]map[string]any, 0, len(tokens))
for _, token := range tokens {
state := "active"
if token.RevokedAt != nil {
@@ -99,6 +137,20 @@ func APITokenCommands(app *backpack.App, withDB func(context.Context, func(*gorm
name = *token.Name
}
rows = append(rows, []string{strconv.FormatUint(uint64(token.ID), 10), strconv.FormatUint(uint64(token.UserID), 10), name, strings.Join(token.Scopes.Get(), ","), state})
list = append(list, map[string]any{
"id": token.ID,
"user_id": token.UserID,
"name": token.Name,
"scopes": token.Scopes.Get(),
"state": state,
"expires_at": token.ExpiresAt,
"revoked_at": token.RevokedAt,
"last_used_at": token.LastUsedAt,
"created_at": token.CreatedAt,
})
}
if flagOn(in, "json") {
return printJSON(out, list)
}
out.Table([]string{"id", "user", "name", "scopes", "state"}, rows)
return nil
@@ -107,7 +159,13 @@ func APITokenCommands(app *backpack.App, withDB func(context.Context, func(*gorm
},
{
Name: "user:token:revoke", Description: "Revoke an API token",
Long: `Revokes the active API token with this id (see user:token:list): requests
that present it are refused from now on. The token row stays, marked
revoked; a token that is already revoked or does not exist is an error.`,
Args: []bonfire.Arg{{Name: "id", Description: "Token id", Required: true}},
Examples: []bonfire.Example{
{Command: "user:token:revoke 12", Description: "Revoke the token with id 12"},
},
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
raw, _ := in.Argument("id")
id, err := strconv.ParseUint(raw, 10, 64)
@@ -129,3 +187,24 @@ func APITokenCommands(app *backpack.App, withDB func(context.Context, func(*gorm
},
}
}
// printJSON writes v as indented JSON and a newline on out: data, printed
// under -q too.
func printJSON(out bonfire.Output, v any) error {
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
out.Println(string(b))
return nil
}
// flagOn reads a bare flag ("true" when given).
func flagOn(in bonfire.Input, name string) bool {
v, _ := in.Flag(name)
switch strings.ToLower(strings.TrimSpace(v)) {
case "true", "1", "yes":
return true
}
return false
}

View File

@@ -19,7 +19,18 @@ import (
func BackfillHandles(app *backpack.App) bonfire.Command {
return bonfire.Command{
Name: "user:backfill-handles",
Description: "Assign unique handles to users that do not have one (D-15)",
Description: "Assign unique handles to users that do not have one",
Long: `Gives every user without a handle a unique one, derived the same way as
for a new registration, with a progress bar over the users (hidden under
-q). Users that already have a handle are not touched, so running it again
changes nothing.
Run it once after copying users from WinterCMS, which had no handles. It
ends with "Assigned handles to N user(s)".`,
Examples: []bonfire.Example{
{Command: "user:backfill-handles", Description: "Assign a handle to every user that has none"},
{Command: "user:backfill-handles -q", Description: "Run it quietly, printing only the result line"},
},
Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error {
if app == nil {
return fmt.Errorf("user:backfill-handles: app is nil")
@@ -38,11 +49,20 @@ func BackfillHandles(app *backpack.App) bonfire.Command {
return err
}
n := 0
for i := range users {
if err := classes.AssignHandle(ctx, gdb, &users[i]); err != nil {
if len(users) > 0 {
err := out.Progress(len(users), func(p bonfire.Progress) error {
for i := range users {
if err := classes.AssignHandle(ctx, gdb, &users[i]); err != nil {
return err
}
n++
p.Advance(1)
}
return nil
})
if err != nil {
return err
}
n++
}
out.Success(fmt.Sprintf("Assigned handles to %d user(s)", n))
return nil

View File

@@ -15,7 +15,14 @@ import (
func RequirePasswordChange(withDB func(context.Context, func(*gorm.DB) error) error) bonfire.Command {
return bonfire.Command{
Name: "user:require-password-change",
Description: "Force a user to change their password on next login (D-21)",
Description: "Force a user to change their password on next login",
Long: `Marks the account with this e-mail so that it must set a new password at its
next sign-in; setting the password clears the mark. Use it after a suspected
leak or when handing over an account created with a temporary password. It
ends with "Password change required for <email>".`,
Examples: []bonfire.Example{
{Command: "user:require-password-change jane@example.com", Description: "Make Jane set a new password at her next sign-in"},
},
Args: []bonfire.Arg{{
Name: "email",
Description: "Account email",

View File

@@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/url"
@@ -30,6 +29,7 @@ import (
"git.golem15.com/golem15/summercms/modules/postcard"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/golem15/summercms/modules/wire"
"github.com/golang-jwt/jwt/v5"
"gocloud.dev/blob"
"gorm.io/gorm"
)
@@ -110,7 +110,7 @@ func Login(app *backpack.App) http.HandlerFunc {
}
// A failed last_seen write is logged and never fails the login.
if err := classes.TouchLastSeen(ctx, gdb, user.ID); err != nil {
slog.Default().Warn("golem15.user: stamp last_seen on login", "user_id", user.ID, "err", err)
pluginLog.Warn("golem15.user: stamp last_seen on login", "user_id", user.ID, "err", err)
}
token, err := mintFor(app, secret, user, requestURL(r))
if err != nil {
@@ -175,7 +175,9 @@ func Fetch(app *backpack.App) http.HandlerFunc {
}
}
// Refresh slides a still-refreshable bearer token.
// Refresh slides a still-refreshable bearer token of a user who may still
// sign in: deactivated and banned users and tokens issued before the user's
// tokens_valid_after are refused with the token-failure 401 body.
func Refresh(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gdb, secret, ok := sessionDeps(w, app)
@@ -199,19 +201,85 @@ func Refresh(app *backpack.App) http.HandlerFunc {
})
return
}
// The refresh never loads the user row: the subject comes from the
// new token. A failed last_seen write is logged and never fails it.
if sub, _, _, _, err := bouncer.VerifyClaims(next, secret); err == nil {
if id, err := strconv.ParseUint(sub, 10, 64); err == nil && id != 0 {
if err := classes.TouchLastSeen(r.Context(), gdb, uint(id)); err != nil {
slog.Default().Warn("golem15.user: stamp last_seen on refresh", "user_id", id, "err", err)
}
}
// bouncer.Refresh checked the token only (signature, audience,
// refresh window, blacklist). The subject check loads the user: a
// missing or deactivated user (who signs in again, which restores the
// account), a token issued before tokens_valid_after, and a banned
// user are refused with the same 401 body. Suspension is not
// checked: it is the failed-password throttle, and refusing refresh
// on it would let anyone who knows an email log its owner out.
userID, refused, err := refreshSubjectRefused(r.Context(), app, gdb, raw)
if err != nil {
writeOpaque500(w)
return
}
if refused {
writeJSON(w, http.StatusUnauthorized, map[string]any{
"error": "Could not refresh token",
"msg": bouncer.ErrSubjectRejected.Error(),
})
return
}
// A failed last_seen write is logged and never fails the refresh.
if err := classes.TouchLastSeen(r.Context(), gdb, userID); err != nil {
pluginLog.Warn("golem15.user: stamp last_seen on refresh", "user_id", userID, "err", err)
}
writeJSON(w, http.StatusOK, map[string]any{"token": next})
}
}
// refreshSubjectRefused reads the subject and iat of a token bouncer.Refresh
// has already verified and reports whether its user may not slide the
// session: not found by a scoped load (missing or deactivated), issued
// before the user's tokens_valid_after, or banned. Only a database failure
// is an error.
func refreshSubjectRefused(ctx context.Context, app *backpack.App, gdb *gorm.DB, raw string) (uint, bool, error) {
claims := jwt.MapClaims{}
if _, _, err := jwt.NewParser().ParseUnverified(raw, claims); err != nil {
return 0, true, nil
}
var id uint64
switch v := claims["sub"].(type) {
case string:
n, err := strconv.ParseUint(strings.TrimSpace(v), 10, 64)
if err != nil {
return 0, true, nil
}
id = n
case float64:
if v <= 0 || v != float64(uint64(v)) {
return 0, true, nil
}
id = uint64(v)
}
if id == 0 {
return 0, true, nil
}
iat, err := claims.GetIssuedAt()
if err != nil || iat == nil {
return 0, true, nil
}
var user models.User
result := gdb.WithContext(ctx).Where("id = ?", id).Limit(1).Find(&user)
if result.Error != nil {
return 0, false, result.Error
}
if result.RowsAffected == 0 {
return 0, true, nil
}
if user.TokensValidAfter != nil && iat.Time.Before(*user.TokensValidAfter) {
return 0, true, nil
}
banned, _, err := classes.ThrottleStates(classes.ContextWithThrottle(ctx, app), gdb.WithContext(ctx), []uint{user.ID})
if err != nil {
return 0, false, err
}
if banned[user.ID] {
return 0, true, nil
}
return user.ID, false, nil
}
// OAuthProviders lists the social sign-in providers a social-login plugin
// has enabled, as {success: true, providers: [{name, label}]}. The plugin
// publishes a classes.OAuthProviderSource, looked up on every request
@@ -269,14 +337,14 @@ func ForgotPassword(app *backpack.App) http.HandlerFunc {
ctx := codeContext(r.Context(), app)
user, err := classes.LookupByEmail(ctx, gdb, strField(fields, "email"))
if err != nil {
slog.Default().Error("golem15.user: forgot-password lookup", "err", err)
pluginLog.Error("golem15.user: forgot-password lookup", "err", err)
writeJSON(w, http.StatusOK, map[string]any{"message": forgotPasswordBody})
return
}
if user != nil {
code, err := classes.IssueResetCode(ctx, gdb, user)
if err != nil {
slog.Default().Error("golem15.user: issue reset code", "err", err)
pluginLog.Error("golem15.user: issue reset code", "err", err)
} else {
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
sendTemplateVars(ctx, app, mailName(ctx, user, "golem15.user::mail.restore"), user.Email, mailVars(displayName(user), resetLink(app, user.ID, code), packed))
@@ -536,7 +604,7 @@ func ChangePassword(app *backpack.App) http.HandlerFunc {
return
}
if !user.HasSelfSetPassword {
slog.Default().Error("golem15.user: change-password requires a self-set password", "user_id", user.ID)
pluginLog.Error("golem15.user: change-password requires a self-set password", "user_id", user.ID)
writeOpaque500(w)
return
}
@@ -683,14 +751,20 @@ func Register(app *backpack.App) http.HandlerFunc {
})
return
}
_ = FireRegisterEvent(r.Context(), app, user, fields)
_ = FireCreatedEvent(r.Context(), app, user)
// The row is committed: a failing listener is logged and never undoes
// or fails the registration, as in Winter.
if err := FireRegisterEvent(r.Context(), app, user, fields); err != nil {
pluginLog.Error("golem15.user: register listener failed", "user_id", user.ID, "err", err)
}
if err := FireCreatedEvent(r.Context(), app, user); err != nil {
pluginLog.Error("golem15.user: created listener failed", "user_id", user.ID, "err", err)
}
ctx := r.Context()
if mode == "user" {
vars := mailVars(displayName(user), "", "")
code, err := classes.IssueActivationCode(ctx, gdb, user)
if err != nil {
slog.Default().Error("golem15.user: issue activation code", "err", err)
pluginLog.Error("golem15.user: issue activation code", "err", err)
} else {
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
vars = mailVars(displayName(user), activationLink(app, user.ID, code), packed)
@@ -935,11 +1009,11 @@ func sendTemplateVars(ctx context.Context, app *backpack.App, template, to strin
}
mailer, ok := app.Lookup[postcard.Mailer]()
if !ok || mailer == nil {
slog.Default().Error("golem15.user: mailer is not configured", "template", template)
pluginLog.Error("golem15.user: mailer is not configured", "template", template)
return
}
if err := mailer.Send(ctx, postcard.Message{Template: template, To: []string{to}, Vars: vars}); err != nil {
slog.Default().Error("golem15.user: send mail", "template", template, "err", err)
pluginLog.Error("golem15.user: send mail", "template", template, "err", err)
}
}
@@ -1198,7 +1272,7 @@ func UploadAvatar(app *backpack.App) http.HandlerFunc {
}
bucket, ok := app.Lookup[*blob.Bucket]()
if !ok || bucket == nil {
slog.Default().Error("golem15.user: avatar bucket is not configured")
pluginLog.Error("golem15.user: avatar bucket is not configured")
writeOpaque500(w)
return
}

7
controllers/logger.go Normal file
View File

@@ -0,0 +1,7 @@
package controllers
import "git.golem15.com/golem15/summercms/modules/diary"
// pluginLog is the plugin's logger: its records carry component=user, so
// config/log.yaml can raise or lower them (log.components.user).
var pluginLog = diary.For("user")

View File

@@ -3,7 +3,6 @@ package controllers
import (
"context"
"errors"
"log/slog"
"maps"
"net/http"
"time"
@@ -23,7 +22,9 @@ import (
// RegisterOptions tunes RegisterUser. Activate creates the account already
// activated (activate_mode auto, or a caller that activates explicitly).
// IP, when set, is recorded as created_ip_address and last_ip_address.
// IP, when set, is recorded as created_ip_address and last_ip_address; it is
// the only source of those columns, so with an empty IP they stay NULL
// whatever the fields say.
type RegisterOptions struct {
Activate bool
IP string
@@ -35,12 +36,16 @@ type RegisterOptions struct {
}
// RegisterUser validates fields against the user model's rules, hashes the
// password with golem15.user.password.bcrypt_cost (default 10), fills the
// fillable columns and creates the users row on db, which may be a
// transaction. Validation failures are returned as Laravel's errors object
// (attribute to messages) with a nil user and nothing written; they are not
// written to a response. fields is not modified. The register event is not
// fired: call FireRegisterEvent once the row is committed.
// password with golem15.user.password.bcrypt_cost (default 10), fills only
// the models.User RegisterFillable columns (name, surname, email, password,
// preferred_locale, marketing_consent) and creates the users row on db,
// which may be a transaction. Any other key in fields is ignored: an
// organisation membership and role are set with an explicit update after
// creation, as an application's onboarding does, and the IP columns come
// only from opts.IP. Validation failures are returned as Laravel's errors
// object (attribute to messages) with a nil user and nothing written; they
// are not written to a response. fields is not modified. The register event
// is not fired: call FireRegisterEvent once the row is committed.
func RegisterUser(ctx context.Context, app *backpack.App, db *gorm.DB, fields map[string]any, opts RegisterOptions) (*models.User, map[string][]string, error) {
if db == nil {
return nil, nil, errors.New("golem15.user: gorm handle is missing")
@@ -65,15 +70,18 @@ func RegisterUser(ctx context.Context, app *backpack.App, db *gorm.DB, fields ma
return nil, nil, err
}
input["password"] = hashed
if opts.IP != "" {
input["created_ip_address"] = opts.IP
input["last_ip_address"] = opts.IP
}
user := &models.User{}
production := app == nil || app.Config == nil || !app.Config.Bool("app.debug")
if err := lagoon.Fill(user, user.Fillable(), input, production); err != nil {
if err := lagoon.Fill(user, user.RegisterFillable(), input, production); err != nil {
return nil, nil, err
}
// The IP columns are server-set after the fill, so a body value can never
// reach them.
if opts.IP != "" {
created, last := opts.IP, opts.IP
user.CreatedIPAddress = &created
user.LastIPAddress = &last
}
user.HasSelfSetPassword = !opts.PasswordLess
if opts.Activate {
user.IsActivated = true
@@ -118,15 +126,16 @@ func FinishLogin(ctx context.Context, app *backpack.App, db *gorm.DB, user *mode
user.LastIPAddress = &addr
}
if err := classes.TouchLastSeen(ctx, db, user.ID); err != nil {
slog.Default().Warn("golem15.user: stamp last_seen on login", "user_id", user.ID, "err", err)
pluginLog.Warn("golem15.user: stamp last_seen on login", "user_id", user.ID, "err", err)
}
return nil
}
// FireRegisterEvent fires classes.RegisterEvent for user with Payload set
// to a copy of fields without password and password_confirmation, and
// returns the listeners' error. /register ignores that error, as Winter
// does not stop a registration for a failing listener.
// returns the listeners' error. /register logs that error and continues, as
// Winter does not stop a registration for a failing listener. Payload is
// untrusted client input: it carries every extra key the client sent.
func FireRegisterEvent(ctx context.Context, app *backpack.App, user *models.User, fields map[string]any) error {
if app == nil || app.Events == nil {
return nil
@@ -141,8 +150,8 @@ func FireRegisterEvent(ctx context.Context, app *backpack.App, user *models.User
}
// FireCreatedEvent fires classes.CreatedEvent (user.Created) for user and
// returns the listeners' error. /register ignores that error, as it does
// for FireRegisterEvent.
// returns the listeners' error. /register logs that error and continues, as
// it does for FireRegisterEvent.
func FireCreatedEvent(ctx context.Context, app *backpack.App, user *models.User) error {
if app == nil || app.Events == nil {
return nil

58
go.mod
View File

@@ -3,7 +3,7 @@ module git.golem15.com/golem15/sm-user-plugin
go 1.27.0
require (
git.golem15.com/golem15/summercms v0.1.9
git.golem15.com/golem15/summercms v0.4.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
@@ -14,11 +14,50 @@ require (
)
require (
charm.land/bubbles/v2 v2.2.1 // indirect
charm.land/bubbletea/v2 v2.1.0 // indirect
charm.land/fang/v2 v2.0.1 // indirect
charm.land/huh/v2 v2.0.3 // indirect
charm.land/lipgloss/v2 v2.0.6 // indirect
dario.cat/mergo v1.0.2 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aws/aws-sdk-go-v2 v1.41.9 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 // indirect
github.com/aws/aws-sdk-go-v2/config v1.32.20 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.19.19 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.25 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.1.1 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.19 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.2 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3 // indirect
github.com/aws/smithy-go v1.26.0 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/catppuccin/go v0.2.0 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/harmonica v0.2.0 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect
github.com/charmbracelet/x/ansi v0.11.9 // indirect
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 // indirect
github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
@@ -28,6 +67,7 @@ require (
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.7.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/ebitengine/purego v0.10.1 // indirect
github.com/felixge/httpsnoop v1.1.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
@@ -41,7 +81,9 @@ require (
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/goccy/go-yaml v1.19.2 // 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
github.com/gorilla/css v1.0.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
@@ -57,9 +99,14 @@ require (
github.com/knadh/koanf/v2 v2.3.6 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/lib/pq v1.12.3 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
github.com/magiconair/properties v1.8.10 // indirect
github.com/mattn/go-runewidth v0.0.30 // indirect
github.com/maypok86/otter/v2 v2.3.0 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.2.0 // indirect
@@ -70,16 +117,23 @@ 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/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/mango v0.1.0 // indirect
github.com/muesli/mango-cobra v1.2.0 // indirect
github.com/muesli/mango-pflag v0.1.0 // indirect
github.com/muesli/roff v0.1.0 // indirect
github.com/nicksnyder/go-i18n/v2 v2.6.1 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/redis/go-redis/v9 v9.23.0 // indirect
github.com/riverqueue/river v0.47.0 // indirect
github.com/riverqueue/river/riverdriver v0.47.0 // indirect
github.com/riverqueue/river/riverdriver/riverdatabasesql v0.47.0 // indirect
github.com/riverqueue/river/riverdriver/riverpgxv5 v0.47.0 // indirect
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/shirou/gopsutil/v4 v4.26.6 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/spf13/cobra v1.10.2 // indirect
@@ -92,6 +146,7 @@ require (
github.com/tklauser/go-sysconf v0.4.0 // indirect
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/yuin/goldmark v1.8.6 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
@@ -101,6 +156,7 @@ require (
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.uber.org/atomic v1.12.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/image v0.46.0 // indirect

104
go.sum
View File

@@ -1,5 +1,15 @@
cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
charm.land/bubbletea/v2 v2.1.0 h1:A9fj9h5LFrvQhQHFNggp8K8rvY6CUfgn9dMbb6p2HIw=
charm.land/bubbletea/v2 v2.1.0/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
charm.land/fang/v2 v2.0.1 h1:zQCM8JQJ1JnQX/66B5jlCYBUxL2as5JXQZ2KJ6EL0mY=
charm.land/fang/v2 v2.0.1/go.mod h1:S1GmkpcvK+OB5w9caywUnJcsMew45Ot8FXqoz8ALrII=
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM=
@@ -28,8 +38,14 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0/go.mod h1:IA1C1U7jO/ENqm/vhi7V9YYpBsp+IMyqNrEN94N7tVc=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0 h1:0s6TxfCu2KHkkZPnBfsQ2y5qia0jl3MMrmBhu3nCOYk=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0/go.mod h1:Mf6O40IAyB9zR/1J8nGDDPirZQQPbYJni8Yisy7NTMc=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/alicebob/miniredis/v2 v2.40.0 h1:6IgTQbvm2JiMYZ8yur/acNJzVjtSOWCelxXbk/LUBXc=
github.com/alicebob/miniredis/v2 v2.40.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aws/aws-sdk-go-v2 v1.41.9 h1:/rYeyO2+HrMztAmxAq9++XJtFMqSIpSsNA0yDGALYq4=
github.com/aws/aws-sdk-go-v2 v1.41.9/go.mod h1:+HsoOEX80qAVUitj1A2DhCNTjmb3edVyuDypb6LNEeo=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
@@ -68,10 +84,52 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.42.3 h1:ErklX/7uhSbkAAeyQD/Y1OoQ9hO3
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3/go.mod h1:ULe4HCzfKPiR6R3HEurE3b1upEkuk8AkMrOKtaOxKO8=
github.com/aws/smithy-go v1.26.0 h1:9ouqbi+NyKP7fV3Te7UElCwdAb6Y8uk7LGwPE5tVe/s=
github.com/aws/smithy-go v1.26.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o=
github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/catppuccin/go v0.2.0 h1:ktBeIrIP42b/8FGiScP9sgrWOss3lw0Z5SktRoithGA=
github.com/catppuccin/go v0.2.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio=
github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM=
github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w=
github.com/charmbracelet/x/conpty v0.1.1 h1:s1bUxjoi7EpqiXysVtC+a8RrvPPNcNvAjfi4jxsAuEs=
github.com/charmbracelet/x/conpty v0.1.1/go.mod h1:OmtR77VODEFbiTzGE9G1XiRJAga6011PIm4u5fTNZpk=
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 h1:IJDiTgVE56gkAGfq0lBEloWgkXMk4hl/bmuPoicI4R0=
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444/go.mod h1:T9jr8CzFpjhFVHjNjKwbAD7KwBNyFnj2pntAO7F2zw0=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=
github.com/charmbracelet/x/exp/ordered v0.1.0 h1:55/qLwjIh0gL0Vni+QAWk7T/qRVP6sBf+2agPBgnOFE=
github.com/charmbracelet/x/exp/ordered v0.1.0/go.mod h1:5UHwmG+is5THxMyCJHNPCn2/ecI07aKNrW+LcResjJ8=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
github.com/charmbracelet/x/xpty v0.1.3 h1:eGSitii4suhzrISYH50ZfufV3v085BXQwIytcOdFSsw=
github.com/charmbracelet/x/xpty v0.1.3/go.mod h1:poPYpWuLDBFCKmKLDnhBp51ATa0ooD8FhypRwEFtH3Y=
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
@@ -96,6 +154,8 @@ github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=
@@ -139,6 +199,12 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-replayers/grpcreplay v1.3.0 h1:1Keyy0m1sIpqstQmgz307zhiJ1pV4uIlFds5weTmxbo=
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/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=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -149,6 +215,8 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA
github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=
github.com/googleapis/gax-go/v2 v2.19.0 h1:fYQaUOiGwll0cGj7jmHT/0nPlcrZDFPrZRhTsoCr8hE=
github.com/googleapis/gax-go/v2 v2.19.0/go.mod h1:w2ROXVdfGEVFXzmlciUU4EdjHgWvB5h2n6x/8XSTTJA=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0=
@@ -167,6 +235,8 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=
github.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=
github.com/knadh/koanf/parsers/yaml v1.1.1 h1:u70vV5IyaM0HvONh8HoqBC97oTgO33KcpZbTLiKVinU=
@@ -183,16 +253,26 @@ github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak=
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk=
github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/maypok86/otter/v2 v2.3.0 h1:8H8AVVFUSzJwIegKwv1uF5aGitTY+AIrtktg7OcLs8w=
github.com/maypok86/otter/v2 v2.3.0/go.mod h1:XgIdlpmL6jYz882/CAx1E4C1ukfgDKSaw4mWq59+7l8=
github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI=
github.com/mdelapenya/tlscert v0.2.0/go.mod h1:O4njj3ELLnJjGdkN7M/vIVCpZ+Cf0L6muqOG4tLSl8o=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
@@ -213,6 +293,16 @@ 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/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=
github.com/muesli/mango v0.1.0/go.mod h1:5XFpbC8jY5UUv89YQciiXNlbi+iJgt29VDC5xbzrLL4=
github.com/muesli/mango-cobra v1.2.0 h1:DQvjzAM0PMZr85Iv9LIMaYISpTOliMEg+uMFtNbYvWg=
github.com/muesli/mango-cobra v1.2.0/go.mod h1:vMJL54QytZAJhCT13LPVDfkvCUJ5/4jNUKF/8NC2UjA=
github.com/muesli/mango-pflag v0.1.0 h1:UADqbYgpUyRoBja3g6LUL+3LErjpsOwaC9ywvBWe7Sg=
github.com/muesli/mango-pflag v0.1.0/go.mod h1:YEQomTxaCUp8PrbhFh10UfbhbQrM/xJ4i2PB8VTLLW0=
github.com/muesli/roff v0.1.0 h1:YD0lalCotmYuF5HhZliKWlIx7IEhiXeSfq7hNjFqGF8=
github.com/muesli/roff v0.1.0/go.mod h1:pjAHQM9hdUUwm/krAfrLGgJkXJ+YuhtsfZ42kieB2Ig=
github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
@@ -224,6 +314,8 @@ github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/riverqueue/river v0.47.0 h1:j8HOEyiOE8gRRhVS2wllKams372TH1WWiH6xCakXHqc=
github.com/riverqueue/river v0.47.0/go.mod h1:Wgmwx475ZBd8lQnNrJgyG2DWH7BfyNiSAtv0rC9bJBQ=
github.com/riverqueue/river/riverdriver v0.47.0 h1:qU8VkjdMl9plqeRg57SxsDUM/i/eECaSYejZ7HynC60=
@@ -236,6 +328,8 @@ github.com/riverqueue/river/rivershared v0.47.0 h1:jdtFsBexCvLqTXf8wnDnGXvB/eeOt
github.com/riverqueue/river/rivershared v0.47.0/go.mod h1:w8Pi1T+6ypyko5/hs9Mv7IIIKo4fAL9eXYnkVV/Y418=
github.com/riverqueue/river/rivertype v0.47.0 h1:SzNavtLGR4nMT1QkrEYQ7n96OMatYsn/z3aJWhewmv0=
github.com/riverqueue/river/rivertype v0.47.0/go.mod h1:XKkcRQR6zm8RR/JQa1Q2ywpj8uXQu21quPa4Lpw1Xhw=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
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=
@@ -277,10 +371,16 @@ github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqo
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
github.com/wneessen/go-mail v0.8.1 h1:tVcncj02/QySVFw3zr/kXOzZcuFQqBNT6K+Rbgm/pcM=
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/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=
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/detectors/gcp v1.42.0 h1:kpt2PEJuOuqYkPcktfJqWWDjTEd/FNgrxcniL7kQrXQ=
@@ -301,6 +401,8 @@ go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRk
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
@@ -310,6 +412,8 @@ gocloud.dev v0.46.0 h1:niIuZwSjMtBx8K+ITB2s5kZullB13PGOS2ZoQPZxQ4Q=
gocloud.dev v0.46.0/go.mod h1:ACQe+2qO+hEO+pdcvvsM+RB63r8TyGD1W3ESCLFyzvM=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=

7
logger.go Normal file
View File

@@ -0,0 +1,7 @@
package user
import "git.golem15.com/golem15/summercms/modules/diary"
// pluginLog is the plugin's logger: its records carry component=user, so
// config/log.yaml can raise or lower them (log.components.user).
var pluginLog = diary.For("user")

View File

@@ -81,8 +81,12 @@ func (User) AttachRelations() []attach.Relation {
return []attach.Relation{{Name: AvatarField, Public: true}}
}
// Fillable is the register/update field list. Username, PIN, and GDPR columns
// stay out of Phase 7 because no ported handler reads them.
// Fillable is the mass-assignment backstop of the admin Users form and of
// trusted application code: cabana intersects it with the form's writable
// fields (and an application's form extensions) and keeps organisation_id
// protected. Registration does not use it: RegisterUser fills only
// RegisterFillable. Username, PIN and GDPR columns stay out because no
// ported handler reads them.
func (User) Fillable() []string {
return []string{
"name", "surname", "email", "password", "created_ip_address", "last_ip_address",
@@ -91,6 +95,20 @@ func (User) Fillable() []string {
}
}
// RegisterFillable is the explicit allow-list of the columns a registration
// body may set (POST /register and controllers.RegisterUser): name, surname,
// email, password (stored as its hash), preferred_locale and
// marketing_consent. A registration body can never set organisation_id or
// organisation_role (membership is the administrator's or the
// application's), created_ip_address or last_ip_address (server-set from
// RegisterOptions.IP only), is_onboarded (application-owned onboarding
// state) or must_change_password (set by an administrator or the
// require-password-change command). The activation, reset, address proof,
// handle and permission columns are never fillable at all.
func (User) RegisterFillable() []string {
return []string{"name", "surname", "email", "password", "preferred_locale", "marketing_consent"}
}
// Hidden mirrors PHP User::$hidden for the secrets this model stores.
func (User) Hidden() []string {
return []string{"password", "reset_password_code", "activation_code"}

195
offboarding_test.go Normal file
View File

@@ -0,0 +1,195 @@
package user
import (
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/controllers"
usermiddleware "git.golem15.com/golem15/sm-user-plugin/middleware"
"git.golem15.com/golem15/sm-user-plugin/models"
)
const refusedRefreshBody = `{"error":"Could not refresh token","msg":"User not found"}`
// offboardingCreds gives a seeded user an older session JWT (issued two
// seconds ago, so a revocation cutoff in this second cuts it) and a usr_
// personal API token.
func offboardingCreds(t *testing.T, e *adminEnv, user *models.User) (jwt, apiSecret string) {
t.Helper()
now := time.Now()
jwt = craftToken(t, strconv.FormatUint(uint64(user.ID), 10), "off-"+adminStamp(), now.Add(-2*time.Second), now.Add(time.Hour))
secret, token, err := classes.MintAPIToken("usr_", user.ID, "offboarding", []string{"read"}, nil, nil)
if err != nil {
t.Fatal(err)
}
if err := e.gdb.Create(token).Error; err != nil {
t.Fatal(err)
}
return jwt, secret
}
// apiTokenWorks authenticates secret through the user.api_token guard.
func apiTokenWorks(t *testing.T, e *adminEnv, secret string) bool {
t.Helper()
guard := &usermiddleware.APITokenGuard{App: e.app}
req := httptest.NewRequest(http.MethodGet, "/api/v1/example", nil)
req.Header.Set("Authorization", "Bearer "+secret)
principal, _, err := guard.AuthenticateCredential(req)
return err == nil && principal != nil
}
func (e *adminEnv) fetchCode(t *testing.T, token string) int {
t.Helper()
return e.call(t, http.MethodGet, "/_user/api/v1/fetch", token, nil).Code
}
func (e *adminEnv) refresh(t *testing.T, token string) *httptest.ResponseRecorder {
t.Helper()
return e.call(t, http.MethodPost, "/_user/api/v1/refresh", token, nil)
}
func assertRefreshRefused(t *testing.T, rec *httptest.ResponseRecorder) {
t.Helper()
if rec.Code != http.StatusUnauthorized || rec.Body.String() != refusedRefreshBody {
t.Fatalf("refresh = %d %s, want 401 %s", rec.Code, rec.Body.String(), refusedRefreshBody)
}
}
// TestOffboarding: deactivate and ban end every earlier session JWT and
// personal API token. A deactivated user reactivates by signing in and gets
// a working token; a banned one is refused. Restore and unban revive no
// token.
func TestOffboarding(t *testing.T) {
e := newAdminEnv(t)
admin := e.admin(t, controllers.PermissionAccessUsers)
t.Run("deactivate", func(t *testing.T) {
user := e.seedUser(t, "off-deactivate", nil)
jwt, secret := offboardingCreds(t, e, user)
if e.fetchCode(t, jwt) != http.StatusOK || !apiTokenWorks(t, e, secret) {
t.Fatal("credentials do not work before the deactivation")
}
e.expect(t, http.StatusOK, http.MethodPost, adminAPI(adminUsersPath+"/bulk/deactivate"), admin, map[string]any{"ids": []uint{user.ID}})
if code := e.fetchCode(t, jwt); code != http.StatusUnauthorized {
t.Fatalf("fetch after deactivate = %d", code)
}
if apiTokenWorks(t, e, secret) {
t.Fatal("API token works after deactivate")
}
assertRefreshRefused(t, e.refresh(t, jwt))
// Signing in right away (the same second allowed) restores the
// account, mails the reactivation and returns a working token.
code, fresh := e.userLogin(t, user.Email, "correct-horse")
if code != http.StatusOK || fresh == "" {
t.Fatalf("login after deactivate = %d", code)
}
if row := e.reload(t, user.ID); row == nil || row.DeletedAt.Valid {
t.Fatal("login did not restore the account")
}
if len(e.mails(user.Email)) != 1 {
t.Fatalf("reactivate mails = %d", len(e.mails(user.Email)))
}
if code := e.fetchCode(t, fresh); code != http.StatusOK {
t.Fatalf("fetch with the fresh token = %d", code)
}
if code := e.fetchCode(t, jwt); code != http.StatusUnauthorized {
t.Fatalf("old JWT after the restore = %d", code)
}
if apiTokenWorks(t, e, secret) {
t.Fatal("old API token works after the restore")
}
})
t.Run("ban", func(t *testing.T) {
user := e.seedUser(t, "off-ban", nil)
jwt, secret := offboardingCreds(t, e, user)
e.expect(t, http.StatusOK, http.MethodPost, adminAPI(adminUsersPath+"/bulk/ban"), admin, map[string]any{"ids": []uint{user.ID}})
if code := e.fetchCode(t, jwt); code != http.StatusUnauthorized {
t.Fatalf("fetch after ban = %d", code)
}
if apiTokenWorks(t, e, secret) {
t.Fatal("API token works after ban")
}
assertRefreshRefused(t, e.refresh(t, jwt))
rec := e.call(t, http.MethodPost, "/_user/api/v1/login", "", map[string]string{"email": user.Email, "password": "correct-horse"})
if rec.Code != http.StatusUnauthorized || rec.Body.String() != invalidLoginBody {
t.Fatalf("banned login = %d %s", rec.Code, rec.Body.String())
}
e.expect(t, http.StatusOK, http.MethodPost, adminAPI(adminUsersPath+"/bulk/unban"), admin, map[string]any{"ids": []uint{user.ID}})
if code := e.fetchCode(t, jwt); code != http.StatusUnauthorized {
t.Fatalf("old JWT after unban = %d", code)
}
if apiTokenWorks(t, e, secret) {
t.Fatal("old API token works after unban")
}
code, fresh := e.userLogin(t, user.Email, "correct-horse")
if code != http.StatusOK || e.fetchCode(t, fresh) != http.StatusOK {
t.Fatalf("login after unban = %d", code)
}
})
}
// TestRefreshSubjectChecks: /refresh loads the subject even without a
// revocation stamp. Deactivated, banned and cut-off subjects are refused
// with the token-failure body and stamp no last_seen; a suspended user still
// refreshes, and a normal refresh stamps last_seen.
func TestRefreshSubjectChecks(t *testing.T) {
e := newAdminEnv(t)
token := func(t *testing.T, user *models.User, iat time.Time) string {
t.Helper()
return craftToken(t, strconv.FormatUint(uint64(user.ID), 10), "refresh-"+adminStamp(), iat, iat.Add(time.Hour))
}
lastSeen := func(t *testing.T, user *models.User) *time.Time {
t.Helper()
return e.reload(t, user.ID).LastSeen
}
t.Run("deactivated", func(t *testing.T) {
user := e.seedUser(t, "refresh-deactivated", nil)
if err := e.gdb.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, user.ID).Error; err != nil {
t.Fatal(err)
}
assertRefreshRefused(t, e.refresh(t, token(t, user, time.Now())))
if lastSeen(t, user) != nil {
t.Fatal("a refused refresh stamped last_seen")
}
})
t.Run("banned", func(t *testing.T) {
user := e.seedUser(t, "refresh-banned", nil)
e.seedThrottle(t, user, "", true, nil)
assertRefreshRefused(t, e.refresh(t, token(t, user, time.Now())))
if lastSeen(t, user) != nil {
t.Fatal("a refused refresh stamped last_seen")
}
})
t.Run("issued before tokens_valid_after", func(t *testing.T) {
user := e.seedUser(t, "refresh-cutoff", nil)
if err := e.gdb.Exec(`UPDATE users SET tokens_valid_after = ? WHERE id = ?`, time.Now().Truncate(time.Second), user.ID).Error; err != nil {
t.Fatal(err)
}
assertRefreshRefused(t, e.refresh(t, token(t, user, time.Now().Add(-10*time.Second))))
})
t.Run("suspended", func(t *testing.T) {
user := e.seedUser(t, "refresh-suspended", nil)
now := time.Now()
e.seedThrottle(t, user, "203.0.113.50", false, &now)
if rec := e.refresh(t, token(t, user, time.Now())); rec.Code != http.StatusOK {
t.Fatalf("suspended refresh = %d %s", rec.Code, rec.Body.String())
}
})
t.Run("normal", func(t *testing.T) {
user := e.seedUser(t, "refresh-normal", nil)
if rec := e.refresh(t, token(t, user, time.Now())); rec.Code != http.StatusOK {
t.Fatalf("refresh = %d %s", rec.Code, rec.Body.String())
}
if lastSeen(t, user) == nil {
t.Fatal("refresh did not stamp last_seen")
}
})
}

View File

@@ -6,7 +6,6 @@ import (
"embed"
"fmt"
"io/fs"
"log/slog"
"net/http"
"strings"
"time"
@@ -138,7 +137,7 @@ func (p *Plugin) startBlacklistSweep(bl bouncer.BlacklistStore) {
select {
case <-ticker.C:
if err := bl.Sweep(context.Background(), time.Now()); err != nil {
slog.Default().Error("golem15.user: jwt blacklist sweep", "err", err)
pluginLog.Error("golem15.user: jwt blacklist sweep", "err", err)
}
case <-stop:
return

View File

@@ -2,6 +2,7 @@ package user
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
@@ -248,6 +249,102 @@ func TestRegisterEventPayload(t *testing.T) {
}
}
// TestRegisterListenerErrors: failing register and created listeners are
// logged and neither fail nor undo the registration.
func TestRegisterListenerErrors(t *testing.T) {
app, gdb := sessionApp(t, "0s")
disableRegisterThrottle(t, app)
app.Events.Listen[*classes.RegisterEvent]("failing-register", func(context.Context, *classes.RegisterEvent) error {
return errors.New("register listener down")
})
app.Events.Listen[*classes.CreatedEvent]("failing-created", func(context.Context, *classes.CreatedEvent) error {
return errors.New("created listener down")
})
rec := postJSON(t, controllers.Register(app), "/_user/api/v1/register", `{"email":"listener-fail@example.test","password":"correct-horse"}`)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"token"`) {
t.Fatalf("register %d %s", rec.Code, rec.Body.String())
}
var count int64
if err := gdb.Model(&models.User{}).Where("email = ?", "listener-fail@example.test").Count(&count).Error; err != nil || count != 1 {
t.Fatalf("stored users = %d, %v", count, err)
}
}
// TestRegisterIgnoresProtectedFields: a registration body sets only the
// RegisterFillable columns. Organisation membership, the IP columns and the
// account flags in the body are ignored, over HTTP and through RegisterUser,
// and the IP columns come only from the server-side address.
func TestRegisterIgnoresProtectedFields(t *testing.T) {
app, gdb := sessionApp(t, "0s")
disableRegisterThrottle(t, app)
org := &models.Organisation{Name: "Mass Assign Org", Slug: "mass-assign-org"}
if err := gdb.Create(org).Error; err != nil {
t.Fatal(err)
}
protected := func(email string) map[string]any {
return map[string]any{
"email": email, "password": "correct-horse", "password_confirmation": "correct-horse", "name": "Mal", "surname": "Lory",
"preferred_locale": "pl", "marketing_consent": true,
"organisation_id": org.ID, "organisation_role": "owner",
"created_ip_address": "203.0.113.9", "last_ip_address": "203.0.113.9",
"is_onboarded": true, "must_change_password": true,
}
}
check := func(t *testing.T, email string, wantIP *string) {
t.Helper()
var stored models.User
if err := gdb.Where("email = ?", email).Take(&stored).Error; err != nil {
t.Fatal(err)
}
if stored.Name == nil || *stored.Name != "Mal" || stored.Surname == nil || *stored.Surname != "Lory" ||
stored.PreferredLocale == nil || *stored.PreferredLocale != "pl" || !stored.MarketingConsent {
t.Fatalf("allowed columns not stored: %+v", stored)
}
if stored.OrganisationID != nil || stored.OrganisationRole != nil {
t.Fatalf("organisation from the body: id %v role %v", stored.OrganisationID, stored.OrganisationRole)
}
if stored.IsOnboarded || stored.MustChangePassword {
t.Fatalf("account flags from the body: onboarded %v must_change %v", stored.IsOnboarded, stored.MustChangePassword)
}
for name, got := range map[string]*string{"created_ip_address": stored.CreatedIPAddress, "last_ip_address": stored.LastIPAddress} {
switch {
case wantIP == nil && got != nil:
t.Fatalf("%s = %q, want NULL", name, *got)
case wantIP != nil && (got == nil || *got != *wantIP):
t.Fatalf("%s = %v, want %q", name, got, *wantIP)
}
}
}
t.Run("http", func(t *testing.T) {
body, err := json.Marshal(protected("mass-http@example.test"))
if err != nil {
t.Fatal(err)
}
rec := postRegister(t, app, "192.0.2.44", string(body))
if rec.Code != http.StatusOK {
t.Fatalf("register %d %s", rec.Code, rec.Body.String())
}
ip := "192.0.2.44"
check(t, "mass-http@example.test", &ip)
})
t.Run("RegisterUser with IP", func(t *testing.T) {
_, errs, err := controllers.RegisterUser(t.Context(), app, gdb, protected("mass-ip@example.test"), controllers.RegisterOptions{IP: "198.51.100.7"})
if err != nil || len(errs) != 0 {
t.Fatalf("RegisterUser = %v, %v", errs, err)
}
ip := "198.51.100.7"
check(t, "mass-ip@example.test", &ip)
})
t.Run("RegisterUser without IP", func(t *testing.T) {
_, errs, err := controllers.RegisterUser(t.Context(), app, gdb, protected("mass-noip@example.test"), controllers.RegisterOptions{})
if err != nil || len(errs) != 0 {
t.Fatalf("RegisterUser = %v, %v", errs, err)
}
check(t, "mass-noip@example.test", nil)
})
}
func TestRegisterImportDirection(t *testing.T) {
cmd := exec.Command("go", "list", "-deps", "./...")
cmd.Dir = moduleRoot(t)

View File

@@ -54,8 +54,8 @@ func TestUserGroupsMigration(t *testing.T) {
t.Fatalf("users_groups primary key = %q", pk)
}
// Handle, OAuth identities, frontend permissions, last seen, API tokens, user permissions, then user groups.
for range 7 {
// Email verified at, handle, OAuth identities, frontend permissions, last seen, API tokens, user permissions, then user groups.
for range 8 {
if err := m.RollbackLast(); err != nil {
t.Fatal(err)
}

View File

@@ -47,9 +47,9 @@ func TestExtendUsersMigration(t *testing.T) {
if !row.HasSelfSetPassword || row.IsActivated || row.MarketingConsent || row.IsOnboarded {
t.Fatalf("defaults = %+v", row)
}
// Handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist,
// Email verified at, handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist,
// throttle, then extend-users.
for range 10 {
for range 11 {
if err := m.RollbackLast(); err != nil {
t.Fatal(err)
}
@@ -88,8 +88,8 @@ func TestCreateUserThrottleMigration(t *testing.T) {
t.Fatalf("missing column %s", col)
}
}
// Handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist, then throttle.
for range 9 {
// Email verified at, handle, OAuth identities, the three admin migrations, API tokens, user groups, jwt blacklist, then throttle.
for range 10 {
if err := m.RollbackLast(); err != nil {
t.Fatal(err)
}
@@ -120,8 +120,8 @@ func TestCreateJwtBlacklistMigration(t *testing.T) {
t.Fatalf("missing column %s", col)
}
}
// Handle, OAuth identities, the three admin migrations, API tokens, user groups, then jwt blacklist.
for range 8 {
// Email verified at, handle, OAuth identities, the three admin migrations, API tokens, user groups, then jwt blacklist.
for range 9 {
if err := m.RollbackLast(); err != nil {
t.Fatal(err)
}