110 Commits

Author SHA1 Message Date
Jakub Zych
bc5f4f7260 fix(quick-261119-kj8): sweep the JWT blacklist from a scheduled user:jwt-blacklist-sweep command
Boot started a ticker goroutine inside lagoon.OnDatabase that nothing
stopped, so every booting process (serve, each console command, each test
boot) leaked one and swept the blacklist once per process. The sweep is
now the console command user:jwt-blacklist-sweep, which the conga
scheduler runs on the job worker every
golem15.user.jwt.blacklist_sweep_interval (default 10m, 0 for none), once
per period across instances. An interval the scheduler cannot run
(unparsable, negative, under 1s, not dividing 24h) now fails boot.
2026-11-19 15:06:29 +01:00
Jakub Zych
6ec4c85c48 fix(quick-261114-p5n): style the user mail layout like the framework's default layout
- wrapper, header (logo or site name), 570px card and copyright footer
  inline, mirroring postcard's default layout
- built-in copy of the default brand CSS before the brandCss and css
  slots, so saved Branding and mail.css still win
- no template function calls; the header and footer sit behind if/with,
  so the layout renders without them on framework v0.6.x
- header and text sections unchanged
2026-11-14 18:44:49 +01:00
Jakub Zych
b179e6b2e5 fix: activate-by-code asks the login gates before it signs in
After the mailed code verifies, ActivateByCode consults the login gates
with source password, as Login does. A gate answer (for example a
second-factor challenge) replaces the token response and sets no session
cookie; a gate error answers the opaque 500. The account is activated
either way. Without a gate, or when every gate allows, the answer is
unchanged. With require_activation off an account can enable a second
factor before it activates, so the mailed code no longer stands in for it.
2026-11-05 17:54:21 +01:00
Jakub Zych
97f83cc2cf feat: plugin.yaml manifest for the SummerCMS marketplace
- plugin.yaml generated by summer plugin:manifest (name override: User)
- TestPluginManifest guards it with kiosk.CheckT
- require SummerCMS v0.6.0, the framework minimum in plugin.yaml
2026-10-29 19:27:56 +01:00
Jakub Zych
6bf219f50a fix(quick-261029-d9j): pick the mail language from Accept-Language, add mail.fallback_locale, Polish subjects
- preferred_locale and the request locale are normalised (comma lists,
  q-weights, region subtags, case) to pl or en by NormalizeMailLocale, so a
  raw Accept-Language such as en-GB,en;q=0.9 selects the -en templates
- new golem15.user.mail.fallback_locale (default pl) is used when neither
  names a supported language; ResolveMailLocaleFor applies it, and Boot
  rejects any value other than pl or en
- activate, reactivate and restore Polish templates get Polish subjects
- no template, route or payload changes; MailTemplate and
  ResolveMailLocale keep their signatures
2026-10-29 09:47:42 +01:00
Jakub Zych
91af10b572 chore: require SummerCMS v0.5.2 2026-10-28 23:39:33 +01:00
Jakub Zych
8446a77605 Merge phase-32.1-mcp-implied-scopes: implied MCP scopes alongside the 403 missing scope fields 2026-10-28 23:36:43 +01:00
756797c2c4 test(32.1-05): keep implied MCP scopes off the subject
- MCPDispatch expands the credential and leaves subject.Scopes unchanged
2026-10-28 16:10:03 +01:00
193a381ece test(32.1-02): keep personal tokens unexpanded and reject bad Implies
- A personal token keeps its scopes and its credential TokenID
- A write grant does not satisfy Implies read, and a present name is not duplicated
- Document Implies and the pact.MemberTokenScopeCatalog publish
2026-10-28 15:03:28 +01:00
25fd981d7f feat(32.1-02): expand OAuth MCP scopes from the published catalog
- Publish the compiled member-token catalog as pact.MemberTokenScopeCatalog
- Imply declared names only when the MCP subject has a ClientID
- Reject a bad Implies and the reserved names backend and offline_access
2026-10-28 15:01:04 +01:00
66fc107eb9 feat: name the missing scope or permission in 403 bodies
A refusal by user.scope:<scope> now answers 403 with missing_scope and a
refusal by user.permission:<code> with missing_permission, next to the
unchanged error (true) and message, so a plain-HTTP script or a personal
token client learns what it lacks. user_me says it needs scope read.
2026-10-28 14:05:57 +01:00
bd2cc0c245 test: expect the missing scope or permission in 403 bodies 2026-10-28 14:05:28 +01:00
a1b78b80f5 fix: the MCP dispatch credential carries the personal token id
MCPUserGuard.MCPDispatch now sets the in-memory credential's ID to the
subject's TokenID when the subject came from a personal usr_ token (no
ClientID), so a handler running under MCP dispatch can record which
token made a change. An OAuth subject's TokenID names the OAuth
server's token row, so its credential keeps ID 0. The credential is
still never saved.
2026-10-28 11:30:44 +01:00
07196a4bcb fix: keep the device polling token off the QR code
golem15.user.device_auth.auth_url gains a {short_code} placeholder and
defaults to {frontend_url}/device/scan/{short_code}; POST
/devices/authorize accepts the short code in its token field, so a scan
page that posts what its URL carries keeps working. The status poll hands
the session token over only to a client with the User-Agent the device
initiated with; another client sees the session confirmed and takes
nothing.
2026-10-26 16:12:08 +01:00
557c03c595 fix: a password change or ban ends authorized device sessions
The device hand-over now refuses a session authorized before the user's
tokens_valid_after, and every AccessRevokedEvent revokes the user's
pending and confirmed device sessions inside the write's transaction
(classes.RevokeDeviceSessions).
2026-10-26 16:08:20 +01:00
20e7b175f8 fix: Reset 2FA keeps the privileged-group guard
Resetting the second factors of a privileged-group member now needs
golem15.users.manage_privileged_groups, as changing their password or
deleting them does; without it the action answers 403 before Reset.
2026-10-26 16:04:11 +01:00
cc3636cea9 fix: a device revoke cannot lose to a concurrent refresh
The revoke now reads the device's jti with UPDATE ... RETURNING under the
row lock, and the refresh's hand-over (classes.FollowDeviceJTI) reports a
session revoked meanwhile, so the refresh answers the blacklisted-token
401 without a token. A hand-over error fails the refresh closed instead
of leaving the session on a stale jti.
2026-10-26 16:00:43 +01:00
1f3266a417 test: device authorization flow and its migration
- TestDeviceCodes (classes, short): tokens, short-code alphabet and
  distribution, normalization
- TestDeviceAuthURL, TestDeviceDisplayName (short): auth_url template, TTL,
  PHP's user-agent order
- TestDeviceInitiate, TestDeviceStatus, TestDeviceAuthorize: PHP bodies for
  every state and refusal, bounded cleanup, short-code collision retry,
  concurrent authorizes binding one user
- TestDeviceHandOverConcurrent, TestDeviceListAndRevoke,
  TestDeviceRevokeAfterRefresh, TestDeviceTokensAtRest
- TestDeviceAuthSessionsMigration (updates): columns, constraints, indexes,
  cascade, rollback and re-up
2026-10-26 14:15:54 +01:00
2c689793f4 test: start the updates package's Postgres only without -short
go test passes -short as -test.short=true, so scanning os.Args for
-test.short never matched and every -short run started a container (and
failed without Docker). Read the flag through flag.Parse and
testing.Short instead.
2026-10-26 14:06:54 +01:00
6844d362c4 test: login gates, password-changed sources and the reset action
- TestLoginGates: registry order, first result or error wins, nil gates,
  concurrent Add and Check, CheckLoginGates without a registry
- TestLoginGateOrder: refused first factors never reach a gate, rehash
  before a challenge, restore and reactivate mail only after the gates,
  gate answers pass through, refresh never asks a gate
- TestPasswordChangedSources: reset, change and admin set fire once inside
  the write's transaction; rehash and registration fire none
- TestResetTwoFactorAction: offered only with a service and a factor,
  danger, permission, transaction and rollback
2026-10-26 14:06:09 +01:00
3b22134292 feat: device list and revoke with the jti followed through refresh
GET /devices lists the caller's confirmed and used device sessions (PHP's
fields, device_name from the stored name or the user agent, is_current
for the session the request's token belongs to). DELETE /devices/{id}
marks the session revoked and blacklists the device token's jti for its
whole refresh window in one transaction. POST /refresh hands a used
session's jwt_jti over to the refreshed token (classes.HandOverDeviceJTI),
so a device that refreshed before the revoke is signed out too.
2026-10-26 10:19:25 +01:00
4e3e5b05b5 feat: device authorization by QR or short code
PHP's device flow on golem15_user_device_auth_sessions (PHP's columns,
the token stored as its SHA-256, plus jwt_jti): POST /devices/initiate
answers a 64-character token, an XXXX-XXXX short code, the configurable
auth_url (golem15.user.device_auth.auth_url) and the expiry; a signed-in
user authorizes it with POST /devices/authorize (short_code or token,
one guarded pending-to-confirmed UPDATE); the device's first poll of
GET /devices/status/{token} after that receives a session JWT through one
guarded confirmed-to-used UPDATE, so exactly one poll gets it. Used and
revoked sessions never turn into expired; each initiate deletes a bounded
batch of stale sessions.
2026-10-26 10:14:48 +01:00
3d4c8d2160 style: gofmt the login gate smoke test 2026-10-26 10:08:57 +01:00
7900f47ba6 feat: password-change hook and the reset-2FA admin slot
The D-07 password-change hook is the existing AccessRevokedEvent, fired
inside the write's transaction by a reset, the user's own change and an
administrator's password; (*AccessRevokedEvent).PasswordChanged reports
those three reasons, and the login rehash fires nothing.

The Users screen declares the record action reset_two_factor (danger)
behind the new permission golem15.users.reset_two_factor, which no role
has by default. It is offered only when a two-factor plugin publishes a
classes.TwoFactorAdmin and the user has a second factor; Run calls the
service's Reset in the action's transaction.
2026-10-26 10:03:59 +01:00
8501f3475a feat: login gates and the login event
Register publishes a *classes.LoginGates registry. POST /login consults
it through controllers.CheckLoginGates after the password, activation and
throttle checks and the bcrypt rehash, and before the restore of a
deactivated account, last_seen and the mint: a gate result replaces the
token response, a gate error answers the opaque 500. The restore and its
reactivate mail now run after the gates, so a password alone cannot
reactivate an account a second factor protects. Without a gate /login
answers as before; refresh never consults the gates.

classes.LoginEvent (golem15.user.login) fires after every password login
that minted a token; controllers.FireLoginEvent lets other plugins fire it.
2026-10-26 09:55:48 +01:00
50da92c1fb chore: require SummerCMS v0.5.0 2026-10-24 06:32:47 +02:00
0428093d33 test: start the link request before minting the session in TestBackendLink
Go evaluates call arguments left to right, so the two subtests minted the
frontend session before the administrator created the link request. Across a
second boundary (a loaded host) the confirm correctly answered 409
stale_session, because the sign-in predated the request.
2026-10-23 21:45:47 +02:00
98924041c9 docs: mark MintAPIToken deprecated in favour of MintAPITokenFor 2026-10-23 21:16:47 +02:00
ebe408f542 test: an organisation delete removes the blobs, Postgres tests skip under -short
TestOrganisationLogo asserted only that the system_files rows go; it now
also waits for the commit and asserts the logo's and avatar's originals and
thumbnails are gone from the bucket. The Postgres tests of the gap closure
call t.Skip under -short instead of returning, so -short runs report them
as skipped, not passed.
2026-10-23 21:14:37 +02:00
9730110d55 fix: the avatar and logo URL fallback follows the configured public path
When the thumbnail fails, AvatarURL and OrganisationLogoURL answered
"/" + the blob key, which skips storage.uploads.public_path_prefix and
public_url (a 404 with the WinterCMS layout). They now answer the
original's attach.File.URL.
2026-10-23 21:11:04 +02:00
b929ba9f33 docs: state the one-second blind spot of the account link's auth_time proof 2026-10-23 21:08:12 +02:00
92676ba14e fix: the backend link show and confirm POSTs ignore a code in the query string
readFields falls back to r.Form, which includes the query string, so
POST /backend-link/show?code=... and /confirm?code=... worked and put the
code into access logs. Both routes now read the code from the body only
(JSON or a form body).
2026-10-23 21:08:00 +02:00
30f7a01d3d fix: a self-service password change revokes every OAuth grant, however recently refreshed
ChangePassword fired the access-revoked event with Before = the calling
session's iat, so an OAuth/MCP grant whose client refreshed it after that
instant kept working. Before is now the instant of the request; the stored
tokens_valid_after still keeps the calling session.
2026-10-23 20:48:38 +02:00
38551a4104 fix: organisation attachment cleanup runs in FormAfterDelete
FormBeforeDelete keeps its declaration and only releases the members; the
avatar and logo rows are deleted by a new FormAfterDelete hook in the same
transaction, their blobs after the commit. Keeps the plugin additive
(no changed exported method declaration).
2026-10-23 18:40:59 +02:00
e3c164fdf0 test: named tests for the account link proof, revocation, member token scopes and the organisation logo
- TestMemberTokenScopes walks E-2's acceptance list item by item, plus the
  per-application catalog and the legacy MintAPIToken fallback;
  TestMemberTokenScopesBoot (no Docker) the boot refusals
- TestBackendLinkAuthTime (C-CR-02), TestBackendLinkShowPost (C-WR-01,
  C-IN-06), TestAccessRevocation (C-CR-01), TestUserMCPGuardClientIP
  (C-IN-04), TestAPITokenRevokeEvent (C-IN-02), TestOrganisationLogo (E-1)
- README Testing section names them
2026-10-23 18:36:39 +02:00
25b9f2e35c fix: deleting an organisation removes its avatar and logo attachments
The Organisations screen's delete left the organisation's system_files
rows and blobs behind. FormBeforeDelete now deletes them in the delete's
transaction (attach.DeleteForOwner) and removes the blobs once it
commits, as the user delete does.
2026-10-23 18:22:01 +02:00
Jakub Zych
f20a8d3b98 feat: organisation logo (attachOne logo) and payload helpers
- Organisation gains the public attachOne logo (OrganisationLogoField),
  editable as an image upload on the Organisations form; avatar unchanged
- OrganisationLogoURL and OrganisationLogoFields give applications the
  has_logo, logo and logo_url keys for their organisation payloads
- no migration: attachments live in system_files
2026-10-23 17:03:13 +02:00
Jakub Zych
ee5c096d0d feat: plugin-declared member token scopes (pact.HasFrontendTokenScopes)
- CompileAPITokenScopes builds the catalog from the built-ins and the
  activated plugins' declarations; a bad name, a redeclared built-in, a
  duplicate, an empty label or a missing phrase key fails boot
- POST /tokens, user:token:create and MintAPITokenFor check the
  application's own catalog (422 text unchanged); MintAPIToken keeps its
  signature with a process-wide fallback for declared scopes
- GET /_user/api/v1/tokens/scopes lists the built-ins and the declared
  scopes with translated labels
- built-in scope labels in en and pl; TestMemberTokenScopesSmoke
2026-10-23 17:00:12 +02:00
Jakub Zych
970719ce75 fix: access-revoked event on ban and password changes, banned users lose their link, token-specific MCP revoke
- AccessRevokedEvent and FireAccessRevoked: fired in the write's transaction
  by the ban action (newly banned users only), the password reset, an
  administrator setting a password and the self-service password change;
  a revoked subject event per user after commit
- LinkedBackendUser answers no administrator for a banned user
- FireSubjectEvent / FireSubjectEventAfterCommit carry TokenID or ClientID;
  DELETE /tokens/{id} ends only that token's MCP sessions
- the MCP personal-token path stamps last_used_ip from towel.ClientIP
- BackendLinksFor replaces the duplicate lookups; requestUsable uses
  IsUsableAt
2026-10-23 16:47:56 +02:00
Jakub Zych
32f92591d6 fix: account link proof by auth_time, code in the URL fragment and POST show
- BackendLinkConfirm reads the session's auth_time (bouncer.VerifyAuthTime);
  a token without it, or a refreshed old session, answers 409 stale_session
- POST /_user/api/v1/backend-link/show takes the code in the body; GET
  /backend-link/{code} stays, deprecated; both answer Cache-Control no-store
- My account answers <frontend_url><page_path>#code=<code>; new key
  golem15.user.backend_links.page_path (default /link-admin)
- TestBackendLink now crafts auth_time tokens; TestBackendLinkAuthTimeSmoke
2026-10-23 16:38:55 +02:00
Jakub Zych
72de822a84 test: backend link, frontend permission catalog and MCP guard matrices (phase 19.7 plan 05)
- TestBackendLink: the fresh sign-in rule at the second, 1:1 on the
  frontend side, the show route's three keys, SetLink and RemoveLink events
  (none after a rollback), deactivated or deleted administrators, and
  deactivating the frontend user
- TestFrontendPermissionCatalog: a second plugin's duplicate and an empty
  code dropped; a group saved with a declared code grants it
- TestUserMCPGuard: parser refusals, a soft-deleted user, an expired token,
  and the dispatch credential against the route's own user.scope:read
2026-10-23 14:09:36 +02:00
Jakub Zych
bfcfea4ed7 chore: require SummerCMS v0.4.4 2026-10-23 12:25:46 +02:00
Jakub Zych
59cc3bde2e docs: account link, Administrators actions, plugin frontend permissions, MCP guard and user_me 2026-10-23 12:20:50 +02:00
Jakub Zych
dbb3d33b48 fix: user groups delete keeps FormAfterDelete's declaration; members' subject events fire from FormBeforeDelete
The member ids are read in the delete's transaction before the memberships
go, and the permissions events fire after it commits, as before; the
smoke now covers a group delete.
2026-10-23 12:16:53 +02:00
Jakub Zych
6f1cb1a774 feat: link and unlink an administrator's frontend account on the Administrators screen
- golem15.users.manage_backend_links (no default role), en and pl labels
- record actions on summercms.cabana.users: link_frontend_account asks for
  the frontend user's email (exact, case-insensitive, active users only),
  records linked_by and fires the link events; unlink_frontend_account
  (danger) removes the link
- a taken or unknown account answers 422 on the prompt
2026-10-23 12:14:21 +02:00
Jakub Zych
0f545f5c81 feat: user MCP guard provider, plugin frontend permissions and the user_me tool
- classes.FrontendPermissionCatalog: the seeded rows, then codes activated
  plugins declare through pact.HasFrontendPermissions (seeded row wins);
  both permission editors offer it
- classes.MCPUserGuard (guard "user"): reads user.api_token, user.scope:*
  and user.permission:*, allows with the route's checks (session scopes,
  group grants, every code), dispatches with an in-memory token credential,
  resolves usr_ personal tokens; registered in *pact.MCPGuards and published
  as pact.MCPPersonalTokenResolver
- GET /_user/api/v1/token/me (user.api_token, user.scope:read) and the MCP
  tool me (user_me)
- pact.MCPSubjectChanged on token revoke, Users saves and User Groups saves
  and deletes
2026-10-23 12:08:38 +02:00
Jakub Zych
7ac80c9aea feat: verified frontend account link for administrators
- golem15_user_backend_links (1:1, both sides unique) and one-shot hashed
  golem15_user_backend_link_requests (golem15.user.backend_links.request_ttl, 10m)
- classes.BackendLinks: CreateLinkRequest, ConfirmLinkRequest (row lock,
  JWT iat not before the request), SetLink, RemoveLink, LinkedBackendUser;
  published as *classes.BackendLinks and pact.MCPLinkedBackendResolver
- GET /_user/api/v1/backend-link/{code} and POST /backend-link/confirm (jwt.auth)
- My account section frontend_account with link and unlink
- BackendLinkedEvent, BackendUnlinkedEvent and pact.MCPSubjectChanged after commit;
  deleting or deactivating a frontend user removes its link
- golem15.user.frontend_url (falls back to app.url)
2026-10-23 12:03:26 +02:00
Jakub Zych
3828a65481 feat: golem15.user.password.public_routes false leaves POST /login, /forgot-password and /reset-password unregistered, so they 404 like any unknown path
The key defaults to true, so the route table is unchanged. False skips only
those three registrations: they get the router's own 404, with no custom
handler and no framework change. /register keeps allow_registration and the
turnstile guard. The key is read at boot, and a value other than true or
false fails boot like golem15.user.turnstile.
2026-10-23 00:09:38 +02:00
Jakub Zych
8bdf2c7d1a feat: opt-in golem15.user.jwt.token_cookie sets the HttpOnly session cookie on /login, /register and /activate-by-code instead of returning the token
Default off, so body-token clients are unchanged. When on, the cookie carries the auth.cookie attributes via bouncer.LoadCookieConfig and the body keeps user (and message); SameSite stays Lax, with no CSRF token; personal API tokens are untouched.
2026-10-22 23:44:44 +02:00
Jakub Zych
846087db45 fix: a /refresh carried by the auth.cookie session cookie rewrites that cookie, so an HttpOnly session survives the rotation
8e4b863 answered a cookie-carried refresh in the body only and blacklisted the old jti, so an HttpOnly cookie (golem15.sociallogin token_cookie) kept a dead token. Now the cookie named auth.cookie.name gets the rotated token and the body is {}; bearer and auth_token refreshes are unchanged, and refusals write no cookie.
2026-10-22 23:39:18 +02:00
Jakub Zych
a484d0e9a2 fix: reset-password and the admin password set stamp tokens_valid_after in whole seconds, so a token minted in the same second is accepted
JWT iat is whole seconds and every cutoff check is iat before tokens_valid_after, so a sub-second cutoff refused the login that followed a reset within the same second. POST /reset-password and the admin Users password set now truncate the cutoff to the second, like RevokeUserAccess; email_verified_at keeps full precision. Change-password and bouncer's comparison are unchanged.
2026-10-22 22:56:38 +02:00
Jakub Zych
b6f8055c56 fix: /login throttles failed logins per client address behind trusted proxies (surf.ClientIP), like /register
Behind a reverse proxy every visitor had the proxy's RemoteAddr, so one client's failed logins locked the account for all. The throttle key is now surf.ClientIP with http.trusted_proxies, the expression /register uses; X-Forwarded-For from an untrusted peer is still ignored. RemoteIP is unchanged.
2026-10-22 22:53:29 +02:00
Jakub Zych
4bf44fc6ea fix: logout revokes the session under serve: the jwt blacklist and GORM hooks are wired when the database is published
Boot runs before summer serve publishes the database, so the plugin's GORM
hooks, the Postgres jwt_blacklist store and its sweep now go through
lagoon.OnDatabase, and the jwt guard resolves the published store on every
request. A logged-out token is refused on jwt.auth, /fetch and /refresh.

The jwt guard reads the cookie names from classes.SessionCookieNames().
2026-10-22 22:29:59 +02:00
Jakub Zych
8e4b863a3f fix: /fetch, /refresh, /update and /change-password accept the session cookies the jwt guard reads
The four routes (and the other signed-in routes through authenticate) read the bearer header, then the token and auth_token cookies, through classes.SessionToken and one cookie-aware guard.
A bearer header still wins and no credentials stays 401 with the old bodies.
A cookie-carried /refresh answers the rotated token in the body and writes no cookie.
2026-10-22 21:45:52 +02:00
Jakub Zych
15ff9793ba fix: login refuses a not-activated account while require_activation is on
The refusal is the same 401 invalid-login answer as a wrong password and is counted by the login throttle.
The activation is checked after the password and before the deactivation restore, so a refused account stays deactivated.
require_activation false keeps the previous behaviour.
2026-10-22 21:25:53 +02:00
Jakub Zych
930b1587a0 chore: require SummerCMS v0.4.3
The organisation role cleanup uses cabana's ClearOnChange, released in v0.4.3.
2026-10-22 10:42:22 +02:00
Jakub Zych
358ee5d308 fix: logout ends cookie-carried sessions, clears the session cookies and keeps the token revoked for its refresh window
POST /logout read the token from the Authorization header only, while the
jwt guard also accepts the token and auth_token cookies. A session carried
by a cookie (golem15.sociallogin's token_cookie sets an httpOnly one that
the browser cannot turn into a bearer header) was answered 401, nothing was
revoked and the cookie kept authenticating jwt.auth routes until the access
token expired (golem15.user.jwt.ttl, 60 minutes). Logout never cleared a
cookie either, and it and EndRequestSession kept the jwt_blacklist row only
until the access token's exp, so once the sweep removed the row POST
/refresh revived the logged-out token for the rest of its refresh window.

classes.EndSession, which Logout now runs, revokes every session token the
request carries (the bearer header, the token and auth_token cookies) that
verifies, an expired one too while it could still be refreshed, until the
later of exp and iat plus refresh_ttl, plus a minute, as bouncer.Refresh
and the admin logout do. The answer, a 401 included, expires the
auth.cookie token cookie and any other session cookie the request carries,
with that cookie's path, domain, SameSite and Secure. EndRequestSession is
its best-effort form. Response bodies are unchanged; an expired but still
refreshable token now logs out with 200 instead of 401.
2026-10-22 04:51:36 +02:00
Jakub Zych
aa8396916e fix: clear a stale organisation_role when a user's organisation changes in the admin
The members relation manager and the organisation field of the Users form
declare cabana ClearOnChange on organisation_role: adding or removing a
member, and a form save that moves a user to another organisation or to
none, clear the role unless the same save writes it. Needs a SummerCMS
release with ClearOnChange.
2026-10-22 03:33:12 +02:00
Jakub Zych
c3712dc0d4 fix: deactivate and ban revoke sessions and API tokens, and /refresh refuses deactivated, banned and cut-off subjects
classes.RevokeUserAccess stamps users.tokens_valid_after (whole seconds) and
revokes the users' personal API tokens; DeactivateUsers and BanUsers call
it for every selected user. Restore and unban revive nothing, and a
deactivated user who signs in again gets a fresh working token.

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

user:token:create and user:token:list gain --json, user:backfill-handles a
progress bar; planning IDs leave the descriptions.
2026-10-21 18:03:50 +02:00
Jakub Zych
35cf16689d test: email_verified_at writers, non-writers and the migration
- TestEmailVerifiedAt: register (auto, admin), activate, activate-by-code, reset-password, change-password, update
- TestAdminEmailVerifiedAt: admin create, activate action, invitation link, email change, JSON
- TestEmailVerifiedAtMigration: column shape, no backfill, existing column kept, rollback keeps column
2026-10-21 14:01:52 +02:00
Jakub Zych
a99cb467b7 fix: an email change drops the address proof
- /update clears email_verified_at in the same write when the email changes (case-only changes keep it)
- the admin Users form clears it in FormBeforeUpdate; storedEmail helper shared with guardCredentials
- README: the proof follows the address, never mass-assigned, no backfill
2026-10-21 14:01:52 +02:00
Jakub Zych
add1f7a806 feat: users.email_verified_at records a proved address (mail activation, reset code)
- additive migration 202610210001_add_users_email_verified_at (ADD COLUMN IF NOT EXISTS, no backfill, no-op rollback)
- User.EmailVerifiedAt (json:"-", not fillable)
- VerifyActivationCode and ResetPassword stamp it in the write that activates or stores the password
2026-10-21 13:53:19 +02:00
Jakub Zych
c7635c56e3 test: change-password still requires the current password (PHP map)
TestChangePassword/real_password_account_still_requires_current_password
ports the PHP OAuthPasswordBootstrapTest case: a missing or wrong
current_password is a 422 with the unchanged body, and the password stays.
2026-10-21 01:23:13 +02:00
Jakub Zych
d6d8f117ea test: provider source, unlink rule and race, sign-in helpers
- TestOAuthProviders: old bytes without a source, order, per-request lookup
- TestOAuthIdentitiesDestroyRule: the PHP last-identity rule table, 404s,
  microsoft by default, source names and opts.Providers precedence
- TestOAuthIdentitiesDestroyRace: two row-locked transactions in both orders,
  the handler waiting for the lock, concurrent handlers
- TestRegisterUserPasswordLess, TestFinishLogin, TestRegistrationExports
2026-10-21 00:49:00 +02:00
Jakub Zych
c43ba87371 fix: user:backfill-handles opens its own database
- without a published *gorm.DB the command opens one with lagoon.OpenFromApp
  for its run and closes it, as the plugin's other commands do (withDB)
- TestBackfillHandlesOpensFromConfigWhenUnpublished; README CLI note
2026-10-20 23:07:14 +02:00
Jakub Zych
174161895e fix: atomic unlink with the PHP last-identity rule
- OAuthIdentitiesDestroy locks the users row (SELECT ... FOR UPDATE) and runs
  the PHP guarded DELETE in one transaction: a self-set password or another
  identity allows the unlink; otherwise 409 with the unchanged body
- the default allow-list adds microsoft, and an OAuthProviderSource's known
  names are used when the host passes no Providers
- TestOAuthIdentitiesDestroyLastIdentityWithPassword (204),
  TestOAuthIdentitiesDestroyConcurrentSmoke; README
- gofmt of the forgotPasswordBody line touched in the previous commit
2026-10-20 23:05:14 +02:00
Jakub Zych
78a867bccb feat: provider source for oauth-providers and sign-in helpers for social login
- classes.OAuthProvider and classes.OAuthProviderSource; GET /oauth-providers
  looks the source up per request and keeps the empty body without one
- exported RegistrationSettings, RegistrationsFromIP, RefreshTTL, RemoteIP
- RegisterOptions.PasswordLess (has_self_set_password=false) and FinishLogin
  (restore + reactivate mail, last_ip_address, last_seen; no event)
- TestOAuthProvidersSourceSmoke, TestSocialHooksSmoke; README
2026-10-20 23:02:37 +02:00
Jakub Zych
1fc0ce7ed0 test: TestTurnstileRoutes pins golem15.user.turnstile per mode
Replaces TestTurnstileRoutesSmoke: empty adds nothing; open, closed and a
space-padded closed add turnstile:{mode} to POST login and register only,
every other route keeps its middleware; invalid values fail naming the key.
2026-10-20 19:19:36 +02:00
Jakub Zych
7b9faa3419 feat: opt-in Cloudflare Turnstile on login and register (golem15.user.turnstile)
- empty (default) adds nothing; open or closed appends turnstile:{mode} to
  POST /login and /register only; any other value fails boot naming the key
- TestTurnstileRoutesSmoke records the declared routes with a recording router
2026-10-20 14:45:22 +02:00
4c5d3b8935 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	plugin.go
2026-10-19 22:35:54 +02:00
9335e80342 test: RequestUser, EndRequestSession, AvatarURL and user.Deactivating
- TestRequestUser: bearer, token and auth_token cookies in guard order;
  expired, foreign, blacklisted, revoked by tokens_valid_after and
  deactivated tokens are anonymous; only infrastructure failures error
- TestEndRequestSession (no database): jti blacklisted until the token
  expires, forget cookie with the configured Domain and Path, best effort
- TestAvatarURL: thumbnail, broken-image and storage-failure fallbacks,
  gravatar with the size, the user payload's avatar_url unchanged
- TestDeactivatingEvent: one event per newly deactivated user inside the
  bulk action's transaction, a listener error rolls the action back
2026-10-19 21:40:41 +02:00
80b436d3d9 feat: fire user.Deactivating from the admin deactivate action
- DeactivatingEvent and DeactivatingEventName in classes
- FireDeactivatingEvent modelled on FireDeletingEvent
- the deactivate bulk action runs DeactivateUsers unchanged, then fires
  the event per newly deactivated user in the action's transaction
2026-10-19 19:06:20 +02:00
ee474401cb feat: export AvatarURL for the display picture at any size
- AvatarURL returns the avatar thumbnail, the file path when the thumbnail
  fails, or the gravatar URL, the rule of the user payload
- applyAvatar takes avatar_url from it; the payload is unchanged
2026-10-19 18:55:57 +02:00
b82d85f440 feat: export RequestUser and EndRequestSession for OAuth providers
- RequestUser resolves the signed-in user exactly like the jwt guard
  (bearer, token and auth_token cookies, blacklist, tokens_valid_after)
  and returns nil for anonymous or invalid requests
- EndRequestSession blacklists the session JWT and forgets the token
  cookie with the configured cookie attributes, best effort
2026-10-19 18:42:38 +02:00
Jakub Zych
c0770294a5 feat(19-04): user authorizer, user.Deleting and handle backfill
Register lighthouse user:{id} if the namespace is free, fire user.Deleting before unscoped delete, and backfill missing handles.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 21:53:21 +02:00
Jakub Zych
15b19c7021 feat(19-04): add users.handle, HandleGenerator and user.Created
Generate a unique mention handle on API register and admin create, and fire user.Created from both paths so listeners run in the same write.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 21:44:59 +02:00
569768e657 test(updates): account for the oauth-identities migration in history and rollback counts 2026-10-11 16:35:33 +02:00
Jakub Zych
24b16b1f10 fix: open Postgres for one-shot console commands 2026-10-07 13:35:59 +02:00
Jakub Zych
7a6fa0e8b6 chore: pin SummerCMS v0.1.9 for v0.1 2026-10-07 11:00:05 +02:00
Jakub Zych
cf5c6b9d44 fix(14.1): omit OAuth identity profile_data from JSON marshaling
Hidden() already listed profile_data, but encoding/json would still emit
the Jsonable field. Tag it json:"-" so the DATA-07 marshal backstop holds.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 21:46:59 +02:00
Jakub Zych
f0d3b8b21d test(14.1-02): prove oauth-identities migration and secret-leak list
- Migration up/down covers jsonb profile_data, unique indexes, and cascade FK
- GET list with Encrypted tokens fails if plaintext, key names, or [redacted] leak

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 21:34:00 +02:00
Jakub Zych
026848fc02 test(14.1-02): port OAuthIdentityApiTest 204, 409, Winter 404s, 401
- Unlink 204 keeps the sibling row
- Last-method 409 matches EN and PL lang strings even with a password
- Missing, foreign, and unknown providers share byte-identical Winter HTML 404s
- Unauthenticated GET and DELETE /google return 401 JSON

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 21:31:50 +02:00
Jakub Zych
ac8aa16217 docs(14.1-01): document host-mounted OAuth identity constructors
The table, migration and Index/Destroy constructors are a shared-plugin
contract; the host chooses the path and 404 writer.
2026-10-05 21:24:04 +02:00
Jakub Zych
8e172c5087 feat(14.1-01): unlink OAuth identities with 204 and last-method 409
- Destroy allow-lists providers and shares WriteNotFound for unknown, missing and foreign rows
- Last remaining identity is refused with a localized 409; password flags are unused
- EN and PL last_method_blocked strings match the PHP texts
2026-10-05 21:11:24 +02:00
Jakub Zych
63ac504c42 feat(14.1-01): add OAuth identities table and empty-list Index
- Model golem15_user_oauth_identities with Encrypted tokens and empty Fillable
- gormigrate 202610050001 with both unique indexes, cascade FK, and jsonb profile_data
- OAuthIdentitiesIndex returns {"data":[]} for a signed-in caller with no rows
2026-10-05 21:09:28 +02:00
Jakub Zych
2b04cda3ff test: T-12.1-24 also marshals a user with last_seen and permissions
The removal check for the json tag of users.last_seen showed that the
subtest read the user API payloads only, which are built field by field.
It now marshals the model as well, so a tag that would expose an admin
column fails it.
2026-10-05 15:46:52 +02:00
Jakub Zych
7991b53979 test: extend the permission resolver table, the admin migration history and the API token refusals
- resolver: several groups, numbers stored as text, empty group sets, a code only at user level, booleans
- migrations: every id once, the history applied twice, the unique code after a down and an up
- personal API tokens: no application, no principal, invalid bodies, another user's token
2026-10-05 15:23:23 +02:00
Jakub Zych
a848aa17d6 test: edge cases of the Users, User Groups and Organisations admin controllers
- each controller driven directly on records of another type, an application that is not booted, one without a database and one whose database fails: a guard that cannot read answers a plain error, never a pass
- D-30: a superuser passes the takeover guard; an unreadable membership is the opaque 500 with nothing changed
- unknown partials, undeclared filters and sorts, options of fields that have none, search and sort on the three lists
- a name-only update of a privileged group, validation before the guard, a seeded group protected through the config list
- known gaps pinned: boolean values in a group's permissions, organisation_role after an unlink
2026-10-05 15:23:23 +02:00
Jakub Zych
493a3ff47c test: unit tests for the admin class functions, the models and the admin registration
- classes: every admin action for its changed-row count and idempotency, the ban across several throttle rows, the cleanup of a permanent delete
- classes: the privileged list and IsPrivilegedMember (D-30), also through a handle that carries conditions
- classes: the five-minute boundary of last_seen
- models: PermissionSet round trip, the slug table shared with the SPA, Fillable and Rules, fields that never marshal, the group filter value
- TestAdminRegistration: permissions, navigation, embedded files and phrase keys in en and pl; the admin secret is required
2026-10-05 15:15:28 +02:00
Jakub Zych
43fabfa6c3 fix: a group filter value that is not a group id lists nobody (D-23)
User.FilterScope handed the filter value to the database as it came. A
value such as abc failed the query, so the Users list answered 500.

- groupFilterID reads a positive whole number, as a number or its text
- any other value narrows the list to nothing
- TestAdminUsersGroupFilterValue fails with a 500 without the change
2026-10-05 15:15:28 +02:00
Jakub Zych
f4969591e2 fix: read privileged membership and the admin actions through a clean statement (T-12.1-38, T-12.1-39)
classes.fresh chained WithContext onto a lazy NewDB session, which clones the
caller's statement with its conditions. A handle that carried a condition
made IsPrivilegedMember answer false for a member of a privileged group, so
the takeover guard would have let the request through. No caller passes such
a handle today: the admin hooks hand over the write's transaction handle.

- fresh builds the empty statement before anything is chained onto it
- IsPrivilegedMember and PrivilegedGroupIDs read through fresh
2026-10-05 14:53:41 +02:00
Jakub Zych
ba43ad9c03 test: pin every mitigated Phase 12.1 threat of the admin screens in TestPhase121Threats
- one subtest per threat id T-12.1-18 to T-12.1-25, 27 to 31, 34, 38 and 39
- T-12.1-28 revisits T-12-18: the groups field is the one writer of users_groups
- T-12.1-38 and T-12.1-39 cover the takeover guard for privileged-group members
2026-10-05 14:30:31 +02:00
Jakub Zych
4693155108 docs: describe the User Groups and Organisations screens and the privileged-group rules 2026-10-05 13:58:54 +02:00
Jakub Zych
58595fef27 feat: Organisations admin screen with the avatar and the members manager
- controller golem15.user.organisations behind golem15.users.access_users
- list and form (name, slug preset from the name, description, avatar)
- members relation manager: link sets and unlink clears users.organisation_id
- deleting an organisation releases its members first
- Organisation gains Fillable, Rules, MorphName, AttachRelations, BeforeValidate
  and the Members relation; models.Slugify
- navigation side item organisations
- TestAdminOrganisations, TestAdminOrganisationMembers, TestSlugify
2026-10-05 13:58:54 +02:00
Jakub Zych
a3992879db feat: User Groups admin screen with the users count and privileged codes protected
- controller golem15.user.usergroups behind golem15.users.access_groups
- list with users_count from the list's own query; form with the checkbox
  permission editor stored in user_groups.permissions
- creating a group with a privileged code, changing a code to or from one and
  deleting a privileged group need golem15.users.manage_privileged_groups
- a group delete removes its users_groups rows in the same transaction
- UserGroup gains Fillable, Rules and the read-only UsersCount; PermissionSet.Text
- TestAdminGroups and the D-06 matrix in TestAdminPrivilegedGroups
2026-10-05 13:52:26 +02:00
Jakub Zych
9611708792 feat: manage a user's groups from the user form, privileged groups locked
- groups relation field on the user form, the only writer of users_groups
- UsersGroup pivot model
- AdminRelationLocks: adding or removing a group whose code is in
  golem15.user.privileged_groups needs golem15.users.manage_privileged_groups,
  on create and on update; refused saves answer 403 and write nothing
- TestAdminUserGroupsField and TestAdminPrivilegedGroups
2026-10-05 13:44:15 +02:00
Jakub Zych
5805c6347f docs: describe the Users admin screen, its permissions and the privileged-member rule 2026-10-05 13:26:53 +02:00
Jakub Zych
c7d9d7d25d feat: stamp users.last_seen on login and token refresh
One conditional UPDATE writes it at most once per five minutes per
user. A failed write is logged and never fails authentication, and no
user payload carries the column.
2026-10-05 13:26:53 +02:00
Jakub Zych
f7ca3c4f59 feat: create users with a password and an invitation in the admin
- password with confirmation on create, optional reset on update that
  ends the user's sessions; the hash is never returned
- send_invite sends one invitation with an activation link after the
  create commits
- organisation picker, avatar upload shared with the user API and the
  frontend permission editor on the user form
- an email held by a deactivated user answers 422 instead of failing
  on the unique constraint
- the privileged-member guard now also refuses a submitted password
2026-10-05 13:21:51 +02:00
Jakub Zych
cdea47a178 feat: frontend permissions and the merged-permission resolver
- PermissionSet reads the stored JSON tolerantly and writes an object
  of integers; FrontendPermission is the catalogue row
- MergedPermissions, HasPermission and UserHasPermission port PHP
  getMergedPermissions and Winter's hasPermission: groups merge with
  most positive wins, the user's own values override, held means
  exactly 1, wildcards as in Winter
- User gains Permissions (never serialized) and declares the avatar
  attachment relation the user API already writes
2026-10-05 13:21:51 +02:00
Jakub Zych
970eba7734 feat: user preview, bulk and record actions and the permanent delete
- the list opens the preview, which shows one status hint (banned,
  deactivated, not activated, suspended) and the IP address fields
- bulk actions activate, deactivate, restore, ban and unban; record
  actions activate, unban and unsuspend, offered while they apply
- delete (form button and bulk) removes the user for good with the
  throttle rows, group memberships and attachments in one transaction;
  blobs go after the commit
- a privileged-group member is still refused, a bulk delete as a whole
2026-10-05 13:10:12 +02:00
Jakub Zych
ebaf3a0817 refactor: spell the five permission codes out in the catalog
The catalog reads like the Winter registerPermissions() list, and a
test pins the codes and their default roles.
2026-10-05 13:03:36 +02:00
Jakub Zych
f3f33b809a style: gofmt the user model and the session test 2026-10-05 13:02:23 +02:00
Jakub Zych
4e17c0d35b test: cover the Users admin list, update and the privileged-member guard
- admin harness: boots the plugin with the admin API mounted and
  mints backend administrators with chosen permissions
- TestAdminUsersTracer and TestAdminPrivilegedMember
2026-10-05 13:01:59 +02:00
Jakub Zych
b410a7fea9 feat: register the Users admin screen with the privileged-member guard
- permissions (the four Winter codes and manage_privileged_groups),
  the user navigation item and the embedded admin YAML
- Users controller: list with deactivated users, row states, the
  groups, created date and activated filters, and the form's name,
  surname and email
- a member of a group in golem15.user.privileged_groups (default
  admin) keeps their email, password and row unless the administrator
  holds golem15.users.manage_privileged_groups; the refusal is a 403
  that saves nothing
2026-10-05 13:01:48 +02:00
Jakub Zych
e22f7660f3 feat: add the admin columns and the frontend permissions table
- users.permissions and users.last_seen as additive columns
- golem15_user_frontend_permissions (code, label, tab, comment)
- User gains LastSeen, read-only CreatedAt and UpdatedAt and the
  filterByGroup list scope; none of them is serialized
- migration tests roll back by position past the three new steps
2026-10-05 12:51:41 +02:00
193 changed files with 30159 additions and 402 deletions

262
README.md
View File

@@ -12,24 +12,56 @@ Module `git.golem15.com/golem15/sm-user-plugin`, package `user`, plugin ID `gole
The plugin is a compiled SummerCMS plugin. Its `init` registers it with the framework, so an application loads it by listing it in `summer.yaml`; `summer build` then emits the blank import above into the application's `plugins.gen.go`. The plugin is a compiled SummerCMS plugin. Its `init` registers it with the framework, so an application loads it by listing it in `summer.yaml`; `summer build` then emits the blank import above into the application's `plugins.gen.go`.
It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_api_tokens`, `golem15_user_organisations`, `user_groups` and `users_groups`, and the JSON API under `/_user/api/v1`. It is a core plugin shared by several applications, so its routes, payloads, table names, migration IDs and config keys are a contract: change them only in a backwards-compatible way. It owns the `users` table extensions, `user_throttle`, `jwt_blacklist`, `user_api_tokens`, `golem15_user_oauth_identities`, `golem15_user_organisations`, `user_groups`, `users_groups`, `golem15_user_frontend_permissions`, `golem15_user_backend_links`, `golem15_user_backend_link_requests` and `golem15_user_device_auth_sessions`, the JSON API under `/_user/api/v1`, and the Users, User Groups and Organisations screens of the admin. It is a core plugin shared by several applications, so its routes, payloads, table names, migration IDs, permission codes and config keys are a contract: change them only in a backwards-compatible way.
## Features ## 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`. - **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. With `require_activation` on (the default), `POST /login` refuses an account that is not activated with the same 401 invalid-login answer as a wrong password and counts the attempt for the login throttle. Such an account is activated by the mailed code (`POST /activate-by-code` answers with a token unless a login gate holds the sign-in back, for example a second-factor challenge the user completes through the gate's plugin; the account is activated either way), by the invitation link or by an administrator. `POST /activate` serves the sessions of not-activated accounts, which exist when `require_activation` is off. `Login` checks in this order: a ban or an active suspension (`RejectIfThrottled`), the password, the activation, then the deactivation restore.
- **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. The guard reads the session cookies `classes.SessionCookieNames()` lists and resolves the published `bouncer.BlacklistStore` on every request. Boot installs the plugin's GORM hooks (`classes.RegisterHooks`) and publishes the Postgres `jwt_blacklist` store (`bouncer.NewPostgresBlacklist`) through `lagoon.OnDatabase`; the expired rows are deleted by the scheduled `user:jwt-blacklist-sweep` command (see Configuration). Under `summer serve`, which publishes the database after Boot, they take effect when `lagoon.Publish` runs, before the router is built; when the database is already published they take effect at once. While no store is published, no token counts as blacklisted. `POST /logout` ends the session however the token travels: the bearer header, or only the `token` or `auth_token` cookie the guard also reads. Every session token the request carries goes to the Postgres `jwt_blacklist` until its refresh window closes (the later of `exp` and `iat` plus `refresh_ttl`, plus a minute), so the guard refuses it on the next request and `POST /refresh` cannot revive it after the access token expired; a token whose access lifetime passed is revoked too while it could still be refreshed. The answer, a 401 included, expires the `auth.cookie.*` token cookie (the one `golem15.sociallogin`'s `token_cookie` sets), and any other session cookie the request carries, with that cookie's path, domain, SameSite and Secure. `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. `GET /fetch`, `POST /refresh`, `POST /update` and `POST /change-password`, like the plugin's other signed-in routes, read the session token as the `jwt` guard does: the bearer header first, then the `token` and `auth_token` cookies, so a cookie-only session works on them and a bearer header wins when both are sent. A `POST /refresh` whose token came from the `auth.cookie.*` cookie (`auth.cookie.name`, default `token`) with no bearer header gets that cookie back with the rotated token: the cookie has the `bouncer.LoadCookieConfig` attributes, HttpOnly and Max-Age `refresh_ttl`, and the answer is `{}`, so the token never reaches JavaScript. This holds whoever wrote the cookie (this plugin's `golem15.user.jwt.token_cookie`, `golem15.sociallogin`'s `token_cookie` or the application); a frontend that writes the `token` cookie itself and refreshes through it gets it back HttpOnly, without a body token, so such a frontend sends the bearer header to keep rotating in the body. A refresh carried by the bearer header (a cookie sent with it included) or by the other session cookie answers `{"token": …}` and writes no cookie; the old token is blacklisted after `golem15.user.jwt.blacklist_grace`, so that caller stores the new token itself. A refused refresh writes and forgets no cookie. When `bouncer.LoadCookieConfig` refuses the `auth.cookie` block, a cookie-carried refresh answers the opaque 500 before anything is rotated; a bearer refresh never reads that block. Keep `auth.cookie.name` at `token` or `auth_token`, the cookies the guard reads. With `golem15.user.jwt.token_cookie` on, `POST /login`, `POST /register` (when it signs the new account in) and `POST /activate-by-code` set that HttpOnly session cookie (`bouncer.LoadCookieConfig` attributes, Max-Age `refresh_ttl`) and leave `token` out of the body; `user`, and `message` on activate-by-code, stay. With it off (the default) the token is in the body and no cookie is set. SameSite stays the `auth.cookie` setting (`lax` by default) and there is no CSRF token, so do not set `same_site: none` for this cookie. With the key on, a broken `auth.cookie` block answers those three routes with the opaque 500 before they sign in, create or activate anything. Personal API tokens (`POST /tokens`) are not sessions and are unaffected. A cookie-carried session relies on the cookie's SameSite attribute against cross-site requests (the `auth.cookie` default is `lax`), as on the `jwt.auth` routes.
- **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. - **Login gates.** Register publishes a `*classes.LoginGates` registry. Another plugin (a two-factor plugin, for example) looks it up with `app.Lookup[*classes.LoginGates]()` and adds a `classes.LoginGate` in its Boot. `POST /login` consults the gates through `controllers.CheckLoginGates` after the password, activation and throttle checks (and the bcrypt rehash) and before it restores a deactivated account, sends the reactivate mail, stamps `last_seen` and mints the token. `POST /activate-by-code` consults them after the mailed code verified and before it mints the token, with source `password`: with `require_activation` off an account can enable a second factor before it activates, so the mailed code must not stand in for that factor. A gate sees a `classes.LoginAttempt` (`User`, `Source`, the already-read login or activation body as `Fields`, `Request`). A nil result allows the sign-in; a `classes.LoginGateResult` replaces the token response with its `Status` (0 means 200) and `Body`, for example `{"two_factor_required":true,"challenge_token":…,"available_methods":[…],"expires_at":…}`, and no token is issued, no session cookie is set, no account is restored and no login event fires. A gate error fails closed with the opaque 500. An activation a gate held back or failed stays committed. Without a gate, `/login` and `/activate-by-code` answer exactly as before. `POST /refresh` never consults the gates.
- **Login event.** Every sign-in that issued a session token fires `classes.LoginEvent` (`classes.LoginEventName`, `golem15.user.login`, PHP's name) with `User` and `Source` (`LoginSourcePassword`, `LoginSourceSocial`, `LoginSourcePasskey`, `LoginSourceTwoFactor`, `LoginSourceDevice`), after the token was minted. `POST /login` fires it with `password`; another plugin that completes a sign-in fires it through `controllers.FireLoginEvent`. A listener error is logged and never fails the sign-in. Refresh and `/register` fire none.
- **Password-change hook.** A password reset, the user's own `POST /change-password` and an administrator setting a password on the Users screen fire `classes.AccessRevokedEvent` inside the write's transaction (see Access revocation); `(*AccessRevokedEvent).PasswordChanged()` reports these three reasons. A two-factor plugin listens to it to revoke trusted devices, and this plugin revokes the users' pending and confirmed device sessions (see Device authorization); a listener error rolls the password write back. The bcrypt rehash on login and a new account fire nothing.
- **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. With `golem15.user.password.public_routes` false, `POST /login`, `POST /forgot-password` and `POST /reset-password` are not registered, so they answer the router's own 404 like any unknown path (any method, so no 405 shows they exist), while the `controllers` handlers stay exported.
- **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. - **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. - **Login throttling.** Failed logins are counted per user and client address in `user_throttle` (`CheckAndRecordLogin`, `RejectIfThrottled`) and suspend the account for a configured time. The client address is `surf.ClientIP` with the framework's `http.trusted_proxies`, as for the `/register` IP limit and the `user-api` rate limit: behind a listed reverse proxy it is the `X-Forwarded-For` client, otherwise the connection address, and an `X-Forwarded-For` header from any other peer is ignored. A deployment behind a proxy lists the proxy's address in `http.trusted_proxies`; otherwise every visitor shares the proxy's counter.
- **Device authorization.** A device without a keyboard (a TV, a desktop app) signs in by QR code or short code, PHP's flow with its paths and bodies. It calls `POST /devices/initiate` (no session; optional `device_name`, at most 255 characters) and gets `{"success":true,"data":{"token","short_code","auth_url","expires_at"}}`: a 64-character token, a short code `XXXX-XXXX` over `23456789ABCDEFGHJKMNPQRSTUVWXYZ`, the page to show as a QR code (`golem15.user.device_auth.auth_url`, default `{frontend_url}/device/scan/{short_code}`) and the expiry (`golem15.user.device_auth.ttl_minutes`, default 5). A signed-in user opens that page, or types the short code, and the site calls `POST /devices/authorize` with the user's session token and `short_code` (any case, hyphen optional) or `token` (the device token, or the short code the default page carries); there is no second-factor check, the user already passed it at sign-in. The device polls `GET /devices/status/{token}`: `pending`, then on the first poll after the authorization `{"success":true,"data":{"status":"confirmed","user_id",…,"message":"Device authorized - complete login","token":<session JWT>,"user":<payload>}}`, exactly once (one guarded `UPDATE` moves the session from `confirmed` to `used`, so of concurrent polls one gets the token), then `used`. The device token is the device's polling secret: the default `auth_url` carries the short code instead, so a photo of the QR code, the page's URL in a browser history or a `Referer` gives an onlooker nothing to poll with, and only a poll with the `User-Agent` the device initiated with receives the session token (another client gets `{"success":true,"data":{"status":"confirmed"}}` and takes nothing). A template with `{token}` still works but puts the polling secret on screen. A user who is gone, deactivated or banned, or whose `tokens_valid_after` is later than the authorization (a password change or `RevokeUserAccess` after the user authorized the device), gets no token: the session becomes `revoked`. Every `AccessRevokedEvent` (a ban, a password reset, change or an administrator's new password) also revokes the user's pending and confirmed sessions inside the write's transaction (`classes.RevokeDeviceSessions`). A pending or confirmed session past its expiry answers PHP's flat `{"success":true,"status":"expired","message":"Authorization session has expired"}`; a used or revoked session never turns into expired. The statuses are `pending`, `confirmed`, `used`, `expired` and `revoked`. Only the SHA-256 of the device token is stored (column `token`, `golem15_user_device_auth_sessions`), with the jti of the session token the device received (`jwt_jti`). The hand-over fires the login event with source `device`. Each initiate deletes up to 500 pending or expired sessions that expired over an hour ago. The token travels in the status URL, so a reverse proxy that logs paths records it; it is one-time and lives `ttl_minutes`. A signed-in user lists their devices with `GET /devices` (`{"success":true,"devices":[{"id","device_name","device_ip","authorized_at","last_activity","is_current"}]}`, confirmed and used sessions, most recent activity first; `device_name` is the stored name or one parsed from the user agent; `is_current` marks the session whose token the request carries) and revokes one with `DELETE /devices/{id}` (`{"success":true,"message":"Device revoked successfully"}`, 404 `{"error":"Device not found"}` for another user's session). A revoke marks the session `revoked` and blacklists the jti of the session token the device holds for the token's whole refresh window, so the device is signed out at once and cannot refresh. `POST /refresh` moves a used session's `jwt_jti` to the refreshed token (`classes.FollowDeviceJTI`), so a device that refreshed before the revoke is signed out too. The revoke reads the jti with its own `UPDATE … RETURNING`, under the row lock the refresh's hand-over takes, so a revoke and a refresh that race cannot leave the device signed in: a refresh that comes second finds the session revoked and answers 401 `{"error":"Could not refresh token","msg":"The token has been blacklisted"}` without a token. The hand-over fails closed: a database error answers the opaque 500 instead of a token the session does not follow. With `golem15.user.jwt.blacklist_grace` above 0, two concurrent refreshes of one token can fork a device's token lineage and only one fork is followed; a password change still ends both through `tokens_valid_after`. The device routes check the session inside the handler and answer PHP's 401 `{"error":"Unauthorized"}`.
- **Rate limiting.** Every route runs behind the `user-api` bucket: 120 requests a minute per authenticated user, or per client IP for anonymous calls. - **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). - **Profile.** `POST /update`, `POST /marketing-consent`, `POST /avatar` and `POST /avatar/remove` (the avatar is stored through the framework's attachment storage).
- **Organisations.** The `Organisation` model and the `organisation_id` and `organisation_role` user columns, as a foreign-key target for other plugins. - **Deactivation and bans.** Deactivation is self-service and reversible: a password login or a `golem15.sociallogin` sign-in restores a deactivated account and sends the reactivate mail, and an administrator can restore it too. It ends every earlier session JWT and personal API token of the user (`RevokeUserAccess` stamps `tokens_valid_after` and revokes the `user_api_tokens` rows), so the user signs in again and gets a fresh token, while the old API tokens stay revoked. A ban is the lock: password login, social sign-in and `POST /refresh` refuse a banned user, and banning revokes the user's sessions and API tokens. A banned user's account link answers no administrator (`LinkedBackendUser`). Neither unban nor restore revives a token. Activation gates login, deactivation does not: while `require_activation` is on, an account that is both deactivated and not activated is refused and stays deactivated, with no reactivate mail. Upgrade note: accounts deactivated or banned before this version keep their API tokens until they are deactivated or banned again (both actions are idempotent) or `RevokeUserAccess` runs for them.
- **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 route of this plugin reads or writes groups, and the user payload still answers `"groups":[]`. - **Organisations.** The `Organisation` model and the `organisation_id` and `organisation_role` user columns, as a foreign-key target for other plugins. An organisation has a name, a slug (filled from the name by `Slugify` when it is left empty), a description, an avatar, a logo and its members: the users whose `organisation_id` points at it. The logo is a second public image attachment (`logo`, `models.OrganisationLogoField`), kept in `system_files` like the avatar. The plugin serves no frontend organisation payload, so applications that build one add the logo with `classes.OrganisationLogoFields(ctx, app, org)`, which answers `has_logo` (bool), `logo` (the attachment's disk name, or null) and `logo_url` (a 256 px thumbnail URL, `classes.OrganisationLogoSize`, or null), the keys the user payload uses for its avatar; `classes.OrganisationLogoURL(ctx, app, org, size)` answers the URL at any size (the thumbnail, or the original file's public URL when the thumbnail fails, as `AvatarURL` does) and false when there is no logo or no file bucket. `organisation_role` belongs to that membership: the admin clears it whenever a user's organisation changes (see the Organisations screen), and an application that sets `organisation_id` itself sets or clears the role with it.
- **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. - **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.
- **Mail templates.** Activation, reset and reactivation mails in Polish and English (`golem15.user::mail.*`, layout `golem15.user::mail.layouts.user`); the locale follows the user (`ResolveMailLocale`). - **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.
- **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). `GetApiArrayEvent` lets other plugins merge keys into the user payload. - **Admin: Reset 2FA.** The Users screen declares the record action `reset_two_factor` ("Reset 2FA", danger confirmation) behind the backend permission `golem15.users.reset_two_factor`, which no role has by default. A two-factor plugin backs it by publishing a `classes.TwoFactorAdmin` (`app.Publish[classes.TwoFactorAdmin](svc)`): the screen looks the service up on every request and offers the action only when one is published and its `HasTwoFactor` reports a second factor for the user, so an application without a two-factor plugin never shows it. Running it calls the service's `Reset` in the action's transaction. On a member of a privileged group it also needs `golem15.users.manage_privileged_groups` (see Privileged groups): without it the action answers 403 and `Reset` does not run.
- **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, avatar and logo (an image upload), and on an existing organisation the Members tab. Adding a member sets that user's `organisation_id` and removing one clears it; both also clear the user's `organisation_role`, so a role never moves to another organisation or outlives the membership. A user is never deleted. Only users without an organisation can be added, so a user moves by being removed from one organisation and added to the other (or through the organisation field of the user form, where a save that changes the organisation, to another one or to none, clears `organisation_role` unless the same save writes it). Deleting an organisation clears `organisation_id` and `organisation_role` of its members first, and removes its avatar and logo attachments with it (the files once the delete commits).
- **Privileged groups.** The groups whose code is listed in `golem15.user.privileged_groups` (default `admin`) are privileged: an application may treat their members as site administrators. Three things therefore need the backend permission `golem15.users.manage_privileged_groups` on top of the screen's own permission, and answer 403 without it, saving nothing. First, membership: adding a privileged group to a user or removing it, on create and on update of the user form. An administrator without the permission sees those groups locked in the field and can still change the user's other groups. Second, the code: creating a group with a privileged code, changing a group's code to or from a privileged one, and deleting a privileged group. Its name, description and frontend permissions need only `golem15.users.access_groups`. Codes compare case-sensitively, and a group without a code is never privileged. Third, the member's account, which is protected against takeover: changing that user's email or password, resetting their second factors (Reset 2FA), and deleting them for good, needs the backend permission `golem15.users.manage_privileged_groups` on top of `golem15.users.access_users`. Without it the request answers 403 and nothing is saved; a bulk delete that contains such a user deletes none of the selected users. Everything else on such a user (name, organisation, avatar, frontend permissions, activate, deactivate, restore, ban, unban, unsuspend) needs only `golem15.users.access_users`. `PrivilegedGroupCodes`, `IsPrivilegedCode`, `PrivilegedGroupIDs` and `IsPrivilegedMember` expose the rule to other code.
- **Frontend permissions.** `golem15_user_frontend_permissions` is the catalogue of permissions a site defines for its users (rows come from the application's migrations or seeds). A user's own choices are stored in `users.permissions` and a group's in `user_groups.permissions`, as a JSON object of code to `1` (allow) or `-1` (deny). `MergedPermissions` combines them as PHP `getMergedPermissions` does: among a user's groups the most positive value wins, then the user's own value replaces the groups'. `HasPermission` and `UserHasPermission` answer whether a code is held: only at exactly `1`, with Winter's `*` wildcards. Neither value appears in the user payload, whose `permissions` key stays `null`.
- **Last seen.** `users.last_seen` is stamped by `POST /login` and a successful `POST /refresh` through `TouchLastSeen`, at most once per five minutes per user. A failed write is logged and never fails authentication. It is shown in the admin list and is not part of any user payload.
- **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. A refusal by `user.scope:<scope>` or `user.permission:<code>` answers 403 with the existing `error` and `message` plus `missing_scope` or `missing_permission` naming what is missing.
- **Member token scopes.** A member personal token (`usr_`) carries the built-in scopes `read`, `write` and `ai`, plus any scope another plugin declares with `pact.HasFrontendTokenScopes`:
```go
func (Plugin) FrontendTokenScopes() []pact.FrontendTokenScope {
return []pact.FrontendTokenScope{
{Name: "inventory:read", Label: "acme.inventory::lang.scopes.read", Description: "acme.inventory::lang.scopes.read_description", Implies: "read"},
{Name: "inventory:write", Label: "acme.inventory::lang.scopes.write", Description: "acme.inventory::lang.scopes.write_description", Implies: "write"},
}
}
```
Boot compiles the catalog from the activated plugins (`classes.CompileAPITokenScopes`, published as `*classes.APITokenScopeCatalog` and as `pact.MemberTokenScopeCatalog`) and fails on a name that does not pass `pact.ValidTokenScopeName`, a built-in redeclared, a reserved name `backend` or `offline_access`, a name two plugins declare (the error names both), an empty label or description, an `Implies` other than empty, `read` or `write` (the error names the plugin and that value), or a label or description phrase key (containing `::`) that the translator does not have. `Implies` is only those three values: empty means the declared scope is not implied, and the built-ins `read`, `write` and `ai` keep it empty. Implied names are not stored on a token row or a fingerprint. `POST /tokens` and `classes.MintAPITokenFor(app, …)` accept the scopes of the application's own catalog (`classes.APITokenScopesFor(app)`) and answer an undeclared one with the usual 422 `The selected scope is invalid.`; the console's `user:token:create` uses `MintAPITokenFor` too. Applications mint with `MintAPITokenFor`. The older `classes.MintAPIToken` is deprecated; it keeps its signature and accepts the built-ins plus every scope a catalog compiled in the same process declared, a fallback for existing callers; production runs one application per process, so that is the application's own catalog, while a test binary that boots several applications shares it (`classes.ResetDeclaredAPITokenScopes` clears it, for tests only). `user.scope:<name>`, `middleware.Scope` and `APIToken.HasScope` check a declared scope like a built-in, and `GET /tokens` lists it in `scopes`. `GET /tokens/scopes` (`jwt.auth`) answers `{"data":[{"name","label","description","built_in"}]}`, the built-ins first, then the declared scopes in activation order, with phrase-key labels and descriptions translated for the request locale. The admin `g15_` token catalog never shows these scopes (it reads `pact.HasTokenScopes` only). `classes.AllowedAPITokenScopes` stays the built-in list.
- **Mail templates.** Activation, reset, reactivation and invitation mails in Polish and English (`golem15.user::mail.*`, layout `golem15.user::mail.layouts.user`); the Polish templates have Polish subjects. The language follows the user's `preferred_locale`, then the request locale (the translate plugin's, else the raw `Accept-Language` header), each normalised to `pl` or `en` by `NormalizeMailLocale` (comma lists, q-weights, region subtags such as `en-GB`, case), then `golem15.user.mail.fallback_locale` (`ResolveMailLocaleFor`). The invitation (`golem15.user::mail.invite`) is sent when an administrator creates a user with "Send invitation by email" set; it carries the user's login and an activation link, never the password.
- **Extension events.** `RegisterEvent` fires after a user row is created; its `Payload` is a copy of the register input (extra keys a client sent included, `password` and `password_confirmation` never), so it is untrusted client input. `CreatedEvent` (`classes.CreatedEventName` `user.Created`) fires from API register and admin create. `/register` logs a failing `RegisterEvent` or `CreatedEvent` listener at Error level and continues: a committed registration is never undone or failed by a listener. `DeletingEvent` (`classes.DeletingEventName` `user.Deleting`) fires from `FormAfterDelete` before `ForceDeleteCleanup` / unscoped delete, inside the same transaction. `GetApiArrayEvent` lets other plugins merge keys into the user payload.
- **Registration for other plugins.** `RegisterUser`, `FireRegisterEvent`, `IssueToken` and `APIArray` are the steps `POST /register` runs, exported so another plugin (a first-run setup endpoint, for example) creates a user with the same validation, hashing, event, token and payload. - **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 configured social login providers (none yet: it returns an empty list). - **OAuth providers.** `GET /oauth-providers` lists the social sign-in providers a social-login plugin has enabled, read on every request from its published `classes.OAuthProviderSource`. Without one it answers the empty list, as before.
- **Frontend account link for administrators.** A backend administrator's account can be linked to one frontend user, and a frontend user to one administrator (`golem15_user_backend_links`, unique on both sides). The administrator starts it on My account (section `frontend_account`, action `link`): the plugin stores a one-shot request (32 random bytes as hex, kept only as its SHA-256, valid `golem15.user.backend_links.request_ttl`) and answers the site URL `golem15.user.frontend_url` (else `app.url`) + `golem15.user.backend_links.page_path` (default `/link-admin`, `classes.BackendLinkPagePath`) + `#code=<code>`, which the admin opens in a new tab. The code travels in the URL fragment, which browsers never send to a server, so it stays out of access logs. The site page reads the fragment, keeps the code in the browser (for example `sessionStorage`) across the sign-in, shows the request through `POST /backend-link/show` with `{"code":…}` in the body (the administrator's login and display name and the expiry, nothing else), shows which frontend account is signed in, and posts the code to `POST /backend-link/confirm` behind `jwt.auth`. Both POST routes read the code from the body only (JSON, or a form body), never from the query string. `GET /backend-link/{code}` answers the same as the POST show route and stays for compatibility; it is deprecated, because its path puts the code in access logs, so pages use POST. The link is written only by the confirm, in one transaction with the request row locked, and only when the session was signed in at or after the request was created: the proof is the session token's `auth_time` claim (`bouncer.VerifyAuthTime`), the time of the sign-in itself, compared in whole seconds with the request. `POST /refresh` copies `auth_time` and never renews it, so a refreshed old session does not pass, and a browser that was already signed in must sign in again; password, social login and any login gate apply as usual. Upgrade note: session tokens issued before the framework stamped `auth_time` (SummerCMS v0.5.0) carry no `auth_time`, and a refresh carries that absence forward, so a frontend user signed in before the upgrade gets `stale_session` and must sign in again before linking. A code works once; a used, expired or unknown code answers 404. No link is ever made by matching emails. The administrator removes it on My account (`unlink`), and an administrator holding `golem15.users.manage_backend_links` links or unlinks another administrator on the Administrators screen (see Admin). Deleting or deactivating the frontend user removes the link in the same transaction; deleting an administrator removes it through the foreign key, and a deactivated or soft-deleted administrator is not answered by the resolver. Boot publishes `*classes.BackendLinks` and the same value as `pact.MCPLinkedBackendResolver` (`LinkedBackendUser`, one query per call), which the framework's MCP endpoint uses to give a frontend user the linked administrator's backend tools. `BackendLinkedEvent` and `BackendUnlinkedEvent` fire inside the write transaction.
- **Frontend permission codes from plugins.** Another plugin declares the frontend permission codes its routes check (`user.permission:<code>`) with `pact.HasFrontendPermissions`. The Users and User Groups permission editors offer the rows of `golem15_user_frontend_permissions` first, unchanged, then the declared codes of the activated plugins in activation order (`classes.FrontendPermissionCatalog`); a seeded row wins over a declared code with the same code, and the first declaring plugin wins over a later one. Nothing is written to the table; the stored permissions keep their shape.
- **Access revocation.** Banning a user (the admin `ban` bulk action, for the users it newly bans), a password reset (`POST /reset-password`), an administrator setting a password on the Users screen and the user's own `POST /change-password` fire `classes.AccessRevokedEvent` (`user.AccessRevoked`: `UserIDs`, `Before`, `Reason`, `Tx`) through `classes.FireAccessRevoked`, inside the write's transaction (a listener error rolls the write back), and a "revoked" `pact.MCPSubjectChanged` per user after it commits, so the users' MCP sessions end. `Before` is the untruncated instant of the revocation for every reason, the self-service change included, so the event ends every OAuth grant of the user however recently its client refreshed it. `tokens_valid_after` keeps its whole-second value: the second of `Before` for a ban, a reset or an administrator's password, and for the self-service change the start of the calling session's `iat` second, so the calling session and the session tokens issued since that second survive. `Reason` is `ban`, `password_reset`, `password_set_by_admin` or `password_changed` (`AccessRevokedBan`, `AccessRevokedPasswordReset`, `AccessRevokedPasswordSetByAdmin`, `AccessRevokedPasswordChanged`). Listeners revoke what such a user still holds elsewhere: `golem15.oauthserver` revokes the users' OAuth access and refresh tokens created before `Before`. `RevokeUserAccess`, `BanUsers` and `DeactivateUsers` keep their behaviour and fire nothing: an application that calls `RevokeUserAccess` or `BanUsers` directly calls `FireAccessRevoked` in the same transaction too. Deactivation and deletion keep their own events (`DeactivatingEvent`, `DeletingEvent`).
- **MCP guard and the `user_me` tool.** Boot registers `classes.MCPUserGuard` as the MCP guard provider `user` in the application's `*pact.MCPGuards` and publishes it as `pact.MCPPersonalTokenResolver`, so the framework's MCP endpoint (built with `-tags summercms_mcp`) can bind tools to routes behind `user.api_token`, `user.scope:<scope>` and `user.permission:<code>` and accept the plugin's personal API tokens (the `golem15.user.api_tokens.prefix`). The guard decides with the routes' own checks: every scope of the route must be granted to the MCP session, and every permission code must be granted by one of the user's groups, as `user.permission` checks it (a user's own permission override does not grant). For an OAuth subject (`ClientID` non-empty), `MCPAllows` and `MCPDispatch` also treat a declared scope as granted when that catalog entry's `Implies` is `read` or `write` and the grant holds that stock scope. `write` does not satisfy `Implies` `read`. A personal token (`ClientID` empty) is not expanded: its scopes stay the grant. The expanded names exist only for that check and on the in-memory credential; they are not written back onto `subject.Scopes`, the token row, or a fingerprint. A tool call runs the route with the user and an in-memory token credential carrying those effective scopes; for a session opened with a personal token the credential's ID is that token's id (the subject's `TokenID`), so a handler can record which token made a change, while an OAuth session's credential has ID 0. The credential is never saved. The plugin's one tool, `me` (exposed as `user_me`), runs `GET /token/me` and answers the signed-in user's payload. A personal token used at the MCP endpoint gets `last_used_at` stamped, and `last_used_ip` when the endpoint passes the client address (`towel.ClientIP`), as the `user.api_token` guard does. Revoking a personal token, saving a user on the Users screen, saving or deleting a group and the link changes fire `pact.MCPSubjectChanged` after they commit, so open MCP sessions re-list their tools or end; revoking a personal token (`DELETE /tokens/{id}`) carries the token's id (`TokenID`), so only the sessions that token opened end. `BackendLinkedEvent` and `BackendUnlinkedEvent`, with `Link.UserID` set, fire on every link and unlink: the confirmation, the Administrators screen, My account and the deletion or deactivation of the frontend user. Deleting an administrator removes the link through the foreign key and fires nothing.
- **Sign-in helpers for social login.** `RegisterOptions.PasswordLess`, `FinishLogin`, `RegistrationSettings`, `RegistrationsFromIP`, `RefreshTTL` and `RemoteIP` let a social-login plugin create accounts and finish logins with the user plugin's own rules instead of copies.
## Usage ## Usage
@@ -68,6 +100,8 @@ plugins:
The plugin's own `go.mod` replaces the framework with `../../../../summercms.go`, so it expects the framework checkout next to the application checkout (`<dir>/summercms.go` and `<dir>/acme/plugins/golem15/user`). The plugin's own `go.mod` replaces the framework with `../../../../summercms.go`, so it expects the framework checkout next to the application checkout (`<dir>/summercms.go` and `<dir>/acme/plugins/golem15/user`).
Because the plugin registers an admin screen, an application that loads it mounts the framework's admin API and must set `admin.jwt.secret` (`SUMMER_ADMIN__JWT__SECRET`); start-up fails while it is empty. The admin screens need framework release v0.1.3 or later.
Another plugin that needs the signed-in user puts its routes behind `jwt.auth`. A machine API uses `user.api_token`, optionally followed by `user.scope:read`, `user.scope:write`, or `user.permission:vendor.plugin.code`. Both guards resolve the same user and current group permissions. Import `git.golem15.com/golem15/sm-user-plugin/models`, `.../classes`, or `.../middleware` for the shared types and helpers. Another plugin that needs the signed-in user puts its routes behind `jwt.auth`. A machine API uses `user.api_token`, optionally followed by `user.scope:read`, `user.scope:write`, or `user.permission:vendor.plugin.code`. Both guards resolve the same user and current group permissions. Import `git.golem15.com/golem15/sm-user-plugin/models`, `.../classes`, or `.../middleware` for the shared types and helpers.
## API reference ## API reference
@@ -93,20 +127,143 @@ All routes are mounted under `/_user/api/v1` with the `throttle:user-api` middle
| `POST /avatar/remove` | `controllers.RemoveAvatar` | | `POST /avatar/remove` | `controllers.RemoveAvatar` |
| `POST /tokens` | `controllers.APITokenStore` (`jwt.auth`) | | `POST /tokens` | `controllers.APITokenStore` (`jwt.auth`) |
| `GET /tokens` | `controllers.APITokenIndex` (`jwt.auth`) | | `GET /tokens` | `controllers.APITokenIndex` (`jwt.auth`) |
| `GET /tokens/scopes` | `controllers.APITokenScopes` (`jwt.auth`) |
| `DELETE /tokens/{id}` | `controllers.APITokenDestroy` (`jwt.auth`) | | `DELETE /tokens/{id}` | `controllers.APITokenDestroy` (`jwt.auth`) |
| `GET /backend-link/{code}` | `controllers.BackendLinkShow` (deprecated: the code is in the logged path; use the POST route) |
| `POST /backend-link/show` | `controllers.BackendLinkShowPost` |
| `POST /backend-link/confirm` | `controllers.BackendLinkConfirm` (`jwt.auth`) |
| `GET /token/me` | `controllers.TokenMe` (`user.api_token`, `user.scope:read`) |
| `POST /devices/initiate` | `controllers.DeviceInitiate` |
| `GET /devices/status/{token}` | `controllers.DeviceStatus` |
| `POST /devices/authorize` | `controllers.DeviceAuthorize` (session token checked in the handler, 401 `{"error":"Unauthorized"}`) |
| `GET /devices` | `controllers.DeviceIndex` (session token checked in the handler) |
| `DELETE /devices/{id}` | `controllers.DeviceDestroy` (session token checked in the handler; `id` is `[0-9]+`) |
`/fetch`, `/refresh`, `/update`, `/change-password`, `/activate`, `/marketing-consent`, `/avatar`, `/avatar/remove` and the `jwt.auth` routes read the session token from the bearer header, then the `token` and `auth_token` cookies.
With `golem15.user.password.public_routes` false the `/login`, `/forgot-password` and `/reset-password` rows are not registered.
`POST /backend-link/show` takes `{"code":…}` (64 lower-case hex characters) and, like the deprecated `GET /backend-link/{code}`, answers `{"data":{"admin":{"login":…,"name":…},"expires_at":"<RFC 3339>"}}` for a usable request and `404 {"error":"not_found"}` for an unknown, used or expired one or when the administrator was deactivated since. `POST /backend-link/confirm` takes `{"code":…}` from the signed-in frontend user and answers `200 {"data":{"backend_user":{"login":…,"name":…}}}`; `409 {"error":"stale_session"}` when the session's `auth_time` is before the request or the token carries no `auth_time` (sign in again), `409 {"error":"already_linked"}` when the user or the administrator is already linked, and `404 {"error":"not_found"}` as the show route. Both show routes send `Cache-Control: no-store, private`. `GET /token/me` answers the `{"user": …}` body of `/fetch` to a personal API token with the `read` scope (401 `{"error":true,"message":"Invalid token."}` from the guard, 403 `Missing required scope: read` from the scope check); it is the target of the MCP tool `user_me`.
### Host-mounted OAuth identities
The host application mounts these constructors on a path it chooses. They are not registered under `/_user/api/v1`. `OAuthIdentitiesOptions.WriteNotFound` is the host's 404 writer so missing, foreign and unknown providers share one body. `OAuthIdentitiesOptions.Providers` is the unlink allow-list; when empty it is read on every request from a published `classes.OAuthProviderSource` (its `KnownOAuthProviders`), else it is `google`, `facebook`, `github` and `microsoft`. Unlinking follows the PHP rule: it succeeds when the user has a self-set password (`has_self_set_password`) or another identity remains, and otherwise answers 409 with the phrase `golem15.user::lang.oauth.last_method_blocked` (body unchanged). The guarded delete runs in a transaction that first locks the user's `users` row, so two concurrent unlinks never remove the last sign-in method.
| Constructor | Role |
|-------------|------|
| `controllers.OAuthIdentitiesIndex` | Lists the caller's linked providers as `{provider, linked_at}` only. |
| `controllers.OAuthIdentitiesDestroy` | Unlinks one provider for the caller (204), or answers 409 when it is the last sign-in method of a user without a self-set password. |
| `controllers.OAuthIdentitiesOptions` | Host injects `Providers` and `WriteNotFound`. |
### Admin
The three screens are served by the framework's generic admin API under `<admin prefix>/api/v1/golem15/user/users`, `.../usergroups` and `.../organisations`; the plugin adds no admin route of its own.
| Item | Value |
|------|-------|
| 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; `deactivate` and `ban` also revoke the selected users' sessions and personal API tokens |
| Record actions (Users) | `activate`, `unban`, `unsuspend`, and `reset_two_factor` (danger, behind `golem15.users.reset_two_factor`, offered only while a published `classes.TwoFactorAdmin` reports a second factor) |
| Record actions (Administrators, `summercms.cabana.users`) | `link_frontend_account` (asks for the frontend user's email) and `unlink_frontend_account` (danger), both behind `golem15.users.manage_backend_links`, from `AdminActionExtensions` |
| My account section | `frontend_account` with the actions `link` and `unlink`, from `AccountContributions` |
On the Administrators screen, `link_frontend_account` links the activated, not deactivated frontend user whose email equals the typed value (letter case and surrounding spaces ignored; no search and no list) to the administrator shown, and records the caller in `linked_by`. An unknown email or an account that is already linked answers 422 on the input. It is offered only while the administrator has no link, and `unlink_frontend_account` only while it has one. The admin's own rule that an administrator cannot act on one whose grants exceed theirs runs first. These two actions skip the frontend user's sign-in proof, which is why their permission has no default role; the My account path always requires it.
Backend permissions, all on the tab `golem15.user::lang.plugin.tab`:
| Code | Default role | Grants |
|------|--------------|--------|
| `golem15.users.access_users` | `developer` | The Users screen and every action on it, including a user's membership of ordinary groups, and the Organisations screen with its members. |
| `golem15.users.access_groups` | `developer` | The User Groups screen. |
| `golem15.users.access_settings` | `developer` | Registered for roles that already name it; no screen uses it yet. |
| `golem15.users.impersonate_user` | `developer` | Registered for roles that already name it; impersonation is not available. |
| `golem15.users.manage_privileged_groups` | none | Adding a privileged group to a user or removing it; creating, re-coding or deleting a privileged group; changing the email or password of a privileged-group member, resetting their second factors, and deleting one for good. Only a superuser or a role that was granted it holds it. |
| `golem15.users.manage_backend_links` | none | Linking a frontend account to another administrator, and unlinking one, on the Administrators screen. Only a superuser or a role that was granted it holds it. |
| `golem15.users.reset_two_factor` | none | The Users screen's "Reset 2FA" record action, which removes every second factor of a user through the two-factor plugin's `classes.TwoFactorAdmin`. Only a superuser or a role that was granted it holds it. |
Migrations added for the admin, all additive:
| ID | Adds |
|----|------|
| `202610040001_add_users_permissions` | `users.permissions` (text, nullable) |
| `202610040002_add_users_last_seen` | `users.last_seen` (timestamp, nullable) |
| `202610040003_create_frontend_permissions` | the table `golem15_user_frontend_permissions` (`code` unique, `label`, `tab`, `comment`) |
Migrations added for linked OAuth identities, all additive:
| ID | Adds |
|----|------|
| `202610050001_create_oauth_identities` | the table `golem15_user_oauth_identities` (`user_id` cascade FK to `users`, unique `(user_id, provider)` and `(provider, provider_id)`, jsonb `profile_data`) |
Migrations added for @mention handles, all additive:
| ID | Adds |
|----|------|
| `202610160002_add_handle_to_users` | `users.handle` (`VARCHAR(255)` NULL, unique index `users_handle_unique`, `ADD COLUMN IF NOT EXISTS`; rollback is a no-op) |
Migrations added for address proof, all additive:
| ID | Adds |
|----|------|
| `202610210001_add_users_email_verified_at` | `users.email_verified_at` (`TIMESTAMPTZ` NULL, `ADD COLUMN IF NOT EXISTS`, no backfill; rollback is a no-op) |
Migrations added for the frontend account link, all additive:
| ID | Adds |
|----|------|
| `202610220001_create_golem15_user_backend_links` | the tables `golem15_user_backend_links` (`user_id` unique, cascade FK to `users`; `backend_user_id` unique, cascade FK to `backend_users`; `linked_by` FK to `backend_users`, set null on delete; `created_at`) and `golem15_user_backend_link_requests` (`code_hash` `CHAR(64)` unique, `backend_user_id` cascade FK, `expires_at`, `used_at`, `created_at`). The `backend_users` keys are added when that table exists, which it does whenever the application migrates through `lagoon.Migrate`. |
Migration added for device authorization, additive:
| ID | Adds |
|----|------|
| `202610260001_create_device_auth_sessions` | the table `golem15_user_device_auth_sessions` with PHP's columns (`token` holding the SHA-256 hex of the device token, unique; `short_code` unique; `user_id` nullable, cascade FK to `users`; `status` checked against the five statuses; `expires_at`, `device_ip`, `device_user_agent`, `device_name`, `auth_ip`, `confirmed_at`, `used_at`, `session_id`, `last_activity_at`) plus `jwt_jti`, indexed on `user_id`, `status`, `expires_at` and `jwt_jti`; rollback drops it |
Packages: Packages:
- `controllers`: the route handlers above, plus the registration steps `POST /register` runs, for other plugins: - `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. - `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` ignores it). Fire it after the user row is committed. - `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` (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. - `IssueToken(app, user, r)` mints the session JWT as `/register` and `/login` do.
- `BackendLinkShow`, `BackendLinkShowPost`, `BackendLinkConfirm` and `TokenMe`, the handlers of the account link and `/token/me` routes.
- `APIArray(ctx, app, user)` builds the user payload, extended by `GetApiArrayEvent` listeners. - `APIArray(ctx, app, user)` builds the user payload, extended by `GetApiArrayEvent` listeners.
- `classes`: `JWTSecret`, `GormUsers` (the `bouncer.UserProvider`), `LookupByEmail`, `UserPermissionGrants`, `UserGroupCodes`, `HasGroupCode`, `APITokenPrefix`, `MintAPIToken`, `HashAPIToken` and `RevokeAPIToken`, plus the activation/reset, throttle, mail locale and event helpers. `RegisterEvent` carries `User` and `Payload map[string]any`, a read-only copy of the register input without the password keys. - `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, consults the login gates before it and fires the login event after it minted the token.
- `CheckLoginGates(ctx, app, attempt)` consults the published `*classes.LoginGates` (none published allows the sign-in) and returns its answer: nil allows, a `*classes.LoginGateResult` replaces the token response, an error must fail the sign-in closed. `Login` and `ActivateByCode` call it before they mint; a social-login plugin calls it before it issues a token.
- `FireLoginEvent(ctx, app, user, source)` fires `classes.LoginEvent` and returns the listeners' error; call it after the token was minted and log the error.
- `DeviceInitiate`, `DeviceStatus`, `DeviceAuthorize`, `DeviceIndex` and `DeviceDestroy`, the device authorization handlers (see Device authorization).
- `RegistrationSettings(app)` returns `allow_registration`, `use_register_throttle`, `activate_mode` and `require_activation` with their defaults (`true`, `true`, `auto`, `true`), and `RegistrationsFromIP(ctx, db, ip)` counts the accounts created from an IP in the last 60 minutes (`/register` refuses at 3 with the throttle on).
- `RefreshTTL(app)` is the refresh window, `golem15.user.jwt.refresh_ttl` minutes (default 20160), and `RemoteIP(r)` the host part of `r.RemoteAddr`, with no proxy handling (`/login` and `/register` use `surf.ClientIP` with `http.trusted_proxies`).
- `classes`: `JWTSecret`, `GormUsers` (the `bouncer.UserProvider`), `LookupByEmail`, `UserPermissionGrants`, `UserGroupCodes`, `HasGroupCode`, `APITokenPrefix`, `MintAPIToken`, `MintAPITokenFor`, `HashAPIToken` and `RevokeAPIToken`, the member token scope catalog `APITokenScope`, `APITokenScopeCatalog` (`Scopes`, `Allowed`, `MemberTokenScopes`), `CompileAPITokenScopes`, `APITokenScopesFor` and the test seam `ResetDeclaredAPITokenScopes`, plus the activation/reset, throttle, mail locale and event helpers. `RegisterEvent` carries `User` and `Payload map[string]any`, a read-only copy of the register input without the password keys. For the admin and for other plugins it also has:
- `MergedPermissions(ctx, db, userID)`, `HasPermission(merged, code)` and `UserHasPermission(ctx, db, userID, code)`, the frontend permission resolver, and `FrontendPermissionOptions(ctx, db)`, the catalogue by tab and code.
- `PermissionManagePrivilegedGroups`, `PrivilegedGroupCodes(cfg)`, `IsPrivilegedCode(codes, code)`, `PrivilegedGroupIDs(ctx, db, codes)` and `IsPrivilegedMember(ctx, db, codes, userID)`, the privileged-group rule.
- `ActivateUsers`, `DeactivateUsers`, `RestoreUsers`, `BanUsers`, `UnbanUsers`, `UnsuspendUser`, `ThrottleStates` and `ForceDeleteCleanup`, the user actions the admin runs. Each takes the handle of the caller's transaction.
- `RevokeUserAccess(ctx, db, userIDs)` ends every session JWT issued before the current second (it stamps `users.tokens_valid_after`, deactivated rows included) and revokes every personal API token of the users. `DeactivateUsers` and `BanUsers` call it; an application may call it for its own offboarding and after writing a ban directly to `user_throttle`. Neither fires `AccessRevokedEvent`: such an application calls `FireAccessRevoked` in the same transaction, so OAuth grants are revoked too.
- `TouchLastSeen(ctx, db, userID)`.
- `OAuthProvider` (`Name`, `Label`) and `OAuthProviderSource` (`EnabledOAuthProviders(ctx)`, `KnownOAuthProviders()`), the seam a social-login plugin publishes with an explicit type argument, `app.Publish[classes.OAuthProviderSource](src)`, so the lookup finds it. `GET /oauth-providers` lists its enabled providers in order; the unlink routes accept its known names.
- `EndSession(ctx, app, w, r)` is what `POST /logout` runs: it blacklists every session JWT the request carries (bearer header, `token` and `auth_token` cookies) that verifies, an expired one too while its refresh window is open, until that window closes, writes the forget cookies described under JWT sessions, and returns the subject of the token the guard would read (`""` when there is none or it does not verify); only a failing blacklist write is an error.
- `SessionToken(r)`, the session JWT the `jwt` guard reads from a request (bearer header, then the `token` and `auth_token` cookies; `""` when there is none); `SessionTokenCookie(r)`, the name of the session cookie that supplied that token (`""` when the bearer header did or there is none), which `POST /refresh` uses to rewrite the `auth.cookie` cookie; and `SessionCookieNames()`, a copy of that cookie list to pass to `bouncer.NewJWTGuard`, so a handler's own guard reads the same token.
- `RequestUser(ctx, app, r)` and `EndRequestSession(ctx, app, w, r)`, for handlers that serve signed-in and anonymous browsers on one route (an OAuth provider's authorize page). `RequestUser` reads and checks the session JWT exactly as the `jwt` guard does (bearer header, then the `token` and `auth_token` cookies, the blacklist, `tokens_valid_after`) and returns the user, or `nil` for an anonymous, invalid, expired or blacklisted request and for a soft-deleted user; only an infrastructure failure is an error. `EndRequestSession` is the best-effort `EndSession`: it revokes and forgets the same way (the forget cookie of `bouncer.LoadCookieConfig`), but a blacklist failure is logged, never returned.
- `OrganisationLogoURL(ctx, app, org, size)`, `OrganisationLogoFields(ctx, app, org)` and `OrganisationLogoSize`, the organisation logo for an application's organisation payloads (see Organisations).
- `AvatarURL(ctx, app, user, size)`, the display picture rule of the user payload at any size: the avatar thumbnail (size by size, mode auto) when the user has an avatar and a file bucket is published, the original file's public URL (`attach.File.URL`, which follows `storage.uploads.public_path_prefix` and `public_url`) when the thumbnail fails, otherwise the gravatar URL. The URL may be protocol-relative or relative. The payload's `avatar_url` comes from it at 128.
- `BackendLinks` (`CreateLinkRequest`, `LinkRequestByCode`, `ConfirmLinkRequest`, `SetLink`, `RemoveLink`, `LinkFor`, `LinkOf`, `LinkedBackendUser`, `RegisterBackendLinkListeners`), its errors `ErrLinkRequestNotFound`, `ErrLinkRequestUsed`, `ErrLinkRequestExpired`, `ErrStaleSession`, `ErrAlreadyLinked`, `ErrBackendUserUnavailable` and `ErrFrontendUserUnavailable`, the events `BackendLinkedEvent` / `BackendLinkedEventName` and `BackendUnlinkedEvent` / `BackendUnlinkedEventName`, `BackendLinkRequestTTL(app)`, `DefaultBackendLinkRequestTTL`, `FrontendURL(app)`, `BackendLinkPagePath(app)`, `DefaultBackendLinkPagePath`, `BackendLinksFor(app)` (the published service, or one over the app) and `BackendDisplayName(admin)`.
- `BlacklistSweepInterval(app)` reads `golem15.user.jwt.blacklist_sweep_interval` (`DefaultBlacklistSweepInterval` when unset, 0 for no sweep, an error for an interval the scheduler cannot run); `JWTBlacklistTable` is the blacklist store's table.
- `PermissionManageBackendLinks`, `FrontendPermissionCatalog(ctx, app, db)`, `MCPUserGuard`, `FireSubjectChanged(ctx, app, guard, userID, kind)` and `FireSubjectChangedAfterCommit(ctx, app, tx, guard, userID, kind)` with the guard names `SubjectGuardUser` and `SubjectGuardBackend`, and `FireSubjectEvent(ctx, app, ev)` and `FireSubjectEventAfterCommit(ctx, app, tx, ev)`, which fire a whole `pact.MCPSubjectChanged` (with `TokenID` or `ClientID` to end only one token's or one client's sessions).
- `AccessRevokedEvent` / `AccessRevokedEventName` and `FireAccessRevoked(ctx, app, tx, userIDs, before, reason)` (see Access revocation).
- `LoginAttempt`, `LoginGateResult`, `LoginGate` (`CheckLogin(ctx, attempt)`), `LoginGates` with `NewLoginGates()`, `Add(gate)` and `Check(ctx, attempt)`, the login-gate seam (see Login gates), and the sources `LoginSourcePassword`, `LoginSourceSocial`, `LoginSourcePasskey`, `LoginSourceTwoFactor` and `LoginSourceDevice`.
- `LoginEvent` / `LoginEventName` (see Login event).
- `DeviceShortCodeAlphabet`, `NewDeviceToken()`, `NewDeviceShortCode()`, `NormalizeDeviceShortCode(s)`, `DeviceAuthTTL(app)`, `DeviceAuthURLFor(app, token, shortCode)`, `DeviceAuthURL(app, token)` (the same with the token in place of the short code), `DeviceDisplayName(stored, userAgent)`, `RevokeDeviceSessions(ctx, db, userIDs...)` (revokes the users' pending and confirmed sessions; the plugin calls it for every `AccessRevokedEvent`), `FollowDeviceJTI(ctx, db, oldJTI, newJTI)` (moves a used session to a refreshed token's jti and reports a session revoked meanwhile; `POST /refresh` calls it and refuses the refresh then) and `HandOverDeviceJTI(ctx, db, oldJTI, newJTI)` (the same move without the report), the device authorization helpers; device tokens are hashed with `HashAPIToken`.
- `TwoFactorAdmin` (`HasTwoFactor(ctx, tx, userID)`, `Reset(ctx, tx, user)`) and `PermissionResetTwoFactor`, the Reset 2FA slot (see Admin: Reset 2FA), and `(*AccessRevokedEvent).PasswordChanged()` (see Password-change hook).
- `MailTemplate(base, locale)`, `ResolveMailLocale(ctx, user)`, `ResolveMailLocaleFor(ctx, app, user)`, `NormalizeMailLocale(raw)` and `MailFallbackLocale(app)`, the mail language helpers. `ResolveMailLocale` returns `pl`, `en` or `""` (neither the user nor the request names a supported language); a plugin that mails in the user's language calls `ResolveMailLocaleFor`, which adds the application's fallback and always returns `pl` or `en`, and passes its result to `MailTemplate`.
- `HandleGenerator`, `AssignHandle(ctx, db, user)`, `CreatedEvent` / `CreatedEventName`, `DeletingEvent` / `DeletingEventName`, `DeactivatingEvent` / `DeactivatingEventName`, `AuthorizeUser` and `RegisterUserAuthorizer`.
- `middleware`: `APITokenGuard`, `Scope`, `Permission` and `BearerToken`. - `middleware`: `APITokenGuard`, `Scope`, `Permission` and `BearerToken`.
- `models`: `User`, `Throttle`, `Organisation`, `UserGroup`, `APIToken`. - `models`: `User`, `Throttle`, `Organisation`, `UserGroup`, `UsersGroup` (the `users_groups` pivot), `APIToken`, `OAuthIdentity`, `FrontendPermission`, `BackendLink`, `BackendLinkRequest`, `DeviceAuthSession` (with `DeviceStatusPending`, `DeviceStatusConfirmed`, `DeviceStatusUsed`, `DeviceStatusExpired` and `DeviceStatusRevoked`) and `PermissionSet`. `PermissionSet` reads a stored permission column tolerantly (NULL, an empty string, `[]`, numeric strings) and writes a JSON object of integers; `ParsePermissionSet` and `PermissionSet.Text` do the same for a column that is a plain string on its model. `UserGroup.UsersCount` is filled only by a query that selects `users_count` (the admin list does). `Organisation.Members` is the relation behind the members manager, `Organisation.AttachRelations` declares its avatar (`OrganisationAvatarField`) and its logo (`OrganisationLogoField`), and `Slugify` is the slug rule. `User.FilterScope` answers the admin list scope `FilterByGroup`, and `User.AttachRelations` declares the avatar (`AvatarField`). `User.RegisterFillable` is the registration allow-list; `User.Fillable` is the wider mass-assignment backstop of the admin Users form (cabana intersects it with the form's fields) and of trusted application code.
- `updates`: the gormigrate migrations, returned by `updates.All()`. - `updates`: the gormigrate migrations, returned by `updates.All()`.
- `console`: `RequirePasswordChange` and `APITokenCommands`. - `console`: `RequirePasswordChange`, `BackfillHandles`, `JWTBlacklistSweep` and `APITokenCommands`.
## Configuration ## Configuration
@@ -119,11 +276,13 @@ Defaults live in `config/config.yaml` and are merged under `golem15.user.*`. Any
| `golem15.user.jwt.refresh_ttl` | `20160` | Refresh window in minutes. | | `golem15.user.jwt.refresh_ttl` | `20160` | Refresh window in minutes. |
| `golem15.user.jwt.blacklist_grace` | `0` | Grace period in seconds for a blacklisted token. | | `golem15.user.jwt.blacklist_grace` | `0` | Grace period in seconds for a blacklisted token. |
| `golem15.user.jwt.leeway` | `0` | Clock leeway in seconds (declared for parity, not read yet). | | `golem15.user.jwt.leeway` | `0` | Clock leeway in seconds (declared for parity, not read yet). |
| `golem15.user.jwt.blacklist_sweep_interval` | `10m` | How often expired blacklist rows are deleted (a Go duration). | | `golem15.user.jwt.blacklist_sweep_interval` | `10m` | How often the scheduler runs `user:jwt-blacklist-sweep`, which deletes the `jwt_blacklist` rows whose `expires_at` has passed (a Go duration). It must be at least 1s and divide 24h evenly (`1m`, `10m`, `1h`); `0` schedules no sweep. A value that does not parse, is negative, is shorter than a second or does not divide 24h fails boot. The sweep runs on the job worker's scheduled queue: the in-process worker of `summer serve` while `queue.work_in_serve` is on, `queue:work`, or `schedule:run`; with no worker on that queue, run `schedule:run --once` from cron or the command by hand. The schedule runs once per period across instances. |
| `golem15.user.activation.require_activation` | `true` | Whether a new account must be activated before login. | | `golem15.user.jwt.token_cookie` | `false` | When on, `POST /login`, `POST /register` (when it signs the new account in) and `POST /activate-by-code` set the HttpOnly session cookie with the `auth.cookie.*` attributes (`bouncer.LoadCookieConfig`; Max-Age `refresh_ttl`) and leave `token` out of the body (`user`, and `message` on activate-by-code, stay). When off, the token is in the body and no cookie is set. The twin of `golem15.sociallogin.token_cookie`. |
| `golem15.user.activation.require_activation` | `true` | Whether an account must be activated before login. When `true`, `POST /login` refuses a not-activated account (the opaque invalid-login answer, counted as a failed attempt) and `/register` in `admin` mode returns no token; when `false`, both sign such an account in. |
| `golem15.user.activation.activate_mode` | `auto` | `auto`, `user` (mailed code) or `admin`. | | `golem15.user.activation.activate_mode` | `auto` | `auto`, `user` (mailed code) or `admin`. |
| `golem15.user.activation.reset_ttl_minutes` | `60` | Password reset code lifetime. | | `golem15.user.activation.reset_ttl_minutes` | `60` | Password reset code lifetime. |
| `golem15.user.activation.activation_ttl_hours` | `72` | Activation code lifetime. | | `golem15.user.activation.activation_ttl_hours` | `72` | Activation code lifetime. |
| `golem15.user.mail.fallback_locale` | `pl` | The mail language when the user's `preferred_locale` and the request locale name neither `pl` nor `en`. `pl` keeps the unsuffixed templates; `en` (`SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en`) suits English-only sites. Region forms such as `en-GB` are accepted; any other value fails boot. Read on every send. The user and the request still come first, so a browser that asks for Polish first gets Polish mail on an application whose fallback is `en`. |
| `golem15.user.registration.allow_registration` | `true` | Whether `POST /register` accepts new accounts. | | `golem15.user.registration.allow_registration` | `true` | Whether `POST /register` accepts new accounts. |
| `golem15.user.registration.use_register_throttle` | `true` | Whether registration is limited to three accounts per IP an hour. | | `golem15.user.registration.use_register_throttle` | `true` | Whether registration is limited to three accounts per IP an hour. |
| `golem15.user.throttle.attempt_limit` | `5` | Failed logins before suspension. | | `golem15.user.throttle.attempt_limit` | `5` | Failed logins before suspension. |
@@ -131,20 +290,33 @@ Defaults live in `config/config.yaml` and are merged under `golem15.user.*`. Any
| `golem15.user.throttle.use_throttle` | `true` | Whether login throttling is on. | | `golem15.user.throttle.use_throttle` | `true` | Whether login throttling is on. |
| `golem15.user.password.bcrypt_cost` | `10` | bcrypt cost for new password hashes. | | `golem15.user.password.bcrypt_cost` | `10` | bcrypt cost for new password hashes. |
| `golem15.user.password.min_length` | `8` | Minimum password length. | | `golem15.user.password.min_length` | `8` | Minimum password length. |
| `golem15.user.password.public_routes` | `true` | When `false`, `POST /login`, `POST /forgot-password` and `POST /reset-password` are not registered and answer 404 like any unknown path; `POST /register` (still gated by `allow_registration` and guarded by `golem15.user.turnstile`) and every other route stay. It is read when the routes are built, so a change needs a restart. It takes `true` or `false`, also as a string (`SUMMER_GOLEM15__USER__PASSWORD__PUBLIC_ROUTES=false`); an empty value means `true`; any other value fails boot. |
| `golem15.user.api_tokens.prefix` | `usr_` | Prefix for newly minted and accepted shared API-token secrets. Override an existing application's legacy prefix without creating a plugin-specific token table. | | `golem15.user.api_tokens.prefix` | `usr_` | Prefix for newly minted and accepted shared API-token secrets. Override an existing application's legacy prefix without creating a plugin-specific token table. |
| `golem15.user.privileged_groups` | `[admin]` | Codes of the privileged user groups. Membership of such a group, the group's code and its delete, and the email, password, Reset 2FA and permanent delete of its members need `golem15.users.manage_privileged_groups`. Read on every request. An empty list protects no group. |
| `golem15.user.frontend_url` | `""` | The site the plugin's own links point to: the account link page is this URL + `backend_links.page_path` + `#code=<code>`, and it fills `{frontend_url}` in `device_auth.auth_url`. Empty falls back to `app.url`; a trailing slash is dropped. |
| `golem15.user.device_auth.auth_url` | `{frontend_url}/device/scan/{short_code}` | The `auth_url` a device shows as its QR code, where a signed-in user authorizes it. `{frontend_url}` is `golem15.user.frontend_url` (else `app.url`, no trailing slash), `{short_code}` the session's short code and `{token}` the device token. `POST /devices/authorize` takes the short code in `token` too. Keep `{token}` out of it: the device token is also the secret the device collects its session token with. |
| `golem15.user.device_auth.ttl_minutes` | `5` | Minutes a device session can be authorized and handed over. |
| `golem15.user.backend_links.page_path` | `/link-admin` | The site page that confirms an account link. A value without a leading `/` gets one. |
| `golem15.user.backend_links.request_ttl` | `10m` | How long a link request an administrator starts on My account stays usable (a Go duration). A value that does not parse or is not positive fails boot. |
| `golem15.user.turnstile` | `""` | Cloudflare Turnstile on `POST /login` and `POST /register` (only `/register` while `golem15.user.password.public_routes` is false). Empty adds nothing; `open` or `closed` appends the framework's `turnstile:open` or `turnstile:closed` middleware to those two routes only (summercms v0.3.0 and later; secret in `turnstile.secret`, token in the `turnstile_token` field). `open` lets requests pass when Cloudflare is unreachable, `closed` refuses them. Any other value fails boot. |
## CLI commands ## CLI commands
| Command | Purpose | | Command | Purpose | Example |
|---------|---------| |---------|---------|---------|
| `user:require-password-change <email>` | Flag an account so its next session must set a new password. | | `user:require-password-change <email>` | Flag an account so its next session must set a new password. Ends with `Password change required for <email>`. | `bin/<app> user:require-password-change jane@example.com` |
| `user:token:create <email> [--name api] [--scopes read,write] [--expires RFC3339]` | Create an application-wide API token and print its secret once. | | `user:backfill-handles` | Assign a unique handle to every user row that still has none, with a progress bar. Ends with `Assigned handles to N user(s)`. | `bin/<app> user:backfill-handles` |
| `user:token:list` | List token metadata without secrets or hashes. | | `user:jwt-blacklist-sweep` | Delete the `jwt_blacklist` rows whose `expires_at` has passed; the scheduler runs it every `golem15.user.jwt.blacklist_sweep_interval`. Ends with `Deleted the expired JWT blacklist rows.` | `bin/<app> user:jwt-blacklist-sweep` |
| `user:token:revoke <id>` | Revoke a shared API token immediately. | | `user:token:create <email> [--name api] [--scopes read,write] [--expires RFC3339] [--json]` | Create an application-wide API token and print its secret once (also under `-q`); `--json` prints the token and its details as one object. | `bin/<app> user:token:create jane@example.com --scopes read --json` |
| `user:token:list` | List token metadata without secrets or hashes; `--json` prints a JSON array with the expiry, revocation and last-use times. | `bin/<app> user:token:list --json` |
| `user:token:revoke <id>` | Revoke a shared API token immediately. | `bin/<app> user:token:revoke 12` |
Each command uses the database the serve command published or, run from the console, opens one from `database.dsn` (and loads the encryption keys from `app.key`) for its duration. `bin/<app> help <command>` shows each command's long help and examples. The plugin logs through the component `user` (`log.components.user` in `config/log.yaml`).
## Dependencies ## Dependencies
- The SummerCMS framework, `git.golem15.com/golem15/summercms` (modules `backpack`, `bonfire`, `bouncer`, `pact`, `party`, `surf` and others). - The SummerCMS framework v0.5.0, `git.golem15.com/golem15/summercms` (modules `backpack`, `bonfire`, `bouncer`, `diary`, `pact`, `party`, `surf` and others).
- The organisation role cleanup of the admin (members manager and user form) uses cabana's `ClearOnChange`, added in SummerCMS v0.4.3.
- gormigrate, GORM, golang-jwt and gocloud.dev, as pinned in `go.mod`. - gormigrate, GORM, golang-jwt and gocloud.dev, as pinned in `go.mod`.
- testcontainers-go for the Postgres-backed tests. - testcontainers-go for the Postgres-backed tests.
@@ -156,3 +328,41 @@ go test ./... # full run, starts Postgres with testcontainers (needs D
``` ```
`TestRegisterCORSPath` reads the host application's `config/http.yaml`, so run the tests inside an application checkout where the plugin is mounted at `plugins/golem15/user`. `TestRegisterCORSPath` reads the host application's `config/http.yaml`, so run the tests inside an application checkout where the plugin is mounted at `plugins/golem15/user`.
The mail language is pinned by `TestNormalizeMailLocale`, `TestResolveMailLocale`, `TestResolveMailLocaleFor` and `TestMailFallbackLocale` (in `classes`, `-short`), `TestMailFallbackLocaleConfig`, `TestMailFallbackLocaleBoot` and `TestPolishMailSubjects` (root, `-short`; the last renders each Polish template next to its `-en` twin and requires a different subject) and `TestMailLocaleFromRequest` (Postgres, skipped under `-short`: `POST /forgot-password` with a raw `Accept-Language` request locale, the default and an `en` fallback, and a saved `en-GB`).
`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.
`TestLogoutEndsTheSession` signs in through `POST /login` and logs out with the bearer header, with only the `token` or `auth_token` cookie, and with both a bearer and a different cookie token, then checks that the token is refused on a `jwt.auth` route, at `/fetch` and at `/refresh`, each through every carrier (bearer header, `token` cookie, `auth_token` cookie), that the forget cookies match the token cookie's attributes (also with a configured domain and SameSite), that the blacklist row lasts for the refresh window so `/refresh` stays refused after the sweep that follows the access token's expiry, that an expired but refreshable token is revoked, and which tokens a logout refuses with 401.
The blacklist sweep is pinned by `TestBlacklistSweepInterval` (in `classes`, `-short`: the default, valid intervals, `0` as a string, a duration, an int and a `SUMMER_` variable, and the values that must fail), `TestBlacklistSweepSchedule` (root, `-short`: the default and custom `Schedule()` entries, none for `0` or a bad value, every scheduled command registered), `TestBlacklistSweepBoot` (root, `-short`: Boot fails naming the key for each bad value and accepts `10m`, `0` and an unset key), `TestJWTBlacklistSweepCommand` (root, `-short`: one `Sweep` through the published store with the result line, a failing store, a nil app) and `TestJWTBlacklistSweepPostgres` (Postgres, skipped under `-short`: the command deletes the expired row and keeps the valid one, through the published store and through a database opened from `database.dsn`).
`TestBootBeforeDatabase` boots in the serve order (`party.Activate` with no database, then `lagoon.Publish`, through `newServeOrderEnv` in `admin_harness_test.go`). It checks that the blacklist store and the GORM hooks are installed on Publish and not before, and that a token ended by `POST /logout` is refused on a `jwt.auth` route through every carrier, at `/fetch` and at `/refresh`, with its `jwt_blacklist` row. `TestAppBlacklist` (in `-short`) covers the guard's per-request store lookup: no store, delegation and a failing store.
`TestSessionRoutesAcceptCookies` checks that a session `jwt.auth` accepts through only the `token` or `auth_token` cookie is served by `GET /fetch`, `POST /refresh` (through `token`, the `auth.cookie` default, the rotated token comes back in a rewritten cookie with a `{}` body; through `auth_token` it comes in the body with no cookie; the old token is refused afterwards), `POST /update`, `POST /change-password` (the calling token stays valid) and `POST /marketing-consent`; that a request without credentials still gets the old 401 bodies; that the bearer header wins over a cookie exactly as on `jwt.auth`, an invalid bearer included; and that a cut-off token and a banned user are refused through the cookie.
`TestLoginRequiresActivation` pins the activation gate of `POST /login`: under the default and an explicit `require_activation: true` a not-activated account's correct password gets the byte-identical 401 (status, body, `Content-Type` and `Cache-Control`) of a wrong password, stamps no `last_seen`, adds one throttle attempt and suspends the account after `attempt_limit` refusals; `require_activation: false` and activated accounts sign in; a deactivated activated account is restored with the reactivate mail, and a deactivated not-activated account is refused and stays deactivated unless the key is off.
`TestLoginThrottleClientIP` sends failed logins through one trusted proxy (`http.trusted_proxies`). It checks that the throttle row carries the `X-Forwarded-For` client, and that this client is suspended while another client behind the same proxy still signs in. It also checks that without trusted proxies a changing `X-Forwarded-For` neither moves the counter nor escapes the suspension.
`TestRefreshRewritesAuthCookie` covers the cookie-carried `POST /refresh`: the `token` cookie rewritten with the rotated token and the `LoadCookieConfig` attributes (the old token refused, the new one served by `/fetch` and `jwt.auth`), `auth_token` and bearer refreshes left body-only (the bearer wins over a cookie), a configured cookie name and refresh window, refusals that set no cookie, and a broken `auth.cookie` block that answers the opaque 500 and rotates nothing. `TestSessionTokenCookie` (in `-short`) is the carrier table of `classes.SessionTokenCookie`.
`TestTokenCookie` covers `golem15.user.jwt.token_cookie`: off by default (body tokens, no cookie); on for `POST /login`, `POST /register` and `POST /activate-by-code`, with the session cookie serving `/fetch` and rotating through a cookie refresh and no `token` in the body; `POST /tokens` unaffected; a configured cookie name and refresh window; and a broken `auth.cookie` block that answers the opaque 500 and signs in, creates and activates nothing.
`TestPasswordPublicRoutes` (in `-short`) and `TestPasswordPublicRoutesAnswer404` cover `golem15.user.password.public_routes`: unset, `true` and the `config.yaml` default register every route; `false` (also from a `SUMMER_` variable) drops exactly the three password routes and keeps every other route and its middleware, the turnstile on `/register` included; an invalid value fails `Routes`. Through the assembled router the dropped routes (and a `GET /login`) answer exactly like an unknown path and sign in, mail and reset nothing, while the default answers are unchanged and `/register`, `/fetch`, `/refresh` and `/logout` still work.
`TestAdminOrganisationMembershipClearsRole` checks that the members manager's unlink and link and a Users form save that changes the organisation clear `organisation_role`, that a save keeping the organisation keeps it, and that deleting an organisation clears both columns.
`TestBackendLinkSmoke` runs the account link end to end: My account offers `link`, the action answers the site URL with a 64-hex code, the show route answers the administrator's login and expiry, a session older than the request gets `stale_session`, a fresh one links (the published resolver answers the administrator), the code is one-shot, a second frontend user gets `already_linked`, an expired code is 404, unlink and deleting the frontend user remove the link, and the subject events fire. `TestBackendLinkAuthTimeSmoke` checks the `auth_time` proof: a session signed in before the request and refreshed after it gets `stale_session`, a sign-in after the request links, `POST /backend-link/show` answers for the code in the body, and My account's URL carries the code in the fragment. `TestBackendLinkAdminSmoke` covers the Administrators screen actions: offered only as they apply and only with `golem15.users.manage_backend_links`, the case-insensitive email match, `linked_by`, `BackendLinkedEvent`, the 422 refusals and the unlink. `TestUserMCPGuardSmoke` covers the `user` guard provider (requirements, the scope and group-permission checks, the dispatch credential, personal token resolution), `GET /token/me` and the revoke, group and user subject events. `TestFrontendPermissionCatalogSmoke` boots a test plugin that declares frontend permission codes and checks both editors' options. `TestMemberTokenScopesSmoke` checks the member token scope catalog (duplicate, built-in and bad names fail) and, with Docker, minting, the scope check, the list, `GET /tokens/scopes` and a second application refusing the scope. The others need Docker.
`TestMemberTokenScopesBoot` (no Docker) checks that the scope Boot step fails for a name two plugins declare (naming both), for a redeclared `read`, `write` or `ai`, for a bad name, an empty label and a missing phrase key. With Docker: `TestMemberTokenScopes` walks the member token scope acceptance list item by item (mint and `middleware.Scope`, the 403 message, the 422 for an undeclared scope, the list, discovery in en and pl, the per-application catalog and the legacy fallback); `TestBackendLinkAuthTime` checks the link proof against login, request, refresh and re-login orders, a token without `auth_time` and another user's session token; `TestBackendLinkShowPost` checks that `POST /backend-link/show` answers like the GET route with `Cache-Control: no-store, private`, the fragment URL and `backend_links.page_path`; `TestAccessRevocation` checks `AccessRevokedEvent` from the ban action, the password reset, the password change and an administrator setting a password (ids, `Before`, reason, the transaction, the subject event after commit, the rollback on a failing listener) and that a banned user loses the backend link until unbanned; `TestUserMCPGuardClientIP` checks `last_used_ip` on the MCP personal-token path; `TestAPITokenRevokeEvent` checks the token-specific revoked event of `DELETE /tokens/{id}`; `TestOrganisationLogo` checks the logo field, the upload, `OrganisationLogoFields` with and without a logo, the URL fallback when the thumbnail fails, and that deleting an organisation removes its avatar and logo attachments, the rows and, once the delete commits, the blobs and thumbnails.
The login-gate seam, the password-change hook and the Reset 2FA slot have their own tests. `TestLoginGates` (in `-short`, clean under `-race`) pins the registry: a nil or empty registry allows, gates run in the order they were added, the first result or error wins and stops the chain, nil gates are ignored, and `controllers.CheckLoginGates` allows when no registry is published. `TestLoginGateOrder` pins where `POST /login` asks the gates: refused first factors (wrong password, unknown email, not activated, banned) never reach them; the gate sees the attempt with the body already read; the bcrypt rehash happens before a challenge and fires no password-change event; a challenged deactivated account stays deactivated with no mail and no login event, while an allowed one is restored with one reactivate mail and one login event; a gate's status and body pass through; `/refresh` never asks a gate. `TestActivateByCodeGates` pins `POST /activate-by-code`: a challenge or a refusal replaces the token with the gate's status and body and sets no cookie, the gate sees source `password` and the code in `Fields`, an allowing gate gets the usual token answer, a gate error answers the opaque 500, an invalid code never reaches a gate, and the account is activated whatever the gate answers. `TestPasswordChangedSources` checks that the reset, the user's own change and an administrator setting a password each fire one `AccessRevokedEvent` with `PasswordChanged()` true inside the write's transaction (a listener's write through `ev.Tx` commits with it, a listener error rolls both back), and that the rehash and a registration fire none. `TestResetTwoFactorAction` covers the `reset_two_factor` record action: not offered without a published `classes.TwoFactorAdmin`, offered with the danger confirmation when one reports a second factor, hidden when it reports none, refused without `golem15.users.reset_two_factor`, `Run` refused outside the action's transaction, `Reset` committed with the action and rolled back by its error, and a privileged-group member refused with 403 before `Reset` without `golem15.users.manage_privileged_groups`. The plan 01 smoke tests (`TestLoginGatesSmoke`, `TestLoginGateSmoke`, `TestPasswordChangedEventSmoke`, `TestResetTwoFactorSlotSmoke`) stay. The Postgres tests need Docker.
The device authorization flow is pinned by `TestDeviceCodes` (in `classes`, `-short`: 10,000 tokens and short codes, the alphabet in every position, no modulo bias, the normalization table), `TestDeviceAuthURL` and `TestDeviceDisplayName` (both `-short`: the `auth_url` template with `{short_code}` as the default, the TTL setting and PHP's user-agent order), and on Postgres through the assembled routes: `TestDeviceInitiate` (PHP's answer with an `auth_url` that carries the short code and not the token, the stored pending row, the TTL, the 255-character `device_name` bound, the cleanup of at most 500 stale pending or expired sessions per call, the retry of an insert whose short code collides with a stored one); `TestDeviceStatus` (unknown, pending, PHP's flat expired body for a pending or confirmed session past `expires_at`, used and revoked sessions that never expire); `TestDeviceAuthorize` (short-code forms, the 422 and 400 refusals, the token path, the short code in the token field, body-only fields, sessions bound to another user, a repeated authorize, expired, used and revoked sessions, concurrent authorizes by two users binding one, and the 401 for a missing, invalid, foreign-signed or ended session); `TestDeviceHandOverConcurrent` (50 concurrent polls hand one token over with one login event of source `device`; a poll with another `User-Agent` than the initiating device's takes nothing and the device still collects its token; a deactivated or banned user's session becomes revoked); `TestDeviceAccessRevocation` (a password change revokes the user's confirmed sessions and keeps used ones and other users' sessions, and a session authorized before `tokens_valid_after` hands nothing over without the event); `TestDeviceListAndRevoke` (only confirmed and used sessions, newest activity first, `is_current`, the display name, an empty list as `[]`, 404 for foreign and unknown ids, a repeated revoke, a revoked device signed out); `TestDeviceRevokeAfterRefresh` (the row follows one and two refreshes, a revoke ends the whole token lineage and the blacklist entry outlives the refresh window, a failed refresh leaves the row); `TestDeviceRevokeRacesRefresh` (a refresh of a session revoked after the blacklist check is refused without a token, and a device refreshing in a tight loop while it is revoked ends with its last token refused); `TestDeviceTokensAtRest` (the token column is the SHA-256 hex, no column holds the token or the session JWT). `TestDeviceAuthSessionsMigration` (in `updates`) checks the table's PHP column names plus `jwt_jti`, the types, the unique `token` and `short_code`, the status CHECK, the indexes, the cascade on user delete, the rollback and a second up. The plan 01 smoke tests `TestDeviceCodesSmoke`, `TestDeviceFlowSmoke` and `TestDeviceRevokeSmoke` stay.
The admin tests (`TestAdmin*`) boot the plugin with the admin API mounted on a database of their own and sign in backend administrators with a chosen permission set; the helpers are in `admin_harness_test.go`.

234
access_revocation_test.go Normal file
View File

@@ -0,0 +1,234 @@
package user
import (
"context"
"errors"
"net/http"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/pact"
)
// revokedSeen is one AccessRevokedEvent as a listener saw it, with what was
// already visible at that moment.
type revokedSeen struct {
ev classes.AccessRevokedEvent
// stored is tokens_valid_after of the first user read through ev.Tx.
stored *time.Time
// subjectEarly reports whether a revoked subject event for the first
// user had already fired (it must wait for the commit).
subjectEarly bool
}
// revocationProbe records every AccessRevokedEvent of an app and can make
// the listener fail.
type revocationProbe struct {
mu sync.Mutex
seen []revokedSeen
fail atomic.Bool
}
func (p *revocationProbe) take() []revokedSeen {
p.mu.Lock()
defer p.mu.Unlock()
out := p.seen
p.seen = nil
return out
}
func listenRevocations(env *adminEnv, spy *subjectSpy) *revocationProbe {
probe := &revocationProbe{}
env.app.Events.Listen("test.access_revoked", func(ctx context.Context, ev *classes.AccessRevokedEvent) error {
if probe.fail.Load() {
return errors.New("listener refused")
}
seen := revokedSeen{ev: *ev}
if ev.Tx != nil && len(ev.UserIDs) > 0 {
var row struct{ TokensValidAfter *time.Time }
if err := ev.Tx.WithContext(ctx).Raw(`SELECT tokens_valid_after FROM users WHERE id = ?`, ev.UserIDs[0]).Scan(&row).Error; err == nil {
seen.stored = row.TokensValidAfter
}
seen.subjectEarly = spy.has(classes.SubjectGuardUser, ev.UserIDs[0], pact.MCPSubjectRevoked)
}
probe.mu.Lock()
probe.seen = append(probe.seen, seen)
probe.mu.Unlock()
return nil
})
return probe
}
// one asserts exactly one event naming id for reason, fired in a
// transaction before the user's revoked subject event.
func one(t *testing.T, probe *revocationProbe, spy *subjectSpy, id uint, reason string) revokedSeen {
t.Helper()
seen := probe.take()
if len(seen) != 1 {
t.Fatalf("%s fired %d access-revoked events, want 1: %+v", reason, len(seen), seen)
}
got := seen[0]
if got.ev.Reason != reason || len(got.ev.UserIDs) != 1 || got.ev.UserIDs[0] != id || got.ev.Tx == nil {
t.Fatalf("%s event = %+v, want user %d in a transaction", reason, got.ev, id)
}
if got.subjectEarly {
t.Fatalf("%s: the revoked subject event fired before the commit", reason)
}
if !spy.has(classes.SubjectGuardUser, id, pact.MCPSubjectRevoked) {
t.Fatalf("%s: no revoked subject event for user %d after the commit", reason, id)
}
return got
}
// wholeSecondsUntruncated checks the stored cutoff has whole seconds and
// Before is the untruncated instant of the same second.
func wholeSecondsUntruncated(t *testing.T, env *adminEnv, id uint, before time.Time) {
t.Helper()
stored := env.reload(t, id).TokensValidAfter
if stored == nil || stored.Nanosecond() != 0 {
t.Fatalf("stored tokens_valid_after = %v, want whole seconds", stored)
}
if before.Before(*stored) || !before.Truncate(time.Second).Equal(stored.Truncate(time.Second)) {
t.Fatalf("Before %s is not the untruncated instant of the stored cutoff %s", before, stored)
}
if before.Nanosecond() == 0 {
t.Logf("the clock answered a whole second (%s); the sub-second part is not observable this run", before)
}
}
// TestAccessRevocation pins plan 08's revocation chain on the user side
// (C-CR-01, RC-CR-01, P-35): the ban bulk action, ResetPassword,
// ChangePassword and an administrator setting a password each fire one
// AccessRevokedEvent in the write's transaction with the right ids, Before
// and Reason (for ChangePassword the instant of the request, never the
// calling session's older iat, while the session itself survives), then one
// revoked subject event per user after the commit; the ban fires only for
// newly banned users; a failing listener rolls a password reset back; and
// a banned linked user loses the backend link until unbanned. Postgres
// only: skipped under -short.
func TestAccessRevocation(t *testing.T) {
if testing.Short() {
t.Skip("Postgres")
}
env := newAdminEnv(t)
spy := env.spySubjects()
probe := listenRevocations(env, spy)
admin := env.superAdmin(t)
ctx := context.Background()
t.Run("the ban bulk action fires for newly banned users only", func(t *testing.T) {
already := env.seedUser(t, "rv-already", nil)
env.seedThrottle(t, already, "203.0.113.20", true, nil)
fresh := env.seedUser(t, "rv-ban", nil)
probe.take()
spy.reset()
started := time.Now()
env.expect(t, http.StatusOK, http.MethodPost, adminAPI(adminUsersPath+"/bulk/ban"), admin, map[string]any{"ids": []uint{already.ID, fresh.ID}})
got := one(t, probe, spy, fresh.ID, classes.AccessRevokedBan)
if got.ev.Before.Before(started) || got.ev.Before.After(time.Now()) {
t.Fatalf("ban Before %s outside the request", got.ev.Before)
}
if spy.has(classes.SubjectGuardUser, already.ID, pact.MCPSubjectRevoked) {
t.Fatal("the already banned user got a revoked event")
}
})
t.Run("ResetPassword fires with the untruncated instant", func(t *testing.T) {
user := env.seedUser(t, "rv-reset", nil)
code, err := classes.IssueResetCode(ctx, env.gdb, user)
if err != nil {
t.Fatal(err)
}
probe.take()
spy.reset()
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/reset-password", "", map[string]string{"code": packed, "password": "rv-new-password", "password_confirmation": "rv-new-password"})
got := one(t, probe, spy, user.ID, classes.AccessRevokedPasswordReset)
if got.stored == nil {
t.Fatal("the listener did not see the new cutoff inside the reset's transaction")
}
wholeSecondsUntruncated(t, env, user.ID, got.ev.Before)
})
t.Run("ChangePassword revokes as of the request and keeps the calling session", func(t *testing.T) {
user := env.seedUser(t, "rv-change", func(u *models.User) { u.HasSelfSetPassword = true })
// A session last refreshed twenty minutes ago: an OAuth grant its
// client rotated since then is newer than the session, and must
// still end (RC-CR-01).
iat := time.Now().Add(-20 * time.Minute)
session := craftToken(t, strconv.FormatUint(uint64(user.ID), 10), "rv-change-"+strconv.FormatInt(time.Now().UnixNano(), 10), iat, time.Now().Add(time.Hour))
probe.take()
spy.reset()
started := time.Now()
env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/change-password", session, map[string]string{"current_password": "correct-horse", "password": "rv-changed-password", "password_confirmation": "rv-changed-password"})
got := one(t, probe, spy, user.ID, classes.AccessRevokedPasswordChanged)
if got.ev.Before.Before(started) || got.ev.Before.After(time.Now()) {
t.Fatalf("Before %s is not the instant of the request (started %s): grants refreshed after the session's iat %s would survive", got.ev.Before, started, iat)
}
stored := env.reload(t, user.ID).TokensValidAfter
if want := time.Unix(iat.Unix(), 0).Add(-time.Second); stored == nil || !stored.Equal(want) {
t.Fatalf("stored cutoff %v, want the session's iat second minus one (%s)", stored, want)
}
env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/fetch", session, nil)
})
t.Run("an administrator setting a password fires with the untruncated instant", func(t *testing.T) {
user := env.seedUser(t, "rv-admin-set", nil)
probe.take()
spy.reset()
const set = "rv-admin-password"
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), admin, map[string]any{"name": user.Name, "email": user.Email, "password": set, "password_confirmation": set})
got := one(t, probe, spy, user.ID, classes.AccessRevokedPasswordSetByAdmin)
wholeSecondsUntruncated(t, env, user.ID, got.ev.Before)
})
t.Run("a failing listener rolls the password reset back", func(t *testing.T) {
user := env.seedUser(t, "rv-rollback", nil)
code, err := classes.IssueResetCode(ctx, env.gdb, user)
if err != nil {
t.Fatal(err)
}
spy.reset()
probe.fail.Store(true)
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
rec := env.call(t, http.MethodPost, "/_user/api/v1/reset-password", "", map[string]string{"code": packed, "password": "rv-never-set", "password_confirmation": "rv-never-set"})
probe.fail.Store(false)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("reset with a failing listener = %d %s", rec.Code, rec.Body.String())
}
if status, _ := env.userLogin(t, user.Email, "correct-horse"); status != http.StatusOK {
t.Fatalf("the old password stopped working (%d): the reset was not rolled back", status)
}
if status, _ := env.userLogin(t, user.Email, "rv-never-set"); status == http.StatusOK {
t.Fatal("the new password works: the reset was not rolled back")
}
if spy.has(classes.SubjectGuardUser, user.ID, pact.MCPSubjectRevoked) {
t.Fatal("a rolled-back reset fired a revoked subject event")
}
})
t.Run("a banned linked user loses the backend link until unbanned", func(t *testing.T) {
user := env.seedUser(t, "rv-linked", nil)
code := env.startLink(t, env.admin(t))
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusOK {
t.Fatalf("link = %d %s", status, body)
}
links, _ := env.app.Lookup[*classes.BackendLinks]()
if _, ok, err := links.LinkedBackendUser(ctx, user.ID); err != nil || !ok {
t.Fatalf("linked before the ban = %v, %v", ok, err)
}
env.expect(t, http.StatusOK, http.MethodPost, adminAPI(adminUsersPath+"/bulk/ban"), admin, map[string]any{"ids": []uint{user.ID}})
if _, ok, err := links.LinkedBackendUser(ctx, user.ID); err != nil || ok {
t.Fatalf("linked while banned = %v, %v", ok, err)
}
env.expect(t, http.StatusOK, http.MethodPost, adminAPI(adminUsersPath+"/bulk/unban"), admin, map[string]any{"ids": []uint{user.ID}})
if _, ok, err := links.LinkedBackendUser(ctx, user.ID); err != nil || !ok {
t.Fatalf("linked after the unban = %v, %v", ok, err)
}
})
}

140
account_contributions.go Normal file
View File

@@ -0,0 +1,140 @@
package user
import (
"context"
"errors"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"gorm.io/gorm"
)
var _ pact.HasAccountContributions = (*Plugin)(nil)
// backendLinkLang prefixes the phrase keys of the account link.
const backendLinkLang = "golem15.user::lang.backend_link."
// AccountContributions adds the "Frontend account" section to the admin's
// My account page (D-04): its status names the linked frontend account,
// "link" starts a link request and answers the site URL the administrator
// opens to sign in there as the frontend user and confirm (D-05; the link is
// written only by that confirmation), and "unlink" removes the link.
func (p *Plugin) AccountContributions() []pact.AccountContribution {
return []pact.AccountContribution{{
Name: "frontend_account",
Label: backendLinkLang + "section",
Description: backendLinkLang + "section_comment",
Status: p.frontendAccountStatus,
Actions: []pact.AccountAction{
{
Name: "link",
Label: backendLinkLang + "link",
Applies: func(ctx context.Context, adminID uint) (bool, error) {
link, err := p.backendLinks().LinkFor(ctx, adminID)
return link == nil, err
},
Run: p.startFrontendLink,
},
{
Name: "unlink",
Label: backendLinkLang + "unlink",
Confirm: backendLinkLang + "unlink_confirm",
Danger: true,
Applies: func(ctx context.Context, adminID uint) (bool, error) {
link, err := p.backendLinks().LinkFor(ctx, adminID)
return link != nil, err
},
Run: p.unlinkOwnFrontendAccount,
},
},
}}
}
// backendLinks returns the published link service, or one over the app.
func (p *Plugin) backendLinks() *classes.BackendLinks {
return classes.BackendLinksFor(p.app)
}
// frontendAccountStatus answers "Linked to <email>" or "Not linked" in the
// request locale for the signed-in administrator.
func (p *Plugin) frontendAccountStatus(ctx context.Context, adminID uint) (string, error) {
link, err := p.backendLinks().LinkFor(ctx, adminID)
if err != nil {
return "", err
}
if link == nil {
return backendLinkLang + "status_unlinked", nil
}
email, err := p.frontendEmail(ctx, link.UserID)
if err != nil {
return "", err
}
const key = backendLinkLang + "status_linked"
if p.app != nil {
if tr, ok := p.app.Lookup[*phrasebook.Translator](); ok && tr != nil {
if text := tr.Get(ctx, key, map[string]string{"email": email}); text != "" && text != key {
return text, nil
}
}
}
return "Linked to " + email, nil
}
// frontendEmail reads the email of a frontend user, deactivated or not.
func (p *Plugin) frontendEmail(ctx context.Context, userID uint) (string, error) {
var db *gorm.DB
if tx, ok := cabana.TxFromContext(ctx); ok {
db = tx.Session(&gorm.Session{NewDB: true})
} else if p.app != nil {
db, _ = p.app.Lookup[*gorm.DB]()
}
if db == nil {
return "", errors.New("golem15.user: gorm handle is missing")
}
var emails []string
if err := db.WithContext(ctx).Unscoped().Model(&models.User{}).Where("id = ?", userID).Pluck("email", &emails).Error; err != nil {
return "", err
}
if len(emails) == 0 {
return "", nil
}
return emails[0], nil
}
// startFrontendLink creates a link request for the signed-in administrator
// and answers the site page that confirms it: golem15.user.frontend_url
// (else app.url), then golem15.user.backend_links.page_path (default
// /link-admin), then the code in the URL fragment. Browsers never send a
// fragment to a server, so the code stays out of access logs; the page reads
// it in the browser and posts it to /_user/api/v1/backend-link/show.
func (p *Plugin) startFrontendLink(ctx context.Context, in pact.AccountActionInput) (pact.AccountActionResult, error) {
plain, _, err := p.backendLinks().CreateLinkRequest(ctx, in.AdminID)
if err != nil {
return pact.AccountActionResult{}, err
}
return pact.AccountActionResult{
Message: backendLinkLang + "link_started",
URL: classes.FrontendURL(p.app) + classes.BackendLinkPagePath(p.app) + "#code=" + plain,
}, nil
}
// unlinkOwnFrontendAccount removes the signed-in administrator's link in
// the action's transaction.
func (p *Plugin) unlinkOwnFrontendAccount(ctx context.Context, in pact.AccountActionInput) (pact.AccountActionResult, error) {
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return pact.AccountActionResult{}, errors.New("golem15.user: unlinking needs the action's transaction")
}
links := p.backendLinks()
link, err := links.LinkFor(ctx, in.AdminID)
if err != nil {
return pact.AccountActionResult{}, err
}
if err := links.RemoveLink(ctx, tx, link); err != nil {
return pact.AccountActionResult{}, err
}
return pact.AccountActionResult{Message: backendLinkLang + "unlinked"}, nil
}

View File

@@ -81,7 +81,7 @@ func TestResetPassword(t *testing.T) {
func TestActivate(t *testing.T) { func TestActivate(t *testing.T) {
app, gdb := sessionApp(t, "0s") app, gdb := sessionApp(t, "0s")
token := loginToken(t, app, gdb, "activate-auth@example.test") token := inactiveSessionToken(t, app, gdb, "activate-auth@example.test")
rec := bearerJSON(t, controllers.Activate(app), "/_user/api/v1/activate", token, `{"code":"wrong"}`) rec := bearerJSON(t, controllers.Activate(app), "/_user/api/v1/activate", token, `{"code":"wrong"}`)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"is_activated":false`) { if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"is_activated":false`) {
t.Fatalf("activate %d %s", rec.Code, rec.Body.String()) t.Fatalf("activate %d %s", rec.Code, rec.Body.String())
@@ -97,7 +97,7 @@ func TestActivate(t *testing.T) {
func TestActivateByCode(t *testing.T) { func TestActivateByCode(t *testing.T) {
app, gdb := sessionApp(t, "0s") app, gdb := sessionApp(t, "0s")
user := insertUser(t, gdb, "activate-code@example.test", "correct-horse") user := insertInactiveUser(t, gdb, "activate-code@example.test", "correct-horse")
code, err := classes.IssueActivationCode(t.Context(), gdb, user) code, err := classes.IssueActivationCode(t.Context(), gdb, user)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

38
admin.go Normal file
View File

@@ -0,0 +1,38 @@
package user
import (
"embed"
"io/fs"
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/pact"
)
// adminFS holds the admin YAML and partials, file by file: the controllers
// directory also holds files that are not admin assets.
//
//go:embed controllers/users/config_list.yaml controllers/users/config_form.yaml controllers/users/config_filter.yaml controllers/users/_hint.htm models/user/fields.yaml models/user/columns.yaml
//go:embed controllers/usergroups/config_list.yaml controllers/usergroups/config_form.yaml models/usergroup/fields.yaml models/usergroup/columns.yaml
//go:embed controllers/organisations/config_list.yaml controllers/organisations/config_form.yaml controllers/organisations/config_relation.yaml models/organisation/fields.yaml models/organisation/columns.yaml
var adminFS embed.FS
func (p *Plugin) AdminFS() fs.FS { return adminFS }
// AdminControllers hands the controllers a lazy accessor of the booted app,
// so they read the database handle and the config at request time.
func (p *Plugin) AdminControllers() []pact.AdminController {
return controllers.AdminControllers(func() *backpack.App {
if p == nil {
return nil
}
return p.app
})
}
var (
_ pact.AdminAssets = (*Plugin)(nil)
_ pact.HasAdminControllers = (*Plugin)(nil)
_ pact.HasPermissions = (*Plugin)(nil)
_ pact.HasNavigation = (*Plugin)(nil)
)

259
admin_groups_edge_test.go Normal file
View File

@@ -0,0 +1,259 @@
package user
import (
"context"
"net/http"
"reflect"
"testing"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/pact"
)
// TestAdminGroupsControllerGuards drives the User Groups controller directly
// on the inputs the HTTP tests cannot produce. A guard that cannot read what
// it needs answers a plain error (the opaque 500), never a pass.
func TestAdminGroupsControllerGuards(t *testing.T) {
ctx := context.Background()
const id = "golem15.user.usergroups"
notGroup := &models.User{}
var nilGroup *models.UserGroup
admin, plain := "admin", "plain-code"
damaged := "{not json"
broken, _ := brokenApp(t)
env := newAdminEnv(t)
sets := map[string]adminControllerSet{
"no accessor": adminControllersOn(nil),
"not booted": adminControllersOn(func() *backpack.App { return nil }),
"no database": adminControllersOn(func() *backpack.App { return bareApp(t) }),
"a failing handle": adminControllersOn(func() *backpack.App { return broken }),
"the live database": adminControllersOn(func() *backpack.App { return env.app }),
}
for name, set := range sets {
t.Run(name, func(t *testing.T) {
ctl := set[id]
for _, record := range []any{notGroup, nilGroup, nil} {
wantPlainError(t, "FormBeforeCreate", ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, record))
wantPlainError(t, "FormBeforeUpdate", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, record))
wantPlainError(t, "FormBeforeDelete", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, record))
wantPlainError(t, "FormAfterDelete", ctl.(pact.FormAfterDelete).FormAfterDelete(ctx, record))
editor := ctl.(cabana.PermissionEditorProvider)
_, err := editor.AdminPermissionValues(ctx, "permissions", record)
wantPlainError(t, "AdminPermissionValues", err)
wantPlainError(t, "AdminSetPermissionValues", editor.AdminSetPermissionValues(ctx, "permissions", record, nil))
}
editor := ctl.(cabana.PermissionEditorProvider)
if _, err := editor.AdminPermissionOptions(ctx, "name"); err == nil {
t.Fatal("permission options for another field")
}
if _, err := editor.AdminPermissionValues(ctx, "name", &models.UserGroup{}); err == nil {
t.Fatal("permission values for another field")
}
if err := editor.AdminSetPermissionValues(ctx, "name", &models.UserGroup{}, nil); err == nil {
t.Fatal("permission write for another field")
}
// A stored value that is not a JSON object is an error, never an
// empty set an edit would then save over it.
_, err := editor.AdminPermissionValues(ctx, "permissions", &models.UserGroup{Permissions: &damaged})
wantPlainError(t, "damaged stored permissions", err)
if values, err := editor.AdminPermissionValues(ctx, "permissions", &models.UserGroup{}); err != nil || len(values) != 0 {
t.Fatalf("no stored permissions = %v %v", values, err)
}
if ctl.(pact.ListExtendQuery).ListExtendQuery(ctx, nil) != nil {
t.Fatal("ListExtendQuery invented a handle")
}
wantPlainError(t, "FormAfterDelete without a transaction", ctl.(pact.FormAfterDelete).FormAfterDelete(ctx, &models.UserGroup{ID: 1}))
// Without a principal the privileged code is refused on every
// path, with the screen's 403 (D-06).
for what, err := range map[string]error{
"create": ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, &models.UserGroup{Name: "Admins", Code: &admin}),
"delete": ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, &models.UserGroup{ID: 1, Name: "Admins", Code: &admin}),
} {
forbidden, ok := err.(*cabana.ForbiddenError)
if !ok || forbidden.Message != "golem15.user::lang.groups.privileged_forbidden" || forbidden.Details["code"] == nil {
t.Fatalf("%s of a privileged group without a principal: %v", what, err)
}
}
// With the extra permission, and for a superuser, it passes.
for _, principal := range []*bouncer.Principal{
{PermissionGrants: map[string]bool{permManagePrivileged: true}},
{IsSuperuser: true},
} {
as := bouncer.WithUser(ctx, principal)
if err := ctl.(pact.FormBeforeCreate).FormBeforeCreate(as, &models.UserGroup{Name: "Admins", Code: &admin}); err != nil {
t.Fatalf("create for %+v: %v", principal, err)
}
if err := ctl.(pact.FormBeforeDelete).FormBeforeDelete(as, &models.UserGroup{ID: 1, Code: &admin}); err != nil {
t.Fatalf("delete for %+v: %v", principal, err)
}
}
// An ordinary code and a group without a code need nothing extra.
if err := ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, &models.UserGroup{Name: "Plain", Code: &plain}); err != nil {
t.Fatal(err)
}
if err := ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, &models.UserGroup{ID: 1}); err != nil {
t.Fatal(err)
}
// An update reads the stored code first: with no database, a
// failing one or an unknown group it is an error, not a pass.
wantPlainError(t, "update of an unreadable group", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, &models.UserGroup{ID: 987654321, Name: "Gone", Code: &plain}))
if name != "the live database" {
_, err := editor.AdminPermissionOptions(ctx, "permissions")
wantPlainError(t, "AdminPermissionOptions", err)
}
})
}
}
// TestAdminGroupsEdge covers the remaining branches of the User Groups
// screen through the admin API.
func TestAdminGroupsEdge(t *testing.T) {
stamp := adminStamp()
privilegedCode := "edgepriv-" + stamp
env := newAdminEnv(t, func(cfg *compass.Config) {
if err := cfg.Set("golem15.user.privileged_groups", []string{"admin", "guest", privilegedCode}); err != nil {
t.Fatal(err)
}
})
token := env.admin(t, permAccessGroups)
manager := env.admin(t, permAccessGroups, permManagePrivileged)
// A group update that keeps a privileged code needs nothing extra: the
// name and description change, the code stays.
privileged := env.seedGroup(t, "Edge privileged "+stamp, privilegedCode)
env.expect(t, http.StatusOK, http.MethodPut, groupPath(privileged.ID), token, map[string]any{"name": "Edge renamed " + stamp, "code": privilegedCode, "description": "kept"})
if got := env.group(t, privileged.ID); got.Name != "Edge renamed "+stamp || got.Code == nil || *got.Code != privilegedCode || got.Description == nil || *got.Description != "kept" {
t.Fatalf("group after a name-only update = %+v", got)
}
// The same administrator may not move the code away from, or onto, a
// privileged one; the manager may.
ordinary := env.seedGroup(t, "Edge ordinary "+stamp, "edgeord-"+stamp)
rec := env.expect(t, http.StatusForbidden, http.MethodPut, groupPath(privileged.ID), token, map[string]any{"code": "edgefree-" + stamp})
if message := adminDecode(t, rec).Error.Message; message != privilegedGroupCodeForbidden {
t.Fatalf("403 message = %q", message)
}
if got := env.group(t, privileged.ID); *got.Code != privilegedCode {
t.Fatalf("a refused re-code changed the code to %q", *got.Code)
}
env.expect(t, http.StatusOK, http.MethodPut, groupPath(ordinary.ID), manager, map[string]any{"name": "Edge ordinary " + stamp + " b"})
// Validation answers before the guard: a create that would be refused
// with 403 answers 422 when its body is also invalid, and saves nothing.
rec = env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminGroupsPath), token, map[string]any{"name": "Edge duplicate " + stamp, "code": privilegedCode})
if details := adminDecode(t, rec).Error.Details; len(details["code"]) == 0 {
t.Fatalf("422 details = %v", details)
}
var count int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM user_groups WHERE code = ?`, privilegedCode).Scan(&count).Error; err != nil || count != 1 {
t.Fatalf("groups with the privileged code = %d err = %v", count, err)
}
// A code with characters outside letters, digits, dash and underscore is
// a 422 on the field, in the request's language.
for _, code := range []string{"with space", "dot.ted", "sl/ash", "ąę"} {
rec := env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminGroupsPath), token, map[string]any{"name": "Edge bad code " + stamp, "code": code})
details := adminDecode(t, rec).Error.Details
if got := details["code"]; len(got) != 1 || got[0] != "The code may only contain letters, numbers, dashes and underscores." {
t.Fatalf("code %q: details = %v", code, details)
}
}
// An application protects a seeded group by naming its code in
// golem15.user.privileged_groups: the guest group then cannot be deleted
// or re-coded with golem15.users.access_groups alone.
var guestID uint
if err := env.gdb.Raw(`SELECT id FROM user_groups WHERE code = 'guest' ORDER BY id LIMIT 1`).Scan(&guestID).Error; err != nil {
t.Fatal(err)
}
if guestID == 0 {
guestID = env.seedGroup(t, "Guest", "guest").ID
}
env.expect(t, http.StatusForbidden, http.MethodDelete, groupPath(guestID), token, nil)
env.expect(t, http.StatusForbidden, http.MethodPut, groupPath(guestID), token, map[string]any{"code": "visitor-" + stamp})
if got := env.group(t, guestID); got == nil || got.Code == nil || *got.Code != "guest" {
t.Fatalf("the protected guest group = %+v", got)
}
// Search and sort on the list.
for _, name := range []string{"b", "a", "c"} {
env.seedGroup(t, "Sort "+stamp+" "+name, "sort-"+stamp+"-"+name)
}
order := func(query string) []string {
var rows []map[string]any
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminGroupsPath)+"?search=Sort%20"+stamp+"&"+query, token, nil), &rows)
codes := []string{}
for _, row := range rows {
code, _ := row["code"].(string)
codes = append(codes, code[len(code)-1:])
}
return codes
}
if got := order("sort=name&dir=asc"); !reflect.DeepEqual(got, []string{"a", "b", "c"}) {
t.Fatalf("name asc = %v", got)
}
if got := order("sort=code&dir=desc"); !reflect.DeepEqual(got, []string{"c", "b", "a"}) {
t.Fatalf("code desc = %v", got)
}
for _, query := range []string{"sort=permissions", "sort=description", "filter[code]=x"} {
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminGroupsPath)+"?"+query, token, nil)
}
// A group whose stored permissions are not a JSON object cannot be
// opened: the answer is the opaque 500, and the row is left as it is.
broken := env.seedGroup(t, "Edge damaged "+stamp, "edgedmg-"+stamp)
if err := env.gdb.Exec(`UPDATE user_groups SET permissions = '{"a":' WHERE id = ?`, broken.ID).Error; err != nil {
t.Fatal(err)
}
rec = env.expect(t, http.StatusInternalServerError, http.MethodGet, groupPath(broken.ID), token, nil)
if message := adminDecode(t, rec).Error.Message; message != "Server error" {
t.Fatalf("500 message = %q", message)
}
if got := env.group(t, broken.ID); got.Permissions == nil || *got.Permissions != `{"a":` {
t.Fatalf("damaged permissions after the read = %v", got.Permissions)
}
}
// TestAdminGroupsLegacyBooleanPermissions pins a known difference between
// the two readers of user_groups.permissions (12.1-SECURITY-REVIEW.md, open
// item 5): the API-token grants count a stored true as granted, the admin
// editor and the merged-permission resolver read only numbers. A group
// stored with booleans therefore shows unchecked, and an edit through the
// editor does not keep the boolean. The change is towards fewer grants,
// never more.
func TestAdminGroupsLegacyBooleanPermissions(t *testing.T) {
env := newAdminEnv(t)
token := env.admin(t, permAccessGroups)
stamp := adminStamp()
legacy, offered := "legacy.bool."+stamp, "offered.bool."+stamp
if err := env.gdb.Exec(`INSERT INTO golem15_user_frontend_permissions (code, label, tab) VALUES (?, 'Legacy', 'Edge'), (?, 'Offered', 'Edge')`, legacy, offered).Error; err != nil {
t.Fatal(err)
}
group := env.seedGroup(t, "Edge boolean "+stamp, "edgebool-"+stamp)
if err := env.gdb.Exec(`UPDATE user_groups SET permissions = ? WHERE id = ?`, `{"`+legacy+`":true}`, group.ID).Error; err != nil {
t.Fatal(err)
}
var record struct {
Permissions map[string]int `json:"permissions"`
}
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, groupPath(group.ID), token, nil), &record)
if len(record.Permissions) != 0 {
t.Fatalf("a boolean value is shown as %v", record.Permissions)
}
// A save that does not carry the field leaves the stored value alone.
env.expect(t, http.StatusOK, http.MethodPut, groupPath(group.ID), token, map[string]any{"description": "untouched"})
if got := env.group(t, group.ID); got.Permissions == nil || *got.Permissions != `{"`+legacy+`":true}` {
t.Fatalf("permissions after a save without the field = %v", got.Permissions)
}
// A save that carries the field writes numbers only.
env.expect(t, http.StatusOK, http.MethodPut, groupPath(group.ID), token, map[string]any{"permissions": map[string]int{offered: 1}})
if got := env.group(t, group.ID); got.Permissions == nil || *got.Permissions != `{"`+offered+`":1}` {
t.Fatalf("permissions after an edit = %v", got.Permissions)
}
}

405
admin_groups_test.go Normal file
View File

@@ -0,0 +1,405 @@
package user
import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"testing"
"git.golem15.com/golem15/sm-user-plugin/models"
)
const (
// adminGroupsPath is the User Groups controller under the admin API.
adminGroupsPath = "/golem15/user/usergroups"
permAccessGroups = "golem15.users.access_groups"
privilegedGroupCodeForbidden = "You do not have permission to create, re-code or delete a privileged group. Nothing was saved."
)
// groupPath is the admin API path of one user group.
func groupPath(id uint) string {
return adminAPI(adminGroupsPath) + "/" + strconv.FormatUint(uint64(id), 10)
}
// storedGroup is a user_groups row as the database holds it.
type storedGroup struct {
Name string
Code *string
Description *string
Permissions *string
}
// group reads a user_groups row; nil when it is gone.
func (e *adminEnv) group(t *testing.T, id uint) *storedGroup {
t.Helper()
var rows []storedGroup
if err := e.gdb.Raw(`SELECT name, code, description, permissions FROM user_groups WHERE id = ?`, id).Scan(&rows).Error; err != nil {
t.Fatal(err)
}
if len(rows) == 0 {
return nil
}
return &rows[0]
}
// sideMenu returns the side item codes of the navigation item `user` as the
// administrator sees them; nil when the item is not shown.
func (e *adminEnv) sideMenu(t *testing.T, token string) []string {
t.Helper()
var nav []struct {
Code string `json:"code"`
SideMenu []struct {
Code string `json:"code"`
Controller string `json:"controller"`
} `json:"sideMenu"`
}
adminInto(t, e.expect(t, http.StatusOK, http.MethodGet, adminAPI("/navigation"), token, nil), &nav)
for _, item := range nav {
if item.Code != "user" {
continue
}
codes := []string{}
for _, side := range item.SideMenu {
codes = append(codes, side.Code+"="+side.Controller)
}
return codes
}
return nil
}
// TestAdminGroups covers the User Groups screen (D-06 ordinary path, D-15,
// D-16, D-24, D-29): its permission, the list with the member count, the
// form with the code rules and the checkbox permission editor, and the
// delete with its pivot cleanup.
func TestAdminGroups(t *testing.T) {
env := newAdminEnv(t)
usersOnly := env.admin(t, permAccessUsers)
token := env.admin(t, permAccessGroups)
stamp := adminStamp()
// The screen needs golem15.users.access_groups: the users permission
// alone opens nothing here and does not show the side item.
for _, path := range []string{adminAPI(adminGroupsPath), adminAPI(adminGroupsPath + "/schema/list"), adminAPI(adminGroupsPath + "/schema/form")} {
rec := env.expect(t, http.StatusForbidden, http.MethodGet, path, usersOnly, nil)
if code := adminDecode(t, rec).Error.Code; code != "forbidden" {
t.Fatalf("%s code = %q", path, code)
}
}
env.expect(t, http.StatusForbidden, http.MethodPost, adminAPI(adminGroupsPath), usersOnly, map[string]any{"name": "Nope " + stamp, "code": "nope-" + stamp})
if got := env.sideMenu(t, usersOnly); !reflect.DeepEqual(got, []string{"users=golem15.user.users", "organisations=golem15.user.organisations"}) {
t.Fatalf("side menu with the users permission = %v", got)
}
if got := env.sideMenu(t, token); !reflect.DeepEqual(got, []string{"usergroups=golem15.user.usergroups"}) {
t.Fatalf("side menu with the groups permission = %v", got)
}
// The users screen stays closed to the groups permission.
env.expect(t, http.StatusForbidden, http.MethodGet, adminAPI(adminUsersPath), token, nil)
// The list schema: Name, Code, Created and Users; rows open the update
// form; no checkboxes, no bulk actions, no delete in the toolbar.
var schema struct {
RecordURL string `json:"recordUrl"`
ShowCheckboxes bool `json:"showCheckboxes"`
Columns []struct {
Key string `json:"key"`
Label string `json:"label"`
Invisible bool `json:"invisible"`
Sortable bool `json:"sortable"`
Type string `json:"type"`
} `json:"columns"`
ToolbarButtons []string `json:"toolbarButtons"`
BulkActions []json.RawMessage `json:"bulkActions"`
Messages map[string]map[string]string `json:"messages"`
}
rawSchema := env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminGroupsPath+"/schema/list"), token, nil)
adminInto(t, rawSchema, &schema)
var visible []string
for _, column := range schema.Columns {
if column.Invisible {
continue
}
visible = append(visible, column.Key+":"+column.Label)
if column.Key == "users_count" && column.Sortable {
t.Fatal("users_count is sortable")
}
}
if want := []string{"name:Name", "code:Code", "created_at:Created", "users_count:Users"}; !reflect.DeepEqual(visible, want) {
t.Fatalf("visible columns = %v, want %v", visible, want)
}
if schema.RecordURL != "golem15/user/usergroups/update/:id" || schema.ShowCheckboxes || len(schema.BulkActions) != 0 ||
!reflect.DeepEqual(schema.ToolbarButtons, []string{"create"}) {
t.Fatalf("list schema = %s", rawSchema.Body.String())
}
if got := schema.Messages["empty"]["other"]; got != "No user groups yet. Create the first one with New Group." {
t.Fatalf("empty message = %q", got)
}
if got := schema.Messages["create"]["other"]; got != "New Group" {
t.Fatalf("create message = %q", got)
}
// Without checkboxes there is no bulk delete on this screen.
if rec := env.call(t, http.MethodPost, adminAPI(adminGroupsPath+"/bulk-delete"), token, map[string]any{"ids": []uint{1}}); rec.Code == http.StatusOK {
t.Fatalf("bulk delete of groups = %d %s", rec.Code, rec.Body.String())
}
// The list carries the member count from its own query: 0 for a group
// without members (a number, not an absent value), the count otherwise.
empty := env.seedGroup(t, "Empty "+stamp, "empty-"+stamp)
pair := env.seedGroup(t, "Pair "+stamp, "pair-"+stamp)
single := env.seedGroup(t, "Single "+stamp, "single-"+stamp)
alice := env.seedUser(t, "alice", nil)
bob := env.seedUser(t, "bob", nil)
env.join(t, alice, pair, single)
env.join(t, bob, pair)
list := func(query string) (map[uint]map[string]any, int) {
t.Helper()
rec := env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminGroupsPath)+"?"+query, token, nil)
var rows []map[string]any
answer := adminInto(t, rec, &rows)
var meta struct {
Total int `json:"total"`
}
if err := json.Unmarshal(answer.Meta, &meta); err != nil {
t.Fatal(err)
}
out := map[uint]map[string]any{}
for _, row := range rows {
out[uint(row["id"].(float64))] = row
}
return out, meta.Total
}
rows, total := list("search=" + stamp)
if total != 3 || len(rows) != 3 {
t.Fatalf("list total = %d rows = %d", total, len(rows))
}
for id, want := range map[uint]float64{empty.ID: 0, pair.ID: 2, single.ID: 1} {
got, ok := rows[id]["users_count"].(float64)
if !ok || got != want {
t.Fatalf("users_count of %d = %v, want %v", id, rows[id]["users_count"], want)
}
}
if rows[pair.ID]["name"] != "Pair "+stamp || rows[pair.ID]["code"] != "pair-"+stamp {
t.Fatalf("list row = %v", rows[pair.ID])
}
// Paging counts groups, not memberships.
if _, total = list("search=" + stamp + "&per_page=20&page=1&sort=name&dir=asc"); total != 3 {
t.Fatalf("sorted list total = %d", total)
}
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminGroupsPath)+"?sort=users_count", token, nil)
// The form: name, code (preset from name), description and the checkbox
// permission editor on the Permissions tab.
read, write := "wiki."+stamp+".read", "wiki."+stamp+".write"
if err := env.gdb.Exec(`INSERT INTO golem15_user_frontend_permissions (code, label, tab) VALUES (?, 'Read', ?), (?, 'Write', ?)`,
read, "Wiki "+stamp, write, "Wiki "+stamp).Error; err != nil {
t.Fatal(err)
}
var form struct {
Fields []struct {
Name string `json:"name"`
Type string `json:"type"`
Mode string `json:"mode"`
Tab string `json:"tab"`
Preset *struct {
Field string `json:"field"`
} `json:"preset"`
Options []struct {
Code string `json:"code"`
} `json:"permissionOptions"`
} `json:"fields"`
Preview json.RawMessage `json:"preview"`
}
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminGroupsPath+"/schema/form"), token, nil), &form)
var names []string
for _, field := range form.Fields {
names = append(names, field.Name+":"+field.Type)
switch field.Name {
case "code":
if field.Preset == nil || field.Preset.Field != "name" {
t.Fatalf("code preset = %+v", field.Preset)
}
case "permissions":
offered := 0
for _, option := range field.Options {
if option.Code == read || option.Code == write {
offered++
}
}
if field.Mode != "checkbox" || field.Tab != "Permissions" || offered != 2 {
t.Fatalf("permissions field = %+v", field)
}
}
}
if want := []string{"name:text", "code:text", "description:textarea", "permissions:permissioneditor"}; !reflect.DeepEqual(names, want) {
t.Fatalf("form fields = %v, want %v", names, want)
}
if len(form.Preview) != 0 && string(form.Preview) != "null" {
t.Fatalf("the group form has a preview: %s", form.Preview)
}
// Create: the code needs the PHP format and must be unique; the name
// needs three characters.
create := func(status int, body map[string]any) *httptest.ResponseRecorder {
t.Helper()
return env.expect(t, status, http.MethodPost, adminAPI(adminGroupsPath), token, body)
}
code := "editors-" + stamp
for field, body := range map[string]map[string]any{
"code": {"name": "Editors " + stamp, "code": "bad code " + stamp},
"name": {"name": "ab", "code": "short-" + stamp},
} {
rec := create(http.StatusUnprocessableEntity, body)
if details := adminDecode(t, rec).Error.Details; len(details[field]) == 0 {
t.Fatalf("create refusal has no detail on %s: %s", field, rec.Body.String())
}
}
for _, bad := range []string{"dot." + stamp, "ąę" + stamp, "semi;" + stamp} {
rec := create(http.StatusUnprocessableEntity, map[string]any{"name": "Editors " + stamp, "code": bad})
if details := adminDecode(t, rec).Error.Details; len(details["code"]) != 1 || details["code"][0] != "The code may only contain letters, numbers, dashes and underscores." {
t.Fatalf("code refusal for %q = %s", bad, rec.Body.String())
}
}
create(http.StatusUnprocessableEntity, map[string]any{"name": "No code " + stamp})
var before int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM user_groups WHERE name LIKE ?`, "%"+stamp).Scan(&before).Error; err != nil || before != 3 {
t.Fatalf("refused creates left rows: %d (%v)", before, err)
}
id := createdID(t, create(http.StatusCreated, map[string]any{"name": "Editors " + stamp, "code": code, "description": "May edit"}))
if got := env.group(t, id); got == nil || got.Name != "Editors "+stamp || got.Code == nil || *got.Code != code ||
got.Description == nil || *got.Description != "May edit" || got.Permissions != nil {
t.Fatalf("created group = %+v", got)
}
rec := create(http.StatusUnprocessableEntity, map[string]any{"name": "Editors again " + stamp, "code": code})
if details := adminDecode(t, rec).Error.Details; len(details["code"]) == 0 {
t.Fatalf("duplicate code refusal = %s", rec.Body.String())
}
// Update: name and description; the group's own code sent back is not a
// duplicate; a bad code is refused and changes nothing.
update := func(status int, body map[string]any) *httptest.ResponseRecorder {
t.Helper()
return env.expect(t, status, http.MethodPut, groupPath(id), token, body)
}
update(http.StatusOK, map[string]any{"name": "Editors renamed " + stamp, "code": code, "description": "Edits the wiki"})
if got := env.group(t, id); got.Name != "Editors renamed "+stamp || *got.Code != code || *got.Description != "Edits the wiki" {
t.Fatalf("updated group = %+v", got)
}
update(http.StatusUnprocessableEntity, map[string]any{"name": "Broken " + stamp, "code": "bad code"})
update(http.StatusUnprocessableEntity, map[string]any{"name": "Broken " + stamp, "code": "pair-" + stamp})
if got := env.group(t, id); got.Name != "Editors renamed "+stamp || *got.Code != code {
t.Fatalf("a refused update changed the group: %+v", got)
}
// An ordinary code changes freely.
code = "wiki-editors-" + stamp
update(http.StatusOK, map[string]any{"name": "Editors renamed " + stamp, "code": code})
if got := env.group(t, id); *got.Code != code {
t.Fatalf("code after the change = %q", *got.Code)
}
base := map[string]any{"name": "Editors renamed " + stamp, "code": code}
save := func(status int, permissions any) *httptest.ResponseRecorder {
t.Helper()
body := map[string]any{"permissions": permissions}
for key, value := range base {
body[key] = value
}
return update(status, body)
}
storedPermissions := func() map[string]int {
t.Helper()
got := env.group(t, id)
if got.Permissions == nil {
return nil
}
var decoded map[string]int
if err := json.Unmarshal([]byte(*got.Permissions), &decoded); err != nil {
t.Fatalf("stored permissions %q: %v", *got.Permissions, err)
}
return decoded
}
// Checkbox mode stores a JSON object of code to 1.
save(http.StatusOK, map[string]int{read: 1, write: 1})
if got := storedPermissions(); !reflect.DeepEqual(got, map[string]int{read: 1, write: 1}) {
t.Fatalf("stored permissions = %v", got)
}
var record struct {
Permissions map[string]int `json:"permissions"`
}
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, groupPath(id), token, nil), &record)
if !reflect.DeepEqual(record.Permissions, map[string]int{read: 1, write: 1}) {
t.Fatalf("record permissions = %v", record.Permissions)
}
// A deny has no place in checkbox mode; neither has an unknown code.
for _, bad := range []any{map[string]int{read: -1}, map[string]int{read: 2}, map[string]int{"unknown." + stamp: 1}, "all"} {
rec := save(http.StatusUnprocessableEntity, bad)
if details := adminDecode(t, rec).Error.Details; len(details["permissions"]) == 0 {
t.Fatalf("permission refusal of %v = %s", bad, rec.Body.String())
}
}
if got := storedPermissions(); !reflect.DeepEqual(got, map[string]int{read: 1, write: 1}) {
t.Fatalf("a refused save changed the permissions: %v", got)
}
// A save without the field leaves them alone; unchecking removes the
// entry; an empty object stores NULL.
update(http.StatusOK, base)
if got := storedPermissions(); len(got) != 2 {
t.Fatalf("a save without the field changed the permissions: %v", got)
}
save(http.StatusOK, map[string]int{read: 1, write: 0})
if got := storedPermissions(); !reflect.DeepEqual(got, map[string]int{read: 1}) {
t.Fatalf("permissions after unchecking = %v", got)
}
save(http.StatusOK, map[string]int{})
if got := env.group(t, id); got.Permissions != nil {
t.Fatalf("cleared permissions = %q", *got.Permissions)
}
// A stored code that is no longer offered survives an edit, and a member
// of the group holds what the editor stored.
legacy := "legacy." + stamp
if err := env.gdb.Exec(`UPDATE user_groups SET permissions = ? WHERE id = ?`, `{"`+legacy+`":1}`, id).Error; err != nil {
t.Fatal(err)
}
save(http.StatusOK, map[string]int{write: 1})
if got := storedPermissions(); !reflect.DeepEqual(got, map[string]int{legacy: 1, write: 1}) {
t.Fatalf("permissions after an edit over a legacy code = %v", got)
}
// The screen cannot write a membership or the count.
created := &models.UserGroup{ID: id}
env.join(t, alice, created)
update(http.StatusOK, map[string]any{"name": base["name"], "code": code, "users_count": 99, "users": []uint{bob.ID}, "Users": []uint{bob.ID}})
if got := env.groupIDs(t, bob.ID); !reflect.DeepEqual(got, sortedIDs(pair)) {
t.Fatalf("a group save changed bob's memberships: %v", got)
}
if rows, _ = list("search=" + stamp); rows[id]["users_count"].(float64) != 1 {
t.Fatalf("users_count after a save that sent one = %v", rows[id]["users_count"])
}
// Delete (D-29): the standard form delete removes the group and its
// memberships in one transaction; the members and their other
// memberships stay.
rec = env.expect(t, http.StatusOK, http.MethodDelete, groupPath(pair.ID), token, nil)
if env.group(t, pair.ID) != nil {
t.Fatalf("the group survived its delete: %s", rec.Body.String())
}
var left int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM users_groups WHERE user_group_id = ?`, pair.ID).Scan(&left).Error; err != nil || left != 0 {
t.Fatalf("memberships of the deleted group = %d (%v)", left, err)
}
if env.reload(t, alice.ID) == nil || env.reload(t, bob.ID) == nil {
t.Fatal("a group delete removed a member")
}
if got := env.groupIDs(t, alice.ID); !reflect.DeepEqual(got, sortedIDs(single, created)) {
t.Fatalf("alice's memberships after the delete = %v", got)
}
if got := env.groupIDs(t, bob.ID); len(got) != 0 {
t.Fatalf("bob's memberships after the delete = %v", got)
}
env.expect(t, http.StatusNotFound, http.MethodGet, groupPath(pair.ID), token, nil)
if rows, total = list("search=" + stamp); total != 3 || rows[pair.ID] != nil {
t.Fatalf("list after the delete: total %d", total)
}
}

714
admin_harness_test.go Normal file
View File

@@ -0,0 +1,714 @@
package user
import (
"bytes"
"context"
"crypto/rand"
"database/sql"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log/slog"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/party"
"git.golem15.com/golem15/summercms/modules/surf"
"gocloud.dev/blob"
"gocloud.dev/blob/memblob"
"gorm.io/gorm"
)
// The admin test harness boots the plugin the way an application does
// (party.Activate, lagoon.Migrate, surf.Assemble) with the admin API mounted,
// on its own database in the session container, and mints backend
// administrators with a chosen permission set.
//
// env := newAdminEnv(t)
// token := env.admin(t, permAccessUsers)
// rec := env.call(t, http.MethodGet, adminAPI("/golem15/user/users"), token, nil)
const (
// adminUsersPath is the Users controller under the admin API.
adminUsersPath = "/golem15/user/users"
permAccessUsers = "golem15.users.access_users"
permManagePrivileged = "golem15.users.manage_privileged_groups"
)
var (
adminHarnessOnce sync.Once
adminHarnessGDB *gorm.DB
adminHarnessSQL *sql.DB
adminHarnessErr error
// adminSeq makes logins, emails and codes unique across the tests that
// share the harness database.
adminSeq atomic.Uint64
)
// adminEnv is one booted application: the assembled handler, its app, the
// shared harness database and the in-memory blob bucket.
type adminEnv struct {
h http.Handler
app *backpack.App
gdb *gorm.DB
bucket *blob.Bucket
mail *mailCapture
}
// adminAPI builds a path under the admin API prefix.
func adminAPI(rel string) string {
return cabana.DefaultAdminPrefix + "/api/v1" + rel
}
// adminStamp returns a token unique within the test binary, for emails,
// logins and group codes.
func adminStamp() string {
return fmt.Sprintf("%d%d", time.Now().UnixNano()%1_000_000_000, adminSeq.Add(1))
}
// adminHarnessDB opens (once) the harness database: a second database in the
// session container, migrated by lagoon.Migrate on the first boot.
func adminHarnessDB(t *testing.T) (*gorm.DB, *sql.DB) {
t.Helper()
if testing.Short() {
t.Skip("requires testcontainers postgres")
}
_, admin := sessionDB(t)
adminHarnessOnce.Do(func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
const name = "user_admin"
if _, err := admin.ExecContext(ctx, `CREATE DATABASE `+name+` TEMPLATE template0 ENCODING 'UTF8' LOCALE_PROVIDER icu ICU_LOCALE 'pl-PL'`); err != nil {
adminHarnessErr = err
return
}
u, err := url.Parse(sessionDSN)
if err != nil {
adminHarnessErr = err
return
}
u.Path = "/" + name
db, err := sql.Open("pgx", u.String())
if err != nil {
adminHarnessErr = err
return
}
gdb, err := lagoon.Use(ctx, db)
if err != nil {
adminHarnessErr = err
return
}
adminHarnessSQL, adminHarnessGDB = db, gdb
})
if adminHarnessErr != nil {
t.Fatal(adminHarnessErr)
}
return adminHarnessGDB, adminHarnessSQL
}
// adminEnvConfig is the config every harness boot starts from: the plugin's
// JWT secret, the admin secret, body limits and the log mail driver.
func adminEnvConfig(t *testing.T) *compass.Config {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: user-admin\nlocale: en\nfallback_locale: en\nurl: https://app.example.test\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := compass.Open(compass.Options{
Dir: dir,
Environ: []string{
"SUMMER_ENV=development",
"SUMMER_GOLEM15__USER__JWT__SECRET=" + sessionSecret,
"SUMMER_ADMIN__JWT__SECRET=" + adminHarnessSecret,
},
})
if err != nil {
t.Fatal(err)
}
for key, value := range map[string]any{
"http.body_limits.default_bytes": 1048576,
"http.body_limits.upload_bytes": 8388608,
// The log driver renders every mail and hands it to the app logger,
// which mailCapture reads.
"mail.driver": "log",
"mail.from": "noreply@example.test",
} {
if err := cfg.Set(key, value); err != nil {
t.Fatal(err)
}
}
return cfg
}
// newAdminEnv boots the plugin alone with the admin API mounted. configure
// functions adjust the config before the plugin is activated.
func newAdminEnv(t *testing.T, configure ...func(*compass.Config)) *adminEnv {
t.Helper()
return newAdminEnvWith(t, nil, configure...)
}
// newAdminEnvWith is newAdminEnv with more registered plugins activated
// after golem15.user, by ID.
func newAdminEnvWith(t *testing.T, extra []string, configure ...func(*compass.Config)) *adminEnv {
t.Helper()
gdb, sqlDB := adminHarnessDB(t)
app := backpack.New(adminEnvConfig(t))
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
t.Fatal(err)
}
mail := &mailCapture{next: slog.Default().Handler()}
if err := app.Publish(slog.New(mail)); err != nil {
t.Fatal(err)
}
bucket := memblob.OpenBucket(nil)
t.Cleanup(func() { _ = bucket.Close() })
if err := attach.Publish(app, bucket); err != nil {
t.Fatal(err)
}
// The registered plugin value is shared by every boot in this binary;
// its blacklist sweep is started at most once and is harmless here.
plugins, err := party.Activate(app, append([]string{"golem15.user"}, extra...))
if err != nil {
t.Fatal(err)
}
// Overrides go in after the plugin's own config defaults were merged.
for _, fn := range configure {
fn(app.Config)
}
if err := lagoon.Migrate(gdb, plugins); err != nil {
t.Fatal(err)
}
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
return &adminEnv{h: h, app: app, gdb: gdb, bucket: bucket, mail: mail}
}
// newServeOrderEnv boots the plugin the way surf's serve command does after
// the generated main's party.Activate: every Boot runs with no database
// published, then lagoon.Publish, the uploads bucket and the router.
// beforePublish, when set, runs between Activate and Publish. Migrate is
// there only because the shared harness database may not be migrated yet.
func newServeOrderEnv(t *testing.T, beforePublish func(*backpack.App)) *adminEnv {
t.Helper()
gdb, sqlDB := adminHarnessDB(t)
app := backpack.New(adminEnvConfig(t))
mail := &mailCapture{next: slog.Default().Handler()}
if err := app.Publish(slog.New(mail)); err != nil {
t.Fatal(err)
}
plugins, err := party.Activate(app, []string{"golem15.user"})
if err != nil {
t.Fatal(err)
}
if beforePublish != nil {
beforePublish(app)
}
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
t.Fatal(err)
}
bucket := memblob.OpenBucket(nil)
t.Cleanup(func() { _ = bucket.Close() })
if err := attach.Publish(app, bucket); err != nil {
t.Fatal(err)
}
if err := lagoon.Migrate(gdb, plugins); err != nil {
t.Fatal(err)
}
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
return &adminEnv{h: h, app: app, gdb: gdb, bucket: bucket, mail: mail}
}
// admin inserts a backend role holding exactly permissions and a backend
// user in it, logs the user in and returns the bearer token. No permission
// at all gives an administrator who may sign in and open nothing.
func (e *adminEnv) admin(t *testing.T, permissions ...string) string {
t.Helper()
stamp := adminStamp()
login := "admin-" + stamp
password := "admin-secret-" + stamp
hash, err := bouncer.HashPassword(10, password)
if err != nil {
t.Fatal(err)
}
grants := map[string]int{}
for _, code := range permissions {
grants[code] = 1
}
raw, err := json.Marshal(grants)
if err != nil {
t.Fatal(err)
}
var roleID uint
if err := e.gdb.Raw(`INSERT INTO backend_user_roles (name, code, permissions, is_system, created_at, updated_at) VALUES (?, ?, ?, FALSE, NOW(), NOW()) RETURNING id`,
"Role "+stamp, "role-"+stamp, string(raw)).Scan(&roleID).Error; err != nil || roleID == 0 {
t.Fatalf("backend role: id=%d err=%v", roleID, err)
}
if err := e.gdb.Exec(`INSERT INTO backend_users (login, email, password, is_activated, is_superuser, role_id, created_at, updated_at) VALUES (?, ?, ?, TRUE, FALSE, ?, NOW(), NOW())`,
login, login+"@example.test", hash, roleID).Error; err != nil {
t.Fatal(err)
}
rec := e.call(t, http.MethodPost, adminAPI("/auth/login"), "", map[string]string{"login": login, "password": password})
if rec.Code != http.StatusOK {
t.Fatalf("admin login %s: %d %s", login, rec.Code, rec.Body.String())
}
var body struct {
Data struct {
AccessToken string `json:"access_token"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.AccessToken == "" {
t.Fatalf("admin login body: %s err=%v", rec.Body.String(), err)
}
return body.Data.AccessToken
}
// call sends one request through the assembled handler. body is JSON-encoded
// unless it is nil; token, when set, is sent as a bearer token. The request
// locale is English and each call comes from its own address, so the login
// throttle never trips inside one test.
func (e *adminEnv) call(t *testing.T, method, path, token string, body any) *httptest.ResponseRecorder {
t.Helper()
var raw []byte
if body != nil {
var err error
if raw, err = json.Marshal(body); err != nil {
t.Fatal(err)
}
}
return e.send(t, method, path, token, raw, "application/json", nil)
}
// send is call with a raw body, its content type and extra headers (for
// example the form session key of a file upload).
func (e *adminEnv) send(t *testing.T, method, path, token string, body []byte, contentType string, headers map[string]string) *httptest.ResponseRecorder {
t.Helper()
var reader io.Reader
if body != nil {
reader = bytes.NewReader(body)
}
req := httptest.NewRequest(method, path, reader)
req.Host = "example.com"
req.RemoteAddr = fmt.Sprintf("198.51.100.%d:4000", adminSeq.Add(1)%250+1)
req.Header.Set("Accept-Language", "en")
req.Header.Set("Content-Type", contentType)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
for name, value := range headers {
req.Header.Set(name, value)
}
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
return rec
}
// sentMail is one message the application sent, as the log mail driver
// reports it: rendered, with the text part.
type sentMail struct {
To []string
Subject string
Text string
}
// mailCapture is the slog handler behind the app logger: it keeps the
// records of the log mail driver and passes everything else on.
type mailCapture struct {
mu sync.Mutex
sent []sentMail
next slog.Handler
}
func (m *mailCapture) Enabled(context.Context, slog.Level) bool { return true }
func (m *mailCapture) Handle(ctx context.Context, record slog.Record) error {
if record.Message != "postcard mail" {
if m.next != nil && m.next.Enabled(ctx, record.Level) {
return m.next.Handle(ctx, record)
}
return nil
}
var mail sentMail
record.Attrs(func(attr slog.Attr) bool {
switch attr.Key {
case "to":
mail.To, _ = attr.Value.Any().([]string)
case "subject":
mail.Subject = attr.Value.String()
case "text":
mail.Text = attr.Value.String()
}
return true
})
m.mu.Lock()
m.sent = append(m.sent, mail)
m.mu.Unlock()
return nil
}
func (m *mailCapture) WithAttrs([]slog.Attr) slog.Handler { return m }
func (m *mailCapture) WithGroup(string) slog.Handler { return m }
// mails returns the messages sent to the address since the env booted.
func (e *adminEnv) mails(to string) []sentMail {
e.mail.mu.Lock()
defer e.mail.mu.Unlock()
var out []sentMail
for _, mail := range e.mail.sent {
for _, recipient := range mail.To {
if recipient == to {
out = append(out, mail)
}
}
}
return out
}
// adminSessionKey returns a fresh form session key, as the admin SPA makes
// one when it opens a form.
func adminSessionKey(t *testing.T) string {
t.Helper()
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
t.Fatal(err)
}
return base64.RawURLEncoding.EncodeToString(raw)
}
// upload posts one file to a fileupload field of a user's form under a form
// session key; the next save sent with the same key attaches it.
func (e *adminEnv) upload(t *testing.T, token string, id uint, field, name string, data []byte, sessionKey string) *httptest.ResponseRecorder {
t.Helper()
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
part, err := mw.CreateFormFile("file_data", name)
if err != nil {
t.Fatal(err)
}
if _, err := part.Write(data); err != nil {
t.Fatal(err)
}
if err := mw.Close(); err != nil {
t.Fatal(err)
}
return e.send(t, http.MethodPost, userPath(id, "/files/"+field), token, buf.Bytes(), mw.FormDataContentType(),
map[string]string{cabana.SessionKeyHeader: sessionKey})
}
// expect is call plus a status assertion.
func (e *adminEnv) expect(t *testing.T, status int, method, path, token string, body any) *httptest.ResponseRecorder {
t.Helper()
rec := e.call(t, method, path, token, body)
if rec.Code != status {
t.Fatalf("%s %s = %d, want %d: %s", method, path, rec.Code, status, rec.Body.String())
}
return rec
}
// adminEnvelope is the admin API answer: data and meta on success, error
// otherwise.
type adminEnvelope struct {
Data json.RawMessage `json:"data"`
Meta json.RawMessage `json:"meta"`
Error struct {
Code string `json:"code"`
Message string `json:"message"`
Details map[string][]string `json:"details"`
} `json:"error"`
}
// adminDecode parses an admin API answer.
func adminDecode(t *testing.T, rec *httptest.ResponseRecorder) adminEnvelope {
t.Helper()
var env adminEnvelope
if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil {
t.Fatalf("admin body %q: %v", rec.Body.String(), err)
}
return env
}
// adminInto decodes the data of an admin API answer into out.
func adminInto(t *testing.T, rec *httptest.ResponseRecorder, out any) adminEnvelope {
t.Helper()
env := adminDecode(t, rec)
if err := json.Unmarshal(env.Data, out); err != nil {
t.Fatalf("admin data %q: %v", string(env.Data), err)
}
return env
}
// adminUserList is a decoded Users list page.
type adminUserList struct {
Rows []map[string]any
RowStates map[string][]string
Total int
Raw string
}
// has reports whether the page holds the user.
func (l adminUserList) has(id uint) bool { return l.row(id) != nil }
// row returns the list row of the user, or nil.
func (l adminUserList) row(id uint) map[string]any {
for _, row := range l.Rows {
if n, ok := row["id"].(float64); ok && uint(n) == id {
return row
}
}
return nil
}
// states returns the row states of the user.
func (l adminUserList) states(id uint) []string {
return l.RowStates[strconv.FormatUint(uint64(id), 10)]
}
// users lists the Users screen with a raw query string (without the leading
// question mark) and expects 200.
func (e *adminEnv) users(t *testing.T, token, query string) adminUserList {
t.Helper()
path := adminAPI(adminUsersPath)
if query != "" {
path += "?" + query
}
rec := e.expect(t, http.StatusOK, http.MethodGet, path, token, nil)
out := adminUserList{Raw: rec.Body.String()}
env := adminInto(t, rec, &out.Rows)
var meta struct {
Total int `json:"total"`
RowStates map[string][]string `json:"row_states"`
}
if err := json.Unmarshal(env.Meta, &meta); err != nil {
t.Fatalf("list meta %q: %v", string(env.Meta), err)
}
out.RowStates, out.Total = meta.RowStates, meta.Total
return out
}
// userPath is the admin API path of one user, with an optional suffix such
// as "/actions/activate".
func userPath(id uint, suffix string) string {
return adminAPI(adminUsersPath) + "/" + strconv.FormatUint(uint64(id), 10) + suffix
}
// seedUser stores a frontend user with the password correct-horse. The email
// is unique; mutate adjusts the row before it is inserted.
func (e *adminEnv) seedUser(t *testing.T, label string, mutate func(*models.User)) *models.User {
t.Helper()
hash, err := bouncer.HashPassword(10, "correct-horse")
if err != nil {
t.Fatal(err)
}
name := label
user := &models.User{Email: label + "-" + adminStamp() + "@example.test", Password: hash, Name: &name, IsActivated: true}
if mutate != nil {
mutate(user)
}
if err := e.gdb.Omit("Groups").Create(user).Error; err != nil {
t.Fatal(err)
}
return user
}
// seedGroup stores a user group; an empty code stores a group without one.
func (e *adminEnv) seedGroup(t *testing.T, name, code string) *models.UserGroup {
t.Helper()
group := &models.UserGroup{Name: name}
if code != "" {
group.Code = &code
}
if err := e.gdb.Create(group).Error; err != nil {
t.Fatal(err)
}
return group
}
// join puts the user into the groups by writing users_groups directly.
func (e *adminEnv) join(t *testing.T, user *models.User, groups ...*models.UserGroup) {
t.Helper()
for _, group := range groups {
if err := e.gdb.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, user.ID, group.ID).Error; err != nil {
t.Fatal(err)
}
}
}
// reload reads a user row, deactivated or not; nil when it is gone.
func (e *adminEnv) reload(t *testing.T, id uint) *models.User {
t.Helper()
var users []models.User
if err := e.gdb.Unscoped().Where("id = ?", id).Limit(1).Find(&users).Error; err != nil {
t.Fatal(err)
}
if len(users) == 0 {
return nil
}
return &users[0]
}
// groupIDs returns the user's users_groups rows, ordered.
func (e *adminEnv) groupIDs(t *testing.T, userID uint) []uint {
t.Helper()
ids := []uint{}
if err := e.gdb.Raw(`SELECT user_group_id FROM users_groups WHERE user_id = ? ORDER BY user_group_id`, userID).Scan(&ids).Error; err != nil {
t.Fatal(err)
}
return ids
}
// seedAvatar stores an avatar for the user the way the user API does: one
// system_files row (field avatar) and its blob. It returns the blob key.
func (e *adminEnv) seedAvatar(t *testing.T, user *models.User) string {
t.Helper()
disk := "avatar" + adminStamp() + ".jpg"
key := attach.BlobKey(disk)
if err := e.bucket.WriteAll(context.Background(), key, []byte("avatar-bytes"), nil); err != nil {
t.Fatal(err)
}
row := attach.File{
DiskName: disk,
FileName: "avatar.jpg",
FileSize: 12,
ContentType: "image/jpeg",
Field: "avatar",
AttachmentID: strconv.FormatUint(uint64(user.ID), 10),
AttachmentType: user.MorphName(),
}
if err := e.gdb.Create(&row).Error; err != nil {
t.Fatal(err)
}
return key
}
// blobExists reports whether the bucket still holds key.
func (e *adminEnv) blobExists(t *testing.T, key string) bool {
t.Helper()
ok, err := e.bucket.Exists(context.Background(), key)
if err != nil {
t.Fatal(err)
}
return ok
}
// seedThrottle stores one user_throttle row. ip may be empty for the row
// without an address.
func (e *adminEnv) seedThrottle(t *testing.T, user *models.User, ip string, banned bool, suspendedAt *time.Time) {
t.Helper()
row := models.Throttle{UserID: user.ID, IsBanned: banned}
if ip != "" {
row.IPAddress = &ip
}
if suspendedAt != nil {
row.IsSuspended, row.SuspendedAt, row.Attempts = true, suspendedAt, 5
}
if err := e.gdb.Create(&row).Error; err != nil {
t.Fatal(err)
}
}
// hangers counts what hangs off a user: throttle rows, group memberships
// and attachment rows.
type hangers struct{ Throttle, Groups, Files int64 }
func (e *adminEnv) hangers(t *testing.T, user *models.User) hangers {
t.Helper()
var out hangers
count := func(into *int64, query string, args ...any) {
t.Helper()
if err := e.gdb.Raw(query, args...).Scan(into).Error; err != nil {
t.Fatal(err)
}
}
count(&out.Throttle, `SELECT COUNT(*) FROM user_throttle WHERE user_id = ?`, user.ID)
count(&out.Groups, `SELECT COUNT(*) FROM users_groups WHERE user_id = ?`, user.ID)
count(&out.Files, `SELECT COUNT(*) FROM system_files WHERE attachment_type = ? AND attachment_id = ?`,
user.MorphName(), strconv.FormatUint(uint64(user.ID), 10))
return out
}
// bulk posts a declared bulk action, or the built-in bulk delete when action
// is "delete", for the given users.
func (e *adminEnv) bulk(t *testing.T, token, action string, users ...*models.User) *httptest.ResponseRecorder {
t.Helper()
ids := make([]uint, len(users))
for i, user := range users {
ids[i] = user.ID
}
path := adminAPI(adminUsersPath + "/bulk/" + action)
if action == "delete" {
path = adminAPI(adminUsersPath + "/bulk-delete")
}
return e.call(t, http.MethodPost, path, token, map[string]any{"ids": ids})
}
// offered returns the record actions the show response of the user offers.
func (e *adminEnv) offered(t *testing.T, token string, id uint) []string {
t.Helper()
rec := e.expect(t, http.StatusOK, http.MethodGet, userPath(id, ""), token, nil)
var meta struct {
Actions []struct {
Name string `json:"name"`
} `json:"actions"`
}
if err := json.Unmarshal(adminDecode(t, rec).Meta, &meta); err != nil {
t.Fatal(err)
}
names := []string{}
for _, action := range meta.Actions {
names = append(names, action.Name)
}
return names
}
// userLogin signs a frontend user in through the user API route and returns
// the status and the token.
func (e *adminEnv) userLogin(t *testing.T, email, password string) (int, string) {
t.Helper()
rec := e.call(t, http.MethodPost, "/_user/api/v1/login", "", map[string]string{"email": email, "password": password})
var body struct {
Token string `json:"token"`
}
_ = json.Unmarshal(rec.Body.Bytes(), &body)
return rec.Code, body.Token
}
// secretKey matches a JSON key that names a password or a one-time code.
var secretKey = regexp.MustCompile(`(?i)"[a-z_]*(password|activation_code|reset_password_code)[a-z_]*"\s*:`)
// assertNoSecret fails when an admin response carries a password key, a
// stored hash or the given plain text.
func assertNoSecret(t *testing.T, raw string, plain ...string) {
t.Helper()
if secretKey.MatchString(raw) || strings.Contains(raw, "$2a$") || strings.Contains(raw, "$2y$") {
t.Fatalf("admin response carries a password: %s", raw)
}
for _, secret := range plain {
if secret != "" && strings.Contains(raw, secret) {
t.Fatalf("admin response carries a secret value: %s", raw)
}
}
}

45
admin_navigation.go Normal file
View File

@@ -0,0 +1,45 @@
package user
import (
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/summercms/modules/pact"
)
// Navigation is the plugin's Winter registerNavigation() entry: the main item
// user (order 555) with its side menu. Controller names an admin controller
// id in place of a backend URL, and icons are lucide names.
func (*Plugin) Navigation() []pact.NavigationItem {
return []pact.NavigationItem{
{
Code: "user",
Label: "golem15.user::lang.users.menu_label",
Icon: "user",
Permissions: []string{"golem15.users.*"},
Order: 555,
Controller: "golem15.user.users",
SideMenu: []pact.NavigationItem{
{
Code: "users",
Label: "golem15.user::lang.users.menu_label",
Icon: "user",
Permissions: []string{controllers.PermissionAccessUsers},
Controller: "golem15.user.users",
},
{
Code: "usergroups",
Label: "golem15.user::lang.groups.all_groups",
Icon: "users",
Permissions: []string{controllers.PermissionAccessGroups},
Controller: "golem15.user.usergroups",
},
{
Code: "organisations",
Label: "golem15.user::lang.organisation.menu_label",
Icon: "users-round",
Permissions: []string{controllers.PermissionAccessUsers},
Controller: "golem15.user.organisations",
},
},
},
}
}

View File

@@ -0,0 +1,233 @@
package user
import (
"context"
"net/http"
"reflect"
"testing"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
)
// TestAdminOrganisationsControllerGuards drives the Organisations controller
// directly on the inputs the HTTP tests cannot produce.
func TestAdminOrganisationsControllerGuards(t *testing.T) {
ctx := context.Background()
const id = "golem15.user.organisations"
notOrganisation := &models.User{}
var nilOrganisation *models.Organisation
env := newAdminEnv(t)
sets := map[string]adminControllerSet{
"no accessor": adminControllersOn(nil),
"not booted": adminControllersOn(func() *backpack.App { return nil }),
"no database": adminControllersOn(func() *backpack.App { return bareApp(t) }),
"the live database": adminControllersOn(func() *backpack.App { return env.app }),
}
for name, set := range sets {
t.Run(name, func(t *testing.T) {
ctl := set[id]
for _, record := range []any{notOrganisation, nilOrganisation, nil} {
wantPlainError(t, "FormBeforeCreate", ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, record))
wantPlainError(t, "FormBeforeUpdate", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, record))
wantPlainError(t, "FormBeforeDelete", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, record))
}
wantPlainError(t, "FormBeforeDelete without a transaction", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, &models.Organisation{ID: 1}))
// The slug check needs no database; without a translator the
// refusal is in English.
if err := ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, &models.Organisation{Name: "Fine", Slug: "fine_slug-1"}); err != nil {
t.Fatal(err)
}
if err := ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, &models.Organisation{Name: "Empty"}); err != nil {
t.Fatalf("an empty slug is left to the required rule: %v", err)
}
err := ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, &models.Organisation{Name: "Bad", Slug: "bad slug"})
invalid, ok := err.(*cabana.ValidationError)
if !ok || !reflect.DeepEqual(invalid.Details["slug"], []string{"The slug may only contain letters, numbers, dashes and underscores."}) {
t.Fatalf("slug refusal = %v", err)
}
// The members manager is the only relation: any other name has
// no candidates.
manage := ctl.(pact.RelationExtendManageQuery)
if manage.RelationExtendManageQuery(ctx, "members", nil) != nil || manage.RelationExtendManageQuery(ctx, "groups", nil) != nil {
t.Fatal("RelationExtendManageQuery invented a handle")
}
contracts := ctl.(cabana.AdminRelationContractProvider).AdminRelationContracts()
if len(contracts) != 1 || contracts[0].Name != "members" || contracts[0].Kind != cabana.RelationHasMany || contracts[0].ForeignKey != "organisation_id" {
t.Fatalf("relation contracts = %+v", contracts)
}
if _, ok := contracts[0].NewRelated().(*models.User); !ok {
t.Fatal("the members relation is not on users")
}
if name == "the live database" {
var all, none int64
users := env.gdb.Model(&models.User{})
if err := manage.RelationExtendManageQuery(ctx, "members", users).Count(&all).Error; err != nil {
t.Fatal(err)
}
if err := manage.RelationExtendManageQuery(ctx, "groups", env.gdb.Model(&models.User{})).Count(&none).Error; err != nil || none != 0 {
t.Fatalf("candidates of another relation = %d err = %v", none, err)
}
_ = all
}
})
}
}
// TestAdminOrganisationsEdge covers the remaining branches of the
// Organisations screen through the admin API.
func TestAdminOrganisationsEdge(t *testing.T) {
env := newAdminEnv(t)
token := env.admin(t, permAccessUsers)
stamp := adminStamp()
// An organisation without members is deleted and nothing else changes.
bystander := env.seedUser(t, "bystander-"+stamp, nil)
empty := env.seedOrganisation(t, "Edge empty "+stamp)
env.expect(t, http.StatusOK, http.MethodDelete, organisationPath(empty.ID, ""), token, nil)
if env.organisation(t, empty.ID) != nil {
t.Fatal("the organisation survived its delete")
}
if env.reload(t, bystander.ID) == nil {
t.Fatal("deleting an organisation without members deleted a user")
}
env.expect(t, http.StatusNotFound, http.MethodGet, organisationPath(empty.ID, ""), token, nil)
// A slug with other characters is a 422 on the field, on create and on
// update; a duplicate slug too.
home := env.seedOrganisation(t, "Edge home "+stamp)
for _, slug := range []string{"with space", "dot.ted", "sl/ash", "ąę"} {
rec := env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminOrganisationsPath), token, map[string]any{"name": "Edge bad " + stamp, "slug": slug})
if details := adminDecode(t, rec).Error.Details; len(details["slug"]) == 0 {
t.Fatalf("slug %q: details = %v", slug, details)
}
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, organisationPath(home.ID, ""), token, map[string]any{"slug": slug})
}
env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminOrganisationsPath), token, map[string]any{"name": "Edge twin " + stamp, "slug": home.Slug})
if got := env.organisation(t, home.ID); got.Slug != home.Slug {
t.Fatalf("a refused update changed the slug to %q", got.Slug)
}
// Search and sort on the list.
for _, name := range []string{"b", "a", "c"} {
env.seedOrganisation(t, "Orgsort "+stamp+" "+name)
}
order := func(query string) []string {
var rows []map[string]any
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath)+"?search=Orgsort%20"+stamp+"&"+query, token, nil), &rows)
names := []string{}
for _, row := range rows {
name, _ := row["name"].(string)
names = append(names, name[len(name)-1:])
}
return names
}
if got := order("sort=name&dir=asc"); !reflect.DeepEqual(got, []string{"a", "b", "c"}) {
t.Fatalf("name asc = %v", got)
}
if got := order("sort=slug&dir=desc"); !reflect.DeepEqual(got, []string{"c", "b", "a"}) {
t.Fatalf("slug desc = %v", got)
}
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminOrganisationsPath)+"?filter[slug]=x", token, nil)
// A deactivated user is not offered as a member and cannot be linked:
// the candidates leave soft-deleted users out.
gone := env.seedUser(t, "gone-"+stamp, nil)
if err := env.gdb.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, gone.ID).Error; err != nil {
t.Fatal(err)
}
var candidates []map[string]any
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, organisationPath(home.ID, "/relations/members/candidates?search=gone-"+stamp), token, nil), &candidates)
if len(candidates) != 0 {
t.Fatalf("a deactivated user is a candidate: %v", candidates)
}
rec := env.call(t, http.MethodPost, organisationPath(home.ID, "/relations/members/link"), token, map[string]any{"ids": []uint{gone.ID}})
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("link of a deactivated user = %d %s", rec.Code, rec.Body.String())
}
if got := env.reload(t, gone.ID); got.OrganisationID != nil {
t.Fatalf("a deactivated user was linked to %d", *got.OrganisationID)
}
// Ids that are not users, and an empty list, change nothing.
for _, body := range []map[string]any{{"ids": []uint{987654321}}, {"ids": []uint{}}, {}} {
rec := env.call(t, http.MethodPost, organisationPath(home.ID, "/relations/members/link"), token, body)
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("link %v = %d %s", body, rec.Code, rec.Body.String())
}
}
}
// TestAdminOrganisationMembershipClearsRole: a role belongs to one
// organisation (12.1-SECURITY-REVIEW.md open item 6, closed). Removing a
// member through the members manager clears organisation_id and
// organisation_role, adding one clears a leftover role, and changing the
// organisation in the Users form clears the role while a save that keeps the
// organisation keeps it. Deleting the organisation clears both.
func TestAdminOrganisationMembershipClearsRole(t *testing.T) {
env := newAdminEnv(t)
token := env.admin(t, permAccessUsers)
stamp := adminStamp()
first := env.seedOrganisation(t, "Role first "+stamp)
second := env.seedOrganisation(t, "Role second "+stamp)
doomed := env.seedOrganisation(t, "Role doomed "+stamp)
owner := "owner"
member := env.seedUser(t, "role-"+stamp, func(u *models.User) { u.OrganisationID, u.OrganisationRole = &first.ID, &owner })
other := env.seedUser(t, "role-other-"+stamp, func(u *models.User) { u.OrganisationID, u.OrganisationRole = &doomed.ID, &owner })
ids := map[string]any{"ids": []uint{member.ID}}
env.expect(t, http.StatusOK, http.MethodPost, organisationPath(first.ID, "/relations/members/unlink"), token, ids)
got := env.reload(t, member.ID)
if got.OrganisationID != nil || got.OrganisationRole != nil {
t.Fatalf("after the unlink: organisation %v role %v, want both NULL", got.OrganisationID, got.OrganisationRole)
}
env.expect(t, http.StatusOK, http.MethodPost, organisationPath(second.ID, "/relations/members/link"), token, ids)
got = env.reload(t, member.ID)
if got.OrganisationID == nil || *got.OrganisationID != second.ID || got.OrganisationRole != nil {
t.Fatalf("after the link elsewhere: organisation %v role %v", got.OrganisationID, got.OrganisationRole)
}
// An organisation-less user with a leftover role loses it when added.
leftover := env.seedUser(t, "role-leftover-"+stamp, func(u *models.User) { u.OrganisationRole = &owner })
env.expect(t, http.StatusOK, http.MethodPost, organisationPath(first.ID, "/relations/members/link"), token, map[string]any{"ids": []uint{leftover.ID}})
if got := env.reload(t, leftover.ID); got.OrganisationID == nil || *got.OrganisationID != first.ID || got.OrganisationRole != nil {
t.Fatalf("linked leftover: organisation %v role %v", got.OrganisationID, got.OrganisationRole)
}
// The Users form: keeping the organisation keeps the role, changing it
// (to another organisation or to none) clears it.
formUser := env.seedUser(t, "role-form-"+stamp, func(u *models.User) { u.OrganisationID, u.OrganisationRole = &first.ID, &owner })
setRole := func(t *testing.T) {
t.Helper()
if err := env.gdb.Model(&models.User{}).Where("id = ?", formUser.ID).UpdateColumn("organisation_role", owner).Error; err != nil {
t.Fatal(err)
}
}
saveForm := func(t *testing.T, organisation any) *models.User {
t.Helper()
env.expect(t, http.StatusOK, http.MethodPut, userPath(formUser.ID, ""), token, map[string]any{
"name": "role-form", "email": formUser.Email, "organisation": organisation,
})
return env.reload(t, formUser.ID)
}
if got := saveForm(t, first.ID); got.OrganisationRole == nil || *got.OrganisationRole != owner {
t.Fatalf("a save that keeps the organisation dropped the role: %v", got.OrganisationRole)
}
if got := saveForm(t, second.ID); got.OrganisationID == nil || *got.OrganisationID != second.ID || got.OrganisationRole != nil {
t.Fatalf("after moving to another organisation: organisation %v role %v", got.OrganisationID, got.OrganisationRole)
}
setRole(t)
if got := saveForm(t, nil); got.OrganisationID != nil || got.OrganisationRole != nil {
t.Fatalf("after clearing the organisation: organisation %v role %v", got.OrganisationID, got.OrganisationRole)
}
// The delete of an organisation releases its members completely.
env.expect(t, http.StatusOK, http.MethodDelete, organisationPath(doomed.ID, ""), token, nil)
if got := env.reload(t, other.ID); got == nil || got.OrganisationID != nil || got.OrganisationRole != nil {
t.Fatalf("member of a deleted organisation = %+v", got)
}
}

491
admin_organisations_test.go Normal file
View File

@@ -0,0 +1,491 @@
package user
import (
"bytes"
"encoding/json"
"mime/multipart"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"testing"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/cabana"
)
// adminOrganisationsPath is the Organisations controller under the admin API.
const adminOrganisationsPath = "/golem15/user/organisations"
// organisationPath is the admin API path of one organisation, with an
// optional suffix such as "/relations/members".
func organisationPath(id uint, suffix string) string {
return adminAPI(adminOrganisationsPath) + "/" + strconv.FormatUint(uint64(id), 10) + suffix
}
// organisation reads an organisation row; nil when it is gone.
func (e *adminEnv) organisation(t *testing.T, id uint) *models.Organisation {
t.Helper()
var rows []models.Organisation
if err := e.gdb.Where("id = ?", id).Limit(1).Find(&rows).Error; err != nil {
t.Fatal(err)
}
if len(rows) == 0 {
return nil
}
return &rows[0]
}
// seedOrganisation stores an organisation with a unique slug.
func (e *adminEnv) seedOrganisation(t *testing.T, name string) *models.Organisation {
t.Helper()
organisation := &models.Organisation{Name: name, Slug: models.Slugify(name)}
if err := e.gdb.Create(organisation).Error; err != nil {
t.Fatal(err)
}
return organisation
}
// TestSlugify pins the slug rule the organisation model shares with the
// admin form's slug preset.
func TestSlugify(t *testing.T) {
for text, want := range map[string]string{
"Acme Records": "acme-records",
" Acme -- Records ": "acme-records",
"ACME_Records 2": "acme-records-2",
"Zażółć gęślą": "za-g-l",
"---": "",
"": "",
"a": "a",
} {
if got := models.Slugify(text); got != want {
t.Fatalf("Slugify(%q) = %q, want %q", text, got, want)
}
}
}
// TestAdminOrganisations covers the Organisations screen (D-22, D-20): its
// permission, the list, the form with the slug rules and the avatar, and the
// delete that releases the members.
func TestAdminOrganisations(t *testing.T) {
env := newAdminEnv(t)
token := env.admin(t, permAccessUsers)
groupsOnly := env.admin(t, permAccessGroups)
both := env.admin(t, permAccessUsers, permAccessGroups)
stamp := adminStamp()
// The screen needs golem15.users.access_users.
for _, path := range []string{adminAPI(adminOrganisationsPath), adminAPI(adminOrganisationsPath + "/schema/list"), adminAPI(adminOrganisationsPath + "/schema/form")} {
rec := env.expect(t, http.StatusForbidden, http.MethodGet, path, groupsOnly, nil)
if code := adminDecode(t, rec).Error.Code; code != "forbidden" {
t.Fatalf("%s code = %q", path, code)
}
}
env.expect(t, http.StatusForbidden, http.MethodPost, adminAPI(adminOrganisationsPath), groupsOnly, map[string]any{"name": "Nope " + stamp})
// All three screens are side items of `user`, in this order, each shown
// only with its permission.
if got := env.sideMenu(t, both); !reflect.DeepEqual(got, []string{
"users=golem15.user.users", "usergroups=golem15.user.usergroups", "organisations=golem15.user.organisations",
}) {
t.Fatalf("side menu with both permissions = %v", got)
}
if got := env.sideMenu(t, groupsOnly); !reflect.DeepEqual(got, []string{"usergroups=golem15.user.usergroups"}) {
t.Fatalf("side menu with the groups permission = %v", got)
}
// The list schema: Name, Slug and Created; rows open the update form.
var schema struct {
RecordURL string `json:"recordUrl"`
ShowCheckboxes bool `json:"showCheckboxes"`
ToolbarButtons []string `json:"toolbarButtons"`
Columns []struct {
Key string `json:"key"`
Invisible bool `json:"invisible"`
Searchable bool `json:"searchable"`
Type string `json:"type"`
} `json:"columns"`
Messages map[string]map[string]string `json:"messages"`
}
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath+"/schema/list"), token, nil), &schema)
var visible []string
for _, column := range schema.Columns {
if !column.Invisible {
visible = append(visible, column.Key)
}
}
if !reflect.DeepEqual(visible, []string{"name", "slug", "created_at"}) || schema.RecordURL != "golem15/user/organisations/update/:id" ||
schema.ShowCheckboxes || !reflect.DeepEqual(schema.ToolbarButtons, []string{"create"}) {
t.Fatalf("list schema = %+v", schema)
}
if got := schema.Messages["empty"]["other"]; got != "No organisations yet. Create the first one with New Organisation." {
t.Fatalf("empty message = %q", got)
}
if got := schema.Messages["create"]["other"]; got != "New Organisation" {
t.Fatalf("create message = %q", got)
}
// The form: name, slug (slug preset from name), description, the avatar
// as a 120 by 120 image and the members manager on update only; no
// preview.
var form struct {
Fields []struct {
Name string `json:"name"`
Type string `json:"type"`
Mode string `json:"mode"`
Tab string `json:"tab"`
Context any `json:"context"`
ImageWidth int `json:"imageWidth"`
ImageHeight int `json:"imageHeight"`
Preset *struct {
Field string `json:"field"`
Type string `json:"type"`
} `json:"preset"`
} `json:"fields"`
Preview json.RawMessage `json:"preview"`
}
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath+"/schema/form"), token, nil), &form)
var names []string
for _, field := range form.Fields {
names = append(names, field.Name+":"+field.Type)
switch field.Name {
case "slug":
if field.Preset == nil || field.Preset.Field != "name" || field.Preset.Type != "slug" {
t.Fatalf("slug preset = %+v", field.Preset)
}
case "avatar":
if field.Mode != "image" || field.ImageWidth != 120 || field.ImageHeight != 120 {
t.Fatalf("avatar field = %+v", field)
}
case "logo":
if field.Mode != "image" || field.ImageWidth != 240 || field.ImageHeight != 120 {
t.Fatalf("logo field = %+v", field)
}
case "members":
if field.Context != "update" || field.Tab != "Members" {
t.Fatalf("members field = %+v", field)
}
}
}
if want := []string{"name:text", "slug:text", "description:textarea", "avatar:fileupload", "logo:fileupload", "members:relation-manager"}; !reflect.DeepEqual(names, want) {
t.Fatalf("form fields = %v, want %v", names, want)
}
if len(form.Preview) != 0 && string(form.Preview) != "null" {
t.Fatalf("the organisation form has a preview: %s", form.Preview)
}
// Create: an empty slug is derived from the name; a given slug is kept.
create := func(status int, body map[string]any) *httptest.ResponseRecorder {
t.Helper()
return env.expect(t, status, http.MethodPost, adminAPI(adminOrganisationsPath), token, body)
}
name := "Acme Records " + stamp
id := createdID(t, create(http.StatusCreated, map[string]any{"name": name, "slug": "", "description": "A label"}))
if got := env.organisation(t, id); got == nil || got.Name != name || got.Slug != "acme-records-"+stamp || got.Description == nil || *got.Description != "A label" {
t.Fatalf("created organisation = %+v", got)
}
omitted := createdID(t, create(http.StatusCreated, map[string]any{"name": "Omitted Slug " + stamp}))
if got := env.organisation(t, omitted); got.Slug != "omitted-slug-"+stamp {
t.Fatalf("slug of a create without the key = %q", got.Slug)
}
given := createdID(t, create(http.StatusCreated, map[string]any{"name": "Given " + stamp, "slug": "Given_Slug-" + stamp}))
if got := env.organisation(t, given); got.Slug != "Given_Slug-"+stamp {
t.Fatalf("given slug = %q", got.Slug)
}
// A slug with other characters, a duplicate slug and a missing name are
// refused on their field and create nothing.
for _, bad := range []string{"has space " + stamp, "dot." + stamp, "ślad-" + stamp} {
rec := create(http.StatusUnprocessableEntity, map[string]any{"name": "Bad " + stamp, "slug": bad})
if details := adminDecode(t, rec).Error.Details; len(details["slug"]) != 1 || details["slug"][0] != "The slug may only contain letters, numbers, dashes and underscores." {
t.Fatalf("slug refusal for %q = %s", bad, rec.Body.String())
}
}
rec := create(http.StatusUnprocessableEntity, map[string]any{"name": "Duplicate " + stamp, "slug": "acme-records-" + stamp})
if details := adminDecode(t, rec).Error.Details; len(details["slug"]) == 0 {
t.Fatalf("duplicate slug refusal = %s", rec.Body.String())
}
// The derived slug collides as well.
rec = create(http.StatusUnprocessableEntity, map[string]any{"name": name})
if details := adminDecode(t, rec).Error.Details; len(details["slug"]) == 0 {
t.Fatalf("derived duplicate slug refusal = %s", rec.Body.String())
}
rec = create(http.StatusUnprocessableEntity, map[string]any{"slug": "nameless-" + stamp})
if details := adminDecode(t, rec).Error.Details; len(details["name"]) == 0 {
t.Fatalf("missing name refusal = %s", rec.Body.String())
}
var count int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM golem15_user_organisations WHERE name LIKE ?`, "%"+stamp).Scan(&count).Error; err != nil || count != 3 {
t.Fatalf("organisations after the refused creates = %d (%v)", count, err)
}
// The list finds it by name and by slug.
for _, term := range []string{"Acme+Records+" + stamp, "acme-records-" + stamp} {
var rows []map[string]any
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath)+"?search="+term, token, nil), &rows)
if len(rows) != 1 || rows[0]["name"] != name || rows[0]["slug"] != "acme-records-"+stamp {
t.Fatalf("list for %q = %v", term, rows)
}
}
// Update: the fields change; a bad slug is refused and changes nothing.
env.expect(t, http.StatusOK, http.MethodPut, organisationPath(id, ""), token, map[string]any{"name": name, "slug": "acme-" + stamp, "description": "Renamed slug"})
if got := env.organisation(t, id); got.Slug != "acme-"+stamp || *got.Description != "Renamed slug" {
t.Fatalf("updated organisation = %+v", got)
}
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, organisationPath(id, ""), token, map[string]any{"name": name, "slug": "acme " + stamp})
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, organisationPath(id, ""), token, map[string]any{"name": name, "slug": "Given_Slug-" + stamp})
if got := env.organisation(t, id); got.Slug != "acme-"+stamp {
t.Fatalf("a refused update changed the slug to %q", got.Slug)
}
// Avatar: a file uploaded through the admin file route is attached to
// the organisation under its morph name when the form is saved.
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
part, err := mw.CreateFormFile("file_data", "logo.jpg")
if err != nil {
t.Fatal(err)
}
if _, err := part.Write(jpegBytes(t)); err != nil {
t.Fatal(err)
}
if err := mw.Close(); err != nil {
t.Fatal(err)
}
sessionKey := adminSessionKey(t)
headers := map[string]string{cabana.SessionKeyHeader: sessionKey}
if up := env.send(t, http.MethodPost, organisationPath(id, "/files/avatar"), token, buf.Bytes(), mw.FormDataContentType(), headers); up.Code != http.StatusCreated && up.Code != http.StatusOK {
t.Fatalf("avatar upload = %d %s", up.Code, up.Body.String())
}
body, err := json.Marshal(map[string]any{"name": name, "slug": "acme-" + stamp})
if err != nil {
t.Fatal(err)
}
if saved := env.send(t, http.MethodPut, organisationPath(id, ""), token, body, "application/json", headers); saved.Code != http.StatusOK {
t.Fatalf("save with the avatar = %d %s", saved.Code, saved.Body.String())
}
files := func() int64 {
t.Helper()
var n int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM system_files WHERE attachment_type = ? AND attachment_id = ? AND field = 'avatar'`,
`Golem15\User\Models\Organisation`, strconv.FormatUint(uint64(id), 10)).Scan(&n).Error; err != nil {
t.Fatal(err)
}
return n
}
if files() != 1 || (models.Organisation{}).MorphName() != `Golem15\User\Models\Organisation` {
t.Fatalf("avatar rows of the organisation = %d", files())
}
// Delete: an organisation with members goes; its members stay, active or
// deactivated, without an organisation and without a role in it. Users
// of another organisation are not touched.
role := "owner"
owner := env.seedUser(t, "org-owner", func(u *models.User) { u.OrganisationID, u.OrganisationRole = &id, &role })
gone := env.seedUser(t, "org-gone", func(u *models.User) { u.OrganisationID = &id })
if err := env.gdb.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, gone.ID).Error; err != nil {
t.Fatal(err)
}
other := env.seedUser(t, "org-other", func(u *models.User) { u.OrganisationID, u.OrganisationRole = &given, &role })
group := env.seedGroup(t, "Org "+stamp, "org-"+stamp)
env.join(t, owner, group)
env.expect(t, http.StatusOK, http.MethodDelete, organisationPath(id, ""), token, nil)
if env.organisation(t, id) != nil {
t.Fatal("the organisation survived its delete")
}
for _, member := range []*models.User{owner, gone} {
got := env.reload(t, member.ID)
if got == nil || got.OrganisationID != nil || got.OrganisationRole != nil || got.Email != member.Email {
t.Fatalf("member %d after the delete = %+v", member.ID, got)
}
}
if got := env.reload(t, other.ID); got.OrganisationID == nil || *got.OrganisationID != given || got.OrganisationRole == nil {
t.Fatalf("a member of another organisation changed: %+v", got)
}
if got := env.groupIDs(t, owner.ID); !reflect.DeepEqual(got, []uint{group.ID}) {
t.Fatalf("the delete changed the owner's groups: %v", got)
}
env.expect(t, http.StatusNotFound, http.MethodGet, organisationPath(id, ""), token, nil)
}
// TestAdminOrganisationMembers covers the members relation manager: link
// sets and unlink clears users.organisation_id, the lists are scoped to the
// organisation, and nothing else of a user changes, least of all
// users_groups (T-12.1-30).
func TestAdminOrganisationMembers(t *testing.T) {
env := newAdminEnv(t)
token := env.admin(t, permAccessUsers)
groupsOnly := env.admin(t, permAccessGroups)
stamp := adminStamp()
here := env.seedOrganisation(t, "Here "+stamp)
there := env.seedOrganisation(t, "There "+stamp)
label := "Member" + stamp
named := func(suffix string, mutate func(*models.User)) *models.User {
return env.seedUser(t, "member-"+suffix, func(u *models.User) {
name := label + " " + suffix
u.Name = &name
if mutate != nil {
mutate(u)
}
})
}
first, second := named("first", nil), named("second", nil)
role := "member"
foreign := named("foreign", func(u *models.User) { u.OrganisationID, u.OrganisationRole = &there.ID, &role })
group := env.seedGroup(t, "Members "+stamp, "members-"+stamp)
adminGroup := env.seedGroup(t, "Admins "+stamp, "admin")
env.join(t, first, group, adminGroup)
env.join(t, second, group)
env.join(t, foreign, adminGroup)
everyone := []*models.User{first, second, foreign}
memberships := map[uint][]uint{}
stored := map[uint]*models.User{}
for _, user := range everyone {
memberships[user.ID] = env.groupIDs(t, user.ID)
stored[user.ID] = env.reload(t, user.ID)
}
untouched := func() {
t.Helper()
for _, user := range everyone {
if got := env.groupIDs(t, user.ID); !reflect.DeepEqual(got, memberships[user.ID]) {
t.Fatalf("users_groups of %d = %v, want %v", user.ID, got, memberships[user.ID])
}
got, want := env.reload(t, user.ID), stored[user.ID]
if got == nil || got.Email != want.Email || got.Password != want.Password || got.IsActivated != want.IsActivated ||
!reflect.DeepEqual(got.Name, want.Name) || !reflect.DeepEqual(got.OrganisationRole, want.OrganisationRole) ||
!reflect.DeepEqual(got.TokensValidAfter, want.TokensValidAfter) || got.DeletedAt.Valid {
t.Fatalf("user %d changed beyond organisation_id: %+v", user.ID, got)
}
}
}
organisationOf := func(user *models.User) uint {
t.Helper()
got := env.reload(t, user.ID)
if got == nil || got.OrganisationID == nil {
return 0
}
return *got.OrganisationID
}
ids := func(path string) []uint {
t.Helper()
var rows []map[string]any
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, path, token, nil), &rows)
out := []uint{}
for _, row := range rows {
out = append(out, uint(row["id"].(float64)))
}
return out
}
members := func(organisation *models.Organisation) []uint {
t.Helper()
return ids(organisationPath(organisation.ID, "/relations/members"))
}
candidates := func() []uint {
t.Helper()
return ids(organisationPath(here.ID, "/relations/members/candidates?search="+label))
}
mutate := func(organisation *models.Organisation, action string, users ...*models.User) *httptest.ResponseRecorder {
t.Helper()
list := make([]uint, len(users))
for i, user := range users {
list[i] = user.ID
}
return env.call(t, http.MethodPost, organisationPath(organisation.ID, "/relations/members/"+action), token, map[string]any{"ids": list})
}
// The relation schema carries the screen's copy: the unlink confirm
// counts and says the users are not deleted.
var relation struct {
Messages map[string]map[string]string `json:"messages"`
}
rawRelation := env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminOrganisationsPath+"/schema/relation/members"), token, nil)
adminInto(t, rawRelation, &relation)
for key, want := range map[string]string{
"link": "Add member",
"unlinkSelected": "Remove selected",
"unlinkConfirm": "Remove the selected (:count) from this organisation? The users are not deleted.",
"empty": "This organisation has no members yet. Add users with Add member.",
} {
if got := relation.Messages[key]["other"]; got != want {
t.Fatalf("relation message %s = %q, want %q (%s)", key, got, want, rawRelation.Body.String())
}
}
env.expect(t, http.StatusNotFound, http.MethodGet, adminAPI(adminOrganisationsPath+"/schema/relation/groups"), token, nil)
// The routes need the screen's permission.
env.expect(t, http.StatusForbidden, http.MethodGet, organisationPath(here.ID, "/relations/members"), groupsOnly, nil)
env.expect(t, http.StatusForbidden, http.MethodPost, organisationPath(here.ID, "/relations/members/link"), groupsOnly, map[string]any{"ids": []uint{first.ID}})
if organisationOf(first) != 0 {
t.Fatal("a refused link set organisation_id")
}
// An organisation without members lists none; the candidates are the
// users without an organisation.
if got := members(here); len(got) != 0 {
t.Fatalf("members of a new organisation = %v", got)
}
if got := candidates(); !reflect.DeepEqual(got, []uint{first.ID, second.ID}) {
t.Fatalf("candidates = %v, want %v", got, []uint{first.ID, second.ID})
}
// Link sets organisation_id of both users.
if rec := mutate(here, "link", first, second); rec.Code != http.StatusOK {
t.Fatalf("link = %d %s", rec.Code, rec.Body.String())
}
if organisationOf(first) != here.ID || organisationOf(second) != here.ID {
t.Fatalf("organisation_id after the link = %d, %d", organisationOf(first), organisationOf(second))
}
untouched()
// Each list shows only its own organisation's members.
if got := members(here); !reflect.DeepEqual(got, []uint{first.ID, second.ID}) {
t.Fatalf("members here = %v", got)
}
if got := members(there); !reflect.DeepEqual(got, []uint{foreign.ID}) {
t.Fatalf("members there = %v", got)
}
if got := candidates(); len(got) != 0 {
t.Fatalf("candidates after the link = %v", got)
}
// A member of another organisation is not a candidate and cannot be
// taken over by a link: they stay where they are.
refused := mutate(here, "link", foreign)
if details := adminDecode(t, refused).Error.Details; refused.Code != http.StatusUnprocessableEntity || len(details["ids"]) == 0 {
t.Fatalf("link of a foreign member = %d %s", refused.Code, refused.Body.String())
}
if organisationOf(foreign) != there.ID {
t.Fatalf("a foreign member moved to %d", organisationOf(foreign))
}
// Unlinking through the wrong organisation is ignored.
mutate(here, "unlink", foreign)
if organisationOf(foreign) != there.ID {
t.Fatal("an unlink through another organisation cleared organisation_id")
}
untouched()
// Unlink clears organisation_id of the chosen user only; the user stays.
if rec := mutate(here, "unlink", first); rec.Code != http.StatusOK {
t.Fatalf("unlink = %d %s", rec.Code, rec.Body.String())
}
if organisationOf(first) != 0 || organisationOf(second) != here.ID || env.reload(t, first.ID) == nil {
t.Fatalf("organisation_id after the unlink = %d, %d", organisationOf(first), organisationOf(second))
}
if got := members(here); !reflect.DeepEqual(got, []uint{second.ID}) {
t.Fatalf("members after the unlink = %v", got)
}
untouched()
// Once released there, the user can be linked here: this is how a user
// moves between organisations.
if rec := mutate(there, "unlink", foreign); rec.Code != http.StatusOK {
t.Fatalf("unlink there = %d %s", rec.Code, rec.Body.String())
}
// The role belonged to the organisation left: the unlink cleared it.
if got := env.reload(t, foreign.ID); got.OrganisationRole != nil {
t.Fatalf("organisation_role after leaving = %q", *got.OrganisationRole)
}
stored[foreign.ID].OrganisationRole = nil
if rec := mutate(here, "link", foreign); rec.Code != http.StatusOK || organisationOf(foreign) != here.ID {
t.Fatalf("link after the release = %d %s", rec.Code, rec.Body.String())
}
untouched()
}

64
admin_permissions.go Normal file
View File

@@ -0,0 +1,64 @@
package user
import (
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/pact"
)
const userPermissionTab = "golem15.user::lang.plugin.tab"
// Permissions is the plugin's Winter registerPermissions() catalog plus two
// codes of its own. The four PHP codes default to the developer role;
// impersonate_user is registered so imported backend roles that name it stay
// valid, although no screen uses it. The fifth code
// (classes.PermissionManagePrivilegedGroups) has no default role: only a
// superuser, or a role that was granted it explicitly, may change the email
// or password of a privileged-group member or delete one. The sixth
// (classes.PermissionManageBackendLinks) has no default role either: it
// links and unlinks another administrator's frontend account on the
// Administrators screen. The seventh (classes.PermissionResetTwoFactor) has
// no default role either: it runs the Users screen's "Reset 2FA" action,
// which a two-factor plugin backs.
func (*Plugin) Permissions() []pact.Permission {
return []pact.Permission{
{
Code: "golem15.users.access_users",
Tab: userPermissionTab,
Label: "golem15.user::lang.plugin.access_users",
Roles: []string{"developer"},
},
{
Code: "golem15.users.access_groups",
Tab: userPermissionTab,
Label: "golem15.user::lang.plugin.access_groups",
Roles: []string{"developer"},
},
{
Code: "golem15.users.access_settings",
Tab: userPermissionTab,
Label: "golem15.user::lang.plugin.access_settings",
Roles: []string{"developer"},
},
{
Code: "golem15.users.impersonate_user",
Tab: userPermissionTab,
Label: "golem15.user::lang.plugin.impersonate_user",
Roles: []string{"developer"},
},
{
Code: "golem15.users.manage_privileged_groups",
Tab: userPermissionTab,
Label: "golem15.user::lang.plugin.manage_privileged_groups",
},
{
Code: classes.PermissionManageBackendLinks,
Tab: userPermissionTab,
Label: "golem15.user::lang.plugin.manage_backend_links",
},
{
Code: classes.PermissionResetTwoFactor,
Tab: userPermissionTab,
Label: "golem15.user::lang.plugin.reset_two_factor",
},
}
}

556
admin_privileged_test.go Normal file
View File

@@ -0,0 +1,556 @@
package user
import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"testing"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/compass"
)
const privilegedGroupForbidden = "You do not have permission to change membership of privileged groups. Nothing was saved."
// groupOptions returns the choices of the user form's groups field that
// match search, as id to locked.
func (e *adminEnv) groupOptions(t *testing.T, token, search string) map[uint]bool {
t.Helper()
var options []struct {
Value uint `json:"value"`
Locked bool `json:"locked"`
}
path := adminAPI(adminUsersPath + "/fields/groups/options?per_page=100&search=" + search)
adminInto(t, e.expect(t, http.StatusOK, http.MethodGet, path, token, nil), &options)
out := map[uint]bool{}
for _, option := range options {
out[option.Value] = option.Locked
}
return out
}
// recordGroups reads a user through the admin API and returns the ids of
// the groups field and, per id, whether its label is flagged locked.
func (e *adminEnv) recordGroups(t *testing.T, token string, userID uint) ([]uint, map[uint]bool) {
t.Helper()
rec := e.expect(t, http.StatusOK, http.MethodGet, userPath(userID, ""), token, nil)
var data struct {
Groups []uint `json:"groups"`
}
answer := adminInto(t, rec, &data)
var meta struct {
Labels map[string][]struct {
Value uint `json:"value"`
Locked bool `json:"locked"`
} `json:"labels"`
}
if err := json.Unmarshal(answer.Meta, &meta); err != nil {
t.Fatalf("record meta %q: %v", string(answer.Meta), err)
}
locked := map[uint]bool{}
for _, label := range meta.Labels["groups"] {
locked[label.Value] = label.Locked
}
return data.Groups, locked
}
// sortedIDs returns the ids of the groups in ascending order, the order
// groupIDs reads the pivot in.
func sortedIDs(groups ...*models.UserGroup) []uint {
ids := make([]uint, 0, len(groups))
for _, group := range groups {
ids = append(ids, group.ID)
}
for i := 1; i < len(ids); i++ {
for j := i; j > 0 && ids[j-1] > ids[j]; j-- {
ids[j-1], ids[j] = ids[j], ids[j-1]
}
}
return ids
}
// TestAdminUserGroupsField covers the groups field of the user form with
// ordinary groups: it is the writer of users_groups, it replaces the user's
// memberships only when the field is sent, it refuses ids that are not
// groups, and none of it reaches a user API payload (D-08).
func TestAdminUserGroupsField(t *testing.T) {
env := newAdminEnv(t)
token := env.admin(t, permAccessUsers)
stamp := adminStamp()
first := env.seedGroup(t, "First "+stamp, "first-"+stamp)
second := env.seedGroup(t, "Second "+stamp, "second-"+stamp)
user := env.seedUser(t, "groups", nil)
base := map[string]any{"name": "groups", "email": user.Email}
save := func(status int, groups any) *httptest.ResponseRecorder {
t.Helper()
body := map[string]any{"groups": groups}
for key, value := range base {
body[key] = value
}
return env.expect(t, status, http.MethodPut, userPath(user.ID, ""), token, body)
}
pivot := func(want ...*models.UserGroup) {
t.Helper()
if got := env.groupIDs(t, user.ID); !reflect.DeepEqual(got, sortedIDs(want...)) {
t.Fatalf("users_groups of %d = %v, want %v", user.ID, got, sortedIDs(want...))
}
}
// The field is a multiple relation field on the Account tab, and its
// options are the user groups; none is locked for ordinary codes.
var form struct {
Fields []struct {
Name string `json:"name"`
Type string `json:"type"`
Multiple bool `json:"multiple"`
Tab string `json:"tab"`
} `json:"fields"`
}
adminInto(t, env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminUsersPath+"/schema/form"), token, nil), &form)
found := false
for _, field := range form.Fields {
if field.Name != "groups" {
continue
}
found = true
if field.Type != "relation" || !field.Multiple || field.Tab != "Account" {
t.Fatalf("groups field = %+v", field)
}
}
if !found {
t.Fatal("the user form has no groups field")
}
if options := env.groupOptions(t, token, stamp); len(options) != 2 || options[first.ID] || options[second.ID] {
t.Fatalf("group options = %v", options)
}
// Setting the field writes exactly the chosen memberships.
saved := save(http.StatusOK, []uint{first.ID, second.ID})
pivot(first, second)
var record struct {
Groups []uint `json:"groups"`
}
adminInto(t, saved, &record)
if !reflect.DeepEqual(record.Groups, sortedIDs(first, second)) {
t.Fatalf("record groups = %v", record.Groups)
}
if ids, locked := env.recordGroups(t, token, user.ID); !reflect.DeepEqual(ids, sortedIDs(first, second)) || locked[first.ID] || locked[second.ID] || len(locked) != 2 {
t.Fatalf("shown groups = %v locked %v", ids, locked)
}
save(http.StatusOK, []uint{second.ID})
pivot(second)
// A save without the field leaves the memberships alone.
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token, map[string]any{"name": "renamed", "email": user.Email})
pivot(second)
if got := env.reload(t, user.ID); got.Name == nil || *got.Name != "renamed" {
t.Fatalf("name after a save without groups = %v", got.Name)
}
// An id that is not a group, a duplicate and a value that is not a list
// are refused on the field and change nothing.
for _, bad := range []any{[]uint{second.ID, 987654321}, []uint{first.ID, first.ID}, first.ID, []string{"x"}} {
rec := save(http.StatusUnprocessableEntity, bad)
if details := adminDecode(t, rec).Error.Details; len(details["groups"]) == 0 {
t.Fatalf("refusal of %v has no detail on groups: %s", bad, rec.Body.String())
}
pivot(second)
}
// The plain relation name of the model is not a way around the field.
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token, map[string]any{
"name": "renamed", "email": user.Email, "Groups": []map[string]any{{"id": first.ID}}, "users_groups": []uint{first.ID},
})
pivot(second)
// The user API payload still answers an empty list (D-08), although the
// user is a member of a group.
status, userToken := env.userLogin(t, user.Email, "correct-horse")
if status != http.StatusOK {
t.Fatalf("user login = %d", status)
}
fetch := env.call(t, http.MethodGet, "/_user/api/v1/fetch", userToken, nil)
var body struct {
User map[string]any `json:"user"`
}
if err := json.Unmarshal(fetch.Body.Bytes(), &body); err != nil || fetch.Code != http.StatusOK {
t.Fatalf("fetch = %d %s (%v)", fetch.Code, fetch.Body.String(), err)
}
if groups, ok := body.User["groups"].([]any); !ok || len(groups) != 0 {
t.Fatalf("user payload groups = %v", body.User["groups"])
}
// Clearing the field removes every membership.
save(http.StatusOK, []uint{})
pivot()
// A create with the field writes the memberships of the new user.
const password = "groups-password-1"
created := env.expect(t, http.StatusCreated, http.MethodPost, adminAPI(adminUsersPath), token, map[string]any{
"name": "Created", "email": "groups-created-" + stamp + "@example.test",
"password": password, "password_confirmation": password, "send_invite": false,
"groups": []uint{first.ID},
})
if got := env.groupIDs(t, createdID(t, created)); !reflect.DeepEqual(got, []uint{first.ID}) {
t.Fatalf("users_groups of the created user = %v", got)
}
// A refused create leaves no user behind.
refusedEmail := "groups-refused-" + stamp + "@example.test"
env.expect(t, http.StatusUnprocessableEntity, http.MethodPost, adminAPI(adminUsersPath), token, map[string]any{
"name": "Refused", "email": refusedEmail, "password": password, "password_confirmation": password, "send_invite": false,
"groups": []uint{987654321},
})
var refused int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM users WHERE email = ?`, refusedEmail).Scan(&refused).Error; err != nil || refused != 0 {
t.Fatalf("a refused create left %d users (%v)", refused, err)
}
}
// TestAdminPrivilegedGroups covers threat T-12-18 as revisited by D-04 to
// D-07: golem15.users.access_users changes ordinary memberships, and adding
// or removing a privileged group additionally needs
// golem15.users.manage_privileged_groups, on create and on update. It also
// ties the field to the takeover guard (D-30).
func TestAdminPrivilegedGroups(t *testing.T) {
env := newAdminEnv(t)
limited := env.admin(t, permAccessUsers)
manager := env.admin(t, permAccessUsers, permManagePrivileged)
stamp := adminStamp()
// The migrations seed only guest and registered; the default privileged
// list is [admin].
adminGroup := env.seedGroup(t, "Admins "+stamp, "admin")
ordinaryCode := "ordinary-" + stamp
ordinary := env.seedGroup(t, "Ordinary "+stamp, ordinaryCode)
uncoded := env.seedGroup(t, "Uncoded "+stamp, "")
// A code that differs from a privileged one only by case is ordinary.
upper := env.seedGroup(t, "Upper "+stamp, "ADMIN")
isAdmin := func(e *adminEnv, userID uint) bool {
t.Helper()
held, err := classes.HasGroupCode(t.Context(), e.gdb, userID, "admin")
if err != nil {
t.Fatal(err)
}
return held
}
put := func(e *adminEnv, status int, token string, user *models.User, extra map[string]any) *httptest.ResponseRecorder {
t.Helper()
body := map[string]any{"name": "kept", "email": user.Email}
for key, value := range extra {
body[key] = value
}
return e.expect(t, status, http.MethodPut, userPath(user.ID, ""), token, body)
}
assertRefused := func(rec *httptest.ResponseRecorder) {
t.Helper()
answer := adminDecode(t, rec)
if answer.Error.Code != "forbidden" || answer.Error.Message != privilegedGroupForbidden {
t.Fatalf("refusal = %s", rec.Body.String())
}
if got := answer.Error.Details["groups"]; len(answer.Error.Details) != 1 || len(got) != 1 || got[0] != privilegedGroupForbidden {
t.Fatalf("refusal details = %v", answer.Error.Details)
}
}
pivot := func(e *adminEnv, user *models.User, want ...*models.UserGroup) {
t.Helper()
if got := e.groupIDs(t, user.ID); !reflect.DeepEqual(got, sortedIDs(want...)) {
t.Fatalf("users_groups of %d = %v, want %v", user.ID, got, sortedIDs(want...))
}
}
unchanged := func(original *models.User) {
t.Helper()
got := env.reload(t, original.ID)
if got == nil || got.Email != original.Email || !reflect.DeepEqual(got.Name, original.Name) ||
got.Password != original.Password || !reflect.DeepEqual(got.OrganisationID, original.OrganisationID) {
t.Fatalf("user %d changed: %+v", original.ID, got)
}
}
// Without the permission the privileged group is flagged locked among the
// options; a group without a code and one whose code differs by case are
// not. With the permission nothing is locked.
if options := env.groupOptions(t, limited, stamp); len(options) != 4 || !options[adminGroup.ID] || options[ordinary.ID] || options[uncoded.ID] || options[upper.ID] {
t.Fatalf("options without the permission = %v", options)
}
if options := env.groupOptions(t, manager, stamp); len(options) != 4 || options[adminGroup.ID] || options[ordinary.ID] || options[uncoded.ID] || options[upper.ID] {
t.Fatalf("options with the permission = %v", options)
}
// Adding the privileged group on update is refused as a whole: the name
// in the same body is not saved and the pivot is unchanged.
target := env.seedUser(t, "target", nil)
env.join(t, target, ordinary)
if isAdmin(env, target.ID) {
t.Fatal("the target starts as a site admin")
}
assertRefused(put(env, http.StatusForbidden, limited, target, map[string]any{"name": "Promoted", "groups": []uint{ordinary.ID, adminGroup.ID}}))
pivot(env, target, ordinary)
unchanged(target)
if isAdmin(env, target.ID) {
t.Fatal("a refused save made a site admin")
}
// The privileged group alone, replacing the ordinary one, is refused too.
assertRefused(put(env, http.StatusForbidden, limited, target, map[string]any{"groups": []uint{adminGroup.ID}}))
pivot(env, target, ordinary)
// Removing it from a member is refused: by leaving it out, and by
// clearing the field.
member := env.seedUser(t, "member", nil)
env.join(t, member, adminGroup, ordinary)
for _, groups := range [][]uint{{ordinary.ID}, {}} {
assertRefused(put(env, http.StatusForbidden, limited, member, map[string]any{"name": "Demoted", "groups": groups}))
pivot(env, member, adminGroup, ordinary)
unchanged(member)
if !isAdmin(env, member.ID) {
t.Fatal("a refused save removed a site admin")
}
}
// The member's privileged label is flagged locked for the limited admin
// and not for the manager.
if ids, locked := env.recordGroups(t, limited, member.ID); !reflect.DeepEqual(ids, sortedIDs(adminGroup, ordinary)) || !locked[adminGroup.ID] || locked[ordinary.ID] {
t.Fatalf("member groups for the limited admin = %v locked %v", ids, locked)
}
if _, locked := env.recordGroups(t, manager, member.ID); locked[adminGroup.ID] || locked[ordinary.ID] {
t.Fatalf("member groups for the manager are locked: %v", locked)
}
// Creating a user who is already in the privileged group is refused and
// leaves no user row.
const password = "privileged-password-1"
create := func(token, email string, groups []uint) *httptest.ResponseRecorder {
t.Helper()
return env.call(t, http.MethodPost, adminAPI(adminUsersPath), token, map[string]any{
"name": "Created", "email": email, "password": password, "password_confirmation": password, "send_invite": false,
"groups": groups,
})
}
refusedEmail := "born-admin-" + stamp + "@example.test"
rec := create(limited, refusedEmail, []uint{adminGroup.ID, ordinary.ID})
if rec.Code != http.StatusForbidden {
t.Fatalf("create with a privileged group = %d %s", rec.Code, rec.Body.String())
}
assertRefused(rec)
var born int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM users WHERE email = ?`, refusedEmail).Scan(&born).Error; err != nil || born != 0 {
t.Fatalf("a refused create left %d users (%v)", born, err)
}
// Ordinary changes need only the users permission, also on a member of
// the privileged group as long as that membership is sent back as it is;
// a group without a code and a case variant are ordinary.
put(env, http.StatusOK, limited, member, map[string]any{"groups": []uint{adminGroup.ID, uncoded.ID, upper.ID}})
pivot(env, member, adminGroup, uncoded, upper)
put(env, http.StatusOK, limited, target, map[string]any{"groups": []uint{uncoded.ID}})
pivot(env, target, uncoded)
put(env, http.StatusOK, limited, target, map[string]any{"groups": []uint{}})
pivot(env, target)
if isAdmin(env, target.ID) || !isAdmin(env, member.ID) {
t.Fatal("ordinary changes moved the site-admin membership")
}
// With the permission every refused request succeeds.
put(env, http.StatusOK, manager, target, map[string]any{"groups": []uint{ordinary.ID, adminGroup.ID}})
pivot(env, target, ordinary, adminGroup)
if !isAdmin(env, target.ID) {
t.Fatal("the manager could not add the privileged group")
}
put(env, http.StatusOK, manager, target, map[string]any{"groups": []uint{ordinary.ID}})
pivot(env, target, ordinary)
put(env, http.StatusOK, manager, member, map[string]any{"groups": []uint{}})
pivot(env, member)
if isAdmin(env, target.ID) || isAdmin(env, member.ID) {
t.Fatal("the manager could not remove the privileged group")
}
rec = create(manager, "born-admin-ok-"+stamp+"@example.test", []uint{adminGroup.ID})
if rec.Code != http.StatusCreated {
t.Fatalf("manager create with a privileged group = %d %s", rec.Code, rec.Body.String())
}
if bornID := createdID(t, rec); !isAdmin(env, bornID) {
t.Fatal("the manager's create did not write the privileged membership")
}
// D-30: the takeover guard follows the membership this field writes. No
// row is inserted into users_groups directly here.
guarded := env.seedUser(t, "guarded", nil)
newEmail := "guarded-new-" + stamp + "@example.test"
put(env, http.StatusOK, manager, guarded, map[string]any{"groups": []uint{adminGroup.ID}})
rec = env.expect(t, http.StatusForbidden, http.MethodPut, userPath(guarded.ID, ""), limited, map[string]any{"name": "kept", "email": newEmail})
if answer := adminDecode(t, rec); answer.Error.Message != privilegedMemberForbidden || len(answer.Error.Details["email"]) != 1 {
t.Fatalf("takeover refusal = %s", rec.Body.String())
}
if got := env.reload(t, guarded.ID); got.Email != guarded.Email {
t.Fatalf("a refused takeover changed the email to %q", got.Email)
}
put(env, http.StatusOK, manager, guarded, map[string]any{"groups": []uint{}})
env.expect(t, http.StatusOK, http.MethodPut, userPath(guarded.ID, ""), limited, map[string]any{"name": "kept", "email": newEmail})
if got := env.reload(t, guarded.ID); got.Email != newEmail {
t.Fatalf("email after the membership was removed = %q", got.Email)
}
// The privileged list is config, read per request. With the ordinary
// group's code in it, that group is the locked one and admin is not.
moved := newAdminEnv(t, func(cfg *compass.Config) {
if err := cfg.Set("golem15.user.privileged_groups", []string{ordinaryCode}); err != nil {
t.Fatal(err)
}
})
movedLimited := moved.admin(t, permAccessUsers)
if options := moved.groupOptions(t, movedLimited, stamp); len(options) != 4 || options[adminGroup.ID] || !options[ordinary.ID] || options[uncoded.ID] {
t.Fatalf("options under the moved list = %v", options)
}
put(moved, http.StatusOK, movedLimited, member, map[string]any{"groups": []uint{adminGroup.ID}})
pivot(moved, member, adminGroup)
assertRefused(put(moved, http.StatusForbidden, movedLimited, member, map[string]any{"groups": []uint{adminGroup.ID, ordinary.ID}}))
pivot(moved, member, adminGroup)
// target is in the ordinary group, which is now the privileged one.
assertRefused(put(moved, http.StatusForbidden, movedLimited, target, map[string]any{"groups": []uint{}}))
pivot(moved, target, ordinary)
// An empty list means no group is privileged: nothing is locked.
open := newAdminEnv(t, func(cfg *compass.Config) {
if err := cfg.Set("golem15.user.privileged_groups", []string{}); err != nil {
t.Fatal(err)
}
})
openLimited := open.admin(t, permAccessUsers)
for id, locked := range open.groupOptions(t, openLimited, stamp) {
if locked {
t.Fatalf("group %s is locked although no code is privileged", strconv.FormatUint(uint64(id), 10))
}
}
// D-06: the group's code carries the privilege, so creating a group with
// a privileged code, changing a code to or from one, and deleting a
// privileged group need the extra permission on the User Groups screen.
// The harness database is shared and may hold several groups coded
// admin, so the matrix runs on two codes of its own next to admin.
priv, second := "priv-"+stamp, "priv2-"+stamp
coded := newAdminEnv(t, func(cfg *compass.Config) {
if err := cfg.Set("golem15.user.privileged_groups", []string{"admin", priv, second}); err != nil {
t.Fatal(err)
}
})
groupsOnly := coded.admin(t, permAccessGroups)
groupsManager := coded.admin(t, permAccessGroups, permManagePrivileged)
privGroup := coded.seedGroup(t, "Privileged "+stamp, priv)
plainCode := "plain-" + stamp
plainGroup := coded.seedGroup(t, "Plain "+stamp, plainCode)
holder := coded.seedUser(t, "holder", nil)
coded.join(t, holder, privGroup, plainGroup)
holds := func(code string) bool {
t.Helper()
held, err := classes.HasGroupCode(t.Context(), coded.gdb, holder.ID, code)
if err != nil {
t.Fatal(err)
}
return held
}
refusedCode := func(rec *httptest.ResponseRecorder) {
t.Helper()
if rec.Code != http.StatusForbidden {
t.Fatalf("status = %d, want 403: %s", rec.Code, rec.Body.String())
}
answer := adminDecode(t, rec)
if answer.Error.Code != "forbidden" || answer.Error.Message != privilegedGroupCodeForbidden {
t.Fatalf("refusal = %s", rec.Body.String())
}
if got := answer.Error.Details["code"]; len(answer.Error.Details) != 1 || len(got) != 1 || got[0] != privilegedGroupCodeForbidden {
t.Fatalf("refusal details = %v", answer.Error.Details)
}
}
sameGroup := func(id uint, name, code string) {
t.Helper()
got := coded.group(t, id)
if got == nil || got.Name != name || got.Code == nil || *got.Code != code {
t.Fatalf("group %d = %+v, want %s (%s)", id, got, name, code)
}
}
codeCount := func(code string) int64 {
t.Helper()
var n int64
if err := coded.gdb.Raw(`SELECT COUNT(*) FROM user_groups WHERE code = ?`, code).Scan(&n).Error; err != nil {
t.Fatal(err)
}
return n
}
groupPut := func(token string, id uint, body map[string]any) *httptest.ResponseRecorder {
t.Helper()
return coded.call(t, http.MethodPut, groupPath(id), token, body)
}
// Without the permission each of the four is refused and changes nothing.
refusedCode(coded.call(t, http.MethodPost, adminAPI(adminGroupsPath), groupsOnly, map[string]any{"name": "Second " + stamp, "code": second}))
if codeCount(second) != 0 {
t.Fatal("a refused create left a privileged group")
}
refusedCode(groupPut(groupsOnly, plainGroup.ID, map[string]any{"name": "Promoted " + stamp, "code": second}))
sameGroup(plainGroup.ID, "Plain "+stamp, plainCode)
refusedCode(groupPut(groupsOnly, privGroup.ID, map[string]any{"name": "Demoted " + stamp, "code": "demoted-" + stamp}))
sameGroup(privGroup.ID, "Privileged "+stamp, priv)
// From one privileged code to another is a change of a privileged code.
refusedCode(groupPut(groupsOnly, privGroup.ID, map[string]any{"name": "Privileged " + stamp, "code": second}))
sameGroup(privGroup.ID, "Privileged "+stamp, priv)
refusedCode(coded.call(t, http.MethodDelete, groupPath(privGroup.ID), groupsOnly, nil))
sameGroup(privGroup.ID, "Privileged "+stamp, priv)
pivot(coded, holder, privGroup, plainGroup)
if !holds(priv) || holds(second) {
t.Fatal("a refused group change moved the privilege")
}
// The default code admin is protected the same way, and a group without
// a code cannot be given a privileged one.
refusedCode(groupPut(groupsOnly, adminGroup.ID, map[string]any{"name": "Admins " + stamp, "code": "was-admin-" + stamp}))
refusedCode(coded.call(t, http.MethodDelete, groupPath(adminGroup.ID), groupsOnly, nil))
sameGroup(adminGroup.ID, "Admins "+stamp, "admin")
refusedCode(groupPut(groupsOnly, uncoded.ID, map[string]any{"name": "Uncoded " + stamp, "code": second}))
if got := coded.group(t, uncoded.ID); got == nil || got.Code != nil {
t.Fatalf("the uncoded group after a refused save = %+v", got)
}
// Everything else on a privileged group needs only the groups
// permission: its name, description and frontend permissions, with the
// code sent back as it is.
if rec := groupPut(groupsOnly, privGroup.ID, map[string]any{"name": "Privileged renamed " + stamp, "code": priv, "description": "Kept code", "permissions": map[string]int{}}); rec.Code != http.StatusOK {
t.Fatalf("name-only update of a privileged group = %d %s", rec.Code, rec.Body.String())
}
sameGroup(privGroup.ID, "Privileged renamed "+stamp, priv)
// Ordinary groups, a case variant of a privileged code included, are
// re-coded and deleted freely.
if rec := groupPut(groupsOnly, plainGroup.ID, map[string]any{"name": "Plain " + stamp, "code": "plain2-" + stamp}); rec.Code != http.StatusOK {
t.Fatalf("ordinary re-code = %d %s", rec.Code, rec.Body.String())
}
plainCode = "plain2-" + stamp
if rec := groupPut(groupsOnly, uncoded.ID, map[string]any{"name": "Uncoded " + stamp, "code": "coded-" + stamp}); rec.Code != http.StatusOK {
t.Fatalf("first code of an uncoded group = %d %s", rec.Code, rec.Body.String())
}
if rec := coded.call(t, http.MethodDelete, groupPath(upper.ID), groupsOnly, nil); rec.Code != http.StatusOK || coded.group(t, upper.ID) != nil {
t.Fatalf("delete of the ADMIN group = %d %s", rec.Code, rec.Body.String())
}
// With the permission all four succeed.
created := coded.call(t, http.MethodPost, adminAPI(adminGroupsPath), groupsManager, map[string]any{"name": "Second " + stamp, "code": second})
if created.Code != http.StatusCreated || codeCount(second) != 1 {
t.Fatalf("manager create of a privileged group = %d %s", created.Code, created.Body.String())
}
if rec := groupPut(groupsManager, privGroup.ID, map[string]any{"name": "Privileged renamed " + stamp, "code": "freed-" + stamp}); rec.Code != http.StatusOK {
t.Fatalf("manager re-code from a privileged code = %d %s", rec.Code, rec.Body.String())
}
if holds(priv) {
t.Fatal("the holder kept the privilege after the group lost its code")
}
if rec := groupPut(groupsManager, plainGroup.ID, map[string]any{"name": "Plain " + stamp, "code": priv}); rec.Code != http.StatusOK {
t.Fatalf("manager re-code to a privileged code = %d %s", rec.Code, rec.Body.String())
}
if !holds(priv) {
t.Fatal("the holder did not gain the privilege with the group's new code")
}
if rec := coded.call(t, http.MethodDelete, groupPath(plainGroup.ID), groupsManager, nil); rec.Code != http.StatusOK || coded.group(t, plainGroup.ID) != nil {
t.Fatalf("manager delete of a privileged group = %d %s", rec.Code, rec.Body.String())
}
pivot(coded, holder, privGroup)
if holds(priv) || coded.reload(t, holder.ID) == nil {
t.Fatal("the delete of the privileged group left the privilege or removed the member")
}
}

274
admin_registration_test.go Normal file
View File

@@ -0,0 +1,274 @@
package user
import (
"io/fs"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"testing"
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/party"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"git.golem15.com/golem15/summercms/modules/surf"
)
// langKey matches one complete phrase key of the plugin.
var langKey = regexp.MustCompile(`golem15\.user::lang\.[a-z0-9_]+(\.[a-z0-9_]+)+`)
// TestAdminRegistration pins what the plugin registers for the admin: the
// permission catalog, the navigation tree, the embedded admin files and the
// phrase keys they and the controllers name, in English and Polish.
func TestAdminRegistration(t *testing.T) {
plugin := &Plugin{}
// The seven permission codes, each on the plugin's tab.
var codes []string
for _, permission := range plugin.Permissions() {
codes = append(codes, permission.Code)
if permission.Tab != "golem15.user::lang.plugin.tab" || !strings.HasPrefix(permission.Label, "golem15.user::lang.plugin.") {
t.Fatalf("permission %+v is not on the plugin tab", permission)
}
}
wantCodes := []string{
"golem15.users.access_users", "golem15.users.access_groups", "golem15.users.access_settings",
"golem15.users.impersonate_user", "golem15.users.manage_privileged_groups",
"golem15.users.manage_backend_links", "golem15.users.reset_two_factor",
}
if !reflect.DeepEqual(codes, wantCodes) {
t.Fatalf("permission codes = %v, want %v", codes, wantCodes)
}
// The privileged-groups, backend-links and reset-2FA permissions have no
// default role: nobody holds them until they are granted on purpose.
for _, permission := range plugin.Permissions() {
if privileged := permission.Code == permManagePrivileged || permission.Code == permManageBackendLinks || permission.Code == permResetTwoFactor; privileged != (len(permission.Roles) == 0) {
t.Fatalf("permission %s has roles %v", permission.Code, permission.Roles)
}
}
// The navigation: one main item with three side items, each behind the
// permission of its screen.
nav := plugin.Navigation()
if len(nav) != 1 || nav[0].Code != "user" || nav[0].Order != 555 || nav[0].Controller != "golem15.user.users" ||
!reflect.DeepEqual(nav[0].Permissions, []string{"golem15.users.*"}) {
t.Fatalf("navigation = %+v", nav)
}
type side struct{ code, controller, permission string }
var sides []side
for _, item := range nav[0].SideMenu {
if len(item.Permissions) != 1 || item.Icon == "" || len(item.SideMenu) != 0 {
t.Fatalf("side item %+v", item)
}
sides = append(sides, side{item.Code, item.Controller, item.Permissions[0]})
}
if want := []side{
{"users", "golem15.user.users", permAccessUsers},
{"usergroups", "golem15.user.usergroups", permAccessGroups},
{"organisations", "golem15.user.organisations", permAccessUsers},
}; !reflect.DeepEqual(sides, want) {
t.Fatalf("side menu = %v, want %v", sides, want)
}
// The controllers: three, each naming a config directory that exists in
// the embedded files, each behind the permission its side item names.
ctls := controllers.AdminControllers(func() *backpack.App { return nil })
if len(ctls) != 3 {
t.Fatalf("controllers = %d", len(ctls))
}
required := map[string]string{}
for _, ctl := range ctls {
permissioned, ok := ctl.(pact.AdminPermissioned)
if !ok || len(permissioned.RequiredPermissions()) != 1 {
t.Fatalf("controller %s declares no single permission", ctl.ID())
}
required[ctl.ID()] = permissioned.RequiredPermissions()[0]
if _, err := fs.Stat(plugin.AdminFS(), ctl.ConfigDir()+"/config_list.yaml"); err != nil {
t.Fatalf("controller %s: %v", ctl.ID(), err)
}
}
for _, item := range sides {
if required[item.controller] != item.permission {
t.Fatalf("side item %s asks for %s, its controller for %s", item.code, item.permission, required[item.controller])
}
}
// Every embedded admin file is readable and not empty.
wantFiles := []string{
"controllers/organisations/config_form.yaml", "controllers/organisations/config_list.yaml", "controllers/organisations/config_relation.yaml",
"controllers/usergroups/config_form.yaml", "controllers/usergroups/config_list.yaml",
"controllers/users/_hint.htm", "controllers/users/config_filter.yaml", "controllers/users/config_form.yaml", "controllers/users/config_list.yaml",
"models/organisation/columns.yaml", "models/organisation/fields.yaml",
"models/user/columns.yaml", "models/user/fields.yaml",
"models/usergroup/columns.yaml", "models/usergroup/fields.yaml",
}
var files []string
keys := map[string]string{}
collect := func(source string, text []byte) {
for _, key := range langKey.FindAllString(string(text), -1) {
if _, seen := keys[key]; !seen {
keys[key] = source
}
}
}
err := fs.WalkDir(plugin.AdminFS(), ".", func(name string, entry fs.DirEntry, err error) error {
if err != nil || entry.IsDir() {
return err
}
data, err := fs.ReadFile(plugin.AdminFS(), name)
if err != nil {
return err
}
if len(data) == 0 {
t.Errorf("embedded admin file %s is empty", name)
}
files = append(files, name)
collect(name, data)
return nil
})
if err != nil {
t.Fatal(err)
}
sort.Strings(files)
if !reflect.DeepEqual(files, wantFiles) {
t.Fatalf("embedded admin files = %v, want %v", files, wantFiles)
}
// Every admin file on disk is embedded: a new YAML file that is not in the
// embed list would be missing from the binary.
for _, pattern := range []string{"controllers/*/*.yaml", "controllers/*/_*.htm", "models/*/*.yaml"} {
onDisk, err := filepath.Glob(pattern)
if err != nil {
t.Fatal(err)
}
for _, name := range onDisk {
if _, err := fs.Stat(plugin.AdminFS(), filepath.ToSlash(name)); err != nil {
t.Errorf("%s is on disk and not embedded", name)
}
}
}
// The phrase keys of the Go side: literal keys in the sources, and the
// labels, confirms and messages the registered actions name.
for _, pattern := range []string{"*.go", "controllers/*.go", "classes/*.go"} {
sources, err := filepath.Glob(pattern)
if err != nil {
t.Fatal(err)
}
for _, name := range sources {
if strings.HasSuffix(name, "_test.go") {
continue
}
data, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
}
collect(name, data)
}
}
for _, permission := range plugin.Permissions() {
keys[permission.Label], keys[permission.Tab] = "permissions", "permissions"
}
keys[nav[0].Label] = "navigation"
for _, item := range nav[0].SideMenu {
keys[item.Label] = "navigation"
}
for _, ctl := range ctls {
if bulk, ok := ctl.(pact.HasAdminBulkActions); ok {
for _, action := range bulk.AdminBulkActions() {
keys[action.Label], keys[action.Confirm] = "bulk action "+action.Name, "bulk action "+action.Name
keys["golem15.user::lang.users."+action.Name+"_selected_success"] = "bulk action " + action.Name
}
}
if record, ok := ctl.(pact.HasAdminRecordActions); ok {
for _, action := range record.AdminRecordActions() {
keys[action.Label], keys[action.Confirm] = "record action "+action.Name, "record action "+action.Name
}
}
}
for _, key := range []string{"activated_success", "unbanned_success", "unsuspend_success"} {
keys["golem15.user::lang.users."+key] = "record action messages"
}
if len(keys) < 80 {
t.Fatalf("only %d phrase keys were collected", len(keys))
}
env := newAdminEnv(t)
tr, ok := env.app.Lookup[*phrasebook.Translator]()
if !ok {
t.Fatal("no translator")
}
var missing []string
for key, source := range keys {
if !strings.HasPrefix(key, "golem15.user::lang.") {
t.Errorf("%s names %q, which is not a phrase key of the plugin", source, key)
continue
}
for _, locale := range []string{"en", "pl"} {
if text := tr.GetIn(locale, key, nil); text == "" || text == key || strings.Contains(text, "::lang.") {
missing = append(missing, locale+" "+key+" ("+source+")")
}
}
}
sort.Strings(missing)
if len(missing) > 0 {
t.Fatalf("%d phrase keys do not resolve:\n%s", len(missing), strings.Join(missing, "\n"))
}
// The two locales carry the same keys.
en, pl := tr.Bundle("en", "golem15.user::lang"), tr.Bundle("pl", "golem15.user::lang")
if len(en) == 0 || len(en) != len(pl) {
t.Fatalf("en has %d phrases, pl has %d", len(en), len(pl))
}
for key := range en {
if _, ok := pl[key]; !ok {
t.Errorf("pl lacks %s", key)
}
}
}
// TestAdminNeedsSecret: a host application that loads the plugin mounts the
// admin API, so assembling its routes without admin.jwt.secret fails loudly
// instead of serving the screens unauthenticated.
func TestAdminNeedsSecret(t *testing.T) {
gdb, sqlDB := adminHarnessDB(t)
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: user-no-admin-secret\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{
"SUMMER_ENV=development",
"SUMMER_GOLEM15__USER__JWT__SECRET=" + sessionSecret,
}})
if err != nil {
t.Fatal(err)
}
// Everything else the router needs is set, so the secret is the one thing
// missing.
for key, value := range map[string]any{
"http.body_limits.default_bytes": 1048576,
"http.body_limits.upload_bytes": 8388608,
} {
if err := cfg.Set(key, value); err != nil {
t.Fatal(err)
}
}
app := backpack.New(cfg)
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
t.Fatal(err)
}
plugins, err := party.Activate(app, []string{"golem15.user"})
if err != nil {
t.Fatal(err)
}
if _, err := surf.Assemble(app, plugins); err == nil || !strings.Contains(err.Error(), "admin.jwt.secret") {
t.Fatalf("assembling without the admin secret: %v, want an error naming admin.jwt.secret", err)
}
// The registered plugin value now points at this app: boot a working
// environment again for whatever runs next.
newAdminEnv(t)
}

437
admin_users_edge_test.go Normal file
View File

@@ -0,0 +1,437 @@
package user
import (
"context"
"database/sql"
"errors"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"gorm.io/gorm"
)
// TestAdminUsersGroupFilterValue (D-23): the groups filter takes a group id.
// A value that is not one matches nobody (or is refused with 422 by the
// framework); it must not reach the database as it is, where a non-numeric
// text fails the whole list with a 500.
func TestAdminUsersGroupFilterValue(t *testing.T) {
env := newAdminEnv(t)
token := env.admin(t, permAccessUsers)
marker := "gfilter" + adminStamp()
group := env.seedGroup(t, "Filter "+marker, "")
member := env.seedUser(t, marker, nil)
other := env.seedUser(t, marker, nil)
env.join(t, member, group)
gid := strconv.FormatUint(uint64(group.ID), 10)
if page := env.users(t, token, "search="+marker+"&filter[groups]="+gid); page.Total != 1 || !page.has(member.ID) || page.has(other.ID) {
t.Fatalf("group filter = %s", page.Raw)
}
for _, value := range []string{"abc", "1%20OR%201=1", "-1", "0", "1.5", "99999999999999999999", gid + "x"} {
rec := env.call(t, http.MethodGet, adminAPI(adminUsersPath)+"?search="+marker+"&filter[groups]="+value, token, nil)
// The framework refuses a value it cannot read as a scope argument
// with 422; whatever it lets through must list nobody.
if rec.Code == http.StatusUnprocessableEntity {
continue
}
if rec.Code != http.StatusOK {
t.Fatalf("filter[groups]=%s answers %d: %s", value, rec.Code, rec.Body.String())
}
var rows []map[string]any
adminInto(t, rec, &rows)
if len(rows) != 0 {
t.Fatalf("filter[groups]=%s lists %d users, want none", value, len(rows))
}
}
// The list without the filter is unaffected.
if page := env.users(t, token, "search="+marker); page.Total != 2 {
t.Fatalf("unfiltered list = %s", page.Raw)
}
}
// adminControllerSet is the plugin's three admin controllers built on one app
// accessor, by controller id.
type adminControllerSet map[string]pact.AdminController
func adminControllersOn(app func() *backpack.App) adminControllerSet {
out := adminControllerSet{}
for _, ctl := range controllers.AdminControllers(app) {
out[ctl.ID()] = ctl
}
return out
}
// bareApp is a booted application value without a database handle, a bucket
// or a translator.
func bareApp(t *testing.T) *backpack.App {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: user-bare\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development"}})
if err != nil {
t.Fatal(err)
}
return backpack.New(cfg)
}
// brokenApp is an application whose database handle fails every query: its
// connection pool is closed.
func brokenApp(t *testing.T) (*backpack.App, *gorm.DB) {
t.Helper()
adminHarnessDB(t)
u, err := url.Parse(sessionDSN)
if err != nil {
t.Fatal(err)
}
u.Path = "/user_admin"
db, err := sql.Open("pgx", u.String())
if err != nil {
t.Fatal(err)
}
gdb, err := lagoon.Use(t.Context(), db)
if err != nil {
t.Fatal(err)
}
app := bareApp(t)
if err := lagoon.Publish(app, db, gdb); err != nil {
t.Fatal(err)
}
if err := db.Close(); err != nil {
t.Fatal(err)
}
return app, gdb
}
// wantPlainError asserts that err is an ordinary error: the framework answers
// it as the opaque 500. A ForbiddenError or a ValidationError would be shown
// to the administrator.
func wantPlainError(t *testing.T, what string, err error) {
t.Helper()
var forbidden *cabana.ForbiddenError
var invalid *cabana.ValidationError
if err == nil || errors.As(err, &forbidden) || errors.As(err, &invalid) {
t.Fatalf("%s: err = %v, want a plain error", what, err)
}
}
// TestAdminUsersControllerGuards drives the Users controller directly, the
// way the framework calls it, on the inputs the HTTP tests cannot produce: a
// record of another type, an application that is not booted, one without a
// database handle and one whose database fails. Each ends in a plain error
// (the opaque 500) or the documented empty answer; none passes a guard.
func TestAdminUsersControllerGuards(t *testing.T) {
ctx := context.Background()
notUser := &models.UserGroup{}
var nilUser *models.User
user := &models.User{ID: 987654001, Email: "guards@example.test"}
sets := map[string]adminControllerSet{
"no accessor": adminControllersOn(nil),
"not booted": adminControllersOn(func() *backpack.App { return nil }),
"no database": adminControllersOn(func() *backpack.App { return bareApp(t) }),
"a failing handle": nil,
"the live database": nil,
}
broken, brokenDB := brokenApp(t)
sets["a failing handle"] = adminControllersOn(func() *backpack.App { return broken })
env := newAdminEnv(t)
sets["the live database"] = adminControllersOn(func() *backpack.App { return env.app })
for name, set := range sets {
t.Run(name, func(t *testing.T) {
ctl := set["golem15.user.users"]
live := name == "the live database"
// Records of another type and nil records.
for _, record := range []any{notUser, nilUser, nil} {
wantPlainError(t, "FormBeforeUpdate", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, record))
wantPlainError(t, "FormBeforeCreate", ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, record))
wantPlainError(t, "FormAfterCreate", ctl.(pact.FormAfterCreate).FormAfterCreate(ctx, record))
wantPlainError(t, "FormBeforeDelete", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, record))
wantPlainError(t, "FormAfterDelete", ctl.(pact.FormAfterDelete).FormAfterDelete(ctx, record))
_, err := ctl.(pact.ListRowStates).ListRowStates(ctx, env.gdb, []any{record})
wantPlainError(t, "ListRowStates", err)
editor := ctl.(cabana.PermissionEditorProvider)
_, err = editor.AdminPermissionValues(ctx, "permissions", record)
wantPlainError(t, "AdminPermissionValues", err)
wantPlainError(t, "AdminSetPermissionValues", editor.AdminSetPermissionValues(ctx, "permissions", record, map[string]int{"a": 1}))
for _, action := range ctl.(pact.HasAdminBulkActions).AdminBulkActions() {
_, err := action.Run(ctx, pact.AdminBulkActionInput{Records: []any{record}})
wantPlainError(t, "bulk "+action.Name, err)
}
for _, action := range ctl.(pact.HasAdminRecordActions).AdminRecordActions() {
_, err := action.Applies(ctx, record)
wantPlainError(t, "applies "+action.Name, err)
_, err = action.Run(ctx, pact.AdminRecordActionInput{Record: record})
wantPlainError(t, "record "+action.Name, err)
}
}
// The hint of a record that is not a user is empty, never an error.
if data, err := ctl.(pact.AdminPartialData).PartialData(ctx, "hint", notUser); err != nil || !reflect.ValueOf(data).IsZero() {
t.Fatalf("hint of another record = %+v %v", data, err)
}
if _, err := ctl.(pact.AdminPartialData).PartialData(ctx, "other", user); err == nil || !strings.Contains(err.Error(), `unknown partial "other"`) {
t.Fatalf("unknown partial: %v", err)
}
// Wrong field names.
editor := ctl.(cabana.PermissionEditorProvider)
if _, err := editor.AdminPermissionOptions(ctx, "groups"); err == nil {
t.Fatal("permission options for another field")
}
if _, err := editor.AdminPermissionValues(ctx, "groups", user); err == nil {
t.Fatal("permission values for another field")
}
if err := editor.AdminSetPermissionValues(ctx, "groups", user, nil); err == nil {
t.Fatal("permission write for another field")
}
if lock, err := ctl.(cabana.RelationLockProvider).AdminRelationLocks(ctx, "organisation"); err != nil || len(lock.IDs) != 0 || lock.Message != "" {
t.Fatalf("locks of another field = %+v %v", lock, err)
}
if options := ctl.(pact.FilterOptions).FilterOptions("other"); options != nil {
t.Fatalf("options of another scope = %v", options)
}
if ctl.(pact.ListExtendQuery).ListExtendQuery(ctx, nil) != nil || ctl.(pact.FormExtendQuery).FormExtendQuery(ctx, nil) != nil {
t.Fatal("an extend query invented a handle")
}
// A bulk or record action outside a transaction never writes.
for _, action := range ctl.(pact.HasAdminBulkActions).AdminBulkActions() {
_, err := action.Run(ctx, pact.AdminBulkActionInput{Records: []any{user}})
wantPlainError(t, "bulk "+action.Name+" without a transaction", err)
}
for _, action := range ctl.(pact.HasAdminRecordActions).AdminRecordActions() {
_, err := action.Run(ctx, pact.AdminRecordActionInput{Record: user})
wantPlainError(t, "record "+action.Name+" without a transaction", err)
}
wantPlainError(t, "FormAfterDelete without a transaction", ctl.(pact.FormAfterDelete).FormAfterDelete(ctx, user))
if live {
// On a working database the same calls answer, and an update
// of a user who does not exist is an error, not a pass.
wantPlainError(t, "update of an unknown user", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, user))
if options := ctl.(pact.FilterOptions).FilterOptions(models.FilterByGroup); options == nil {
t.Fatal("no group choices on a working database")
}
if lock, err := ctl.(cabana.RelationLockProvider).AdminRelationLocks(ctx, "groups"); err != nil || lock.Message == "" {
t.Fatalf("locks without a principal = %+v %v, want the locks", lock, err)
}
return
}
// Without a working database every read that a guard depends on
// is an error: the guard never answers "not privileged".
wantPlainError(t, "FormBeforeUpdate", ctl.(pact.FormBeforeUpdate).FormBeforeUpdate(ctx, user))
wantPlainError(t, "FormBeforeCreate", ctl.(pact.FormBeforeCreate).FormBeforeCreate(ctx, user))
wantPlainError(t, "FormBeforeDelete", ctl.(pact.FormBeforeDelete).FormBeforeDelete(ctx, user))
_, err := ctl.(cabana.RelationLockProvider).AdminRelationLocks(ctx, "groups")
wantPlainError(t, "AdminRelationLocks", err)
_, err = editor.AdminPermissionOptions(ctx, "permissions")
wantPlainError(t, "AdminPermissionOptions", err)
_, err = ctl.(pact.AdminPartialData).PartialData(ctx, "hint", user)
wantPlainError(t, "PartialData", err)
for _, action := range ctl.(pact.HasAdminRecordActions).AdminRecordActions() {
if action.Name == "activate" {
continue // reads the record only
}
if action.Name == "reset_two_factor" {
// No classes.TwoFactorAdmin is published, so it reads
// nothing and is simply not offered.
if applies, err := action.Applies(ctx, user); applies || err != nil {
t.Fatalf("applies reset_two_factor without a service = %v, %v", applies, err)
}
continue
}
_, err := action.Applies(ctx, user)
wantPlainError(t, "applies "+action.Name, err)
}
if options := ctl.(pact.FilterOptions).FilterOptions(models.FilterByGroup); options != nil {
t.Fatalf("group choices without a database = %v", options)
}
if name == "a failing handle" {
_, err := ctl.(pact.ListRowStates).ListRowStates(ctx, brokenDB, []any{user})
wantPlainError(t, "ListRowStates on a failing handle", err)
}
// A principal who holds the extra permission, and a superuser,
// pass the delete guard before any query is made (D-30).
for _, principal := range []*bouncer.Principal{
{PermissionGrants: map[string]bool{permManagePrivileged: true}},
{IsSuperuser: true},
} {
if err := ctl.(pact.FormBeforeDelete).FormBeforeDelete(bouncer.WithUser(ctx, principal), user); err != nil {
t.Fatalf("delete guard for %+v: %v", principal, err)
}
if lock, err := ctl.(cabana.RelationLockProvider).AdminRelationLocks(bouncer.WithUser(ctx, principal), "groups"); err != nil || len(lock.IDs) != 0 {
t.Fatalf("locks for %+v = %+v %v", principal, lock, err)
}
}
// One who holds only the screen's permission does not.
limited := bouncer.WithUser(ctx, &bouncer.Principal{PermissionGrants: map[string]bool{permAccessUsers: true}})
wantPlainError(t, "delete guard without the extra permission", ctl.(pact.FormBeforeDelete).FormBeforeDelete(limited, user))
})
}
}
// TestAdminUsersEdge covers the remaining branches of the Users screen
// through the admin API: an unknown partial, an undeclared filter, options
// of a field that has none, search and sort, the superuser, and a membership
// query that fails while the takeover guard needs it (D-30).
func TestAdminUsersEdge(t *testing.T) {
env := newAdminEnv(t)
token := env.admin(t, permAccessUsers)
marker := "edge" + adminStamp()
surname := "Sur" + marker
first := env.seedUser(t, "a-"+marker, func(u *models.User) { u.Surname = &surname })
second := env.seedUser(t, "b-"+marker, nil)
third := env.seedUser(t, "c-"+marker, nil)
id := strconv.FormatUint(uint64(first.ID), 10)
// Partials: only the declared hint is served.
for _, name := range []string{"nope", "status", "_hint", "hint.htm", "..%2Fhint"} {
rec := env.call(t, http.MethodGet, adminAPI(adminUsersPath+"/partials/"+name+"?id="+id), token, nil)
if rec.Code != http.StatusNotFound && rec.Code != http.StatusBadRequest && rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("partial %s answers %d: %s", name, rec.Code, rec.Body.String())
}
assertNoSecret(t, rec.Body.String())
}
env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminUsersPath+"/partials/hint?id="+id), token, nil)
env.expect(t, http.StatusNotFound, http.MethodGet, adminAPI(adminUsersPath+"/partials/hint?id=987654321"), token, nil)
// Filters: an undeclared name and a malformed value are 422, never a
// query.
for _, query := range []string{
"filter[nope]=1", "filter[password]=x", "filter[activated]=maybe",
"filter[created_date]=yesterday", "filter[created_date]=2020-06-30..2020-06-01x",
} {
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminUsersPath)+"?"+query, token, nil)
}
// Options exist for the groups filter and the two relation fields only.
for _, path := range []string{
"/filters/activated/options", "/filters/created_date/options", "/filters/nope/options",
"/fields/name/options", "/fields/password/options", "/fields/permissions/options", "/fields/nope/options",
} {
rec := env.call(t, http.MethodGet, adminAPI(adminUsersPath+path), token, nil)
if rec.Code != http.StatusNotFound && rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("%s answers %d: %s", path, rec.Code, rec.Body.String())
}
}
// Search reaches the invisible surname column; sort orders both ways and
// refuses a column that is not sortable.
if page := env.users(t, token, "search="+surname); page.Total != 1 || !page.has(first.ID) {
t.Fatalf("surname search = %s", page.Raw)
}
order := func(query string) []uint {
ids := []uint{}
for _, row := range env.users(t, token, "search="+marker+"&"+query).Rows {
ids = append(ids, uint(row["id"].(float64)))
}
return ids
}
if got, want := order("sort=email&dir=asc"), []uint{first.ID, second.ID, third.ID}; !reflect.DeepEqual(got, want) {
t.Fatalf("email asc = %v, want %v", got, want)
}
if got, want := order("sort=email&dir=desc"), []uint{third.ID, second.ID, first.ID}; !reflect.DeepEqual(got, want) {
t.Fatalf("email desc = %v, want %v", got, want)
}
if got, want := order("sort=id&dir=desc"), []uint{third.ID, second.ID, first.ID}; !reflect.DeepEqual(got, want) {
t.Fatalf("id desc = %v, want %v", got, want)
}
for _, query := range []string{"sort=password", "sort=permissions", "sort=email&dir=sideways", "sort=email%3Bdrop", "per_page=2"} {
env.expect(t, http.StatusUnprocessableEntity, http.MethodGet, adminAPI(adminUsersPath)+"?"+query, token, nil)
}
// D-30: a superuser needs no extra permission for a privileged member.
code := "edgepriv-" + marker
privileged := func(cfg *compass.Config) {
if err := cfg.Set("golem15.user.privileged_groups", []string{code}); err != nil {
t.Fatal(err)
}
}
env = newAdminEnv(t, privileged)
limited := env.admin(t, permAccessUsers)
super := env.admin(t)
if err := env.gdb.Exec(`UPDATE backend_users SET is_superuser = TRUE WHERE id = (SELECT MAX(id) FROM backend_users)`).Error; err != nil {
t.Fatal(err)
}
group := env.seedGroup(t, "Edge privileged "+marker, code)
member := env.seedUser(t, "member-"+marker, nil)
env.join(t, member, group)
env.expect(t, http.StatusForbidden, http.MethodPut, userPath(member.ID, ""), limited, map[string]any{"email": "taken-" + marker + "@example.test"})
renamed := "super-" + marker + "@example.test"
env.expect(t, http.StatusOK, http.MethodPut, userPath(member.ID, ""), super, map[string]any{"email": renamed})
if got := env.reload(t, member.ID); got.Email != renamed {
t.Fatalf("superuser update: email = %s", got.Email)
}
// D-30: when the membership cannot be read, the guard does not let the
// request through. The answer is the opaque 500 and nothing changes.
before := env.reload(t, member.ID)
victim := env.seedUser(t, "victim-"+marker, nil)
rename := func(from, to string) {
t.Helper()
if err := env.gdb.Exec(`ALTER TABLE ` + from + ` RENAME TO ` + to).Error; err != nil {
t.Fatal(err)
}
}
rename("users_groups", "users_groups_away")
restored := false
restore := func() {
if !restored {
restored = true
rename("users_groups_away", "users_groups")
}
}
t.Cleanup(restore)
for what, rec := range map[string]interface {
Result() *http.Response
}{
"email change": env.call(t, http.MethodPut, userPath(member.ID, ""), limited, map[string]any{"email": "stolen-" + marker + "@example.test"}),
"password reset": env.call(t, http.MethodPut, userPath(member.ID, ""), limited, map[string]any{"password": "stolen-secret-1", "password_confirmation": "stolen-secret-1"}),
"delete": env.call(t, http.MethodDelete, userPath(member.ID, ""), limited, nil),
"bulk delete": env.bulk(t, limited, "delete", victim, member),
"ordinary delete": env.call(t, http.MethodDelete, userPath(victim.ID, ""), limited, nil),
} {
res := rec.Result()
body := make([]byte, 4096)
n, _ := res.Body.Read(body)
text := string(body[:n])
if res.StatusCode != http.StatusInternalServerError {
t.Fatalf("%s with an unreadable membership answers %d: %s", what, res.StatusCode, text)
}
if strings.Contains(text, "users_groups") || strings.Contains(strings.ToLower(text), "sqlstate") || strings.Contains(text, "relation") {
t.Fatalf("%s leaks the database error: %s", what, text)
}
}
restore()
after := env.reload(t, member.ID)
if after == nil || after.Email != before.Email || after.Password != before.Password || !reflect.DeepEqual(after.TokensValidAfter, before.TokensValidAfter) {
t.Fatalf("a failed guard changed the member: %+v", after)
}
if env.reload(t, victim.ID) == nil {
t.Fatal("a failed guard deleted a user")
}
if got := env.groupIDs(t, member.ID); !reflect.DeepEqual(got, []uint{group.ID}) {
t.Fatalf("memberships after the failed guard = %v", got)
}
if status, _ := env.userLogin(t, before.Email, "correct-horse"); status != http.StatusOK {
t.Fatalf("login with the old password = %d", status)
}
}

1513
admin_users_test.go Normal file

File diff suppressed because it is too large Load Diff

37
api_token_events_test.go Normal file
View File

@@ -0,0 +1,37 @@
package user
import (
"net/http"
"strconv"
"testing"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/pact"
)
// TestAPITokenRevokeEvent pins plan 08's token-specific MCP revocation
// (C-IN-02, user side): DELETE /tokens/{id} fires exactly one revoked
// subject event for the user carrying that TokenID, so only the sessions of
// that token end. Postgres only: skipped under -short.
func TestAPITokenRevokeEvent(t *testing.T) {
if testing.Short() {
t.Skip("Postgres")
}
env := newAdminEnv(t)
spy := env.spySubjects()
user := env.seedUser(t, "token-revoke", nil)
_, kept := env.mintUserToken(t, user, "read")
_, gone := env.mintUserToken(t, user, "read")
spy.reset()
env.expect(t, http.StatusOK, http.MethodDelete, "/_user/api/v1/tokens/"+strconv.FormatUint(uint64(gone.ID), 10), freshUserToken(t, user), nil)
spy.mu.Lock()
events := append([]pact.MCPSubjectChanged(nil), spy.events...)
spy.mu.Unlock()
want := pact.MCPSubjectChanged{Guard: classes.SubjectGuardUser, UserID: user.ID, Kind: pact.MCPSubjectRevoked, TokenID: gone.ID}
if len(events) != 1 || events[0] != want {
t.Fatalf("events = %+v, want exactly %+v", events, want)
}
if spy.hasEvent(pact.MCPSubjectChanged{Guard: classes.SubjectGuardUser, UserID: user.ID, Kind: pact.MCPSubjectRevoked, TokenID: kept.ID}) {
t.Fatal("the kept token was revoked too")
}
}

104
api_tokens_edge_test.go Normal file
View File

@@ -0,0 +1,104 @@
package user
import (
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
// TestAPITokenManagementRefusals covers the refusals of the personal API
// token routes: no application, no principal, invalid bodies, and a token
// that is not the caller's.
func TestAPITokenManagementRefusals(t *testing.T) {
app, db := sessionApp(t, "0s")
if err := app.Config.Set("golem15.user.api_tokens.prefix", "usr_"); err != nil {
t.Fatal(err)
}
owner := insertUser(t, db, "token-owner@example.test", "correct-horse")
stranger := insertUser(t, db, "token-stranger@example.test", "correct-horse")
call := func(handler http.Handler, method, body, id string, userID uint) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, "/_user/api/v1/tokens", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if id != "" {
req.SetPathValue("id", id)
}
if userID != 0 {
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: userID}))
}
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
// Without an application or a principal nothing is served.
for name, handler := range map[string]http.Handler{
"store": controllers.APITokenStore(nil), "index": controllers.APITokenIndex(nil), "destroy": controllers.APITokenDestroy(nil),
} {
if rec := call(handler, http.MethodPost, `{"name":"x"}`, "1", owner.ID); rec.Code != http.StatusInternalServerError {
t.Fatalf("%s without an application = %d", name, rec.Code)
}
}
for name, handler := range map[string]http.Handler{
"store": controllers.APITokenStore(app), "index": controllers.APITokenIndex(app), "destroy": controllers.APITokenDestroy(app),
} {
if rec := call(handler, http.MethodPost, `{"name":"x"}`, "1", 0); rec.Code != http.StatusUnauthorized {
t.Fatalf("%s without a principal = %d %s", name, rec.Code, rec.Body.String())
}
}
// Invalid bodies are 422 on the field and mint nothing.
for body, field := range map[string]string{
`{}`: "name",
`{"name":" "}`: "name",
`{"name":"` + strings.Repeat("n", 256) + `"}`: "name",
`{"name":"a","scopes":"read"}`: "scopes",
`{"name":"a","scopes":["nope"]}`: "scopes",
`{"name":"a","scopes":[1]}`: "scopes",
`{"name":"a","expires_at":"tomorrow"}`: "expires_at",
} {
rec := call(controllers.APITokenStore(app), http.MethodPost, body, "", owner.ID)
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"`+field+`"`) {
t.Fatalf("store %s = %d %s, want 422 on %s", body, rec.Code, rec.Body.String(), field)
}
}
var minted int64
if err := db.Model(&models.APIToken{}).Where("user_id = ?", owner.ID).Count(&minted).Error; err != nil || minted != 0 {
t.Fatalf("tokens after refused creates = %d err = %v", minted, err)
}
// A token with an expiry is minted; only its owner can revoke it.
created := call(controllers.APITokenStore(app), http.MethodPost, `{"name":"expiring","expires_at":"2099-01-02T03:04:05Z"}`, "", owner.ID)
if created.Code != http.StatusCreated {
t.Fatalf("create = %d %s", created.Code, created.Body.String())
}
var token models.APIToken
if err := db.Where("user_id = ?", owner.ID).First(&token).Error; err != nil || token.ExpiresAt == nil {
t.Fatalf("stored token = %+v err = %v", token, err)
}
id := strconv.FormatUint(uint64(token.ID), 10)
for _, bad := range []string{"", "0", "abc", "-1", "987654321"} {
if rec := call(controllers.APITokenDestroy(app), http.MethodDelete, "", bad, owner.ID); rec.Code != http.StatusNotFound {
t.Fatalf("destroy %q = %d %s", bad, rec.Code, rec.Body.String())
}
}
if rec := call(controllers.APITokenDestroy(app), http.MethodDelete, "", id, stranger.ID); rec.Code != http.StatusNotFound {
t.Fatalf("destroy by another user = %d %s", rec.Code, rec.Body.String())
}
if rec := call(controllers.APITokenIndex(app), http.MethodGet, "", "", stranger.ID); rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "expiring") {
t.Fatalf("another user's list = %d %s", rec.Code, rec.Body.String())
}
if rec := call(controllers.APITokenDestroy(app), http.MethodDelete, "", id, owner.ID); rec.Code != http.StatusOK {
t.Fatalf("destroy = %d %s", rec.Code, rec.Body.String())
}
if rec := call(controllers.APITokenIndex(app), http.MethodGet, "", "", owner.ID); rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "expiring") {
t.Fatalf("list after the revoke = %d %s", rec.Code, rec.Body.String())
}
}

141
avatar_url_test.go Normal file
View File

@@ -0,0 +1,141 @@
package user
import (
"context"
"crypto/md5"
"fmt"
"strconv"
"strings"
"testing"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"gocloud.dev/blob/memblob"
)
// jpegAvatar stores a real JPEG avatar for user (a system_files row and its
// blob) and returns the row.
func (e *adminEnv) jpegAvatar(t *testing.T, user *models.User) attach.File {
t.Helper()
disk := "face" + adminStamp() + ".jpg"
data := jpegBytes(t)
if err := e.bucket.WriteAll(context.Background(), attach.BlobKey(disk), data, nil); err != nil {
t.Fatal(err)
}
row := attach.File{
DiskName: disk, FileName: "face.jpg", FileSize: int64(len(data)), ContentType: "image/jpeg",
Field: models.AvatarField, AttachmentID: strconv.FormatUint(uint64(user.ID), 10), AttachmentType: user.MorphName(),
}
if err := e.gdb.Create(&row).Error; err != nil {
t.Fatal(err)
}
return row
}
func gravatarFor(email string, size int) string {
return fmt.Sprintf("//www.gravatar.com/avatar/%x?s=%d&d=mm", md5.Sum([]byte(strings.ToLower(strings.TrimSpace(email)))), size)
}
// TestAvatarURL pins classes.AvatarURL (D-05): the avatar thumbnail at the
// asked size, the file path when the thumbnail fails, the gravatar
// fallback with the size, errors only for a failing lookup, and the user
// API payload (applyAvatar) unchanged: its avatar_url is AvatarURL at 128.
func TestAvatarURL(t *testing.T) {
env := newAdminEnv(t)
ctx := t.Context()
if _, err := classes.AvatarURL(ctx, env.app, nil, 128); err == nil {
t.Fatal("a nil user must be refused")
}
// Gravatar: no app, an unsaved user, no attachment; the email is
// trimmed and lower-cased, the size is the one asked for.
plain := env.seedUser(t, "plain", func(u *models.User) { u.Email = " Mixed.Case-" + adminStamp() + "@Example.TEST " })
for _, size := range []int{32, 128, 256} {
for name, call := range map[string]func() (string, error){
"no app": func() (string, error) { return classes.AvatarURL(ctx, nil, plain, size) },
"unsaved user": func() (string, error) { return classes.AvatarURL(ctx, env.app, &models.User{Email: plain.Email}, size) },
"no attachment": func() (string, error) { return classes.AvatarURL(ctx, env.app, plain, size) },
} {
got, err := call()
if err != nil || got != gravatarFor(plain.Email, size) {
t.Fatalf("%s at %d = %q %v, want %q", name, size, got, err, gravatarFor(plain.Email, size))
}
}
}
if gravatarFor(plain.Email, 1) != gravatarFor(strings.ToLower(strings.TrimSpace(plain.Email)), 1) {
t.Fatal("the gravatar hash is not of the normalised email")
}
// A file avatar: the thumbnail at size by size, mode auto.
withFile := env.seedUser(t, "withfile", nil)
row := env.jpegAvatar(t, withFile)
thumb, err := classes.AvatarURL(ctx, env.app, withFile, 64)
want := attach.ThumbFilename(row.ID, 64, 64, 0, 0, "auto", "jpg")
if err != nil || !strings.HasSuffix(thumb, want) || strings.HasPrefix(thumb, "//") {
t.Fatalf("thumbnail = %q %v, want a path ending in %s", thumb, err, want)
}
// Without a published bucket the gravatar is used even with a file.
noBucket := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)
if err := noBucket.Publish(env.gdb); err != nil {
t.Fatal(err)
}
if got, err := classes.AvatarURL(ctx, noBucket, withFile, 64); err != nil || got != gravatarFor(withFile.Email, 64) {
t.Fatalf("no bucket = %q %v", got, err)
}
// An original that does not decode gets WinterCMS's broken-image
// thumbnail, still a thumbnail path.
notImage := env.seedUser(t, "notimage", nil)
env.seedAvatar(t, notImage) // its blob is not an image
if got, err := classes.AvatarURL(ctx, env.app, notImage, 128); err != nil || !strings.Contains(got, "thumb_") {
t.Fatalf("non-image avatar = %q %v", got, err)
}
// A thumbnail that cannot be made (here: the storage fails) falls back
// to the file path.
closed := memblob.OpenBucket(nil)
_ = closed.Close()
failing := sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)
if err := failing.Publish(env.gdb); err != nil {
t.Fatal(err)
}
if err := attach.Publish(failing, closed); err != nil {
t.Fatal(err)
}
// The file's public URL follows storage.uploads.public_path_prefix
// (RC-IN-03), never a bare /<key>.
if want := attach.PublicURL(attach.BlobKey(row.DiskName)); want == "/"+attach.BlobKey(row.DiskName) {
t.Fatalf("the public path prefix is empty (%q): the fallback is not observable", attach.PublicPathPrefix())
}
if got, err := classes.AvatarURL(ctx, failing, withFile, 128); err != nil || got != attach.PublicURL(attach.BlobKey(row.DiskName)) {
t.Fatalf("failing thumbnail = %q %v, want %s", got, err, attach.PublicURL(attach.BlobKey(row.DiskName)))
}
// A failing lookup is the only error.
canceled, cancel := context.WithCancel(ctx)
cancel()
if got, err := classes.AvatarURL(canceled, env.app, withFile, 128); err == nil {
t.Fatalf("failing lookup = %q, want an error", got)
}
// The user API payload is unchanged: avatar_url is AvatarURL at 128,
// next to has_avatar and the disk name.
payload, err := controllers.APIArray(ctx, env.app, withFile)
if err != nil {
t.Fatal(err)
}
at128, _ := classes.AvatarURL(ctx, env.app, withFile, 128)
if payload["has_avatar"] != true || payload["avatar"] != row.DiskName || payload["avatar_url"] != at128 {
t.Fatalf("payload avatar fields = %v %v %v, want true %s %s", payload["has_avatar"], payload["avatar"], payload["avatar_url"], row.DiskName, at128)
}
without, err := controllers.APIArray(ctx, env.app, plain)
if err != nil {
t.Fatal(err)
}
// Without one the payload keeps its gravatar default (size 25).
if without["has_avatar"] != false || without["avatar"] != gravatarFor(plain.Email, 25) {
t.Fatalf("payload without an avatar = %v %v", without["has_avatar"], without["avatar"])
}
}

View File

@@ -0,0 +1,151 @@
package user
import (
"context"
"encoding/json"
"net/http"
"slices"
"strconv"
"strings"
"sync"
"testing"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
)
const permManageBackendLinks = "golem15.users.manage_backend_links"
// administratorPath is the admin API path of one administrator on the
// Administrators screen, with an optional suffix.
func administratorPath(id uint, suffix string) string {
return adminAPI("/summercms/cabana/users/" + strconv.FormatUint(uint64(id), 10) + suffix)
}
// superAdmin is admin with the superuser flag set.
func (e *adminEnv) superAdmin(t *testing.T) string {
t.Helper()
token := e.admin(t)
if err := e.gdb.Exec(`UPDATE backend_users SET is_superuser = TRUE WHERE id = ?`, adminID(t, token)).Error; err != nil {
t.Fatal(err)
}
return token
}
// administratorActions returns the record actions the Administrators screen
// offers on an administrator.
func (e *adminEnv) administratorActions(t *testing.T, token string, id uint) []string {
t.Helper()
rec := e.expect(t, http.StatusOK, http.MethodGet, administratorPath(id, ""), token, nil)
var meta struct {
Actions []struct {
Name string `json:"name"`
} `json:"actions"`
}
if err := json.Unmarshal(adminDecode(t, rec).Meta, &meta); err != nil {
t.Fatal(err)
}
names := []string{}
for _, action := range meta.Actions {
if strings.HasSuffix(action.Name, "frontend_account") {
names = append(names, action.Name)
}
}
return names
}
// TestBackendLinkAdminSmoke: on the Administrators screen an administrator
// with golem15.users.manage_backend_links links a frontend account to
// another administrator by its exact email (any letter case) and unlinks
// it; linked_by records the caller, the event fires, a taken or unknown
// account is a 422 on the prompt, and an administrator without the
// permission is neither offered the actions nor allowed to run them.
func TestBackendLinkAdminSmoke(t *testing.T) {
env := newAdminEnv(t)
var mu sync.Mutex
var linked []models.BackendLink
env.app.Events.Listen("test.backend_linked", func(_ context.Context, e *classes.BackendLinkedEvent) error {
mu.Lock()
linked = append(linked, *e.Link)
mu.Unlock()
return nil
})
stamp := adminStamp()
editor := env.seedUser(t, "editor", func(u *models.User) { u.Email = "editor-" + stamp + "@example.test" })
second := env.seedUser(t, "second", nil)
targetToken := env.admin(t)
target := adminID(t, targetToken)
super := env.superAdmin(t)
superID := adminID(t, super)
resolver, _ := env.app.Lookup[pact.MCPLinkedBackendResolver]()
if got := env.administratorActions(t, super, target); !slices.Equal(got, []string{"link_frontend_account"}) {
t.Fatalf("offered before the link = %v", got)
}
link := func(token, value string) *http.Response {
t.Helper()
rec := env.call(t, http.MethodPost, administratorPath(target, "/actions/link_frontend_account"), token, map[string]any{"payload": value})
return rec.Result()
}
// Unknown email: 422 on payload with the unknown_user text.
rec := env.call(t, http.MethodPost, administratorPath(target, "/actions/link_frontend_account"), super, map[string]any{"payload": "nobody-" + stamp + "@example.test"})
if rec.Code != http.StatusUnprocessableEntity || !slices.Contains(adminDecode(t, rec).Error.Details["payload"], "No active frontend user has this email.") {
t.Fatalf("unknown email = %d %s", rec.Code, rec.Body.String())
}
// The email matches whatever its letter case.
if res := link(super, " Editor-"+stamp+"@Example.TEST "); res.StatusCode != http.StatusOK {
t.Fatalf("set = %d", res.StatusCode)
}
var row models.BackendLink
if err := env.gdb.Where("backend_user_id = ?", target).Take(&row).Error; err != nil || row.UserID != editor.ID || row.LinkedBy == nil || *row.LinkedBy != superID {
t.Fatalf("link row = %+v %v", row, err)
}
if got, found, err := resolver.LinkedBackendUser(context.Background(), editor.ID); err != nil || !found || got.ID != target {
t.Fatalf("LinkedBackendUser = %+v %v %v", got, found, err)
}
mu.Lock()
if len(linked) != 1 || linked[0].UserID != editor.ID || linked[0].BackendUserID != target {
t.Fatalf("BackendLinkedEvent saw %+v", linked)
}
mu.Unlock()
if got := env.administratorActions(t, super, target); !slices.Equal(got, []string{"unlink_frontend_account"}) {
t.Fatalf("offered after the link = %v", got)
}
// The administrator is linked: a second set no longer applies (409),
// and the same frontend user cannot be linked to another administrator.
if res := link(super, second.Email); res.StatusCode != http.StatusConflict {
t.Fatalf("second set on a linked administrator = %d", res.StatusCode)
}
otherToken := env.admin(t)
other := adminID(t, otherToken)
rec = env.call(t, http.MethodPost, administratorPath(other, "/actions/link_frontend_account"), super, map[string]any{"payload": editor.Email})
if rec.Code != http.StatusUnprocessableEntity || !slices.Contains(adminDecode(t, rec).Error.Details["payload"], "This administrator or this frontend user is already linked.") {
t.Fatalf("frontend user linked twice = %d %s", rec.Code, rec.Body.String())
}
// Without the permission: not offered, and refused.
limited := env.admin(t, cabana.PermissionManageUsers)
if got := env.administratorActions(t, limited, target); len(got) != 0 {
t.Fatalf("limited administrator is offered %v", got)
}
env.expect(t, http.StatusForbidden, http.MethodPost, administratorPath(target, "/actions/unlink_frontend_account"), limited, map[string]any{})
env.expect(t, http.StatusForbidden, http.MethodPost, administratorPath(other, "/actions/link_frontend_account"), limited, map[string]any{"payload": second.Email})
manager := env.admin(t, cabana.PermissionManageUsers, permManageBackendLinks)
if got := env.administratorActions(t, manager, target); !slices.Equal(got, []string{"unlink_frontend_account"}) {
t.Fatalf("manager is offered %v", got)
}
// Unlink.
env.expect(t, http.StatusOK, http.MethodPost, administratorPath(target, "/actions/unlink_frontend_account"), manager, map[string]any{})
if _, found, err := resolver.LinkedBackendUser(context.Background(), editor.ID); err != nil || found {
t.Fatalf("after unlink found=%v err=%v", found, err)
}
if got := env.administratorActions(t, super, target); !slices.Equal(got, []string{"link_frontend_account"}) {
t.Fatalf("offered after the unlink = %v", got)
}
}

View File

@@ -0,0 +1,103 @@
package user
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/bouncer"
"github.com/golang-jwt/jwt/v5"
)
// craftSignInToken is craftToken with an auth_time claim: a session token
// issued at iat for a sign-in at authTime.
func craftSignInToken(t *testing.T, sub, jti string, iat, authTime time.Time) string {
t.Helper()
claims := jwt.MapClaims{
"sub": sub,
"iss": "http://example.com/_user/api/v1/login",
"iat": iat.Unix(),
"nbf": iat.Unix(),
"exp": time.Now().Add(time.Hour).Unix(),
"jti": jti,
"prv": prvHash,
bouncer.ClaimAuthTime: authTime.Unix(),
}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(sessionSecret))
if err != nil {
t.Fatal(err)
}
return signed
}
// TestBackendLinkAuthTimeSmoke: the account link proof is the sign-in time.
// A session signed in before the request and refreshed after it is refused
// with stale_session, a sign-in after the request confirms, POST show
// answers the administrator for the code in the body, and My account's URL
// carries the code in the fragment, never in a query string. Skips under
// -short.
func TestBackendLinkAuthTimeSmoke(t *testing.T) {
env := newAdminEnv(t)
user := env.seedUser(t, "auth-time", nil)
sub := strconv.FormatUint(uint64(user.ID), 10)
admin := env.admin(t)
login := env.adminLogin(t, adminID(t, admin))
// 1. The user signed in an hour ago.
old := craftSignInToken(t, sub, "auth-time-old-"+adminStamp(), time.Now().Add(-time.Hour), time.Now().Add(-time.Hour))
// 2. The administrator starts a link; 6. its URL holds the code in the
// fragment only.
var started struct {
URL string `json:"url"`
}
adminInto(t, env.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/link"), admin, map[string]any{}), &started)
if !strings.Contains(started.URL, "/link-admin#code=") || strings.Contains(started.URL, "?") {
t.Fatalf("link URL = %q", started.URL)
}
m := linkURL.FindStringSubmatch(started.URL)
if m == nil {
t.Fatalf("link URL = %q", started.URL)
}
code := m[1]
// 5. POST show answers the administrator for the code in the body.
rec := env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/backend-link/show", "", map[string]string{"code": code})
var shown struct {
Data struct {
Admin map[string]any `json:"admin"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &shown); err != nil || shown.Data.Admin["login"] != login {
t.Fatalf("POST show = %s (%v)", rec.Body.String(), err)
}
if got := rec.Header().Get("Cache-Control"); got != "no-store, private" {
t.Fatalf("POST show Cache-Control = %q", got)
}
env.expect(t, http.StatusNotFound, http.MethodPost, "/_user/api/v1/backend-link/show", "", map[string]string{"code": strings.Repeat("0", 64)})
// 3. Refreshing the old session after the request does not make it a
// fresh sign-in.
rec = env.refresh(t, old)
var refreshed struct {
Token string `json:"token"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &refreshed); rec.Code != http.StatusOK || err != nil || refreshed.Token == "" {
t.Fatalf("refresh = %d %s", rec.Code, rec.Body.String())
}
if status, body := env.confirmLink(t, refreshed.Token, code); status != http.StatusConflict || !strings.Contains(body, `"stale_session"`) {
t.Fatalf("refreshed confirm = %d %s", status, body)
}
// 4. A sign-in after the request confirms.
status, fresh := env.userLogin(t, user.Email, "correct-horse")
if status != http.StatusOK || fresh == "" {
t.Fatalf("login = %d", status)
}
if status, body := env.confirmLink(t, fresh, code); status != http.StatusOK || !strings.Contains(body, `"login":"`+login+`"`) {
t.Fatalf("fresh confirm = %d %s", status, body)
}
}

View File

@@ -0,0 +1,114 @@
package user
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
// TestBackendLinkAuthTime pins the account link proof of plan 08 (C-CR-02,
// P-34): confirming a link needs a sign-in at or after the request, read
// from the session's auth_time, which refresh copies and never renews. A
// session signed in before the request stays stale through a refresh, a
// sign-in after the request confirms (also after a refresh), a token
// without auth_time is stale, and a session token of another user than the
// authenticated one is 401. Postgres only: skipped under -short.
func TestBackendLinkAuthTime(t *testing.T) {
if testing.Short() {
t.Skip("Postgres")
}
env := newAdminEnv(t)
login := func(t *testing.T, user *models.User) string {
t.Helper()
status, token := env.userLogin(t, user.Email, "correct-horse")
if status != http.StatusOK || token == "" {
t.Fatalf("login = %d", status)
}
return token
}
refresh := func(t *testing.T, token string) string {
t.Helper()
rec := env.refresh(t, token)
var body struct {
Token string `json:"token"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); rec.Code != http.StatusOK || err != nil || body.Token == "" {
t.Fatalf("refresh = %d %s", rec.Code, rec.Body.String())
}
return body.Token
}
// signInEarlier waits past the second of the sign-in, so a request
// created next is strictly later (auth_time has whole seconds).
signInEarlier := func() { time.Sleep(1100 * time.Millisecond) }
expect := func(t *testing.T, token, code string, status int, contains string) {
t.Helper()
got, body := env.confirmLink(t, token, code)
if got != status || !strings.Contains(body, contains) {
t.Fatalf("confirm = %d %s, want %d with %q", got, body, status, contains)
}
}
t.Run("login, request, refresh, confirm is stale", func(t *testing.T) {
user := env.seedUser(t, "at-refresh", nil)
session := login(t, user)
signInEarlier()
code := env.startLink(t, env.admin(t))
expect(t, refresh(t, session), code, http.StatusConflict, `"stale_session"`)
})
t.Run("request, login, confirm links", func(t *testing.T) {
user := env.seedUser(t, "at-after", nil)
code := env.startLink(t, env.admin(t))
expect(t, login(t, user), code, http.StatusOK, `"backend_user"`)
})
t.Run("login, request, login again, confirm links", func(t *testing.T) {
user := env.seedUser(t, "at-again", nil)
first := login(t, user)
signInEarlier()
code := env.startLink(t, env.admin(t))
expect(t, first, code, http.StatusConflict, `"stale_session"`)
expect(t, login(t, user), code, http.StatusOK, `"backend_user"`)
})
t.Run("a hand-made token without auth_time is stale", func(t *testing.T) {
user := env.seedUser(t, "at-legacy", nil)
code := env.startLink(t, env.admin(t))
legacy := craftToken(t, strconv.FormatUint(uint64(user.ID), 10), "at-legacy-"+adminStamp(), time.Now(), time.Now().Add(time.Hour))
expect(t, legacy, code, http.StatusConflict, `"stale_session"`)
})
t.Run("a refreshed session of a post-request sign-in keeps working", func(t *testing.T) {
user := env.seedUser(t, "at-carried", nil)
code := env.startLink(t, env.admin(t))
session := login(t, user)
expect(t, refresh(t, refresh(t, session)), code, http.StatusOK, `"backend_user"`)
})
t.Run("another user's session token is 401", func(t *testing.T) {
user := env.seedUser(t, "at-owner", nil)
other := env.seedUser(t, "at-other", nil)
code := env.startLink(t, env.admin(t))
// jwt.auth authenticated user, but the session token the handler
// reads again for its sign-in time belongs to other.
req := httptest.NewRequest(http.MethodPost, "/_user/api/v1/backend-link/confirm", strings.NewReader(`{"code":"`+code+`"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+login(t, other))
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: user.ID}))
rec := httptest.NewRecorder()
controllers.BackendLinkConfirm(env.app)(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("mismatched session token = %d %s", rec.Code, rec.Body.String())
}
// The code is still usable by its rightful user.
expect(t, login(t, user), code, http.StatusOK, `"backend_user"`)
})
}

141
backend_link_show_test.go Normal file
View File

@@ -0,0 +1,141 @@
package user
import (
"bytes"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/compass"
)
// TestBackendLinkShowPost pins plan 08's link code transport (C-WR-01,
// C-IN-06): POST /backend-link/show answers exactly like the GET route (the
// data for a live code, 404 for an unknown, a used or an expired one), both
// with Cache-Control no-store, private; a code in the query string of the
// show or confirm POST is ignored (RC-IN-01); My account answers the link as
// <frontend_url>/link-admin#code=<64 hex> with no query string;
// golem15.user.backend_links.page_path changes the path, and a value
// without a leading slash gets one. Postgres only: skipped under
// -short.
func TestBackendLinkShowPost(t *testing.T) {
if testing.Short() {
t.Skip("Postgres")
}
env := newAdminEnv(t)
show := func(t *testing.T, code string) (get, post *struct {
status int
body string
cache string
}) {
t.Helper()
g := env.call(t, http.MethodGet, "/_user/api/v1/backend-link/"+code, "", nil)
p := env.call(t, http.MethodPost, "/_user/api/v1/backend-link/show", "", map[string]string{"code": code})
return &struct {
status int
body string
cache string
}{g.Code, g.Body.String(), g.Header().Get("Cache-Control")}, &struct {
status int
body string
cache string
}{p.Code, p.Body.String(), p.Header().Get("Cache-Control")}
}
same := func(t *testing.T, code string, status int) {
t.Helper()
get, post := show(t, code)
if get.status != status || post.status != status {
t.Fatalf("show %s: GET %d, POST %d, want %d", code[:8], get.status, post.status, status)
}
if !bytes.Equal([]byte(get.body), []byte(post.body)) {
t.Fatalf("POST show differs from GET:\nGET %s\nPOST %s", get.body, post.body)
}
if get.cache != "no-store, private" || post.cache != "no-store, private" {
t.Fatalf("Cache-Control: GET %q, POST %q", get.cache, post.cache)
}
}
t.Run("POST show answers like GET", func(t *testing.T) {
token := env.admin(t)
live := env.startLink(t, token)
same(t, live, http.StatusOK)
if _, post := show(t, live); !strings.Contains(post.body, `"admin"`) || !strings.Contains(post.body, `"expires_at"`) {
t.Fatalf("POST show data = %s", post.body)
}
same(t, strings.Repeat("a", 64), http.StatusNotFound)
used := env.startLink(t, env.admin(t))
if status, body := env.confirmLink(t, freshUserToken(t, env.seedUser(t, "show-used", nil)), used); status != http.StatusOK {
t.Fatalf("confirm = %d %s", status, body)
}
same(t, used, http.StatusNotFound)
expiring := env.admin(t)
expired := env.startLink(t, expiring)
if err := env.gdb.Model(&models.BackendLinkRequest{}).Where("backend_user_id = ?", adminID(t, expiring)).
Update("expires_at", time.Now().Add(-time.Minute)).Error; err != nil {
t.Fatal(err)
}
same(t, expired, http.StatusNotFound)
})
t.Run("a code in the query string is ignored", func(t *testing.T) {
live := env.startLink(t, env.admin(t))
path := "/_user/api/v1/backend-link/show?code=" + live
for name, send := range map[string]func() *httptest.ResponseRecorder{
"no body": func() *httptest.ResponseRecorder { return env.send(t, http.MethodPost, path, "", nil, "", nil) },
"a JSON body without a code": func() *httptest.ResponseRecorder { return env.call(t, http.MethodPost, path, "", map[string]string{}) },
"a form body without a code": func() *httptest.ResponseRecorder {
return env.send(t, http.MethodPost, path, "", []byte("other=1"), "application/x-www-form-urlencoded", nil)
},
} {
if got := send(); got.Code != http.StatusNotFound {
t.Fatalf("show with ?code= and %s = %d %s, want 404", name, got.Code, got.Body.String())
}
}
user := env.seedUser(t, "show-query", nil)
rec := env.send(t, http.MethodPost, "/_user/api/v1/backend-link/confirm?code="+live, freshUserToken(t, user), []byte("other=1"), "application/x-www-form-urlencoded", nil)
if rec.Code != http.StatusNotFound {
t.Fatalf("confirm with ?code= = %d %s, want 404", rec.Code, rec.Body.String())
}
// A form body still carries the code, and the query string never did.
form := env.send(t, http.MethodPost, "/_user/api/v1/backend-link/show", "", []byte("code="+live), "application/x-www-form-urlencoded", nil)
if form.Code != http.StatusOK {
t.Fatalf("show with the code in a form body = %d %s", form.Code, form.Body.String())
}
if status, body := env.confirmLink(t, freshUserToken(t, user), live); status != http.StatusOK {
t.Fatalf("confirm with the code in the body after the refusals = %d %s", status, body)
}
})
t.Run("the My account URL carries the code in the fragment only", func(t *testing.T) {
var out struct {
URL string `json:"url"`
}
adminInto(t, env.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/link"), env.admin(t), map[string]any{}), &out)
if !regexp.MustCompile(`^https://app\.example\.test/link-admin#code=[a-f0-9]{64}$`).MatchString(out.URL) || strings.Contains(out.URL, "?") {
t.Fatalf("link URL = %q", out.URL)
}
})
for _, c := range []struct{ value, want string }{{"/pl/polacz", "/pl/polacz"}, {"pl/polacz", "/pl/polacz"}} {
t.Run("page_path "+c.value, func(t *testing.T) {
custom := newAdminEnv(t, func(cfg *compass.Config) {
if err := cfg.Set("golem15.user.backend_links.page_path", c.value); err != nil {
t.Fatal(err)
}
})
var out struct {
URL string `json:"url"`
}
adminInto(t, custom.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/link"), custom.admin(t), map[string]any{}), &out)
if !regexp.MustCompile(`^https://app\.example\.test` + regexp.QuoteMeta(c.want) + `#code=[a-f0-9]{64}$`).MatchString(out.URL) {
t.Fatalf("link URL with page_path %q = %q", c.value, out.URL)
}
})
}
}

279
backend_link_smoke_test.go Normal file
View File

@@ -0,0 +1,279 @@
package user
import (
"context"
"encoding/json"
"net/http"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/pact"
)
// subjectSpy records the pact.MCPSubjectChanged events fired on an app.
type subjectSpy struct {
mu sync.Mutex
events []pact.MCPSubjectChanged
}
func (s *subjectSpy) has(guard string, id uint, kind string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return slices.Contains(s.events, pact.MCPSubjectChanged{Guard: guard, UserID: id, Kind: kind})
}
// hasEvent reports whether ev, with its TokenID and ClientID, was fired.
func (s *subjectSpy) hasEvent(ev pact.MCPSubjectChanged) bool {
s.mu.Lock()
defer s.mu.Unlock()
return slices.Contains(s.events, ev)
}
func (s *subjectSpy) reset() {
s.mu.Lock()
s.events = nil
s.mu.Unlock()
}
// spySubjects listens for the subject events the plugin fires.
func (e *adminEnv) spySubjects() *subjectSpy {
spy := &subjectSpy{}
e.app.Events.Listen("test.subjects", func(_ context.Context, ev *pact.MCPSubjectChanged) error {
spy.mu.Lock()
spy.events = append(spy.events, *ev)
spy.mu.Unlock()
return nil
})
return spy
}
// adminID is the backend user id inside an admin session token.
func adminID(t *testing.T, token string) uint {
t.Helper()
sub, _, _, _, err := bouncer.VerifyClaimsAudience(token, adminHarnessSecret, bouncer.AudienceBackend)
if err != nil {
t.Fatal(err)
}
id, err := strconv.ParseUint(sub, 10, 64)
if err != nil {
t.Fatal(err)
}
return uint(id)
}
// adminLogin reads an administrator's login.
func (e *adminEnv) adminLogin(t *testing.T, id uint) string {
t.Helper()
var login string
if err := e.gdb.Raw(`SELECT login FROM backend_users WHERE id = ?`, id).Scan(&login).Error; err != nil {
t.Fatal(err)
}
return login
}
// freshUserToken mints a frontend session token issued now.
func freshUserToken(t *testing.T, user *models.User) string {
t.Helper()
token, _, err := bouncer.Mint(sessionSecret, strconv.FormatUint(uint64(user.ID), 10), "https://app.example.test", time.Hour)
if err != nil {
t.Fatal(err)
}
return token
}
// accountSection is one My account contribution as the admin API lists it.
type accountSection struct {
Name string `json:"name"`
Status string `json:"status"`
Actions []struct {
Name string `json:"name"`
} `json:"actions"`
}
func (s accountSection) actions() []string {
out := []string{}
for _, a := range s.Actions {
out = append(out, a.Name)
}
return out
}
// frontendSection lists My account and returns the frontend_account section.
func (e *adminEnv) frontendSection(t *testing.T, token string) accountSection {
t.Helper()
var sections []accountSection
adminInto(t, e.expect(t, http.StatusOK, http.MethodGet, adminAPI("/account/contributions"), token, nil), &sections)
for _, s := range sections {
if s.Name == "frontend_account" {
return s
}
}
t.Fatalf("My account has no frontend_account section: %+v", sections)
return accountSection{}
}
var linkURL = regexp.MustCompile(`^https://app\.example\.test/link-admin#code=([a-f0-9]{64})$`)
// startLink runs My account's link action and returns the code in its URL.
func (e *adminEnv) startLink(t *testing.T, token string) string {
t.Helper()
var out struct {
Message string `json:"message"`
URL string `json:"url"`
}
adminInto(t, e.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/link"), token, map[string]any{}), &out)
m := linkURL.FindStringSubmatch(out.URL)
if m == nil || out.Message == "" {
t.Fatalf("link action answered %+v", out)
}
return m[1]
}
// confirmLink posts the code as the frontend session token.
func (e *adminEnv) confirmLink(t *testing.T, userToken, code string) (int, string) {
t.Helper()
rec := e.call(t, http.MethodPost, "/_user/api/v1/backend-link/confirm", userToken, map[string]string{"code": code})
return rec.Code, rec.Body.String()
}
// TestBackendLinkSmoke: an administrator starts a link on My account, the
// site shows who asked, a session older than the request is refused, a
// fresh one links the accounts (the published resolver answers), the code is
// one-shot, the 1:1 rule holds, unlink and deleting the frontend user remove
// the link, and the subject events fire.
func TestBackendLinkSmoke(t *testing.T) {
env := newAdminEnv(t)
spy := env.spySubjects()
frontend := env.seedUser(t, "linker", nil)
other := env.seedUser(t, "linker-other", nil)
token := env.admin(t)
id := adminID(t, token)
login := env.adminLogin(t, id)
links, ok := env.app.Lookup[*classes.BackendLinks]()
if !ok || links == nil {
t.Fatal("*classes.BackendLinks is not published")
}
resolver, ok := env.app.Lookup[pact.MCPLinkedBackendResolver]()
if !ok || resolver == nil {
t.Fatal("pact.MCPLinkedBackendResolver is not published")
}
ctx := context.Background()
section := env.frontendSection(t, token)
if section.Status != "Not linked" || !slices.Equal(section.actions(), []string{"link"}) {
t.Fatalf("unlinked section = %+v", section)
}
code := env.startLink(t, token)
rec := env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/backend-link/"+code, "", nil)
var shown struct {
Data struct {
Admin map[string]any `json:"admin"`
ExpiresAt string `json:"expires_at"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &shown); err != nil {
t.Fatal(err)
}
if shown.Data.Admin["login"] != login || shown.Data.Admin["name"] != login || len(shown.Data.Admin) != 2 {
t.Fatalf("show = %s", rec.Body.String())
}
if expires, err := time.Parse(time.RFC3339, shown.Data.ExpiresAt); err != nil || time.Until(expires) < 9*time.Minute || time.Until(expires) > 11*time.Minute {
t.Fatalf("expires_at = %q (%v)", shown.Data.ExpiresAt, err)
}
env.expect(t, http.StatusNotFound, http.MethodGet, "/_user/api/v1/backend-link/"+strings.Repeat("0", 64), "", nil)
// A session signed in before the request is refused: sign in again.
stale := craftToken(t, strconv.FormatUint(uint64(frontend.ID), 10), "stale-"+adminStamp(), time.Now().Add(-time.Hour), time.Now().Add(time.Hour))
if status, body := env.confirmLink(t, stale, code); status != http.StatusConflict || !strings.Contains(body, `"stale_session"`) {
t.Fatalf("stale confirm = %d %s", status, body)
}
if status, _ := env.confirmLink(t, "", code); status != http.StatusUnauthorized {
t.Fatalf("anonymous confirm = %d", status)
}
spy.reset()
status, body := env.confirmLink(t, freshUserToken(t, frontend), code)
if status != http.StatusOK || !strings.Contains(body, `"login":"`+login+`"`) {
t.Fatalf("fresh confirm = %d %s", status, body)
}
linked, found, err := resolver.LinkedBackendUser(ctx, frontend.ID)
if err != nil || !found || linked.ID != id || linked.Login != login || linked.DisplayName != login {
t.Fatalf("LinkedBackendUser = %+v %v %v", linked, found, err)
}
if !spy.has("user", frontend.ID, pact.MCPSubjectLink) || !spy.has("backend", id, pact.MCPSubjectLink) {
t.Fatalf("confirm fired %+v", spy.events)
}
var row models.BackendLink
if err := env.gdb.Where("user_id = ?", frontend.ID).Take(&row).Error; err != nil || row.BackendUserID != id || row.LinkedBy != nil {
t.Fatalf("link row = %+v %v", row, err)
}
section = env.frontendSection(t, token)
if !strings.Contains(section.Status, frontend.Email) || !slices.Equal(section.actions(), []string{"unlink"}) {
t.Fatalf("linked section = %+v", section)
}
// The code is one-shot.
if status, _ := env.confirmLink(t, freshUserToken(t, frontend), code); status != http.StatusNotFound {
t.Fatalf("replayed confirm = %d", status)
}
env.expect(t, http.StatusNotFound, http.MethodGet, "/_user/api/v1/backend-link/"+code, "", nil)
// One link per administrator: another frontend user cannot take it.
second, _, err := links.CreateLinkRequest(ctx, id)
if err != nil {
t.Fatal(err)
}
if status, body := env.confirmLink(t, freshUserToken(t, other), second); status != http.StatusConflict || !strings.Contains(body, `"already_linked"`) {
t.Fatalf("second link = %d %s", status, body)
}
// Unlink on My account.
spy.reset()
env.expect(t, http.StatusOK, http.MethodPost, adminAPI("/account/contributions/frontend_account/actions/unlink"), token, map[string]any{})
if _, found, err := resolver.LinkedBackendUser(ctx, frontend.ID); err != nil || found {
t.Fatalf("after unlink LinkedBackendUser found=%v err=%v", found, err)
}
if !spy.has("user", frontend.ID, pact.MCPSubjectLink) || !spy.has("backend", id, pact.MCPSubjectLink) {
t.Fatalf("unlink fired %+v", spy.events)
}
if section := env.frontendSection(t, token); !slices.Equal(section.actions(), []string{"link"}) {
t.Fatalf("section after unlink = %+v", section)
}
// An expired request answers 404 like an unknown one.
expired, _, err := links.CreateLinkRequest(ctx, id)
if err != nil {
t.Fatal(err)
}
if err := env.gdb.Exec(`UPDATE golem15_user_backend_link_requests SET expires_at = NOW() - INTERVAL '1 minute' WHERE backend_user_id = ? AND used_at IS NULL`, id).Error; err != nil {
t.Fatal(err)
}
if status, _ := env.confirmLink(t, freshUserToken(t, frontend), expired); status != http.StatusNotFound {
t.Fatalf("expired confirm = %d", status)
}
// Deleting the frontend user removes the link and ends its subject.
code = env.startLink(t, token)
if status, body := env.confirmLink(t, freshUserToken(t, frontend), code); status != http.StatusOK {
t.Fatalf("relink = %d %s", status, body)
}
spy.reset()
manager := env.admin(t, permAccessUsers)
env.expect(t, http.StatusOK, http.MethodDelete, userPath(frontend.ID, ""), manager, nil)
var left int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM golem15_user_backend_links WHERE backend_user_id = ?`, id).Scan(&left).Error; err != nil || left != 0 {
t.Fatalf("links left after delete = %d %v", left, err)
}
if !spy.has("user", frontend.ID, pact.MCPSubjectDeleted) || !spy.has("backend", id, pact.MCPSubjectLink) {
t.Fatalf("delete fired %+v", spy.events)
}
}

217
backend_link_test.go Normal file
View File

@@ -0,0 +1,217 @@
package user
import (
"context"
"encoding/json"
"net/http"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"gorm.io/gorm"
)
// requestCreatedAt reads when the administrator's open link request was
// created.
func (e *adminEnv) requestCreatedAt(t *testing.T, adminID uint) time.Time {
t.Helper()
var created time.Time
if err := e.gdb.Raw(`SELECT created_at FROM golem15_user_backend_link_requests WHERE backend_user_id = ? AND used_at IS NULL ORDER BY id DESC LIMIT 1`, adminID).Scan(&created).Error; err != nil || created.IsZero() {
t.Fatalf("link request created_at = %v, %v", created, err)
}
return created
}
// TestBackendLink (D-03..D-08) extends the link smokes: the fresh sign-in
// rule at the second (an auth_time equal to the request's created_at
// confirms, one second earlier is stale_session, and a token without
// auth_time is stale_session whatever its iat); 1:1 on the frontend side too (a
// linked user cannot confirm another administrator's request); the show
// route exposes the administrator's login and name and the expiry only;
// SetLink records linked_by and fires BackendLinkedEvent and both subject
// events after commit, nothing on rollback; RemoveLink fires
// BackendUnlinkedEvent and both subject events; LinkedBackendUser answers
// false for a deactivated or soft-deleted administrator; deactivating the
// frontend user removes the link and fires deleted. Skips under -short.
func TestBackendLink(t *testing.T) {
env := newAdminEnv(t)
spy := env.spySubjects()
links, _ := env.app.Lookup[*classes.BackendLinks]()
resolver, _ := env.app.Lookup[pact.MCPLinkedBackendResolver]()
ctx := context.Background()
t.Run("fresh sign-in at the second", func(t *testing.T) {
token := env.admin(t)
admin := adminID(t, token)
user := env.seedUser(t, "iat", nil)
sub := strconv.FormatUint(uint64(user.ID), 10)
code := env.startLink(t, token)
created := env.requestCreatedAt(t, admin).Truncate(time.Second)
early := craftSignInToken(t, sub, "early-"+adminStamp(), time.Now(), created.Add(-time.Second))
if status, body := env.confirmLink(t, early, code); status != http.StatusConflict || !strings.Contains(body, `"stale_session"`) {
t.Fatalf("auth_time one second early = %d %s", status, body)
}
noAuthTime := craftToken(t, sub, "legacy-"+adminStamp(), time.Now(), time.Now().Add(time.Hour))
if status, body := env.confirmLink(t, noAuthTime, code); status != http.StatusConflict || !strings.Contains(body, `"stale_session"`) {
t.Fatalf("no auth_time = %d %s", status, body)
}
exact := craftSignInToken(t, sub, "exact-"+adminStamp(), created, created)
if status, body := env.confirmLink(t, exact, code); status != http.StatusOK {
t.Fatalf("auth_time equal to created_at = %d %s", status, body)
}
})
t.Run("a linked frontend user cannot take a second administrator", func(t *testing.T) {
first, second := env.admin(t), env.admin(t)
user := env.seedUser(t, "one-to-one", nil)
code := env.startLink(t, first)
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusOK {
t.Fatalf("first link = %d %s", status, body)
}
code = env.startLink(t, second)
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusConflict || !strings.Contains(body, `"already_linked"`) {
t.Fatalf("second administrator = %d %s", status, body)
}
})
t.Run("show exposes login, name and expiry only", func(t *testing.T) {
token := env.admin(t)
code := env.startLink(t, token)
rec := env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/backend-link/"+code, "", nil)
var shown map[string]map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &shown); err != nil {
t.Fatal(err)
}
keys := func(m map[string]any) []string {
var out []string
for k := range m {
out = append(out, k)
}
slices.Sort(out)
return out
}
admin, _ := shown["data"]["admin"].(map[string]any)
if len(shown) != 1 || !slices.Equal(keys(shown["data"]), []string{"admin", "expires_at"}) || !slices.Equal(keys(admin), []string{"login", "name"}) {
t.Fatalf("show = %s", rec.Body.String())
}
if strings.Contains(rec.Body.String(), "@") || strings.Contains(rec.Body.String(), code) {
t.Fatalf("show leaks an email or the code: %s", rec.Body.String())
}
})
t.Run("SetLink and RemoveLink events", func(t *testing.T) {
var mu sync.Mutex
var linked, unlinked int
env.app.Events.Listen("test.link_events", func(context.Context, *classes.BackendLinkedEvent) error {
mu.Lock()
linked++
mu.Unlock()
return nil
})
env.app.Events.Listen("test.link_events", func(context.Context, *classes.BackendUnlinkedEvent) error {
mu.Lock()
unlinked++
mu.Unlock()
return nil
})
setter := adminID(t, env.admin(t))
target := adminID(t, env.admin(t))
user := env.seedUser(t, "set-link", nil)
// A rolled-back SetLink fires no subject event.
spy.reset()
_ = lagoon.Transaction(ctx, env.gdb, func(ctx context.Context, tx *gorm.DB) error {
if _, err := links.SetLink(ctx, tx, user.ID, target, setter); err != nil {
t.Fatal(err)
}
return context.Canceled
})
if spy.has("user", user.ID, pact.MCPSubjectLink) || spy.has("backend", target, pact.MCPSubjectLink) {
t.Fatalf("a rolled-back SetLink fired %+v", spy.events)
}
var link *models.BackendLink
if err := lagoon.Transaction(ctx, env.gdb, func(ctx context.Context, tx *gorm.DB) error {
var err error
link, err = links.SetLink(ctx, tx, user.ID, target, setter)
return err
}); err != nil {
t.Fatal(err)
}
if link.LinkedBy == nil || *link.LinkedBy != setter {
t.Fatalf("linked_by = %v, want %d", link.LinkedBy, setter)
}
if !spy.has("user", user.ID, pact.MCPSubjectLink) || !spy.has("backend", target, pact.MCPSubjectLink) {
t.Fatalf("SetLink fired %+v", spy.events)
}
spy.reset()
if err := lagoon.Transaction(ctx, env.gdb, func(ctx context.Context, tx *gorm.DB) error {
return links.RemoveLink(ctx, tx, link)
}); err != nil {
t.Fatal(err)
}
if !spy.has("user", user.ID, pact.MCPSubjectLink) || !spy.has("backend", target, pact.MCPSubjectLink) {
t.Fatalf("RemoveLink fired %+v", spy.events)
}
mu.Lock()
defer mu.Unlock()
// The rolled-back SetLink fired BackendLinkedEvent inside its
// transaction too (listeners run with the transaction).
if linked != 2 || unlinked != 1 {
t.Fatalf("BackendLinkedEvent %d, BackendUnlinkedEvent %d", linked, unlinked)
}
})
t.Run("deactivated or deleted administrator", func(t *testing.T) {
token := env.admin(t)
admin := adminID(t, token)
user := env.seedUser(t, "admin-gone", nil)
code := env.startLink(t, token) // the request first: the sign-in must not predate it
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusOK {
t.Fatalf("link = %d %s", status, body)
}
check := func(want bool, why string) {
t.Helper()
if _, found, err := resolver.LinkedBackendUser(ctx, user.ID); err != nil || found != want {
t.Fatalf("%s: found = %v, %v", why, found, err)
}
}
check(true, "active")
env.gdb.Exec(`UPDATE backend_users SET is_activated = FALSE WHERE id = ?`, admin)
check(false, "deactivated administrator")
env.gdb.Exec(`UPDATE backend_users SET is_activated = TRUE, deleted_at = NOW() WHERE id = ?`, admin)
check(false, "soft-deleted administrator")
env.gdb.Exec(`UPDATE backend_users SET deleted_at = NULL WHERE id = ?`, admin)
check(true, "restored administrator")
})
t.Run("deactivating the frontend user removes the link", func(t *testing.T) {
token := env.admin(t)
admin := adminID(t, token)
user := env.seedUser(t, "deactivated", nil)
code := env.startLink(t, token) // the request first: the sign-in must not predate it
if status, body := env.confirmLink(t, freshUserToken(t, user), code); status != http.StatusOK {
t.Fatalf("link = %d %s", status, body)
}
spy.reset()
if err := lagoon.Transaction(ctx, env.gdb, func(ctx context.Context, tx *gorm.DB) error {
return controllers.FireDeactivatingEvent(ctx, env.app, user, tx)
}); err != nil {
t.Fatal(err)
}
if link, err := links.LinkOf(ctx, user.ID); err != nil || link != nil {
t.Fatalf("link after deactivation = %+v, %v", link, err)
}
if !spy.has("user", user.ID, pact.MCPSubjectDeleted) || !spy.has("backend", admin, pact.MCPSubjectLink) {
t.Fatalf("deactivation fired %+v", spy.events)
}
})
}

128
backend_links_admin.go Normal file
View File

@@ -0,0 +1,128 @@
package user
import (
"context"
"errors"
"strings"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"gorm.io/gorm"
)
var _ pact.HasAdminActionExtensions = (*Plugin)(nil)
// AdminActionExtensions adds two record actions to the admin's
// Administrators screen (D-07, D-34), both behind
// golem15.users.manage_backend_links: link_frontend_account asks for the
// email of an active frontend user and links that user to the
// administrator shown (exact, case-insensitive match; no search and no
// list), recording who set it; unlink_frontend_account removes the
// administrator's link. cabana's outranking check runs before either.
func (p *Plugin) AdminActionExtensions() []pact.AdminActionExtension {
return []pact.AdminActionExtension{{
Controller: cabana.AdministratorsControllerID,
RecordActions: []pact.AdminRecordAction{
{
Name: "link_frontend_account",
Label: backendLinkLang + "set",
Confirm: backendLinkLang + "set_confirm",
Permissions: []string{classes.PermissionManageBackendLinks},
Prompt: &pact.AdminActionPrompt{
Label: backendLinkLang + "prompt_email",
Comment: backendLinkLang + "prompt_comment",
MaxLength: 254,
},
Applies: func(ctx context.Context, record any) (bool, error) {
link, err := p.adminRecordLink(ctx, record)
return link == nil, err
},
Run: p.setFrontendLink,
},
{
Name: "unlink_frontend_account",
Label: backendLinkLang + "remove",
Confirm: backendLinkLang + "remove_confirm",
Danger: true,
Permissions: []string{classes.PermissionManageBackendLinks},
Applies: func(ctx context.Context, record any) (bool, error) {
link, err := p.adminRecordLink(ctx, record)
return link != nil, err
},
Run: p.removeFrontendLink,
},
},
}}
}
// adminRecordLink returns the link of the administrator record, or nil.
func (p *Plugin) adminRecordLink(ctx context.Context, record any) (*models.BackendLink, error) {
admin, ok := record.(*cabana.BackendUser)
if !ok || admin == nil {
return nil, errors.New("golem15.user: the record is not an administrator")
}
return p.backendLinks().LinkFor(ctx, admin.ID)
}
// payloadError is the 422 on the prompt's input.
func payloadError(key string) error {
return &cabana.ValidationError{Details: map[string]any{"payload": []string{backendLinkLang + key}}}
}
// setFrontendLink links the active frontend user whose email is the prompt
// value to the administrator record.
func (p *Plugin) setFrontendLink(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
admin, ok := in.Record.(*cabana.BackendUser)
if !ok || admin == nil {
return pact.AdminRecordActionResult{}, errors.New("golem15.user: the record is not an administrator")
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return pact.AdminRecordActionResult{}, errors.New("golem15.user: linking needs the action's transaction")
}
email := strings.TrimSpace(in.Value)
var ids []uint
if err := tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Model(&models.User{}).
Where("lower(email) = lower(?) AND is_activated = TRUE", email).Limit(2).Pluck("id", &ids).Error; err != nil {
return pact.AdminRecordActionResult{}, err
}
if email == "" || len(ids) != 1 {
return pact.AdminRecordActionResult{}, payloadError("unknown_user")
}
var by uint
if caller, ok := bouncer.User(ctx); ok && caller != nil {
by = caller.ID
}
_, err := p.backendLinks().SetLink(ctx, tx, ids[0], admin.ID, by)
switch {
case err == nil:
case errors.Is(err, classes.ErrAlreadyLinked):
return pact.AdminRecordActionResult{}, payloadError("already_linked")
case errors.Is(err, classes.ErrFrontendUserUnavailable):
return pact.AdminRecordActionResult{}, payloadError("unknown_user")
case errors.Is(err, classes.ErrBackendUserUnavailable):
return pact.AdminRecordActionResult{}, &cabana.ForbiddenError{}
default:
return pact.AdminRecordActionResult{}, err
}
return pact.AdminRecordActionResult{Message: backendLinkLang + "set_success"}, nil
}
// removeFrontendLink removes the administrator record's link.
func (p *Plugin) removeFrontendLink(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return pact.AdminRecordActionResult{}, errors.New("golem15.user: unlinking needs the action's transaction")
}
link, err := p.adminRecordLink(ctx, in.Record)
if err != nil {
return pact.AdminRecordActionResult{}, err
}
if err := p.backendLinks().RemoveLink(ctx, tx, link); err != nil {
return pact.AdminRecordActionResult{}, err
}
return pact.AdminRecordActionResult{Message: backendLinkLang + "remove_success"}, nil
}

61
blacklist.go Normal file
View File

@@ -0,0 +1,61 @@
package user
import (
"context"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
var _ bouncer.BlacklistStore = (*appBlacklist)(nil)
// appBlacklist is the blacklist store the jwt guard is built with. The guard
// is built in Boot, which under summer serve runs before the database is
// published, so the store the plugin publishes on lagoon.Publish is resolved
// on every call. While none is published, no token counts as blacklisted and
// Add and Sweep do nothing. An appBlacklist must never be published as the
// app's bouncer.BlacklistStore: the lookup would then find itself.
type appBlacklist struct {
app *backpack.App
}
// store returns the published blacklist store, or nil when there is none
// (or the published value is an appBlacklist).
func (b *appBlacklist) store() bouncer.BlacklistStore {
if b == nil || b.app == nil {
return nil
}
s, ok := b.app.Lookup[bouncer.BlacklistStore]()
if !ok || s == nil {
return nil
}
if _, self := s.(*appBlacklist); self {
return nil
}
return s
}
func (b *appBlacklist) Add(ctx context.Context, jti string, expiresAt, validUntil time.Time) error {
s := b.store()
if s == nil {
return nil
}
return s.Add(ctx, jti, expiresAt, validUntil)
}
func (b *appBlacklist) IsBlacklisted(ctx context.Context, jti string) (bool, error) {
s := b.store()
if s == nil {
return false, nil
}
return s.IsBlacklisted(ctx, jti)
}
func (b *appBlacklist) Sweep(ctx context.Context, now time.Time) error {
s := b.store()
if s == nil {
return nil
}
return s.Sweep(ctx, now)
}

283
blacklist_sweep_test.go Normal file
View File

@@ -0,0 +1,283 @@
package user
import (
"bytes"
"context"
"encoding/base64"
"errors"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/pact"
"gorm.io/gorm"
)
const (
sweepCommand = "user:jwt-blacklist-sweep"
sweepIntervalKey = "golem15.user.jwt.blacklist_sweep_interval"
)
// badSweepIntervals are values the scheduler cannot run, so Boot rejects them.
var badSweepIntervals = []string{"soon", "3", "-1m", "500ms", "7m", "48h"}
// fakeBlacklist is a bouncer.BlacklistStore that records the Sweep calls.
type fakeBlacklist struct {
mu sync.Mutex
sweeps []time.Time
sweepErr error
}
func (f *fakeBlacklist) Add(context.Context, string, time.Time, time.Time) error { return nil }
func (f *fakeBlacklist) IsBlacklisted(context.Context, string) (bool, error) {
return false, nil
}
func (f *fakeBlacklist) Sweep(_ context.Context, now time.Time) error {
f.mu.Lock()
defer f.mu.Unlock()
f.sweeps = append(f.sweeps, now)
return f.sweepErr
}
func (f *fakeBlacklist) calls() []time.Time {
f.mu.Lock()
defer f.mu.Unlock()
return append([]time.Time(nil), f.sweeps...)
}
// TestBlacklistSweepSchedule schedules user:jwt-blacklist-sweep every 10m
// by default, before Register (nil app) too, at a custom interval, not at
// all for 0 or a bad value, and every scheduled command is a registered
// command.
func TestBlacklistSweepSchedule(t *testing.T) {
want := pact.ScheduledCommand{Command: sweepCommand, Cadence: pact.Every(10 * time.Minute)}
app := bareApp(t)
for name, p := range map[string]*Plugin{"unset": {app: app}, "nil app": {}} {
s := p.Schedule()
if len(s) != 1 || s[0].Command != want.Command || s[0].Cadence != want.Cadence || len(s[0].Args) != 0 {
t.Fatalf("%s: schedule = %+v", name, s)
}
}
names := map[string]bool{}
for _, c := range (&Plugin{app: app}).Commands() {
names[c.Name] = true
}
for _, s := range (&Plugin{app: app}).Schedule() {
if !names[s.Command] {
t.Fatalf("scheduled %s is not registered: %v", s.Command, names)
}
}
for value, every := range map[string]time.Duration{"1h": time.Hour, "30s": 30 * time.Second} {
app := bareApp(t)
if err := app.Config.Set(sweepIntervalKey, value); err != nil {
t.Fatal(err)
}
s := (&Plugin{app: app}).Schedule()
if len(s) != 1 || s[0].Command != sweepCommand || s[0].Cadence != pact.Every(every) {
t.Fatalf("%s: schedule = %+v", value, s)
}
}
for _, off := range []string{"0", "0s"} {
app := bareApp(t)
if err := app.Config.Set(sweepIntervalKey, off); err != nil {
t.Fatal(err)
}
if s := (&Plugin{app: app}).Schedule(); len(s) != 0 {
t.Fatalf("%s: schedule = %+v, want none", off, s)
}
}
if s := (&Plugin{app: envApp(t, "SUMMER_GOLEM15__USER__JWT__BLACKLIST_SWEEP_INTERVAL=0")}).Schedule(); len(s) != 0 {
t.Fatalf("SUMMER_ 0: schedule = %+v, want none", s)
}
for _, bad := range badSweepIntervals {
app := bareApp(t)
if err := app.Config.Set(sweepIntervalKey, bad); err != nil {
t.Fatal(err)
}
if s := (&Plugin{app: app}).Schedule(); s != nil {
t.Fatalf("%s: schedule = %+v, want nil", bad, s)
}
}
}
// envApp is a bare application whose config also reads environ.
func envApp(t *testing.T, environ ...string) *backpack.App {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: user-env\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: append([]string{"SUMMER_ENV=development"}, environ...)})
if err != nil {
t.Fatal(err)
}
return backpack.New(cfg)
}
// TestBlacklistSweepBoot fails Boot on an interval the scheduler cannot run,
// naming the key, and accepts 10m, 0 and an unset key.
func TestBlacklistSweepBoot(t *testing.T) {
withSecret := func(t *testing.T) *backpack.App {
app := bareApp(t)
if err := app.Config.Set("golem15.user.jwt.secret", "blacklist-sweep-boot-secret"); err != nil {
t.Fatal(err)
}
return app
}
for _, bad := range badSweepIntervals {
app := withSecret(t)
if err := app.Config.Set(sweepIntervalKey, bad); err != nil {
t.Fatal(err)
}
if err := (&Plugin{}).Boot(app); err == nil || !strings.Contains(err.Error(), sweepIntervalKey) {
t.Fatalf("Boot with %q: %v", bad, err)
}
}
for _, good := range []string{"10m", "0", ""} {
app := withSecret(t)
if good != "" {
if err := app.Config.Set(sweepIntervalKey, good); err != nil {
t.Fatal(err)
}
}
if err := (&Plugin{}).Boot(app); err != nil && strings.Contains(err.Error(), sweepIntervalKey) {
t.Fatalf("Boot with %q: %v", good, err)
}
}
}
// TestJWTBlacklistSweepCommand runs the command over a published store: one
// Sweep with the current time and the result line; a failing store is an
// error and no result line; a nil app is an error.
func TestJWTBlacklistSweepCommand(t *testing.T) {
run := func(t *testing.T, p *Plugin) (string, error) {
t.Helper()
cmd := commandNamed(t, p.Commands(), sweepCommand)
var buf bytes.Buffer
err := cmd.Run(context.Background(), emailArg{}, bonfire.NewOutput(nil, &buf, &buf))
return buf.String(), err
}
t.Run("published store", func(t *testing.T) {
app := bareApp(t)
fake := &fakeBlacklist{}
if err := app.Publish[bouncer.BlacklistStore](fake); err != nil {
t.Fatal(err)
}
before := time.Now()
out, err := run(t, &Plugin{app: app})
after := time.Now()
if err != nil {
t.Fatalf("run: %v (output %q)", err, out)
}
calls := fake.calls()
if len(calls) != 1 || calls[0].Before(before) || calls[0].After(after) {
t.Fatalf("sweeps = %v, want one between %v and %v", calls, before, after)
}
if !strings.Contains(out, "Deleted the expired JWT blacklist rows.") {
t.Fatalf("output = %q", out)
}
})
t.Run("failing store", func(t *testing.T) {
app := bareApp(t)
down := errors.New("blacklist down")
if err := app.Publish[bouncer.BlacklistStore](&fakeBlacklist{sweepErr: down}); err != nil {
t.Fatal(err)
}
out, err := run(t, &Plugin{app: app})
if !errors.Is(err, down) {
t.Fatalf("run error = %v, want it to wrap %v", err, down)
}
if strings.Contains(out, "Deleted") {
t.Fatalf("output after a failure = %q", out)
}
})
t.Run("nil app", func(t *testing.T) {
if _, err := run(t, &Plugin{}); err == nil {
t.Fatal("run with a nil app: no error")
}
})
}
// TestJWTBlacklistSweepPostgres runs user:jwt-blacklist-sweep against
// Postgres: through the store Boot published it deletes the expired row and
// keeps the one still valid; as a console command with no published
// database it opens one from database.dsn.
func TestJWTBlacklistSweepPostgres(t *testing.T) {
skipShortPostgres(t)
gdb, sqlDB := sessionDB(t)
insert := func(t *testing.T, jti string, at time.Time) {
t.Helper()
if err := gdb.Exec(`INSERT INTO jwt_blacklist (jti, expires_at, valid_until) VALUES (?, ?, ?)`, jti, at, at).Error; err != nil {
t.Fatal(err)
}
t.Cleanup(func() { gdb.Exec(`DELETE FROM jwt_blacklist WHERE jti = ?`, jti) })
}
count := func(t *testing.T, jti string) int64 {
t.Helper()
var n int64
if err := gdb.Raw(`SELECT COUNT(*) FROM jwt_blacklist WHERE jti = ?`, jti).Scan(&n).Error; err != nil {
t.Fatal(err)
}
return n
}
run := func(t *testing.T, p *Plugin) string {
t.Helper()
var buf bytes.Buffer
if err := commandNamed(t, p.Commands(), sweepCommand).Run(context.Background(), emailArg{}, bonfire.NewOutput(nil, &buf, &buf)); err != nil {
t.Fatalf("run: %v (output %q)", err, buf.String())
}
return buf.String()
}
t.Run("published store", func(t *testing.T) {
p := bootPlugin(t, newSessionApp(t, gdb, sqlDB), "0s")
insert(t, "sweep-me-published", time.Now().Add(-time.Minute))
insert(t, "sweep-keep-published", time.Now().Add(time.Hour))
out := run(t, p)
if count(t, "sweep-me-published") != 0 {
t.Fatal("the expired row was not deleted")
}
if count(t, "sweep-keep-published") != 1 {
t.Fatal("the unexpired row was deleted")
}
if !strings.Contains(out, "Deleted the expired JWT blacklist rows.") {
t.Fatalf("output = %q", out)
}
})
t.Run("database from config", func(t *testing.T) {
app := backpack.New(sessionConfig(t))
if err := app.Config.Set("database.dsn", sessionDSN); err != nil {
t.Fatal(err)
}
// Opening a database also loads the encryption keys from app.key.
if err := app.Config.Set("app.key", base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef"))); err != nil {
t.Fatal(err)
}
if _, ok := app.Lookup[*gorm.DB](); ok {
t.Fatal("setup: a database is published")
}
insert(t, "sweep-me-console", time.Now().Add(-time.Minute))
insert(t, "sweep-keep-console", time.Now().Add(time.Hour))
run(t, &Plugin{app: app})
if count(t, "sweep-me-console") != 0 {
t.Fatal("the expired row was not deleted")
}
if count(t, "sweep-keep-console") != 1 {
t.Fatal("the unexpired row was deleted")
}
})
}

86
blacklist_test.go Normal file
View File

@@ -0,0 +1,86 @@
package user
import (
"errors"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
// TestAppBlacklist: the jwt guard's store resolves the app's published
// bouncer.BlacklistStore on every call. With none published (or only an
// appBlacklist, which would recurse) no token is blacklisted and Add and
// Sweep do nothing; otherwise calls are delegated and a store error comes
// back unchanged, so the guard still fails closed.
func TestAppBlacklist(t *testing.T) {
ctx := t.Context()
now := time.Now()
newApp := func() *appBlacklist {
return &appBlacklist{app: sessionUserApp(t, "SUMMER_GOLEM15__USER__JWT__SECRET="+sessionSecret)}
}
assertNoStore := func(t *testing.T, bl *appBlacklist) {
t.Helper()
if got, err := bl.IsBlacklisted(ctx, "jti-none"); got || err != nil {
t.Fatalf("IsBlacklisted with no store = %v, %v", got, err)
}
if err := bl.Add(ctx, "jti-none", now.Add(time.Hour), now); err != nil {
t.Fatalf("Add with no store = %v", err)
}
if err := bl.Sweep(ctx, now); err != nil {
t.Fatalf("Sweep with no store = %v", err)
}
}
t.Run("no store", func(t *testing.T) {
assertNoStore(t, newApp())
})
t.Run("wrapper published as the store", func(t *testing.T) {
bl := newApp()
if err := bl.app.Publish[bouncer.BlacklistStore](&appBlacklist{app: bl.app}); err != nil {
t.Fatal(err)
}
assertNoStore(t, bl)
})
t.Run("delegates", func(t *testing.T) {
bl := newApp()
mem := bouncer.NewMemoryBlacklist()
if err := bl.app.Publish[bouncer.BlacklistStore](mem); err != nil {
t.Fatal(err)
}
// Blacklisted from now on, kept for an hour.
if err := bl.Add(ctx, "jti-ended", now.Add(time.Hour), now); err != nil {
t.Fatal(err)
}
if got, err := mem.IsBlacklisted(ctx, "jti-ended"); !got || err != nil {
t.Fatalf("memory store after Add through the wrapper = %v, %v", got, err)
}
if got, err := bl.IsBlacklisted(ctx, "jti-ended"); !got || err != nil {
t.Fatalf("IsBlacklisted(jti-ended) = %v, %v", got, err)
}
if got, err := bl.IsBlacklisted(ctx, "jti-other"); got || err != nil {
t.Fatalf("IsBlacklisted(jti-other) = %v, %v", got, err)
}
if err := bl.Sweep(ctx, now); err != nil {
t.Fatal(err)
}
})
t.Run("store error passes through", func(t *testing.T) {
bl := newApp()
if err := bl.app.Publish[bouncer.BlacklistStore](failingBlacklist{}); err != nil {
t.Fatal(err)
}
if _, err := bl.IsBlacklisted(ctx, "jti"); !errors.Is(err, errBlacklistDown) {
t.Fatalf("IsBlacklisted error = %v", err)
}
if err := bl.Add(ctx, "jti", now.Add(time.Hour), now); !errors.Is(err, errBlacklistDown) {
t.Fatalf("Add error = %v", err)
}
if err := bl.Sweep(ctx, now); !errors.Is(err, errBlacklistDown) {
t.Fatalf("Sweep error = %v", err)
}
})
}

57
classes/access_revoked.go Normal file
View File

@@ -0,0 +1,57 @@
package classes
import (
"context"
"fmt"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/pact"
"gorm.io/gorm"
)
// Reasons FireAccessRevoked is called with by this plugin.
const (
AccessRevokedBan = "ban"
AccessRevokedPasswordReset = "password_reset"
AccessRevokedPasswordSetByAdmin = "password_set_by_admin"
AccessRevokedPasswordChanged = "password_changed"
)
// FireAccessRevoked tells the application that userIDs lost every
// credential issued before before (reason names why: a ban, a password reset
// or change). It fires *AccessRevokedEvent in tx at once, so a listener
// error is returned and the caller's transaction rolls back, and then one
// "revoked" *pact.MCPSubjectChanged per user once tx commits, so MCP
// sessions of those users end on every instance. A nil app or bus, or an
// empty id list, does nothing. A nil tx fires the subject events at once.
//
// The plugin calls it from the ban action, the password reset, an
// administrator setting a password and the self-service password change.
// RevokeUserAccess, BanUsers and DeactivateUsers do not fire it: an
// application that calls RevokeUserAccess or BanUsers directly calls
// FireAccessRevoked too, in the same transaction.
func FireAccessRevoked(ctx context.Context, app *backpack.App, tx *gorm.DB, userIDs []uint, before time.Time, reason string) error {
if app == nil || app.Events == nil || len(userIDs) == 0 {
return nil
}
if ctx == nil {
ctx = context.Background()
}
ids := make([]uint, 0, len(userIDs))
for _, id := range userIDs {
if id != 0 {
ids = append(ids, id)
}
}
if len(ids) == 0 {
return nil
}
if err := app.Events.Fire(ctx, &AccessRevokedEvent{UserIDs: ids, Before: before, Reason: reason, Tx: tx}); err != nil {
return fmt.Errorf("%s: %w", AccessRevokedEventName, err)
}
for _, id := range ids {
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardUser, id, pact.MCPSubjectRevoked)
}
return nil
}

316
classes/admin_actions.go Normal file
View File

@@ -0,0 +1,316 @@
package classes
import (
"context"
"fmt"
"strconv"
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"gocloud.dev/blob"
"gorm.io/gorm"
)
// The functions in this file are the admin screen's user actions. Each takes
// the handle of the transaction the admin write runs in and never opens one
// of its own. None of them writes users_groups, except the cleanup of a user
// who is being deleted for good.
// ThrottleStates reads the ban and suspension state of userIDs from
// user_throttle in one query. A user is banned when any of their rows is
// banned, and suspended when a row is suspended and its suspended_at lies
// inside the suspension window (golem15.user.throttle.suspension_minutes,
// read from ctx as ContextWithThrottle stores it). It is a pure read: an
// expired suspension is not lifted here.
func ThrottleStates(ctx context.Context, db *gorm.DB, userIDs []uint) (banned, suspended map[uint]bool, err error) {
banned, suspended = map[uint]bool{}, map[uint]bool{}
if db == nil {
return nil, nil, fmt.Errorf("golem15.user: gorm handle is missing")
}
if len(userIDs) == 0 {
return banned, suspended, nil
}
minutes := throttleFrom(ctx).minutes
if minutes <= 0 {
minutes = 15
}
window := time.Duration(minutes) * time.Minute
var rows []models.Throttle
err = fresh(ctx, db).
Where("user_id IN ? AND (is_banned OR is_suspended)", userIDs).
Find(&rows).Error
if err != nil {
return nil, nil, err
}
now := time.Now()
for _, row := range rows {
if row.IsBanned {
banned[row.UserID] = true
}
if row.IsSuspended && row.SuspendedAt != nil && now.Before(row.SuspendedAt.Add(window)) {
suspended[row.UserID] = true
}
}
return banned, suspended, nil
}
// ActivateUsers activates the users that are not active yet and returns how
// many it changed. Like VerifyActivationCode it sets is_activated, stamps
// activated_at, clears the activation code and restores a deactivated user.
// Users that are already active are skipped.
func ActivateUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
if db == nil {
return 0, fmt.Errorf("golem15.user: gorm handle is missing")
}
changed := 0
for _, user := range users {
if user == nil || user.ID == 0 || user.IsActivated {
continue
}
now := time.Now()
err := fresh(ctx, db).Unscoped().Model(&models.User{}).Where("id = ?", user.ID).UpdateColumns(map[string]any{
"is_activated": true,
"activated_at": now,
"activation_code": nil,
"activation_code_issued_at": nil,
"deleted_at": nil,
}).Error
if err != nil {
return 0, err
}
user.IsActivated = true
user.ActivatedAt = &now
user.ActivationCode = nil
user.ActivationCodeIssuedAt = nil
user.DeletedAt = gorm.DeletedAt{}
changed++
}
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. 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")
}
changed := 0
for _, user := range users {
if user == nil || user.ID == 0 || user.DeletedAt.Valid {
continue
}
now := time.Now()
err := fresh(ctx, db).Unscoped().Model(&models.User{}).Where("id = ?", user.ID).UpdateColumn("deleted_at", now).Error
if err != nil {
return 0, err
}
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
}
// RestoreUsers brings deactivated users back, the PHP $user->restore(), and
// returns how many it changed.
func RestoreUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
if db == nil {
return 0, fmt.Errorf("golem15.user: gorm handle is missing")
}
changed := 0
for _, user := range users {
if user == nil || user.ID == 0 || !user.DeletedAt.Valid {
continue
}
err := fresh(ctx, db).Unscoped().Model(&models.User{}).Where("id = ?", user.ID).UpdateColumn("deleted_at", nil).Error
if err != nil {
return 0, err
}
user.DeletedAt = gorm.DeletedAt{}
changed++
}
return changed, nil
}
// 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). 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 {
return 0, err
}
banned, _, err := ThrottleStates(ctx, db, ids)
if err != nil {
return 0, err
}
changed := 0
for _, id := range ids {
if err := fresh(ctx, db).Model(&models.Throttle{}).Where("user_id = ?", id).UpdateColumn("is_banned", true).Error; err != nil {
return 0, err
}
var anyAddress int64
if err := fresh(ctx, db).Model(&models.Throttle{}).Where("user_id = ? AND ip_address IS NULL", id).Count(&anyAddress).Error; err != nil {
return 0, err
}
if anyAddress == 0 {
if err := fresh(ctx, db).Create(&models.Throttle{UserID: id, IsBanned: true}).Error; err != nil {
return 0, err
}
}
if !banned[id] {
changed++
}
}
if err := RevokeUserAccess(ctx, db, ids); err != nil {
return 0, err
}
return changed, nil
}
// UnbanUsers clears the ban on every user_throttle row of the users and
// returns how many were banned before.
func UnbanUsers(ctx context.Context, db *gorm.DB, users []*models.User) (int, error) {
ids, err := userIDs(db, users)
if err != nil {
return 0, err
}
banned, _, err := ThrottleStates(ctx, db, ids)
if err != nil {
return 0, err
}
changed := 0
for _, id := range ids {
if !banned[id] {
continue
}
if err := fresh(ctx, db).Model(&models.Throttle{}).Where("user_id = ?", id).UpdateColumn("is_banned", false).Error; err != nil {
return 0, err
}
changed++
}
return changed, nil
}
// UnsuspendUser lifts a suspension: it clears is_suspended, suspended_at and
// the attempt counter on every user_throttle row of the user.
func UnsuspendUser(ctx context.Context, db *gorm.DB, userID uint) error {
if db == nil {
return fmt.Errorf("golem15.user: gorm handle is missing")
}
return fresh(ctx, db).Model(&models.Throttle{}).Where("user_id = ?", userID).UpdateColumns(map[string]any{
"is_suspended": false,
"suspended_at": nil,
"attempts": 0,
}).Error
}
// ForceDeleteCleanup removes what hangs off a user who is being deleted for
// good: the user_throttle rows (their foreign key has no ON DELETE), the
// users_groups rows and the attachments. It runs inside the delete's
// transaction and does not delete the user row; the caller does that with
// the same handle. The attachments' blobs are removed only after the
// transaction commits, so a rollback leaves the files in place. bucket may be
// nil: the rows are still deleted.
func ForceDeleteCleanup(ctx context.Context, db *gorm.DB, bucket *blob.Bucket, user *models.User) error {
if db == nil {
return fmt.Errorf("golem15.user: gorm handle is missing")
}
if user == nil || user.ID == 0 {
return fmt.Errorf("golem15.user: cannot clean up a user without an id")
}
if err := fresh(ctx, db).Exec(`DELETE FROM user_throttle WHERE user_id = ?`, user.ID).Error; err != nil {
return err
}
if err := fresh(ctx, db).Exec(`DELETE FROM users_groups WHERE user_id = ?`, user.ID).Error; err != nil {
return err
}
var keys []string
err := attach.DeleteForOwner(fresh(ctx, db), user, strconv.FormatUint(uint64(user.ID), 10), func(blobKeys []string) error {
keys = append(keys, blobKeys...)
return nil
})
if err != nil {
return err
}
if bucket == nil || len(keys) == 0 {
return nil
}
userID := user.ID
lagoon.AfterCommit(ctx, db, func(ctx context.Context, _ *gorm.DB) {
// The rows are gone by now, so a blob that cannot be removed is
// orphaned, not lost data: log it and carry on.
if err := attach.DeleteKeys(ctx, bucket, keys); err != nil {
pluginLog.Warn("golem15.user: remove attachment blobs of a deleted user", "user_id", userID, "err", err)
}
})
return nil
}
// fresh returns db with an empty statement on ctx, so a query never continues
// from conditions the caller's handle already carries. A NewDB session is
// lazy: GORM builds the empty statement on the next chain method, and a
// WithContext chained directly onto it clones the caller's statement with its
// conditions instead. Clauses() makes the empty statement exist first, so the
// handle stays clean whatever is chained next.
func fresh(ctx context.Context, db *gorm.DB) *gorm.DB {
return db.Session(&gorm.Session{NewDB: true, Context: ctx}).Clauses().Session(&gorm.Session{NewDB: true})
}
// userIDs returns the ids of users, skipping nil and unsaved entries.
func userIDs(db *gorm.DB, users []*models.User) ([]uint, error) {
if db == nil {
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
}
ids := make([]uint, 0, len(users))
for _, user := range users {
if user != nil && user.ID != 0 {
ids = append(ids, user.ID)
}
}
return ids, nil
}

View File

@@ -0,0 +1,562 @@
package classes
import (
"context"
"errors"
"reflect"
"strconv"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"gocloud.dev/blob/memblob"
"gorm.io/gorm"
)
// actionUser stores an active user for the admin action tests.
func actionUser(t *testing.T, db *gorm.DB, label string, mutate func(*models.User)) *models.User {
t.Helper()
user := &models.User{Email: "action-" + label + "@example.test", IsActivated: true}
if mutate != nil {
mutate(user)
}
if err := db.Omit("Groups").Create(user).Error; err != nil {
t.Fatal(err)
}
return user
}
// actionReload reads a user row, deactivated or not.
func actionReload(t *testing.T, db *gorm.DB, id uint) models.User {
t.Helper()
var user models.User
if err := db.Unscoped().Take(&user, id).Error; err != nil {
t.Fatal(err)
}
return user
}
// actionThrottle returns the user's throttle rows ordered by id.
func actionThrottle(t *testing.T, db *gorm.DB, id uint) []models.Throttle {
t.Helper()
var rows []models.Throttle
if err := db.Where("user_id = ?", id).Order("id").Find(&rows).Error; err != nil {
t.Fatal(err)
}
return rows
}
// actionPivot is the whole users_groups table, for "nothing changed" checks.
func actionPivot(t *testing.T, db *gorm.DB) []models.UsersGroup {
t.Helper()
var rows []models.UsersGroup
if err := db.Order("user_id, user_group_id").Find(&rows).Error; err != nil {
t.Fatal(err)
}
return rows
}
// TestAdminActions covers the admin screen's user actions against a real
// Postgres: the changed-row count of each, its idempotency, and that none of
// them writes users_groups (D-13, D-14, D-29).
func TestAdminActions(t *testing.T) {
ctx := t.Context()
db := throttleDB(t)
group := models.UserGroup{Name: "Action group"}
if err := db.Create(&group).Error; err != nil {
t.Fatal(err)
}
join := func(user *models.User) {
t.Helper()
if err := db.Create(&models.UsersGroup{UserID: user.ID, UserGroupID: group.ID}).Error; err != nil {
t.Fatal(err)
}
}
t.Run("a missing handle is an error", func(t *testing.T) {
users := []*models.User{{ID: 1}}
if _, err := ActivateUsers(ctx, nil, users); err == nil {
t.Error("ActivateUsers")
}
if _, err := DeactivateUsers(ctx, nil, users); err == nil {
t.Error("DeactivateUsers")
}
if _, err := RestoreUsers(ctx, nil, users); err == nil {
t.Error("RestoreUsers")
}
if _, err := BanUsers(ctx, nil, users); err == nil {
t.Error("BanUsers")
}
if _, err := UnbanUsers(ctx, nil, users); err == nil {
t.Error("UnbanUsers")
}
if err := UnsuspendUser(ctx, nil, 1); err == nil {
t.Error("UnsuspendUser")
}
if _, _, err := ThrottleStates(ctx, nil, []uint{1}); err == nil {
t.Error("ThrottleStates")
}
if err := ForceDeleteCleanup(ctx, nil, nil, &models.User{ID: 1}); err == nil {
t.Error("ForceDeleteCleanup")
}
})
t.Run("activate, deactivate and restore", func(t *testing.T) {
code := "pending"
issued := time.Now()
idle := actionUser(t, db, "idle", func(u *models.User) {
u.IsActivated, u.ActivationCode, u.ActivationCodeIssuedAt = false, &code, &issued
})
gone := actionUser(t, db, "gone-idle", func(u *models.User) {
u.IsActivated = false
u.DeletedAt = gorm.DeletedAt{Time: time.Now(), Valid: true}
})
live := actionUser(t, db, "live", nil)
join(idle)
join(live)
before := actionPivot(t, db)
everyone := []*models.User{idle, nil, gone, live, {}}
n, err := ActivateUsers(ctx, db, everyone)
if err != nil || n != 2 {
t.Fatalf("ActivateUsers = %d %v, want the two users that were not active", n, err)
}
for _, id := range []uint{idle.ID, gone.ID} {
got := actionReload(t, db, id)
if !got.IsActivated || got.ActivatedAt == nil || got.ActivationCode != nil || got.ActivationCodeIssuedAt != nil || got.DeletedAt.Valid {
t.Fatalf("user %d after activate = %+v", id, got)
}
}
// The passed values are updated too, so the caller's next step sees them.
if !idle.IsActivated || idle.ActivationCode != nil || gone.DeletedAt.Valid {
t.Fatalf("the passed users were not updated: %+v %+v", idle, gone)
}
if n, err = ActivateUsers(ctx, db, everyone); err != nil || n != 0 {
t.Fatalf("second ActivateUsers = %d %v, want 0", n, err)
}
if n, err = DeactivateUsers(ctx, db, everyone); err != nil || n != 3 {
t.Fatalf("DeactivateUsers = %d %v, want 3", n, err)
}
for _, user := range []*models.User{idle, gone, live} {
if got := actionReload(t, db, user.ID); !got.DeletedAt.Valid || !got.IsActivated {
t.Fatalf("user %d after deactivate = %+v", user.ID, got)
}
}
if n, err = DeactivateUsers(ctx, db, everyone); err != nil || n != 0 {
t.Fatalf("second DeactivateUsers = %d %v, want 0", n, err)
}
if n, err = RestoreUsers(ctx, db, []*models.User{idle, live}); err != nil || n != 2 {
t.Fatalf("RestoreUsers = %d %v, want 2", n, err)
}
if got := actionReload(t, db, idle.ID); got.DeletedAt.Valid {
t.Fatal("restore left deleted_at")
}
if got := actionReload(t, db, gone.ID); !got.DeletedAt.Valid {
t.Fatal("restore touched a user outside its selection")
}
if n, err = RestoreUsers(ctx, db, []*models.User{idle, live}); err != nil || n != 0 {
t.Fatalf("second RestoreUsers = %d %v, want 0", n, err)
}
if !reflect.DeepEqual(actionPivot(t, db), before) {
t.Fatal("an action changed users_groups")
}
// Conditions on the caller's handle never narrow an action: each one
// starts from an empty statement.
scoped := db.Where("1 = 0")
late := actionUser(t, db, "scoped", func(u *models.User) { u.IsActivated = false })
if n, err = ActivateUsers(ctx, scoped, []*models.User{late}); err != nil || n != 1 || !actionReload(t, db, late.ID).IsActivated {
t.Fatalf("ActivateUsers through a scoped handle = %d %v", n, err)
}
if n, err = DeactivateUsers(ctx, scoped, []*models.User{late}); err != nil || n != 1 || !actionReload(t, db, late.ID).DeletedAt.Valid {
t.Fatalf("DeactivateUsers through a scoped handle = %d %v", n, err)
}
if n, err = BanUsers(ctx, scoped, []*models.User{late}); err != nil || n != 1 || len(actionThrottle(t, db, late.ID)) != 1 {
t.Fatalf("BanUsers through a scoped handle = %d %v", n, err)
}
if banned, _, err := ThrottleStates(ctx, scoped, []uint{late.ID}); err != nil || !banned[late.ID] {
t.Fatalf("ThrottleStates through a scoped handle = %v %v", banned, err)
}
})
t.Run("ban and unban", func(t *testing.T) {
several := actionUser(t, db, "several", nil)
none := actionUser(t, db, "none", nil)
anyRow := actionUser(t, db, "any-row", nil)
first, second := "203.0.113.1", "203.0.113.2"
for _, row := range []models.Throttle{
{UserID: several.ID, IPAddress: &first, Attempts: 2},
{UserID: several.ID, IPAddress: &second},
{UserID: anyRow.ID},
} {
if err := db.Create(&row).Error; err != nil {
t.Fatal(err)
}
}
join(several)
before := actionPivot(t, db)
everyone := []*models.User{several, none, anyRow, nil}
n, err := BanUsers(ctx, db, everyone)
if err != nil || n != 3 {
t.Fatalf("BanUsers = %d %v, want 3", n, err)
}
// Every row is banned, and each user has exactly one row without an
// address: created for the two who had none, kept for the third.
for user, want := range map[*models.User]int{several: 3, none: 1, anyRow: 1} {
rows := actionThrottle(t, db, user.ID)
nullRows := 0
for _, row := range rows {
if !row.IsBanned {
t.Fatalf("user %d has a row that is not banned: %+v", user.ID, row)
}
if row.IPAddress == nil {
nullRows++
}
}
if len(rows) != want || nullRows != 1 {
t.Fatalf("user %d has %d rows (%d without an address), want %d and 1", user.ID, len(rows), nullRows, want)
}
}
if rows := actionThrottle(t, db, several.ID); rows[0].Attempts != 2 {
t.Fatalf("a ban changed the attempt counter: %+v", rows[0])
}
if n, err = BanUsers(ctx, db, everyone); err != nil || n != 0 {
t.Fatalf("second BanUsers = %d %v, want 0", n, err)
}
if rows := actionThrottle(t, db, none.ID); len(rows) != 1 {
t.Fatalf("a second ban created another row: %d", len(rows))
}
banned, suspended, err := ThrottleStates(ctx, db, []uint{several.ID, none.ID, anyRow.ID, 987654})
if err != nil || len(banned) != 3 || len(suspended) != 0 {
t.Fatalf("ThrottleStates = %v %v %v", banned, suspended, err)
}
// A mixed selection counts only the users who were banned.
fresh := actionUser(t, db, "never-banned", nil)
if n, err = UnbanUsers(ctx, db, []*models.User{several, fresh, nil}); err != nil || n != 1 {
t.Fatalf("UnbanUsers = %d %v, want 1", n, err)
}
for _, row := range actionThrottle(t, db, several.ID) {
if row.IsBanned {
t.Fatalf("a row stayed banned: %+v", row)
}
}
if rows := actionThrottle(t, db, fresh.ID); len(rows) != 0 {
t.Fatalf("unban created a row for a user who was not banned: %+v", rows)
}
if rows := actionThrottle(t, db, none.ID); !rows[0].IsBanned {
t.Fatal("unban touched a user outside its selection")
}
if n, err = UnbanUsers(ctx, db, []*models.User{several}); err != nil || n != 0 {
t.Fatalf("second UnbanUsers = %d %v, want 0", n, err)
}
if !reflect.DeepEqual(actionPivot(t, db), before) {
t.Fatal("ban or unban changed users_groups")
}
})
t.Run("the suspension window is a pure read", func(t *testing.T) {
inside := actionUser(t, db, "inside", nil)
expired := actionUser(t, db, "expired", nil)
flagged := actionUser(t, db, "flagged", nil)
recent, longAgo := time.Now().Add(-14*time.Minute), time.Now().Add(-16*time.Minute)
ip := "203.0.113.9"
for _, row := range []models.Throttle{
{UserID: inside.ID, IPAddress: &ip, IsSuspended: true, SuspendedAt: &recent, Attempts: 5},
{UserID: expired.ID, IPAddress: &ip, IsSuspended: true, SuspendedAt: &longAgo, Attempts: 5},
// Suspended without a time: not inside any window.
{UserID: flagged.ID, IPAddress: &ip, IsSuspended: true, Attempts: 5},
} {
if err := db.Create(&row).Error; err != nil {
t.Fatal(err)
}
}
ids := []uint{inside.ID, expired.ID, flagged.ID}
_, suspended, err := ThrottleStates(ctx, db, ids)
if err != nil || !reflect.DeepEqual(suspended, map[uint]bool{inside.ID: true}) {
t.Fatalf("suspended = %v %v, want only the user inside the 15 minute window", suspended, err)
}
// A shorter window from the context moves the boundary.
short := withThrottle(ctx, throttleSettings{use: true, limit: 5, minutes: 10})
if _, suspended, err = ThrottleStates(short, db, ids); err != nil || len(suspended) != 0 {
t.Fatalf("suspended under a 10 minute window = %v %v", suspended, err)
}
long := withThrottle(ctx, throttleSettings{use: true, limit: 5, minutes: 30})
if _, suspended, err = ThrottleStates(long, db, ids); err != nil || len(suspended) != 2 {
t.Fatalf("suspended under a 30 minute window = %v %v", suspended, err)
}
// A window of zero falls back to the default.
zero := withThrottle(ctx, throttleSettings{use: true})
if _, suspended, err = ThrottleStates(zero, db, ids); err != nil || len(suspended) != 1 {
t.Fatalf("suspended under a zero window = %v %v", suspended, err)
}
// Reading changed nothing: the expired suspension is still flagged.
for _, id := range ids {
if rows := actionThrottle(t, db, id); len(rows) != 1 || !rows[0].IsSuspended || rows[0].Attempts != 5 {
t.Fatalf("reading the state changed the row of %d: %+v", id, rows)
}
}
banned, suspended, err := ThrottleStates(ctx, db, nil)
if err != nil || banned == nil || suspended == nil || len(banned)+len(suspended) != 0 {
t.Fatalf("ThrottleStates without ids = %v %v %v", banned, suspended, err)
}
if err := UnsuspendUser(ctx, db, inside.ID); err != nil {
t.Fatal(err)
}
if rows := actionThrottle(t, db, inside.ID); rows[0].IsSuspended || rows[0].SuspendedAt != nil || rows[0].Attempts != 0 {
t.Fatalf("row after unsuspend = %+v", rows[0])
}
if rows := actionThrottle(t, db, expired.ID); !rows[0].IsSuspended {
t.Fatal("unsuspend touched another user")
}
// Idempotent, and a user without rows is no error.
if err := UnsuspendUser(ctx, db, inside.ID); err != nil {
t.Fatal(err)
}
if err := UnsuspendUser(ctx, db, 987654); err != nil {
t.Fatal(err)
}
})
t.Run("the cleanup of a permanent delete", func(t *testing.T) {
bucket := memblob.OpenBucket(nil)
t.Cleanup(func() { _ = bucket.Close() })
// The class harness runs the plugin's migrations only; system_files is
// the framework's table.
if err := db.AutoMigrate(&attach.File{}); err != nil {
t.Fatal(err)
}
loaded := func(label string) (*models.User, string) {
t.Helper()
user := actionUser(t, db, label, nil)
join(user)
ip := "203.0.113.20"
for _, row := range []models.Throttle{{UserID: user.ID, IPAddress: &ip}, {UserID: user.ID, IsBanned: true}} {
if err := db.Create(&row).Error; err != nil {
t.Fatal(err)
}
}
disk := "cleanup-" + label + ".jpg"
key := attach.BlobKey(disk)
if err := bucket.WriteAll(ctx, key, []byte("avatar"), nil); err != nil {
t.Fatal(err)
}
file := attach.File{DiskName: disk, FileName: "a.jpg", FileSize: 6, ContentType: "image/jpeg", Field: models.AvatarField,
AttachmentID: strconv.FormatUint(uint64(user.ID), 10), AttachmentType: user.MorphName()}
if err := db.Create(&file).Error; err != nil {
t.Fatal(err)
}
return user, key
}
left := func(user *models.User) [3]int64 {
t.Helper()
var out [3]int64
for i, query := range []string{
`SELECT COUNT(*) FROM user_throttle WHERE user_id = ?`,
`SELECT COUNT(*) FROM users_groups WHERE user_id = ?`,
} {
if err := db.Raw(query, user.ID).Scan(&out[i]).Error; err != nil {
t.Fatal(err)
}
}
err := db.Raw(`SELECT COUNT(*) FROM system_files WHERE attachment_type = ? AND attachment_id = ?`,
user.MorphName(), strconv.FormatUint(uint64(user.ID), 10)).Scan(&out[2]).Error
if err != nil {
t.Fatal(err)
}
return out
}
exists := func(key string) bool {
t.Helper()
ok, err := bucket.Exists(ctx, key)
if err != nil {
t.Fatal(err)
}
return ok
}
// A transaction that rolls back keeps the rows and the blob.
kept, keptKey := loaded("kept")
bystander, bystanderKey := loaded("bystander")
rollback := errors.New("rollback")
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
if err := ForceDeleteCleanup(ctx, tx, bucket, kept); err != nil {
return err
}
return rollback
})
if !errors.Is(err, rollback) || left(kept) != [3]int64{2, 1, 1} || !exists(keptKey) {
t.Fatalf("after a rollback: err=%v rows=%v blob=%v", err, left(kept), exists(keptKey))
}
// A committed one removes the rows, and the blob after the commit.
err = lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
if err := ForceDeleteCleanup(ctx, tx, bucket, kept); err != nil {
return err
}
if !exists(keptKey) {
t.Error("the blob was removed before the commit")
}
return nil
})
if err != nil || left(kept) != [3]int64{} || exists(keptKey) {
t.Fatalf("after the commit: err=%v rows=%v blob=%v", err, left(kept), exists(keptKey))
}
// The user row itself is the caller's to delete.
if got := actionReload(t, db, kept.ID); got.ID != kept.ID {
t.Fatal("the cleanup deleted the user row")
}
if left(bystander) != [3]int64{2, 1, 1} || !exists(bystanderKey) {
t.Fatal("the cleanup touched another user")
}
// Idempotent: nothing left to remove is no error.
if err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
return ForceDeleteCleanup(ctx, tx, bucket, kept)
}); err != nil {
t.Fatal(err)
}
// Without a bucket the rows still go; the blob is left for the host.
err = lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
return ForceDeleteCleanup(ctx, tx, nil, bystander)
})
if err != nil || left(bystander) != [3]int64{} || !exists(bystanderKey) {
t.Fatalf("without a bucket: err=%v rows=%v blob=%v", err, left(bystander), exists(bystanderKey))
}
for _, user := range []*models.User{nil, {}} {
if err := ForceDeleteCleanup(ctx, db, bucket, user); err == nil {
t.Fatalf("cleanup of %+v was accepted", user)
}
}
// Only the group itself is left of the pivot's side.
var groups int64
if err := db.Model(&models.UserGroup{}).Where("id = ?", group.ID).Count(&groups).Error; err != nil || groups != 1 {
t.Fatalf("the cleanup removed the group: %d %v", groups, err)
}
})
}
// 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)
}
}
})
}

209
classes/api_token_scopes.go Normal file
View File

@@ -0,0 +1,209 @@
package classes
import (
"fmt"
"slices"
"strings"
"sync"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/party"
)
// APITokenScope is one scope a member personal API token (usr_) may carry:
// a built-in (read, write, ai) or one a plugin declared through
// pact.HasFrontendTokenScopes. Label and Description are phrase keys
// (containing "::") or literal text; PluginID is the declaring plugin, empty
// for a built-in. Implies is empty on a built-in. On a declared scope it is
// empty, read, or write: an OAuth MCP grant of that stock scope also
// satisfies the declared name. The name is not stored on the grant.
type APITokenScope struct {
Name string
Label string
Description string
PluginID string
BuiltIn bool
Implies string
}
// APITokenScopeCatalog is the compiled list of member token scopes of one
// application: the built-ins first, then the declared scopes in activation
// order. Boot publishes it, and the same value as pact.MemberTokenScopeCatalog.
// APITokenScopesFor reads the concrete catalog.
type APITokenScopeCatalog struct {
scopes []APITokenScope
byName map[string]int
}
var _ pact.MemberTokenScopeCatalog = (*APITokenScopeCatalog)(nil)
// Scopes returns a copy of the catalog, built-ins first.
func (c *APITokenScopeCatalog) Scopes() []APITokenScope {
if c == nil {
return builtInAPITokenScopes()
}
return slices.Clone(c.scopes)
}
// Allowed reports whether a member token may carry name in this catalog.
func (c *APITokenScopeCatalog) Allowed(name string) bool {
if c == nil {
return slices.Contains(AllowedAPITokenScopes, name)
}
_, ok := c.byName[name]
return ok
}
// MemberTokenScopes returns the compiled list as pact scopes, built-ins
// first, then declared scopes. Implied names are not a separate entry: they
// are the Implies field of the declared scope.
func (c *APITokenScopeCatalog) MemberTokenScopes() []pact.FrontendTokenScope {
scopes := c.Scopes()
out := make([]pact.FrontendTokenScope, 0, len(scopes))
for _, scope := range scopes {
out = append(out, pact.FrontendTokenScope{
Name: scope.Name,
Label: scope.Label,
Description: scope.Description,
Implies: scope.Implies,
})
}
return out
}
// builtInAPITokenScopeKeys are the label and description phrase keys of
// the built-in scopes, in AllowedAPITokenScopes order.
var builtInAPITokenScopeKeys = map[string][2]string{
"read": {"golem15.user::lang.api_tokens.scope_read", "golem15.user::lang.api_tokens.scope_read_description"},
"write": {"golem15.user::lang.api_tokens.scope_write", "golem15.user::lang.api_tokens.scope_write_description"},
"ai": {"golem15.user::lang.api_tokens.scope_ai", "golem15.user::lang.api_tokens.scope_ai_description"},
}
// builtInAPITokenScopes are AllowedAPITokenScopes with their phrase keys.
func builtInAPITokenScopes() []APITokenScope {
out := make([]APITokenScope, 0, len(AllowedAPITokenScopes))
for _, name := range AllowedAPITokenScopes {
keys := builtInAPITokenScopeKeys[name]
out = append(out, APITokenScope{Name: name, Label: keys[0], Description: keys[1], BuiltIn: true})
}
return out
}
func newAPITokenScopeCatalog(scopes []APITokenScope) *APITokenScopeCatalog {
c := &APITokenScopeCatalog{scopes: scopes, byName: make(map[string]int, len(scopes))}
for i, scope := range scopes {
c.byName[scope.Name] = i
}
return c
}
// CompileAPITokenScopes builds the member token scope catalog from the
// built-ins and every plugin that implements pact.HasFrontendTokenScopes, in
// the order given (party.Activated). A declared name is trimmed and must
// pass pact.ValidTokenScopeName, must not be a built-in (read, write, ai),
// must not be the reserved name backend or offline_access, and must not
// repeat a name another plugin (or the same one) declared; its label and
// description must not be empty, and Implies must be empty, read, or write.
// Built-ins keep Implies empty. Any violation is an error, which fails boot.
// Phrase keys are checked against the translator by Boot. Every name of a
// catalog that compiles is added to the process-wide set the legacy
// MintAPIToken accepts.
func CompileAPITokenScopes(plugins []party.Plugin) (*APITokenScopeCatalog, error) {
scopes := builtInAPITokenScopes()
owner := map[string]string{}
for _, scope := range scopes {
owner[scope.Name] = ""
}
var declared []string
for _, plugin := range plugins {
if plugin == nil {
continue
}
src, ok := plugin.(pact.HasFrontendTokenScopes)
if !ok || src == nil {
continue
}
id := plugin.ID()
for _, scope := range src.FrontendTokenScopes() {
name := strings.TrimSpace(scope.Name)
if name == "" || !pact.ValidTokenScopeName(name) {
return nil, fmt.Errorf("golem15.user: plugin %s declared invalid member token scope name %q", id, scope.Name)
}
if other, taken := owner[name]; taken {
if other == "" {
return nil, fmt.Errorf("golem15.user: plugin %s declared the built-in member token scope %q", id, name)
}
return nil, fmt.Errorf("golem15.user: duplicate member token scope %q declared by %s and %s", name, other, id)
}
if name == "backend" || name == "offline_access" {
return nil, fmt.Errorf("golem15.user: plugin %s declared the reserved member token scope %q", id, name)
}
if strings.TrimSpace(scope.Label) == "" {
return nil, fmt.Errorf("golem15.user: plugin %s member token scope %s has an empty label", id, name)
}
if strings.TrimSpace(scope.Description) == "" {
return nil, fmt.Errorf("golem15.user: plugin %s member token scope %s has an empty description", id, name)
}
if scope.Implies != "" && scope.Implies != "read" && scope.Implies != "write" {
return nil, fmt.Errorf("golem15.user: plugin %s member token scope %s has implies %q", id, name, scope.Implies)
}
owner[name] = id
scopes = append(scopes, APITokenScope{
Name: name, Label: scope.Label, Description: scope.Description, PluginID: id, Implies: scope.Implies,
})
declared = append(declared, name)
}
}
declaredScopes.add(declared)
return newAPITokenScopeCatalog(scopes), nil
}
// APITokenScopesFor returns the catalog Boot published on app, or the
// built-ins alone when none is published.
func APITokenScopesFor(app *backpack.App) *APITokenScopeCatalog {
if app != nil {
if catalog, ok := app.Lookup[*APITokenScopeCatalog](); ok && catalog != nil {
return catalog
}
}
return newAPITokenScopeCatalog(builtInAPITokenScopes())
}
// declaredScopes is the process-wide set of every member token scope name a
// compiled catalog declared, the legacy MintAPIToken's fallback. Production
// runs one application per process, so it equals that application's
// declared scopes.
var declaredScopes = &scopeSet{names: map[string]bool{}}
type scopeSet struct {
mu sync.RWMutex
names map[string]bool
}
func (s *scopeSet) add(names []string) {
if len(names) == 0 {
return
}
s.mu.Lock()
defer s.mu.Unlock()
for _, name := range names {
s.names[name] = true
}
}
func (s *scopeSet) has(name string) bool {
s.mu.RLock()
defer s.mu.RUnlock()
return s.names[name]
}
// ResetDeclaredAPITokenScopes clears the process-wide set of declared member
// token scopes that the legacy MintAPIToken accepts. It is a test seam for
// tests outside this package that compile catalogs; production never calls
// it.
func ResetDeclaredAPITokenScopes() {
declaredScopes.mu.Lock()
defer declaredScopes.mu.Unlock()
declaredScopes.names = map[string]bool{}
}

View File

@@ -18,6 +18,9 @@ import (
const DefaultAPITokenPrefix = "usr_" const DefaultAPITokenPrefix = "usr_"
// DefaultAPITokenScopes is what a token minted without scopes carries, and
// AllowedAPITokenScopes are the built-in member token scopes. Plugins add
// their own through pact.HasFrontendTokenScopes (APITokenScopeCatalog).
var ( var (
DefaultAPITokenScopes = []string{"read"} DefaultAPITokenScopes = []string{"read"}
AllowedAPITokenScopes = []string{"read", "write", "ai"} AllowedAPITokenScopes = []string{"read", "write", "ai"}
@@ -44,8 +47,31 @@ func APITokenPrefix(app *backpack.App) (string, error) {
} }
// MintAPIToken builds a token record and returns its one-time clear-text // MintAPIToken builds a token record and returns its one-time clear-text
// secret. A nil scopes slice receives DefaultAPITokenScopes. // secret. A nil scopes slice receives DefaultAPITokenScopes. It accepts the
// built-in scopes (AllowedAPITokenScopes) and, as a fallback for existing
// callers, every member token scope a catalog compiled in this process
// declared (CompileAPITokenScopes). New code calls MintAPITokenFor, which
// checks the scopes against the application's own catalog.
//
// Deprecated: the declared-scope fallback is process-wide, so in a process
// that boots several applications it accepts another application's scopes.
// Use MintAPITokenFor.
func MintAPIToken(prefix string, userID uint, name string, scopes []string, expiresAt *time.Time, collectionIDs []uint) (string, *models.APIToken, error) { func MintAPIToken(prefix string, userID uint, name string, scopes []string, expiresAt *time.Time, collectionIDs []uint) (string, *models.APIToken, error) {
return mintAPIToken(prefix, userID, name, scopes, expiresAt, collectionIDs, func(scope string) bool {
return slices.Contains(AllowedAPITokenScopes, scope) || declaredScopes.has(scope)
})
}
// MintAPITokenFor is MintAPIToken with the scopes checked against app's
// member token scope catalog (APITokenScopesFor): the built-ins and the
// scopes app's activated plugins declared through
// pact.HasFrontendTokenScopes. A scope another application in the same
// process declared is refused.
func MintAPITokenFor(app *backpack.App, prefix string, userID uint, name string, scopes []string, expiresAt *time.Time, collectionIDs []uint) (string, *models.APIToken, error) {
return mintAPIToken(prefix, userID, name, scopes, expiresAt, collectionIDs, APITokenScopesFor(app).Allowed)
}
func mintAPIToken(prefix string, userID uint, name string, scopes []string, expiresAt *time.Time, collectionIDs []uint, allowed func(string) bool) (string, *models.APIToken, error) {
name = strings.TrimSpace(name) name = strings.TrimSpace(name)
if userID == 0 || name == "" || len(name) > 255 { if userID == 0 || name == "" || len(name) > 255 {
return "", nil, fmt.Errorf("a user and token name of 1 to 255 characters are required") return "", nil, fmt.Errorf("a user and token name of 1 to 255 characters are required")
@@ -59,7 +85,7 @@ func MintAPIToken(prefix string, userID uint, name string, scopes []string, expi
scopes = slices.Clone(scopes) scopes = slices.Clone(scopes)
} }
for _, scope := range scopes { for _, scope := range scopes {
if !slices.Contains(AllowedAPITokenScopes, scope) { if !allowed(scope) {
return "", nil, fmt.Errorf("scope %q is not allowed", scope) return "", nil, fmt.Errorf("scope %q is not allowed", scope)
} }
} }

48
classes/authorizer.go Normal file
View File

@@ -0,0 +1,48 @@
package classes
import (
"context"
"strings"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/lighthouse"
)
// AuthorizeUser is the lighthouse authorizer for the user namespace
// (D-17, T-19-10). It allows only user:{id} for that user. ChannelID is
// the two-segment reader (segment 1 is the id). A second presence: prefix
// or extra segments are denied.
func AuthorizeUser() lighthouse.AuthorizerFunc {
return func(_ context.Context, userID uint, channel string) lighthouse.Result {
name := strings.TrimPrefix(channel, "presence:")
if strings.HasPrefix(name, "presence:") {
return lighthouse.Denied("invalid user channel")
}
parts := strings.Split(name, ":")
if len(parts) != 2 || parts[0] != "user" {
return lighthouse.Denied("invalid user channel")
}
if userID == 0 || lighthouse.ChannelID(name) != int64(userID) {
return lighthouse.Denied("not that user")
}
return lighthouse.Allowed(nil)
}
}
// RegisterUserAuthorizer registers the user namespace if it is free. A
// missing lighthouse service is skipped so Boot stays additive on hosts
// that never mount realtime.
func RegisterUserAuthorizer(app *backpack.App) error {
svc, err := lighthouse.From(app)
if err != nil {
pluginLog.Warn("golem15.user: lighthouse unavailable; user authorizer not registered", "err", err)
return nil
}
if svc == nil || svc.Registry() == nil {
return nil
}
if _, ok := svc.Registry().Get("user"); ok {
return nil
}
return svc.Registry().Register("user", AuthorizeUser())
}

View File

@@ -0,0 +1,36 @@
package classes
import (
"context"
"testing"
"git.golem15.com/golem15/summercms/modules/lighthouse"
)
// TestUserAuthorizer: user:9 is allowed only for user 9 (T-19-10).
func TestUserAuthorizer(t *testing.T) {
auth := AuthorizeUser()
ctx := context.Background()
if got := auth.Authorize(ctx, 9, "user:9"); !got.Allowed {
t.Fatalf("user:9 for 9 denied: %s", got.Reason())
}
if got := auth.Authorize(ctx, 9, "presence:user:9"); !got.Allowed {
t.Fatalf("presence:user:9 for 9 denied: %s", got.Reason())
}
if lighthouse.ChannelID("user:9") != 9 {
t.Fatalf("ChannelID(user:9) = %d, want 9", lighthouse.ChannelID("user:9"))
}
for _, channel := range []string{"user:8", "user:9:extra", "chat:9", "user:", "user", "presence:presence:user:9"} {
if got := auth.Authorize(ctx, 9, channel); got.Allowed {
t.Errorf("%q for 9 allowed, want deny", channel)
}
}
if got := auth.Authorize(ctx, 8, "user:9"); got.Allowed {
t.Fatal("user:9 for 8 allowed, want deny")
}
if got := auth.Authorize(ctx, 0, "user:0"); got.Allowed {
t.Fatal("user:0 for 0 allowed, want deny")
}
}

65
classes/avatar.go Normal file
View File

@@ -0,0 +1,65 @@
package classes
import (
"context"
"crypto/md5"
"errors"
"fmt"
"strconv"
"strings"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"gocloud.dev/blob"
"gorm.io/gorm"
)
// AvatarURL returns the display picture URL of user at size pixels, the
// rule the user API payload follows: the thumbnail (size by size, mode
// auto) of the user's avatar attachment when there is one and a file
// bucket is published, the original file's public URL (attach.File.URL,
// following storage.uploads.public_path_prefix and public_url) when the
// thumbnail fails (logged), and otherwise the gravatar URL
// //www.gravatar.com/avatar/{md5 of the email}?s={size}&d=mm. The URL may
// be protocol-relative or relative; a caller that needs an absolute URL
// resolves it. Only a failing database lookup is an error.
func AvatarURL(ctx context.Context, app *backpack.App, user *models.User, size int) (string, error) {
if user == nil {
return "", errors.New("golem15.user: avatar needs a user")
}
fallback := gravatar(user.Email, size)
if app == nil || user.ID == 0 {
return fallback, nil
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok || gdb == nil {
return fallback, nil
}
var f attach.File
err := gdb.WithContext(ctx).
Where("attachment_type = ? AND attachment_id = ? AND field = ?", user.MorphName(), strconv.FormatUint(uint64(user.ID), 10), models.AvatarField).
Take(&f).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return fallback, nil
}
if err != nil {
return "", err
}
bucket, ok := app.Lookup[*blob.Bucket]()
if !ok || bucket == nil {
return fallback, nil
}
url, err := f.Thumb(ctx, bucket, size, size, "auto")
if err != nil {
pluginLog.Error("golem15.user: avatar thumb", "err", err)
return f.URL(), nil
}
return url, nil
}
// gravatar is the gravatar URL of an email at size pixels.
func gravatar(email string, size int) string {
sum := md5.Sum([]byte(strings.ToLower(strings.TrimSpace(email))))
return fmt.Sprintf("//www.gravatar.com/avatar/%x?s=%d&d=mm", sum, size)
}

555
classes/backend_links.go Normal file
View File

@@ -0,0 +1,555 @@
package classes
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"github.com/jackc/pgx/v5/pgconn"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// Errors of the account link service. A request that is unknown, used or
// expired is reported apart so callers can log the difference; the site
// routes answer all three with the same 404.
var (
ErrLinkRequestNotFound = errors.New("golem15.user: backend link request not found")
ErrLinkRequestUsed = errors.New("golem15.user: backend link request already used")
ErrLinkRequestExpired = errors.New("golem15.user: backend link request expired")
ErrStaleSession = errors.New("golem15.user: the session was signed in before the link request")
ErrAlreadyLinked = errors.New("golem15.user: one of the accounts is already linked")
ErrBackendUserUnavailable = errors.New("golem15.user: the administrator is missing or not activated")
ErrFrontendUserUnavailable = errors.New("golem15.user: the frontend user is missing or deactivated")
)
// DefaultBackendLinkRequestTTL is how long a link request stays usable when
// golem15.user.backend_links.request_ttl is not set.
const DefaultBackendLinkRequestTTL = 10 * time.Minute
var _ pact.MCPLinkedBackendResolver = (*BackendLinks)(nil)
// BackendLinks is the verified link between a frontend user and a backend
// administrator (D-03): one link per account on each side, written either
// after the frontend user proves the account with a fresh sign-in
// (CreateLinkRequest, then ConfirmLinkRequest) or by an administrator with
// golem15.users.manage_backend_links on the Administrators screen (SetLink).
// Boot publishes it as *BackendLinks and as pact.MCPLinkedBackendResolver.
//
// Every read and write uses the transaction cabana runs a hook or an action
// in when the context carries one (cabana.TxFromContext), else the
// application's database.
type BackendLinks struct {
App *backpack.App
}
// BackendLinksFor returns the link service Boot published on app, or one
// over app when none is published.
func BackendLinksFor(app *backpack.App) *BackendLinks {
if app != nil {
if links, ok := app.Lookup[*BackendLinks](); ok && links != nil {
return links
}
}
return &BackendLinks{App: app}
}
// BackendLinkRequestTTL reads golem15.user.backend_links.request_ttl, a Go
// duration (10m by default). A value that does not parse or is not positive
// is an error, so a typo fails the boot instead of silently changing the
// lifetime.
func BackendLinkRequestTTL(app *backpack.App) (time.Duration, error) {
if app == nil || app.Config == nil {
return DefaultBackendLinkRequestTTL, nil
}
raw := strings.TrimSpace(app.Config.String("golem15.user.backend_links.request_ttl"))
if raw == "" {
return DefaultBackendLinkRequestTTL, nil
}
ttl, err := time.ParseDuration(raw)
if err != nil || ttl <= 0 {
return 0, fmt.Errorf("golem15.user: backend_links.request_ttl must be a positive duration such as 10m, got %q", raw)
}
return ttl, nil
}
// DefaultBackendLinkPagePath is the site page the account link points to when
// golem15.user.backend_links.page_path is not set.
const DefaultBackendLinkPagePath = "/link-admin"
// BackendLinkPagePath reads golem15.user.backend_links.page_path, the path of
// the site page that confirms an account link (default /link-admin). A value
// without a leading slash gets one.
func BackendLinkPagePath(app *backpack.App) string {
if app == nil || app.Config == nil {
return DefaultBackendLinkPagePath
}
path := strings.TrimSpace(app.Config.String("golem15.user.backend_links.page_path"))
if path == "" {
return DefaultBackendLinkPagePath
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return path
}
// FrontendURL is the site the plugin sends people to for pages it does not
// serve itself (the account link page): golem15.user.frontend_url, falling
// back to app.url, without a trailing slash. Empty when neither is set.
func FrontendURL(app *backpack.App) string {
if app == nil || app.Config == nil {
return ""
}
base := strings.TrimSpace(app.Config.String("golem15.user.frontend_url"))
if base == "" {
base = strings.TrimSpace(app.Config.String("app.url"))
}
return strings.TrimRight(base, "/")
}
// db returns the handle a call works on: the cabana transaction on ctx, or
// the application's database.
func (s *BackendLinks) db(ctx context.Context) (*gorm.DB, error) {
if tx, ok := cabana.TxFromContext(ctx); ok {
return fresh(ctx, tx), nil
}
if s == nil || s.App == nil {
return nil, fmt.Errorf("golem15.user: app is nil")
}
gdb, ok := s.App.Lookup[*gorm.DB]()
if !ok || gdb == nil {
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
}
return gdb.WithContext(ctx), nil
}
// hashLinkCode is the only form of a link code that is stored.
func hashLinkCode(plain string) string {
sum := sha256.Sum256([]byte(plain))
return hex.EncodeToString(sum[:])
}
// validLinkCode reports whether plain has the shape CreateLinkRequest
// issues: 64 lower-case hex characters.
func validLinkCode(plain string) bool {
if len(plain) != 64 {
return false
}
for _, r := range plain {
if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f') {
return false
}
}
return true
}
// CreateLinkRequest starts a link for the administrator: a one-shot code
// (32 random bytes, hex) valid for golem15.user.backend_links.request_ttl,
// stored as its SHA-256. The administrator's earlier requests that were not
// used are dropped, so only the newest code works. The plain code is
// returned once, for the site URL.
func (s *BackendLinks) CreateLinkRequest(ctx context.Context, backendUserID uint) (string, time.Time, error) {
if backendUserID == 0 {
return "", time.Time{}, ErrBackendUserUnavailable
}
ttl, err := BackendLinkRequestTTL(s.app())
if err != nil {
return "", time.Time{}, err
}
db, err := s.db(ctx)
if err != nil {
return "", time.Time{}, err
}
plain, err := newCode()
if err != nil {
return "", time.Time{}, err
}
now := time.Now()
req := &models.BackendLinkRequest{
CodeHash: hashLinkCode(plain),
BackendUserID: backendUserID,
ExpiresAt: now.Add(ttl),
CreatedAt: now,
}
if err := fresh(ctx, db).Where("backend_user_id = ? AND used_at IS NULL", backendUserID).
Delete(&models.BackendLinkRequest{}).Error; err != nil {
return "", time.Time{}, err
}
if err := fresh(ctx, db).Create(req).Error; err != nil {
return "", time.Time{}, err
}
return plain, req.ExpiresAt, nil
}
// LinkRequestByCode returns a usable request and its administrator for the
// site's link page. An unknown, used or expired code is
// ErrLinkRequestNotFound, ErrLinkRequestUsed or ErrLinkRequestExpired; an
// administrator who was deactivated or deleted since is
// ErrBackendUserUnavailable.
func (s *BackendLinks) LinkRequestByCode(ctx context.Context, plain string) (*models.BackendLinkRequest, *cabana.BackendUser, error) {
if !validLinkCode(plain) {
return nil, nil, ErrLinkRequestNotFound
}
db, err := s.db(ctx)
if err != nil {
return nil, nil, err
}
var rows []models.BackendLinkRequest
if err := fresh(ctx, db).Where("code_hash = ?", hashLinkCode(plain)).Limit(1).Find(&rows).Error; err != nil {
return nil, nil, err
}
if len(rows) == 0 {
return nil, nil, ErrLinkRequestNotFound
}
req := &rows[0]
if err := requestUsable(req, time.Now()); err != nil {
return nil, nil, err
}
admin, err := activeBackendUser(ctx, db, req.BackendUserID)
if err != nil {
return nil, nil, err
}
return req, admin, nil
}
// requestUsable answers why a request cannot be used (used or expired), or
// nil when req.IsUsableAt(now).
func requestUsable(req *models.BackendLinkRequest, now time.Time) error {
if req.IsUsableAt(now) {
return nil
}
if req.UsedAt != nil {
return ErrLinkRequestUsed
}
return ErrLinkRequestExpired
}
// ConfirmLinkRequest stores the link between the signed-in frontend user and
// the administrator who created the request, in one transaction: the request
// row is locked, must be unused and unexpired, and the session must have
// been signed in at or after the request was created, so a browser that was
// already signed in has to sign in again (D-05). sessionAuthTime is the
// session token's auth_time claim (bouncer.VerifyAuthTime): the time of the
// sign-in itself, which a refresh copies and never renews. It is compared in
// whole seconds with the request's created_at because the claim has no
// fraction, which leaves a one-second blind spot: a sign-in earlier in the
// same second as the request, but before it, counts as fresh. Telling the
// two apart would need a sub-second claim; refusing that whole second
// instead would make a sign-in in the request's own second sign in once
// more. The window is accepted (it needs a sign-in in the very second the
// administrator starts the link). A zero time is ErrStaleSession. Neither
// account may be linked already (ErrAlreadyLinked) and the administrator
// must still be activated (ErrBackendUserUnavailable). The request is used
// up with the link; BackendLinkedEvent fires inside the transaction and the
// two pact.MCPSubjectChanged events after it commits.
func (s *BackendLinks) ConfirmLinkRequest(ctx context.Context, plain string, frontendUserID uint, sessionAuthTime time.Time) (*models.BackendLink, error) {
if !validLinkCode(plain) {
return nil, ErrLinkRequestNotFound
}
if frontendUserID == 0 {
return nil, ErrFrontendUserUnavailable
}
gdb, err := s.pool()
if err != nil {
return nil, err
}
var link *models.BackendLink
err = lagoon.Transaction(ctx, gdb, func(ctx context.Context, tx *gorm.DB) error {
var rows []models.BackendLinkRequest
if err := fresh(ctx, tx).Clauses(clause.Locking{Strength: "UPDATE"}).
Where("code_hash = ?", hashLinkCode(plain)).Limit(1).Find(&rows).Error; err != nil {
return err
}
if len(rows) == 0 {
return ErrLinkRequestNotFound
}
req := &rows[0]
now := time.Now()
if err := requestUsable(req, now); err != nil {
return err
}
// Whole seconds on both sides: see the blind spot above.
if sessionAuthTime.IsZero() || sessionAuthTime.Before(req.CreatedAt.Truncate(time.Second)) {
return ErrStaleSession
}
if _, err := activeBackendUser(ctx, tx, req.BackendUserID); err != nil {
return err
}
created, err := s.insertLink(ctx, tx, frontendUserID, req.BackendUserID, nil)
if err != nil {
return err
}
if err := fresh(ctx, tx).Model(&models.BackendLinkRequest{}).Where("id = ?", req.ID).
Update("used_at", now).Error; err != nil {
return err
}
link = created
return nil
})
if err != nil {
return nil, err
}
return link, nil
}
// SetLink stores a link an administrator sets on the Administrators screen
// (D-07): the frontend user must exist and not be deactivated
// (ErrFrontendUserUnavailable), the administrator must be activated
// (ErrBackendUserUnavailable) and neither may be linked already
// (ErrAlreadyLinked). linkedBy is recorded (0 records none). It runs in tx,
// fires BackendLinkedEvent there and the two pact.MCPSubjectChanged events
// after tx commits.
func (s *BackendLinks) SetLink(ctx context.Context, tx *gorm.DB, frontendUserID, backendUserID, linkedBy uint) (*models.BackendLink, error) {
if tx == nil {
return nil, fmt.Errorf("golem15.user: setting a link needs a transaction")
}
var users []models.User
if err := fresh(ctx, tx).Where("id = ?", frontendUserID).Limit(1).Find(&users).Error; err != nil {
return nil, err
}
if frontendUserID == 0 || len(users) == 0 {
return nil, ErrFrontendUserUnavailable
}
if _, err := activeBackendUser(ctx, tx, backendUserID); err != nil {
return nil, err
}
var by *uint
if linkedBy != 0 {
by = &linkedBy
}
return s.insertLink(ctx, tx, frontendUserID, backendUserID, by)
}
// insertLink writes one link in tx after checking both sides are free; a
// concurrent writer that wins the unique index also ends in
// ErrAlreadyLinked. It is the one write path of a link (ConfirmLinkRequest
// and SetLink), so BackendLinkedEvent, with Link.UserID set, fires on every
// link; RemoveLink is the one removal path and fires BackendUnlinkedEvent.
func (s *BackendLinks) insertLink(ctx context.Context, tx *gorm.DB, frontendUserID, backendUserID uint, linkedBy *uint) (*models.BackendLink, error) {
var taken int64
if err := fresh(ctx, tx).Model(&models.BackendLink{}).
Where("user_id = ? OR backend_user_id = ?", frontendUserID, backendUserID).
Count(&taken).Error; err != nil {
return nil, err
}
if taken > 0 {
return nil, ErrAlreadyLinked
}
link := &models.BackendLink{UserID: frontendUserID, BackendUserID: backendUserID, LinkedBy: linkedBy, CreatedAt: time.Now()}
if err := fresh(ctx, tx).Create(link).Error; err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return nil, ErrAlreadyLinked
}
return nil, err
}
app := s.app()
if app != nil && app.Events != nil {
if err := app.Events.Fire(ctx, &BackendLinkedEvent{Link: link, Tx: tx}); err != nil {
return nil, fmt.Errorf("%s: %w", BackendLinkedEventName, err)
}
}
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardUser, link.UserID, pact.MCPSubjectLink)
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardBackend, link.BackendUserID, pact.MCPSubjectLink)
return link, nil
}
// RemoveLink deletes link in tx, fires BackendUnlinkedEvent (Link.UserID
// set) there and the
// two pact.MCPSubjectChanged link events after tx commits. A link that is
// already gone is not an error and fires nothing.
func (s *BackendLinks) RemoveLink(ctx context.Context, tx *gorm.DB, link *models.BackendLink) error {
if link == nil || link.ID == 0 {
return nil
}
if tx == nil {
return fmt.Errorf("golem15.user: removing a link needs a transaction")
}
res := fresh(ctx, tx).Where("id = ?", link.ID).Delete(&models.BackendLink{})
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return nil
}
app := s.app()
if app != nil && app.Events != nil {
if err := app.Events.Fire(ctx, &BackendUnlinkedEvent{Link: link, Tx: tx}); err != nil {
return fmt.Errorf("%s: %w", BackendUnlinkedEventName, err)
}
}
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardUser, link.UserID, pact.MCPSubjectLink)
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardBackend, link.BackendUserID, pact.MCPSubjectLink)
return nil
}
// LinkFor returns the link of the administrator, or nil.
func (s *BackendLinks) LinkFor(ctx context.Context, backendUserID uint) (*models.BackendLink, error) {
return s.linkWhere(ctx, "backend_user_id = ?", backendUserID)
}
// LinkOf returns the link of the frontend user, or nil.
func (s *BackendLinks) LinkOf(ctx context.Context, frontendUserID uint) (*models.BackendLink, error) {
return s.linkWhere(ctx, "user_id = ?", frontendUserID)
}
func (s *BackendLinks) linkWhere(ctx context.Context, where string, id uint) (*models.BackendLink, error) {
if id == 0 {
return nil, nil
}
db, err := s.db(ctx)
if err != nil {
return nil, err
}
var rows []models.BackendLink
if err := fresh(ctx, db).Where(where, id).Limit(1).Find(&rows).Error; err != nil {
return nil, err
}
if len(rows) == 0 {
return nil, nil
}
return &rows[0], nil
}
// LinkedBackendUser implements pact.MCPLinkedBackendResolver with one
// indexed query per call (no cache): the administrator linked to the
// frontend user, false when there is no link, when the frontend user is
// deactivated or banned (user_throttle.is_banned on any of their rows), or
// when the administrator is deactivated or deleted.
func (s *BackendLinks) LinkedBackendUser(ctx context.Context, frontendUserID uint) (pact.LinkedBackendUser, bool, error) {
if frontendUserID == 0 {
return pact.LinkedBackendUser{}, false, nil
}
db, err := s.db(ctx)
if err != nil {
return pact.LinkedBackendUser{}, false, err
}
var rows []struct {
ID uint
Login string
FirstName *string
LastName *string
}
err = fresh(ctx, db).Raw(`SELECT b.id, b.login, b.first_name, b.last_name
FROM golem15_user_backend_links l
JOIN backend_users b ON b.id = l.backend_user_id
JOIN users u ON u.id = l.user_id
WHERE l.user_id = ? AND b.deleted_at IS NULL AND b.is_activated = TRUE AND u.deleted_at IS NULL
AND NOT EXISTS (SELECT 1 FROM user_throttle t WHERE t.user_id = l.user_id AND t.is_banned)
LIMIT 1`, frontendUserID).Scan(&rows).Error
if err != nil {
return pact.LinkedBackendUser{}, false, err
}
if len(rows) == 0 {
return pact.LinkedBackendUser{}, false, nil
}
row := rows[0]
return pact.LinkedBackendUser{ID: row.ID, Login: row.Login, DisplayName: backendDisplayName(deref(row.FirstName), deref(row.LastName), row.Login)}, true, nil
}
// BackendDisplayName is the name the link pages show for an administrator:
// first and last name, else the login.
func BackendDisplayName(admin *cabana.BackendUser) string {
if admin == nil {
return ""
}
return backendDisplayName(admin.FirstName, admin.LastName, admin.Login)
}
func backendDisplayName(first, last, login string) string {
if name := strings.TrimSpace(strings.TrimSpace(first) + " " + strings.TrimSpace(last)); name != "" {
return name
}
return login
}
func deref(s *string) string {
if s == nil {
return ""
}
return *s
}
// activeBackendUser loads an activated, not deleted administrator, else
// ErrBackendUserUnavailable.
func activeBackendUser(ctx context.Context, db *gorm.DB, id uint) (*cabana.BackendUser, error) {
if id == 0 {
return nil, ErrBackendUserUnavailable
}
var rows []cabana.BackendUser
if err := fresh(ctx, db).Where("id = ? AND is_activated = TRUE", id).Limit(1).Find(&rows).Error; err != nil {
return nil, err
}
if len(rows) == 0 {
return nil, ErrBackendUserUnavailable
}
return &rows[0], nil
}
// RegisterBackendLinkListeners removes a frontend user's link inside the
// transaction that deletes (DeletingEvent) or deactivates
// (DeactivatingEvent) the user, and fires pact.MCPSubjectChanged deleted
// for the user and link for the administrator after it commits.
func (s *BackendLinks) RegisterBackendLinkListeners(app *backpack.App) {
if app == nil || app.Events == nil {
return
}
const owner = "golem15.user.backend_links"
app.Events.Listen(owner, func(ctx context.Context, e *DeletingEvent) error {
if e == nil {
return nil
}
return s.dropUserLink(ctx, e.Tx, e.User)
})
app.Events.Listen(owner, func(ctx context.Context, e *DeactivatingEvent) error {
if e == nil {
return nil
}
return s.dropUserLink(ctx, e.Tx, e.User)
})
}
func (s *BackendLinks) dropUserLink(ctx context.Context, tx *gorm.DB, user *models.User) error {
if user == nil || user.ID == 0 || tx == nil {
return nil
}
var rows []models.BackendLink
if err := fresh(ctx, tx).Where("user_id = ?", user.ID).Limit(1).Find(&rows).Error; err != nil {
return err
}
if len(rows) > 0 {
if err := s.RemoveLink(ctx, tx, &rows[0]); err != nil {
return err
}
}
FireSubjectChangedAfterCommit(ctx, s.app(), tx, SubjectGuardUser, user.ID, pact.MCPSubjectDeleted)
return nil
}
func (s *BackendLinks) app() *backpack.App {
if s == nil {
return nil
}
return s.App
}
func (s *BackendLinks) pool() (*gorm.DB, error) {
if s == nil || s.App == nil {
return nil, fmt.Errorf("golem15.user: app is nil")
}
gdb, ok := s.App.Lookup[*gorm.DB]()
if !ok || gdb == nil {
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
}
return gdb, nil
}

View File

@@ -0,0 +1,52 @@
package classes
import (
"fmt"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
)
// JWTBlacklistTable is the table of migration
// 202609220007_create_jwt_blacklist that the plugin's blacklist store uses.
const JWTBlacklistTable = "jwt_blacklist"
// DefaultBlacklistSweepInterval is how often the scheduler runs
// user:jwt-blacklist-sweep when golem15.user.jwt.blacklist_sweep_interval is
// not set.
const DefaultBlacklistSweepInterval = 10 * time.Minute
const blacklistSweepIntervalKey = "golem15.user.jwt.blacklist_sweep_interval"
// BlacklistSweepInterval reads golem15.user.jwt.blacklist_sweep_interval, a
// Go duration (10m by default). 0 means no sweep is scheduled. Any other
// value must be at least 1s and divide 24h evenly: the scheduler's Every
// cadence is aligned to local midnight, so a period that does not divide the
// day cannot be scheduled. A value that does not parse, is negative, is
// shorter than a second or does not divide 24h is an error, so a typo fails
// the boot instead of silently stopping the sweep.
func BlacklistSweepInterval(app *backpack.App) (time.Duration, error) {
if app == nil || app.Config == nil {
return DefaultBlacklistSweepInterval, nil
}
raw := strings.TrimSpace(app.Config.String(blacklistSweepIntervalKey))
if raw == "" {
// A non-string value (an unquoted YAML 0) may read as "".
if v, ok := app.Config.Lookup(blacklistSweepIntervalKey); ok && v != nil {
raw = strings.TrimSpace(fmt.Sprint(v))
}
}
if raw == "" {
return DefaultBlacklistSweepInterval, nil
}
d, err := time.ParseDuration(raw)
switch {
case err != nil:
case d == 0:
return 0, nil
case d >= time.Second && (24*time.Hour)%d == 0:
return d, nil
}
return 0, fmt.Errorf("golem15.user: %s must be 0 (no sweep) or a duration of at least 1s that divides 24h evenly, such as 10m, got %q", blacklistSweepIntervalKey, raw)
}

View File

@@ -0,0 +1,59 @@
package classes
import (
"strings"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
)
// TestBlacklistSweepInterval reads golem15.user.jwt.blacklist_sweep_interval:
// 10m by default, 0 for no sweep (string, duration or unquoted YAML int, and
// from a SUMMER_ variable), and an error naming the key for a value the
// scheduler cannot run.
func TestBlacklistSweepInterval(t *testing.T) {
const key = "golem15.user.jwt.blacklist_sweep_interval"
if got, err := BlacklistSweepInterval(nil); got != DefaultBlacklistSweepInterval || err != nil {
t.Errorf("nil app: %v %v", got, err)
}
if got, err := BlacklistSweepInterval(&backpack.App{}); got != DefaultBlacklistSweepInterval || err != nil {
t.Errorf("nil config: %v %v", got, err)
}
if got, err := BlacklistSweepInterval(mailTestApp(t)); got != 10*time.Minute || err != nil {
t.Errorf("unset: %v %v", got, err)
}
for _, tc := range []struct {
value any
want time.Duration
}{
{"10m", 10 * time.Minute},
{"1h", time.Hour},
{"30s", 30 * time.Second},
{"24h", 24 * time.Hour},
{" 1m ", time.Minute},
{"0", 0},
{"0s", 0},
{0, 0},
} {
app := mailTestApp(t)
if err := app.Config.Set(key, tc.value); err != nil {
t.Fatal(err)
}
if got, err := BlacklistSweepInterval(app); got != tc.want || err != nil {
t.Errorf("%#v: %v %v, want %v", tc.value, got, err, tc.want)
}
}
if got, err := BlacklistSweepInterval(mailTestApp(t, "SUMMER_GOLEM15__USER__JWT__BLACKLIST_SWEEP_INTERVAL=0")); got != 0 || err != nil {
t.Errorf("SUMMER_ 0: %v %v", got, err)
}
for _, bad := range []any{"soon", "3", "-1m", "500ms", "7m", "48h", -5} {
app := mailTestApp(t)
if err := app.Config.Set(key, bad); err != nil {
t.Fatal(err)
}
if got, err := BlacklistSweepInterval(app); err == nil || got != 0 || !strings.Contains(err.Error(), key) {
t.Errorf("%#v: %v %v, want an error naming %s", bad, got, err, key)
}
}
}

View File

@@ -113,7 +113,9 @@ func VerifyResetCode(ctx context.Context, db *gorm.DB, userID uint, code string)
} }
// VerifyActivationCode accepts the stored code inside the activation TTL. // VerifyActivationCode accepts the stored code inside the activation TTL.
// A soft-deleted row is visible and is restored on success. // A soft-deleted row is visible and is restored on success. The code was
// mailed to the account's address, so success also records the proof of that
// address (email_verified_at, D-27) in the same write that activates it.
func VerifyActivationCode(ctx context.Context, db *gorm.DB, userID uint, code string) (*models.User, bool) { func VerifyActivationCode(ctx context.Context, db *gorm.DB, userID uint, code string) (*models.User, bool) {
user, err := takeUser(ctx, db, userID, true) user, err := takeUser(ctx, db, userID, true)
if err != nil || user == nil || user.IsActivated || user.ActivationCode == nil { if err != nil || user == nil || user.IsActivated || user.ActivationCode == nil {
@@ -134,11 +136,13 @@ func VerifyActivationCode(ctx context.Context, db *gorm.DB, userID uint, code st
"activated_at": now, "activated_at": now,
"activation_code": nil, "activation_code": nil,
"activation_code_issued_at": nil, "activation_code_issued_at": nil,
"email_verified_at": now,
}).Error; err != nil { }).Error; err != nil {
return nil, false return nil, false
} }
user.IsActivated = true user.IsActivated = true
user.ActivatedAt = &now user.ActivatedAt = &now
user.EmailVerifiedAt = &now
user.ActivationCode = nil user.ActivationCode = nil
user.ActivationCodeIssuedAt = nil user.ActivationCodeIssuedAt = nil
return user, true return user, true

201
classes/device_auth.go Normal file
View File

@@ -0,0 +1,201 @@
package classes
import (
"context"
"crypto/rand"
"encoding/base64"
"strings"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"gorm.io/gorm"
)
// DeviceShortCodeAlphabet is the alphabet of device short codes (PHP's
// recovery-code alphabet: no 0, 1, I, L or O).
const DeviceShortCodeAlphabet = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"
// defaultDeviceAuthURL is golem15.user.device_auth.auth_url when unset. It
// carries the short code, never the device token: the token is the secret
// the device polls the session token with, and a QR code, a scan URL in a
// browser history or a Referer must not hand it to an onlooker.
const defaultDeviceAuthURL = "{frontend_url}/device/scan/{short_code}"
// defaultDeviceAuthTTL is golem15.user.device_auth.ttl_minutes when unset.
const defaultDeviceAuthTTL = 5 * time.Minute
// NewDeviceToken returns a fresh device token: 48 bytes from crypto/rand as
// unpadded base64url, 64 characters. Store only its HashAPIToken.
func NewDeviceToken() (string, error) {
var b [48]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b[:]), nil
}
// NewDeviceShortCode returns a fresh short code XXXX-XXXX, eight characters
// drawn uniformly from DeviceShortCodeAlphabet with crypto/rand (rejection
// sampling, no modulo bias).
func NewDeviceShortCode() (string, error) {
n := len(DeviceShortCodeAlphabet)
limit := 256 - 256%n // largest multiple of n that fits a byte
out := make([]byte, 0, 9)
var buf [16]byte
for len(out) < 9 {
if _, err := rand.Read(buf[:]); err != nil {
return "", err
}
for _, c := range buf {
if int(c) >= limit {
continue
}
if len(out) == 4 {
out = append(out, '-')
}
out = append(out, DeviceShortCodeAlphabet[int(c)%n])
if len(out) == 9 {
break
}
}
}
return string(out), nil
}
// NormalizeDeviceShortCode turns what a user typed into the stored form
// XXXX-XXXX: upper case, spaces and hyphens removed, exactly eight
// characters of DeviceShortCodeAlphabet. It reports false otherwise.
func NormalizeDeviceShortCode(s string) (string, bool) {
s = strings.ToUpper(s)
s = strings.NewReplacer(" ", "", "-", "").Replace(s)
if len(s) != 8 {
return "", false
}
for i := 0; i < len(s); i++ {
if strings.IndexByte(DeviceShortCodeAlphabet, s[i]) < 0 {
return "", false
}
}
return s[:4] + "-" + s[4:], true
}
// DeviceAuthTTL is how long a device authorization session can be
// authorized and handed over: golem15.user.device_auth.ttl_minutes, default
// 5.
func DeviceAuthTTL(app *backpack.App) time.Duration {
if app != nil && app.Config != nil {
if mins := app.Config.Int("golem15.user.device_auth.ttl_minutes"); mins > 0 {
return time.Duration(mins) * time.Minute
}
}
return defaultDeviceAuthTTL
}
// DeviceAuthURL is DeviceAuthURLFor without a short code: {short_code}
// is filled with the device token, as the template's only key.
func DeviceAuthURL(app *backpack.App, token string) string {
return DeviceAuthURLFor(app, token, "")
}
// DeviceAuthURLFor is the auth_url a new device shows as its QR code: the
// template golem15.user.device_auth.auth_url (default
// {frontend_url}/device/scan/{short_code}) with {frontend_url} replaced by
// FrontendURL (golem15.user.frontend_url, else app.url, no trailing slash),
// {short_code} by the session's short code and {token} by the device
// token. POST /devices/authorize accepts the short code in its token field
// too, so a page that posts what its URL carries as token works with
// either template. An empty shortCode fills {short_code} with the token.
func DeviceAuthURLFor(app *backpack.App, token, shortCode string) string {
tpl := ""
if app != nil && app.Config != nil {
tpl = strings.TrimSpace(app.Config.String("golem15.user.device_auth.auth_url"))
}
if tpl == "" {
tpl = defaultDeviceAuthURL
}
if shortCode == "" {
shortCode = token
}
return strings.NewReplacer("{frontend_url}", FrontendURL(app), "{short_code}", shortCode, "{token}", token).Replace(tpl)
}
// DeviceDisplayName is the name a device list shows (PHP's device_name
// accessor): the stored name, else a name parsed from the user agent
// (iPhone, iPad, Android Device, Windows PC, Mac, Linux PC), else Unknown
// Device.
func DeviceDisplayName(stored *string, userAgent string) string {
if stored != nil && *stored != "" {
return *stored
}
switch {
case strings.Contains(userAgent, "iPhone"):
return "iPhone"
case strings.Contains(userAgent, "iPad"):
return "iPad"
case strings.Contains(userAgent, "Android"):
return "Android Device"
case strings.Contains(userAgent, "Windows"):
return "Windows PC"
case strings.Contains(userAgent, "Macintosh"):
return "Mac"
case strings.Contains(userAgent, "Linux"):
return "Linux PC"
}
return "Unknown Device"
}
// HandOverDeviceJTI moves a used device session from the jti of a session
// token to the jti of the token that refreshed it, and stamps its
// last_activity_at, so revoking the device still reaches the token the
// device holds now. It is FollowDeviceJTI without the revoked report;
// empty values do nothing.
func HandOverDeviceJTI(ctx context.Context, db *gorm.DB, oldJTI, newJTI string) error {
_, err := FollowDeviceJTI(ctx, db, oldJTI, newJTI)
return err
}
// RevokeDeviceSessions marks the pending and confirmed device sessions of
// userIDs revoked, so none of them hands a session token over any more.
// Used sessions keep their status: their tokens end through
// tokens_valid_after or a revoke. The plugin calls it on db, the write's
// transaction, for every AccessRevokedEvent (a ban or a password change).
func RevokeDeviceSessions(ctx context.Context, db *gorm.DB, userIDs ...uint) error {
if db == nil || len(userIDs) == 0 {
return nil
}
return db.WithContext(ctx).Exec(`UPDATE golem15_user_device_auth_sessions
SET status = 'revoked', updated_at = NOW()
WHERE user_id IN ? AND status IN ('pending', 'confirmed')`, userIDs).Error
}
// FollowDeviceJTI moves a used device session from oldJTI, the jti of the
// session token a refresh presented, to newJTI, the jti of the token it
// minted, and stamps last_activity_at. It reports revoked when no used
// session moved but a session with oldJTI exists in another status: the
// device was revoked after the refresh passed the blacklist check, so the
// caller must refuse the refresh and drop the new token. The move is one
// guarded UPDATE that takes the session's row lock, as the revoke's
// UPDATE … RETURNING jwt_jti does (controllers.DeviceDestroy): a revoke
// that runs after the move blacklists newJTI, and a move that runs after
// the revoke matches nothing and reports revoked. POST /refresh calls it
// and fails closed on an error. Empty or equal values do nothing.
func FollowDeviceJTI(ctx context.Context, db *gorm.DB, oldJTI, newJTI string) (revoked bool, err error) {
if db == nil || oldJTI == "" || newJTI == "" || oldJTI == newJTI {
return false, nil
}
res := db.WithContext(ctx).Exec(`UPDATE golem15_user_device_auth_sessions
SET jwt_jti = ?, last_activity_at = NOW(), updated_at = NOW()
WHERE jwt_jti = ? AND status = 'used'`, newJTI, oldJTI)
if res.Error != nil {
return false, res.Error
}
if res.RowsAffected > 0 {
return false, nil
}
var stale int64
if err := db.WithContext(ctx).Raw(`SELECT COUNT(*) FROM golem15_user_device_auth_sessions
WHERE jwt_jti = ? AND status <> 'used'`, oldJTI).Scan(&stale).Error; err != nil {
return false, err
}
return stale > 0, nil
}

129
classes/device_auth_test.go Normal file
View File

@@ -0,0 +1,129 @@
package classes
import (
"crypto/sha256"
"encoding/hex"
"regexp"
"strings"
"testing"
)
// TestDeviceCodes pins the device token and short code (D-11, D-06)
// without a database: 10,000 tokens are 64 base64url characters, all
// distinct, and their stored form is the SHA-256 hex; 10,000 short codes
// are XXXX-XXXX over DeviceShortCodeAlphabet with every character of the
// alphabet in every position and no character far from its expected
// share; NormalizeDeviceShortCode accepts case, spaces and a missing
// hyphen and refuses lengths other than eight and the excluded letters.
func TestDeviceCodes(t *testing.T) {
const draws = 10000
t.Run("tokens", func(t *testing.T) {
seen := make(map[string]struct{}, draws)
for range draws {
tok, err := NewDeviceToken()
if err != nil {
t.Fatal(err)
}
if len(tok) != 64 {
t.Fatalf("token %q has %d characters", tok, len(tok))
}
if strings.Trim(tok, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != "" {
t.Fatalf("token %q is not base64url", tok)
}
if _, dup := seen[tok]; dup {
t.Fatalf("token %q drawn twice", tok)
}
seen[tok] = struct{}{}
}
tok, _ := NewDeviceToken()
sum := sha256.Sum256([]byte(tok))
if got := HashAPIToken(tok); got != hex.EncodeToString(sum[:]) || len(got) != 64 || got == tok {
t.Fatalf("stored form %q is not the SHA-256 hex of the token", got)
}
})
t.Run("short_codes", func(t *testing.T) {
alphabet := DeviceShortCodeAlphabet
if alphabet != "23456789ABCDEFGHJKMNPQRSTUVWXYZ" || len(alphabet) != 31 {
t.Fatalf("alphabet = %q", alphabet)
}
format := regexp.MustCompile(`^[` + alphabet + `]{4}-[` + alphabet + `]{4}$`)
perPosition := make([]map[byte]int, 8)
for i := range perPosition {
perPosition[i] = map[byte]int{}
}
total := map[byte]int{}
seen := map[string]struct{}{}
for range draws {
code, err := NewDeviceShortCode()
if err != nil {
t.Fatal(err)
}
if !format.MatchString(code) {
t.Fatalf("short code %q", code)
}
seen[code] = struct{}{}
raw := code[:4] + code[5:]
for i := 0; i < 8; i++ {
perPosition[i][raw[i]]++
total[raw[i]]++
}
}
// 31^8 codes: 10,000 draws repeating more than a handful would mean
// a broken generator.
if len(seen) < draws-5 {
t.Fatalf("%d distinct codes in %d draws", len(seen), draws)
}
for i, counts := range perPosition {
for j := 0; j < len(alphabet); j++ {
if counts[alphabet[j]] == 0 {
t.Fatalf("character %q never drawn at position %d", alphabet[j], i)
}
}
}
// Each character is expected 80000/31 ≈ 2581 times; a modulo bias
// of the byte draw would push the first 8 characters ~3% up. Allow
// 10% either way, far outside the noise of a fair draw.
expected := float64(8*draws) / float64(len(alphabet))
for j := 0; j < len(alphabet); j++ {
got := float64(total[alphabet[j]])
if got < expected*0.9 || got > expected*1.1 {
t.Fatalf("character %q drawn %v times, expected about %.0f", alphabet[j], got, expected)
}
}
for _, excluded := range "01ILO" {
if total[byte(excluded)] != 0 {
t.Fatalf("excluded character %q drawn", excluded)
}
}
})
t.Run("normalization", func(t *testing.T) {
for _, c := range []struct{ in, want string }{
{"ABCD-EFGH", "ABCD-EFGH"},
{"abcd-efgh", "ABCD-EFGH"},
{"AbCd-eFgH", "ABCD-EFGH"},
{"ABCDEFGH", "ABCD-EFGH"},
{"abcdefgh", "ABCD-EFGH"},
{" ab cd ef gh ", "ABCD-EFGH"},
{"ABCD - EFGH", "ABCD-EFGH"},
{"A-B-C-D-E-F-G-H", "ABCD-EFGH"},
{"2345-6789", "2345-6789"},
{"zzzz zzzz", "ZZZZ-ZZZZ"},
} {
if got, ok := NormalizeDeviceShortCode(c.in); !ok || got != c.want {
t.Errorf("normalize %q = %q, %v; want %q", c.in, got, ok, c.want)
}
}
for _, in := range []string{
"", "-", "ABCDEFG", "ABCD-EFG", "ABCDEFGHJ", "ABCD-EFGHJ",
"ABCDEFG0", "ABCDEFG1", "ABCDEFGI", "ABCDEFGL", "ABCDEFGO", "abcdefgo", "abcdefgl", "abcdefgi",
"ABCD_EFGH", "ABCD.EFGH", "ABCDÉFGH", "ABCD\tEFGH",
} {
if got, ok := NormalizeDeviceShortCode(in); ok {
t.Errorf("normalize %q accepted as %q", in, got)
}
}
})
}

View File

@@ -1,6 +1,33 @@
package classes package classes
import "git.golem15.com/golem15/sm-user-plugin/models" import (
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"gorm.io/gorm"
)
// CreatedEventName is the festival name of CreatedEvent (D-13 / RESEARCH A6).
const CreatedEventName = "user.Created"
// DeletingEventName is the festival name of DeletingEvent (D-13 / RESEARCH A6).
const DeletingEventName = "user.Deleting"
// DeactivatingEventName is the festival name of DeactivatingEvent.
const DeactivatingEventName = "user.Deactivating"
// BackendLinkedEventName is the festival name of BackendLinkedEvent.
const BackendLinkedEventName = "user.BackendLinked"
// BackendUnlinkedEventName is the festival name of BackendUnlinkedEvent.
const BackendUnlinkedEventName = "user.BackendUnlinked"
// AccessRevokedEventName is the festival name of AccessRevokedEvent.
const AccessRevokedEventName = "user.AccessRevoked"
// LoginEventName is the festival name of LoginEvent, the PHP plugin's
// golem15.user.login.
const LoginEventName = "golem15.user.login"
// GetApiArrayEvent is the fire-and-collect payload other plugins extend. // GetApiArrayEvent is the fire-and-collect payload other plugins extend.
type GetApiArrayEvent struct { type GetApiArrayEvent struct {
@@ -27,3 +54,93 @@ type RegisterEvent struct {
// or hashed. Listeners must treat it as read-only input. // or hashed. Listeners must treat it as read-only input.
Payload map[string]any Payload map[string]any
} }
// CreatedEvent fires from every user create path (API register and admin
// create) so listeners can run inside the same write, including handle
// generation (D-13, D-15). Tx is the create transaction when there is one.
type CreatedEvent struct {
User *models.User
Tx *gorm.DB
}
// DeletingEvent fires from FormAfterDelete before ForceDeleteCleanup /
// unscoped delete, inside the same transaction, so listeners (chatchannels
// GDPR) can sever rows before the user row is gone (D-13, T-19-07).
type DeletingEvent struct {
User *models.User
Tx *gorm.DB
}
// 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. 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
}
// BackendLinkedEvent fires inside the write transaction after a link was
// stored, by the frontend user's confirmation (Link.LinkedBy nil) or by an
// administrator (Link.LinkedBy set). A listener error rolls the link back.
type BackendLinkedEvent struct {
Link *models.BackendLink
Tx *gorm.DB
}
// BackendUnlinkedEvent fires inside the write transaction after a link was
// removed, from My account, the Administrators screen or because one of the
// accounts was deleted or deactivated. A listener error rolls the removal
// back.
type BackendUnlinkedEvent struct {
Link *models.BackendLink
Tx *gorm.DB
}
// AccessRevokedEvent fires inside the write transaction when users lose
// every credential issued before Before: a ban, a password reset, a password
// an administrator set, or the user's own password change (FireAccessRevoked;
// Reason names which). Listeners revoke what such a credential still holds
// elsewhere, for example OAuth access and refresh tokens created before
// Before. Before is the untruncated instant of the revocation, while the
// users' tokens_valid_after keeps its whole-second value. A listener error
// rolls the write back. Deactivation and deletion keep their own events
// (DeactivatingEvent, DeletingEvent).
type AccessRevokedEvent struct {
UserIDs []uint
Before time.Time
Reason string
Tx *gorm.DB
}
// PasswordChanged reports whether the event comes from a new password the
// user or an administrator chose: a password reset, the user's own change or
// an administrator setting one (Reason AccessRevokedPasswordReset,
// AccessRevokedPasswordChanged or AccessRevokedPasswordSetByAdmin). The
// bcrypt rehash on login and a new account fire no AccessRevokedEvent. A
// two-factor plugin listens for these events to revoke the users' trusted
// devices inside the same transaction.
func (e *AccessRevokedEvent) PasswordChanged() bool {
if e == nil {
return false
}
switch e.Reason {
case AccessRevokedPasswordReset, AccessRevokedPasswordChanged, AccessRevokedPasswordSetByAdmin:
return true
}
return false
}
// LoginEvent fires after a sign-in issued a session token: a password login,
// a sign-in completed by a second factor, a passkey sign-in or a device
// hand-over (Source is one of the LoginSource constants). It does not fire
// on refresh, on /register or for a sign-in a login gate held back. It fires
// after the token was minted and outside any transaction; a listener error
// is logged and never fails the sign-in (PHP's golem15.user.login).
type LoginEvent struct {
User *models.User
Source string
}

View File

@@ -46,3 +46,41 @@ func TestRegisterEventFires(t *testing.T) {
t.Fatalf("event user = %#v", seen) t.Fatalf("event user = %#v", seen)
} }
} }
func TestCreatedEventFires(t *testing.T) {
if CreatedEventName != "user.Created" {
t.Fatalf("CreatedEventName = %q, want user.Created", CreatedEventName)
}
bus := festival.New()
var seen *models.User
bus.Listen[*CreatedEvent]("golem15.user", func(_ context.Context, e *CreatedEvent) error {
seen = e.User
return nil
})
user := &models.User{ID: 9, Email: "created@example.test"}
if err := bus.Fire(context.Background(), &CreatedEvent{User: user}); err != nil {
t.Fatal(err)
}
if seen == nil || seen.Email != user.Email {
t.Fatalf("created event user = %#v", seen)
}
}
func TestDeletingEventFires(t *testing.T) {
if DeletingEventName != "user.Deleting" {
t.Fatalf("DeletingEventName = %q, want user.Deleting", DeletingEventName)
}
bus := festival.New()
var seen *models.User
bus.Listen[*DeletingEvent]("golem15.user", func(_ context.Context, e *DeletingEvent) error {
seen = e.User
return nil
})
user := &models.User{ID: 9, Email: "gone@example.test"}
if err := bus.Fire(context.Background(), &DeletingEvent{User: user}); err != nil {
t.Fatal(err)
}
if seen == nil || seen.Email != user.Email {
t.Fatalf("deleting event user = %#v", seen)
}
}

View File

@@ -0,0 +1,59 @@
package classes
import (
"context"
"strings"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/party"
"gorm.io/gorm"
)
// FrontendPermissionCatalog is what the user and user group permission
// editors offer (D-09): the rows of golem15_user_frontend_permissions first,
// in FrontendPermissionOptions order and unchanged, then the codes activated
// plugins declare through pact.HasFrontendPermissions, in activation order.
// A declared code that a seeded row already has is skipped (the seeded row
// wins), and so is a code an earlier plugin declared; an empty code is
// skipped. The table, its rows and the stored permissions are never
// written.
func FrontendPermissionCatalog(ctx context.Context, app *backpack.App, db *gorm.DB) ([]cabana.PermissionOption, error) {
rows, err := FrontendPermissionOptions(ctx, db)
if err != nil {
return nil, err
}
options := make([]cabana.PermissionOption, 0, len(rows))
seen := make(map[string]bool, len(rows))
for _, row := range rows {
option := cabana.PermissionOption{Code: row.Code, Label: row.Label, Tab: row.Tab}
if row.Comment != nil {
option.Comment = *row.Comment
}
options = append(options, option)
seen[row.Code] = true
}
if app == nil {
return options, nil
}
activated, ok := app.Lookup[party.Activated]()
if !ok {
return options, nil
}
for _, plugin := range activated {
declares, ok := plugin.(pact.HasFrontendPermissions)
if !ok || declares == nil {
continue
}
for _, perm := range declares.FrontendPermissions() {
code := strings.TrimSpace(perm.Code)
if code == "" || seen[code] {
continue
}
seen[code] = true
options = append(options, cabana.PermissionOption{Code: code, Label: perm.Label, Tab: perm.Tab, Comment: perm.Comment})
}
}
return options, nil
}

160
classes/handle_generator.go Normal file
View File

@@ -0,0 +1,160 @@
package classes
import (
"context"
"errors"
"strconv"
"strings"
"unicode"
"git.golem15.com/golem15/sm-user-plugin/models"
"gorm.io/gorm"
)
const (
handleMinLen = 2
handleMaxLen = 255
)
// HandleGenerator ports the PHP ChatChannels HandleGenerator. The emitted
// charset [a-z0-9._-] is a strict subset of MentionParser [A-Za-z0-9._-],
// length 2–255, so every generated handle is matchable as an @-token.
type HandleGenerator struct{}
// Slug transliterates name to ASCII, lowercases, drops every rune outside
// [a-z0-9._-], then trims leading/trailing `._-`. A result shorter than 2
// is not a valid base (Generate falls back to user{id}).
func (HandleGenerator) Slug(name string) string {
name = strings.TrimSpace(name)
if name == "" {
return ""
}
var b strings.Builder
b.Grow(len(name))
for _, r := range name {
b.WriteString(foldHandleRune(r))
}
return strings.Trim(b.String(), "._-")
}
// Generate returns a unique handle for name. The base is Slug(name); if
// that is shorter than 2 it falls back to "user{fallbackID}" (or "user"
// when no id is known). The smallest free integer suffix is then appended
// until isTaken returns false: first "James" → "james", second → "james1".
func (g HandleGenerator) Generate(name string, isTaken func(string) bool, fallbackID *uint) string {
base := g.Slug(name)
if len(base) < handleMinLen {
if fallbackID != nil {
base = "user" + strconv.FormatUint(uint64(*fallbackID), 10)
} else {
base = "user"
}
}
base = clipHandle(base)
candidate := base
i := 0
for isTaken != nil && isTaken(candidate) {
i++
candidate = clipHandle(base + strconv.Itoa(i))
}
return candidate
}
// AssignHandle writes a unique handle onto user when it has none, using
// the user's display name and id. It is idempotent when handle is already
// set. The write uses db (the create transaction when there is one).
func AssignHandle(ctx context.Context, db *gorm.DB, user *models.User) error {
if user == nil {
return errors.New("golem15.user: a handle needs a user")
}
if user.Handle != nil && strings.TrimSpace(*user.Handle) != "" {
return nil
}
if db == nil {
return errors.New("golem15.user: a handle needs a database")
}
name := ""
if user.Name != nil {
name = *user.Name
}
var fallback *uint
if user.ID != 0 {
id := user.ID
fallback = &id
}
gen := HandleGenerator{}
for attempt := 0; attempt < 8; attempt++ {
handle := gen.Generate(name, func(candidate string) bool {
var n int64
q := db.WithContext(ctx).Model(&models.User{}).Where("handle = ?", candidate)
if user.ID != 0 {
q = q.Where("id <> ?", user.ID)
}
if err := q.Count(&n).Error; err != nil {
return true
}
return n > 0
}, fallback)
user.Handle = &handle
res := db.WithContext(ctx).Model(user).Where("id = ?", user.ID).Update("handle", handle)
if res.Error == nil {
return nil
}
if !isUniqueHandleConflict(res.Error) {
return res.Error
}
}
return errors.New("golem15.user: could not allocate a unique handle")
}
func clipHandle(s string) string {
if len(s) <= handleMaxLen {
return s
}
return s[:handleMaxLen]
}
func isUniqueHandleConflict(err error) bool {
if err == nil {
return false
}
if errors.Is(err, gorm.ErrDuplicatedKey) {
return true
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "users_handle_unique") || strings.Contains(msg, "duplicate key")
}
// foldHandleRune maps r into the handle charset [a-z0-9._-] or "".
func foldHandleRune(r rune) string {
r = unicode.ToLower(r)
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '.', r == '_', r == '-':
return string(r)
}
if mapped, ok := latinHandleFold[r]; ok {
return mapped
}
return ""
}
// latinHandleFold covers Latin-1 / Latin Extended-A letters PHP Str::ascii
// would emit for the names we generate handles from (Polish, French, German).
var latinHandleFold = map[rune]string{
'à': "a", 'á': "a", 'â': "a", 'ã': "a", 'ä': "a", 'å': "a", 'ą': "a", 'ā': "a",
'æ': "ae",
'ç': "c", 'ć': "c", 'č': "c",
'ď': "d", 'đ': "d", 'ð': "d",
'è': "e", 'é': "e", 'ê': "e", 'ë': "e", 'ę': "e", 'ē': "e", 'ě': "e",
'ì': "i", 'í': "i", 'î': "i", 'ï': "i", 'ī': "i",
'ł': "l",
'ñ': "n", 'ń': "n", 'ň': "n",
'ò': "o", 'ó': "o", 'ô': "o", 'õ': "o", 'ö': "o", 'ø': "o", 'ō': "o",
'œ': "oe",
'ř': "r",
'ś': "s", 'š': "s", 'ş': "s", 'ß': "ss",
'ť': "t", 'þ': "th",
'ù': "u", 'ú': "u", 'û': "u", 'ü': "u", 'ū': "u",
'ý': "y", 'ÿ': "y",
'ź': "z", 'ż': "z", 'ž': "z",
}

View File

@@ -0,0 +1,78 @@
package classes
import "testing"
// TestHandle: generator charset is a subset of MentionParser, uniqueness
// uses the smallest free integer suffix, and short names fall back to user{id}.
func TestHandle(t *testing.T) {
t.Parallel()
g := HandleGenerator{}
if got := g.Slug("Paweł"); got != "pawel" {
t.Fatalf("slug Paweł = %q, want pawel", got)
}
if got := g.Slug("John Doe"); got != "johndoe" {
t.Fatalf("slug John Doe = %q, want johndoe", got)
}
if got := g.Slug("Zoë"); got != "zoe" {
t.Fatalf("slug Zoë = %q, want zoe", got)
}
handle := g.Generate("James", func(string) bool { return false }, nil)
if handle != "james" {
t.Fatalf("generate James = %q, want james", handle)
}
if !validHandle(handle) {
t.Fatalf("generated %q is outside [a-z0-9._-]{2,255}", handle)
}
taken := map[string]struct{}{}
isTaken := func(c string) bool {
_, ok := taken[c]
return ok
}
first := g.Generate("James", isTaken, nil)
taken[first] = struct{}{}
second := g.Generate("James", isTaken, nil)
taken[second] = struct{}{}
third := g.Generate("James", isTaken, nil)
if first != "james" || second != "james1" || third != "james2" {
t.Fatalf("suffixes = %q %q %q, want james james1 james2", first, second, third)
}
id := uint(42)
if got := g.Generate("", func(string) bool { return false }, &id); got != "user42" {
t.Fatalf("empty name = %q, want user42", got)
}
if got := g.Generate("x", func(string) bool { return false }, &id); got != "user42" {
t.Fatalf("short name = %q, want user42", got)
}
if got := g.Generate("???", func(string) bool { return false }, &id); got != "user42" {
t.Fatalf("punctuation name = %q, want user42", got)
}
if got := g.Generate("", func(string) bool { return false }, nil); got != "user" {
t.Fatalf("no id = %q, want user", got)
}
names := []string{"James", "Paweł", "John Doe", "???", "a", "Zoë", " ", "....", "O'Brien"}
for _, name := range names {
got := g.Generate(name, func(string) bool { return false }, &id)
if !validHandle(got) {
t.Errorf("generated %q for %q is outside the MentionParser subset", got, name)
}
}
}
func validHandle(s string) bool {
if len(s) < 2 || len(s) > 255 {
return false
}
for _, r := range s {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '.', r == '_', r == '-':
default:
return false
}
}
return true
}

27
classes/last_seen.go Normal file
View File

@@ -0,0 +1,27 @@
package classes
import (
"context"
"fmt"
"gorm.io/gorm"
)
// TouchLastSeen stamps users.last_seen with the current time, at most once
// per five minutes per user: it is one UPDATE that matches the row only when
// last_seen is NULL or older than five minutes, so a busy client costs one
// write per window. It does not touch updated_at, and it applies to a
// deactivated user too. Login and token refresh call it and ignore its
// error apart from logging it: authentication never depends on this write.
func TouchLastSeen(ctx context.Context, db *gorm.DB, userID uint) error {
if db == nil {
return fmt.Errorf("golem15.user: gorm handle is missing")
}
if userID == 0 {
return nil
}
return fresh(ctx, db).Exec(
`UPDATE users SET last_seen = NOW() WHERE id = ? AND (last_seen IS NULL OR last_seen < NOW() - INTERVAL '5 minutes')`,
userID,
).Error
}

124
classes/last_seen_test.go Normal file
View File

@@ -0,0 +1,124 @@
package classes
import (
"context"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"gorm.io/gorm"
)
// contextCancelled returns a context that is already cancelled, so a query
// through it fails.
func contextCancelled(t *testing.T) (context.Context, context.CancelFunc) {
t.Helper()
ctx, cancel := context.WithCancel(t.Context())
cancel()
return ctx, cancel
}
// TestTouchLastSeen pins the five-minute rule of users.last_seen on both
// sides of the boundary, for an active and a deactivated user (D-17).
func TestTouchLastSeen(t *testing.T) {
ctx := t.Context()
db := throttleDB(t)
user := models.User{Email: "touch@example.test", IsActivated: true}
gone := models.User{Email: "touch-gone@example.test", IsActivated: true, DeletedAt: gorm.DeletedAt{Time: time.Now(), Valid: true}}
for _, u := range []*models.User{&user, &gone} {
if err := db.Omit("Groups").Create(u).Error; err != nil {
t.Fatal(err)
}
}
read := func(id uint) *time.Time {
t.Helper()
var row struct{ LastSeen *time.Time }
if err := db.Raw(`SELECT last_seen FROM users WHERE id = ?`, id).Scan(&row).Error; err != nil {
t.Fatal(err)
}
return row.LastSeen
}
set := func(id uint, age time.Duration) time.Time {
t.Helper()
at := time.Now().Add(-age).Truncate(time.Microsecond)
if err := db.Exec(`UPDATE users SET last_seen = ? WHERE id = ?`, at, id).Error; err != nil {
t.Fatal(err)
}
return at
}
updatedAt := func(id uint) time.Time {
t.Helper()
var at time.Time
if err := db.Raw(`SELECT updated_at FROM users WHERE id = ?`, id).Scan(&at).Error; err != nil {
t.Fatal(err)
}
return at
}
for _, id := range []uint{user.ID, gone.ID} {
if read(id) != nil {
t.Fatalf("user %d starts with last_seen", id)
}
stamped := updatedAt(id)
started := time.Now().Add(-time.Second)
if err := TouchLastSeen(ctx, db, id); err != nil {
t.Fatal(err)
}
first := read(id)
if first == nil || first.Before(started) {
t.Fatalf("user %d: a NULL last_seen was not stamped: %v", id, first)
}
if !updatedAt(id).Equal(stamped) {
t.Fatalf("user %d: the stamp touched updated_at", id)
}
// Just inside the window: untouched. Just outside: stamped again.
for _, tc := range []struct {
age time.Duration
stamped bool
}{
{0, false}, {4*time.Minute + 55*time.Second, false},
{5*time.Minute + 5*time.Second, true}, {24 * time.Hour, true},
} {
was := set(id, tc.age)
if err := TouchLastSeen(ctx, db, id); err != nil {
t.Fatal(err)
}
now := read(id)
if now == nil || now.Equal(was) == tc.stamped {
t.Fatalf("user %d, last seen %s ago: stamped = %v, want %v", id, tc.age, !now.Equal(was), tc.stamped)
}
}
}
// One user's stamp never moves another's.
other := set(gone.ID, time.Hour)
if err := TouchLastSeen(ctx, db, user.ID); err != nil {
t.Fatal(err)
}
if got := read(gone.ID); got == nil || !got.Equal(other) {
t.Fatal("a stamp moved another user's last_seen")
}
// An unknown id and the zero id are no error; a missing handle and a
// failed write are.
if err := TouchLastSeen(ctx, db, 987654); err != nil {
t.Fatal(err)
}
if err := TouchLastSeen(ctx, db, 0); err != nil {
t.Fatal(err)
}
if err := TouchLastSeen(ctx, nil, user.ID); err == nil {
t.Fatal("TouchLastSeen without a handle")
}
cancelled, cancel := contextCancelled(t)
defer cancel()
set(user.ID, time.Hour)
if err := TouchLastSeen(cancelled, db, user.ID); err == nil {
t.Fatal("TouchLastSeen swallowed a failed write")
}
// The handle's own conditions do not leak into the update.
if err := TouchLastSeen(ctx, db.Where("1 = 0"), user.ID); err != nil {
t.Fatal(err)
}
if got := read(user.ID); got == nil || time.Since(*got) > time.Minute {
t.Fatalf("a scoped handle kept the stamp from being written: %v", got)
}
}

7
classes/logger.go Normal file
View File

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

127
classes/login_gate.go Normal file
View File

@@ -0,0 +1,127 @@
package classes
import (
"context"
"net/http"
"slices"
"sync"
"git.golem15.com/golem15/sm-user-plugin/models"
)
// Login sources name the first factor a LoginAttempt or a LoginEvent comes
// from.
const (
// LoginSourcePassword is POST /_user/api/v1/login (email and password)
// and POST /_user/api/v1/activate-by-code (the mailed activation code,
// the first factor of that sign-in).
LoginSourcePassword = "password"
// LoginSourceSocial is a social sign-in completed by a social-login
// plugin.
LoginSourceSocial = "social"
// LoginSourcePasskey is a passwordless passkey sign-in.
LoginSourcePasskey = "passkey"
// LoginSourceTwoFactor is a sign-in completed by a second factor after a
// gate challenged it.
LoginSourceTwoFactor = "two_factor"
// LoginSourceDevice is the device authorization hand-over (the first poll
// of devices/status after a signed-in user authorized the device).
LoginSourceDevice = "device"
)
// LoginAttempt is a first-factor sign-in that already succeeded: the
// password (or the social identity) checked out, the throttle was reset and
// the account may sign in. A LoginGate decides whether a token is issued
// now.
type LoginAttempt struct {
// User is the account signing in. A deactivated account still has
// DeletedAt set: Login restores it only after every gate allowed the
// sign-in.
User *models.User
// Source is one of the LoginSource constants.
Source string
// Fields is the login body Login already read (a gate must not read the
// request body again, it is consumed). It carries keys a gate needs,
// such as trusted_device_token. It is nil on a social sign-in. Treat it
// as read-only, untrusted input; it holds the password on a password
// login and the activation code on an activation.
Fields map[string]any
// Request is the sign-in request, for the client address and the user
// agent.
Request *http.Request
}
// LoginGateResult replaces the token response of a sign-in a gate held
// back.
type LoginGateResult struct {
// Status is the HTTP status of the answer; 0 means 200. A challenge
// answers 200, a refusal (for example a second-factor failure cap)
// answers its own status.
Status int
// Body is the JSON body of the answer, for example
// {two_factor_required, challenge_token, available_methods, expires_at}.
Body map[string]any
}
// LoginGate inspects a first-factor sign-in that already succeeded, before
// any token exists. A two-factor plugin implements one to challenge users
// who enabled a second factor.
type LoginGate interface {
// CheckLogin returns nil, nil to allow the sign-in. A non-nil result
// replaces the token response with its Status and Body, and no token is
// issued. An error must fail the sign-in closed: the caller answers the
// opaque 500 and issues no token. Error strings must not carry a token,
// a code or a password.
CheckLogin(ctx context.Context, a LoginAttempt) (*LoginGateResult, error)
}
// LoginGates is the registry of login gates. The user plugin publishes one
// in its Register (app.Publish(classes.NewLoginGates())), and another plugin
// looks it up with app.Lookup[*classes.LoginGates]() and adds its gate in
// its Boot: every Register runs before every Boot. Password Login consults
// it after the password, activation and throttle checks and before it
// restores a deactivated account and mints the token; activate-by-code
// consults it after the code verified and before it mints the token; JWT
// refresh never consults it. It is safe for concurrent use.
type LoginGates struct {
mu sync.RWMutex
gates []LoginGate
}
// NewLoginGates returns an empty registry.
func NewLoginGates() *LoginGates {
return &LoginGates{}
}
// Add appends gate; gates run in the order they were added. A nil gate is
// ignored.
func (g *LoginGates) Add(gate LoginGate) {
if g == nil || gate == nil {
return
}
g.mu.Lock()
g.gates = append(g.gates, gate)
g.mu.Unlock()
}
// Check runs the gates in order and returns the first non-nil result or the
// first error; gates after it are not called. A nil registry and an empty
// one return nil, nil, which allows the sign-in.
func (g *LoginGates) Check(ctx context.Context, a LoginAttempt) (*LoginGateResult, error) {
if g == nil {
return nil, nil
}
g.mu.RLock()
gates := slices.Clone(g.gates)
g.mu.RUnlock()
for _, gate := range gates {
res, err := gate.CheckLogin(ctx, a)
if err != nil {
return nil, err
}
if res != nil {
return res, nil
}
}
return nil, nil
}

View File

@@ -2,27 +2,128 @@ package classes
import ( import (
"context" "context"
"fmt"
"strconv"
"strings"
"git.golem15.com/golem15/sm-user-plugin/models" "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/towel" "git.golem15.com/golem15/summercms/modules/towel"
) )
// MailTemplate appends -en for English and leaves every other locale, const (
// including empty and pl, on the unsuffixed Polish template name. // mailFallbackLocaleKey names the mail language used when neither the
// user nor the request names one the plugin has mail for.
mailFallbackLocaleKey = "golem15.user.mail.fallback_locale"
// mailLocalePL is the unsuffixed (Polish) template set and the default
// fallback.
mailLocalePL = "pl"
// mailLocaleEN is the -en template set.
mailLocaleEN = "en"
)
// supportedMailLocale reports whether the plugin has mail in lang.
func supportedMailLocale(lang string) bool {
return lang == mailLocalePL || lang == mailLocaleEN
}
// NormalizeMailLocale reduces a locale value to the language the plugin has
// mail for: pl, en or "". It accepts a plain code (en, PL), a region form
// (en-GB, pl_PL) and an Accept-Language list with q-weights
// (en-GB,en;q=0.9). Entries whose q does not parse, lies outside 0..1 or is
// 0 are dropped, as are languages other than pl and en (the wildcard
// included); of the rest the one with the highest q wins, ties going to the
// earliest. The result never holds anything but pl, en or "".
func NormalizeMailLocale(raw string) string {
best, bestQ := "", -1.0
for _, entry := range strings.Split(raw, ",") {
parts := strings.Split(entry, ";")
tag := strings.ToLower(strings.TrimSpace(parts[0]))
if i := strings.IndexAny(tag, "-_"); i >= 0 {
tag = tag[:i]
}
if !supportedMailLocale(tag) {
continue
}
q, ok := 1.0, true
for _, param := range parts[1:] {
param = strings.TrimSpace(param)
if len(param) < 2 || !strings.EqualFold(param[:2], "q=") {
continue
}
v, err := strconv.ParseFloat(strings.TrimSpace(param[2:]), 64)
if err != nil || v < 0 || v > 1 {
ok = false
break
}
q = v
}
if !ok || q == 0 {
continue
}
if q > bestQ {
best, bestQ = tag, q
}
}
return best
}
// MailTemplate appends -en when locale normalises to English
// (NormalizeMailLocale) and leaves every other value, empty included, on the
// unsuffixed Polish template name. Callers that want the application's
// configured fallback resolve the locale with ResolveMailLocaleFor first.
func MailTemplate(base, locale string) string { func MailTemplate(base, locale string) string {
if locale == "en" { if NormalizeMailLocale(locale) == mailLocaleEN {
return base + "-en" return base + "-en"
} }
return base return base
} }
// ResolveMailLocale prefers the user's saved locale, then the request locale. // ResolveMailLocale prefers the user's saved locale, then the request locale,
// each normalised by NormalizeMailLocale; a value naming neither pl nor en is
// skipped. It returns pl, en or "" (neither names a supported language).
func ResolveMailLocale(ctx context.Context, user *models.User) string { func ResolveMailLocale(ctx context.Context, user *models.User) string {
if user != nil && user.PreferredLocale != nil && *user.PreferredLocale != "" { if user != nil && user.PreferredLocale != nil {
return *user.PreferredLocale if loc := NormalizeMailLocale(*user.PreferredLocale); loc != "" {
return loc
}
} }
if loc, ok := towel.Locale(ctx); ok { if ctx != nil {
return loc if raw, ok := towel.Locale(ctx); ok {
return NormalizeMailLocale(raw)
}
} }
return "" return ""
} }
// MailFallbackLocale returns golem15.user.mail.fallback_locale normalised to
// pl or en: the mail language when neither the user nor the request names
// one the plugin has mail for. The default is pl (the unsuffixed
// templates); an English-only site sets en, for example through
// SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en. A missing app, config or
// blank value gives pl; any other value gives pl and an error naming the key.
func MailFallbackLocale(app *backpack.App) (string, error) {
if app == nil || app.Config == nil {
return mailLocalePL, nil
}
raw := strings.TrimSpace(app.Config.String(mailFallbackLocaleKey))
if raw == "" {
return mailLocalePL, nil
}
if loc := NormalizeMailLocale(raw); loc != "" {
return loc, nil
}
return mailLocalePL, fmt.Errorf("golem15.user: %s must be pl or en, got %q", mailFallbackLocaleKey, raw)
}
// ResolveMailLocaleFor returns the language to mail user in, always pl or
// en: ResolveMailLocale, then the application's MailFallbackLocale. It is the
// helper other plugins use to mail in the user's language with the
// application's fallback; an invalid fallback (rejected at boot) counts as pl.
func ResolveMailLocaleFor(ctx context.Context, app *backpack.App, user *models.User) string {
if loc := ResolveMailLocale(ctx, user); loc != "" {
return loc
}
loc, _ := MailFallbackLocale(app)
return loc
}

View File

@@ -1,16 +1,187 @@
package classes package classes
import "testing" import (
"context"
"strings"
"testing"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/towel"
)
func TestMailTemplate(t *testing.T) { func TestMailTemplate(t *testing.T) {
base := "golem15.user::mail.reactivate" base := "golem15.user::mail.reactivate"
if got := MailTemplate(base, "pl"); got != base { for _, tc := range []struct {
t.Fatalf("pl = %s", got) locale, want string
} }{
if got := MailTemplate(base, ""); got != base { {"pl", base},
t.Fatalf("empty = %s", got) {"", base},
} {"en", base + "-en"},
if got := MailTemplate(base, "en"); got != base+"-en" { {"en-GB", base + "-en"},
t.Fatalf("en = %s", got) {"en-GB,en;q=0.9", base + "-en"},
{"de", base},
{"pl-PL,en;q=0.5", base},
} {
if got := MailTemplate(base, tc.locale); got != tc.want {
t.Errorf("MailTemplate(%q) = %s, want %s", tc.locale, got, tc.want)
}
}
}
func TestNormalizeMailLocale(t *testing.T) {
for _, tc := range []struct {
raw, want string
}{
{"en", "en"},
{"pl", "pl"},
{"EN", "en"},
{"en-GB", "en"},
{"en_US", "en"},
{"pl-PL", "pl"},
{" en-gb ; q=0.9 ", "en"},
{"en-GB,en;q=0.9", "en"},
{"pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7", "pl"},
{"de-DE,de;q=0.9,en;q=0.8", "en"},
{"de-DE,en;q=0.5,pl;q=0.7", "pl"},
{"en;q=0.5,pl;q=0.5", "en"},
{"en;q=0,pl", "pl"},
{"en;q=0", ""},
{"en;q=abc,pl;q=0.1", "pl"},
{"en;q=1.5", ""},
{"english", ""},
{"de", ""},
{"*", ""},
{"", ""},
{" ", ""},
} {
if got := NormalizeMailLocale(tc.raw); got != tc.want {
t.Errorf("NormalizeMailLocale(%q) = %q, want %q", tc.raw, got, tc.want)
}
}
}
func TestResolveMailLocale(t *testing.T) {
str := func(s string) *string { return &s }
header := "en-GB,en;q=0.9"
for _, tc := range []struct {
name string
saved *string
nilUser bool
request string
want string
}{
{"saved region form wins", str("en-GB"), false, "pl", "en"},
{"saved upper case", str("PL"), false, "", "pl"},
{"unsupported saved falls through", str("de"), false, header, "en"},
{"nil user, raw header", nil, true, header, "en"},
{"nil user, no request locale", nil, true, "", ""},
{"empty saved, unsupported request", str(""), false, "fr", ""},
} {
ctx := context.Background()
if tc.request != "" {
ctx = towel.WithLocale(ctx, tc.request)
}
var user *models.User
if !tc.nilUser {
user = &models.User{PreferredLocale: tc.saved}
}
if got := ResolveMailLocale(ctx, user); got != tc.want {
t.Errorf("%s: got %q, want %q", tc.name, got, tc.want)
}
}
}
func mailTestApp(t *testing.T, environ ...string) *backpack.App {
t.Helper()
cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Env: "development", Environ: append([]string{"SUMMER_ENV=development"}, environ...)})
if err != nil {
t.Fatal(err)
}
return backpack.New(cfg)
}
func TestMailFallbackLocale(t *testing.T) {
if got, err := MailFallbackLocale(nil); got != "pl" || err != nil {
t.Errorf("nil app: %q %v", got, err)
}
if got, err := MailFallbackLocale(&backpack.App{}); got != "pl" || err != nil {
t.Errorf("nil config: %q %v", got, err)
}
if got, err := MailFallbackLocale(mailTestApp(t)); got != "pl" || err != nil {
t.Errorf("no key: %q %v", got, err)
}
for _, tc := range []struct {
value, want string
bad bool
}{
{"", "pl", false},
{" ", "pl", false},
{"en", "en", false},
{"EN-gb", "en", false},
{"pl", "pl", false},
{"de", "pl", true},
} {
app := mailTestApp(t)
if err := app.Config.Set("golem15.user.mail.fallback_locale", tc.value); err != nil {
t.Fatal(err)
}
got, err := MailFallbackLocale(app)
if got != tc.want {
t.Errorf("%q: got %q, want %q", tc.value, got, tc.want)
}
if tc.bad {
if err == nil || !strings.Contains(err.Error(), "golem15.user.mail.fallback_locale") || !strings.Contains(err.Error(), `"de"`) {
t.Errorf("%q: error %v", tc.value, err)
}
} else if err != nil {
t.Errorf("%q: unexpected error %v", tc.value, err)
}
}
app := mailTestApp(t, "SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en")
if got, err := MailFallbackLocale(app); got != "en" || err != nil {
t.Errorf("env override: %q %v", got, err)
}
}
func TestResolveMailLocaleFor(t *testing.T) {
const restore = "golem15.user::mail.restore"
user := &models.User{}
headerCtx := towel.WithLocale(context.Background(), "en-GB,en;q=0.9")
// The reported bug: raw Accept-Language, no preferred_locale, default config.
if got := MailTemplate(restore, ResolveMailLocaleFor(headerCtx, mailTestApp(t), user)); got != restore+"-en" {
t.Errorf("raw header: %s", got)
}
if got := MailTemplate(restore, ResolveMailLocaleFor(context.Background(), mailTestApp(t), user)); got != restore {
t.Errorf("default fallback: %s", got)
}
if got := ResolveMailLocaleFor(context.Background(), nil, nil); got != "pl" {
t.Errorf("nil app and user: %q", got)
}
set := mailTestApp(t)
if err := set.Config.Set("golem15.user.mail.fallback_locale", "en"); err != nil {
t.Fatal(err)
}
if got := MailTemplate(restore, ResolveMailLocaleFor(context.Background(), set, user)); got != restore+"-en" {
t.Errorf("fallback en via Set: %s", got)
}
env := mailTestApp(t, "SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en")
if got := MailTemplate(restore, ResolveMailLocaleFor(context.Background(), env, user)); got != restore+"-en" {
t.Errorf("fallback en via env: %s", got)
}
// The user and the request still come first.
if got := ResolveMailLocaleFor(towel.WithLocale(context.Background(), "pl-PL,en;q=0.5"), set, user); got != "pl" {
t.Errorf("Polish-first browser on an en fallback: %q", got)
}
bad := mailTestApp(t)
if err := bad.Config.Set("golem15.user.mail.fallback_locale", "de"); err != nil {
t.Fatal(err)
}
if got := ResolveMailLocaleFor(context.Background(), bad, user); got != "pl" {
t.Errorf("invalid fallback: %q", got)
} }
} }

237
classes/mcp_guard.go Normal file
View File

@@ -0,0 +1,237 @@
package classes
import (
"context"
"fmt"
"slices"
"strings"
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/towel"
"gorm.io/gorm"
)
// The middleware names the guard provider reads on a route.
const (
mcpTokenMiddleware = "user.api_token"
mcpScopeMiddleware = "user.scope:"
mcpPermissionMiddleware = "user.permission:"
)
var (
_ pact.MCPGuard = (*MCPUserGuard)(nil)
_ pact.MCPPersonalTokenResolver = (*MCPUserGuard)(nil)
)
// MCPUserGuard is the plugin's MCP guard provider, named "user": MCP tools
// bind to the plugin's token-guarded routes (user.api_token, user.scope:*,
// user.permission:*) through it, and it resolves the plugin's personal API
// tokens (the usr_ prefix, golem15.user.api_tokens.prefix) at the MCP
// endpoint. Boot registers it in the application's *pact.MCPGuards and
// publishes it as pact.MCPPersonalTokenResolver.
//
// Its checks are the ones the routes run: a scope must be granted to the
// session (as user.scope checks the token), and a permission code must be
// granted by one of the user's groups (as user.permission checks the
// principal PrincipalByID loads; a user's own permission overrides do not
// grant, D-35).
type MCPUserGuard struct {
App *backpack.App
}
// MCPGuardName is "user".
func (g *MCPUserGuard) MCPGuardName() string { return SubjectGuardUser }
// MCPTokenGuarded reports whether the route runs the user.api_token guard.
func (g *MCPUserGuard) MCPTokenGuarded(middleware []string) bool {
return slices.Contains(middleware, mcpTokenMiddleware)
}
// MCPRequirements collects the scopes of user.scope:<scope> and the codes of
// user.permission:<code>. Another user.* name than these and user.api_token
// is an error, so a guard this provider does not understand cannot be
// skipped silently.
func (g *MCPUserGuard) MCPRequirements(middleware []string) (pact.MCPRequirements, error) {
var req pact.MCPRequirements
for _, name := range middleware {
switch {
case name == mcpTokenMiddleware:
case strings.HasPrefix(name, mcpScopeMiddleware):
scope := strings.TrimPrefix(name, mcpScopeMiddleware)
if scope == "" {
return pact.MCPRequirements{}, fmt.Errorf("golem15.user: middleware %q names no scope", name)
}
if !slices.Contains(req.Scopes, scope) {
req.Scopes = append(req.Scopes, scope)
}
case strings.HasPrefix(name, mcpPermissionMiddleware):
code := strings.TrimPrefix(name, mcpPermissionMiddleware)
if code == "" {
return pact.MCPRequirements{}, fmt.Errorf("golem15.user: middleware %q names no permission", name)
}
if !slices.Contains(req.Permissions, code) {
req.Permissions = append(req.Permissions, code)
}
case strings.HasPrefix(name, "user."):
return pact.MCPRequirements{}, fmt.Errorf("golem15.user: the MCP guard does not know middleware %q", name)
}
}
return req, nil
}
// MCPAllows requires every scope of req in the subject's effective scopes,
// then every permission code of req and of the tool, one by one (the route
// runs one user.permission middleware per code), granted to the user's
// groups. Effective scopes are the grant itself for a personal token, and
// for an OAuth subject also the declared names the catalog implies. The
// expanded list is not written back onto the subject.
func (g *MCPUserGuard) MCPAllows(ctx context.Context, subject pact.MCPSubject, req pact.MCPRequirements, permissions []string) (bool, error) {
scopes := g.mcpEffectiveScopes(subject)
for _, scope := range req.Scopes {
if !slices.Contains(scopes, scope) {
return false, nil
}
}
db, err := g.db()
if err != nil {
return false, err
}
principal, err := PrincipalByID(ctx, db.WithContext(ctx), subject.UserID)
if err != nil {
return false, err
}
if principal == nil {
return false, nil
}
for _, code := range append(slices.Clone(req.Permissions), permissions...) {
if !cabana.Allows(principal, []string{code}) {
return false, nil
}
}
return true, nil
}
// MCPDispatch builds the principal (the user with the group grants, as the
// api_token guard loads it) and an in-memory token credential carrying the
// subject's effective scopes, so user.scope sees what the session may call.
// For an OAuth subject that includes declared names the catalog marks as
// implied by a stock scope the grant holds; a personal token's scopes are
// the grant unchanged. For a personal-token subject (ClientID empty) the
// credential's ID is the subject's TokenID, the user_api_tokens row the
// session was opened with, so a handler can record which token made a
// change; an OAuth subject's TokenID is the OAuth server's own token row,
// not one of this plugin's, and its credential keeps ID 0. The credential
// is never saved, and implied names are not written onto a token row or
// onto subject.Scopes. The marker is honoured by the api_token guard only.
func (g *MCPUserGuard) MCPDispatch(ctx context.Context, subject pact.MCPSubject, _ string) (pact.MCPDispatch, error) {
db, err := g.db()
if err != nil {
return pact.MCPDispatch{}, err
}
principal, err := PrincipalByID(ctx, db.WithContext(ctx), subject.UserID)
if err != nil {
return pact.MCPDispatch{}, err
}
if principal == nil {
return pact.MCPDispatch{}, fmt.Errorf("golem15.user: user %d is gone", subject.UserID)
}
credential := &models.APIToken{
UserID: subject.UserID,
Scopes: lagoon.Jsonable[[]string]{Data: g.mcpEffectiveScopes(subject), Valid: true},
}
if subject.ClientID == "" {
credential.ID = subject.TokenID
}
return pact.MCPDispatch{Principal: principal, Credential: credential, Guards: []string{"api_token"}}, nil
}
// mcpEffectiveScopes is the scope list MCPAllows and MCPDispatch share.
// A personal token (ClientID empty) is returned unchanged: the same slice,
// with no declared name added. An OAuth subject gets a clone of its grant
// plus each catalog name whose Implies is read or write, when the clone
// holds that stock scope and not the name. write does not satisfy Implies
// read. Nothing the catalog does not mark is appended. The clone is not
// written back onto subject.Scopes, a token row, or a fingerprint.
func (g *MCPUserGuard) mcpEffectiveScopes(subject pact.MCPSubject) []string {
if subject.ClientID == "" {
return subject.Scopes
}
scopes := slices.Clone(subject.Scopes)
for _, entry := range APITokenScopesFor(g.app()).MemberTokenScopes() {
if entry.Implies != "read" && entry.Implies != "write" {
continue
}
if entry.Name == "" || slices.Contains(scopes, entry.Name) || !slices.Contains(scopes, entry.Implies) {
continue
}
scopes = append(scopes, entry.Name)
}
return scopes
}
// MCPResolvePersonalToken resolves a personal API token of this plugin into
// an MCP subject with the token's own scopes. A token without the configured
// prefix answers false; one with it that is unknown, revoked, expired or
// whose user is gone answers pact.ErrMCPTokenInvalid. A usable token gets
// its last_used_at stamped, and its last_used_ip when the context carries
// the client address (towel.ClientIP, which the MCP endpoint sets), as the
// api_token guard does.
func (g *MCPUserGuard) MCPResolvePersonalToken(ctx context.Context, raw string) (pact.MCPSubject, bool, error) {
prefix, err := APITokenPrefix(g.app())
if err != nil || !strings.HasPrefix(raw, prefix) {
return pact.MCPSubject{}, false, nil
}
db, err := g.db()
if err != nil {
return pact.MCPSubject{}, true, err
}
db = db.WithContext(ctx)
var token models.APIToken
result := db.Where("token_hash = ?", HashAPIToken(raw)).Limit(1).Find(&token)
if result.Error != nil {
return pact.MCPSubject{}, true, result.Error
}
now := time.Now()
if result.RowsAffected == 0 || !token.IsUsableAt(now) {
return pact.MCPSubject{}, true, pact.ErrMCPTokenInvalid
}
principal, err := PrincipalByID(ctx, db, token.UserID)
if err != nil {
return pact.MCPSubject{}, true, err
}
if principal == nil {
return pact.MCPSubject{}, true, pact.ErrMCPTokenInvalid
}
used := map[string]any{"last_used_at": now}
if ip, ok := towel.ClientIP(ctx); ok && strings.TrimSpace(ip) != "" {
used["last_used_ip"] = strings.TrimSpace(ip)
}
if err := db.Model(&models.APIToken{}).Where("id = ?", token.ID).UpdateColumns(used).Error; err != nil {
return pact.MCPSubject{}, true, err
}
return pact.MCPSubject{Guard: SubjectGuardUser, UserID: token.UserID, Scopes: slices.Clone(token.Scopes.Get()), TokenID: token.ID}, true, nil
}
func (g *MCPUserGuard) app() *backpack.App {
if g == nil {
return nil
}
return g.App
}
func (g *MCPUserGuard) db() (*gorm.DB, error) {
app := g.app()
if app == nil {
return nil, fmt.Errorf("golem15.user: app is nil")
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok || gdb == nil {
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
}
return gdb, nil
}

View File

@@ -0,0 +1,31 @@
package classes
import "context"
// OAuthProvider is one social sign-in provider as GET
// /_user/api/v1/oauth-providers lists it: Name is the route segment
// (/oauth/{name}) and Label the button text.
type OAuthProvider struct {
Name string `json:"name"`
Label string `json:"label"`
}
// OAuthProviderSource is what a social-login plugin publishes so the user
// plugin can list its providers and accept them in the unlink routes. The
// user plugin looks it up on every request, so a plugin that boots later is
// still found.
//
// Publish it with an explicit type argument,
//
// app.Publish[classes.OAuthProviderSource](src)
//
// because a bare app.Publish(src) keys the service on its concrete type and
// the lookup misses it (the list then stays empty).
type OAuthProviderSource interface {
// EnabledOAuthProviders returns the providers that are configured right
// now, in display order.
EnabledOAuthProviders(ctx context.Context) []OAuthProvider
// KnownOAuthProviders returns the name of every registered provider,
// enabled or not: an identity of any of them may be unlinked.
KnownOAuthProviders() []string
}

View File

@@ -0,0 +1,91 @@
package classes
import (
"context"
"errors"
"strconv"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"gocloud.dev/blob"
"gorm.io/gorm"
)
// OrganisationLogoSize is the edge in pixels of the logo thumbnail
// OrganisationLogoFields answers.
const OrganisationLogoSize = 256
// organisationLogo loads the organisation's logo attachment, or nil.
func organisationLogo(ctx context.Context, app *backpack.App, org *models.Organisation) (*attach.File, error) {
if app == nil || org == nil || org.ID == 0 {
return nil, nil
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok || gdb == nil {
return nil, nil
}
var f attach.File
err := gdb.WithContext(ctx).
Where("attachment_type = ? AND attachment_id = ? AND field = ?", org.MorphName(), strconv.FormatUint(uint64(org.ID), 10), models.OrganisationLogoField).
Take(&f).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &f, nil
}
// OrganisationLogoURL returns the URL of the organisation's logo at size
// pixels, the way AvatarURL serves a user's picture: the thumbnail (size by
// size, mode auto) of the logo attachment, or the original file's public
// URL (attach.File.URL, which follows storage.uploads.public_path_prefix and
// public_url) when the thumbnail fails (logged). It answers false when the organisation
// has no logo or no file bucket is published. The URL may be relative; a
// caller that needs an absolute URL resolves it. Only a failing database
// lookup is an error.
func OrganisationLogoURL(ctx context.Context, app *backpack.App, org *models.Organisation, size int) (string, bool, error) {
f, err := organisationLogo(ctx, app, org)
if err != nil || f == nil {
return "", false, err
}
bucket, ok := app.Lookup[*blob.Bucket]()
if !ok || bucket == nil {
return "", false, nil
}
url, err := f.Thumb(ctx, bucket, size, size, "auto")
if err != nil {
pluginLog.Error("golem15.user: organisation logo thumb", "err", err)
return f.URL(), true, nil
}
return url, true, nil
}
// OrganisationLogoFields answers the logo keys an application adds to its
// own organisation payloads, named like the user payload's avatar keys:
// has_logo (bool), logo (the attachment's disk name, or nil) and logo_url
// (the OrganisationLogoSize thumbnail URL, or nil). An organisation without
// a logo answers false, nil and nil. Only a failing database lookup is an
// error.
func OrganisationLogoFields(ctx context.Context, app *backpack.App, org *models.Organisation) (map[string]any, error) {
out := map[string]any{"has_logo": false, "logo": nil, "logo_url": nil}
f, err := organisationLogo(ctx, app, org)
if err != nil {
return nil, err
}
if f == nil {
return out, nil
}
out["has_logo"] = true
out["logo"] = f.DiskName
url, ok, err := OrganisationLogoURL(ctx, app, org, OrganisationLogoSize)
if err != nil {
return nil, err
}
if ok && url != "" {
out["logo_url"] = url
}
return out, nil
}

133
classes/permissions.go Normal file
View File

@@ -0,0 +1,133 @@
package classes
import (
"context"
"fmt"
"strings"
"git.golem15.com/golem15/sm-user-plugin/models"
"gorm.io/gorm"
)
// MergedPermissions returns the frontend permissions of a user as PHP
// User::getMergedPermissions builds them:
//
// 1. the permissions of every group the user belongs to are merged, and
// where two groups name the same code the higher value wins ("most
// positive wins": 1 over 0 over -1);
// 2. the user's own permissions are laid over the result, and a user value
// replaces the groups' value whatever it is (a user-level -1 overrides a
// group's 1, and a user-level 1 overrides a group's -1).
//
// The result maps a code to 1 (allowed), -1 (denied) or 0. Use HasPermission
// to ask it a question. A deactivated user's permissions are read as well.
func MergedPermissions(ctx context.Context, db *gorm.DB, userID uint) (map[string]int, error) {
if db == nil {
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
}
var groups []struct{ Permissions models.PermissionSet }
err := fresh(ctx, db).
Table("user_groups").
Select("user_groups.permissions").
Joins("JOIN users_groups ON users_groups.user_group_id = user_groups.id").
Where("users_groups.user_id = ?", userID).
Order("user_groups.id").
Scan(&groups).Error
if err != nil {
return nil, err
}
merged := map[string]int{}
for _, group := range groups {
for code, value := range group.Permissions {
if held, ok := merged[code]; !ok || value > held {
merged[code] = value
}
}
}
var own []struct{ Permissions models.PermissionSet }
err = fresh(ctx, db).
Table("users").
Select("users.permissions").
Where("users.id = ?", userID).
Scan(&own).Error
if err != nil {
return nil, err
}
for _, row := range own {
for code, value := range row.Permissions {
merged[code] = value
}
}
return merged, nil
}
// HasPermission reports whether merged holds code, the single-permission
// case of Winter's User::hasPermission. A permission is held only when the
// matching value is exactly 1. Wildcards work as in Winter:
//
// - code ending in "*" is held when a different stored code starts with the
// part before the asterisk and has the value 1;
// - code starting with "*" is held when a different stored code ends with
// the part after the asterisk and has the value 1;
// - otherwise code is held when it is stored with the value 1, or when a
// stored code ending in "*" with the value 1 is a proper prefix of it.
//
// A stored code that starts with "*" is not treated as a wildcard; Winter
// does not treat it as one either.
func HasPermission(merged map[string]int, code string) bool {
switch {
case len(code) > 1 && strings.HasSuffix(code, "*"):
prefix := strings.TrimSuffix(code, "*")
for stored, value := range merged {
if prefix != stored && strings.HasPrefix(stored, prefix) && value == 1 {
return true
}
}
return false
case len(code) > 1 && strings.HasPrefix(code, "*"):
suffix := strings.TrimPrefix(code, "*")
for stored, value := range merged {
if suffix != stored && strings.HasSuffix(stored, suffix) && value == 1 {
return true
}
}
return false
}
for stored, value := range merged {
if len(stored) > 1 && strings.HasSuffix(stored, "*") {
prefix := strings.TrimSuffix(stored, "*")
if prefix != code && strings.HasPrefix(code, prefix) && value == 1 {
return true
}
continue
}
if stored == code && value == 1 {
return true
}
}
return false
}
// UserHasPermission reports whether the user holds the frontend permission
// code: MergedPermissions followed by HasPermission.
func UserHasPermission(ctx context.Context, db *gorm.DB, userID uint, code string) (bool, error) {
merged, err := MergedPermissions(ctx, db, userID)
if err != nil {
return false, err
}
return HasPermission(merged, code), nil
}
// FrontendPermissionOptions returns the rows of
// golem15_user_frontend_permissions ordered by tab, then code, as PHP
// FrontendPermission::listTabbedPermissions reads them.
func FrontendPermissionOptions(ctx context.Context, db *gorm.DB) ([]models.FrontendPermission, error) {
if db == nil {
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
}
rows := []models.FrontendPermission{}
if err := fresh(ctx, db).Order("tab ASC, code ASC").Find(&rows).Error; err != nil {
return nil, err
}
return rows, nil
}

359
classes/permissions_test.go Normal file
View File

@@ -0,0 +1,359 @@
package classes
import (
"fmt"
"reflect"
"testing"
"git.golem15.com/golem15/sm-user-plugin/models"
)
// TestMergedPermissions pins the port of PHP User::getMergedPermissions and
// Winter's hasPermission: groups merge with "most positive wins", the user's
// own values override the groups' whatever they are, a permission is held
// only at exactly 1, and wildcards work as in Winter.
func TestMergedPermissions(t *testing.T) {
ctx := t.Context()
db := throttleDB(t)
type ask struct {
code string
want bool
}
cases := []struct {
name string
groups []string // permissions column of each group, as stored
own string // users.permissions, as stored; "NULL" stores NULL
merged map[string]int
asks []ask
}{
{
name: "two groups, the higher value wins",
groups: []string{`{"blog.post":-1,"blog.edit":0}`, `{"blog.post":1,"blog.edit":-1}`},
own: "NULL",
merged: map[string]int{"blog.post": 1, "blog.edit": 0},
asks: []ask{{"blog.post", true}, {"blog.edit", false}, {"blog.other", false}},
},
{
name: "the order of the groups does not matter",
groups: []string{`{"blog.post":1}`, `{"blog.post":-1}`},
own: "NULL",
merged: map[string]int{"blog.post": 1},
asks: []ask{{"blog.post", true}},
},
{
name: "a user-level deny overrides a group's allow",
groups: []string{`{"blog.post":1,"blog.edit":1}`},
own: `{"blog.post":-1}`,
merged: map[string]int{"blog.post": -1, "blog.edit": 1},
asks: []ask{{"blog.post", false}, {"blog.edit", true}},
},
{
// The port is not "deny wins".
name: "a user-level allow overrides a group's deny",
groups: []string{`{"blog.post":-1}`, `{"blog.post":-1}`},
own: `{"blog.post":1}`,
merged: map[string]int{"blog.post": 1},
asks: []ask{{"blog.post", true}},
},
{
name: "a code held only at 0 or -1 is not held",
groups: []string{`{"blog.zero":0,"blog.denied":-1}`},
own: `{"blog.own_denied":-1}`,
merged: map[string]int{"blog.zero": 0, "blog.denied": -1, "blog.own_denied": -1},
asks: []ask{{"blog.zero", false}, {"blog.denied", false}, {"blog.own_denied", false}},
},
{
name: "a user with no groups has only their own permissions",
groups: nil,
own: `{"blog.post":1,"shop.buy":-1}`,
merged: map[string]int{"blog.post": 1, "shop.buy": -1},
asks: []ask{{"blog.post", true}, {"shop.buy", false}},
},
{
name: "a user with nothing stored holds nothing",
groups: nil,
own: "NULL",
merged: map[string]int{},
asks: []ask{{"blog.post", false}, {"*", false}, {"blog.*", false}},
},
{
name: "an asked code ending in an asterisk matches a stored code by prefix",
groups: []string{`{"blog.post":1,"shop.buy":-1}`},
own: "NULL",
merged: map[string]int{"blog.post": 1, "shop.buy": -1},
asks: []ask{
{"blog.*", true},
{"shop.*", false}, // the only match is denied
{"blog.post*", false}, // the prefix must not equal the stored code
{"news.*", false},
},
},
{
name: "an asked code starting with an asterisk matches a stored code by suffix",
groups: []string{`{"blog.post":1,"shop.post":-1,"shop.buy":-1}`},
own: "NULL",
merged: map[string]int{"blog.post": 1, "shop.post": -1, "shop.buy": -1},
asks: []ask{{"*.post", true}, {"*.buy", false}, {"*blog.post", false}},
},
{
name: "a stored code ending in an asterisk grants the codes under it",
groups: []string{`{"blog.*":1,"shop.*":-1}`},
own: `{"news.*":0}`,
merged: map[string]int{"blog.*": 1, "shop.*": -1, "news.*": 0},
asks: []ask{
{"blog.post", true},
{"blog.", false}, // the stored prefix itself is not under it
{"shop.buy", false},
{"news.read", false},
},
},
{
// Winter treats a leading asterisk as a wildcard only on the asked
// code, never on a stored one. Asking "*.post" still matches the
// stored "*.post" as a longer code with that suffix.
name: "a stored code starting with an asterisk is not a wildcard",
groups: []string{`{"*.post":1}`},
own: "NULL",
merged: map[string]int{"*.post": 1},
asks: []ask{{"blog.post", false}, {"*.post", true}},
},
{
name: "stored shapes are read tolerantly",
groups: []string{``, `[]`, `{"blog.post":"1","blog.bad":"yes","blog.edit":"-1"}`},
own: ``,
merged: map[string]int{"blog.post": 1, "blog.edit": -1},
asks: []ask{{"blog.post", true}, {"blog.bad", false}, {"blog.edit", false}},
},
{
name: "several groups: the highest value of each code wins",
groups: []string{
`{"blog.post":-1,"blog.edit":1,"shop.buy":0}`,
`{"blog.post":0,"blog.edit":-1,"news.read":1}`,
`{"blog.post":1,"shop.buy":-1}`,
`{}`,
},
own: "NULL",
merged: map[string]int{"blog.post": 1, "blog.edit": 1, "shop.buy": 0, "news.read": 1},
asks: []ask{{"blog.post", true}, {"blog.edit", true}, {"shop.buy", false}, {"news.read", true}, {"news.*", true}},
},
{
name: "numbers stored as text count at both levels",
groups: []string{`{"blog.post":"1","blog.edit":"1","shop.buy":"-1"}`},
own: `{"blog.edit":"-1","shop.buy":"1","news.read":"0"}`,
merged: map[string]int{"blog.post": 1, "blog.edit": -1, "shop.buy": 1, "news.read": 0},
asks: []ask{{"blog.post", true}, {"blog.edit", false}, {"shop.buy", true}, {"news.read", false}},
},
{
name: "groups that store nothing leave the user's own permissions",
groups: []string{`{}`, ``, `[]`},
own: `{"blog.post":1}`,
merged: map[string]int{"blog.post": 1},
asks: []ask{{"blog.post", true}, {"blog.edit", false}},
},
{
name: "a code present only at user level is held or denied by that value alone",
groups: []string{`{"blog.post":1}`},
own: `{"only.allow":1,"only.deny":-1,"only.inherit":0}`,
merged: map[string]int{"blog.post": 1, "only.allow": 1, "only.deny": -1, "only.inherit": 0},
asks: []ask{{"only.allow", true}, {"only.deny", false}, {"only.inherit", false}, {"only.*", true}, {"blog.post", true}},
},
{
// 12.1-SECURITY-REVIEW.md, open item 5: the resolver reads
// numbers only. A boolean is not a grant here.
name: "a boolean value is not a grant",
groups: []string{`{"blog.post":true,"blog.edit":false}`},
own: `{"shop.buy":true}`,
merged: map[string]int{},
asks: []ask{{"blog.post", false}, {"shop.buy", false}},
},
}
for i, c := range cases {
t.Run(c.name, func(t *testing.T) {
user := models.User{Email: fmt.Sprintf("merged-%d@example.test", i)}
if err := db.Omit("Groups").Create(&user).Error; err != nil {
t.Fatal(err)
}
if c.own != "NULL" {
if err := db.Exec(`UPDATE users SET permissions = ? WHERE id = ?`, c.own, user.ID).Error; err != nil {
t.Fatal(err)
}
}
for j, stored := range c.groups {
var groupID uint
if err := db.Raw(`INSERT INTO user_groups (name, permissions, created_at, updated_at) VALUES (?, ?, NOW(), NOW()) RETURNING id`,
fmt.Sprintf("Merged %d.%d", i, j), stored).Scan(&groupID).Error; err != nil {
t.Fatal(err)
}
if err := db.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, user.ID, groupID).Error; err != nil {
t.Fatal(err)
}
}
merged, err := MergedPermissions(ctx, db, user.ID)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(merged, c.merged) {
t.Fatalf("merged = %v, want %v", merged, c.merged)
}
for _, a := range c.asks {
if got := HasPermission(merged, a.code); got != a.want {
t.Errorf("HasPermission(%q) = %v, want %v", a.code, got, a.want)
}
got, err := UserHasPermission(ctx, db, user.ID, a.code)
if err != nil || got != a.want {
t.Errorf("UserHasPermission(%q) = %v %v, want %v", a.code, got, err, a.want)
}
}
})
}
// A deactivated user's permissions are still read.
gone := models.User{Email: "merged-gone@example.test"}
if err := db.Omit("Groups").Create(&gone).Error; err != nil {
t.Fatal(err)
}
if err := db.Exec(`UPDATE users SET permissions = '{"blog.post":1}', deleted_at = NOW() WHERE id = ?`, gone.ID).Error; err != nil {
t.Fatal(err)
}
if held, err := UserHasPermission(ctx, db, gone.ID, "blog.post"); err != nil || !held {
t.Fatalf("deactivated user: %v %v", held, err)
}
// A user who does not exist holds nothing.
if merged, err := MergedPermissions(ctx, db, 987654321); err != nil || len(merged) != 0 {
t.Fatalf("unknown user: %v %v", merged, err)
}
// A damaged row is an error, never "no permissions".
damaged := models.User{Email: "merged-damaged@example.test"}
if err := db.Omit("Groups").Create(&damaged).Error; err != nil {
t.Fatal(err)
}
if err := db.Exec(`UPDATE users SET permissions = '{"blog.post":' WHERE id = ?`, damaged.ID).Error; err != nil {
t.Fatal(err)
}
if _, err := MergedPermissions(ctx, db, damaged.ID); err == nil {
t.Fatal("damaged permissions were read without an error")
}
if _, err := UserHasPermission(ctx, db, damaged.ID, "blog.post"); err == nil {
t.Fatal("UserHasPermission swallowed the error")
}
if err := db.Exec(`DELETE FROM users WHERE id = ?`, damaged.ID).Error; err != nil {
t.Fatal(err)
}
if _, err := MergedPermissions(ctx, nil, gone.ID); err == nil {
t.Fatal("MergedPermissions without a handle")
}
if _, err := FrontendPermissionOptions(ctx, nil); err == nil {
t.Fatal("FrontendPermissionOptions without a handle")
}
// The option catalogue is read by tab, then code.
if err := db.Exec(`INSERT INTO golem15_user_frontend_permissions (code, label, tab, comment) VALUES
('merged.b', 'B', 'Zeta', NULL), ('merged.c', 'C', 'Alpha', 'A comment'), ('merged.a', 'A', 'Zeta', NULL)`).Error; err != nil {
t.Fatal(err)
}
options, err := FrontendPermissionOptions(ctx, db)
if err != nil {
t.Fatal(err)
}
var codes []string
for _, option := range options {
if len(option.Code) > 7 && option.Code[:7] == "merged." {
codes = append(codes, option.Code)
if option.Code == "merged.c" && (option.Comment == nil || *option.Comment != "A comment" || option.Tab != "Alpha" || option.Label != "C") {
t.Fatalf("option = %+v", option)
}
}
}
if want := []string{"merged.c", "merged.a", "merged.b"}; !reflect.DeepEqual(codes, want) {
t.Fatalf("option order = %v, want %v", codes, want)
}
}
// TestPermissionSetScan pins the tolerant read and the strict write of a
// stored permission column.
func TestPermissionSetScan(t *testing.T) {
scans := []struct {
name string
src any
want models.PermissionSet
wantErr bool
}{
{"NULL", nil, models.PermissionSet{}, false},
{"empty string", "", models.PermissionSet{}, false},
{"blank string", " \n", models.PermissionSet{}, false},
{"the text []", "[]", models.PermissionSet{}, false},
{"the text null", "null", models.PermissionSet{}, false},
{"empty object", "{}", models.PermissionSet{}, false},
{"bytes", []byte(`{"a.b":1}`), models.PermissionSet{"a.b": 1}, false},
{"integers", `{"a.b":1,"c.d":-1,"e.f":0}`, models.PermissionSet{"a.b": 1, "c.d": -1, "e.f": 0}, false},
{"numeric strings", `{"a.b":"1","c.d":"-1"," e.f":" 1 "}`, models.PermissionSet{"a.b": 1, "c.d": -1, " e.f": 1}, false},
{"a non-numeric entry is skipped", `{"a.b":1,"c.d":"yes","e.f":true,"g.h":null,"i.j":1.5,"k.l":[1],"m.n":{"x":1}}`, models.PermissionSet{"a.b": 1}, false},
{"malformed JSON", `{"a.b":1`, nil, true},
{"a non-empty list", `["a.b"]`, nil, true},
{"a scalar", `1`, nil, true},
{"a string scalar", `"a.b"`, nil, true},
{"trailing data", `{"a.b":1} {"c.d":1}`, nil, true},
{"an unsupported driver type", 42, nil, true},
}
for _, c := range scans {
t.Run(c.name, func(t *testing.T) {
set := models.PermissionSet{"stale": 1}
err := set.Scan(c.src)
if c.wantErr {
if err == nil {
t.Fatalf("Scan(%v) = %v, want an error", c.src, set)
}
return
}
if err != nil || set == nil || !reflect.DeepEqual(set, c.want) {
t.Fatalf("Scan(%v) = %v %v, want %v", c.src, set, err, c.want)
}
})
}
values := []struct {
name string
set models.PermissionSet
want any
}{
{"nil set", nil, nil},
{"empty set", models.PermissionSet{}, nil},
{"only zeros", models.PermissionSet{"a.b": 0}, nil},
{"a zero is left out", models.PermissionSet{"b.c": -1, "a.b": 1, "z.z": 0}, `{"a.b":1,"b.c":-1}`},
}
for _, c := range values {
t.Run("value of "+c.name, func(t *testing.T) {
got, err := c.set.Value()
if err != nil || !reflect.DeepEqual(got, c.want) {
t.Fatalf("Value() = %#v %v, want %#v", got, err, c.want)
}
})
}
// Through GORM: a stored set comes back as written, an empty one as NULL.
db := throttleDB(t)
user := models.User{Email: "permission-set@example.test", Permissions: models.PermissionSet{"a.b": 1, "c.d": -1, "e.f": 0}}
if err := db.Omit("Groups").Create(&user).Error; err != nil {
t.Fatal(err)
}
var stored *string
if err := db.Raw(`SELECT permissions FROM users WHERE id = ?`, user.ID).Scan(&stored).Error; err != nil || stored == nil || *stored != `{"a.b":1,"c.d":-1}` {
t.Fatalf("stored permissions = %v err = %v", stored, err)
}
var loaded models.User
if err := db.Take(&loaded, user.ID).Error; err != nil || !reflect.DeepEqual(loaded.Permissions, models.PermissionSet{"a.b": 1, "c.d": -1}) {
t.Fatalf("loaded permissions = %v err = %v", loaded.Permissions, err)
}
loaded.Permissions = models.PermissionSet{}
if err := db.Omit("Groups").Save(&loaded).Error; err != nil {
t.Fatal(err)
}
if err := db.Raw(`SELECT permissions FROM users WHERE id = ?`, user.ID).Scan(&stored).Error; err != nil {
t.Fatal(err)
}
var isNull bool
if err := db.Raw(`SELECT permissions IS NULL FROM users WHERE id = ?`, user.ID).Scan(&isNull).Error; err != nil || !isNull {
t.Fatalf("an empty set was not stored as NULL: %v", err)
}
}

124
classes/privileged.go Normal file
View File

@@ -0,0 +1,124 @@
package classes
import (
"context"
"fmt"
"strings"
"git.golem15.com/golem15/summercms/modules/compass"
"gorm.io/gorm"
)
// PermissionManagePrivilegedGroups is the backend permission an administrator
// needs, on top of golem15.users.access_users, to change the email or the
// password of a member of a privileged group, or to delete such a user for
// good.
const PermissionManagePrivilegedGroups = "golem15.users.manage_privileged_groups"
// PermissionManageBackendLinks is the backend permission an administrator
// needs to link a frontend account to another administrator, or to unlink
// one, on the Administrators screen. No role has it by default.
const PermissionManageBackendLinks = "golem15.users.manage_backend_links"
// privilegedGroupsKey is the config list of privileged group codes.
const privilegedGroupsKey = "golem15.user.privileged_groups"
// defaultPrivilegedGroup is the only privileged code when the config names
// none: the site-admin group.
const defaultPrivilegedGroup = "admin"
// PrivilegedGroupCodes returns the group codes whose members are protected,
// read from golem15.user.privileged_groups on every call so a config change
// applies without a restart. A nil config or a missing key gives the single
// code admin. Blank entries are dropped; a key that is present and empty
// means that no group is privileged.
func PrivilegedGroupCodes(cfg *compass.Config) []string {
if cfg == nil {
return []string{defaultPrivilegedGroup}
}
raw, ok := cfg.Lookup(privilegedGroupsKey)
if !ok {
return []string{defaultPrivilegedGroup}
}
var entries []string
switch v := raw.(type) {
case []string:
entries = v
case []any:
for _, item := range v {
if s, ok := item.(string); ok {
entries = append(entries, s)
}
}
case string:
// An environment override arrives as one comma-separated string.
entries = strings.Split(v, ",")
}
codes := make([]string, 0, len(entries))
for _, entry := range entries {
if code := strings.TrimSpace(entry); code != "" {
codes = append(codes, code)
}
}
return codes
}
// IsPrivilegedCode reports whether a group's code is in codes. Codes compare
// case-sensitively, as HasGroupCode does, and a group without a code is
// never privileged.
func IsPrivilegedCode(codes []string, code *string) bool {
if code == nil || *code == "" {
return false
}
for _, privileged := range codes {
if privileged == *code {
return true
}
}
return false
}
// PrivilegedGroupIDs returns the ids of the user_groups rows whose code is in
// codes, ordered by id.
func PrivilegedGroupIDs(ctx context.Context, db *gorm.DB, codes []string) ([]uint, error) {
if db == nil {
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
}
ids := []uint{}
if len(codes) == 0 {
return ids, nil
}
err := fresh(ctx, db).
Table("user_groups").
Where("code IN ?", codes).
Order("id").
Pluck("id", &ids).Error
if err != nil {
return nil, err
}
return ids, nil
}
// IsPrivilegedMember reports whether the user belongs to at least one group
// whose code is in codes. A user in no group, and a group without a code,
// give false. A deactivated user's membership counts: it survives the soft
// delete. The membership is read through an empty statement on db's
// connection, so conditions the caller's handle carries never narrow it.
func IsPrivilegedMember(ctx context.Context, db *gorm.DB, codes []string, userID uint) (bool, error) {
if db == nil {
return false, fmt.Errorf("golem15.user: gorm handle is missing")
}
if len(codes) == 0 || userID == 0 {
return false, nil
}
held, err := UserGroupCodes(ctx, fresh(ctx, db), userID)
if err != nil {
return false, err
}
for i := range held {
if IsPrivilegedCode(codes, &held[i]) {
return true, nil
}
}
return false, nil
}

207
classes/privileged_test.go Normal file
View File

@@ -0,0 +1,207 @@
package classes
import (
"os"
"path/filepath"
"reflect"
"testing"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/compass"
)
// privilegedConfig opens a config whose golem15.user.privileged_groups is
// value; a nil value leaves the key out.
func privilegedConfig(t *testing.T, value any, environ ...string) *compass.Config {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: privileged\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: append([]string{"SUMMER_ENV=development"}, environ...)})
if err != nil {
t.Fatal(err)
}
if value != nil {
if err := cfg.Set(privilegedGroupsKey, value); err != nil {
t.Fatal(err)
}
}
return cfg
}
// TestPrivilegedGroupCodes pins how the privileged list is read (D-05): the
// default, an override, blank entries and the comma-separated form of an
// environment variable.
func TestPrivilegedGroupCodes(t *testing.T) {
if got := PrivilegedGroupCodes(nil); !reflect.DeepEqual(got, []string{"admin"}) {
t.Fatalf("nil config = %v", got)
}
for _, tc := range []struct {
name string
value any
want []string
}{
{"a missing key", nil, []string{"admin"}},
{"a list", []string{"admin", "moderator"}, []string{"admin", "moderator"}},
{"a list of any", []any{"owner", 7, "staff"}, []string{"owner", "staff"}},
{"blank entries", []string{" admin ", "", " ", "staff"}, []string{"admin", "staff"}},
{"an empty list", []string{}, []string{}},
{"a comma-separated string", "admin, staff ,,owner", []string{"admin", "staff", "owner"}},
{"an empty string", "", []string{}},
{"a value of another type", 5, []string{}},
} {
t.Run(tc.name, func(t *testing.T) {
got := PrivilegedGroupCodes(privilegedConfig(t, tc.value))
if got == nil || !reflect.DeepEqual(got, tc.want) {
t.Fatalf("codes = %#v, want %#v", got, tc.want)
}
})
}
// The key is read on every call: a change applies without a new config.
cfg := privilegedConfig(t, []string{"first"})
if got := PrivilegedGroupCodes(cfg); !reflect.DeepEqual(got, []string{"first"}) {
t.Fatalf("codes = %v", got)
}
if err := cfg.Set(privilegedGroupsKey, []string{"second"}); err != nil {
t.Fatal(err)
}
if got := PrivilegedGroupCodes(cfg); !reflect.DeepEqual(got, []string{"second"}) {
t.Fatalf("codes after the change = %v", got)
}
if PermissionManagePrivilegedGroups != "golem15.users.manage_privileged_groups" {
t.Fatalf("permission code = %q", PermissionManagePrivilegedGroups)
}
}
// TestIsPrivilegedCode: codes compare case-sensitively and a group without a
// code is never privileged.
func TestIsPrivilegedCode(t *testing.T) {
str := func(s string) *string { return &s }
codes := []string{"admin", "Staff"}
for _, tc := range []struct {
code *string
want bool
}{
{str("admin"), true}, {str("Staff"), true},
{str("Admin"), false}, {str("ADMIN"), false}, {str("staff"), false},
{str("admin "), false}, {str(" admin"), false}, {str("administrator"), false},
{str(""), false}, {nil, false},
} {
if got := IsPrivilegedCode(codes, tc.code); got != tc.want {
label := "<nil>"
if tc.code != nil {
label = *tc.code
}
t.Errorf("IsPrivilegedCode(%q) = %v, want %v", label, got, tc.want)
}
}
if IsPrivilegedCode(nil, str("admin")) || IsPrivilegedCode([]string{}, str("admin")) {
t.Error("an empty list has a privileged code")
}
// An empty entry in the list never matches a group without a code.
if IsPrivilegedCode([]string{""}, str("")) || IsPrivilegedCode([]string{""}, nil) {
t.Error("an empty code is privileged")
}
}
// TestIsPrivilegedMember covers the membership question behind the takeover
// guard (D-30) and PrivilegedGroupIDs behind the groups lock (D-07).
func TestIsPrivilegedMember(t *testing.T) {
ctx := t.Context()
db := throttleDB(t)
str := func(s string) *string { return &s }
admins := models.UserGroup{Name: "Admins", Code: str("admin")}
second := models.UserGroup{Name: "Second admins", Code: str("admin2")}
ordinary := models.UserGroup{Name: "Ordinary", Code: str("ordinary")}
upper := models.UserGroup{Name: "Upper", Code: str("ADMIN")}
uncoded := models.UserGroup{Name: "Uncoded"}
for _, group := range []*models.UserGroup{&admins, &second, &ordinary, &upper, &uncoded} {
if err := db.Create(group).Error; err != nil {
t.Fatal(err)
}
}
user := func(label string, groups ...*models.UserGroup) uint {
t.Helper()
u := models.User{Email: "privileged-" + label + "@example.test", IsActivated: true}
if err := db.Omit("Groups").Create(&u).Error; err != nil {
t.Fatal(err)
}
for _, group := range groups {
if err := db.Create(&models.UsersGroup{UserID: u.ID, UserGroupID: group.ID}).Error; err != nil {
t.Fatal(err)
}
}
return u.ID
}
nobody := user("nobody")
plain := user("plain", &ordinary)
codeless := user("codeless", &uncoded, &upper)
member := user("member", &ordinary, &admins)
gone := user("gone", &admins)
if err := db.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, gone).Error; err != nil {
t.Fatal(err)
}
defaults := PrivilegedGroupCodes(nil)
for _, tc := range []struct {
name string
codes []string
user uint
want bool
}{
{"a user in no group", defaults, nobody, false},
{"an ordinary group only", defaults, plain, false},
{"a group without a code and a case variant", defaults, codeless, false},
{"a member of a listed group", defaults, member, true},
{"a deactivated member", defaults, gone, true},
{"an overridden list without admin", []string{"ordinary"}, gone, false},
{"an overridden list with the ordinary code", []string{"ordinary"}, plain, true},
{"an overridden list, a member of both", []string{"ordinary"}, member, true},
{"a case variant in the list", []string{"ADMIN"}, codeless, true},
{"an empty list", []string{}, member, false},
{"a nil list", nil, member, false},
{"an unknown user", defaults, 987654, false},
{"the zero user", defaults, 0, false},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := IsPrivilegedMember(ctx, db, tc.codes, tc.user)
if err != nil || got != tc.want {
t.Fatalf("IsPrivilegedMember = %v %v, want %v", got, err, tc.want)
}
})
}
if _, err := IsPrivilegedMember(ctx, nil, defaults, member); err == nil {
t.Fatal("IsPrivilegedMember without a handle")
}
// The handle's own conditions do not leak into the query.
scoped := db.Where("1 = 0")
if got, err := IsPrivilegedMember(ctx, scoped, defaults, member); err != nil || !got {
t.Fatalf("with a scoped handle = %v %v", got, err)
}
// A failing query is an error, never "not a member".
cancelled, cancel := contextCancelled(t)
defer cancel()
if got, err := IsPrivilegedMember(cancelled, db, defaults, member); err == nil || got {
t.Fatalf("a failed query answered %v %v", got, err)
}
ids, err := PrivilegedGroupIDs(ctx, db, []string{"admin", "admin2", "missing"})
if err != nil || !reflect.DeepEqual(ids, []uint{admins.ID, second.ID}) {
t.Fatalf("PrivilegedGroupIDs = %v %v", ids, err)
}
if ids, err = PrivilegedGroupIDs(ctx, scoped, defaults); err != nil || !reflect.DeepEqual(ids, []uint{admins.ID}) {
t.Fatalf("PrivilegedGroupIDs with a scoped handle = %v %v", ids, err)
}
for _, codes := range [][]string{nil, {}, {"nothing"}} {
if ids, err = PrivilegedGroupIDs(ctx, db, codes); err != nil || ids == nil || len(ids) != 0 {
t.Fatalf("PrivilegedGroupIDs(%v) = %#v %v", codes, ids, err)
}
}
if _, err = PrivilegedGroupIDs(ctx, nil, defaults); err == nil {
t.Fatal("PrivilegedGroupIDs without a handle")
}
if _, err = PrivilegedGroupIDs(cancelled, db, defaults); err == nil {
t.Fatal("PrivilegedGroupIDs swallowed a failed query")
}
}

275
classes/session_user.go Normal file
View File

@@ -0,0 +1,275 @@
package classes
import (
"context"
"errors"
"fmt"
"net/http"
"slices"
"strconv"
"strings"
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"gorm.io/gorm"
)
// sessionCookieNames are the cookies the plugin's "jwt" guard reads after
// the Authorization header, in the same order (plugin.go Boot).
var sessionCookieNames = []string{"token", "auth_token"}
// SessionCookieNames returns a copy of the cookie names the plugin's "jwt"
// guard (plugin.go Boot) reads after the Authorization header, in order.
// A handler that builds its own guard passes them to bouncer.NewJWTGuard so
// it reads the same token as SessionToken and jwt.auth.
func SessionCookieNames() []string {
return slices.Clone(sessionCookieNames)
}
// RequestUser returns the signed-in user of r for handlers that run without
// the jwt.auth middleware and must also serve anonymous requests (an OAuth
// provider's authorize page, for example). The token is read and checked
// exactly as the plugin's "jwt" guard does: the Authorization bearer header
// first, then the token and auth_token cookies; the plugin's JWT secret;
// the published bouncer.BlacklistStore when there is one; and the user's
// tokens_valid_after cutoff. A soft-deleted user is not returned.
//
// An anonymous request, or a token that is invalid, expired, blacklisted or
// names no user, returns (nil, nil). Only an infrastructure failure (no
// database handle, a failing query or blacklist lookup) returns an error.
func RequestUser(ctx context.Context, app *backpack.App, r *http.Request) (*models.User, error) {
if r == nil {
return nil, nil
}
raw := SessionToken(r)
if raw == "" {
return nil, nil
}
secret, err := JWTSecret(app)
if err != nil {
return nil, err
}
sub, iat, _, jti, err := bouncer.VerifyClaims(raw, secret)
if err != nil {
return nil, nil
}
id, err := strconv.ParseUint(sub, 10, 64)
if err != nil || id == 0 {
return nil, nil
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok || gdb == nil {
return nil, fmt.Errorf("golem15.user: gorm handle is missing")
}
var user models.User
err = gdb.WithContext(ctx).Where("id = ?", uint(id)).Take(&user).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
if bl, ok := app.Lookup[bouncer.BlacklistStore](); ok && bl != nil {
blocked, err := bl.IsBlacklisted(ctx, jti)
if err != nil {
return nil, err
}
if blocked {
return nil, nil
}
}
if user.TokensValidAfter != nil && iat.Before(*user.TokensValidAfter) {
return nil, nil
}
return &user, nil
}
// EndSession signs the request out; POST /logout runs it. Every session JWT
// r carries (the Authorization bearer header and the token and auth_token
// cookies the "jwt" guard reads) that verifies is added to the published
// bouncer.BlacklistStore, so the guard, RequestUser and POST /refresh refuse
// it from then on. A token verifies while it is unexpired, and a token with
// the user audience also after its access lifetime while its refresh window
// is open (it could still be refreshed). The row is kept until the later of
// the token's exp and its iat plus the refresh window
// (golem15.user.jwt.refresh_ttl), plus one minute, as bouncer.Refresh keeps
// a rotated jti: a row that ended at exp would let /refresh revive the
// logged-out token for the rest of its window.
//
// When w is not nil the response gets the forget cookie of
// bouncer.LoadCookieConfig(app.Config), with the name, path, domain,
// SameSite and Secure of the token cookie a login writes, and one with the
// same attributes for each other session cookie r carries. It writes no
// status or body.
//
// It returns the subject of the token the guard would read (the bearer
// header first, then the cookies in order), or "" when r carries none or it
// does not verify. Only a failing blacklist write is an error; the cookies
// are forgotten and the other tokens revoked in any case. Without a
// published blacklist nothing is revoked.
func EndSession(ctx context.Context, app *backpack.App, w http.ResponseWriter, r *http.Request) (string, error) {
if w != nil {
forgetSessionCookies(app, w, r)
}
if r == nil || app == nil {
return "", nil
}
secret, err := JWTSecret(app)
if err != nil {
return "", nil
}
bl, _ := app.Lookup[bouncer.BlacklistStore]()
window := refreshWindow(app)
subject := ""
var firstErr error
for i, raw := range sessionTokens(r) {
sub, iat, exp, jti, ok := verifySessionToken(raw, secret, window)
if !ok {
continue
}
if i == 0 {
subject = sub
}
if bl == nil {
continue
}
if err := bl.Add(ctx, jti, revokedUntil(iat, exp, window), time.Now()); err != nil && firstErr == nil {
firstErr = err
}
}
return subject, firstErr
}
// EndRequestSession is the best-effort EndSession, as in the PHP provider:
// it revokes the session JWTs r carries and forgets the session cookies the
// same way, logs a blacklist failure instead of returning it, and always
// returns nil. It writes no status or body.
func EndRequestSession(ctx context.Context, app *backpack.App, w http.ResponseWriter, r *http.Request) error {
if _, err := EndSession(ctx, app, w, r); err != nil {
pluginLog.Warn("golem15.user: end session: blacklist token", "err", err)
}
return nil
}
// forgetSessionCookies expires the token cookie of
// bouncer.LoadCookieConfig(app.Config) and, with the same path, domain,
// SameSite and Secure, each other session cookie r carries.
func forgetSessionCookies(app *backpack.App, w http.ResponseWriter, r *http.Request) {
cfg := bouncer.CookieConfig{Name: bouncer.DefaultCookieName, Path: "/", SameSite: http.SameSiteLaxMode}
if app != nil && app.Config != nil {
loaded, err := bouncer.LoadCookieConfig(app.Config)
if err != nil {
pluginLog.Warn("golem15.user: end session: cookie config", "err", err)
} else {
cfg = loaded
}
}
http.SetCookie(w, cfg.ForgetTokenCookie())
if r == nil {
return
}
for _, name := range sessionCookieNames {
if name == cfg.Name {
continue
}
if _, err := r.Cookie(name); err != nil {
continue
}
other := cfg
other.Name = name
http.SetCookie(w, other.ForgetTokenCookie())
}
}
// verifySessionToken accepts raw when it is a token the "jwt" guard accepts
// or POST /refresh still rotates: a user-audience token whose refresh window
// is open (its exp may have passed), or an unexpired token, which also
// covers one without an audience (issued by the PHP backend). A token
// without a jti cannot be revoked and is refused.
func verifySessionToken(raw, secret string, window time.Duration) (sub string, iat, exp time.Time, jti string, ok bool) {
sub, iat, exp, jti, err := bouncer.VerifyRefreshableClaimsAudience(raw, secret, bouncer.AudienceUser, window)
if err != nil {
sub, iat, exp, jti, err = bouncer.VerifyClaims(raw, secret)
}
return sub, iat, exp, jti, err == nil && jti != ""
}
// revokedUntil is the storage expiry of a revoked session jti: the later of
// exp and iat plus the refresh window, plus one minute (PHP jwt-auth's
// Blacklist::getMinutesUntilExpired, which bouncer.Refresh follows).
func revokedUntil(iat, exp time.Time, window time.Duration) time.Time {
until := iat.Add(window)
if exp.After(until) {
until = exp
}
return until.Add(time.Minute)
}
// refreshWindow is golem15.user.jwt.refresh_ttl minutes, default 20160: the
// window POST /refresh accepts (controllers.RefreshTTL reads the same key).
func refreshWindow(app *backpack.App) time.Duration {
mins := 20160
if app != nil && app.Config != nil && app.Config.Int("golem15.user.jwt.refresh_ttl") > 0 {
mins = app.Config.Int("golem15.user.jwt.refresh_ttl")
}
return time.Duration(mins) * time.Minute
}
// SessionToken returns the session JWT the plugin's "jwt" guard reads from r:
// the Authorization bearer header, then each cookie of SessionCookieNames in
// order, trimmed, empty values skipped. It returns "" when r carries none.
// A controller that builds its own guard passes SessionCookieNames() to
// bouncer.NewJWTGuard, so the guard and SessionToken read the same token.
func SessionToken(r *http.Request) string {
if tokens := sessionTokens(r); len(tokens) > 0 {
return tokens[0]
}
return ""
}
// SessionTokenCookie names the session cookie that supplied the token
// SessionToken returns, for a handler that writes that cookie back (POST
// /refresh rewrites it with the rotated token). It is "" when the bearer
// header supplied the token or the request carries none.
func SessionTokenCookie(r *http.Request) string {
if r == nil || bearerToken(r) != "" {
return ""
}
for _, name := range sessionCookieNames {
if c, err := r.Cookie(name); err == nil && strings.TrimSpace(c.Value) != "" {
return name
}
}
return ""
}
// bearerToken returns the trimmed token of r's Authorization bearer header,
// "" when there is none.
func bearerToken(r *http.Request) string {
h := strings.TrimSpace(r.Header.Get("Authorization"))
if token, ok := strings.CutPrefix(h, "Bearer "); ok {
return strings.TrimSpace(token)
}
return ""
}
// sessionTokens returns every distinct session JWT r carries, in the order
// the "jwt" guard tries them: the Authorization bearer header, then each
// session cookie. Empty values are skipped.
func sessionTokens(r *http.Request) []string {
var out []string
add := func(v string) {
if v = strings.TrimSpace(v); v != "" && !slices.Contains(out, v) {
out = append(out, v)
}
}
add(bearerToken(r))
for _, name := range sessionCookieNames {
if c, err := r.Cookie(name); err == nil {
add(c.Value)
}
}
return out
}

69
classes/subject_events.go Normal file
View File

@@ -0,0 +1,69 @@
package classes
import (
"context"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"gorm.io/gorm"
)
// Guard names the plugin's pact.MCPSubjectChanged events carry: the frontend
// user guard this plugin provides and the admin's guard (for the backend
// side of an account link).
const (
SubjectGuardUser = "user"
SubjectGuardBackend = "backend"
)
// FireSubjectEvent fires ev through the application's event bus at once, so
// the MCP endpoint re-lists the subject's tools or ends its sessions. A
// revoked event may carry TokenID (only the sessions one personal token
// opened end) or ClientID with UserID (only that OAuth client's sessions
// end). A missing application or bus, a zero UserID or an empty Kind is a
// no-op; a listener's error is logged and never returned, so the write that
// caused the event never fails because of it (every MCP request re-checks
// anyway).
func FireSubjectEvent(ctx context.Context, app *backpack.App, ev pact.MCPSubjectChanged) {
if app == nil || app.Events == nil || ev.UserID == 0 || ev.Kind == "" {
return
}
if ctx == nil {
ctx = context.Background()
}
event := ev
if err := app.Events.Fire(ctx, &event); err != nil {
pluginLog.WarnContext(ctx, "golem15.user: subject changed listener failed", "guard", ev.Guard, "user_id", ev.UserID, "kind", ev.Kind, "token_id", ev.TokenID, "client_id", ev.ClientID, "err", err)
}
}
// FireSubjectEventAfterCommit is FireSubjectEvent once the write
// transaction tx commits (lagoon.AfterCommit), so a listener that reads the
// database sees the change; nothing is fired when the transaction rolls
// back. A nil tx fires at once. ctx must be the context the transaction
// runs under (the one cabana hands a hook or an action).
func FireSubjectEventAfterCommit(ctx context.Context, app *backpack.App, tx *gorm.DB, ev pact.MCPSubjectChanged) {
if app == nil || app.Events == nil || ev.UserID == 0 || ev.Kind == "" {
return
}
if tx == nil {
FireSubjectEvent(ctx, app, ev)
return
}
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
FireSubjectEvent(ctx, app, ev)
})
}
// FireSubjectChanged fires one *pact.MCPSubjectChanged (guard, user id,
// kind) at once: FireSubjectEvent for the whole subject.
func FireSubjectChanged(ctx context.Context, app *backpack.App, guard string, userID uint, kind string) {
FireSubjectEvent(ctx, app, pact.MCPSubjectChanged{Guard: guard, UserID: userID, Kind: kind})
}
// FireSubjectChangedAfterCommit is FireSubjectChanged once the write
// transaction tx commits: FireSubjectEventAfterCommit for the whole subject.
func FireSubjectChangedAfterCommit(ctx context.Context, app *backpack.App, tx *gorm.DB, guard string, userID uint, kind string) {
FireSubjectEventAfterCommit(ctx, app, tx, pact.MCPSubjectChanged{Guard: guard, UserID: userID, Kind: kind})
}

View File

@@ -0,0 +1,38 @@
package classes
import (
"context"
"git.golem15.com/golem15/sm-user-plugin/models"
"gorm.io/gorm"
)
// PermissionResetTwoFactor is the backend permission an administrator needs
// to run the Users screen's "Reset 2FA" record action (reset_two_factor). No
// role has it by default: only a superuser, or a role granted it
// explicitly, may remove a user's second factors.
const PermissionResetTwoFactor = "golem15.users.reset_two_factor"
// TwoFactorAdmin is what a two-factor plugin publishes so the Users screen
// can offer its "Reset 2FA" record action. The screen looks it up on every
// request: without a published service the action is never offered, so an
// application that mounts no two-factor plugin never shows it.
//
// Publish it with an explicit type argument,
//
// app.Publish[classes.TwoFactorAdmin](svc)
//
// because a bare app.Publish(svc) keys the service on its concrete type and
// the lookup misses it.
type TwoFactorAdmin interface {
// HasTwoFactor reports whether the user has any second factor (an
// enabled method, a WebAuthn credential, recovery codes or a trusted
// device) to reset. It only reads, through tx.
HasTwoFactor(ctx context.Context, tx *gorm.DB, userID uint) (bool, error)
// Reset disables every second-factor method of user, deletes the
// WebAuthn credentials and recovery codes, revokes the trusted devices
// and fires the plugin's disabled event, all on tx (the record action's
// transaction): an error rolls the reset back. The user then signs in
// with the password alone until they set up a second factor again.
Reset(ctx context.Context, tx *gorm.DB, user *models.User) error
}

View File

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

View File

@@ -4,12 +4,26 @@ jwt:
refresh_ttl: 20160 refresh_ttl: 20160
blacklist_grace: 0 blacklist_grace: 0
leeway: 0 leeway: 0
# 0 schedules no sweep; any other value must divide 24h (1m, 10m, 1h).
blacklist_sweep_interval: 10m blacklist_sweep_interval: 10m
# On: POST /login, /register (when it signs the account in) and
# /activate-by-code set the HttpOnly session cookie from auth.cookie.* and
# leave token out of the body. A POST /refresh carried by that cookie
# rewrites it either way. Keep auth.cookie.name token or auth_token.
token_cookie: false
activation: activation:
require_activation: true require_activation: true
activate_mode: auto activate_mode: auto
reset_ttl_minutes: 60 reset_ttl_minutes: 60
activation_ttl_hours: 72 activation_ttl_hours: 72
mail:
# The language of this plugin's mails when neither the user's
# preferred_locale nor the request locale (the translate plugin's locale,
# else the Accept-Language header) names one the plugin has mail for (pl or
# en). pl keeps the unsuffixed Polish templates; an English-only site sets
# en (SUMMER_GOLEM15__USER__MAIL__FALLBACK_LOCALE=en). Any other value
# fails boot.
fallback_locale: pl
registration: registration:
allow_registration: true allow_registration: true
use_register_throttle: true use_register_throttle: true
@@ -20,5 +34,38 @@ throttle:
password: password:
bcrypt_cost: 10 bcrypt_cost: 10
min_length: 8 min_length: 8
# false leaves POST /login, /forgot-password and /reset-password
# unregistered, so they 404 like any unknown path; /register and the other
# routes stay. Read at boot (a change needs a restart). Takes true or false.
public_routes: true
api_tokens: api_tokens:
prefix: usr_ prefix: usr_
privileged_groups:
- admin
# Cloudflare Turnstile on POST /login and /register. Empty (the default) adds
# nothing. "open" lets requests pass when Cloudflare is unreachable, "closed"
# refuses them. The turnstile:* middleware comes from the framework (summercms
# v0.3.0 and later); its secret is turnstile.secret (SUMMER_TURNSTILE__SECRET).
turnstile: ""
# The site this plugin's links point to (the account link page,
# <frontend_url><backend_links.page_path>#code=..., and the device
# authorization page of device_auth.auth_url). Empty falls back to app.url.
frontend_url: ""
device_auth:
# The page a new device shows as its QR code, where a signed-in user
# authorizes it. {frontend_url} is frontend_url (else app.url, no trailing
# slash), {short_code} the session's short code and {token} the device
# token. Keep {token} out of it: the device token is also the secret the
# device collects its session token with, and whoever sees the QR code or
# the page's URL could take the session.
auth_url: "{frontend_url}/device/scan/{short_code}"
# Minutes a device session can be authorized and handed over.
ttl_minutes: 5
backend_links:
# How long a link request an administrator starts on My account stays
# usable (a Go duration). The code is one-shot.
request_ttl: 10m
# The site page that confirms a link. My account sends the administrator
# to <frontend_url><page_path>#code=<code>; the code is in the fragment,
# which browsers never send to a server.
page_path: /link-admin

View File

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

View File

@@ -0,0 +1,71 @@
package console
import (
"context"
"fmt"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/golem15/summercms/modules/lagoon"
"gorm.io/gorm"
)
// BackfillHandles fills a unique handle on every user row that still has none.
// It uses the database the serve command published or, when it runs as a
// console command, opens one from the config for the duration of the run,
// as the plugin's other commands do.
func BackfillHandles(app *backpack.App) bonfire.Command {
return bonfire.Command{
Name: "user:backfill-handles",
Description: "Assign unique handles to users that do not have one",
Long: `Gives every user without a handle a unique one, derived the same way as
for a new registration, with a progress bar over the users (hidden under
-q). Users that already have a handle are not touched, so running it again
changes nothing.
Run it once after copying users from WinterCMS, which had no handles. It
ends with "Assigned handles to N user(s)".`,
Examples: []bonfire.Example{
{Command: "user:backfill-handles", Description: "Assign a handle to every user that has none"},
{Command: "user:backfill-handles -q", Description: "Run it quietly, printing only the result line"},
},
Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error {
if app == nil {
return fmt.Errorf("user:backfill-handles: app is nil")
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok || gdb == nil {
sqlDB, opened, err := lagoon.OpenFromApp(ctx, app)
if err != nil {
return fmt.Errorf("user:backfill-handles: %w", err)
}
defer sqlDB.Close()
gdb = opened
}
var users []models.User
if err := gdb.WithContext(ctx).Where("handle IS NULL OR handle = ''").Find(&users).Error; err != nil {
return err
}
n := 0
if len(users) > 0 {
err := out.Progress(len(users), func(p bonfire.Progress) error {
for i := range users {
if err := classes.AssignHandle(ctx, gdb, &users[i]); err != nil {
return err
}
n++
p.Advance(1)
}
return nil
})
if err != nil {
return err
}
}
out.Success(fmt.Sprintf("Assigned handles to %d user(s)", n))
return nil
},
}
}

View File

@@ -0,0 +1,55 @@
package console
import (
"context"
"fmt"
"time"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/lagoon"
)
// JWTBlacklistSweep deletes the expired rows of the JWT blacklist. It uses
// the blacklist store the plugin published or, when it runs as a console
// command without a published database, a store over a database opened from
// the config for the duration of the run.
func JWTBlacklistSweep(app *backpack.App) bonfire.Command {
return bonfire.Command{
Name: "user:jwt-blacklist-sweep",
Description: "Delete the expired JWT blacklist rows",
Long: `Deletes the jwt_blacklist rows whose expires_at has passed. A row that
still blocks a token or its refresh is not touched, so running it twice
changes nothing.
The scheduler runs it every golem15.user.jwt.blacklist_sweep_interval on
the job worker's scheduled queue. Run it by hand or from cron when no
worker runs that queue. It ends with "Deleted the expired JWT blacklist
rows."`,
Examples: []bonfire.Example{
{Command: "user:jwt-blacklist-sweep", Description: "Delete the expired JWT blacklist rows"},
{Command: "user:jwt-blacklist-sweep -q", Description: "Run it quietly, printing only the result line"},
},
Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error {
if app == nil {
return fmt.Errorf("user:jwt-blacklist-sweep: app is nil")
}
store, ok := app.Lookup[bouncer.BlacklistStore]()
if !ok || store == nil {
sqlDB, _, err := lagoon.OpenFromApp(ctx, app)
if err != nil {
return fmt.Errorf("user:jwt-blacklist-sweep: %w", err)
}
defer sqlDB.Close()
store = bouncer.NewPostgresBlacklist(sqlDB, classes.JWTBlacklistTable)
}
if err := store.Sweep(ctx, time.Now()); err != nil {
return fmt.Errorf("user:jwt-blacklist-sweep: %w", err)
}
out.Success("Deleted the expired JWT blacklist rows.")
return nil
},
}
}

View File

@@ -7,16 +7,22 @@ import (
"git.golem15.com/golem15/sm-user-plugin/classes" "git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models" "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bonfire" "git.golem15.com/golem15/summercms/modules/bonfire"
"gorm.io/gorm" "gorm.io/gorm"
) )
// RequirePasswordChange forces the named account to set a new password on next login. // RequirePasswordChange forces the named account to set a new password on next login.
func RequirePasswordChange(app *backpack.App) bonfire.Command { func RequirePasswordChange(withDB func(context.Context, func(*gorm.DB) error) error) bonfire.Command {
return bonfire.Command{ return bonfire.Command{
Name: "user:require-password-change", Name: "user:require-password-change",
Description: "Force a user to change their password on next login (D-21)", Description: "Force a user to change their password on next login",
Long: `Marks the account with this e-mail so that it must set a new password at its
next sign-in; setting the password clears the mark. Use it after a suspected
leak or when handing over an account created with a temporary password. It
ends with "Password change required for <email>".`,
Examples: []bonfire.Example{
{Command: "user:require-password-change jane@example.com", Description: "Make Jane set a new password at her next sign-in"},
},
Args: []bonfire.Arg{{ Args: []bonfire.Arg{{
Name: "email", Name: "email",
Description: "Account email", Description: "Account email",
@@ -28,29 +34,27 @@ func RequirePasswordChange(app *backpack.App) bonfire.Command {
if !ok || email == "" { if !ok || email == "" {
return fmt.Errorf("email is required") return fmt.Errorf("email is required")
} }
if app == nil { if withDB == nil {
return fmt.Errorf("user:require-password-change: app is nil")
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok || gdb == nil {
return fmt.Errorf("user:require-password-change: database is not configured") return fmt.Errorf("user:require-password-change: database is not configured")
} }
user, err := classes.LookupByEmail(ctx, gdb, email) return withDB(ctx, func(gdb *gorm.DB) error {
if err != nil { user, err := classes.LookupByEmail(ctx, gdb, email)
return err if err != nil {
} return err
if user == nil { }
return fmt.Errorf("user %s not found", email) if user == nil {
} return fmt.Errorf("user %s not found", email)
res := gdb.WithContext(ctx).Model(&models.User{}).Where("id = ?", user.ID).Update("must_change_password", true) }
if res.Error != nil { res := gdb.WithContext(ctx).Model(&models.User{}).Where("id = ?", user.ID).Update("must_change_password", true)
return res.Error if res.Error != nil {
} return res.Error
if res.RowsAffected != 1 { }
return fmt.Errorf("user %s was not updated", email) if res.RowsAffected != 1 {
} return fmt.Errorf("user %s was not updated", email)
out.Success("Password change required for " + user.Email) }
return nil out.Success("Password change required for " + user.Email)
return nil
})
}, },
} }
} }

View File

@@ -3,12 +3,15 @@ package user
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/base64"
"strings" "strings"
"testing" "testing"
"git.golem15.com/golem15/sm-user-plugin/models" "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bonfire" "git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/pact"
"gorm.io/gorm"
) )
func TestRequirePasswordChange(t *testing.T) { func TestRequirePasswordChange(t *testing.T) {
@@ -16,17 +19,7 @@ func TestRequirePasswordChange(t *testing.T) {
user := insertUser(t, gdb, "alice@example.com", "correct-horse") user := insertUser(t, gdb, "alice@example.com", "correct-horse")
p := &Plugin{app: app} p := &Plugin{app: app}
var _ pact.HasCommands = p var _ pact.HasCommands = p
cmds := p.Commands() cmd := commandNamed(t, p.Commands(), "user:require-password-change")
var cmd bonfire.Command
for _, candidate := range cmds {
if candidate.Name == "user:require-password-change" {
cmd = candidate
break
}
}
if cmd.Name == "" {
t.Fatalf("commands = %#v", cmds)
}
var buf bytes.Buffer var buf bytes.Buffer
out := bonfire.NewOutput(nil, &buf, &buf) out := bonfire.NewOutput(nil, &buf, &buf)
if err := cmd.Run(context.Background(), emailArg{email: "alice@example.com"}, out); err != nil { if err := cmd.Run(context.Background(), emailArg{email: "alice@example.com"}, out); err != nil {
@@ -47,6 +40,89 @@ func TestRequirePasswordChange(t *testing.T) {
} }
} }
func TestAPITokenCreateCommand(t *testing.T) {
app, gdb := sessionApp(t, "0s")
user := insertUser(t, gdb, "pat@example.com", "correct-horse")
cmd := commandNamed(t, (&Plugin{app: app}).Commands(), "user:token:create")
var buf bytes.Buffer
out := bonfire.NewOutput(nil, &buf, &buf)
if err := cmd.Run(context.Background(), tokenCreateArg{email: user.Email, name: "rome scripts", scopes: "read,write"}, out); err != nil {
t.Fatal(err)
}
if !strings.Contains(buf.String(), "usr_") {
t.Fatalf("secret missing from output %q", buf.String())
}
var n int64
if err := gdb.Model(&models.APIToken{}).Where("user_id = ? AND revoked_at IS NULL", user.ID).Count(&n).Error; err != nil {
t.Fatal(err)
}
if n != 1 {
t.Fatalf("tokens = %d", n)
}
}
func TestConsoleWithDBOpensFromConfigWhenUnpublished(t *testing.T) {
p := &Plugin{app: backpack.New(sessionConfig(t))}
err := p.withDB(context.Background(), func(*gorm.DB) error {
t.Fatal("fn should not run without a DSN")
return nil
})
if err == nil {
t.Fatal("expected OpenFromApp to fail")
}
if strings.Contains(err.Error(), "database is not configured") {
t.Fatalf("still the Lookup-only error: %v", err)
}
if !strings.Contains(err.Error(), "database.dsn is empty") {
t.Fatalf("got %v", err)
}
}
// TestBackfillHandlesOpensFromConfigWhenUnpublished runs user:backfill-handles
// as the console does: no published database, only database.dsn in the config.
func TestBackfillHandlesOpensFromConfigWhenUnpublished(t *testing.T) {
_, gdb := sessionApp(t, "0s")
user := insertUser(t, gdb, "backfill-unpublished@example.test", "correct-horse")
if err := gdb.Model(user).Update("handle", nil).Error; err != nil {
t.Fatal(err)
}
app := backpack.New(sessionConfig(t))
if err := app.Config.Set("database.dsn", sessionDSN); err != nil {
t.Fatal(err)
}
// Opening a database also loads the encryption keys from app.key.
if err := app.Config.Set("app.key", base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef"))); err != nil {
t.Fatal(err)
}
if _, ok := app.Lookup[*gorm.DB](); ok {
t.Fatal("setup: a database is published")
}
cmd := commandNamed(t, (&Plugin{app: app}).Commands(), "user:backfill-handles")
var buf bytes.Buffer
out := bonfire.NewOutput(nil, &buf, &buf)
if err := cmd.Run(context.Background(), emailArg{}, out); err != nil {
t.Fatalf("run: %v (output %q)", err, buf.String())
}
var fresh models.User
if err := gdb.First(&fresh, user.ID).Error; err != nil {
t.Fatal(err)
}
if fresh.Handle == nil || *fresh.Handle == "" {
t.Fatal("the user still has no handle")
}
}
func commandNamed(t *testing.T, cmds []bonfire.Command, name string) bonfire.Command {
t.Helper()
for _, candidate := range cmds {
if candidate.Name == name {
return candidate
}
}
t.Fatalf("commands = %#v", cmds)
return bonfire.Command{}
}
type emailArg struct{ email string } type emailArg struct{ email string }
func (e emailArg) Args() []string { return []string{e.email} } func (e emailArg) Args() []string { return []string{e.email} }
@@ -61,3 +137,27 @@ func (e emailArg) Argument(name string) (string, bool) {
func (e emailArg) Flag(string) (string, bool) { return "", false } func (e emailArg) Flag(string) (string, bool) { return "", false }
func (e emailArg) Flags(string) []string { return nil } func (e emailArg) Flags(string) []string { return nil }
type tokenCreateArg struct{ email, name, scopes string }
func (a tokenCreateArg) Args() []string { return []string{a.email} }
func (a tokenCreateArg) Argument(name string) (string, bool) {
if name == "email" {
return a.email, true
}
return "", false
}
func (a tokenCreateArg) Flag(name string) (string, bool) {
switch name {
case "name":
return a.name, true
case "scopes":
return a.scopes, true
default:
return "", false
}
}
func (a tokenCreateArg) Flags(string) []string { return nil }

View File

@@ -0,0 +1,60 @@
package controllers
import (
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/pact"
)
// AdminControllers is the plugin's admin controller list. app returns the
// booted application; it is asked on every call, so a controller never keeps
// a database handle, a config or a mailer of its own.
func AdminControllers(app func() *backpack.App) []pact.AdminController {
return []pact.AdminController{
usersAdminController{app: app},
usergroupsAdminController{app: appAccess(app)},
organisationsAdminController{app: appAccess(app)},
}
}
func init() {
var _ pact.AdminController = usersAdminController{}
var _ pact.AdminPermissioned = usersAdminController{}
var _ pact.AdminRecordSource = usersAdminController{}
var _ pact.ListExtendQuery = usersAdminController{}
var _ pact.FormExtendQuery = usersAdminController{}
var _ pact.ListRowStates = usersAdminController{}
var _ pact.FormRules = usersAdminController{}
var _ pact.FilterOptions = usersAdminController{}
var _ pact.FormBeforeUpdate = usersAdminController{}
var _ pact.FormBeforeDelete = usersAdminController{}
var _ pact.FormAfterDelete = usersAdminController{}
var _ pact.HasAdminBulkActions = usersAdminController{}
var _ pact.HasAdminRecordActions = usersAdminController{}
var _ pact.AdminPartialData = usersAdminController{}
var _ pact.FormVirtualFields = usersAdminController{}
var _ pact.FormBeforeCreate = usersAdminController{}
var _ pact.FormAfterCreate = usersAdminController{}
var _ cabana.FieldRelationProvider = usersAdminController{}
var _ cabana.RelationLockProvider = usersAdminController{}
var _ cabana.PermissionEditorProvider = usersAdminController{}
var _ pact.AdminController = usergroupsAdminController{}
var _ pact.AdminPermissioned = usergroupsAdminController{}
var _ pact.AdminRecordSource = usergroupsAdminController{}
var _ pact.ListExtendQuery = usergroupsAdminController{}
var _ pact.FormBeforeCreate = usergroupsAdminController{}
var _ pact.FormBeforeUpdate = usergroupsAdminController{}
var _ pact.FormBeforeDelete = usergroupsAdminController{}
var _ pact.FormAfterDelete = usergroupsAdminController{}
var _ cabana.PermissionEditorProvider = usergroupsAdminController{}
var _ pact.AdminController = organisationsAdminController{}
var _ pact.AdminPermissioned = organisationsAdminController{}
var _ pact.AdminRecordSource = organisationsAdminController{}
var _ pact.FormBeforeCreate = organisationsAdminController{}
var _ pact.FormBeforeUpdate = organisationsAdminController{}
var _ pact.FormBeforeDelete = organisationsAdminController{}
var _ pact.RelationExtendManageQuery = organisationsAdminController{}
var _ cabana.AdminRelationContractProvider = organisationsAdminController{}
}

View File

@@ -10,7 +10,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"log/slog"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@@ -30,6 +29,7 @@ import (
"git.golem15.com/golem15/summercms/modules/postcard" "git.golem15.com/golem15/summercms/modules/postcard"
"git.golem15.com/golem15/summercms/modules/surf" "git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/golem15/summercms/modules/wire" "git.golem15.com/golem15/summercms/modules/wire"
"github.com/golang-jwt/jwt/v5"
"gocloud.dev/blob" "gocloud.dev/blob"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -44,12 +44,36 @@ var errNoAvatar = errors.New("golem15.user: no avatar")
const invalidLoginBody = "Invalid email or password" const invalidLoginBody = "Invalid email or password"
// Login authenticates email and password and returns a JWT plus the user payload. // Login authenticates email and password and returns a JWT plus the user payload.
//
// It checks in this order: a ban or an active suspension
// (classes.RejectIfThrottled), the password (bcrypt), the activation, then
// records the successful attempt, consults the login gates
// (CheckLoginGates: a gate answer replaces the token response, a gate error
// answers the opaque 500), restores a deactivated (deleted_at) account and
// sends it the reactivate mail, mints the token and fires
// classes.LoginEvent. With
// golem15.user.activation.require_activation on (the default) the correct
// password of a not-activated account gets the same 401 invalid-login answer
// as a wrong password and counts as a failed attempt for the throttle; an
// account that is also deactivated is refused before the restore, so it
// stays deactivated and gets no mail. With the key off such an account signs
// in as before. Activation gates login, deactivation does not. The throttle
// counts failed attempts per user and client address, which is
// surf.ClientIP with http.trusted_proxies, as for /register. With
// golem15.user.jwt.token_cookie on, the token goes into the auth.cookie
// session cookie instead of the body.
func Login(app *backpack.App) http.HandlerFunc { func Login(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
gdb, secret, ok := sessionDeps(w, app) gdb, secret, ok := sessionDeps(w, app)
if !ok { if !ok {
return return
} }
cc, err := sessionCookie(app)
if err != nil {
pluginLog.Error("golem15.user: token cookie config", "err", err)
writeOpaque500(w)
return
}
fields, err := readFields(r) fields, err := readFields(r)
if err != nil { if err != nil {
writeOpaque500(w) writeOpaque500(w)
@@ -63,7 +87,7 @@ func Login(app *backpack.App) http.HandlerFunc {
writeOpaque500(w) writeOpaque500(w)
return return
} }
ip := remoteIP(r) ip := surf.ClientIP(r, surf.TrustedProxies(appConfig(app)))
if user != nil { if user != nil {
if err := classes.RejectIfThrottled(ctx, gdb, user, ip); err != nil { if err := classes.RejectIfThrottled(ctx, gdb, user, ip); err != nil {
if classes.IsLoginRejected(err) { if classes.IsLoginRejected(err) {
@@ -75,21 +99,15 @@ func Login(app *backpack.App) http.HandlerFunc {
} }
} }
if user == nil || !bouncer.CheckPassword(user.Password, password) { if user == nil || !bouncer.CheckPassword(user.Password, password) {
if user != nil { refuseLogin(ctx, w, r, app, gdb, user, ip)
if err := classes.CheckAndRecordLogin(ctx, gdb, user, ip, false); err != nil && !classes.IsLoginRejected(err) {
writeOpaque500(w)
return
}
}
writeInvalidLogin(w, r, app)
return return
} }
if user.DeletedAt.Valid { // The activation gate runs after the password check, so a wrong
if err := gdb.WithContext(ctx).Unscoped().Model(user).Update("deleted_at", nil).Error; err != nil { // password and a not-activated account cost the same and answer the
writeOpaque500(w) // same, and before the restore, so a refused account is not revived.
return if _, _, _, requireActivation := registrationSettings(app); requireActivation && !user.IsActivated {
} refuseLogin(ctx, w, r, app, gdb, user, ip)
sendTemplateVars(ctx, app, mailName(ctx, user, "golem15.user::mail.reactivate"), user.Email, mailVars(displayName(user), "", "")) return
} }
if err := classes.CheckAndRecordLogin(ctx, gdb, user, ip, true); err != nil { if err := classes.CheckAndRecordLogin(ctx, gdb, user, ip, true); err != nil {
if classes.IsLoginRejected(err) { if classes.IsLoginRejected(err) {
@@ -99,15 +117,55 @@ func Login(app *backpack.App) http.HandlerFunc {
writeOpaque500(w) writeOpaque500(w)
return return
} }
// The rehash runs before the login gates, so a user who is always
// challenged still gets the stronger hash. It is not a password
// change: it fires no AccessRevokedEvent (D-07). Unscoped, because a
// deactivated account is restored only after the gates.
cost := 10 cost := 10
if app.Config != nil && app.Config.Int("golem15.user.password.bcrypt_cost") > 0 { if app.Config != nil && app.Config.Int("golem15.user.password.bcrypt_cost") > 0 {
cost = app.Config.Int("golem15.user.password.bcrypt_cost") cost = app.Config.Int("golem15.user.password.bcrypt_cost")
} }
if bouncer.NeedsRehash(user.Password, cost) { if bouncer.NeedsRehash(user.Password, cost) {
if next, err := bouncer.HashPassword(cost, password); err == nil { if next, err := bouncer.HashPassword(cost, password); err == nil {
_ = gdb.WithContext(ctx).Model(user).Update("password", next).Error _ = gdb.WithContext(ctx).Unscoped().Model(user).Update("password", next).Error
} }
} }
// Login gates (D-02) run after the password, activation and throttle
// checks and before anything that signs the user in. A gate answer
// replaces the token response; a gate error fails closed. The
// restore of a deactivated account and its reactivate mail come
// after the gates (D-18 A10), so the password alone cannot reactivate
// an account that a second factor protects.
gate, err := CheckLoginGates(ctx, app, classes.LoginAttempt{
User: user,
Source: classes.LoginSourcePassword,
Fields: fields,
Request: r,
})
if err != nil {
pluginLog.Error("golem15.user: login gate", "user_id", user.ID, "err", err)
writeOpaque500(w)
return
}
if gate != nil {
status := gate.Status
if status == 0 {
status = http.StatusOK
}
writeJSON(w, status, gate.Body)
return
}
if user.DeletedAt.Valid {
if err := gdb.WithContext(ctx).Unscoped().Model(user).Update("deleted_at", nil).Error; err != nil {
writeOpaque500(w)
return
}
sendTemplateVars(ctx, app, mailName(ctx, app, user, "golem15.user::mail.reactivate"), user.Email, mailVars(displayName(user), "", ""))
}
// A failed last_seen write is logged and never fails the login.
if err := classes.TouchLastSeen(ctx, gdb, user.ID); err != nil {
pluginLog.Warn("golem15.user: stamp last_seen on login", "user_id", user.ID, "err", err)
}
token, err := mintFor(app, secret, user, requestURL(r)) token, err := mintFor(app, secret, user, requestURL(r))
if err != nil { if err != nil {
writeOpaque500(w) writeOpaque500(w)
@@ -118,21 +176,29 @@ func Login(app *backpack.App) http.HandlerFunc {
writeOpaque500(w) writeOpaque500(w)
return return
} }
writeJSON(w, http.StatusOK, map[string]any{"token": token, "user": payload}) if err := FireLoginEvent(ctx, app, user, classes.LoginSourcePassword); err != nil {
pluginLog.Warn("golem15.user: login event listener", "user_id", user.ID, "err", err)
}
writeSession(w, app, cc, token, map[string]any{"user": payload})
} }
} }
// Logout forever-blacklists the presented bearer token. // Logout ends the request's session through classes.EndSession: every
// session token it carries (the bearer header, or the token and auth_token
// cookies the jwt guard also reads) is blacklisted for the rest of its
// refresh window, so the next request with it is refused and /refresh
// cannot revive it, and the session cookies are expired, on a 401 too.
// It answers 200 {"message":"Logged out"} when the token the guard reads
// verifies (an expired one too while it can still be refreshed) and names a
// user, 401 otherwise, and 500 when the blacklist write fails.
func Logout(app *backpack.App) http.HandlerFunc { func Logout(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
_, secret, ok := sessionDeps(w, app) if _, _, ok := sessionDeps(w, app); !ok {
if !ok {
return return
} }
raw := bearerToken(r) sub, err := classes.EndSession(r.Context(), app, w, r)
sub, _, exp, jti, err := bouncer.VerifyClaims(raw, secret) if err != nil {
if err != nil || jti == "" { writeOpaque500(w)
writeUnauthorized(w)
return return
} }
id, err := strconv.ParseUint(sub, 10, 64) id, err := strconv.ParseUint(sub, 10, 64)
@@ -145,12 +211,6 @@ func Logout(app *backpack.App) http.HandlerFunc {
writeUnauthorized(w) writeUnauthorized(w)
return return
} }
if bl, ok := app.Lookup[bouncer.BlacklistStore](); ok && bl != nil {
if err := bl.Add(r.Context(), jti, exp, time.Now()); err != nil {
writeOpaque500(w)
return
}
}
writeJSON(w, http.StatusOK, map[string]any{"message": "Logged out"}) writeJSON(w, http.StatusOK, map[string]any{"message": "Logged out"})
} }
} }
@@ -171,18 +231,44 @@ func Fetch(app *backpack.App) http.HandlerFunc {
} }
} }
// Refresh slides a still-refreshable bearer token. // Refresh slides a still-refreshable session token of a user who may still
// sign in. The token is read as the plugin's jwt guard reads it: the bearer
// header, then the token and auth_token cookies. When it came from the cookie
// named auth.cookie.name with no bearer header, that cookie is rewritten with
// the rotated token (bouncer.LoadCookieConfig attributes, HttpOnly, Max-Age
// golem15.user.jwt.refresh_ttl) and the body is {}, whoever wrote the
// cookie. A bearer-carried or other-cookie refresh answers the rotated token
// in the body and writes no cookie; the old token is blacklisted after
// golem15.user.jwt.blacklist_grace, so that caller stores the new token
// itself. Refusals write and forget no cookie, and a broken auth.cookie
// block answers a cookie-carried refresh with the opaque 500 before anything
// is rotated. 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 { func Refresh(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
_, secret, ok := sessionDeps(w, app) gdb, secret, ok := sessionDeps(w, app)
if !ok { if !ok {
return return
} }
raw := bearerToken(r) raw := classes.SessionToken(r)
if raw == "" { if raw == "" {
writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Token not found"}) writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Token not found"})
return return
} }
// The auth.cookie block is read before bouncer.Refresh, so a broken
// block rotates and blacklists nothing; a bearer refresh never reads it.
var rotate *bouncer.CookieConfig
if name := classes.SessionTokenCookie(r); name != "" {
cc, err := tokenCookieConfig(app)
if err != nil {
pluginLog.Error("golem15.user: refresh: auth.cookie config", "err", err)
writeOpaque500(w)
return
}
if cc.Name == name {
rotate = &cc
}
}
var bl bouncer.BlacklistStore var bl bouncer.BlacklistStore
if store, ok := app.Lookup[bouncer.BlacklistStore](); ok { if store, ok := app.Lookup[bouncer.BlacklistStore](); ok {
bl = store bl = store
@@ -195,20 +281,163 @@ func Refresh(app *backpack.App) http.HandlerFunc {
}) })
return return
} }
writeJSON(w, http.StatusOK, map[string]any{"token": next}) // 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 device session follows its token through refresh (D-12b), so a
// revoke blacklists the token the device holds now. Reading the old
// jti unverified is safe: bouncer.Refresh has just verified it. The
// hand-over and the revoke take the session's row lock, so whichever
// runs second sees the other: a device revoked after bouncer.Refresh
// checked the blacklist is refused here with the blacklisted-token
// answer and the new token is never sent. The hand-over fails
// closed: a database error answers the opaque 500 (the presented
// token is already rotated out), never a token the device row does
// not follow. With golem15.user.jwt.blacklist_grace above 0 two
// concurrent refreshes of one token can fork a device's lineage and
// only one fork is followed; a password change still ends both
// (tokens_valid_after). Log lines carry no token or jti.
if oldJTI := unverifiedJTI(raw); oldJTI != "" {
_, _, _, newJTI, err := bouncer.VerifyClaims(next, secret)
if err != nil {
pluginLog.Error("golem15.user: read the refreshed token", "user_id", userID, "err", err)
writeOpaque500(w)
return
}
revoked, err := classes.FollowDeviceJTI(r.Context(), gdb, oldJTI, newJTI)
if err != nil {
pluginLog.Error("golem15.user: hand a device session over on refresh", "user_id", userID, "err", err)
writeOpaque500(w)
return
}
if revoked {
writeJSON(w, http.StatusUnauthorized, map[string]any{
"error": "Could not refresh token",
"msg": refreshBlacklistedMsg,
})
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)
}
writeSession(w, app, rotate, next, map[string]any{})
} }
} }
// OAuthProviders reports that this app configures no social providers. // refreshBlacklistedMsg is bouncer.Refresh's message for a blacklisted
// token, which POST /refresh also answers for a revoked device session.
const refreshBlacklistedMsg = "The token has been blacklisted"
// unverifiedJTI returns the jti claim of a token without verifying it, ""
// when there is none. Only call it on a token that was verified already.
func unverifiedJTI(raw string) string {
claims := jwt.MapClaims{}
if _, _, err := jwt.NewParser().ParseUnverified(raw, claims); err != nil {
return ""
}
jti, _ := claims["jti"].(string)
return jti
}
// 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
// because it boots after this plugin; without one the list is empty.
func OAuthProviders(app *backpack.App) http.HandlerFunc { func OAuthProviders(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
providers := []any{}
if src, ok := oauthProviderSource(app); ok {
for _, p := range src.EnabledOAuthProviders(r.Context()) {
providers = append(providers, map[string]any{"name": p.Name, "label": p.Label})
}
}
writeJSON(w, http.StatusOK, map[string]any{ writeJSON(w, http.StatusOK, map[string]any{
"success": true, "success": true,
"providers": wire.Slice([]any{}), "providers": wire.Slice(providers),
}) })
} }
} }
// oauthProviderSource returns the social-login plugin's published provider
// source, if any.
func oauthProviderSource(app *backpack.App) (classes.OAuthProviderSource, bool) {
if app == nil {
return nil, false
}
src, ok := app.Lookup[classes.OAuthProviderSource]()
return src, ok && src != nil
}
const forgotPasswordBody = "If that email exists, a reset link has been sent." const forgotPasswordBody = "If that email exists, a reset link has been sent."
// ForgotPassword always returns the same 200 body. A real account also gets a reset mail. // ForgotPassword always returns the same 200 body. A real account also gets a reset mail.
@@ -237,17 +466,17 @@ func ForgotPassword(app *backpack.App) http.HandlerFunc {
ctx := codeContext(r.Context(), app) ctx := codeContext(r.Context(), app)
user, err := classes.LookupByEmail(ctx, gdb, strField(fields, "email")) user, err := classes.LookupByEmail(ctx, gdb, strField(fields, "email"))
if err != nil { if err != nil {
slog.Default().Error("golem15.user: forgot-password lookup", "err", err) pluginLog.Error("golem15.user: forgot-password lookup", "err", err)
writeJSON(w, http.StatusOK, map[string]any{"message": forgotPasswordBody}) writeJSON(w, http.StatusOK, map[string]any{"message": forgotPasswordBody})
return return
} }
if user != nil { if user != nil {
code, err := classes.IssueResetCode(ctx, gdb, user) code, err := classes.IssueResetCode(ctx, gdb, user)
if err != nil { if err != nil {
slog.Default().Error("golem15.user: issue reset code", "err", err) pluginLog.Error("golem15.user: issue reset code", "err", err)
} else { } else {
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
sendTemplateVars(ctx, app, mailName(ctx, user, "golem15.user::mail.restore"), user.Email, mailVars(displayName(user), resetLink(app, user.ID, code), packed)) sendTemplateVars(ctx, app, mailName(ctx, app, user, "golem15.user::mail.restore"), user.Email, mailVars(displayName(user), resetLink(app, user.ID, code), packed))
} }
} }
writeJSON(w, http.StatusOK, map[string]any{"message": forgotPasswordBody}) writeJSON(w, http.StatusOK, map[string]any{"message": forgotPasswordBody})
@@ -297,11 +526,26 @@ func ResetPassword(app *backpack.App) http.HandlerFunc {
writeOpaque500(w) writeOpaque500(w)
return return
} }
// The reset code was mailed to the account's address, so the write
// that stores the new password also records the proof of that
// address (D-27). A reset that fails here records nothing. The
// session cutoff is truncated to whole seconds, as in
// RevokeUserAccess, because JWT iat has whole-second precision, so
// the login that follows the reset is not refused. The same
// transaction fires the access-revoked event with the untruncated
// instant, so OAuth grants created before the reset are revoked
// with the password change or not at all.
now := time.Now() now := time.Now()
if err := gdb.WithContext(r.Context()).Model(&models.User{}).Where("id = ?", user.ID).Updates(map[string]any{ if err := lagoon.Transaction(r.Context(), gdb, func(ctx context.Context, tx *gorm.DB) error {
"password": hashed, if err := tx.WithContext(ctx).Model(&models.User{}).Where("id = ?", user.ID).Updates(map[string]any{
"tokens_valid_after": now, "password": hashed,
}).Error; err != nil { "tokens_valid_after": now.Truncate(time.Second),
"email_verified_at": now,
}).Error; err != nil {
return err
}
return classes.FireAccessRevoked(ctx, app, tx, []uint{user.ID}, now, classes.AccessRevokedPasswordReset)
}); err != nil {
writeOpaque500(w) writeOpaque500(w)
return return
} }
@@ -344,13 +588,28 @@ func Activate(app *backpack.App) http.HandlerFunc {
} }
} }
// ActivateByCode activates from a public "{id}!{code}" value and mints a token. // ActivateByCode activates from a public "{id}!{code}" value, consults the
// login gates and mints a token. The gates run as on password Login, with
// source password, because the mailed code is the first factor here: with
// golem15.user.activation.require_activation off an account can enable a
// second factor before it activates, and the code must not stand in for it.
// A gate answer replaces the token response with its status and body and a
// gate error answers the opaque 500; neither mints a token or sets a
// session cookie, and the account stays activated either way. With
// golem15.user.jwt.token_cookie on, the token goes into the auth.cookie
// session cookie instead of the body.
func ActivateByCode(app *backpack.App) http.HandlerFunc { func ActivateByCode(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
gdb, secret, ok := sessionDeps(w, app) gdb, secret, ok := sessionDeps(w, app)
if !ok { if !ok {
return return
} }
cc, err := sessionCookie(app)
if err != nil {
pluginLog.Error("golem15.user: token cookie config", "err", err)
writeOpaque500(w)
return
}
fields, err := readFields(r) fields, err := readFields(r)
if err != nil { if err != nil {
writeOpaque500(w) writeOpaque500(w)
@@ -386,6 +645,28 @@ func ActivateByCode(app *backpack.App) http.HandlerFunc {
writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"error": "This activation link is invalid or has expired"}) writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"error": "This activation link is invalid or has expired"})
return return
} }
// The activation above is committed whatever the gates answer. A
// gate answer replaces the token response; a gate error fails
// closed.
gate, err := CheckLoginGates(r.Context(), app, classes.LoginAttempt{
User: user,
Source: classes.LoginSourcePassword,
Fields: fields,
Request: r,
})
if err != nil {
pluginLog.Error("golem15.user: login gate", "user_id", user.ID, "err", err)
writeOpaque500(w)
return
}
if gate != nil {
status := gate.Status
if status == 0 {
status = http.StatusOK
}
writeJSON(w, status, gate.Body)
return
}
token, err := mintFor(app, secret, user, requestURL(r)) token, err := mintFor(app, secret, user, requestURL(r))
if err != nil { if err != nil {
writeOpaque500(w) writeOpaque500(w)
@@ -396,11 +677,7 @@ func ActivateByCode(app *backpack.App) http.HandlerFunc {
writeOpaque500(w) writeOpaque500(w)
return return
} }
writeJSON(w, http.StatusOK, map[string]any{ writeSession(w, app, cc, token, map[string]any{"message": "Account activated", "user": payload})
"message": "Account activated",
"token": token,
"user": payload,
})
} }
} }
@@ -435,17 +712,29 @@ func Update(app *backpack.App) http.HandlerFunc {
} }
name := strField(fields, "name") name := strField(fields, "name")
surname := strField(fields, "surname") surname := strField(fields, "surname")
if err := gdb.WithContext(r.Context()).Model(user).Updates(map[string]any{ email := strField(fields, "email")
columns := map[string]any{
"name": name, "name": name,
"surname": surname, "surname": surname,
"email": strField(fields, "email"), "email": email,
}).Error; err != nil { }
// The proof of the address follows the address (D-27): a new email
// is unproven until its owner proves it. A change of letter case
// only keeps it, because email matching is case-insensitive.
emailChanged := !strings.EqualFold(email, user.Email)
if emailChanged {
columns["email_verified_at"] = nil
}
if err := gdb.WithContext(r.Context()).Model(user).Updates(columns).Error; err != nil {
writeOpaque500(w) writeOpaque500(w)
return return
} }
user.Name = &name user.Name = &name
user.Surname = &surname user.Surname = &surname
user.Email = strField(fields, "email") user.Email = email
if emailChanged {
user.EmailVerifiedAt = nil
}
payload, err := apiArray(r.Context(), app, user) payload, err := apiArray(r.Context(), app, user)
if err != nil { if err != nil {
writeOpaque500(w) writeOpaque500(w)
@@ -456,24 +745,29 @@ func Update(app *backpack.App) http.HandlerFunc {
} }
// ChangePassword replaces a self-set password and invalidates older tokens. // ChangePassword replaces a self-set password and invalidates older tokens.
// The token that made this call stays valid. // The token is read as the plugin's jwt guard reads it (the bearer header,
// then the token and auth_token cookies), and the token that made this call,
// header or cookie, stays valid.
func ChangePassword(app *backpack.App) http.HandlerFunc { func ChangePassword(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
gdb, secret, ok := sessionDeps(w, app) gdb, secret, ok := sessionDeps(w, app)
if !ok { if !ok {
return return
} }
raw := bearerToken(r) raw := classes.SessionToken(r)
sub, iat, _, _, err := bouncer.VerifyClaims(raw, secret) sub, iat, _, _, err := bouncer.VerifyClaims(raw, secret)
if err != nil { if err != nil {
writeUnauthorized(w) writeUnauthorized(w)
return return
} }
var bl bouncer.BlacklistStore principal, err := sessionGuard(app, secret).Authenticate(r)
if store, ok := app.Lookup[bouncer.BlacklistStore](); ok { if err != nil || principal == nil {
bl = store writeUnauthorized(w)
return
} }
if _, err := bouncer.NewJWTGuard(secret, classes.GormUsers{App: app}, bl).Authenticate(r); err != nil { // The guard and SessionToken read the same token; a differing
// subject fails closed.
if strconv.FormatUint(uint64(principal.ID), 10) != sub {
writeUnauthorized(w) writeUnauthorized(w)
return return
} }
@@ -488,7 +782,7 @@ func ChangePassword(app *backpack.App) http.HandlerFunc {
return return
} }
if !user.HasSelfSetPassword { if !user.HasSelfSetPassword {
slog.Default().Error("golem15.user: change-password requires a self-set password", "user_id", user.ID) pluginLog.Error("golem15.user: change-password requires a self-set password", "user_id", user.ID)
writeOpaque500(w) writeOpaque500(w)
return return
} }
@@ -534,13 +828,24 @@ func ChangePassword(app *backpack.App) http.HandlerFunc {
writeOpaque500(w) writeOpaque500(w)
return return
} }
// The cutoff keeps the current session (issued at iat) and every
// session token issued since that second. OAuth grants are revoked
// as of now, whatever their age: the request needs none, and a
// grant its client refreshed after iat would otherwise survive the
// change (its rotated tokens are newer than the session).
cutoff := iat.Add(-time.Second) cutoff := iat.Add(-time.Second)
if err := gdb.WithContext(r.Context()).Model(&user).Updates(map[string]any{ revokedAt := time.Now()
"password": hashed, if err := lagoon.Transaction(r.Context(), gdb, func(ctx context.Context, tx *gorm.DB) error {
"must_change_password": false, if err := tx.WithContext(ctx).Model(&user).Updates(map[string]any{
"has_self_set_password": true, "password": hashed,
"tokens_valid_after": cutoff, "must_change_password": false,
}).Error; err != nil { "has_self_set_password": true,
"tokens_valid_after": cutoff,
}).Error; err != nil {
return err
}
return classes.FireAccessRevoked(ctx, app, tx, []uint{user.ID}, revokedAt, classes.AccessRevokedPasswordChanged)
}); err != nil {
writeOpaque500(w) writeOpaque500(w)
return return
} }
@@ -599,12 +904,20 @@ func MarketingConsent(app *backpack.App) http.HandlerFunc {
} }
// Register creates an account and follows activate_mode: auto, user, or admin. // Register creates an account and follows activate_mode: auto, user, or admin.
// With golem15.user.jwt.token_cookie on, the token of an account it signs in
// goes into the auth.cookie session cookie instead of the body.
func Register(app *backpack.App) http.HandlerFunc { func Register(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
gdb, _, ok := sessionDeps(w, app) gdb, _, ok := sessionDeps(w, app)
if !ok { if !ok {
return return
} }
cc, err := sessionCookie(app)
if err != nil {
pluginLog.Error("golem15.user: token cookie config", "err", err)
writeOpaque500(w)
return
}
allow, throttle, mode, require := registrationSettings(app) allow, throttle, mode, require := registrationSettings(app)
ip := surf.ClientIP(r, surf.TrustedProxies(appConfig(app))) ip := surf.ClientIP(r, surf.TrustedProxies(appConfig(app)))
if !allow { if !allow {
@@ -635,18 +948,25 @@ func Register(app *backpack.App) http.HandlerFunc {
}) })
return return
} }
_ = FireRegisterEvent(r.Context(), app, user, fields) // 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() ctx := r.Context()
if mode == "user" { if mode == "user" {
vars := mailVars(displayName(user), "", "") vars := mailVars(displayName(user), "", "")
code, err := classes.IssueActivationCode(ctx, gdb, user) code, err := classes.IssueActivationCode(ctx, gdb, user)
if err != nil { if err != nil {
slog.Default().Error("golem15.user: issue activation code", "err", err) pluginLog.Error("golem15.user: issue activation code", "err", err)
} else { } else {
packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code packed := strconv.FormatUint(uint64(user.ID), 10) + "!" + code
vars = mailVars(displayName(user), activationLink(app, user.ID, code), packed) vars = mailVars(displayName(user), activationLink(app, user.ID, code), packed)
} }
sendTemplateVars(ctx, app, mailName(ctx, user, "golem15.user::mail.activate"), user.Email, vars) sendTemplateVars(ctx, app, mailName(ctx, app, user, "golem15.user::mail.activate"), user.Email, vars)
writeJSON(w, http.StatusOK, map[string]any{"message": "Activation email sent"}) writeJSON(w, http.StatusOK, map[string]any{"message": "Activation email sent"})
return return
} }
@@ -661,13 +981,30 @@ func Register(app *backpack.App) http.HandlerFunc {
writeOpaque500(w) writeOpaque500(w)
return return
} }
writeJSON(w, http.StatusOK, map[string]any{"token": token, "user": payload}) writeSession(w, app, cc, token, map[string]any{"user": payload})
return return
} }
writeJSON(w, http.StatusOK, map[string]any{}) writeJSON(w, http.StatusOK, map[string]any{})
} }
} }
// RegistrationSettings returns the registration settings /register
// applies: allow is golem15.user.registration.allow_registration (default
// true), throttle is golem15.user.registration.use_register_throttle
// (default true), mode is golem15.user.activation.activate_mode (auto, user
// or admin; default auto) and require is
// golem15.user.activation.require_activation (default true).
func RegistrationSettings(app *backpack.App) (allow, throttle bool, mode string, require bool) {
return registrationSettings(app)
}
// RegistrationsFromIP counts the users created from ip in the last 60
// minutes (created_ip_address). /register refuses a registration when the
// throttle is on and the count is 3 or more. A query error counts as 0.
func RegistrationsFromIP(ctx context.Context, gdb *gorm.DB, ip string) int64 {
return registrationsFromIP(ctx, gdb, ip)
}
func registrationSettings(app *backpack.App) (allow, throttle bool, mode string, require bool) { func registrationSettings(app *backpack.App) (allow, throttle bool, mode string, require bool) {
allow, throttle, require = true, true, true allow, throttle, require = true, true, true
mode = "auto" mode = "auto"
@@ -726,38 +1063,41 @@ func appConfig(app *backpack.App) *compass.Config {
return app.Config return app.Config
} }
// authenticate resolves the signed-in user of r for the session routes that
// run without jwt.auth: /fetch, /update, /activate, /marketing-consent,
// /avatar and /avatar/remove. It reads the token as the plugin's jwt guard
// does (the bearer header, then the token and auth_token cookies), applies
// the blacklist and the user's tokens_valid_after cutoff, and answers 401
// otherwise.
func authenticate(w http.ResponseWriter, r *http.Request, app *backpack.App) (*models.User, bool) { func authenticate(w http.ResponseWriter, r *http.Request, app *backpack.App) (*models.User, bool) {
gdb, secret, ok := sessionDeps(w, app) gdb, secret, ok := sessionDeps(w, app)
if !ok { if !ok {
return nil, false return nil, false
} }
raw := bearerToken(r) principal, err := sessionGuard(app, secret).Authenticate(r)
sub, _, _, _, err := bouncer.VerifyClaims(raw, secret) if err != nil || principal == nil || principal.ID == 0 {
if err != nil {
writeUnauthorized(w)
return nil, false
}
id, err := strconv.ParseUint(sub, 10, 64)
if err != nil || id == 0 {
writeUnauthorized(w)
return nil, false
}
var bl bouncer.BlacklistStore
if store, ok := app.Lookup[bouncer.BlacklistStore](); ok {
bl = store
}
if _, err := bouncer.NewJWTGuard(secret, classes.GormUsers{App: app}, bl).Authenticate(r); err != nil {
writeUnauthorized(w) writeUnauthorized(w)
return nil, false return nil, false
} }
var user models.User var user models.User
if err := gdb.WithContext(r.Context()).Where("id = ?", id).Take(&user).Error; err != nil { if err := gdb.WithContext(r.Context()).Where("id = ?", principal.ID).Take(&user).Error; err != nil {
writeUnauthorized(w) writeUnauthorized(w)
return nil, false return nil, false
} }
return &user, true return &user, true
} }
// sessionGuard is the plugin's jwt guard as plugin.go Boot registers it: the
// bearer header, then the cookies of classes.SessionCookieNames, checked
// against the published bouncer.BlacklistStore when there is one.
func sessionGuard(app *backpack.App, secret string) bouncer.Guard {
var bl bouncer.BlacklistStore
if store, ok := app.Lookup[bouncer.BlacklistStore](); ok {
bl = store
}
return bouncer.NewJWTGuard(secret, classes.GormUsers{App: app}, bl, classes.SessionCookieNames()...)
}
func sessionDeps(w http.ResponseWriter, app *backpack.App) (*gorm.DB, string, bool) { func sessionDeps(w http.ResponseWriter, app *backpack.App) (*gorm.DB, string, bool) {
if app == nil { if app == nil {
writeOpaque500(w) writeOpaque500(w)
@@ -809,12 +1149,25 @@ func apiArray(ctx context.Context, app *backpack.App, user *models.User) (map[st
} }
func mintFor(app *backpack.App, secret string, user *models.User, issuer string) (string, error) { func mintFor(app *backpack.App, secret string, user *models.User, issuer string) (string, error) {
token, _, err := bouncer.Mint(secret, strconv.FormatUint(uint64(user.ID), 10), issuer, sessionTTL(app))
return token, err
}
// sessionTTL is the lifetime of a session JWT: golem15.user.jwt.ttl
// minutes, default 60.
func sessionTTL(app *backpack.App) time.Duration {
ttl := 60 * time.Minute ttl := 60 * time.Minute
if app != nil && app.Config != nil && app.Config.Int("golem15.user.jwt.ttl") > 0 { if app != nil && app.Config != nil && app.Config.Int("golem15.user.jwt.ttl") > 0 {
ttl = time.Duration(app.Config.Int("golem15.user.jwt.ttl")) * time.Minute ttl = time.Duration(app.Config.Int("golem15.user.jwt.ttl")) * time.Minute
} }
token, _, err := bouncer.Mint(secret, strconv.FormatUint(uint64(user.ID), 10), issuer, ttl) return ttl
return token, err }
// RefreshTTL is the refresh window of a session token:
// golem15.user.jwt.refresh_ttl minutes, default 20160 (two weeks). A cookie
// carrying the token should live this long.
func RefreshTTL(app *backpack.App) time.Duration {
return refreshTTL(app)
} }
func refreshTTL(app *backpack.App) time.Duration { func refreshTTL(app *backpack.App) time.Duration {
@@ -833,8 +1186,8 @@ func blacklistGrace(app *backpack.App) time.Duration {
return time.Duration(secs) * time.Second return time.Duration(secs) * time.Second
} }
func mailName(ctx context.Context, user *models.User, base string) string { func mailName(ctx context.Context, app *backpack.App, user *models.User, base string) string {
return classes.MailTemplate(base, classes.ResolveMailLocale(ctx, user)) return classes.MailTemplate(base, classes.ResolveMailLocaleFor(ctx, app, user))
} }
func sendTemplate(ctx context.Context, app *backpack.App, template, to string) { func sendTemplate(ctx context.Context, app *backpack.App, template, to string) {
@@ -862,11 +1215,11 @@ func sendTemplateVars(ctx context.Context, app *backpack.App, template, to strin
} }
mailer, ok := app.Lookup[postcard.Mailer]() mailer, ok := app.Lookup[postcard.Mailer]()
if !ok || mailer == nil { if !ok || mailer == nil {
slog.Default().Error("golem15.user: mailer is not configured", "template", template) pluginLog.Error("golem15.user: mailer is not configured", "template", template)
return return
} }
if err := mailer.Send(ctx, postcard.Message{Template: template, To: []string{to}, Vars: vars}); err != nil { if err := mailer.Send(ctx, postcard.Message{Template: template, To: []string{to}, Vars: vars}); err != nil {
slog.Default().Error("golem15.user: send mail", "template", template, "err", err) pluginLog.Error("golem15.user: send mail", "template", template, "err", err)
} }
} }
@@ -931,6 +1284,26 @@ func activationLink(app *backpack.App, id uint, code string) string {
return base + "?" + q.Encode() return base + "?" + q.Encode()
} }
// readBodyFields is readFields without the query string: a JSON body, or a
// form-encoded body read from r.PostForm. The routes that carry a secret in
// a field use it, so the secret is never taken from a URL that access logs
// record.
func readBodyFields(r *http.Request) (map[string]any, error) {
if strings.Contains(r.Header.Get("Content-Type"), "application/json") {
return readFields(r)
}
if err := r.ParseForm(); err != nil {
return nil, err
}
fields := map[string]any{}
for k, v := range r.PostForm {
if len(v) > 0 {
fields[k] = v[0]
}
}
return fields, nil
}
func readFields(r *http.Request) (map[string]any, error) { func readFields(r *http.Request) (map[string]any, error) {
ct := r.Header.Get("Content-Type") ct := r.Header.Get("Content-Type")
if strings.Contains(ct, "application/json") { if strings.Contains(ct, "application/json") {
@@ -977,16 +1350,6 @@ func jsonNumber(v any) string {
} }
} }
func bearerToken(r *http.Request) string {
h := strings.TrimSpace(r.Header.Get("Authorization"))
token, ok := strings.CutPrefix(h, "Bearer ")
token = strings.TrimSpace(token)
if !ok || token == "" {
return ""
}
return token
}
func requestURL(r *http.Request) string { func requestURL(r *http.Request) string {
scheme := "http" scheme := "http"
if r.TLS != nil { if r.TLS != nil {
@@ -998,6 +1361,14 @@ func requestURL(r *http.Request) string {
return scheme + "://" + r.Host + r.URL.Path return scheme + "://" + r.Host + r.URL.Path
} }
// RemoteIP returns the host part of r.RemoteAddr (r.RemoteAddr itself when
// it has no port, "" when it is empty), with no proxy handling. /login and
// /register key their throttles on surf.ClientIP with the trusted proxies;
// RemoteIP stays for callers that want the connection address.
func RemoteIP(r *http.Request) string {
return remoteIP(r)
}
func remoteIP(r *http.Request) string { func remoteIP(r *http.Request) string {
if r.RemoteAddr == "" { if r.RemoteAddr == "" {
return "" return ""
@@ -1009,6 +1380,47 @@ func remoteIP(r *http.Request) string {
return host return host
} }
// tokenCookieConfig is the auth.cookie block the plugin writes the session
// cookie with: bouncer.LoadCookieConfig of the application config, or its
// defaults when there is no config.
func tokenCookieConfig(app *backpack.App) (bouncer.CookieConfig, error) {
if app == nil || app.Config == nil {
return bouncer.LoadCookieConfig(nil)
}
return bouncer.LoadCookieConfig(app.Config)
}
// sessionCookie is the golem15.sociallogin token_cookie twin: with
// golem15.user.jwt.token_cookie on it returns the auth.cookie config the
// session routes write their token cookie with, or the error that block
// gives. A nil config means the token goes into the body; auth.cookie is
// then not read.
func sessionCookie(app *backpack.App) (*bouncer.CookieConfig, error) {
if app == nil || app.Config == nil || !app.Config.Bool("golem15.user.jwt.token_cookie") {
return nil, nil
}
cc, err := tokenCookieConfig(app)
if err != nil {
return nil, err
}
return &cc, nil
}
// writeSession answers 200 with a session token, the user plugin's twin of
// golem15.sociallogin's writeSession. With cc nil the token goes into
// body["token"], the key set the session routes have always answered. With
// cc set it goes only into the HttpOnly cookie cc writes (Max-Age
// golem15.user.jwt.refresh_ttl), so the token never reaches JavaScript, and
// body is answered without it.
func writeSession(w http.ResponseWriter, app *backpack.App, cc *bouncer.CookieConfig, token string, body map[string]any) {
if cc == nil {
body["token"] = token
} else {
http.SetCookie(w, cc.TokenCookie(token, refreshTTL(app)))
}
writeJSON(w, http.StatusOK, body)
}
func writeJSON(w http.ResponseWriter, status int, v any) { func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Cache-Control", "no-cache, private") w.Header().Set("Cache-Control", "no-cache, private")
wire.WriteJSON(w, status, v) wire.WriteJSON(w, status, v)
@@ -1021,6 +1433,18 @@ func writeInvalidLogin(w http.ResponseWriter, r *http.Request, app *backpack.App
}) })
} }
// refuseLogin is the one refusal /login gives after the throttle check: it
// records a failed attempt for user (a nil user, an unknown email, records
// nothing) and answers the 401 invalid-login body. The wrong-password and
// the not-activated branches share it, so their answers cannot be told apart.
func refuseLogin(ctx context.Context, w http.ResponseWriter, r *http.Request, app *backpack.App, gdb *gorm.DB, user *models.User, ip string) {
if err := classes.CheckAndRecordLogin(ctx, gdb, user, ip, false); err != nil && !classes.IsLoginRejected(err) {
writeOpaque500(w)
return
}
writeInvalidLogin(w, r, app)
}
func writeUnauthorized(w http.ResponseWriter) { func writeUnauthorized(w http.ResponseWriter) {
writeJSON(w, http.StatusUnauthorized, map[string]any{"error": true, "message": "Unauthorized"}) writeJSON(w, http.StatusUnauthorized, map[string]any{"error": true, "message": "Unauthorized"})
} }
@@ -1118,7 +1542,7 @@ func UploadAvatar(app *backpack.App) http.HandlerFunc {
} }
bucket, ok := app.Lookup[*blob.Bucket]() bucket, ok := app.Lookup[*blob.Bucket]()
if !ok || bucket == nil { if !ok || bucket == nil {
slog.Default().Error("golem15.user: avatar bucket is not configured") pluginLog.Error("golem15.user: avatar bucket is not configured")
writeOpaque500(w) writeOpaque500(w)
return return
} }
@@ -1269,17 +1693,9 @@ func applyAvatar(ctx context.Context, app *backpack.App, user *models.User, payl
} }
payload["has_avatar"] = true payload["has_avatar"] = true
payload["avatar"] = f.DiskName payload["avatar"] = f.DiskName
bucket, ok := app.Lookup[*blob.Bucket]() if url, err := classes.AvatarURL(ctx, app, user, 128); err == nil && url != "" {
if !ok || bucket == nil { payload["avatar_url"] = url
return
} }
url, err := f.Thumb(ctx, bucket, 128, 128, "auto")
if err != nil {
slog.Default().Error("golem15.user: avatar thumb", "err", err)
payload["avatar_url"] = "/" + attach.BlobKey(f.DiskName)
return
}
payload["avatar_url"] = url
} }
func avatarExt(mime string) (string, bool) { func avatarExt(mime string) (string, bool) {

View File

@@ -3,7 +3,6 @@ package controllers
import ( import (
"errors" "errors"
"net/http" "net/http"
"slices"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -12,6 +11,7 @@ import (
"git.golem15.com/golem15/sm-user-plugin/models" "git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer" "git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/wire" "git.golem15.com/golem15/summercms/modules/wire"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -34,7 +34,8 @@ func APITokenStore(app *backpack.App) http.HandlerFunc {
writeValidation(w, map[string][]string{"name": {"The name field is required and may not be longer than 255 characters."}}) writeValidation(w, map[string][]string{"name": {"The name field is required and may not be longer than 255 characters."}})
return return
} }
scopes, err := apiTokenScopes(fields["scopes"]) catalog := classes.APITokenScopesFor(app)
scopes, err := apiTokenScopes(catalog, fields["scopes"])
if err != nil { if err != nil {
writeValidation(w, map[string][]string{"scopes": {err.Error()}}) writeValidation(w, map[string][]string{"scopes": {err.Error()}})
return return
@@ -53,7 +54,7 @@ func APITokenStore(app *backpack.App) http.HandlerFunc {
writeOpaque500(w) writeOpaque500(w)
return return
} }
secret, token, err := classes.MintAPIToken(prefix, user.ID, name, scopes, expiresAt, nil) secret, token, err := classes.MintAPITokenFor(app, prefix, user.ID, name, scopes, expiresAt, nil)
if err != nil || db.WithContext(r.Context()).Create(token).Error != nil { if err != nil || db.WithContext(r.Context()).Create(token).Error != nil {
writeOpaque500(w) writeOpaque500(w)
return return
@@ -62,6 +63,37 @@ func APITokenStore(app *backpack.App) http.HandlerFunc {
} }
} }
// APITokenScopes serves GET /_user/api/v1/tokens/scopes behind jwt.auth:
// the member token scopes the caller may mint, {"data":[{"name","label",
// "description","built_in"}]}, the built-ins first, then the scopes the
// application's plugins declared. Phrase-key labels and descriptions are
// translated for the request locale.
func APITokenScopes(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, ok := bouncer.User(r.Context())
if !ok || user == nil || user.ID == 0 {
writeUnauthorized(w)
return
}
tr := appTranslator(app)
text := func(s string) string {
if tr == nil || !strings.Contains(s, "::") {
return s
}
return tr.Get(r.Context(), s, nil)
}
scopes := classes.APITokenScopesFor(app).Scopes()
data := make([]map[string]any, 0, len(scopes))
for _, scope := range scopes {
data = append(data, map[string]any{
"name": scope.Name, "label": text(scope.Label),
"description": text(scope.Description), "built_in": scope.BuiltIn,
})
}
writeJSON(w, http.StatusOK, map[string]any{"data": wire.Slice(data)})
}
}
// APITokenIndex lists the caller's live personal tokens without hashes. // APITokenIndex lists the caller's live personal tokens without hashes.
func APITokenIndex(app *backpack.App) http.HandlerFunc { func APITokenIndex(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
@@ -106,6 +138,8 @@ func APITokenDestroy(app *backpack.App) http.HandlerFunc {
writeOpaque500(w) writeOpaque500(w)
return return
} }
// Only the MCP sessions opened with this token end.
classes.FireSubjectEvent(r.Context(), app, pact.MCPSubjectChanged{Guard: classes.SubjectGuardUser, UserID: user.ID, Kind: pact.MCPSubjectRevoked, TokenID: token.ID})
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"revoked": true}}) writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"revoked": true}})
} }
} }
@@ -128,7 +162,9 @@ func apiTokenDeps(w http.ResponseWriter, r *http.Request, app *backpack.App) (*g
return db, user, true return db, user, true
} }
func apiTokenScopes(raw any) ([]string, error) { // apiTokenScopes reads the scopes field: nil, or an array of names the
// catalog allows.
func apiTokenScopes(catalog *classes.APITokenScopeCatalog, raw any) ([]string, error) {
if raw == nil { if raw == nil {
return nil, nil return nil, nil
} }
@@ -139,7 +175,7 @@ func apiTokenScopes(raw any) ([]string, error) {
out := make([]string, 0, len(values)) out := make([]string, 0, len(values))
for _, rawScope := range values { for _, rawScope := range values {
scope, ok := rawScope.(string) scope, ok := rawScope.(string)
if !ok || !slices.Contains(classes.AllowedAPITokenScopes, scope) { if !ok || !catalog.Allowed(scope) {
return nil, errors.New("The selected scope is invalid.") return nil, errors.New("The selected scope is invalid.")
} }
out = append(out, scope) out = append(out, scope)

47
controllers/app_access.go Normal file
View File

@@ -0,0 +1,47 @@
package controllers
import (
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"gorm.io/gorm"
)
// appAccess resolves the booted application on every call, so an admin
// controller never keeps a database handle or a config of its own.
type appAccess func() *backpack.App
// application returns the booted app, or nil before boot.
func (a appAccess) application() *backpack.App {
if a == nil {
return nil
}
return a()
}
// db is the application pool, or nil when the app has none.
func (a appAccess) db() *gorm.DB {
app := a.application()
if app == nil {
return nil
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok {
return nil
}
return gdb
}
// config is the application config, or nil before boot.
func (a appAccess) config() *compass.Config {
app := a.application()
if app == nil {
return nil
}
return app.Config
}
// translator is the application translator, or nil when none is published.
func (a appAccess) translator() *phrasebook.Translator {
return appTranslator(a.application())
}

View File

@@ -0,0 +1,152 @@
package controllers
import (
"errors"
"net/http"
"strconv"
"time"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/wire"
)
// backendLinks returns the published link service, or one over app.
func backendLinks(app *backpack.App) *classes.BackendLinks {
return classes.BackendLinksFor(app)
}
// linkNotFound is the one answer for an unknown, used or expired code and
// for an administrator who is no longer available: the page cannot tell
// them apart.
func linkNotFound(w http.ResponseWriter) {
writeJSON(w, http.StatusNotFound, map[string]any{"error": "not_found"})
}
// BackendLinkShow serves GET /_user/api/v1/backend-link/{code}, the site's
// "link this account to the administrator?" page: the administrator's login
// and display name and when the code expires, nothing else. Anyone holding
// the code may read it; a code that is unknown, used or expired, or whose
// administrator was deactivated, answers 404.
//
// Deprecated: the code sits in the request path, which access logs record.
// Pages call BackendLinkShowPost (POST /_user/api/v1/backend-link/show with
// the code in the body); this route stays for compatibility.
func BackendLinkShow(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
showLinkRequest(w, r, app, r.PathValue("code"))
}
}
// BackendLinkShowPost serves POST /_user/api/v1/backend-link/show: body
// {"code": ...}, the same answers as BackendLinkShow. The code travels in
// the body, so it stays out of the URLs servers and proxies log; a code in
// the query string is ignored.
func BackendLinkShowPost(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fields, err := readBodyFields(r)
if err != nil {
writeNoStoreJSON(w, http.StatusNotFound, map[string]any{"error": "not_found"})
return
}
showLinkRequest(w, r, app, strField(fields, "code"))
}
}
// showLinkRequest answers the link request behind code. Both show routes
// mark every answer as not storable, since it is keyed by a secret.
func showLinkRequest(w http.ResponseWriter, r *http.Request, app *backpack.App, code string) {
req, admin, err := backendLinks(app).LinkRequestByCode(r.Context(), code)
if err != nil {
if isLinkGone(err) {
writeNoStoreJSON(w, http.StatusNotFound, map[string]any{"error": "not_found"})
return
}
writeOpaque500(w)
return
}
writeNoStoreJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"admin": map[string]any{"login": admin.Login, "name": classes.BackendDisplayName(admin)},
"expires_at": req.ExpiresAt.UTC().Format(time.RFC3339),
}})
}
// writeNoStoreJSON is writeJSON with Cache-Control: no-store, private.
func writeNoStoreJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Cache-Control", "no-store, private")
wire.WriteJSON(w, status, v)
}
// BackendLinkConfirm serves POST /_user/api/v1/backend-link/confirm behind
// jwt.auth: body {"code": ...}. The signed-in frontend user is linked to the
// administrator who created the code, only when the session was signed in at
// or after the request: the token's auth_time (bouncer.VerifyAuthTime), which
// a refresh copies and never renews, is the proof. An older sign-in, or a
// token without auth_time (minted before auth_time existed, or refreshed from
// one), answers 409 with the stale-session error, an account already linked
// on either side 409 already_linked, an unknown, used or expired code 404.
// The code is read from the body only; one in the query string is ignored.
func BackendLinkConfirm(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
principal, ok := bouncer.User(r.Context())
if !ok || principal == nil || principal.ID == 0 {
writeUnauthorized(w)
return
}
secret, err := classes.JWTSecret(app)
if err != nil {
writeOpaque500(w)
return
}
// The token jwt.auth accepted (bearer header, then the session
// cookies), read again for its sign-in time.
sub, authTime, signedIn, err := bouncer.VerifyAuthTime(classes.SessionToken(r), secret, bouncer.AudienceUser)
if err != nil || sub != strconv.FormatUint(uint64(principal.ID), 10) {
writeUnauthorized(w)
return
}
if !signedIn {
writeJSON(w, http.StatusConflict, map[string]any{"error": "stale_session"})
return
}
fields, err := readBodyFields(r)
if err != nil {
linkNotFound(w)
return
}
links := backendLinks(app)
_, err = links.ConfirmLinkRequest(r.Context(), strField(fields, "code"), principal.ID, authTime)
switch {
case err == nil:
case errors.Is(err, classes.ErrStaleSession):
writeJSON(w, http.StatusConflict, map[string]any{"error": "stale_session"})
return
case errors.Is(err, classes.ErrAlreadyLinked):
writeJSON(w, http.StatusConflict, map[string]any{"error": "already_linked"})
return
case isLinkGone(err):
linkNotFound(w)
return
default:
writeOpaque500(w)
return
}
linked, found, err := links.LinkedBackendUser(r.Context(), principal.ID)
if err != nil || !found {
writeOpaque500(w)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"backend_user": map[string]any{"login": linked.Login, "name": linked.DisplayName},
}})
}
}
func isLinkGone(err error) bool {
return errors.Is(err, classes.ErrLinkRequestNotFound) ||
errors.Is(err, classes.ErrLinkRequestUsed) ||
errors.Is(err, classes.ErrLinkRequestExpired) ||
errors.Is(err, classes.ErrBackendUserUnavailable) ||
errors.Is(err, classes.ErrFrontendUserUnavailable)
}

573
controllers/devices.go Normal file
View File

@@ -0,0 +1,573 @@
package controllers
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/surf"
"git.golem15.com/golem15/summercms/modules/wire"
"github.com/jackc/pgx/v5/pgconn"
"gorm.io/gorm"
)
// deviceTable is the device authorization session table.
const deviceTable = "golem15_user_device_auth_sessions"
// deviceInsertAttempts bounds the retries of an initiate whose fresh short
// code (or token) collided with a stored one.
const deviceInsertAttempts = 5
// deviceCleanupBatch bounds the stale sessions one initiate deletes.
const deviceCleanupBatch = 500
// writeDeviceUnauthorized is the PHP device controller's 401 body, which
// differs from the session routes' {"error":true,"message":"Unauthorized"}.
func writeDeviceUnauthorized(w http.ResponseWriter) {
writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Unauthorized"})
}
// deviceCaller resolves the signed-in user of a device route that needs one
// (authorize, list, revoke). It reads and checks the session token as the
// plugin's jwt guard does (bearer header, then the session cookies; the
// blacklist and tokens_valid_after apply) and also returns the token's jti.
// Anything else answers PHP's 401 {"error":"Unauthorized"}.
func deviceCaller(w http.ResponseWriter, r *http.Request, app *backpack.App, gdb *gorm.DB, secret string) (*models.User, string, bool) {
principal, err := sessionGuard(app, secret).Authenticate(r)
if err != nil || principal == nil || principal.ID == 0 {
writeDeviceUnauthorized(w)
return nil, "", false
}
var user models.User
if err := gdb.WithContext(r.Context()).Where("id = ?", principal.ID).Take(&user).Error; err != nil {
writeDeviceUnauthorized(w)
return nil, "", false
}
jti := ""
if raw := classes.SessionToken(r); raw != "" {
if _, _, _, id, err := bouncer.VerifyClaims(raw, secret); err == nil {
jti = id
}
}
return &user, jti, true
}
// deviceClientIP is the client address device rows record: surf.ClientIP
// with http.trusted_proxies, as /login and /register use.
func deviceClientIP(app *backpack.App, r *http.Request) string {
return surf.ClientIP(r, surf.TrustedProxies(appConfig(app)))
}
// DeviceInitiate is POST /devices/initiate, called without a session by the
// device that wants to sign in. It stores a pending session (the SHA-256 of
// a 64-character token, a short code XXXX-XXXX, expires_at now plus
// golem15.user.device_auth.ttl_minutes, the device's address, user agent and
// optional device_name of at most 255 characters) and answers
// {"success":true,"data":{"token","short_code","auth_url","expires_at"}}.
// Each call first deletes at most 500 pending or expired sessions that
// expired more than an hour ago.
func DeviceInitiate(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gdb, _, ok := sessionDeps(w, app)
if !ok {
return
}
fields, err := readFields(r)
if err != nil {
writeOpaque500(w)
return
}
name := strField(fields, "device_name")
if utf8.RuneCountInString(name) > 255 {
writeValidation(w, map[string][]string{"device_name": {"The device name may not be greater than 255 characters."}})
return
}
ctx := r.Context()
// Stale sessions go in bounded batches, so the unauthenticated route
// cannot grow the table without limit (a failure is only logged).
if err := gdb.WithContext(ctx).Exec(`DELETE FROM `+deviceTable+` WHERE id IN (
SELECT id FROM `+deviceTable+`
WHERE status IN ('pending', 'expired') AND expires_at < NOW() - INTERVAL '1 hour'
LIMIT ?)`, deviceCleanupBatch).Error; err != nil {
pluginLog.Warn("golem15.user: device session cleanup", "err", err)
}
ip := deviceClientIP(app, r)
ua := r.UserAgent()
expires := time.Now().Add(classes.DeviceAuthTTL(app)).Truncate(time.Second)
var (
token string
row models.DeviceAuthSession
)
for attempt := 0; ; attempt++ {
token, err = classes.NewDeviceToken()
if err != nil {
writeOpaque500(w)
return
}
code, err := classes.NewDeviceShortCode()
if err != nil {
writeOpaque500(w)
return
}
row = models.DeviceAuthSession{
TokenHash: classes.HashAPIToken(token),
ShortCode: &code,
Status: models.DeviceStatusPending,
ExpiresAt: &expires,
}
if ip != "" {
row.DeviceIP = &ip
}
if ua != "" {
row.DeviceUserAgent = &ua
}
if name != "" {
row.DeviceName = &name
}
err = gdb.WithContext(ctx).Create(&row).Error
if err == nil {
break
}
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) || pgErr.Code != "23505" || attempt+1 >= deviceInsertAttempts {
pluginLog.Error("golem15.user: store device session", "err", err)
writeOpaque500(w)
return
}
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"data": map[string]any{
"token": token,
"short_code": *row.ShortCode,
"auth_url": classes.DeviceAuthURLFor(app, token, *row.ShortCode),
"expires_at": wire.Time{Time: expires},
},
})
}
}
// DeviceStatus is GET /devices/status/{token}, polled by the waiting
// device. It answers 404 {"error":"Session not found"} for an unknown token
// and PHP's flat {"success":true,"status":"expired","message":…} for a
// pending or confirmed session past expires_at (which it marks expired).
// The first poll after a signed-in user authorized the session receives a
// session token: {"success":true,"data":{"status":"confirmed","user_id",
// "message":"Device authorized - complete login","token","user"}}. One
// guarded confirmed-to-used UPDATE decides which poll that is, so of
// concurrent polls exactly one gets the token; the others, and every later
// poll, answer {"success":true,"data":{"status":"used"}}. Other statuses
// answer {"success":true,"data":{"status":…}}. Only a poll with the
// User-Agent the device initiated with receives the token: another client
// that learned the device token answers {"status":"confirmed"} and takes
// nothing, so the device still collects its session.
func DeviceStatus(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gdb, secret, ok := sessionDeps(w, app)
if !ok {
return
}
row, found, err := deviceByToken(r, gdb, r.PathValue("token"))
if err != nil {
writeOpaque500(w)
return
}
if !found {
writeJSON(w, http.StatusNotFound, map[string]any{"error": "Session not found"})
return
}
if row.Status == models.DeviceStatusConfirmed && row.UserID != nil && !row.ExpiredAt(time.Now()) && sameDeviceClient(r, row) {
if handOverDevice(w, r, app, gdb, secret, row) {
return
}
// Another poll won the hand-over or the session just expired:
// answer what the row says now, never a token.
row, found, err = deviceByID(r, gdb, row.ID)
if err != nil || !found {
writeOpaque500(w)
return
}
}
writeDeviceStatus(w, r, gdb, row)
}
}
// sameDeviceClient reports whether r comes with the User-Agent the device
// initiated the session with (none for none), the binding of the token
// hand-over to the initiating client.
func sameDeviceClient(r *http.Request, row models.DeviceAuthSession) bool {
stored := ""
if row.DeviceUserAgent != nil {
stored = *row.DeviceUserAgent
}
return r.UserAgent() == stored
}
// deviceByToken loads the session whose token hash matches token.
func deviceByToken(r *http.Request, gdb *gorm.DB, token string) (models.DeviceAuthSession, bool, error) {
var row models.DeviceAuthSession
if token == "" {
return row, false, nil
}
res := gdb.WithContext(r.Context()).Where("token = ?", classes.HashAPIToken(token)).Limit(1).Find(&row)
return row, res.RowsAffected == 1, res.Error
}
func deviceByID(r *http.Request, gdb *gorm.DB, id uint) (models.DeviceAuthSession, bool, error) {
var row models.DeviceAuthSession
res := gdb.WithContext(r.Context()).Where("id = ?", id).Limit(1).Find(&row)
return row, res.RowsAffected == 1, res.Error
}
// writeDeviceStatus answers a status poll that hands over no token. A
// pending or confirmed session past expires_at is marked expired (used and
// revoked sessions never are); an expired session answers PHP's flat
// expired body.
func writeDeviceStatus(w http.ResponseWriter, r *http.Request, gdb *gorm.DB, row models.DeviceAuthSession) {
expire := row.ExpiredAt(time.Now())
if expire || row.Status == models.DeviceStatusExpired {
if expire {
if err := gdb.WithContext(r.Context()).Exec(`UPDATE `+deviceTable+` SET status = 'expired', updated_at = NOW()
WHERE id = ? AND status IN ('pending', 'confirmed')`, row.ID).Error; err != nil {
writeOpaque500(w)
return
}
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"status": models.DeviceStatusExpired,
"message": "Authorization session has expired",
})
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"status": row.Status}})
}
// handOverDevice gives the confirmed session's user a session token for the
// device (D-12a). It reports false, having written nothing, when another
// poll already took the session or it expired meanwhile; the token it
// minted is then dropped unsent. A user who is gone, deactivated or
// banned, or whose tokens_valid_after (a password change, a revocation)
// is later than the authorization, gets nothing: the session becomes
// revoked, as a token minted at the authorization would be refused.
func handOverDevice(w http.ResponseWriter, r *http.Request, app *backpack.App, gdb *gorm.DB, secret string, row models.DeviceAuthSession) bool {
ctx := r.Context()
var user models.User
res := gdb.WithContext(ctx).Where("id = ?", *row.UserID).Limit(1).Find(&user)
if res.Error != nil {
writeOpaque500(w)
return true
}
refused := res.RowsAffected == 0
if !refused {
banned, _, err := classes.ThrottleStates(classes.ContextWithThrottle(ctx, app), gdb.WithContext(ctx), []uint{user.ID})
if err != nil {
writeOpaque500(w)
return true
}
refused = banned[user.ID] || authorizedBeforeCutoff(&user, row)
}
if refused {
// A deactivated, deleted or banned user signs no device in.
if err := gdb.WithContext(ctx).Exec(`UPDATE `+deviceTable+` SET status = 'revoked', updated_at = NOW()
WHERE id = ? AND status = 'confirmed'`, row.ID).Error; err != nil {
writeOpaque500(w)
return true
}
return false
}
token, jti, err := mintWithJTI(app, secret, &user, requestURL(r))
if err != nil {
writeOpaque500(w)
return true
}
payload, err := apiArray(ctx, app, &user)
if err != nil {
writeOpaque500(w)
return true
}
res = gdb.WithContext(ctx).Exec(`UPDATE `+deviceTable+`
SET status = 'used', used_at = NOW(), last_activity_at = NOW(), jwt_jti = ?, updated_at = NOW()
WHERE id = ? AND status = 'confirmed' AND expires_at > NOW()`, jti, row.ID)
if res.Error != nil {
writeOpaque500(w)
return true
}
if res.RowsAffected != 1 {
return false
}
if err := FinishLogin(ctx, app, gdb, &user, deviceClientIP(app, r)); err != nil {
pluginLog.Warn("golem15.user: finish device login", "user_id", user.ID, "err", err)
}
if err := FireLoginEvent(ctx, app, &user, classes.LoginSourceDevice); err != nil {
pluginLog.Warn("golem15.user: login event listener", "user_id", user.ID, "err", err)
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"data": map[string]any{
"status": models.DeviceStatusConfirmed,
"user_id": user.ID,
"message": "Device authorized - complete login",
"token": token,
"user": payload,
},
})
return true
}
// authorizedBeforeCutoff reports whether row was confirmed before the
// user's tokens_valid_after, compared as the jwt guard compares a token's
// whole-second iat.
func authorizedBeforeCutoff(user *models.User, row models.DeviceAuthSession) bool {
if user.TokensValidAfter == nil || row.ConfirmedAt == nil {
return false
}
return row.ConfirmedAt.Truncate(time.Second).Before(*user.TokensValidAfter)
}
// DeviceAuthorize is POST /devices/authorize: a signed-in user (a valid,
// not blacklisted session token; no second-factor check, D-12c) binds a
// pending device session to themselves by its short_code (hyphens and
// spaces optional, any case) or by its token (the QR code page). The token
// field also takes the short code, which the default auth_url carries in
// place of the device token. A short_code of
// other than 8 characters after removing hyphens answers 422 {"error":
// "Please enter a valid 8-character code"}; an unknown, expired, used,
// revoked or foreign session answers 400 {"error":"Invalid or expired
// code"}; success, and repeating it for a session the caller already
// confirmed, answers {"success":true,"message":"Device authorized
// successfully"}. Without a session it answers 401 {"error":"Unauthorized"}.
// The fields are read from the body only, never the query string.
func DeviceAuthorize(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gdb, secret, ok := sessionDeps(w, app)
if !ok {
return
}
user, _, ok := deviceCaller(w, r, app, gdb, secret)
if !ok {
return
}
fields, err := readBodyFields(r)
if err != nil {
writeOpaque500(w)
return
}
invalid := func() {
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "Invalid or expired code"})
}
var (
row models.DeviceAuthSession
found bool
)
if _, has := fields["short_code"]; has {
raw := strings.ReplaceAll(strField(fields, "short_code"), "-", "")
if len(raw) != 8 {
writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"error": "Please enter a valid 8-character code"})
return
}
code, valid := classes.NormalizeDeviceShortCode(raw)
if !valid {
invalid()
return
}
res := gdb.WithContext(r.Context()).Where("short_code = ?", code).Limit(1).Find(&row)
if res.Error != nil {
writeOpaque500(w)
return
}
found = res.RowsAffected == 1
} else if _, has := fields["token"]; has {
raw := strField(fields, "token")
if code, isCode := classes.NormalizeDeviceShortCode(raw); isCode {
// The QR page of the default auth_url carries the short
// code; a 64-character device token never normalizes.
res := gdb.WithContext(r.Context()).Where("short_code = ?", code).Limit(1).Find(&row)
if res.Error != nil {
writeOpaque500(w)
return
}
found = res.RowsAffected == 1
} else {
row, found, err = deviceByToken(r, gdb, raw)
if err != nil {
writeOpaque500(w)
return
}
}
}
if !found {
invalid()
return
}
res := gdb.WithContext(r.Context()).Exec(`UPDATE `+deviceTable+`
SET status = 'confirmed', user_id = ?, confirmed_at = NOW(), auth_ip = ?, updated_at = NOW()
WHERE id = ? AND status = 'pending' AND (user_id IS NULL OR user_id = ?) AND expires_at > NOW()`,
user.ID, nullableString(deviceClientIP(app, r)), row.ID, user.ID)
if res.Error != nil {
writeOpaque500(w)
return
}
if res.RowsAffected != 1 {
now, ok, err := deviceByID(r, gdb, row.ID)
if err != nil || !ok {
writeOpaque500(w)
return
}
again := now.Status == models.DeviceStatusConfirmed && now.UserID != nil && *now.UserID == user.ID && !now.ExpiredAt(time.Now())
if !again {
if now.ExpiredAt(time.Now()) {
_ = gdb.WithContext(r.Context()).Exec(`UPDATE `+deviceTable+` SET status = 'expired', updated_at = NOW()
WHERE id = ? AND status IN ('pending', 'confirmed')`, now.ID).Error
}
invalid()
return
}
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "Device authorized successfully"})
}
}
// nullableString is nil for "", else s.
func nullableString(s string) any {
if s == "" {
return nil
}
return s
}
// mintWithJTI mints the session JWT as mintFor does and also returns its
// jti, which device sessions store.
func mintWithJTI(app *backpack.App, secret string, user *models.User, issuer string) (string, string, error) {
return bouncer.Mint(secret, strconv.FormatUint(uint64(user.ID), 10), issuer, sessionTTL(app))
}
// DeviceIndex is GET /devices: the caller's authorized devices (sessions
// confirmed or used), most recent activity first, as {"success":true,
// "devices":[{id, device_name, device_ip, authorized_at, last_activity,
// is_current}]}. device_name is the stored name or one parsed from the user
// agent (classes.DeviceDisplayName); is_current is true for the session
// whose token is the one the request carries. Without a session it answers
// 401 {"error":"Unauthorized"}.
func DeviceIndex(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gdb, secret, ok := sessionDeps(w, app)
if !ok {
return
}
user, jti, ok := deviceCaller(w, r, app, gdb, secret)
if !ok {
return
}
var rows []models.DeviceAuthSession
if err := gdb.WithContext(r.Context()).
Where("user_id = ? AND status IN ?", user.ID, []string{models.DeviceStatusConfirmed, models.DeviceStatusUsed}).
Order("last_activity_at DESC NULLS LAST, id DESC").
Find(&rows).Error; err != nil {
writeOpaque500(w)
return
}
devices := make([]map[string]any, 0, len(rows))
for _, row := range rows {
ua := ""
if row.DeviceUserAgent != nil {
ua = *row.DeviceUserAgent
}
devices = append(devices, map[string]any{
"id": row.ID,
"device_name": classes.DeviceDisplayName(row.DeviceName, ua),
"device_ip": row.DeviceIP,
"authorized_at": wireTimeOrNil(row.ConfirmedAt),
"last_activity": wireTimeOrNil(row.LastActivityAt),
"is_current": jti != "" && row.JWTJTI != nil && *row.JWTJTI == jti,
})
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "devices": wire.Slice(devices)})
}
}
// DeviceDestroy is DELETE /devices/{id}: the caller revokes one of their
// device sessions. In one transaction the row is marked revoked and the jti
// of the session token the device holds (followed through refresh) is
// added to the JWT blacklist for the token's whole refresh window, so the
// device is signed out at once and cannot refresh. The jti is the one the
// revoking UPDATE returns, read under the row lock a concurrent refresh's
// hand-over also takes (classes.FollowDeviceJTI), so a refresh that moved
// the session first is blacklisted and one that comes after is refused. A
// blacklist failure answers the opaque 500 and leaves the row as it was.
// Success answers PHP's body with success true and the message Device
// revoked successfully, also for a row already revoked; a row of another
// user, or none, answers 404 with the error Device not found; no session
// answers 401 {"error":"Unauthorized"}.
func DeviceDestroy(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
gdb, secret, ok := sessionDeps(w, app)
if !ok {
return
}
user, _, ok := deviceCaller(w, r, app, gdb, secret)
if !ok {
return
}
notFound := func() { writeJSON(w, http.StatusNotFound, map[string]any{"error": "Device not found"}) }
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
if err != nil || id == 0 {
notFound()
return
}
found := false
err = lagoon.Transaction(r.Context(), gdb, func(ctx context.Context, tx *gorm.DB) error {
// The jti current at the revoke, under the row lock: never one
// read before a concurrent refresh moved the session on.
var revoked []struct {
JWTJTI *string `gorm:"column:jwt_jti"`
}
if err := tx.WithContext(ctx).Raw(`UPDATE `+deviceTable+` SET status = 'revoked', updated_at = NOW()
WHERE id = ? AND user_id = ?
RETURNING jwt_jti`, id, user.ID).Scan(&revoked).Error; err != nil {
return err
}
if len(revoked) == 0 {
return nil
}
found = true
jti := revoked[0].JWTJTI
if jti == nil || *jti == "" {
return nil
}
bl, ok := app.Lookup[bouncer.BlacklistStore]()
if !ok || bl == nil {
return errors.New("golem15.user: no JWT blacklist store is published")
}
now := time.Now()
return bl.Add(ctx, *jti, now.Add(refreshTTL(app)+sessionTTL(app)+time.Minute), now)
})
if err != nil {
pluginLog.Error("golem15.user: revoke device session", "user_id", user.ID, "err", err)
writeOpaque500(w)
return
}
if !found {
notFound()
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "Device revoked successfully"})
}
}
// wireTimeOrNil is t as a +00:00 timestamp, or nil.
func wireTimeOrNil(t *time.Time) any {
if t == nil {
return nil
}
return wire.Time{Time: *t}
}

7
controllers/logger.go Normal file
View File

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

View File

@@ -0,0 +1,27 @@
package controllers
import (
"context"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/summercms/modules/backpack"
)
// CheckLoginGates consults the published *classes.LoginGates for a
// first-factor sign-in that already succeeded and returns its answer: nil,
// nil allows the sign-in, a result replaces the token response, and an error
// must fail the sign-in closed (answer the opaque 500, issue no token). It
// looks the registry up on every call and allows the sign-in when none is
// published. Password Login calls it, activate-by-code calls it after the
// mailed code verified (source password), and a social-login plugin calls
// it before it issues a token.
func CheckLoginGates(ctx context.Context, app *backpack.App, a classes.LoginAttempt) (*classes.LoginGateResult, error) {
if app == nil {
return nil, nil
}
gates, ok := app.Lookup[*classes.LoginGates]()
if !ok || gates == nil {
return nil, nil
}
return gates.Check(ctx, a)
}

View File

@@ -0,0 +1,174 @@
package controllers
import (
"errors"
"net/http"
"slices"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/wire"
"gorm.io/gorm"
)
// OAuthIdentitiesOptions configures host-mounted list/unlink handlers.
// Providers is the unlink allow-list. When nil or empty, the allow-list is
// read on every request: the KnownOAuthProviders of a published
// classes.OAuthProviderSource, else google, facebook, github and microsoft.
// WriteNotFound is injected by the host so 404 bodies match that app.
type OAuthIdentitiesOptions struct {
Providers []string
WriteNotFound func(http.ResponseWriter, *http.Request)
}
// defaultOAuthProviders is the unlink allow-list without options and without
// a published provider source.
var defaultOAuthProviders = []string{"google", "facebook", "github", "microsoft"}
// oauthGuardedDelete is the PHP unlink rule (User.php unlinkOAuthProvider):
// the identity goes only when the user has a self-set password or another
// identity remains.
const oauthGuardedDelete = `DELETE FROM golem15_user_oauth_identities
WHERE user_id = ? AND provider = ?
AND (EXISTS (SELECT 1 FROM users u WHERE u.id = golem15_user_oauth_identities.user_id AND u.has_self_set_password)
OR (SELECT COUNT(*) FROM golem15_user_oauth_identities oi WHERE oi.user_id = golem15_user_oauth_identities.user_id) > 1)`
// OAuthIdentitiesIndex lists the caller's linked OAuth providers.
func OAuthIdentitiesIndex(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
db, user, ok := oauthIdentityDeps(w, r, app)
if !ok {
return
}
var rows []models.OAuthIdentity
if err := db.WithContext(r.Context()).
Where("user_id = ?", user.ID).
Order("provider").
Find(&rows).Error; err != nil {
writeOpaque500(w)
return
}
data := make([]map[string]any, 0, len(rows))
for i := range rows {
item := map[string]any{
"provider": rows[i].Provider,
"linked_at": nil,
}
if rows[i].LinkedAt != nil {
item["linked_at"] = &wire.Time{Time: rows[i].LinkedAt.UTC()}
}
data = append(data, item)
}
writeJSON(w, http.StatusOK, map[string]any{"data": wire.Slice(data)})
}
}
// OAuthIdentitiesDestroy unlinks one provider for the caller, under the PHP
// rule: it succeeds (204) when the user has a self-set password or another
// identity remains, and answers 409 with the last_method_blocked phrase
// otherwise. An unknown provider or a missing identity goes to WriteNotFound.
func OAuthIdentitiesDestroy(app *backpack.App, opts OAuthIdentitiesOptions) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
db, user, ok := oauthIdentityDeps(w, r, app)
if !ok {
return
}
provider := r.PathValue("provider")
if !slices.Contains(unlinkProviders(app, opts), provider) {
writeOAuthIdentityNotFound(w, r, opts)
return
}
var row models.OAuthIdentity
err := db.WithContext(r.Context()).
Where("user_id = ? AND provider = ?", user.ID, provider).
First(&row).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
writeOAuthIdentityNotFound(w, r, opts)
return
}
if err != nil {
writeOpaque500(w)
return
}
// D-13: the guarded DELETE alone is not race-safe on Postgres. Under
// READ COMMITTED two unlinks of different identities each see the
// other's row in their COUNT and do not wait for each other, so both
// succeed and a password-less user loses every sign-in method. The
// lock on the users row serialises them: the second DELETE runs after
// the first commits and sees one identity left.
var deleted int64
err = db.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
if err := tx.Exec(`SELECT id FROM users WHERE id = ? FOR UPDATE`, user.ID).Error; err != nil {
return err
}
res := tx.Exec(oauthGuardedDelete, user.ID, provider)
if res.Error != nil {
return res.Error
}
deleted = res.RowsAffected
return nil
})
if err != nil {
writeOpaque500(w)
return
}
if deleted == 0 {
writeJSON(w, http.StatusConflict, map[string]any{
"error": oauthLastMethodBlocked(r, app),
})
return
}
w.WriteHeader(http.StatusNoContent)
}
}
// unlinkProviders is the unlink allow-list for one request.
func unlinkProviders(app *backpack.App, opts OAuthIdentitiesOptions) []string {
if len(opts.Providers) > 0 {
return opts.Providers
}
if src, ok := oauthProviderSource(app); ok {
return src.KnownOAuthProviders()
}
return defaultOAuthProviders
}
func writeOAuthIdentityNotFound(w http.ResponseWriter, r *http.Request, opts OAuthIdentitiesOptions) {
if opts.WriteNotFound != nil {
opts.WriteNotFound(w, r)
return
}
writeOpaque500(w)
}
func oauthLastMethodBlocked(r *http.Request, app *backpack.App) string {
const fallback = "This is the only remaining way to sign in. Link another method before disconnecting this one."
tr := appTranslator(app)
if tr == nil {
return fallback
}
s := tr.Get(r.Context(), "golem15.user::lang.oauth.last_method_blocked", nil)
if s == "" || s == "golem15.user::lang.oauth.last_method_blocked" {
return fallback
}
return s
}
func oauthIdentityDeps(w http.ResponseWriter, r *http.Request, app *backpack.App) (*gorm.DB, *bouncer.Principal, bool) {
if app == nil {
writeOpaque500(w)
return nil, nil, false
}
db, ok := app.Lookup[*gorm.DB]()
if !ok || db == nil {
writeOpaque500(w)
return nil, nil, false
}
user, ok := bouncer.User(r.Context())
if !ok || user == nil || user.ID == 0 {
writeUnauthorized(w)
return nil, nil, false
}
return db, user, true
}

View File

@@ -0,0 +1,18 @@
name: golem15.user::lang.organisation.label
form: ~/plugins/golem15/user/models/organisation/fields.yaml
modelClass: Golem15\User\Models\Organisation
defaultRedirect: golem15/user/organisations
create:
redirect: golem15/user/organisations/update/:id
redirectClose: golem15/user/organisations
update:
redirect: golem15/user/organisations
redirectClose: golem15/user/organisations
messages:
create: golem15.user::lang.organisation.new
update: backend::lang.messages.form.update
saved: backend::lang.messages.form.saved
deleted: backend::lang.messages.form.deleted

View File

@@ -0,0 +1,15 @@
list: ~/plugins/golem15/user/models/organisation/columns.yaml
modelClass: Golem15\User\Models\Organisation
title: golem15.user::lang.organisation.label_plural
recordUrl: golem15/user/organisations/update/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 20
toolbar:
buttons: [create]
search:
prompt: backend::lang.list.search_prompt
messages:
create: golem15.user::lang.organisation.new
empty: golem15.user::lang.organisation.list_empty

View File

@@ -0,0 +1,24 @@
members:
label: golem15.user::lang.organisation.members
messages:
link: golem15.user::lang.organisation.add_member
unlinkSelected: golem15.user::lang.organisation.remove_members
unlinkConfirm: golem15.user::lang.organisation.remove_members_confirm
empty: golem15.user::lang.organisation.members_empty
view:
list:
columns:
name:
label: golem15.user::lang.user.name
email:
label: golem15.user::lang.user.email
toolbarButtons: link|unlink
showSearch: true
manage:
list:
columns:
name:
label: golem15.user::lang.user.name
email:
label: golem15.user::lang.user.email
showSearch: true

View File

@@ -0,0 +1,172 @@
package controllers
import (
"context"
"errors"
"regexp"
"strconv"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"gocloud.dev/blob"
"gorm.io/gorm"
)
// organisationSlugPattern is the PHP alpha_dash rule on the slug, kept to
// ASCII. lagoon.Validate has no alpha_dash token, so the Form before-hooks
// check it.
var organisationSlugPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
// membersRelation is the organisation's hasMany relation to its users.
const membersRelation = "members"
// organisationsAdminController is the Winter Organisations backend
// controller: the list, the form with the avatar, and the members relation
// manager. The screen and every write need golem15.users.access_users, as in
// PHP.
//
// The members manager sets and clears users.organisation_id, and clears
// users.organisation_role with it (a role belongs to one organisation). It
// never writes users_groups.
type organisationsAdminController struct {
app appAccess
}
func (organisationsAdminController) ID() string { return "golem15.user.organisations" }
func (organisationsAdminController) ModelName() string { return `Golem15\User\Models\Organisation` }
func (organisationsAdminController) ConfigDir() string { return "controllers/organisations" }
func (organisationsAdminController) RequiredPermissions() []string {
return []string{PermissionAccessUsers}
}
func (organisationsAdminController) NewRecord() any { return &models.Organisation{} }
// FormBeforeCreate and FormBeforeUpdate check the slug's characters.
func (c organisationsAdminController) FormBeforeCreate(ctx context.Context, model any) error {
return c.requireSlugFormat(ctx, model)
}
func (c organisationsAdminController) FormBeforeUpdate(ctx context.Context, model any) error {
return c.requireSlugFormat(ctx, model)
}
// requireSlugFormat answers 422 on slug when it holds anything but letters,
// digits, underscore and hyphen. An empty slug is left to the required rule.
func (c organisationsAdminController) requireSlugFormat(ctx context.Context, model any) error {
organisation, ok := model.(*models.Organisation)
if !ok || organisation == nil {
return errors.New("organisations admin: form model is not an organisation")
}
if organisation.Slug == "" || organisationSlugPattern.MatchString(organisation.Slug) {
return nil
}
message := "The slug may only contain letters, numbers, dashes and underscores."
if tr := c.app.translator(); tr != nil {
const key = "golem15.user::lang.organisation.slug_invalid"
if text := tr.Get(ctx, key, nil); text != "" && text != key {
message = text
}
}
return &cabana.ValidationError{Details: map[string]any{"slug": []string{message}}}
}
// AdminRelationContracts declares the members relation manager: the users
// whose organisation_id is the organisation. Linking sets the column and
// unlinking clears it; the column is nullable, so a user is never deleted.
// Both also clear organisation_role (ClearOnChange), so a role never moves
// to another organisation or outlives the membership.
func (organisationsAdminController) AdminRelationContracts() []cabana.RelationContract {
return []cabana.RelationContract{{
Name: membersRelation,
Kind: cabana.RelationHasMany,
NewRelated: func() any { return &models.User{} },
ForeignKey: "organisation_id",
ClearOnChange: []string{"organisation_role"},
Columns: map[string]string{
"name": "name",
"email": "email",
},
}}
}
// RelationExtendManageQuery fails closed: any relation name other than
// members has no candidates.
func (organisationsAdminController) RelationExtendManageQuery(_ context.Context, relation string, db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
if relation != membersRelation {
return db.Where("1 = 0")
}
return db
}
// FormBeforeDelete releases the members of the organisation in the delete's
// transaction: organisation_id and organisation_role are cleared, on
// deactivated users too, so the delete does not fail on the users foreign key
// and no user is deleted.
func (organisationsAdminController) FormBeforeDelete(ctx context.Context, model any) error {
organisation, ok := model.(*models.Organisation)
if !ok || organisation == nil {
return errors.New("organisations admin: form model is not an organisation")
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return errors.New("organisations admin: a delete needs its transaction")
}
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped().
Model(&models.User{}).Where("organisation_id = ?", organisation.ID).
Updates(map[string]any{"organisation_id": nil, "organisation_role": nil}).Error
}
// FormAfterDelete deletes the organisation's attachments (avatar and logo)
// in the delete's transaction, and their blobs once it commits, so no
// system_files row outlives the organisation row.
func (c organisationsAdminController) FormAfterDelete(ctx context.Context, model any) error {
organisation, ok := model.(*models.Organisation)
if !ok || organisation == nil {
return errors.New("organisations admin: form model is not an organisation")
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return errors.New("organisations admin: a delete needs its transaction")
}
var keys []string
if err := attach.DeleteForOwner(tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx), organisation, strconv.FormatUint(uint64(organisation.ID), 10), func(blobKeys []string) error {
keys = append(keys, blobKeys...)
return nil
}); err != nil {
return err
}
bucket := c.bucket()
if bucket == nil || len(keys) == 0 {
return nil
}
id := organisation.ID
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
// The rows are gone by now, so a blob that cannot be removed is
// orphaned, not lost data: log it and carry on.
if err := attach.DeleteKeys(ctx, bucket, keys); err != nil {
pluginLog.Warn("golem15.user: remove attachment blobs of a deleted organisation", "organisation_id", id, "err", err)
}
})
return nil
}
// bucket is the application's blob bucket, or nil when none is published.
func (c organisationsAdminController) bucket() *blob.Bucket {
app := c.app.application()
if app == nil {
return nil
}
bucket, ok := app.Lookup[*blob.Bucket]()
if !ok {
return nil
}
return bucket
}

View File

@@ -22,19 +22,30 @@ import (
// RegisterOptions tunes RegisterUser. Activate creates the account already // RegisterOptions tunes RegisterUser. Activate creates the account already
// activated (activate_mode auto, or a caller that activates explicitly). // 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 { type RegisterOptions struct {
Activate bool Activate bool
IP string IP string
// PasswordLess creates the account with has_self_set_password=false: its
// password is random and was never known to the user (social sign-in,
// PHP password_bootstrap_source oauth_registration). The zero value
// keeps true.
PasswordLess bool
} }
// RegisterUser validates fields against the user model's rules, hashes the // RegisterUser validates fields against the user model's rules, hashes the
// password with golem15.user.password.bcrypt_cost (default 10), fills the // password with golem15.user.password.bcrypt_cost (default 10), fills only
// fillable columns and creates the users row on db, which may be a // the models.User RegisterFillable columns (name, surname, email, password,
// transaction. Validation failures are returned as Laravel's errors object // preferred_locale, marketing_consent) and creates the users row on db,
// (attribute to messages) with a nil user and nothing written; they are not // which may be a transaction. Any other key in fields is ignored: an
// written to a response. fields is not modified. The register event is not // organisation membership and role are set with an explicit update after
// fired: call FireRegisterEvent once the row is committed. // 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) { 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 { if db == nil {
return nil, nil, errors.New("golem15.user: gorm handle is missing") return nil, nil, errors.New("golem15.user: gorm handle is missing")
@@ -59,16 +70,19 @@ func RegisterUser(ctx context.Context, app *backpack.App, db *gorm.DB, fields ma
return nil, nil, err return nil, nil, err
} }
input["password"] = hashed input["password"] = hashed
if opts.IP != "" {
input["created_ip_address"] = opts.IP
input["last_ip_address"] = opts.IP
}
user := &models.User{} user := &models.User{}
production := app == nil || app.Config == nil || !app.Config.Bool("app.debug") 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 return nil, nil, err
} }
user.HasSelfSetPassword = true // 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 { if opts.Activate {
user.IsActivated = true user.IsActivated = true
now := time.Now() now := time.Now()
@@ -77,13 +91,53 @@ func RegisterUser(ctx context.Context, app *backpack.App, db *gorm.DB, fields ma
if err := db.WithContext(ctx).Create(user).Error; err != nil { if err := db.WithContext(ctx).Create(user).Error; err != nil {
return nil, nil, err return nil, nil, err
} }
if err := classes.AssignHandle(ctx, db, user); err != nil {
return nil, nil, err
}
return user, nil, nil return user, nil, nil
} }
// FinishLogin runs the steps password Login takes after it has
// authenticated a user, 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. It
// checks no password, throttle, activation or ban and fires no event; the
// caller does those checks, consults the login gates (CheckLoginGates)
// before it, and fires the login event (FireLoginEvent) after it minted the
// token. A failed last_seen write is logged and does not fail it, as in
// Login.
func FinishLogin(ctx context.Context, app *backpack.App, db *gorm.DB, user *models.User, ip string) error {
if db == nil {
return errors.New("golem15.user: gorm handle is missing")
}
if user == nil || user.ID == 0 {
return errors.New("golem15.user: finishing a login needs a stored user")
}
if user.DeletedAt.Valid {
if err := db.WithContext(ctx).Unscoped().Model(user).Update("deleted_at", nil).Error; err != nil {
return err
}
user.DeletedAt = gorm.DeletedAt{}
sendTemplateVars(ctx, app, mailName(ctx, app, user, "golem15.user::mail.reactivate"), user.Email, mailVars(displayName(user), "", ""))
}
if ip != "" {
if err := db.WithContext(ctx).Unscoped().Model(user).Update("last_ip_address", ip).Error; err != nil {
return err
}
addr := ip
user.LastIPAddress = &addr
}
if err := classes.TouchLastSeen(ctx, db, user.ID); err != nil {
pluginLog.Warn("golem15.user: stamp last_seen on login", "user_id", user.ID, "err", err)
}
return nil
}
// FireRegisterEvent fires classes.RegisterEvent for user with Payload set // FireRegisterEvent fires classes.RegisterEvent for user with Payload set
// to a copy of fields without password and password_confirmation, and // to a copy of fields without password and password_confirmation, and
// returns the listeners' error. /register ignores that error, as Winter // returns the listeners' error. /register logs that error and continues, as
// does not stop a registration for a failing listener. // 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 { func FireRegisterEvent(ctx context.Context, app *backpack.App, user *models.User, fields map[string]any) error {
if app == nil || app.Events == nil { if app == nil || app.Events == nil {
return nil return nil
@@ -97,6 +151,47 @@ func FireRegisterEvent(ctx context.Context, app *backpack.App, user *models.User
return app.Events.Fire(ctx, &classes.RegisterEvent{User: user, Payload: payload}) return app.Events.Fire(ctx, &classes.RegisterEvent{User: user, Payload: payload})
} }
// FireCreatedEvent fires classes.CreatedEvent (user.Created) for user and
// 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
}
return app.Events.Fire(ctx, &classes.CreatedEvent{User: user})
}
// FireDeletingEvent fires classes.DeletingEvent (user.Deleting) for user
// inside the delete transaction. FormAfterDelete returns the listeners'
// error so a failed cascade rolls the delete back.
func FireDeletingEvent(ctx context.Context, app *backpack.App, user *models.User, tx *gorm.DB) error {
if app == nil || app.Events == nil {
return nil
}
return app.Events.Fire(ctx, &classes.DeletingEvent{User: user, Tx: tx})
}
// FireDeactivatingEvent fires classes.DeactivatingEvent (user.Deactivating)
// for user inside the deactivation transaction and returns the listeners'
// error, so a failed listener rolls the deactivation back.
func FireDeactivatingEvent(ctx context.Context, app *backpack.App, user *models.User, tx *gorm.DB) error {
if app == nil || app.Events == nil {
return nil
}
return app.Events.Fire(ctx, &classes.DeactivatingEvent{User: user, Tx: tx})
}
// FireLoginEvent fires classes.LoginEvent (golem15.user.login) for user
// with source, one of the classes.LoginSource constants, and returns the
// listeners' error. Call it after the session token was minted; a caller
// logs the error and still answers the sign-in.
func FireLoginEvent(ctx context.Context, app *backpack.App, user *models.User, source string) error {
if app == nil || app.Events == nil {
return nil
}
return app.Events.Fire(ctx, &classes.LoginEvent{User: user, Source: source})
}
// IssueToken mints the session JWT for user exactly as /register and // IssueToken mints the session JWT for user exactly as /register and
// /login do: the plugin's JWT secret, golem15.user.jwt.ttl and the request // /login do: the plugin's JWT secret, golem15.user.jwt.ttl and the request
// URL as the issuer. // URL as the issuer.

23
controllers/request_db.go Normal file
View File

@@ -0,0 +1,23 @@
package controllers
import (
"context"
"git.golem15.com/golem15/summercms/modules/cabana"
"gorm.io/gorm"
)
// requestDB is the database handle a hook or scope should read through. Inside
// an admin write it is the transaction the write runs in, so the hook sees the
// write's snapshot and does not take a second pool connection while the
// transaction holds row locks. Outside a transaction (the list) it is the
// application pool from the booted app. It is nil when neither exists.
func requestDB(ctx context.Context, pool func() *gorm.DB) *gorm.DB {
if tx, ok := cabana.TxFromContext(ctx); ok {
return tx
}
if pool == nil {
return nil
}
return pool()
}

39
controllers/token_me.go Normal file
View File

@@ -0,0 +1,39 @@
package controllers
import (
"net/http"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
// TokenMe serves GET /_user/api/v1/token/me behind user.api_token and
// user.scope:read: the token owner's user payload, the same {"user": ...}
// body GET /fetch answers for a session. It is the target of the MCP tool
// user_me. The guard answers 401 for a missing or unusable token and the
// scope middleware 403 for a token without read.
func TokenMe(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
principal, ok := bouncer.User(r.Context())
if !ok || principal == nil || principal.ID == 0 {
writeUnauthorized(w)
return
}
gdb, _, ok := sessionDeps(w, app)
if !ok {
return
}
var user models.User
if err := gdb.WithContext(r.Context()).Where("id = ?", principal.ID).Take(&user).Error; err != nil {
writeUnauthorized(w)
return
}
payload, err := apiArray(r.Context(), app, &user)
if err != nil {
writeOpaque500(w)
return
}
writeJSON(w, http.StatusOK, map[string]any{"user": payload})
}
}

View File

@@ -0,0 +1,19 @@
name: golem15.user::lang.group.label
form: ~/plugins/golem15/user/models/usergroup/fields.yaml
modelClass: Golem15\User\Models\UserGroup
defaultRedirect: golem15/user/usergroups
create:
redirect: golem15/user/usergroups/update/:id
redirectClose: golem15/user/usergroups
update:
redirect: golem15/user/usergroups
redirectClose: golem15/user/usergroups
messages:
create: golem15.user::lang.groups.new_group
update: backend::lang.messages.form.update
saved: backend::lang.messages.form.saved
deleteConfirm: golem15.user::lang.groups.delete_confirm
deleted: backend::lang.messages.form.deleted

View File

@@ -0,0 +1,17 @@
list: ~/plugins/golem15/user/models/usergroup/columns.yaml
modelClass: Golem15\User\Models\UserGroup
title: golem15.user::lang.groups.list_title
recordUrl: golem15/user/usergroups/update/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 20
showSetup: true
showSorting: true
toolbar:
buttons: [create]
search:
prompt: backend::lang.list.search_prompt
messages:
create: golem15.user::lang.groups.new_group
empty: golem15.user::lang.groups.list_empty

View File

@@ -0,0 +1,295 @@
package controllers
import (
"context"
"errors"
"fmt"
"regexp"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"gorm.io/gorm"
)
// PermissionAccessGroups is the backend permission of the User Groups
// screen, the PHP UserGroups::$requiredPermissions.
const PermissionAccessGroups = "golem15.users.access_groups"
// groupsLang prefixes the phrase keys of the User Groups screen.
const groupsLang = "golem15.user::lang.groups."
// groupCodePattern is the PHP UserGroup code rule
// regex:/^[a-zA-Z0-9_\-]+$/. lagoon.Validate has no regex token, so the
// Form before-hooks check it.
var groupCodePattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
// usergroupsAdminController is the Winter UserGroups backend controller: the
// list with the member count and the form with the frontend permissions of
// the group. The screen and every write need golem15.users.access_groups.
//
// A group's code decides whether its members are privileged
// (golem15.user.privileged_groups), so three writes additionally need
// golem15.users.manage_privileged_groups: creating a group with a privileged
// code, changing a code to or from a privileged one, and deleting a
// privileged group. Everything else on a privileged group (its name,
// description and frontend permissions) needs only the screen's permission.
//
// The screen never writes a membership: users_groups changes only through
// the user form's groups field, and loses the rows of a deleted group.
type usergroupsAdminController struct {
app appAccess
}
func (usergroupsAdminController) ID() string { return "golem15.user.usergroups" }
func (usergroupsAdminController) ModelName() string { return `Golem15\User\Models\UserGroup` }
func (usergroupsAdminController) ConfigDir() string { return "controllers/usergroups" }
func (usergroupsAdminController) RequiredPermissions() []string {
return []string{PermissionAccessGroups}
}
func (usergroupsAdminController) NewRecord() any { return &models.UserGroup{} }
// ListExtendQuery adds the member count of every group on the page, the PHP
// users_count relation column, in the list's own query. The two select
// arguments keep the list's count query a plain COUNT(*).
func (usergroupsAdminController) ListExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
return db.Select("user_groups.*",
"(SELECT COUNT(*) FROM users_groups WHERE users_groups.user_group_id = user_groups.id) AS users_count")
}
// FormBeforeCreate checks the code's format and refuses a privileged code
// without golem15.users.manage_privileged_groups.
func (c usergroupsAdminController) FormBeforeCreate(ctx context.Context, model any) error {
group, ok := model.(*models.UserGroup)
if !ok || group == nil {
return errors.New("user groups admin: form model is not a user group")
}
if err := c.requireCodeFormat(ctx, group); err != nil {
return err
}
if !classes.IsPrivilegedCode(classes.PrivilegedGroupCodes(c.app.config()), group.Code) {
return nil
}
return c.requirePrivilegedPermission(ctx)
}
// FormBeforeUpdate checks the code's format and refuses a code change to or
// from a privileged code without golem15.users.manage_privileged_groups. The
// stored code is read through the write's transaction; a save that leaves
// the code as it is passes, whatever the code.
func (c usergroupsAdminController) FormBeforeUpdate(ctx context.Context, model any) error {
group, ok := model.(*models.UserGroup)
if !ok || group == nil {
return errors.New("user groups admin: form model is not a user group")
}
if err := c.requireCodeFormat(ctx, group); err != nil {
return err
}
db := requestDB(ctx, c.app.db)
if db == nil {
return errors.New("user groups admin: gorm handle is missing")
}
var stored []struct{ Code *string }
err := db.Session(&gorm.Session{NewDB: true}).WithContext(ctx).
Table("user_groups").Select("code").Where("id = ?", group.ID).Scan(&stored).Error
if err != nil {
return err
}
if len(stored) != 1 {
return errors.New("user groups admin: the group being updated was not found")
}
if sameCode(stored[0].Code, group.Code) {
return nil
}
codes := classes.PrivilegedGroupCodes(c.app.config())
if !classes.IsPrivilegedCode(codes, stored[0].Code) && !classes.IsPrivilegedCode(codes, group.Code) {
return nil
}
return c.requirePrivilegedPermission(ctx)
}
// FormBeforeDelete refuses the delete of a privileged group without
// golem15.users.manage_privileged_groups: it would take the privilege from
// every member. The record is the stored row, loaded in the delete's
// transaction. A delete that goes ahead reads the members there; each gets
// a pact.MCPSubjectChanged permissions event after the delete commits,
// since the group's grants are gone (FormAfterDelete removes the
// memberships).
func (c usergroupsAdminController) FormBeforeDelete(ctx context.Context, model any) error {
group, ok := model.(*models.UserGroup)
if !ok || group == nil {
return errors.New("user groups admin: form model is not a user group")
}
if classes.IsPrivilegedCode(classes.PrivilegedGroupCodes(c.app.config()), group.Code) {
if err := c.requirePrivilegedPermission(ctx); err != nil {
return err
}
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return nil
}
members, err := groupMemberIDs(ctx, tx, group.ID)
if err != nil {
return err
}
c.permissionsChanged(ctx, tx, members)
return nil
}
// FormAfterDelete removes the memberships of the deleted group in the same
// transaction: users_groups has no foreign key that would do it. The member
// users stay.
func (usergroupsAdminController) FormAfterDelete(ctx context.Context, model any) error {
group, ok := model.(*models.UserGroup)
if !ok || group == nil {
return errors.New("user groups admin: form model is not a user group")
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return errors.New("user groups admin: a delete needs its transaction")
}
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).
Where("user_group_id = ?", group.ID).Delete(&models.UsersGroup{}).Error
}
// FormAfterUpdate tells the MCP endpoint that the members of the group may
// do something else now (the form saves the group's permissions): one
// pact.MCPSubjectChanged permissions event per member, the members read in
// the save's transaction and the events fired after it commits.
func (c usergroupsAdminController) FormAfterUpdate(ctx context.Context, model any) error {
group, ok := model.(*models.UserGroup)
if !ok || group == nil {
return errors.New("user groups admin: form model is not a user group")
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return errors.New("user groups admin: an update needs its transaction")
}
members, err := groupMemberIDs(ctx, tx, group.ID)
if err != nil {
return err
}
c.permissionsChanged(ctx, tx, members)
return nil
}
// permissionsChanged fires one permissions subject event per user after tx
// commits.
func (c usergroupsAdminController) permissionsChanged(ctx context.Context, tx *gorm.DB, userIDs []uint) {
if len(userIDs) == 0 {
return
}
app := c.app.application()
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
for _, id := range userIDs {
classes.FireSubjectChanged(ctx, app, classes.SubjectGuardUser, id, pact.MCPSubjectPermissions)
}
})
}
// groupMemberIDs reads the ids of the group's members through tx.
func groupMemberIDs(ctx context.Context, tx *gorm.DB, groupID uint) ([]uint, error) {
ids := []uint{}
err := tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).
Model(&models.UsersGroup{}).Where("user_group_id = ?", groupID).Order("user_id").Pluck("user_id", &ids).Error
return ids, err
}
// requirePrivilegedPermission answers nil when the administrator on ctx
// holds golem15.users.manage_privileged_groups, else the 403 of the screen.
// A context without a principal is refused.
func (usergroupsAdminController) requirePrivilegedPermission(ctx context.Context) error {
principal, _ := bouncer.User(ctx)
if cabana.Allows(principal, []string{classes.PermissionManagePrivilegedGroups}) {
return nil
}
const message = groupsLang + "privileged_forbidden"
return &cabana.ForbiddenError{Message: message, Details: map[string]any{"code": []string{message}}}
}
// requireCodeFormat answers 422 on code when it holds anything but letters,
// digits, underscore and hyphen. An empty code is left to the required rule.
func (c usergroupsAdminController) requireCodeFormat(ctx context.Context, group *models.UserGroup) error {
if group.Code == nil || *group.Code == "" || groupCodePattern.MatchString(*group.Code) {
return nil
}
message := "The code may only contain letters, numbers, dashes and underscores."
if tr := c.app.translator(); tr != nil {
const key = "golem15.user::lang.group.code_invalid"
if text := tr.Get(ctx, key, nil); text != "" && text != key {
message = text
}
}
return &cabana.ValidationError{Details: map[string]any{"code": []string{message}}}
}
// sameCode compares two nullable group codes, case-sensitively.
func sameCode(a, b *string) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
return *a == *b
}
// AdminPermissionOptions offers the rows of
// golem15_user_frontend_permissions, by tab and code, then the frontend
// permission codes activated plugins declare (classes.FrontendPermissionCatalog).
// None is locked.
func (c usergroupsAdminController) AdminPermissionOptions(ctx context.Context, field string) ([]cabana.PermissionOption, error) {
if field != permissionsField {
return nil, fmt.Errorf("user groups admin: unknown permission field %q", field)
}
db := requestDB(ctx, c.app.db)
if db == nil {
return nil, errors.New("user groups admin: gorm handle is missing")
}
return classes.FrontendPermissionCatalog(ctx, c.app.application(), db)
}
// AdminPermissionValues returns the group's stored permissions, read with
// the tolerance of models.ParsePermissionSet.
func (usergroupsAdminController) AdminPermissionValues(_ context.Context, field string, record any) (map[string]int, error) {
group, ok := record.(*models.UserGroup)
if field != permissionsField || !ok || group == nil {
return nil, fmt.Errorf("user groups admin: cannot read permission field %q", field)
}
if group.Permissions == nil {
return map[string]int{}, nil
}
set, err := models.ParsePermissionSet([]byte(*group.Permissions))
if err != nil {
return nil, err
}
values := make(map[string]int, len(set))
for code, value := range set {
values[code] = value
}
return values, nil
}
// AdminSetPermissionValues writes the validated set back as the JSON object
// PHP stores (checkbox mode: 1 per allowed code), or NULL for an empty set.
// The save writes the row.
func (usergroupsAdminController) AdminSetPermissionValues(_ context.Context, field string, record any, values map[string]int) error {
group, ok := record.(*models.UserGroup)
if field != permissionsField || !ok || group == nil {
return fmt.Errorf("user groups admin: cannot write permission field %q", field)
}
set := make(models.PermissionSet, len(values))
for code, value := range values {
set[code] = value
}
group.Permissions = set.Text()
return nil
}

View File

@@ -0,0 +1,7 @@
{{- /* Status hint above the user preview: one callout, or nothing (usersHintView). */ -}}
{{- if .Data.Title -}}
<div class="summer-callout summer-callout--{{ .Data.Kind }}" role="status">
<p class="summer-callout__title">{{ trans .Data.Title }}</p>
<p class="summer-callout__text">{{ trans .Data.Text }}</p>
</div>
{{- end -}}

View File

@@ -0,0 +1,14 @@
scopes:
groups:
label: golem15.user::lang.group.label
modelClass: Golem15\User\Models\UserGroup
nameFrom: name
scope: filterByGroup
created_date:
label: golem15.user::lang.user.created_at
type: daterange
column: created_at
activated:
label: golem15.user::lang.user.status_activated
type: switch
column: is_activated

View File

@@ -0,0 +1,25 @@
name: golem15.user::lang.user.label
form: ~/plugins/golem15/user/models/user/fields.yaml
modelClass: Golem15\User\Models\User
defaultRedirect: golem15/user/users
create:
redirect: golem15/user/users/preview/:id
redirectClose: golem15/user/users
update:
redirect: golem15/user/users/update/:id
redirectClose: golem15/user/users/preview/:id
preview:
headerPartial: hint
recordActions: [activate, unban, unsuspend, reset_two_factor]
messages:
create: golem15.user::lang.users.new_user
update: backend::lang.messages.form.update
saved: backend::lang.messages.form.saved
deleteConfirm: golem15.user::lang.users.delete_confirm
deleted: backend::lang.messages.form.deleted
edit: golem15.user::lang.users.update_details

View File

@@ -0,0 +1,25 @@
list: ~/plugins/golem15/user/models/user/columns.yaml
modelClass: Golem15\User\Models\User
title: golem15.user::lang.users.list_title
recordUrl: golem15/user/users/preview/:id
noRecordsMessage: backend::lang.list.no_records
recordsPerPage: 20
showCheckboxes: true
showSetup: true
filter: config_filter.yaml
toolbar:
buttons: [create, delete]
search:
prompt: backend::lang.list.search_prompt
bulkActions: [activate, deactivate, restore, ban, unban]
messages:
create: golem15.user::lang.users.new_user
empty: golem15.user::lang.users.list_empty
deleteConfirm: golem15.user::lang.users.delete_selected_confirm
deleted: backend::lang.messages.list.deleted
rowStateDeleted: golem15.user::lang.users.state_deactivated
rowStateNegative: golem15.user::lang.users.state_banned
rowStateDisabled: golem15.user::lang.users.state_not_activated

View File

@@ -0,0 +1,887 @@
package controllers
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"gocloud.dev/blob"
"gorm.io/gorm"
)
// PermissionAccessUsers is the backend permission of the Users screen, the
// PHP Users::$requiredPermissions.
const PermissionAccessUsers = "golem15.users.access_users"
// usersLang prefixes the phrase keys of the Users screen.
const usersLang = "golem15.user::lang.users."
// usersAdminController is the Winter Users backend controller: the list with
// its filters and row states, and the form. The screen and every write need
// golem15.users.access_users.
//
// app is resolved per call from the booted plugin. Nothing is cached: the
// database handle, the config and the privileged group list are read when a
// request needs them.
type usersAdminController struct {
app func() *backpack.App
}
func (usersAdminController) ID() string { return "golem15.user.users" }
func (usersAdminController) ModelName() string { return `Golem15\User\Models\User` }
func (usersAdminController) ConfigDir() string { return "controllers/users" }
func (usersAdminController) RequiredPermissions() []string {
return []string{PermissionAccessUsers}
}
func (usersAdminController) NewRecord() any { return &models.User{} }
// application returns the booted app, or nil before boot.
func (c usersAdminController) application() *backpack.App {
if c.app == nil {
return nil
}
return c.app()
}
// db is the application pool, or nil when the app has none.
func (c usersAdminController) db() *gorm.DB {
app := c.application()
if app == nil {
return nil
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok {
return nil
}
return gdb
}
// config is the application config, or nil before boot.
func (c usersAdminController) config() *compass.Config {
app := c.application()
if app == nil {
return nil
}
return app.Config
}
// ListExtendQuery and FormExtendQuery include deactivated (soft-deleted)
// users, the PHP listExtendQuery and formExtendQuery withTrashed().
func (usersAdminController) ListExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
return db.Unscoped()
}
func (usersAdminController) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
return db.Unscoped()
}
// ListRowStates is the PHP listInjectRowClass: deleted for a deactivated
// user, negative for a banned one, disabled for one who is not activated.
// The ban state of the whole page comes from one user_throttle query.
func (c usersAdminController) ListRowStates(ctx context.Context, db *gorm.DB, records []any) ([][]pact.RowState, error) {
ids := make([]uint, 0, len(records))
for _, record := range records {
user, ok := record.(*models.User)
if !ok || user == nil {
return nil, errors.New("users admin: list record is not a user")
}
ids = append(ids, user.ID)
}
banned, _, err := classes.ThrottleStates(classes.ContextWithThrottle(ctx, c.application()), db, ids)
if err != nil {
return nil, err
}
out := make([][]pact.RowState, len(records))
for i, record := range records {
user := record.(*models.User)
if user.DeletedAt.Valid {
out[i] = append(out[i], pact.RowStateDeleted)
}
if banned[user.ID] {
out[i] = append(out[i], pact.RowStateNegative)
}
if !user.IsActivated {
out[i] = append(out[i], pact.RowStateDisabled)
}
}
return out, nil
}
// FormVirtualFields are the form fields that are not columns of the form:
// the password with its confirmation, and the create-only invitation
// checkbox. The framework never fills or returns them; the Form hooks read
// them with cabana.VirtualFieldsFromContext.
func (usersAdminController) FormVirtualFields() []string {
return []string{"password", "password_confirmation", "send_invite"}
}
// FormRules are the rules of an admin save. They replace User.Rules(), which
// is the register contract and would ask every admin update for a confirmed
// password: a create needs a confirmed password, an update takes one only
// when the administrator types it (empty means unchanged). The minimum
// length is golem15.user.password.min_length.
func (c usersAdminController) FormRules(_ context.Context, op string) map[string]string {
length := "between:" + strconv.Itoa(c.configInt("golem15.user.password.min_length", 8)) + ",255"
password := "nullable|" + length + "|confirmed"
if op == "create" {
password = "required|" + length + "|confirmed"
}
return map[string]string{
"email": "required|between:6,255|email|unique:users",
"password": password,
}
}
// configInt reads a positive integer config value, else fallback.
func (c usersAdminController) configInt(key string, fallback int) int {
if cfg := c.config(); cfg != nil {
if n := cfg.Int(key); n > 0 {
return n
}
}
return fallback
}
// FilterOptions serves the choices of the groups filter (scope
// filterByGroup): every user group by name. Any other scope has no choices.
func (c usersAdminController) FilterOptions(scope string) []pact.Option {
if scope != models.FilterByGroup {
return nil
}
db := c.db()
if db == nil {
return nil
}
var groups []models.UserGroup
if err := db.Session(&gorm.Session{NewDB: true}).Order("name ASC, id ASC").Find(&groups).Error; err != nil {
return nil
}
out := make([]pact.Option, 0, len(groups))
for _, group := range groups {
out = append(out, pact.Option{Value: strconv.FormatUint(uint64(group.ID), 10), Label: group.Name})
}
return out
}
// guardPrivilegedMember protects the account of a privileged-group member
// against takeover. It answers nil when the administrator on ctx holds
// golem15.users.manage_privileged_groups, or when the user is not a member of
// a group whose code is in golem15.user.privileged_groups; otherwise it
// refuses with a 403 carrying message and details. Membership is read
// through the write's transaction. A failed query is returned as it is.
func (c usersAdminController) guardPrivilegedMember(ctx context.Context, userID uint, message string, details map[string]any) error {
principal, _ := bouncer.User(ctx)
if cabana.Allows(principal, []string{classes.PermissionManagePrivilegedGroups}) {
return nil
}
db := requestDB(ctx, c.db)
if db == nil {
return errors.New("users admin: gorm handle is missing")
}
privileged, err := classes.IsPrivilegedMember(ctx, db, classes.PrivilegedGroupCodes(c.config()), userID)
if err != nil {
return err
}
if !privileged {
return nil
}
return &cabana.ForbiddenError{Message: message, Details: details}
}
// FormBeforeUpdate starts with the takeover guard: a changed email or a
// submitted password on a member of a privileged group needs
// golem15.users.manage_privileged_groups. Everything else an update does
// comes after it, including clearing the proof of the address
// (email_verified_at) when the email changes.
func (c usersAdminController) FormBeforeUpdate(ctx context.Context, model any) error {
user, ok := model.(*models.User)
if !ok || user == nil {
return errors.New("users admin: form model is not a user")
}
if err := c.guardCredentials(ctx, user); err != nil {
return err
}
if err := c.requireFreeEmail(ctx, user); err != nil {
return err
}
// The proof of the address follows the address (D-27): a changed email
// is unproven until its owner proves it; a change of letter case only
// keeps it. cabana's Save writes the cleared column.
stored, err := c.storedEmail(ctx, user)
if err != nil {
return err
}
if !strings.EqualFold(stored, user.Email) {
user.EmailVerifiedAt = nil
}
changed, err := c.storePassword(ctx, user)
if err != nil {
return err
}
if changed {
// An admin password reset ends every session of the user, as the
// user's own change-password does. The cutoff is truncated to whole
// seconds, as in RevokeUserAccess, because JWT iat has whole-second
// precision, so the user's next login in that second is not refused.
// OAuth grants created before the untruncated instant are revoked in
// the save's transaction (the access-revoked event).
at := time.Now()
now := at.Truncate(time.Second)
user.TokensValidAfter = &now
tx, _ := cabana.TxFromContext(ctx)
if err := classes.FireAccessRevoked(ctx, c.application(), tx, []uint{user.ID}, at, classes.AccessRevokedPasswordSetByAdmin); err != nil {
return err
}
}
return nil
}
// FormAfterUpdate tells the MCP endpoint that what the user may do may have
// changed (their permissions or group memberships are saved by this form):
// one pact.MCPSubjectChanged permissions event for the user, fired after the
// save commits. Every MCP call re-checks anyway; the event only refreshes
// the tool list sooner.
func (c usersAdminController) FormAfterUpdate(ctx context.Context, model any) error {
user, ok := model.(*models.User)
if !ok || user == nil {
return errors.New("users admin: form model is not a user")
}
tx, _ := cabana.TxFromContext(ctx)
app := c.application()
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
classes.FireSubjectChanged(ctx, app, classes.SubjectGuardUser, user.ID, pact.MCPSubjectPermissions)
})
return nil
}
// FormBeforeCreate checks the email against deactivated users too and stores
// the hash of the submitted password. A user created here starts not
// activated: is_activated is never written from the form, and only the
// activate actions (or the invitation link) set it.
func (c usersAdminController) FormBeforeCreate(ctx context.Context, model any) error {
user, ok := model.(*models.User)
if !ok || user == nil {
return errors.New("users admin: form model is not a user")
}
if err := c.requireFreeEmail(ctx, user); err != nil {
return err
}
if _, err := c.storePassword(ctx, user); err != nil {
return err
}
user.IsActivated = false
// The column defaults to true; only an account created through a social
// login starts without a password of its own.
user.HasSelfSetPassword = true
return nil
}
// requireFreeEmail refuses an email another user already has, deactivated
// users included: the unique rule leaves deactivated rows out, and the
// database constraint does not.
func (c usersAdminController) requireFreeEmail(ctx context.Context, user *models.User) error {
db := requestDB(ctx, c.db)
if db == nil {
return errors.New("users admin: gorm handle is missing")
}
var taken int64
err := db.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped().
Model(&models.User{}).Where("email = ? AND id <> ?", user.Email, user.ID).Count(&taken).Error
if err != nil {
return err
}
if taken == 0 {
return nil
}
message := "The email has already been taken."
if tr := appTranslator(c.application()); tr != nil {
const key = "lagoon::validate.unique"
if text := tr.Get(ctx, key, map[string]string{"attribute": "email"}); text != "" && text != key {
message = text
}
}
return &cabana.ValidationError{Details: map[string]any{"email": []string{message}}}
}
// storePassword hashes a submitted password onto the user with
// golem15.user.password.bcrypt_cost and reports whether one was submitted.
// An absent or empty password changes nothing.
func (c usersAdminController) storePassword(ctx context.Context, user *models.User) (bool, error) {
values, _ := cabana.VirtualFieldsFromContext(ctx)
plain, _ := values["password"].(string)
if plain == "" {
return false, nil
}
hashed, err := bouncer.HashPassword(c.configInt("golem15.user.password.bcrypt_cost", 10), plain)
if err != nil {
return false, err
}
user.Password = hashed
return true, nil
}
// FormAfterCreate assigns a unique handle, fires user.Created
// (CreatedEventName) inside the create transaction, and sends the
// invitation when the send_invite checkbox was set: an activation code is
// issued inside the same transaction, and exactly one
// golem15.user::mail.invite message with the activation link leaves after
// the commit. A create that rolls back sends nothing.
func (c usersAdminController) FormAfterCreate(ctx context.Context, model any) error {
user, ok := model.(*models.User)
if !ok || user == nil {
return errors.New("users admin: form model is not a user")
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return errors.New("users admin: a create needs its transaction")
}
if err := classes.AssignHandle(ctx, tx.Session(&gorm.Session{NewDB: true}), user); err != nil {
return err
}
if app := c.application(); app != nil && app.Events != nil {
if err := app.Events.Fire(ctx, &classes.CreatedEvent{User: user, Tx: tx}); err != nil {
return fmt.Errorf("%s: %w", classes.CreatedEventName, err)
}
}
values, _ := cabana.VirtualFieldsFromContext(ctx)
if invite, _ := values["send_invite"].(bool); !invite {
return nil
}
code, err := classes.IssueActivationCode(ctx, tx.Session(&gorm.Session{NewDB: true}), user)
if err != nil {
return err
}
app := c.application()
id, email := user.ID, user.Email
vars := mailVars(displayName(user), activationLink(app, id, code), strconv.FormatUint(uint64(id), 10)+"!"+code)
vars["login"], vars["Login"] = email, email
hours := c.configInt("golem15.user.activation.activation_ttl_hours", 72)
vars["hours"], vars["Hours"] = hours, hours
template := mailName(ctx, app, user, "golem15.user::mail.invite")
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
sendTemplateVars(ctx, app, template, email, vars)
})
return nil
}
// groupsField is the form's group membership field.
const groupsField = "groups"
// AdminFieldRelations binds the organisation picker and the groups field.
// organisation_id is a protected column, so the contract opts in to writing
// it through this one field; the submitted id is still checked against the
// options. A save that changes the organisation (to another one or to none)
// clears organisation_role (ClearOnChange) unless the same save writes it.
// groups is the users_groups pivot: a save that carries the field
// replaces the user's memberships, and AdminRelationLocks decides which of
// them the administrator may change.
func (usersAdminController) AdminFieldRelations() []cabana.FieldRelationContract {
return []cabana.FieldRelationContract{
{
Field: "organisation",
Kind: "belongsTo",
NewRelated: func() any { return &models.Organisation{} },
ForeignKey: "organisation_id",
LabelColumn: "name",
WritableForeignKey: true,
ClearOnChange: []string{"organisation_role"},
},
{
Field: groupsField,
Kind: "belongsToMany",
NewRelated: func() any { return &models.UserGroup{} },
NewPivot: func() any { return &models.UsersGroup{} },
ParentForeignKey: "user_id",
RelatedForeignKey: "user_group_id",
LabelColumn: "name",
},
}
}
// AdminRelationLocks locks the privileged groups in the groups field for an
// administrator who lacks golem15.users.manage_privileged_groups: the
// framework shows them locked and answers 403, before any row is written, to
// a create or update that would add or remove one. Membership of a
// privileged group makes a site administrator, so golem15.users.access_users
// alone must not be able to grant or revoke it. The privileged codes come
// from golem15.user.privileged_groups on every call and the group ids are
// read through the write's transaction when there is one. An administrator
// without a principal on the context gets the locks. Every other field has
// none.
func (c usersAdminController) AdminRelationLocks(ctx context.Context, field string) (cabana.RelationLock, error) {
if field != groupsField {
return cabana.RelationLock{}, nil
}
principal, _ := bouncer.User(ctx)
if cabana.Allows(principal, []string{classes.PermissionManagePrivilegedGroups}) {
return cabana.RelationLock{}, nil
}
db := requestDB(ctx, c.db)
if db == nil {
return cabana.RelationLock{}, errors.New("users admin: gorm handle is missing")
}
ids, err := classes.PrivilegedGroupIDs(ctx, db, classes.PrivilegedGroupCodes(c.config()))
if err != nil {
return cabana.RelationLock{}, err
}
return cabana.RelationLock{IDs: ids, Message: usersLang + "privileged_group_forbidden"}, nil
}
// permissionsField is the form's permission editor field.
const permissionsField = "permissions"
// AdminPermissionOptions offers the rows of
// golem15_user_frontend_permissions, by tab and code, then the frontend
// permission codes activated plugins declare (classes.FrontendPermissionCatalog).
// None is locked.
func (c usersAdminController) AdminPermissionOptions(ctx context.Context, field string) ([]cabana.PermissionOption, error) {
if field != permissionsField {
return nil, fmt.Errorf("users admin: unknown permission field %q", field)
}
db := requestDB(ctx, c.db)
if db == nil {
return nil, errors.New("users admin: gorm handle is missing")
}
return classes.FrontendPermissionCatalog(ctx, c.application(), db)
}
// AdminPermissionValues returns the user's own stored permissions.
func (usersAdminController) AdminPermissionValues(_ context.Context, field string, record any) (map[string]int, error) {
user, ok := record.(*models.User)
if field != permissionsField || !ok || user == nil {
return nil, fmt.Errorf("users admin: cannot read permission field %q", field)
}
values := make(map[string]int, len(user.Permissions))
for code, value := range user.Permissions {
values[code] = value
}
return values, nil
}
// AdminSetPermissionValues puts the validated set on the user; the save
// writes the row. Zero values are left out on write (PermissionSet.Value).
func (usersAdminController) AdminSetPermissionValues(_ context.Context, field string, record any, values map[string]int) error {
user, ok := record.(*models.User)
if field != permissionsField || !ok || user == nil {
return fmt.Errorf("users admin: cannot write permission field %q", field)
}
set := make(models.PermissionSet, len(values))
for code, value := range values {
set[code] = value
}
user.Permissions = set
return nil
}
// storedEmail reads the stored email of the user being updated, before the
// form's values are saved.
func (c usersAdminController) storedEmail(ctx context.Context, user *models.User) (string, error) {
db := requestDB(ctx, c.db)
if db == nil {
return "", errors.New("users admin: gorm handle is missing")
}
var stored []string
err := db.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped().
Model(&models.User{}).Where("id = ?", user.ID).Pluck("email", &stored).Error
if err != nil {
return "", err
}
if len(stored) != 1 {
return "", errors.New("users admin: the user being updated was not found")
}
return stored[0], nil
}
// guardCredentials compares the email the save would write with the stored
// one and looks for a submitted password, then asks guardPrivilegedMember
// for the fields that would change.
func (c usersAdminController) guardCredentials(ctx context.Context, user *models.User) error {
stored, err := c.storedEmail(ctx, user)
if err != nil {
return err
}
const message = usersLang + "privileged_member_forbidden"
details := map[string]any{}
if stored != user.Email {
details["email"] = []string{message}
}
if values, ok := cabana.VirtualFieldsFromContext(ctx); ok {
if password, _ := values["password"].(string); password != "" {
details["password"] = []string{message}
}
}
if len(details) == 0 {
return nil
}
return c.guardPrivilegedMember(ctx, user.ID, message, details)
}
// FormBeforeDelete refuses the delete of a privileged-group member without
// golem15.users.manage_privileged_groups. The framework calls it for the
// form's delete and once per record inside the bulk delete's transaction, so
// one refused record rolls the whole selection back.
func (c usersAdminController) FormBeforeDelete(ctx context.Context, model any) error {
user, ok := model.(*models.User)
if !ok || user == nil {
return errors.New("users admin: form model is not a user")
}
return c.guardPrivilegedMember(ctx, user.ID, usersLang+"privileged_member_delete_forbidden", nil)
}
// FormAfterDelete makes the delete permanent, the PHP update_onDelete and
// bulk delete forceDelete(): the list keeps deactivated users, so the
// framework's soft delete alone would change nothing an administrator can
// see. The user's throttle rows, group memberships and attachments go in the
// same transaction; the files' blobs are removed after it commits.
// FormBeforeDelete has already refused a privileged-group member.
func (c usersAdminController) FormAfterDelete(ctx context.Context, model any) error {
user, ok := model.(*models.User)
if !ok || user == nil {
return errors.New("users admin: form model is not a user")
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return errors.New("users admin: a delete needs its transaction")
}
if err := FireDeletingEvent(ctx, c.application(), user, tx); err != nil {
return fmt.Errorf("%s: %w", classes.DeletingEventName, err)
}
if err := classes.ForceDeleteCleanup(ctx, tx, c.bucket(), user); err != nil {
return err
}
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped().
Where("id = ?", user.ID).Delete(&models.User{}).Error
}
// bucket is the application's blob bucket, or nil when none is published.
func (c usersAdminController) bucket() *blob.Bucket {
app := c.application()
if app == nil {
return nil
}
bucket, ok := app.Lookup[*blob.Bucket]()
if !ok {
return nil
}
return bucket
}
// usersOf asserts that every record of a bulk action is a user.
func usersOf(records []any) ([]*models.User, error) {
users := make([]*models.User, 0, len(records))
for _, record := range records {
user, ok := record.(*models.User)
if !ok || user == nil {
return nil, errors.New("users admin: bulk record is not a user")
}
users = append(users, user)
}
return users, nil
}
// AdminBulkActions are the PHP index_onBulkAction cases next to the built-in
// delete: activate, deactivate, restore, ban and unban. Each needs only
// golem15.users.access_users, changes the users it applies to and reports how
// many that were. The fixed success phrase is returned only when every
// selected user was changed; otherwise the framework shows its count text,
// which never overstates. None of them touches users_groups.
func (c usersAdminController) AdminBulkActions() []pact.AdminBulkAction {
bulk := func(name string, run func(ctx context.Context, tx *gorm.DB, users []*models.User) (int, error)) pact.AdminBulkAction {
return pact.AdminBulkAction{
Name: name,
Label: usersLang + name + "_selected",
Confirm: usersLang + name + "_selected_confirm",
Permissions: []string{PermissionAccessUsers},
Run: func(ctx context.Context, in pact.AdminBulkActionInput) (pact.AdminBulkActionResult, error) {
users, err := usersOf(in.Records)
if err != nil {
return pact.AdminBulkActionResult{}, err
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return pact.AdminBulkActionResult{}, errors.New("users admin: a bulk action needs its transaction")
}
affected, err := run(classes.ContextWithThrottle(ctx, c.application()), tx, users)
if err != nil {
return pact.AdminBulkActionResult{}, err
}
result := pact.AdminBulkActionResult{Affected: affected}
if affected == len(users) {
result.Message = usersLang + name + "_selected_success"
}
return result, nil
},
}
}
return []pact.AdminBulkAction{
bulk("activate", classes.ActivateUsers),
bulk("deactivate", c.deactivateUsers),
bulk("restore", classes.RestoreUsers),
bulk("ban", c.banUsers),
bulk("unban", classes.UnbanUsers),
}
}
// banUsers runs classes.BanUsers unchanged in the action's transaction and
// fires the access-revoked event there for the users it newly banned (banned
// after, not before), so their OAuth grants are revoked with the ban and
// their MCP sessions end once it commits. A listener error rolls the action
// back.
func (c usersAdminController) banUsers(ctx context.Context, tx *gorm.DB, users []*models.User) (int, error) {
ids := make([]uint, 0, len(users))
for _, user := range users {
if user != nil && user.ID != 0 {
ids = append(ids, user.ID)
}
}
before, _, err := classes.ThrottleStates(ctx, tx, ids)
if err != nil {
return 0, err
}
at := time.Now()
changed, err := classes.BanUsers(ctx, tx, users)
if err != nil {
return 0, err
}
after, _, err := classes.ThrottleStates(ctx, tx, ids)
if err != nil {
return 0, err
}
newly := make([]uint, 0, len(ids))
for _, id := range ids {
if after[id] && !before[id] {
newly = append(newly, id)
}
}
if len(newly) > 0 {
if err := classes.FireAccessRevoked(ctx, c.application(), tx, newly, at, classes.AccessRevokedBan); err != nil {
return 0, err
}
}
return changed, nil
}
// deactivateUsers runs classes.DeactivateUsers unchanged and then fires
// user.Deactivating, in the action's transaction, for every selected user
// that was not deactivated before. A listener error rolls the action back.
func (c usersAdminController) deactivateUsers(ctx context.Context, tx *gorm.DB, users []*models.User) (int, error) {
pending := make([]*models.User, 0, len(users))
for _, user := range users {
if user != nil && user.ID != 0 && !user.DeletedAt.Valid {
pending = append(pending, user)
}
}
changed, err := classes.DeactivateUsers(ctx, tx, users)
if err != nil {
return 0, err
}
for _, user := range pending {
if err := FireDeactivatingEvent(ctx, c.application(), user, tx); err != nil {
return 0, err
}
}
return changed, nil
}
// throttleState reads whether one user is banned and whether they are
// suspended, through the write's transaction when there is one.
func (c usersAdminController) throttleState(ctx context.Context, userID uint) (banned, suspended bool, err error) {
db := requestDB(ctx, c.db)
if db == nil {
return false, false, errors.New("users admin: gorm handle is missing")
}
bannedSet, suspendedSet, err := classes.ThrottleStates(classes.ContextWithThrottle(ctx, c.application()), db, []uint{userID})
if err != nil {
return false, false, err
}
return bannedSet[userID], suspendedSet[userID], nil
}
// AdminRecordActions are the PHP preview handlers onActivate, onUnban and
// onUnsuspendUser, plus reset_two_factor. Each is offered only while it
// applies; the checks only read. There is no impersonate action and no
// guest action.
//
// reset_two_factor ("Reset 2FA") needs classes.PermissionResetTwoFactor and
// asks for a danger confirmation. It is offered only when a two-factor
// plugin published a classes.TwoFactorAdmin (looked up per request) and the
// user has a second factor; Run hands the record to that service's Reset in
// the action's transaction.
func (c usersAdminController) AdminRecordActions() []pact.AdminRecordAction {
asUser := func(record any) (*models.User, error) {
user, ok := record.(*models.User)
if !ok || user == nil {
return nil, errors.New("users admin: action record is not a user")
}
return user, nil
}
action := func(name, label, confirm, success string,
applies func(ctx context.Context, user *models.User) (bool, error),
run func(ctx context.Context, tx *gorm.DB, user *models.User) error,
) pact.AdminRecordAction {
return pact.AdminRecordAction{
Name: name,
Label: usersLang + label,
Confirm: usersLang + confirm,
Permissions: []string{PermissionAccessUsers},
Applies: func(ctx context.Context, record any) (bool, error) {
user, err := asUser(record)
if err != nil {
return false, err
}
return applies(ctx, user)
},
Run: func(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
user, err := asUser(in.Record)
if err != nil {
return pact.AdminRecordActionResult{}, err
}
tx, ok := cabana.TxFromContext(ctx)
if !ok {
return pact.AdminRecordActionResult{}, errors.New("users admin: a record action needs its transaction")
}
if err := run(ctx, tx, user); err != nil {
return pact.AdminRecordActionResult{}, err
}
return pact.AdminRecordActionResult{Message: usersLang + success}, nil
},
}
}
return []pact.AdminRecordAction{
action("activate", "activate_user", "activate_confirm", "activated_success",
func(_ context.Context, user *models.User) (bool, error) { return !user.IsActivated, nil },
func(ctx context.Context, tx *gorm.DB, user *models.User) error {
_, err := classes.ActivateUsers(ctx, tx, []*models.User{user})
return err
}),
action("unban", "unban_user", "unban_confirm", "unbanned_success",
func(ctx context.Context, user *models.User) (bool, error) {
banned, _, err := c.throttleState(ctx, user.ID)
return banned, err
},
func(ctx context.Context, tx *gorm.DB, user *models.User) error {
_, err := classes.UnbanUsers(ctx, tx, []*models.User{user})
return err
}),
action("unsuspend", "unsuspend_user", "unsuspend_confirm", "unsuspend_success",
func(ctx context.Context, user *models.User) (bool, error) {
_, suspended, err := c.throttleState(ctx, user.ID)
return suspended, err
},
func(ctx context.Context, tx *gorm.DB, user *models.User) error {
return classes.UnsuspendUser(ctx, tx, user.ID)
}),
c.resetTwoFactorAction(action),
}
}
// resetTwoFactorAction builds the reset_two_factor record action with the
// shared action builder, behind classes.PermissionResetTwoFactor and marked
// as dangerous. A member of a privileged group keeps the takeover guard of
// a password change and a delete: without
// golem15.users.manage_privileged_groups Run refuses with a 403 and its
// message before Reset runs, inside the action's transaction.
func (c usersAdminController) resetTwoFactorAction(action func(name, label, confirm, success string,
applies func(ctx context.Context, user *models.User) (bool, error),
run func(ctx context.Context, tx *gorm.DB, user *models.User) error,
) pact.AdminRecordAction) pact.AdminRecordAction {
reset := action("reset_two_factor", "reset_two_factor", "reset_two_factor_confirm", "reset_two_factor_success",
func(ctx context.Context, user *models.User) (bool, error) {
svc, ok := c.twoFactorAdmin()
if !ok {
return false, nil
}
db := requestDB(ctx, c.db)
if db == nil {
return false, errors.New("users admin: gorm handle is missing")
}
return svc.HasTwoFactor(ctx, db, user.ID)
},
func(ctx context.Context, tx *gorm.DB, user *models.User) error {
svc, ok := c.twoFactorAdmin()
if !ok {
return errors.New("users admin: no two-factor plugin publishes classes.TwoFactorAdmin")
}
if err := c.guardPrivilegedMember(ctx, user.ID, usersLang+"privileged_member_reset_two_factor_forbidden", nil); err != nil {
return err
}
return svc.Reset(ctx, tx, user)
})
reset.Permissions = []string{classes.PermissionResetTwoFactor}
reset.Danger = true
return reset
}
// twoFactorAdmin looks up the classes.TwoFactorAdmin a two-factor plugin
// published, on every call, so a plugin that boots later is still found.
func (c usersAdminController) twoFactorAdmin() (classes.TwoFactorAdmin, bool) {
app := c.application()
if app == nil {
return nil, false
}
svc, ok := app.Lookup[classes.TwoFactorAdmin]()
if !ok || svc == nil {
return nil, false
}
return svc, true
}
// usersHintView is the view model of controllers/users/_hint.htm, the status
// callout above the preview: the callout kind (danger or warning) and the
// phrase keys of its title and text. It is empty when no state applies, and
// the template then renders nothing.
type usersHintView struct {
Kind string
Title string
Text string
}
// PartialData serves the preview header partial `hint`: one callout by
// precedence banned, deactivated, not activated, suspended (the PHP
// _hint_banned, _hint_trashed and _hint_activate partials plus a suspension
// hint). Any other partial name is an error.
func (c usersAdminController) PartialData(ctx context.Context, name string, record any) (any, error) {
if name != "hint" {
return nil, fmt.Errorf("users admin: unknown partial %q", name)
}
user, ok := record.(*models.User)
if !ok || user == nil {
return usersHintView{}, nil
}
banned, suspended, err := c.throttleState(ctx, user.ID)
if err != nil {
return nil, err
}
switch {
case banned:
return usersHintView{Kind: "danger", Title: usersLang + "banned_hint_title", Text: usersLang + "banned_hint_desc"}, nil
case user.DeletedAt.Valid:
return usersHintView{Kind: "danger", Title: usersLang + "trashed_hint_title", Text: usersLang + "trashed_hint_desc"}, nil
case !user.IsActivated:
return usersHintView{Kind: "warning", Title: usersLang + "activate_warning_title", Text: usersLang + "activate_warning_desc"}, nil
case suspended:
return usersHintView{Kind: "warning", Title: usersLang + "suspended_hint_title", Text: usersLang + "suspended_hint_desc"}, nil
}
return usersHintView{}, nil
}

110
deactivating_event_test.go Normal file
View File

@@ -0,0 +1,110 @@
package user
import (
"context"
"errors"
"net/http"
"sync"
"testing"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"gorm.io/gorm"
)
// TestDeactivatingEvent pins user.Deactivating (D-05): the admin deactivate
// bulk action fires one event per newly deactivated user inside the
// action's transaction, already deactivated users fire none, a listener
// error rolls the whole action back, and the event name is the constant.
func TestDeactivatingEvent(t *testing.T) {
if classes.DeactivatingEventName != "user.Deactivating" {
t.Fatalf("DeactivatingEventName = %q", classes.DeactivatingEventName)
}
env := newAdminEnv(t)
token := env.admin(t, permAccessUsers)
var mu sync.Mutex
var fired []uint
var failFor uint
var txSawDeactivation = map[uint]bool{}
env.app.Events.Listen[*classes.DeactivatingEvent]("test.deactivating", func(ctx context.Context, e *classes.DeactivatingEvent) error {
mu.Lock()
defer mu.Unlock()
if e.User == nil || e.Tx == nil {
return errors.New("event without user or transaction")
}
fired = append(fired, e.User.ID)
// Inside the action's transaction the row is already deactivated.
var deleted int64
if err := e.Tx.Session(&gorm.Session{NewDB: true}).Unscoped().Model(&models.User{}).
Where("id = ? AND deleted_at IS NOT NULL", e.User.ID).Count(&deleted).Error; err != nil {
return err
}
txSawDeactivation[e.User.ID] = deleted == 1
if e.User.ID == failFor {
return errors.New("listener refuses")
}
return nil
})
reset := func() {
mu.Lock()
defer mu.Unlock()
fired, txSawDeactivation = nil, map[uint]bool{}
}
a, b := env.seedUser(t, "deact-a", nil), env.seedUser(t, "deact-b", nil)
if rec := env.bulk(t, token, "deactivate", a, b); rec.Code != http.StatusOK {
t.Fatalf("deactivate: %d %s", rec.Code, rec.Body.String())
}
mu.Lock()
if len(fired) != 2 || !txSawDeactivation[a.ID] || !txSawDeactivation[b.ID] {
t.Fatalf("events %v, seen in the transaction %v", fired, txSawDeactivation)
}
mu.Unlock()
for _, u := range []*models.User{a, b} {
if row := env.reload(t, u.ID); row == nil || !row.DeletedAt.Valid {
t.Fatalf("user %d not deactivated", u.ID)
}
}
// Already deactivated users fire nothing; a mixed selection fires only
// for the newly deactivated one.
reset()
c := env.seedUser(t, "deact-c", nil)
if rec := env.bulk(t, token, "deactivate", a, c); rec.Code != http.StatusOK {
t.Fatalf("mixed deactivate: %d %s", rec.Code, rec.Body.String())
}
mu.Lock()
if len(fired) != 1 || fired[0] != c.ID {
t.Fatalf("mixed selection fired %v, want only %d", fired, c.ID)
}
mu.Unlock()
// A listener error rolls the whole action back.
reset()
d, e := env.seedUser(t, "deact-d", nil), env.seedUser(t, "deact-e", nil)
failFor = e.ID
if rec := env.bulk(t, token, "deactivate", d, e); rec.Code < 400 {
t.Fatalf("deactivate with a refusing listener: %d %s", rec.Code, rec.Body.String())
}
failFor = 0
for _, u := range []*models.User{d, e} {
if row := env.reload(t, u.ID); row == nil || row.DeletedAt.Valid {
t.Fatalf("user %d deactivated although a listener refused", u.ID)
}
}
// Other bulk actions fire nothing.
reset()
if rec := env.bulk(t, token, "restore", a); rec.Code != http.StatusOK {
t.Fatalf("restore: %d %s", rec.Code, rec.Body.String())
}
if rec := env.bulk(t, token, "activate", d); rec.Code != http.StatusOK {
t.Fatalf("activate: %d %s", rec.Code, rec.Body.String())
}
mu.Lock()
if len(fired) != 0 {
t.Fatalf("restore and activate fired %v", fired)
}
mu.Unlock()
}

1318
device_auth_test.go Normal file

File diff suppressed because it is too large Load Diff

320
device_flow_smoke_test.go Normal file
View File

@@ -0,0 +1,320 @@
package user
import (
"encoding/json"
"net/http"
"net/http/httptest"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
"gorm.io/gorm"
)
var deviceShortCodeRE = regexp.MustCompile(`^[2-9A-HJKMNP-Z]{4}-[2-9A-HJKMNP-Z]{4}$`)
// TestDeviceCodesSmoke pins the device token, the short code, its
// normalisation and the auth_url template. No database.
func TestDeviceCodesSmoke(t *testing.T) {
seen := map[string]bool{}
for range 1000 {
tok, err := classes.NewDeviceToken()
if err != nil {
t.Fatal(err)
}
if len(tok) != 64 || strings.Trim(tok, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") != "" {
t.Fatalf("token %q is not 64 base64url characters", tok)
}
if seen[tok] {
t.Fatalf("token %q repeated", tok)
}
seen[tok] = true
code, err := classes.NewDeviceShortCode()
if err != nil {
t.Fatal(err)
}
if !deviceShortCodeRE.MatchString(code) {
t.Fatalf("short code %q", code)
}
}
for in, want := range map[string]string{
"abcd-efgh": "ABCD-EFGH",
"ABCDEFGH": "ABCD-EFGH",
" ab cd ef gh ": "ABCD-EFGH",
"2345-6789": "2345-6789",
} {
if got, ok := classes.NormalizeDeviceShortCode(in); !ok || got != want {
t.Fatalf("normalize %q = %q %v, want %q", in, got, ok, want)
}
}
for _, in := range []string{"ABCDEFG", "ABCDEFGHJ", "ABCDEFGO", "ABCDEFGI", "ABCDEFGL", "ABCDEFG0", "ABCDEFG1", ""} {
if got, ok := classes.NormalizeDeviceShortCode(in); ok {
t.Fatalf("normalize %q accepted as %q", in, got)
}
}
app := backpack.New(sessionConfig(t))
if got := classes.DeviceAuthURL(app, "tok"); got != "/device/scan/tok" {
t.Fatalf("auth_url without urls = %q", got)
}
if err := app.Config.Set("app.url", "https://api.example.test/"); err != nil {
t.Fatal(err)
}
if got := classes.DeviceAuthURL(app, "tok"); got != "https://api.example.test/device/scan/tok" {
t.Fatalf("auth_url from app.url = %q", got)
}
if err := app.Config.Set("golem15.user.frontend_url", "https://www.example.test/"); err != nil {
t.Fatal(err)
}
if got := classes.DeviceAuthURL(app, "tok"); got != "https://www.example.test/device/scan/tok" {
t.Fatalf("auth_url from frontend_url = %q", got)
}
if err := app.Config.Set("golem15.user.device_auth.auth_url", "{frontend_url}/link?device={token}"); err != nil {
t.Fatal(err)
}
if got := classes.DeviceAuthURL(app, "tok"); got != "https://www.example.test/link?device=tok" {
t.Fatalf("auth_url from a custom template = %q", got)
}
if got := classes.DeviceAuthTTL(app); got != 5*time.Minute {
t.Fatalf("default ttl = %s", got)
}
tv := "Living room TV"
for _, c := range []struct {
stored *string
ua string
want string
}{
{&tv, "Mozilla/5.0 (iPhone)", tv},
{nil, "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0)", "iPhone"},
{nil, "Mozilla/5.0 (iPad; CPU OS 17_0)", "iPad"},
{nil, "Mozilla/5.0 (Linux; Android 14)", "Android Device"},
{nil, "Mozilla/5.0 (Windows NT 10.0)", "Windows PC"},
{nil, "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0)", "Mac"},
{nil, "Mozilla/5.0 (X11; Linux x86_64)", "Linux PC"},
{nil, "curl/8.0", "Unknown Device"},
} {
if got := classes.DeviceDisplayName(c.stored, c.ua); got != c.want {
t.Fatalf("display name of %q = %q, want %q", c.ua, got, c.want)
}
}
}
// deviceCall runs one device handler with an optional bearer token and JSON
// body; pathToken fills {token} or {id}.
func deviceCall(t *testing.T, h http.HandlerFunc, method, path, bearerToken, body string, pathValues map[string]string) *httptest.ResponseRecorder {
t.Helper()
var req *http.Request
if body != "" {
req = httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
} else {
req = httptest.NewRequest(method, path, nil)
}
req.Host = "example.com"
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) SmokeTV")
if bearerToken != "" {
req.Header.Set("Authorization", "Bearer "+bearerToken)
}
for k, v := range pathValues {
req.SetPathValue(k, v)
}
rec := httptest.NewRecorder()
h(rec, req)
return rec
}
type deviceInitiated struct {
Token string `json:"token"`
ShortCode string `json:"short_code"`
AuthURL string `json:"auth_url"`
ExpiresAt string `json:"expires_at"`
}
func initiateDevice(t *testing.T, app *backpack.App, name string) deviceInitiated {
t.Helper()
body := `{}`
if name != "" {
body = `{"device_name":"` + name + `"}`
}
rec := deviceCall(t, controllers.DeviceInitiate(app), http.MethodPost, "/_user/api/v1/devices/initiate", "", body, nil)
if rec.Code != http.StatusOK {
t.Fatalf("initiate = %d %s", rec.Code, rec.Body.String())
}
var out struct {
Success bool `json:"success"`
Data deviceInitiated `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || !out.Success {
t.Fatalf("initiate body %s: %v", rec.Body.String(), err)
}
return out.Data
}
func deviceStatus(t *testing.T, app *backpack.App, token string) (int, map[string]any) {
t.Helper()
rec := deviceCall(t, controllers.DeviceStatus(app), http.MethodGet, "/_user/api/v1/devices/status/"+token, "", "", map[string]string{"token": token})
var body map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &body)
return rec.Code, body
}
func authorizeDevice(t *testing.T, app *backpack.App, bearerToken, body string) *httptest.ResponseRecorder {
t.Helper()
return deviceCall(t, controllers.DeviceAuthorize(app), http.MethodPost, "/_user/api/v1/devices/authorize", bearerToken, body, nil)
}
func deviceRow(t *testing.T, gdb *gorm.DB, token string) models.DeviceAuthSession {
t.Helper()
var row models.DeviceAuthSession
if err := gdb.Where("token = ?", classes.HashAPIToken(token)).Take(&row).Error; err != nil {
t.Fatal(err)
}
return row
}
func statusData(body map[string]any) map[string]any {
data, _ := body["data"].(map[string]any)
return data
}
// TestDeviceFlowSmoke drives initiate, authorize and the one-time hand-over
// on Postgres.
func TestDeviceFlowSmoke(t *testing.T) {
if testing.Short() {
t.Skip("Postgres (testcontainers)")
}
app, gdb := sessionApp(t, "0s")
email := "device-owner-" + strconv.FormatInt(time.Now().UnixNano(), 10) + "@example.test"
session := loginToken(t, app, gdb, email)
var owner models.User
if err := gdb.Where("email = ?", email).Take(&owner).Error; err != nil {
t.Fatal(err)
}
dev := initiateDevice(t, app, "Living room TV")
if len(dev.Token) != 64 || !deviceShortCodeRE.MatchString(dev.ShortCode) || !strings.HasSuffix(dev.AuthURL, "/device/scan/"+dev.ShortCode) || strings.Contains(dev.AuthURL, dev.Token) || !strings.HasSuffix(dev.ExpiresAt, "+00:00") {
t.Fatalf("initiate data = %+v", dev)
}
row := deviceRow(t, gdb, dev.Token)
if row.TokenHash != classes.HashAPIToken(dev.Token) || row.Status != models.DeviceStatusPending || row.UserID != nil ||
row.DeviceName == nil || *row.DeviceName != "Living room TV" || row.DeviceUserAgent == nil {
t.Fatalf("stored row = %+v", row)
}
if code, body := deviceStatus(t, app, dev.Token); code != http.StatusOK || body["success"] != true || statusData(body)["status"] != "pending" {
t.Fatalf("pending status = %d %v", code, body)
}
if code, body := deviceStatus(t, app, strings.Repeat("z", 64)); code != http.StatusNotFound || body["error"] != "Session not found" {
t.Fatalf("unknown status = %d %v", code, body)
}
// Authorize needs a session, answering PHP's 401 body.
if rec := authorizeDevice(t, app, "", `{"short_code":"`+dev.ShortCode+`"}`); rec.Code != http.StatusUnauthorized || rec.Body.String() != `{"error":"Unauthorized"}` {
t.Fatalf("authorize without a session = %d %s", rec.Code, rec.Body.String())
}
if rec := authorizeDevice(t, app, session, `{"short_code":"ABC"}`); rec.Code != http.StatusUnprocessableEntity || rec.Body.String() != `{"error":"Please enter a valid 8-character code"}` {
t.Fatalf("short code of 3 = %d %s", rec.Code, rec.Body.String())
}
lower := strings.ToLower(dev.ShortCode)
if rec := authorizeDevice(t, app, session, `{"short_code":"`+lower+`"}`); rec.Code != http.StatusOK || rec.Body.String() != `{"message":"Device authorized successfully","success":true}` {
t.Fatalf("authorize = %d %s", rec.Code, rec.Body.String())
}
if rec := authorizeDevice(t, app, session, `{"short_code":"`+lower+`"}`); rec.Code != http.StatusOK {
t.Fatalf("authorizing again for the same user = %d %s", rec.Code, rec.Body.String())
}
// The first poll after confirmation receives the token, once.
code, body := deviceStatus(t, app, dev.Token)
data := statusData(body)
if code != http.StatusOK || data["status"] != "confirmed" || data["message"] != "Device authorized - complete login" || data["user_id"] != float64(owner.ID) {
t.Fatalf("hand-over = %d %v", code, body)
}
jwtToken, _ := data["token"].(string)
sub, _, _, jti, err := bouncer.VerifyClaims(jwtToken, sessionSecret)
if err != nil || sub != strconv.FormatUint(uint64(owner.ID), 10) {
t.Fatalf("device token sub=%q err=%v", sub, err)
}
if user, _ := data["user"].(map[string]any); user["email"] != email {
t.Fatalf("hand-over user = %v", data["user"])
}
row = deviceRow(t, gdb, dev.Token)
if row.Status != models.DeviceStatusUsed || row.JWTJTI == nil || *row.JWTJTI != jti || row.UsedAt == nil {
t.Fatalf("row after hand-over = %+v", row)
}
if _, body := deviceStatus(t, app, dev.Token); statusData(body)["status"] != "used" || statusData(body)["token"] != nil {
t.Fatalf("second poll = %v", body)
}
// The used session is past nothing: even past expires_at it stays used.
if err := gdb.Model(&models.DeviceAuthSession{}).Where("id = ?", row.ID).Update("expires_at", time.Now().Add(-time.Hour)).Error; err != nil {
t.Fatal(err)
}
if _, body := deviceStatus(t, app, dev.Token); statusData(body)["status"] != "used" {
t.Fatalf("used session past expires_at = %v", body)
}
// A used session cannot be authorized again.
if rec := authorizeDevice(t, app, session, `{"token":"`+dev.Token+`"}`); rec.Code != http.StatusBadRequest || rec.Body.String() != `{"error":"Invalid or expired code"}` {
t.Fatalf("authorize a used session = %d %s", rec.Code, rec.Body.String())
}
// Ten concurrent polls of a confirmed session yield exactly one token.
race := initiateDevice(t, app, "")
if rec := authorizeDevice(t, app, session, `{"token":"`+race.Token+`"}`); rec.Code != http.StatusOK {
t.Fatalf("authorize by token = %d %s", rec.Code, rec.Body.String())
}
var (
wg sync.WaitGroup
mu sync.Mutex
tokens int
used int
)
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
_, body := deviceStatus(t, app, race.Token)
d := statusData(body)
mu.Lock()
defer mu.Unlock()
if tok, _ := d["token"].(string); tok != "" {
tokens++
} else if d["status"] == "used" {
used++
}
}()
}
wg.Wait()
if tokens != 1 || used != 9 {
t.Fatalf("concurrent polls: %d tokens, %d used", tokens, used)
}
// A pending session past expires_at answers PHP's flat expired body.
stale := initiateDevice(t, app, "")
if err := gdb.Model(&models.DeviceAuthSession{}).Where("token = ?", classes.HashAPIToken(stale.Token)).Update("expires_at", time.Now().Add(-time.Minute)).Error; err != nil {
t.Fatal(err)
}
if rec := authorizeDevice(t, app, session, `{"short_code":"`+stale.ShortCode+`"}`); rec.Code != http.StatusBadRequest {
t.Fatalf("authorize an expired session = %d %s", rec.Code, rec.Body.String())
}
rec := deviceCall(t, controllers.DeviceStatus(app), http.MethodGet, "/_user/api/v1/devices/status/"+stale.Token, "", "", map[string]string{"token": stale.Token})
if rec.Body.String() != `{"message":"Authorization session has expired","status":"expired","success":true}` {
t.Fatalf("expired status = %d %s", rec.Code, rec.Body.String())
}
if row := deviceRow(t, gdb, stale.Token); row.Status != models.DeviceStatusExpired {
t.Fatalf("expired row status = %s", row.Status)
}
// device_name is bounded.
long := strings.Repeat("n", 256)
if rec := deviceCall(t, controllers.DeviceInitiate(app), http.MethodPost, "/_user/api/v1/devices/initiate", "", `{"device_name":"`+long+`"}`, nil); rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("device_name of 256 = %d %s", rec.Code, rec.Body.String())
}
}

183
device_revoke_smoke_test.go Normal file
View File

@@ -0,0 +1,183 @@
package user
import (
"encoding/json"
"net/http"
"strconv"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
// envDevice signs a device in through the assembled routes: initiate,
// authorize by session, first poll. It returns the device's session token,
// its jti and the session row id.
func envDevice(t *testing.T, env *adminEnv, session, name string) (string, string, uint) {
t.Helper()
rec := env.call(t, http.MethodPost, "/_user/api/v1/devices/initiate", "", map[string]string{"device_name": name})
if rec.Code != http.StatusOK {
t.Fatalf("initiate = %d %s", rec.Code, rec.Body.String())
}
var started struct {
Data deviceInitiated `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &started); err != nil {
t.Fatal(err)
}
env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/devices/authorize", session, map[string]string{"token": started.Data.Token})
rec = env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/devices/status/"+started.Data.Token, "", nil)
var polled struct {
Data struct {
Token string `json:"token"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &polled); err != nil || polled.Data.Token == "" {
t.Fatalf("hand-over %s: %v", rec.Body.String(), err)
}
_, _, _, jti, err := bouncer.VerifyClaims(polled.Data.Token, sessionSecret)
if err != nil {
t.Fatal(err)
}
var row models.DeviceAuthSession
if err := env.gdb.Where("jwt_jti = ?", jti).Take(&row).Error; err != nil {
t.Fatal(err)
}
return polled.Data.Token, jti, row.ID
}
type deviceListBody struct {
Success bool `json:"success"`
Devices []struct {
ID uint `json:"id"`
DeviceName string `json:"device_name"`
DeviceIP *string `json:"device_ip"`
AuthorizedAt *string `json:"authorized_at"`
LastActivity *string `json:"last_activity"`
IsCurrent bool `json:"is_current"`
} `json:"devices"`
}
func envDevices(t *testing.T, env *adminEnv, token string) deviceListBody {
t.Helper()
rec := env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/devices", token, nil)
var body deviceListBody
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
return body
}
// TestDeviceRevokeSmoke lists and revokes device sessions through the
// assembled routes, including a device that refreshed its token first.
func TestDeviceRevokeSmoke(t *testing.T) {
if testing.Short() {
t.Skip("Postgres")
}
env := newAdminEnv(t)
owner := env.seedUser(t, "dev-owner", nil)
other := env.seedUser(t, "dev-other", nil)
status, session := env.userLogin(t, owner.Email, "correct-horse")
if status != http.StatusOK {
t.Fatalf("owner login = %d", status)
}
otherStatus, otherSession := env.userLogin(t, other.Email, "correct-horse")
if otherStatus != http.StatusOK {
t.Fatalf("other login = %d", otherStatus)
}
tvToken, _, tvID := envDevice(t, env, session, "Living room TV")
// A second used session with no name and an older activity, a pending
// session of the owner and a device of another user.
hourAgo := time.Now().Add(-time.Hour)
ua := "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0)"
oldJTI := "dev-old-" + strconv.FormatInt(time.Now().UnixNano(), 10)
ownerID := owner.ID
phone := models.DeviceAuthSession{TokenHash: "a" + strconv.FormatInt(time.Now().UnixNano(), 10), UserID: &ownerID, Status: models.DeviceStatusUsed,
ExpiresAt: &hourAgo, DeviceUserAgent: &ua, ConfirmedAt: &hourAgo, LastActivityAt: &hourAgo, JWTJTI: &oldJTI}
pendingRow := models.DeviceAuthSession{TokenHash: "b" + strconv.FormatInt(time.Now().UnixNano(), 10), UserID: &ownerID, Status: models.DeviceStatusPending, ExpiresAt: &hourAgo}
if err := env.gdb.Create(&phone).Error; err != nil {
t.Fatal(err)
}
if err := env.gdb.Create(&pendingRow).Error; err != nil {
t.Fatal(err)
}
_, _, foreignID := envDevice(t, env, otherSession, "Other TV")
t.Run("list", func(t *testing.T) {
if rec := env.call(t, http.MethodGet, "/_user/api/v1/devices", "", nil); rec.Code != http.StatusUnauthorized || rec.Body.String() != `{"error":"Unauthorized"}` {
t.Fatalf("list without a session = %d %s", rec.Code, rec.Body.String())
}
list := envDevices(t, env, tvToken)
if !list.Success || len(list.Devices) != 2 {
t.Fatalf("list = %+v", list)
}
first, second := list.Devices[0], list.Devices[1]
if first.ID != tvID || first.DeviceName != "Living room TV" || !first.IsCurrent || first.AuthorizedAt == nil || first.LastActivity == nil {
t.Fatalf("first device = %+v", first)
}
if second.ID != phone.ID || second.DeviceName != "iPhone" || second.IsCurrent {
t.Fatalf("second device = %+v", second)
}
for _, d := range envDevices(t, env, session).Devices {
if d.IsCurrent {
t.Fatalf("device %d is current for the owner's own session", d.ID)
}
}
})
t.Run("revoke", func(t *testing.T) {
env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/fetch", tvToken, nil)
rec := env.expect(t, http.StatusOK, http.MethodDelete, "/_user/api/v1/devices/"+strconv.FormatUint(uint64(tvID), 10), session, nil)
if rec.Body.String() != `{"message":"Device revoked successfully","success":true}` {
t.Fatalf("revoke body = %s", rec.Body.String())
}
env.expect(t, http.StatusUnauthorized, http.MethodGet, "/_user/api/v1/fetch", tvToken, nil)
env.expect(t, http.StatusOK, http.MethodDelete, "/_user/api/v1/devices/"+strconv.FormatUint(uint64(tvID), 10), session, nil)
rec = env.expect(t, http.StatusNotFound, http.MethodDelete, "/_user/api/v1/devices/"+strconv.FormatUint(uint64(foreignID), 10), session, nil)
if rec.Body.String() != `{"error":"Device not found"}` {
t.Fatalf("foreign revoke body = %s", rec.Body.String())
}
// The id constraint keeps a non-numeric id away from the handler,
// which would answer 401 without a session.
if rec := env.call(t, http.MethodDelete, "/_user/api/v1/devices/abc", "", nil); rec.Code != http.StatusNotFound && rec.Code != http.StatusMethodNotAllowed {
t.Fatalf("DELETE /devices/abc = %d %s", rec.Code, rec.Body.String())
}
var row models.DeviceAuthSession
if err := env.gdb.Where("id = ?", tvID).Take(&row).Error; err != nil || row.Status != models.DeviceStatusRevoked {
t.Fatalf("revoked row = %+v %v", row, err)
}
for _, d := range envDevices(t, env, session).Devices {
if d.ID == tvID {
t.Fatal("a revoked device is still listed")
}
}
})
t.Run("revoke_after_refresh", func(t *testing.T) {
deskToken, deskJTI, deskID := envDevice(t, env, session, "Desktop")
rec := env.expect(t, http.StatusOK, http.MethodPost, "/_user/api/v1/refresh", deskToken, nil)
var refreshed struct {
Token string `json:"token"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &refreshed); err != nil || refreshed.Token == "" {
t.Fatalf("refresh %s: %v", rec.Body.String(), err)
}
_, _, _, newJTI, err := bouncer.VerifyClaims(refreshed.Token, sessionSecret)
if err != nil || newJTI == deskJTI {
t.Fatalf("refreshed jti %q err %v", newJTI, err)
}
var row models.DeviceAuthSession
if err := env.gdb.Where("id = ?", deskID).Take(&row).Error; err != nil || row.JWTJTI == nil || *row.JWTJTI != newJTI {
t.Fatalf("row after refresh = %+v %v, want jti %s", row, err, newJTI)
}
env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/fetch", refreshed.Token, nil)
env.expect(t, http.StatusOK, http.MethodDelete, "/_user/api/v1/devices/"+strconv.FormatUint(uint64(deskID), 10), session, nil)
env.expect(t, http.StatusUnauthorized, http.MethodGet, "/_user/api/v1/fetch", deskToken, nil)
env.expect(t, http.StatusUnauthorized, http.MethodGet, "/_user/api/v1/fetch", refreshed.Token, nil)
env.expect(t, http.StatusUnauthorized, http.MethodPost, "/_user/api/v1/refresh", refreshed.Token, nil)
// The owner's own session is untouched.
env.expect(t, http.StatusOK, http.MethodGet, "/_user/api/v1/fetch", session, nil)
})
}

377
email_verified_test.go Normal file
View File

@@ -0,0 +1,377 @@
package user
import (
"net/http"
"net/url"
"strconv"
"strings"
"testing"
"time"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/controllers"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/postcard"
"gorm.io/gorm"
)
// proofOf reads users.email_verified_at of the user id.
func proofOf(t *testing.T, gdb *gorm.DB, id uint) *time.Time {
t.Helper()
var got *time.Time
if err := gdb.Raw(`SELECT email_verified_at FROM users WHERE id = ?`, id).Row().Scan(&got); err != nil {
t.Fatal(err)
}
return got
}
// userIDByEmail returns the id of the user with email.
func userIDByEmail(t *testing.T, gdb *gorm.DB, email string) uint {
t.Helper()
var u models.User
if err := gdb.Unscoped().Where("lower(email) = lower(?)", email).Take(&u).Error; err != nil {
t.Fatal(err)
}
return u.ID
}
// setProof stores a proof time on the user id and returns it.
func setProof(t *testing.T, gdb *gorm.DB, id uint) time.Time {
t.Helper()
at := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
if err := gdb.Exec(`UPDATE users SET email_verified_at = ? WHERE id = ?`, at, id).Error; err != nil {
t.Fatal(err)
}
return at
}
// assertStamped requires got to be set between before and after (with a
// millisecond of slack for the database's microsecond precision).
func assertStamped(t *testing.T, got *time.Time, before, after time.Time) {
t.Helper()
if got == nil {
t.Fatal("email_verified_at is NULL, want the time of the proof")
}
if got.Before(before.Add(-time.Millisecond)) || got.After(after.Add(time.Millisecond)) {
t.Fatalf("email_verified_at = %v, want between %v and %v", got, before, after)
}
}
// assertNoProofKey requires a response body without the proof column.
func assertNoProofKey(t *testing.T, body string) {
t.Helper()
if strings.Contains(body, "email_verified_at") {
t.Fatalf("the payload carries email_verified_at: %s", body)
}
}
// TestEmailVerifiedAt pins the user API side of D-26 and D-27: only the
// mailed activation code and a completed reset-code password reset record
// the proof of the address, an email change clears it, and the column is
// never mass-assigned or part of a payload.
func TestEmailVerifiedAt(t *testing.T) {
app, gdb := sessionApp(t, "0s")
disableRegisterThrottle(t, app)
if err := app.Publish[postcard.Mailer](&captureMail{}); err != nil {
t.Fatal(err)
}
stamp := adminStamp()
email := func(label string) string { return "proof-" + label + "-" + stamp + "@example.test" }
mode := func(t *testing.T, m string) {
t.Helper()
if err := app.Config.Set("golem15.user.activation.activate_mode", m); err != nil {
t.Fatal(err)
}
}
register := func(t *testing.T, body string) string {
t.Helper()
rec := postJSON(t, controllers.Register(app), "/_user/api/v1/register", body)
if rec.Code != http.StatusOK {
t.Fatalf("register %d %s", rec.Code, rec.Body.String())
}
assertNoProofKey(t, rec.Body.String())
return rec.Body.String()
}
t.Run("register_auto_no_proof", func(t *testing.T) {
mode(t, "auto")
addr := email("register-auto")
body := register(t, `{"email":"`+addr+`","password":"correct-horse"}`)
if !strings.Contains(body, `"token":`) {
t.Fatalf("auto-mode register answered %s", body)
}
id := userIDByEmail(t, gdb, addr)
var activated bool
if err := gdb.Raw(`SELECT is_activated FROM users WHERE id = ?`, id).Row().Scan(&activated); err != nil {
t.Fatal(err)
}
if !activated || proofOf(t, gdb, id) != nil {
t.Fatalf("auto-mode account: activated=%v proof=%v", activated, proofOf(t, gdb, id))
}
})
t.Run("register_admin_mode_no_proof", func(t *testing.T) {
mode(t, "admin")
t.Cleanup(func() { mode(t, "auto") })
addr := email("register-admin")
if body := register(t, `{"email":"`+addr+`","password":"correct-horse"}`); body != `{}` {
t.Fatalf("admin-mode register answered %s", body)
}
if got := proofOf(t, gdb, userIDByEmail(t, gdb, addr)); got != nil {
t.Fatalf("admin-mode account has proof %v", got)
}
})
t.Run("register_ignores_submitted_proof", func(t *testing.T) {
mode(t, "auto")
addr := email("register-submitted")
register(t, `{"email":"`+addr+`","password":"correct-horse","email_verified_at":"2020-01-01T00:00:00Z"}`)
if got := proofOf(t, gdb, userIDByEmail(t, gdb, addr)); got != nil {
t.Fatalf("a submitted email_verified_at was stored: %v", got)
}
})
t.Run("activate_by_code_stamps", func(t *testing.T) {
user := insertInactiveUser(t, gdb, email("activate-by-code"), "correct-horse")
code, err := classes.IssueActivationCode(t.Context(), gdb, user)
if err != nil {
t.Fatal(err)
}
before := time.Now()
rec := postJSON(t, controllers.ActivateByCode(app), "/_user/api/v1/activate-by-code",
`{"code":"`+strconv.FormatUint(uint64(user.ID), 10)+"!"+code+`"}`)
after := time.Now()
if rec.Code != http.StatusOK {
t.Fatalf("activate-by-code %d %s", rec.Code, rec.Body.String())
}
assertNoProofKey(t, rec.Body.String())
assertStamped(t, proofOf(t, gdb, user.ID), before, after)
})
t.Run("activate_stamps", func(t *testing.T) {
addr := email("activate")
token := inactiveSessionToken(t, app, gdb, addr)
user := &models.User{ID: userIDByEmail(t, gdb, addr)}
code, err := classes.IssueActivationCode(t.Context(), gdb, user)
if err != nil {
t.Fatal(err)
}
before := time.Now()
rec := bearerJSON(t, controllers.Activate(app), "/_user/api/v1/activate", token, `{"code":"`+code+`"}`)
after := time.Now()
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"is_activated":true`) {
t.Fatalf("activate %d %s", rec.Code, rec.Body.String())
}
assertNoProofKey(t, rec.Body.String())
assertStamped(t, proofOf(t, gdb, user.ID), before, after)
})
t.Run("activate_wrong_code_no_proof", func(t *testing.T) {
addr := email("activate-wrong")
token := inactiveSessionToken(t, app, gdb, addr)
user := &models.User{ID: userIDByEmail(t, gdb, addr)}
if _, err := classes.IssueActivationCode(t.Context(), gdb, user); err != nil {
t.Fatal(err)
}
rec := bearerJSON(t, controllers.Activate(app), "/_user/api/v1/activate", token, `{"code":"wrong"}`)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"is_activated":false`) {
t.Fatalf("activate %d %s", rec.Code, rec.Body.String())
}
assertNoProofKey(t, rec.Body.String())
if got := proofOf(t, gdb, user.ID); got != nil {
t.Fatalf("a wrong activation code recorded proof %v", got)
}
})
t.Run("reset_password_stamps", func(t *testing.T) {
user := insertUser(t, gdb, email("reset"), "correct-horse")
code, err := classes.IssueResetCode(t.Context(), gdb, user)
if err != nil {
t.Fatal(err)
}
before := time.Now()
rec := postJSON(t, controllers.ResetPassword(app), "/_user/api/v1/reset-password",
`{"code":"`+strconv.FormatUint(uint64(user.ID), 10)+"!"+code+`","password":"new-password","password_confirmation":"new-password"}`)
after := time.Now()
if rec.Code != http.StatusOK || rec.Body.String() != `{"message":"Password has been reset"}` {
t.Fatalf("reset %d %s", rec.Code, rec.Body.String())
}
assertStamped(t, proofOf(t, gdb, user.ID), before, after)
})
t.Run("reset_wrong_code_no_proof", func(t *testing.T) {
user := insertUser(t, gdb, email("reset-wrong"), "correct-horse")
if _, err := classes.IssueResetCode(t.Context(), gdb, user); err != nil {
t.Fatal(err)
}
for _, code := range []string{strconv.FormatUint(uint64(user.ID), 10) + "!nope", "not-a-code"} {
rec := postJSON(t, controllers.ResetPassword(app), "/_user/api/v1/reset-password",
`{"code":"`+code+`","password":"new-password","password_confirmation":"new-password"}`)
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("reset with %q: %d %s", code, rec.Code, rec.Body.String())
}
}
if got := proofOf(t, gdb, user.ID); got != nil {
t.Fatalf("a refused reset recorded proof %v", got)
}
})
t.Run("change_password_no_proof", func(t *testing.T) {
addr := email("change-password")
token := loginToken(t, app, gdb, addr)
// change-password replaces a self-set password only.
if err := gdb.Exec(`UPDATE users SET has_self_set_password = TRUE WHERE id = ?`, userIDByEmail(t, gdb, addr)).Error; err != nil {
t.Fatal(err)
}
rec := bearerJSON(t, controllers.ChangePassword(app), "/_user/api/v1/change-password", token,
`{"current_password":"correct-horse","password":"brand-new-password","password_confirmation":"brand-new-password"}`)
if rec.Code != http.StatusOK {
t.Fatalf("change-password %d %s", rec.Code, rec.Body.String())
}
assertNoProofKey(t, rec.Body.String())
if got := proofOf(t, gdb, userIDByEmail(t, gdb, addr)); got != nil {
t.Fatalf("change-password recorded proof %v", got)
}
})
update := func(t *testing.T, token, body string) string {
t.Helper()
rec := bearerJSON(t, controllers.Update(app), "/_user/api/v1/update", token, body)
if rec.Code != http.StatusOK {
t.Fatalf("update %d %s", rec.Code, rec.Body.String())
}
assertNoProofKey(t, rec.Body.String())
return rec.Body.String()
}
t.Run("update_email_change_clears", func(t *testing.T) {
addr := email("update-change")
token := loginToken(t, app, gdb, addr)
id := userIDByEmail(t, gdb, addr)
setProof(t, gdb, id)
moved := email("update-changed-to")
update(t, token, `{"name":"Ann","surname":"Owner","email":"`+moved+`"}`)
if got := proofOf(t, gdb, id); got != nil {
t.Fatalf("an email change kept the proof %v", got)
}
})
t.Run("update_same_email_keeps", func(t *testing.T) {
addr := email("update-same")
token := loginToken(t, app, gdb, addr)
id := userIDByEmail(t, gdb, addr)
want := setProof(t, gdb, id)
update(t, token, `{"name":"Ann","surname":"Owner","email":"`+addr+`"}`)
if got := proofOf(t, gdb, id); got == nil || !got.Equal(want) {
t.Fatalf("the same email changed the proof to %v", got)
}
update(t, token, `{"name":"Ann","surname":"Owner","email":"`+strings.ToUpper(addr)+`"}`)
if got := proofOf(t, gdb, id); got == nil || !got.Equal(want) {
t.Fatalf("a case-only change dropped the proof: %v", got)
}
})
t.Run("update_ignores_submitted_proof", func(t *testing.T) {
addr := email("update-submitted")
token := loginToken(t, app, gdb, addr)
update(t, token, `{"name":"Ann","surname":"Owner","email":"`+addr+`","email_verified_at":"2020-01-01T00:00:00Z"}`)
if got := proofOf(t, gdb, userIDByEmail(t, gdb, addr)); got != nil {
t.Fatalf("a submitted email_verified_at was stored: %v", got)
}
})
}
// TestAdminEmailVerifiedAt pins the admin side of D-26 and D-27: an
// administrator's create and Activate action record no proof, the
// invitation link (the mailed activation code) does, an email change on the
// form clears it, and the admin JSON never carries it.
func TestAdminEmailVerifiedAt(t *testing.T) {
env := newAdminEnv(t)
token := env.admin(t, permAccessUsers)
stamp := adminStamp()
const password = "proof-admin-password-1"
create := func(t *testing.T, email string, extra map[string]any) uint {
t.Helper()
body := map[string]any{"name": "Proof", "email": email, "password": password, "password_confirmation": password}
for k, v := range extra {
body[k] = v
}
return createdID(t, env.expect(t, http.StatusCreated, http.MethodPost, adminAPI(adminUsersPath), token, body))
}
proven := func(t *testing.T, label string) *models.User {
t.Helper()
at := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
return env.seedUser(t, label, func(u *models.User) { u.EmailVerifiedAt = &at })
}
t.Run("admin_create_no_proof", func(t *testing.T) {
id := create(t, "admin-proof-create-"+stamp+"@example.test", nil)
if got := env.reload(t, id); got == nil || got.EmailVerifiedAt != nil {
t.Fatalf("admin-created user = %+v", got)
}
})
t.Run("admin_activate_action_no_proof", func(t *testing.T) {
user := env.seedUser(t, "admin-proof-activate", func(u *models.User) { u.IsActivated = false })
if rec := env.bulk(t, token, "activate", user); rec.Code != http.StatusOK {
t.Fatalf("activate action %d %s", rec.Code, rec.Body.String())
}
got := env.reload(t, user.ID)
if !got.IsActivated || got.EmailVerifiedAt != nil {
t.Fatalf("after the activate action: activated=%v proof=%v", got.IsActivated, got.EmailVerifiedAt)
}
})
t.Run("admin_invite_link_stamps", func(t *testing.T) {
invited := "admin-proof-invite-" + stamp + "@example.test"
id := create(t, invited, map[string]any{"send_invite": true})
if got := env.reload(t, id); got.EmailVerifiedAt != nil {
t.Fatalf("the invitation recorded proof before the link: %v", got.EmailVerifiedAt)
}
mails := env.mails(invited)
if len(mails) != 1 {
t.Fatalf("invitations sent = %d", len(mails))
}
start := strings.Index(mails[0].Text, "https://app.example.test/activate?code=")
if start < 0 {
t.Fatalf("no activation link in %q", mails[0].Text)
}
link := mails[0].Text[start:]
link = link[:strings.IndexAny(link, ")\n ")]
parsed, err := url.Parse(link)
if err != nil {
t.Fatal(err)
}
before := time.Now()
rec := env.call(t, http.MethodPost, "/_user/api/v1/activate-by-code", "", map[string]string{"code": parsed.Query().Get("code")})
after := time.Now()
if rec.Code != http.StatusOK {
t.Fatalf("activate-by-code %d %s", rec.Code, rec.Body.String())
}
got := env.reload(t, id)
if !got.IsActivated {
t.Fatal("the invitation link did not activate")
}
assertStamped(t, got.EmailVerifiedAt, before, after)
})
t.Run("admin_email_change_clears", func(t *testing.T) {
user := proven(t, "admin-proof-change")
moved := "admin-proof-moved-" + stamp + "@example.test"
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token, map[string]any{"name": "Moved", "email": moved})
got := env.reload(t, user.ID)
if got.Email != moved || got.EmailVerifiedAt != nil {
t.Fatalf("after the email change: email=%s proof=%v", got.Email, got.EmailVerifiedAt)
}
})
t.Run("admin_save_keeps_proof", func(t *testing.T) {
user := proven(t, "admin-proof-keep")
want := *user.EmailVerifiedAt
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token, map[string]any{"name": "Renamed", "email": user.Email})
if got := env.reload(t, user.ID); got.EmailVerifiedAt == nil || !got.EmailVerifiedAt.Equal(want) {
t.Fatalf("a save with the same email changed the proof to %v", got.EmailVerifiedAt)
}
env.expect(t, http.StatusOK, http.MethodPut, userPath(user.ID, ""), token, map[string]any{"name": "Renamed", "email": strings.ToUpper(user.Email)})
if got := env.reload(t, user.ID); got.EmailVerifiedAt == nil || !got.EmailVerifiedAt.Equal(want) {
t.Fatalf("a case-only change dropped the proof: %v", got.EmailVerifiedAt)
}
})
t.Run("admin_json_hides_proof", func(t *testing.T) {
user := proven(t, "admin-proof-json")
show := env.expect(t, http.StatusOK, http.MethodGet, userPath(user.ID, ""), token, nil)
assertNoProofKey(t, show.Body.String())
form := env.expect(t, http.StatusOK, http.MethodGet, adminAPI(adminUsersPath+"/schema/form"), token, nil)
assertNoProofKey(t, form.Body.String())
list := env.users(t, token, "search="+url.QueryEscape(user.Email))
if !list.has(user.ID) {
t.Fatal("the proven user is not in the list")
}
assertNoProofKey(t, list.Raw)
})
}

Some files were not shown because too many files have changed in this diff Show More