Repository navigation
feat: admin user-management API with explicit admin authorization (#5) - #6
Conversation
Authenticated does not mean administrator. Every /api/auth/admin/* route now authenticates the caller and re-reads the account from the database to require the admin role (401 anonymous, 403 non-admin), so a stale token claim, an API token or an impersonated session never grants access. - users CRUD with email validation/uniqueness, direct by-id queries, paginated list, last-admin protection, no swallowed errors, generic client messages - impersonation: act/jti claims, short TTL, audit events with actor and target, admins protected by default, revocable via /api/auth/impersonation/stop, /api/auth/me exposes `impersonator` - magic and reset links: single-use, short-lived, purpose-bound, hashed at rest, never in events; base URL from config only - borrowed sessions cannot change the account's password, 2FA, PIN or tokens Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
Security gate: FAIL (round 1). The admin authorization core is sound: every privileged route is behind a DB-revalidated
The review's regression tests ( Non-blocking hardening is tracked separately and does not block this PR. |
F1 admin targets are refused for reset-password and magic-link too (AUTH_IMPERSONATE_ADMINS governs all three). F2 magic-link sessions carry the issuing admin (act claim, impersonator, login event, new auth.magic_link_redeemed event) and the impersonation TTL. F3 reset redemption is one conditional UPDATE with a rows-affected check, committed together with the password change. F4 last-admin and email checks run in a transaction that locks a sentinel row (works on Postgres and SQLite); in-process adminMu removed. F5 email uniqueness is case-insensitive (LOWER(email)). F6 NUL / invalid UTF-8 stripped from q and rejected in ids. F7 Verify delegates to VerifyContext, which enforces revocation and actor checks for every caller. Adds the reviewer's tests; pgx is a test-only dependency used by the authpg build-tag run. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Security gate: FAIL (round 2). This was a full re-review on SQLite and Postgres. F1 to F7 are verified fixed, the Postgres-only issue is gone, and the cross-instance last-admin guard and revocation in New finding:
Required:
The gate re-runs in full after the fix. |
PATCH of another administrator's email now follows the F1 policy (403 unless AUTH_IMPERSONATE_ADMINS), closing the takeover through the public password-reset flow. Role/permission changes and deletes of admins stay allowed and audited with actor_id and target_id. README and SECURITY document the admin API rules, env vars, Verify -> VerifyContext and the reset-requested event. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Security gate: FAIL (round 3). Full re-review on SQLite and Postgres. F8 is fixed. New findings:
Required policy:
The gate re-runs in full afterwards. |
Changing another admin's email, roles or permissions, like impersonate, reset and magic link, is refused unless the single AUTH_ADMIN_CROSS_CONTROL policy is on; each use emits auth.admin_cross_control. Admin-issued reset (issuer recorded) and magic tokens are re-authorized at redemption and refused when the target is now an admin. Request bodies reject unknown fields. The flag was renamed from AUTH_IMPERSONATE_ADMINS (unreleased). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Security gate: FAIL (round 4). Full re-review on SQLite and Postgres. F9 and F10 are verified fixed. Every chained sequence passes except one race. F11 (medium): a promotion can race a reset redemption. The "target is now an admin" check in F11 is not being patched yet. This is the second chained or concurrent privilege-transition finding in a row, so fixes are paused for a focused admin lifecycle threat model. It needs to establish the invariant boundary before more individual paths get fixed. Once the owner has reviewed that model, the author implements F11 together with any other release-blocking invariant fixes. Then a fresh full independent review runs. This PR stays blocked: no merge and no tag. |
|
Owner decisions on the admin lifecycle threat model (approved). The author is now implementing one coherent change set on this branch:
After that, one fresh independent security review runs against the full threat model. If it finds another High or Medium privilege-takeover path, work stops and goes to the owner. This PR stays blocked: no merge, no tag. |
…, F13, D2) Reset redemption and admin set-password run in one transaction with a compare-and-set on the roles value judged non-administrator; identity writes by administrators are recorded per field in auth_account_state and promotion of a tainted account needs an explicit accept (409 otherwise); act-limited sessions end when the target becomes an administrator; sessions are revalidated against the database on the base driver. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…on tests Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Both interleavings of a self-demotion and another admin's email change are legal; the invariant is that the email never changes on a still-admin account and that the answer agrees with the state. The previous assertion held only when the email change happened to be judged first. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… for gosec Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Security review Round 5: FAIL (High). Final independent gate against the approved lifecycle threat model v2Reviewed commit: F-R5-1 (High): an admin launders email provenance through the promoter's write and gains authentication as an adminInvariants violated: I1 (the primary invariant: without the explicit cross-admin exception, Admin A never obtains authentication as Admin B), I4 (the provenance gate at promotion), and the forbidden transitions X1 and X9. Exact sequence (A and C are admins, U is a normal user):
Why the model missed it: threat model §130 states that self-service reset is "safe only because promotion needs untainted email". The exemption for the promoter's own write removes exactly that safety. F-R5-1c (High, distinct variant): a self-service reset token survives the email change and the promotionA self-service reset token issued to A's inbox before the promotion remains redeemable after C changes the email and promotes U. The token is not bound to the email it was sent to, and the self-service redeem path has no roles check, so A can set a new password on the now-admin account after it is promoted. This needs the same action from C (the cleanup promote, or an explicit accept). It is separate from the provenance gap: it would still work even if the redeem recorded provenance. Reproduction
The behaviour was identical on SQLite and Postgres. The orchestrator independently re-ran the SQLite results on Not covered (the review stopped at the blocker)The remaining races, the D2 session revalidation sweep, the depth-3 matrix, the soak runs, the two-instance Postgres test and the judgement on each author deviation were not run. The existing suites passed on both databases at Owner decision (approved): one contained correction to the lifecycle model, implementing (a), (b) and (c) together
🤖 Generated with Claude Code |
…changed Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…covery tokens bound to account state (F-R5-1, F-R5-1c) (a) promotion judges the provenance stored before the request; the promoter's same-request email write earns no exemption. (b) a credential set through a recovery channel inherits the channel's provenance (admin link -> issuer, self-service token -> whoever set the email). (c) reset and magic-link tokens record the account state they were issued against and are re-checked under the row lock at redemption; a refusal is burned and committed and answers like any invalid token. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Strict owner ruling (Round 5): email and password provenance is security
history, not last-writer state. Each field stores the sorted set of every
non-holder administrator who ever wrote it; taintedFields taints on any
member that is neither the holder nor the promoter, so the promoter's own
earlier writes are exempt only as the sole writer. Self-service redemption
adds every email writer of the channel, admin-issued adds the issuer.
Password provenance was last-writer too and now accumulates.
Changed assertions (only tightening):
- review_lifecycle_matrix_test.go oracle: emailBy/pwBy single value ->
writer set; tainted = any member != promoter; final provenance check
compares the sorted joined ids. Before: emailA,emailB => {B}. After:
{A,B}. The old expectation let B launder A's taint with one extra write,
contradicting I1/X9 of the approved threat model.
- TestLifecyclePromoterOwnWriteExempt: assertion unchanged (200, sole writer).
- Reviewer TestReview5LaunderViaSeparateEmailEdit unchanged; now skips on
the 409 refusal.
New: TestR5Strict* (accumulate, sole writer exempt, holder write and accept
do not clear, password accumulates).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Security review Round 6: FAIL (Medium). Full independent gate on
|
| Test | SQLite | Postgres |
|---|---|---|
TestR6DemotedIssuerTakesOverTarget |
FAIL: the ex-admin authenticated as the target | FAIL |
TestR6ResetLinkIssuerDemoted |
FAIL: the link still redeems | FAIL |
The orchestrator independently reran both tests on SQLite at ee074e2 and confirmed the cited path.
Passed before the stop
- Email round trips keep the taint: A→Y→A, A→C→A, and a case-only change all still get 409 at promotion.
- An accepted promotion voids every earlier token: self-service, admin-issued and magic.
- Tokens without a recovery context are refused.
- A refused token and an unknown token return the same status and body.
Low (non-blocking, not fixed in this patch)
A voided token takes about 70 ms to refuse and an unknown token about 0.7 ms, probably because of bcrypt cost on the voided path. The owner kept this out of the privilege-retention fix, so it is recorded as an existing Low.
Not covered (the review stopped at the blocker)
- The depth-3 matrix.
- The stress and soak runs.
- The two-instance Postgres test.
- The full D2 sweep.
- The race suite.
- The audit and leakage checks.
- Judgements on the author's deviations.
The baselines were green at ee074e2 on both databases.
Owner decision (approved): a contained fix, F-R6-1 only
- Issuer check: every admin-issued credential (reset links and magic links) revalidates its issuer inside the redeem transaction. The check runs after the row or token lock and before any effect that changes a credential or authenticates. The issuer must still exist and still hold admin privilege, or redemption fails.
- Refusals: the credential stays burned, and the response is the same as for an unknown credential.
- Existing checks kept: the target-side epoch, email and context checks stay as additional checks. Neither the admin-target protection nor any Round 5 invariant is weakened.
- Threat-model rule: "An admin-issued credential carries both target context and issuer-authority context. Validity at issuance does not imply validity after a relevant identity or privilege transition of either party."
- Tests: the reviewer's Round 6 tests come in unchanged, plus minimal regression tests for issuer deletion and demotion on both credential types.
- Next gate: a fresh reviewer reruns the complete Round 6 gate and verifies the fix on both SQLite and Postgres. Any finding of Medium or higher stops it again. Nothing merges or tags until the whole gate passes.
🤖 Generated with Claude Code
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…tion (F-R6-1) A reset link read its issuer from auth_reset_issuers but never checked it again, so an admin demoted or deleted after issuing could still redeem the link, set a password and sign in as the target. issuerHolds now reads the issuer inside the redeem transaction (after the target row lock, before any credential change or session) and requires the account to exist and hold admin. Both paths use it: reset redemption and magic-link consume (the latter moved ahead of the second-factor prompt so a refused link looks like an unknown one). A refusal commits the burn and answers the generic 401. Target-side epoch/email/context checks are unchanged. No existing assertion changed. The ~70 ms vs ~0.7 ms refusal timing difference is untouched (existing Low). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Round 6 security gate (fresh reviewer, complete scope): PASS on
|
| Run | Result |
|---|---|
| Full suite, SQLite | ok (92s) |
Full suite, Postgres (-tags authpg) |
ok (123s) |
| Round 6b reviewer tests, SQLite | ok |
| Round 6b reviewer tests, Postgres | ok, except the deliberate O1 repro (see below) |
Soak -count=10 (race, lock, R5, R6, R6b), SQLite / Postgres |
ok / ok except the O1 repro |
-count=5 race, act-session, delete, magic, two-kernel, issuer, impersonation-stop, queued-redeem |
ok on both |
Privilege-epoch interleavings (-count=3), SQLite / Postgres |
ok |
TestReviewR4DefaultDeniesEveryPeerOp alone, -count=5, both DBs |
ok |
| Two kernels on one Postgres DB, promote vs redeem ×5 | promote 409, target stays non-admin |
| Depth-3 matrix as shipped | 429 from the sensitive-route rate limiter (L1 below) |
| Depth-3 matrix with the limiter lifted in a scratch copy, SQLite / Postgres | ok (239s) / ok (291s) |
Coverage
- Invariants I1–I14, including cumulative email and password provenance (security history, not last-writer state), the recovery-context binding, and issuer and target revalidation at redeem.
- Lifecycle matrix: SSO
FindOrCreateByEmail, register, change-password and revoked tokens. - Races, run lock-held:
- promote vs set-password, email change or redeem (accept on and off, both orders);
- accept-promote vs a concurrent write;
- act session vs issuer demote or delete under load;
- delete vs session use;
- issuer demote or delete during a reset or magic-link redeem.
- Privilege epoch: promote, demote and
SetRoleseach void outstanding recovery tokens, including a redeem queued behind the target row lock while the bump commits. - Session revalidation sweep (D2): bearer, cookie and store sessions, PATs,
RequireRole,RequirePermission, and every claims-reading path.verifyis reachable only throughVerifyContext. Impersonation stop revokes the act session on bearer, cookie and store sessions. The supabase driver skips revalidation by design, and no admin surfaces exist under it. - Audit and leakage: no tokens, passwords or JWTs in events or logs. Accept is audited (
accepted:trueplus the tainted fields). The 409 exposes other admins' ids only to admins. - Author deviations: each was judged sound: the 1db1b35 test rewrite, the nil-kernel
verifytests, accept as audit-only, the promoter-as-sole-writer exemption, inherited provenance for self-service recovery, theadminTxcaller recheck,#nosec G101, and the tightened writer-set oracle. - GHSA-8jr8-x9fc-8qvh: fixed on the auth side. Removing the template's
/api/adminremains a separate release precondition.
Final owner questions (resolved without code changes)
O1: issuer demotion racing a password-reset redemption.
The redeem transaction (reset.go) runs in this order: burn the token, read the issuer, txLockUser(target), read the target, issuerHolds (a plain SELECT of the issuer row), recoveryContextHolds, a roles compare-and-set on the target's password, provenance, burn the other tokens, commit.
The demotion transaction (adminUpdateUser in adminTx) runs: guard row, recheck the actor, txLockUser(issuer), bumpPrivEpoch(issuer), last-admin count, UPDATE users SET roles on the issuer, commit.
In the repro, issuerHolds reads the last committed issuer row (still admin), the demotion commits, and then the redeem commits.
The two transactions share no written row. The redeem writes only the target's rows and the reset tokens. The demotion writes only the issuer's row, the issuer's epoch and the guard. The only dependency is redeem → demote (the redeem read the issuer before the demotion wrote it). The demotion's last-admin count reads roles, which the redeem never changes. The dependency graph is therefore acyclic, and the history is equivalent to the serial order redeem, then demote.
The authority decision (the linearization point) is the issuerHolds read, which falls inside the redeem's interval and before the demotion commits. A demotion that commits before that read is refused: covered by the R6 and R6b tests, and by A's admin API returning 403 immediately after the demotion. So no authority decision is made after the demotion takes effect.
The result is exactly what the serial history allows: a then-admin resets a non-admin's password, then loses admin. No capability is gained beyond that. The target is non-admin, the token is one-shot, and the issuer cannot observe or time someone else's demotion.
One residual property: under READ COMMITTED, a third reader could see the demotion before the password write becomes visible (a visibility-order effect, not an authority decision). The window is the remaining redeem duration. The repro widens it with an artificially held lock on another of the target's token rows.
Verdict: Low. Locking the issuer row in the redeem would close it. That is deferred to auth#7.
Self-demotion 403 in TestR6bEpochInterleavings: expected behaviour, not a regression.
- In isolation, promote then self-demote with the target's own token returns 200, and the admin list returns 403 afterwards.
- In the interleaving harness, the holder transaction owns the target row while the promote is queued behind it (uncommitted). The self-demote arrives 150 ms later, and
requireAdminauthenticates it against the database first, where the target is still not an admin. The result is{"error":"forbidden"}(therequireAdmindeny), before any lock oradminTargetErr. - That is default-deny authorization judged at request time. A non-admin cannot act on the admin API before its promotion commits.
Low findings, deferred to auth#7 (not fixed in this release)
- O1: the issuer row is read without a lock in the reset redeem (above).
- L1 (harness):
AUTH_MATRIX_DEPTH=3cannot pass as shipped. The matrix sends every request through one test server and one client IP, so it exhausts the sensitive-route limiter (60 per 5 minutes per IP,admin.go:86) and gets 429. The independent run with the limiter lifted passed on SQLite and Postgres. Future gates need a corrected configuration: rotate the client IP per sequence, or add a test-only limiter override. - L2: logout does not invalidate a stateless bearer JWT or cookie. Only store sessions are ended.
- L3: programmatic
SetRoleschanges privilege without firingadmin_promotedoradmin_demoted. - L4: the Round 5 reviewer tests report SKIP when the attack is refused. They should assert it explicitly.
- Timing (existing, owner-deferred): the ~70 ms vs ~0.7 ms response-time difference.
- Existing, owner-deferred:
auth.registeredcarries the bcrypt hash.
The reviewer evidence is kept outside the repo: patch auth-review-tests-r6b.patch (1177 lines) and the review notes.
🤖 Generated with Claude Code
What
Adds the admin user-management API the Nasaq dashboard calls, with explicit administrator authorization on every route. Part of the foundation release train: circlexo/apps#78.
Closes #5. Supersedes #2.
Why
Authenticated does not mean administrator. Every
/api/auth/admin/*route authenticates the caller and then re-reads the account from the database to require theadminrole: anonymous gets 401, a signed-in non-admin gets 403. A stale token claim, an API token, or an impersonated session never qualifies.How
admin.go): users CRUD,impersonate,reset-password,magic-link. Cookie-authenticated writes needX-CSRF-Token; bearer requests are exempt, as elsewhere in the plugin. Mounted only forAUTH_DRIVER=base.limitmax 500,offset) with a literalqsearch, email validation and uniqueness on create and update, last-admin delete/demote refused, role and permission lists validated, user deletion cleans credentials in a transaction. No swallowed errors; the client gets generic messages and the real error is logged.admin_links.go): 256-bit token, only its hash stored, single-use via an atomic conditional update, 15 min (magic) / 30 min (reset), purpose-bound, superseded by the next link for the account, never placed in events. The base URL comes only fromAUTH_PUBLIC_URL/APP_URL; if unset or invalid the link is a relative path, so the Host header is never trusted. Magic links do not bypass 2FA.admin_impersonate.go): the token carriesact.sub(the admin) and ajti, lives 30 min by default (AUTH_IMPERSONATION_TTL_MINUTES, max 480), and is revocable viaPOST /api/auth/impersonation/stop. Audit events name actor id, target id and time, with no secrets. It dies if the admin is demoted or either account is deleted. It cannot call the admin API or change the borrowed account's password, 2FA, PIN or API tokens. Impersonating another admin is refused unlessAUTH_IMPERSONATE_ADMINS=true(default refuse)./api/auth/menow includesimpersonatorwhile impersonating.Tests
TDD:
admin_test.gowas written first. It covers:actclaim, TTL,/me, admin policy, stop and revocation, and death when the actor is demotedgofmt,go vet ./...,go test -count=1 ./...,gosec ./...(0 issues) andgovulncheck ./...(no affected vulnerabilities) pass locally. The old PR'sscanfailure could not be diagnosed from its logs (expired); the equivalent gosec findings are fixed at the root and the scan now passes locally.Notes
Recommended version: v0.10.0 (new feature, additive). Not tagged here. Tested on SQLite; placeholders are dialect-aware (
s.ph) for Postgres/pgx.🤖 Generated with Claude Code