Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3712dc0d4 | ||
|
|
e0b5ffe20d | ||
|
|
b6b7ac7534 | ||
|
|
499b6dc408 |
28
README.md
28
README.md
@@ -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`.
|
||||
|
||||
@@ -248,4 +250,8 @@ go test ./... # full run, starts Postgres with testcontainers (needs D
|
||||
|
||||
`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`.
|
||||
|
||||
@@ -90,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")
|
||||
@@ -109,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
|
||||
}
|
||||
|
||||
@@ -136,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 {
|
||||
@@ -164,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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -29,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"
|
||||
)
|
||||
@@ -174,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)
|
||||
@@ -198,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 {
|
||||
pluginLog.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
|
||||
@@ -682,8 +751,14 @@ 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), "", "")
|
||||
|
||||
@@ -22,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
|
||||
@@ -34,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")
|
||||
@@ -64,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
|
||||
@@ -124,8 +133,9 @@ func FinishLogin(ctx context.Context, app *backpack.App, db *gorm.DB, user *mode
|
||||
|
||||
// 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
|
||||
@@ -140,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
|
||||
|
||||
@@ -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
195
offboarding_test.go
Normal 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")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user