Skip to content

feat: admin user-management API with explicit admin authorization (#5) - #6

Merged
fadymondy merged 19 commits into
mainfrom
feat/5-admin-api-authz
Oct 8, 2026
Merged

fadymondy merged 19 commits into
mainfrom
feat/5-admin-api-authz

Conversation

@fadymondy

Copy link
Copy Markdown
Contributor

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 the admin role: anonymous gets 401, a signed-in non-admin gets 403. A stale token claim, an API token, or an impersonated session never qualifies.

How

  • Routes (admin.go): users CRUD, impersonate, reset-password, magic-link. Cookie-authenticated writes need X-CSRF-Token; bearer requests are exempt, as elsewhere in the plugin. Mounted only for AUTH_DRIVER=base.
  • Data handling: direct by-id queries, paginated list (limit max 500, offset) with a literal q search, 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.
  • Magic and reset links (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 from AUTH_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.
  • Impersonation (admin_impersonate.go): the token carries act.sub (the admin) and a jti, lives 30 min by default (AUTH_IMPERSONATION_TTL_MINUTES, max 480), and is revocable via POST /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 unless AUTH_IMPERSONATE_ADMINS=true (default refuse).
  • /api/auth/me now includes impersonator while impersonating.

Tests

TDD: admin_test.go was written first. It covers:

  • a table over every admin route and method (anonymous 401, garbage token 401, non-admin 403)
  • API tokens refused, and a demoted or deleted admin's token refused despite its claims
  • CSRF on cookie writes
  • CRUD, pagination past 500 users, and the last-admin rules
  • link single-use, expiry and supersession; no secrets in events; Host-header immunity
  • impersonation audit event, act claim, TTL, /me, admin policy, stop and revocation, and death when the actor is demoted

gofmt, go vet ./..., go test -count=1 ./..., gosec ./... (0 issues) and govulncheck ./... (no affected vulnerabilities) pass locally. The old PR's scan failure 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

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

Copy link
Copy Markdown
Contributor Author

Security gate: FAIL (round 1). The admin authorization core is sound: every privileged route is behind a DB-revalidated requireAdmin, it denies by default, 401 and 403 are correct, and PATs and impersonated sessions are rejected. Fix the following before the gate re-runs. These findings apply to the unreleased code in this PR.

  • F1 (high): the admin-target restriction must also apply to reset-password and magic-link. Today those routes let one admin obtain another admin's session without the impersonation rule or an act claim. Deny admin targets unless AUTH_IMPERSONATE_ADMINS is set.
  • F2 (medium): magic-link redemption must be attributable. Carry the issuing admin into the session or token and into the login event.
  • F3 (medium): password-reset redemption must be atomic. Use a single conditional update and check rows affected, as the magic-link path already does.
  • F4 (medium/low): the last-admin invariant must hold across instances. Use a transaction or a conditional statement, not an in-process mutex.
  • F5 (low): email uniqueness must be case-insensitive (lower(email)).
  • F6 (low, Postgres): reject or strip NUL bytes in q, which currently gives a 500.
  • F7: every exported token-verification path must honour the revoked-jti check (Verify() currently skips it), or it must not be usable for request authentication.

The review's regression tests (review_*_test.go) are to be added to this PR. F1 to F5 fail until fixed. The Postgres run passed apart from F6.

Non-blocking hardening is tracked separately and does not block this PR.

fadymondy and others added 2 commits October 7, 2026 20:09
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>
@fadymondy

Copy link
Copy Markdown
Contributor Author

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 VerifyContext are confirmed.

New finding:

  • F8 (high): updating a user does not apply the admin-target rule, so changing another admin's login identity (email) allows a takeover through the public reset flow.

Required:

  • Refuse credential and identity changes to other admins unless AUTH_IMPERSONATE_ADMINS is set.
  • Role changes and deletes of other admins stay allowed, but they must keep the last-admin invariant and be audited with the actor.
  • Update README and SECURITY for the new behaviour.

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

Copy link
Copy Markdown
Contributor Author

Security gate: FAIL (round 3). Full re-review on SQLite and Postgres. F8 is fixed.

New findings:

  • F9 (high): a chain of admin actions on another admin, under the default config, still ends in an account takeover.
  • F10 (low/medium): admin-issued links aren't re-checked when the target's role changes.

Required policy:

  • By default, admins can't change another admin's roles, permissions or email, and can't issue impersonation, reset or magic-link credentials for them.
  • Self-edits, deleting another admin (audited, last-admin rule kept) and promoting a user remain allowed.
  • Admin-issued reset and magic tokens are re-checked or invalidated when the target becomes an admin.
  • Docs updated to match.

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

Copy link
Copy Markdown
Contributor Author

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 handlePasswordReset runs before the redemption transaction, and it doesn't take the auth_admin_guard row that role changes serialise on. A promotion by a third admin that lands between the check and the commit sets the password on an account that is an admin by the time the write commits. The race reproduces in 5 of 25 runs on SQLite and in 25 of 25 on Postgres. The reproduction is TestReviewR4RacePromoteVsRedeem, preserved unchanged with base commit 901e2f7.

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.

@fadymondy

Copy link
Copy Markdown
Contributor Author

Owner decisions on the admin lifecycle threat model (approved). The author is now implementing one coherent change set on this branch:

  • F11 and F11c: every write that redeems a credential or sets a password re-checks the account's roles inside the write itself (UPDATE ... WHERE id=? AND roles=?), in one transaction. A refused token is still burned.
  • F12 (D1a): the plugin records who set each account's email and password. Promotion returns 409 if another admin set either one, unless the promoter explicitly accepts. The acceptance applies only to that one promotion and is audited (auth.admin_promoted). If the account holder later changes the password themselves, the record is not cleared.
  • F13: impersonation and magic-link sessions stop working once their target becomes an admin. F11b is not a separate blocker, provided the regression matrix proves F13 covers it.
  • Strict session revalidation (D2b, on by default): each authenticated request reloads the account's current state.
    • A deleted account gets 401.
    • A demoted admin loses admin authority immediately, including on claims-based RequireRole checks.
    • This release adds no token-version redesign.
  • The rest of §14 and the full deterministic regression matrix, on SQLite and Postgres.

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.

fadymondy and others added 5 commits October 7, 2026 21:39
…, 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>
@fadymondy

Copy link
Copy Markdown
Contributor Author

Security review Round 5: FAIL (High). Final independent gate against the approved lifecycle threat model v2

Reviewed commit: 56e32ae (feat/5-admin-api-authz). The review was independent and ran on both SQLite and Postgres. Per the owner's stop rule, the review halted at the first High finding. Nothing was patched during the review.

F-R5-1 (High): an admin launders email provenance through the promoter's write and gains authentication as an admin

Invariants 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):

  1. A sends PATCH /api/auth/admin/users/U with {"email":"a-inbox@…"}. U's email provenance is now A.
  2. A calls POST /api/auth/password/forgot for that address and receives the token in the inbox A controls.
  3. A calls POST /api/auth/password/reset and sets a password A knows. This self-service redeem (reset.go:163, the issuer == "" branch) writes the password unconditionally and records no password provenance: markProvenance (reset.go:198) runs only on the admin-issued branch.
  4. C sends PATCH /api/auth/admin/users/U with {"roles":["admin"],"email":"bob-clean@…"}, a plausible cleanup. It returns 200 with no 409.
    • admin.go:632 sets emailChanges because the email changes in this request.
    • admin.go:642 passes it to taintedFields(…, skipEmail) (admin_state.go:120), which drops A's email taint as the "promoter's own write".
    • The password provenance is empty, so no field is reported as tainted.
  5. A logs in as U with the password from step 3. GET /api/auth/admin/users returns 200, so A is authenticated as admin U.

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. TestLifecyclePromoterOwnWriteExempt covers only a promoter overwriting their own earlier write. It does not cover the exemption masking an earlier write by a third party.

F-R5-1c (High, distinct variant): a self-service reset token survives the email change and the promotion

A 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

  • Tests: review5_launder_test.go (reviewer patch auth-review-tests-r5.patch, applied on 56e32ae).
  • SQLite: go test -count=1 -run TestReview5 .
  • Postgres: go test -count=1 -tags authpg -run TestReview5 . with AUTH_REVIEW_PG_URL pointing at a throwaway DB.
Test Result on SQLite and Postgres
TestReview5LaunderViaPromoterEmailWrite FAIL: the takeover succeeds
TestReview5SelfServiceTokenSurvivesPromotion FAIL: the pre-promotion token redeems on the admin account
TestReview5LaunderViaSeparateEmailEdit FAIL. Weak and non-blocking on its own; it matters only combined with the two above
TestReview5ControlEmailTaintGate PASS. Without the email change in the same request, promotion correctly returns 409, so the gate works and only the exemption defeats it

The behaviour was identical on SQLite and Postgres. The orchestrator independently re-ran the SQLite results on 56e32ae and confirmed the cited code paths.

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 56e32ae before the new tests. The auth side of the template advisory cannot be considered fixed while this path exists.

Owner decision (approved): one contained correction to the lifecycle model, implementing (a), (b) and (c) together

  • (a) No laundering through the promoter's write. Promotion evaluates the account's provenance as it existed before the requested promotion or identity mutation. Changing a field in the same request that grants admin authority must not turn a tainted identity into a clean one.
  • (b) Self-service recovery preserves provenance. Credential provenance follows the authority that established the recovery path, not the endpoint used to redeem it.
  • (c) Recovery credentials do not survive security-boundary transitions. At minimum this covers a change of email or recovery identity and promotion to admin. It is enforced by authoritative validation at redemption, and burn and single-use semantics stay correct when redemption is refused.
  • Threat model correction: "Self-service is not a trust source. Its trust derives from the provenance and current validity of the recovery identity/credential used to perform it." F-R5-1 and F-R5-1c are added to the model and the regression matrix.
  • After the fix, a fresh independent reviewer reruns the complete gate. Nothing merges or tags until then. auth#7 stays out of scope, and dashboard#3 stays parked.

🤖 Generated with Claude Code

fadymondy and others added 6 commits October 7, 2026 22:06
…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>
@fadymondy

Copy link
Copy Markdown
Contributor Author

Security review Round 6: FAIL (Medium). Full independent gate on ee074e2

The gate was independent and ran on both SQLite and Postgres. Under the owner's stop rule it halted at the first finding of Medium or higher. Nothing was patched during the review.

F-R6-1 (Medium): a demoted admin can redeem a reset link it issued before the demotion, then authenticate as the target

Violates: the approved principle "credential valid when issued does not imply credential valid after identity/privilege transition". The transition here belongs to the issuer, not the target.

Exact sequence

  1. Admin A calls POST /api/auth/admin/users/{U}/reset-password for a normal user U and keeps the link.
  2. A is demoted (SetRoles(A, nil)). A's existing session is refused immediately, as D2 requires.
  3. A redeems the link at POST /api/auth/password/reset and sets a password A knows.
  4. A logs in as U.

Path: the redeem transaction in reset.go, around lines 158–230

  • Line 160 reads the issuer from auth_reset_issuers.created_by, but nothing checks that the issuer still exists or is still an admin.
  • recoveryContextHolds (line 199) binds only the target's email and privilege epoch.
  • The roles check at line 216 looks only at the target.
  • Magic links do check the issuer (checkImpersonation / linkContextHolds), so the two token types are inconsistent.

Scope: the window lasts up to PasswordResetTTL (30 minutes), and only non-admin targets are affected.

  • Promoting the target bumps the epoch, which voids the token.
  • Peer-admin targets are denied by default.

No path to Admin B was found, so I1 holds. The finding is Medium because it is exactly the "valid when issued, not after a transition" case.

Reproduction

  • Tests: review6_attack_test.go (reviewer patch auth-review-tests-r6.patch, on ee074e2).
  • SQLite: go test -count=1 -run 'TestR6ResetLinkIssuerDemoted|TestR6DemotedIssuerTakesOverTarget' .
  • Postgres: the same command with -tags authpg and AUTH_REVIEW_PG_URL.
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

fadymondy and others added 3 commits October 7, 2026 22:52
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>
@fadymondy

Copy link
Copy Markdown
Contributor Author

Round 6 security gate (fresh reviewer, complete scope): PASS on 16af359

This is the independent gate against the Admin Lifecycle Threat Model v2 (with the Round 5 and Round 6 amendments) and the owner decisions. Reviewed head: 16af35949ec32316bd94a082bbb1344d5eb7b9e2. No Medium-or-higher finding. No production code was changed during the review.

The primary invariant holds under every tested sequence and race: without the explicit cross-admin exception, Admin A never obtains authentication as Admin B.

F-R6-1 fix

  • TestR6DemotedIssuerTakesOverTarget and TestR6ResetLinkIssuerDemoted are unchanged from the Round 6 FAIL. Both pass on SQLite and Postgres.
  • A credential whose issuer was deleted, demoted, self-demoted, or given a malformed id (unknown, root,evil, whitespace, 300 characters) is refused. The token is burned, the response is identical to an unknown token, and the password and cookie are unchanged.
  • Mutation check: with issuerHolds neutered, only the reset tests fail. On magic links, checkImpersonation is a second, independent guard.

Results

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 SetRoles each 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. verify is reachable only through VerifyContext. 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:true plus 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 verify tests, accept as audit-only, the promoter-as-sole-writer exemption, inherited provenance for self-service recovery, the adminTx caller recheck, #nosec G101, and the tightened writer-set oracle.
  • GHSA-8jr8-x9fc-8qvh: fixed on the auth side. Removing the template's /api/admin remains 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 requireAdmin authenticates it against the database first, where the target is still not an admin. The result is {"error":"forbidden"} (the requireAdmin deny), before any lock or adminTargetErr.
  • 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=3 cannot 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 SetRoles changes privilege without firing admin_promoted or admin_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.registered carries 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

@fadymondy
fadymondy merged commit 38aea0d into main Oct 8, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Admin user-management API under /api/auth/admin with explicit admin authorization and audited impersonation

1 participant