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.
This commit is contained in:
Jakub Zych
2026-10-22 03:11:32 +02:00
parent e0b5ffe20d
commit 09ebc6cd87
6 changed files with 456 additions and 18 deletions

View File

@@ -17,20 +17,21 @@ 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`. 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.
- **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).
@@ -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`:
@@ -172,7 +173,7 @@ Packages:
- `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,6 +183,7 @@ 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.
@@ -250,4 +252,6 @@ go test ./... # full run, starts Postgres with testcontainers (needs D
`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

@@ -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
}

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

@@ -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

View File

@@ -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

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")
}
})
}