Repository navigation
fix(platform): close account and credential authorization holes - #3159
Merged
Merged
Conversation
The live Better Auth access matrix granted `auditLogs: ['read']` to every active role via `uniformGrants(['read'])`, so any member/editor/developer could read the whole org audit trail (actor email, IP, user agent) by hitting /api/app/audit-logs directly — a regression from the 0.4 admin-only doctrine (#1505/#1852) still encoded in the retained RLS matrix and the frontend ability. Pin `auditLogs` explicitly per role: owner/admin read+write, developer/editor write-only (their RLS-wrapped mutations still self-audit), member none. Every audit read route gates on this via `authorizeRls`.
Better Auth's apiKey plugin measures `rateLimit.timeWindow` in MILLISECONDS (`evaluateRateLimit` resets the per-key counter once `now - lastRequest > timeWindow`), so the configured `timeWindow: 60` was a 60ms window: any two requests more than 60ms apart reset the counter, leaving API keys effectively unthrottled. Set the intended 60-second window to 60_000 and export it as `API_KEY_RATE_LIMIT` so a unit test pins the value and unit against a silent regression.
When org 2FA enforcement returned 'blocked', the sign-in after-hook only
swapped the response body to {twoFactorRedirect,enrollRequired} while
keeping a fully usable session — no middleware re-checked the decision,
so a client that ignored the body kept full API access to every
org-scoped route. Gate `requireOrgMember` on the 'blocked' decision: a
blocked user is refused 403 on org data, while the enrolment path stays
reachable (Better Auth's /api/auth/two-factor/* is handled before this
middleware, and /api/app/two-factor/status is session-scoped).
Two account-seizure holes in the users password service: setMemberPassword gated only on isAdminRole(caller) in the target's org, never checking the target's role or other memberships, then rewrote the GLOBAL credential (one `account` row per user) and killed every session. So an admin could set the OWNER's password and log in as owner, and — the credential being global — one org's admin could seize a user shared with orgs the admin does not administer. Add `evaluateCredentialResetAuthority`: the caller must strictly outrank the target in EVERY org the target belongs to, and never target themselves (self-service proves the old password). This keeps the admin door AND blocks owner/peer/cross-org seizure. Deliberately stricter than the passkey/2FA sibling ops, which only remove a factor; a password reset hands the actor a working login. update-password accepted trigger:'forced' straight from the request body, and the forced branch skipped the current-password check — so any holder of a live session could rotate the password without proving the old one. Derive forced eligibility server-side from computePasswordExpiry().expired (`forcedResetEligible`); the client `trigger` is advisory only and can never widen authority.
Extend the real-Postgres integration harness with probes for the account/credential/session authorization class: - credential reset: an admin cannot seize the org owner nor a cross-org-shared user, while an owner's reset of a low member still works (throwaway orgs/users, so a base run's successful takeovers never touch the shared fixture); - update-password: a client-supplied trigger:'forced' cannot skip the current-password check; - two-factor: a 'blocked' session is denied 403 on org routes while the enrolment status endpoint stays reachable; - audit reads: a non-admin member is refused on every audit read entry point (list/summary/errors/by-id/integrity); - api-key: a minted key persists a 60000ms window, not 60ms.
larryro
marked this pull request as ready for review
September 3, 2026 04:17
…dening # Conflicts: # services/platform/backend/auth/access.test.ts
This was referenced Sep 3, 2026
Israeltheminer
added a commit
that referenced
this pull request
Sep 3, 2026
Two authorization and audit behaviours the port dropped. ## A read-only member could write to conversations Reply, send outbound mail, close, bulk-act, delete, and act on individual messages. 0.4 ran every conversation mutation through `mutationWithRLS`, whose `conversations` and `conversationMessages` rules put each write through `authorizeRls` at editor-or-above. `viewerCanWrite` reuses that same matrix rather than declaring a second role list. It composes with the half that was correctly ported: a write door checks the role first, then loads the row through `loadVisibleConversation`, which applies `conversationAssignmentAllows` per row. Role decides whether you may change a conversation; assignment decides which ones you can see at all, and is stricter still. Twelve doors carry the check, as the handler's first statement — before the body parse, so a refusal never depends on the payload. The two assignment doors are the deliberate exception: they gate on `viewerIsAdmin` in the service, which is stricter than editor, so a route-level editor check would loosen them. Sending outbound mail is the sharpest of the twelve — it leaves the building under the organization's name. The attachment-fetch door answers 501 today, but it is where the Gmail/Outlook `get_attachments` fetch lands, so it is gated now rather than after that wiring makes it live. ## 2FA and passkey events audited only on failure An attacker who added a passkey and disabled 2FA left no successful-action trail. All five events now audit, inside the same serializable transaction as the state change. The 0.4 action names are reused verbatim — `2fa_enrolled`, `2fa_disabled`, `passkey_added`, `passkey_removed`, `passkey_sign_in`. A renamed action silently breaks any existing query or export that groups on it. Checked against 0.4's full vocabulary: `passkey_removed` and `passkey_revoked_by_admin` were distinct events there and stay distinct. ## Tests Three layers, because they fail on different mistakes: - `viewerCanWrite` is pinned across the whole role vocabulary, so a matrix edit that widens it by accident cannot pass unnoticed. - The twelve doors are driven through the real handlers: a `member` gets 403 and no service function is reached; an `editor` never sees the gate's refusal envelope, and the four doors whose services are mocked run all the way through. - A gate applied door by door invites the next door to ship ungated, so a static check reads the route table and fails when a POST, PATCH or DELETE handler has no role check on its first line. The assignment pair is allowlisted there, and a companion assertion pins their service-side admin check so the allowlist cannot become a hole. `integration-check.ts` walks all twelve doors end to end at `member` expecting 403 and confirms the thread is untouched, then flips the row to `editor` and re-walks. The audit-log third of this change is dropped: #3159 landed the same role matrix, and main's doors already call `authorizeRls(role, 'auditLogs', 'read')`, which that matrix now denies below admin. Restating the rule as a second `isAdminRole` check at each door would be a divergent copy.
Israeltheminer
added a commit
that referenced
this pull request
Sep 3, 2026
Two authorization and audit behaviours the port dropped. ## A read-only member could write to conversations Reply, send outbound mail, close, bulk-act, delete, and act on individual messages. 0.4 ran every conversation mutation through `mutationWithRLS`, whose `conversations` and `conversationMessages` rules put each write through `authorizeRls` at editor-or-above. `viewerCanWrite` reuses that same matrix rather than declaring a second role list. It composes with the half that was correctly ported: a write door checks the role first, then loads the row through `loadVisibleConversation`, which applies `conversationAssignmentAllows` per row. Role decides whether you may change a conversation; assignment decides which ones you can see at all, and is stricter still. Twelve doors carry the check, as the handler's first statement — before the body parse, so a refusal never depends on the payload. The two assignment doors are the deliberate exception: they gate on `viewerIsAdmin` in the service, which is stricter than editor, so a route-level editor check would loosen them. Sending outbound mail is the sharpest of the twelve — it leaves the building under the organization's name. The attachment-fetch door answers 501 today, but it is where the Gmail/Outlook `get_attachments` fetch lands, so it is gated now rather than after that wiring makes it live. ## 2FA and passkey events audited only on failure An attacker who added a passkey and disabled 2FA left no successful-action trail. All five events now audit, inside the same serializable transaction as the state change. The 0.4 action names are reused verbatim — `2fa_enrolled`, `2fa_disabled`, `passkey_added`, `passkey_removed`, `passkey_sign_in`. A renamed action silently breaks any existing query or export that groups on it. Checked against 0.4's full vocabulary: `passkey_removed` and `passkey_revoked_by_admin` were distinct events there and stay distinct. ## Tests Three layers, because they fail on different mistakes: - `viewerCanWrite` is pinned across the whole role vocabulary, so a matrix edit that widens it by accident cannot pass unnoticed. - The twelve doors are driven through the real handlers: a `member` gets 403 and no service function is reached; an `editor` never sees the gate's refusal envelope, and the four doors whose services are mocked run all the way through. - A gate applied door by door invites the next door to ship ungated, so a static check reads the route table and fails when a POST, PATCH or DELETE handler has no role check on its first line. The assignment pair is allowlisted there, and a companion assertion pins their service-side admin check so the allowlist cannot become a hole. `integration-check.ts` walks all twelve doors end to end at `member` expecting 403 and confirms the thread is untouched, then flips the row to `editor` and re-walks. The audit-log third of this change is dropped: #3159 landed the same role matrix, and main's doors already call `authorizeRls(role, 'auditLogs', 'read')`, which that matrix now denies below admin. Restating the rule as a second `isAdminRole` check at each door would be a divergent copy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem class
Account / credential / session authorization holes that let one user or admin seize another account or bypass a security control. Five findings, all confirmed in code and reproduced against real Postgres. None refuted.
Enforced authority model (one model, not per-endpoint patches)
Authority is by role rank (owner 5 > admin 4 > developer 3 > editor 2 > member 1 > disabled 0) evaluated per organization, with the credential's global nature made explicit. An actor may seize/reset another account only when it strictly outranks the target in every org the target belongs to; the owner is never seizable; self-service always proves the current password; org-required 2FA is a server-side gate on every org-scoped request, not a client-side redirect; audit reads are admin-only. The email/password credential is a single
accountrow per(userId, providerId='credential')— one global credential — so a reset governs identity in all the target's orgs, which is why cross-org authority is required before one is allowed.Findings
1 (high) — Admin could reset the OWNER's password / seize a cross-org-shared user
domains/users/service.ts::setMemberPasswordgated only onisAdminRole(caller)in the target's org, then rewrote the global credential and killed sessions. Threat: admin→owner privilege escalation, and (credential being global) one org's admin taking over a user shared with orgs the admin doesn't administer. Fix: new pureevaluateCredentialResetAuthority(inauth/membership.ts) — caller must strictly outrank the target in every org the target belongs to, never self; the admin-door check is retained on top. Deliberately stricter than the passkey/2FA sibling ops (which only protect owners) because a password reset hands the actor a working login, not just factor removal. Tests:membership.authority.test.ts(10 cases) + integration probe (admin→owner 403, admin→cross-org 403, owner→member 200).2 (high) — Client-chosen
trigger:'forced'skipped current-password re-authupdate-passwordtooktrigger:'forced'from the request body and the forced branch skipped the current-password check. Threat: any holder of a live/stolen session could rotate the password without knowing it. Fix: forced eligibility is derived server-side fromcomputePasswordExpiry().expired(forcedResetEligible); the clienttriggeris advisory only. Tests:forced-reset.test.ts+ integration probe (forced-without-current → 400current_password_required; legit change with current password → 200).3 (high) — Org 2FA enforcement was client-side only
On a
blockeddecision the sign-in after-hook only swapped the response body while keeping a usable session; no middleware re-checked it. Threat: a client ignoring the body kept full API access with no 2FA. Fix:requireOrgMembernow denies (403two_factor_enrollment_required) whenevaluateTwoFactorEnforcementreturnsblocked. Enrolment stays reachable: Better Auth's/api/auth/two-factor/*runs before app middleware and/api/app/two-factor/statusis session-scoped. Test: integration probe (blocked session → 403 on an org route; status endpoint → 200).4 (high) — Audit-log reads regressed to every active role
auth/access.tsgrantedauditLogs:['read']to member/editor/developer viauniformGrants(['read']); every audit read route gates on it. Threat: any member could read the whole org audit trail (actor email, IP, user agent) by direct URL. Fix: pinauditLogsper role to match the retained RLS matrix + frontend ability — owner/admin read+write, developer/editor write-only, member none. Tests:access.test.ts+ integration probe (non-admin member refused 403 on list/summary/errors/by-id/integrity).5 (high) — API-key rate limiter was inert
Better Auth's apiKey plugin reads
rateLimit.timeWindowin milliseconds, sotimeWindow: 60was a 60ms window — the counter reset between virtually every request. Fix: set to60_000and exportAPI_KEY_RATE_LIMIT. Tests:auth.rate-limit.test.ts(pins value + unit) + integration probe (a minted key persistsrateLimitTimeWindow=60000).Refuted
None — all five reproduced on base (see base counts).
Gates (observed)
serverproject, 4 files / 20 tests): green on branch. Base proof (stash the 5 source files, keep tests): 18 failed / 2 passed — every security assertion red on base.tsc --noEmit): exit 0. oxlint --type-aware (touched files): exit 0.tools/opengrep/run.sh, touched files + per-commit pre-commit hook): 0 findings.Cross-class discoveries (not fixed here — kept to this class)
members/service.ts::revokePasskeyForMemberandresetTwoFactorForMemberact on global factors but guard with owner-protection only, not the cross-org authority guard. They are factor removal (DoS/weakening), not seizure, so lower severity — but a cross-org admin can still strip a shared user's factors in an org they don't administer. Candidate follow-up.organizations/routes.tsandconnectors/oauth-routes.tscallrequireOrganizationMemberdirectly, bypassing therequireOrgMembermiddleware, so the new 2FA gate does not cover them — intentional (navigation + OAuth-consent surfaces must stay reachable for the enrolment redirect), noted for awareness./api/v1, API-key auth) is a distinct machine credential and is not 2FA-gated by design.