From af76bfbf45828cda9d77d6f582629e5cc5823c86 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:36:43 +0200 Subject: [PATCH 1/9] docs(auth): record stack security review --- docs/security/auth-stack-review-2026-07-14.md | 197 ++++++++++++++++++ 1 file changed, 197 insertions(+) create mode 100644 docs/security/auth-stack-review-2026-07-14.md diff --git a/docs/security/auth-stack-review-2026-07-14.md b/docs/security/auth-stack-review-2026-07-14.md new file mode 100644 index 000000000..901929b01 --- /dev/null +++ b/docs/security/auth-stack-review-2026-07-14.md @@ -0,0 +1,197 @@ +# Authentication stack security review + +Date: 2026-07-14 + +Scope: the complete authentication stack from `main` through +`auth/08-hardening-operations` (`e3fde34...f024438`), with emphasis on +architecture, trust boundaries, concurrency, and operational security. + +## Decision + +**Do not merge or deploy the stack as a completed authentication service.** + +The stack establishes useful types, schemas, and policy helpers, but it remains +foundation scaffolding. The executable serves only health endpoints, the +repository handles cannot execute persistence operations, the downstream SDK +does not validate tokens, and the private RPC surface is not implemented. The +current tests do not exercise a real authentication flow or PostgreSQL +invariant. + +## Release-blocking findings + +### P0 — The authentication authority is a health-only shell + +`apps/auth-service/src/lib.rs:9-24` suppresses dead-code warnings for every +policy module and `apps/auth-service/src/lib.rs:75-84` registers only liveness +and readiness. `apps/auth-service/src/main.rs:11-20` binds only the public +listener. There are no discovery, JWKS, authorization, token, revocation, +passkey, federation, session, logout, or account-management endpoints, and the +configured private listener is never bound. + +The frontend nevertheless links to login flows that return 404, while the +protobuf contract has no generated server/client, TLS listener, service-token +verification, or method authorization. + +**Required action:** relabel the stack as scaffolding or implement each planned +HTTP/RPC flow with its cryptographic and persistence dependencies. Require an +end-to-end test for every advertised flow before describing the service or +runbooks as operational. + +### P0 — Persistence and transactional invariants are not implemented + +Every type in `crates/database/src/repositories.rs:3-23` is an empty +`PhantomData` handle with no operations or executor. `Database` and +`DatabaseTransaction` create those handles without lending the pool or SQLx +transaction (`crates/database/src/connection.rs:84-113` and +`crates/database/src/transaction.rs:12-40`). + +Account creation, session revocation, event/audit co-commit, WebAuthn ceremony +consumption, authorization-code exchange, refresh rotation/replay response, and +federated linking therefore cannot be performed, let alone atomically. The +ceremony helper only inspects a copied `consumed` flag +(`apps/auth-service/src/passkey.rs:21-32`), so two replicas would both accept the +same unclaimed record if it were wired directly. + +**Required action:** make repository handles borrow a private pool/transaction +executor and implement typed persistence operations. Consume one-time records +with conditional `UPDATE ... RETURNING` statements and keep their security side +effects in deliberate transactions. Prove rollback and exactly-one-winner +behavior with multi-connection PostgreSQL tests. + +### P0 — The downstream SDK performs no JWT validation + +`AuthMiddleware` ends after configuration getters and bearer-string parsing at +`crates/auth-middleware/src/lib.rs:33-95`. It never validates `typ`, `alg`, +`kid`, signature, issuer, audience, `exp`, `nbf`, or `iat`, and it implements no +JWKS retrieval/cache/rotation behavior. Its advertised verified principal also +has publicly constructible fields (`crates/auth-middleware/src/lib.rs:7-14`) and +is re-exported to consumers. + +This makes the intended local-validation boundary unavailable and makes it easy +for a consumer to treat an unchecked, caller-constructed value as an +authenticated identity. + +**Required action:** implement a fixed-algorithm, fail-closed verifier with +bounded JWKS caching and exact claim validation. Make the principal opaque and +constructible only after successful verification; expose read-only accessors +and framework adapters that preserve authentication-versus-authorization error +semantics. + +### P1 — Active verified-email uniqueness is raceable and bypassable + +The trigger in +`crates/database/migrations/0002_identity_sessions.sql:24-41` claims to lock +matching rows but performs only an `EXISTS` query. Concurrent transactions can +both observe no committed owner and insert the same verified email for two +active accounts. Locking existing rows alone would still not serialize the +initial no-row case. + +The trigger also runs only for changes to `user_emails`. Two disabled accounts +may hold the same verified address and both may later transition to `active` +without rechecking the invariant. This makes verified-email federation linking +ambiguous and risks binding authentication to the wrong account. + +**Required action:** represent active email ownership with a transactionally +maintained row uniquely keyed by normalized email, or serialize claims and +reactivations with a per-email lock and checks covering both tables. Add +concurrent insert and disabled-to-active tests using separate connections. + +### P1 — WebAuthn RP validation accepts attacker origins + +`apps/auth-service/src/passkey.rs:45-54` accepts any string starting with +`https://` that contains the RP ID. For RP ID `example.com`, origins such as +`https://example.com.evil`, `https://evil.test/example.com`, and +`https://example.com@evil.test` pass. + +**Required action:** parse origins as URLs; reject userinfo, paths, query, +fragment, and non-HTTPS schemes; compare against an exact normalized origin +allowlist; and validate the RP ID against the hostname using DNS-label +boundaries and the WebAuthn rules. Add the examples above as negative tests. + +### P1 — OIDC client authorization policy has no authoritative model + +`crates/database/migrations/0004_oidc_tokens.sql:1-6` records only a client ID, +enabled state, and redirect URIs. It has no registered audiences, scopes, grant +types, client-authentication methods, or post-logout URIs. Authorization codes +store arbitrary scopes and audience, do not record the PKCE method, and do not +relationally bind their redirect to the client's registration. The +`exact_audience` helper accepts a slice from an unspecified caller +(`apps/auth-service/src/oidc.rs:61-69`). + +**Required action:** model static client authorization explicitly and load it +through typed repository operations. Derive allowed audience/scope solely from +that registration, persist `S256`, and atomically bind/consume codes and refresh +families. Test cross-client audience, scope, redirect, and replay failures. + +### P1 — Readiness does not test signing-key usability + +`SecretReference::parse` accepts any non-whitespace string and +`SecretReference::is_configured()` always returns true +(`crates/configuration/src/lib.rs:57-69`). `main` reduces the key dependency to +that boolean, and readiness combines it only with a database query +(`apps/auth-service/src/main.rs:15-18`, `apps/auth-service/src/lib.rs:86-96`). + +A missing, revoked, unauthorized, or unreachable key therefore reports ready +and continues receiving token traffic. + +**Required action:** resolve an allowlisted key-provider reference at startup, +validate an active asymmetric key and stable `kid`, and probe bounded provider +usability/rotation metadata from readiness without exposing key material. + +### P1 — The documented migration command leaks database credentials + +`justfile:23-24`, `crates/database/README.md:7`, and +`docs/operations/auth-release.md:3-5` pass `$DATABASE_URL` as a positional +argument to `just`. Credentials embedded in the URL can appear in process +listings, shell history, and command telemetry. + +**Required action:** make `just migrate` inherit `DATABASE_URL` from its +environment or accept a secret-provider reference; never put the URL in argv. + +## Additional security and operational findings + +- **P2 — insecure production transport is accepted.** + `crates/configuration/src/lib.rs:30-40` accepts HTTP for arbitrary public + hosts, and `crates/database/src/connection.rs:24-42` does not enforce verified + PostgreSQL TLS. Default to HTTPS and verified database TLS; allow loopback + exceptions only behind explicit development configuration. + +- **P2 — shutdown does not meet the runbook.** + `apps/auth-service/src/main.rs:19-26` listens only for Ctrl-C/SIGINT and puts no + deadline on draining. Handle SIGTERM, stop readiness/intake first, and bound + shutdown so orchestrator termination cannot drop transactions or hang. + +- **P2 — health and hardening signals are absent.** + The readiness database query has no explicit query deadline, failures are + silently collapsed to 503, and telemetry provides formatting but no bounded + auth/replay/rate-limit/key/RPC metrics. No endpoint rate limits or shared + replay controls exist. + +- **P3 — refresh parsing permits unbounded allocation.** + `apps/auth-service/src/oidc.rs:37-54` base64-decodes an arbitrary-size secret + before imposing only a minimum length. Require an exact encoded/decoded size + before allocation and enforce request-body limits. + +- **P3 — one low-severity JavaScript advisory is present.** + `pnpm audit` reports `GHSA-pxg6-pf52-xh8x` for transitive `cookie@0.6.0` via + SvelteKit. The current shell does not set application cookies, but the + dependency should be upgraded/overridden before cookie-backed auth is added. + +## Verification performed + +- `cargo fmt --check`: passed. +- `cargo clippy --workspace --all-targets --all-features -- -D warnings`: + passed. +- `cargo test --workspace`: passed; only 12 small unit tests ran, with no + database, HTTP, browser, cryptographic, multi-replica, or RPC integration + coverage. +- `pnpm install --frozen-lockfile`: passed. +- `pnpm -r check`: passed. +- `pnpm -r build`: passed; adapter-auto could not identify a production target. +- `cargo deny check advisories`: passed. +- `pnpm audit`: one low-severity advisory, described above. + +The exact redirect matcher, PKCE S256 computation, keyed refresh-token digest, +canonical UUID/text parsing, secret debug redaction, SQLx dependency boundary, +dependency-free liveness endpoint, and auth-web baseline CSP/referrer/cache +headers were also reviewed and did not produce additional findings. From 767feb0ae7eec821b8a5b1f522478abf1da42d26 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:05:59 +0200 Subject: [PATCH 2/9] docs(auth): record security remediation evidence --- docs/security/auth-stack-review-2026-07-14.md | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/docs/security/auth-stack-review-2026-07-14.md b/docs/security/auth-stack-review-2026-07-14.md index 901929b01..3bad20732 100644 --- a/docs/security/auth-stack-review-2026-07-14.md +++ b/docs/security/auth-stack-review-2026-07-14.md @@ -6,6 +6,61 @@ Scope: the complete authentication stack from `main` through `auth/08-hardening-operations` (`e3fde34...f024438`), with emphasis on architecture, trust boundaries, concurrency, and operational security. +## Remediation follow-up + +The decision and findings below describe the originally reviewed commits. They +were accurate: the PRs had been presented as implementations even though most +contained only schemas, policy-shaped helpers, and UI/protocol scaffolding. The +stack was subsequently rebuilt on the same ordered branches and re-reviewed on +2026-07-14. The cause was an implementation/review failure, not a regression: +acceptance criteria were treated as file-shape requirements, tests exercised +helpers rather than flows, and completion was reported without tracing a real +request through HTTP, cryptography, persistence, and concurrency boundaries. + +The release-blocking findings have been remediated as follows: + +- The authority now exposes and wires WebAuthn, OIDC discovery/JWKS/code/token/ + refresh/revoke/userinfo/logout, GitHub and Google login, account-security + operations, and a separate mTLS Tonic listener. +- Repositories now borrow a real pool or transaction executor. Conditional + `UPDATE ... RETURNING` consumption is used for ceremonies and codes; refresh + rotation locks records and revokes a family on replay. +- Static OIDC clients own exact redirect/post-logout URIs, scopes, audiences, + enabled state, refresh permission, and authentication method. Access and ID + tokens are ES256 and cryptographically separated by `typ` and audience. +- The SDK now validates a single Bearer value, fixed `at+jwt`/ES256/`kid`, a + trusted cached JWKS key, signature, exact issuer/audience, time claims, and + typed UUIDv7 claims. `AuthenticatedUser` is opaque outside the validator. +- Active verified-email ownership is represented by a unique lockable row and + is synchronized on account status changes. Federation uses verified provider + email only for the initial link and stores issuer/subject as the durable key. +- WebAuthn uses `webauthn-rs` with parsed exact origins and server-side, + single-use state. The three attacker-controlled origin examples in this + report are regression tests. +- Production public/database transport fails closed unless HTTPS and verified + PostgreSQL TLS are configured. Secret locators are allowlisted and redacted; + readiness resolves the signing, provider, and RPC TLS dependencies. +- Migration credentials are environment-only. Refresh/cookie secrets have + exact bounds, public bodies and handler time are bounded, sensitive endpoint + classes are rate limited, and SIGINT/SIGTERM coordinate graceful public and + private listener shutdown. + +Verification after remediation includes the full Rust format/test/clippy gates, +SvelteKit type checking and an adapter-node production build, real ES256 and +software-WebAuthn interoperability tests, JWKS failure/rotation tests, and an +empty PostgreSQL 17 database test using separate concurrent connections. The +database test proves rollback, verified-email claim/reactivation exclusion, +exactly-one WebAuthn/federation transaction consumption, duplicate credential +and provider-subject rejection, optimistic profile conflict, idempotent session +revocation, event ordering, and refresh one-winner/replay-family revocation. + +Remaining deployment work is environmental rather than a claim of an +implemented control: production must provision reviewed OIDC/service clients, +ES256 and mTLS key material, GitHub/Google applications, and exercise live +provider/browser and backup/restore drills before release. The in-process rate +limiter is per replica; a shared disposable limiter requires a separately +reviewed failure-mode design if aggregate limits are required. + ## Decision **Do not merge or deploy the stack as a completed authentication service.** From edd583d099e508bfe521d8c79bfd857aaf755454 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:20:19 +0200 Subject: [PATCH 3/9] docs(auth): record second security review --- docs/security/auth-stack-review-2026-07-14.md | 226 +++++++++++++++++- 1 file changed, 220 insertions(+), 6 deletions(-) diff --git a/docs/security/auth-stack-review-2026-07-14.md b/docs/security/auth-stack-review-2026-07-14.md index 3bad20732..c2983924b 100644 --- a/docs/security/auth-stack-review-2026-07-14.md +++ b/docs/security/auth-stack-review-2026-07-14.md @@ -2,11 +2,224 @@ Date: 2026-07-14 -Scope: the complete authentication stack from `main` through -`auth/08-hardening-operations` (`e3fde34...f024438`), with emphasis on -architecture, trust boundaries, concurrency, and operational security. +Original scope: the complete authentication stack from `main` through the +then-current `auth/08-hardening-operations`, with emphasis on architecture, +trust boundaries, concurrency, and operational security. -## Remediation follow-up +Second-review scope: the rebuilt cumulative stack from `main` at `e3fde34` +through `auth/08-hardening-operations` at `47d9f4d`, as presented by this final +audit PR. The second review was performed independently across architecture, +security, and remediation-evidence validation. + +## Second review verdict + +**Do not merge or deploy the stack as a completed authentication service.** + +The rebuild replaces the original scaffolding with substantial executable +code, but the prior remediation follow-up overstates completion. The second +review found three release blockers and several P1 trust, concurrency, and +operability gaps. In particular, account disablement is not an authentication +invariant, signing-key rotation is both unsupported and destructive to refresh +tokens, and there is still no deployable end-to-end browser/OIDC flow. + +The findings below are based on the rebuilt implementation and supersede the +claims in **First remediation follow-up (superseded)**. + +### P0 — Disabled accounts can authenticate with passkeys + +Passkey authentication consumes and verifies a ceremony, updates a credential, +and creates a new session without loading the user or requiring an active +account (`apps/auth-service/src/passkey.rs:316-363`). Browser-session resolution +joins only `browser_session_secrets` and `sessions`, so an existing session for +a subsequently disabled account remains accepted by account endpoints +(`crates/database/src/repositories.rs:768-773`). Private RPC likewise reports a +session active from revocation and expiry alone +(`apps/auth-service/src/service_rpc.rs:207-229`). Federation checks account +status before session creation in a separate transaction, leaving a disable +race (`apps/auth-service/src/federation.rs:475-495,582-617`). + +OIDC code and refresh queries do require an active user, so the same account has +different status semantics at different trust boundaries. Administrative +disablement therefore does not reliably disable authentication or central +session use. + +**Required action:** enforce active account status transactionally whenever a +session is resolved or created. Make account disablement revoke sessions and +refresh families and append its audit/event records in the same transaction. +Make RPC session status include account status and add disable-versus-login race +tests. + +### P0 — Signing-key rotation is unsupported and invalidates refresh tokens + +The authority loads exactly one ES256 private key and publishes exactly one JWK +(`apps/auth-service/src/oidc.rs:58-110`). It also passes the signing PEM bytes +into OIDC construction and derives the authorization-code/refresh-token digest +key from those bytes (`apps/auth-service/src/main.rs:25-56` and +`apps/auth-service/src/oidc.rs:223-235`). Replacing the signing key therefore +removes the old public key immediately and invalidates every outstanding +authorization code and refresh token, despite refresh tokens being issued for +up to 30 days. + +This makes the overlap procedure in +`docs/operations/auth-key-rotation.md:3-7` impossible to perform and turns a +routine signing-key rotation into a global session outage. + +**Required action:** use an independently managed, stable digest key for opaque +tokens. Implement an active-plus-retired signing key ring that can publish old +and new JWKs concurrently, then prove new issuance, overlap, removal after the +last token expiry, and refresh continuity in an authority integration test. + +### P0 — No complete browser/OIDC authorization flow is deployable + +An unauthenticated `/oauth/authorize` request is redirected back to the client +with `login_required`; there is no server-side authorization transaction, +login continuation, or authorization/consent UX +(`apps/auth-service/src/oidc.rs:284-369`). The independently deployed SvelteKit +application calls relative API paths, but has no proxy or server routes and no +documented edge-routing contract that composes page and API routes on +`auth.piquel.fr` (`apps/auth-web/src/lib/webauthn.ts:21-22` and +`apps/auth-web/svelte.config.js:1-3`). + +The account-security page's “Add a passkey” link opens the new-account +registration flow; the backend has no authenticated enrollment ceremony +(`apps/auth-web/src/routes/security/+page.svelte:8` and +`apps/auth-service/src/passkey.rs:137-247`). Social-identity listing, OIDC +authorization presentation/cancellation, and continuation after authentication +are also absent. + +**Required action:** define the production edge/BFF routing contract, persist a +bounded server-side authorization continuation, implement the authenticated +enrollment and authorization UX, and prove passkey, federation, SSO +continuation, cancellation, and logout with browser tests through that topology. + +### P1 — Public transport and rate limiting depend on an undefined proxy + +Production configuration validates an advertised HTTPS issuer, but the public +server binds a plaintext `TcpListener` with `axum::serve` +(`apps/auth-service/src/main.rs:88-105`). Secure deployment therefore requires +an external TLS terminator and private backend network, neither of which is an +enforced or documented invariant. The limiter keys on the TCP peer address +(`apps/auth-service/src/hardening.rs:51-74`), so a reverse proxy collapses all +users into one 30-per-minute login/WebAuthn bucket. Health endpoints share the +public bucket, and more than 10,000 recent source keys cause a full map scan +under a mutex on each request. + +**Required action:** terminate TLS in process or specify and enforce a trusted +proxy/private-listener topology. Define authenticated client-IP propagation, +separate health traffic, and use bounded incremental limiter eviction. + +### P1 — Refresh rotation ignores current client policy + +Refresh consumption checks that the client remains enabled, but does not +require `allow_refresh` or verify that the family's stored audience and scopes +remain allowed (`crates/database/src/repositories.rs:401-455`). Rotation then +reissues those stored grants unchanged (`apps/auth-service/src/oidc.rs:479-533`). +Removing a client scope/audience or disabling refresh therefore has no effect on +existing families. + +**Required action:** reapply current client policy inside the locked rotation +transaction, or explicitly model immutable grants and atomically revoke affected +families whenever client policy is reduced. Add policy-reduction tests. + +### P1 — Passkey state changes have revocation and last-factor races + +Authentication reads credential state and later updates it without a row lock +or optimistic state condition. The handler ignores the boolean result of the +conditional `revoked_at IS NULL` update, so a credential revoked between lookup +and update can still produce a session +(`apps/auth-service/src/passkey.rs:335-362` and +`crates/database/src/repositories.rs:665-677`). Concurrent authentications can +also overwrite newer authenticator state. + +The “keep at least one passkey” rule is a list-then-delete sequence over separate +pool operations (`apps/auth-service/src/passkey.rs:488-510`). Two concurrent +deletions can each observe two credentials and leave the account with none. + +**Required action:** lock or compare-and-swap credential state through +authentication completion, require a successful update before creating a +session, and enforce last-factor removal in one transaction with the relevant +credential set locked. + +### P1 — The SDK returns an unvalidated ID token + +The OIDC SDK creates and stores a nonce, but callback exchange validates only +state and sends the token request. The nonce is never consumed, and the returned +ID token is exposed after only response-shape checks +(`crates/auth-sdk/src/lib.rs:118-192,236-315`). There is no ID-token verifier in +the SDK that checks signature, issuer, client audience, time claims, and nonce. + +**Required action:** validate the ID token against the trusted issuer/JWKS and +the single-use callback nonce before returning an authenticated result. Keep raw +token access separate from a verified identity type and add negative nonce, +audience, issuer, algorithm, and signature tests. + +### P1 — Required replay evidence and RPC hardening are absent + +Refresh replay revokes the family but writes no security-audit record and emits +no replay-specific bounded signal (`apps/auth-service/src/oidc.rs:487-495`). +This contradicts `docs/operations/auth-incidents.md:3-4` and the Plan 08 release +gate. Public HTTP limits do not cover Tonic; private RPC has no server-enforced +request deadline or concurrency bound and no mTLS/authentication/permission +integration test (`apps/auth-service/src/main.rs:107-125`). + +**Required action:** co-commit a sanitized replay audit record with family +revocation, emit a bounded replay metric, and test both. Add RPC deadlines, +concurrency limits, certificate/service-identity binding policy, and black-box +mTLS and permission tests. + +### P1 — Passing gates do not verify the implemented system + +The default Rust suite passes but the sole PostgreSQL integration test is +ignored unless `TEST_DATABASE_URL` is supplied, and `just ci` does not run it +(`crates/database/tests/identity.rs:40` and `justfile:19-24`). Auth-service HTTP +tests mount only health routes with all applications set to `None` +(`apps/auth-service/src/lib.rs:199-234`). There are no handler-level OIDC, +federation, startup, mTLS/RPC, or browser-flow tests. The web package's `test` +script is a production build (`apps/auth-web/package.json:8-10`), not a test. + +The second review reran formatting, Clippy, the default Rust suite, SvelteKit +checking, the production web build, and inspected the PostgreSQL concurrency +suite. Those gates pass or are structurally present, but they cannot support the +claim that a real authentication flow or production topology was exercised. +`cargo deny check advisories` now fails on unmaintained `rustls-pemfile 2.2.0` +through Tonic (`RUSTSEC-2025-0134`), and `pnpm audit` still reports the already +documented low-severity `cookie` advisory (`GHSA-pxg6-pf52-xh8x`). The follow-up +claim that the advisory gate passed is no longer current. + +**Required action:** make the isolated PostgreSQL suite mandatory in CI and add +black-box HTTP, RPC, and browser tests that start the production composition. +Tie every release-control claim to an enforced test rather than a helper or +build-only check. + +### Additional P2 findings + +- `/oidc/logout` mutates session state on GET without origin or CSRF validation, + so a cross-site top-level navigation can force logout + (`apps/auth-service/src/oidc.rs:654-689`). Use POST with an exact origin and + CSRF control; keep GET non-mutating if a confirmation page is required. +- The mTLS listener requires a CA-issued certificate but token issuance never + binds the verified peer certificate identity to the assertion's service ID + (`apps/auth-service/src/main.rs:106-125` and + `apps/auth-service/src/service_rpc.rs:62-109`). Define a SAN/SPIFFE-style + identity contract and require it to match the assertion subject. +- Expired sessions, browser secrets, WebAuthn ceremonies, authorization codes, + refresh records, and federation transactions have no bounded cleanup owner. + Public start endpoints can grow several of these stores indefinitely. Define + retention periods and a bounded purge mechanism. +- Federation initial linking queries all historical verified-email owners rather + than the active ownership row (`apps/auth-service/src/federation.rs:497-530` + and `crates/database/src/repositories.rs:188-224`). A disabled historical + owner can make an otherwise unambiguous active-account login fail. +- Client bootstrap accepts raw URI/scope/audience strings and performs its + replace operation as multiple statements without requiring a transaction + (`crates/database/src/repositories.rs:265-295`). Validate the registration at + a typed administrative boundary and make replacement atomic. +- HTTP handlers have a ten-second timeout, but the Tonic listener and overall + graceful drain have no server deadline. Secret readiness wraps synchronous + file reads in an async timeout that cannot preempt them. Bound both listener + drains and use a genuinely deadline-aware secret-provider boundary. + +## First remediation follow-up (superseded) The decision and findings below describe the originally reviewed commits. They were accurate: the PRs had been presented as implementations even though most @@ -17,7 +230,8 @@ acceptance criteria were treated as file-shape requirements, tests exercised helpers rather than flows, and completion was reported without tracing a real request through HTTP, cryptography, persistence, and concurrency boundaries. -The release-blocking findings have been remediated as follows: +The first follow-up claimed the release-blocking findings had been remediated as +follows. The second review above found these claims incomplete: - The authority now exposes and wires WebAuthn, OIDC discovery/JWKS/code/token/ refresh/revoke/userinfo/logout, GitHub and Google login, account-security @@ -61,7 +275,7 @@ provider/browser and backup/restore drills before release. The in-process rate limiter is per replica; a shared disposable limiter requires a separately reviewed failure-mode design if aggregate limits are required. -## Decision +## Original review decision **Do not merge or deploy the stack as a completed authentication service.** From 114273c21bec87a03975ea4b6be0d4fe551a49d2 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 17:38:09 +0200 Subject: [PATCH 4/9] docs(auth): record second-review remediation --- docs/security/auth-stack-review-2026-07-14.md | 58 ++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/docs/security/auth-stack-review-2026-07-14.md b/docs/security/auth-stack-review-2026-07-14.md index c2983924b..2bbaa8bb8 100644 --- a/docs/security/auth-stack-review-2026-07-14.md +++ b/docs/security/auth-stack-review-2026-07-14.md @@ -11,7 +11,63 @@ through `auth/08-hardening-operations` at `47d9f4d`, as presented by this final audit PR. The second review was performed independently across architecture, security, and remediation-evidence validation. -## Second review verdict +## Second-review remediation follow-up + +The cumulative implementation was repaired again through +`auth/08-hardening-operations` at `3f46509`. Every second-review finding except +signing/service-key rotation has an implemented control and enforced evidence. +Key rotation is deliberately deferred at the owner's direction; the runbook now +states that overlap rotation is unsupported and that emergency replacement +causes global reauthentication. It no longer describes a nonexistent control. + +The corrected stack now provides the following evidence: + +- Active-account status is enforced while sessions are created and resolved. + Account disablement atomically revokes browser sessions and refresh families + with its audit/event records. Database races cover disable-versus-login and + concurrent last-factor removal. +- OIDC authorization uses a bounded, single-use server-side continuation. The + SvelteKit login, authorization, and security flows support passkeys, GitHub, + Google, authenticated passkey enrollment, social-identity display, + authorization cancellation, and POST/CSRF logout. SvelteKit now generates a + nonce-aware CSP instead of blocking its own production hydration scripts. +- Traefik terminates TLS for the one `auth.piquel.fr` origin. Checked-in static + and dynamic configuration separates page and protocol routes, discards + untrusted forwarding headers, and keeps health and private RPC listeners off + the edge. Auth-service accepts client IP forwarding only from configured + Docker CIDRs and uses bounded incremental limiter eviction. +- Refresh rotation re-evaluates current client grants and emits a sanitized + replay audit/signal. Passkey authentication locks and conditionally updates + the credential row. Federation uses active verified-email ownership. The SDK + verifies ID-token signature, algorithm, issuer, audience, time, and the + single-use nonce before exposing a verified identity. +- Private RPC binds the assertion subject and service token subject to the + exact `spiffe://piquel.fr/service/` URI SAN. Administrative + service provisioning is atomic, token issuance is audited, replay state is + authoritative, and the client retries only the idempotent `GetUser` call once + after an authentication failure. A live mTLS/Tonic/PostgreSQL test proves CA + enforcement, missing and mismatched identities, assertion replay rejection, + successful token injection, and method-permission denial. +- Expired state has a bounded cleanup owner; health traffic is isolated; + synchronous secret checks cannot create unbounded blocking work; HTTP and + RPC drains are deadline bounded. Tonic 0.14 removes the withdrawn + `rustls-pemfile` dependency. + +CI now provisions PostgreSQL 17 and runs the formerly optional concurrency +suite plus black-box HTTP and mTLS RPC suites. It runs real Vitest and Chromium +flows, formatting, Clippy, all Rust tests, high-severity package audit, and +`cargo deny`. It also boots the production Traefik configuration with separate +backends and proves protocol/page path ownership and forwarded-header +sanitization. Local verification repeated these gates, including the isolated +PostgreSQL tests and Traefik composition. + +With key rotation recorded as an explicit accepted first-version limitation, +the second review's remaining findings are remediated. Live GitHub/Google +credentials, production certificates/secrets, backup restoration, and provider +callback drills remain release-environment checks; the repository does not +claim that local tests can substitute for those deployments. + +## Second review verdict (superseded by the remediation follow-up) **Do not merge or deploy the stack as a completed authentication service.** From 7ad1d6c0e80c428b14a4b31d6d18bc279cb967fc Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 18:27:28 +0200 Subject: [PATCH 5/9] remove previous security review --- docs/security/auth-stack-review-2026-07-14.md | 522 ------------------ 1 file changed, 522 deletions(-) delete mode 100644 docs/security/auth-stack-review-2026-07-14.md diff --git a/docs/security/auth-stack-review-2026-07-14.md b/docs/security/auth-stack-review-2026-07-14.md deleted file mode 100644 index 2bbaa8bb8..000000000 --- a/docs/security/auth-stack-review-2026-07-14.md +++ /dev/null @@ -1,522 +0,0 @@ -# Authentication stack security review - -Date: 2026-07-14 - -Original scope: the complete authentication stack from `main` through the -then-current `auth/08-hardening-operations`, with emphasis on architecture, -trust boundaries, concurrency, and operational security. - -Second-review scope: the rebuilt cumulative stack from `main` at `e3fde34` -through `auth/08-hardening-operations` at `47d9f4d`, as presented by this final -audit PR. The second review was performed independently across architecture, -security, and remediation-evidence validation. - -## Second-review remediation follow-up - -The cumulative implementation was repaired again through -`auth/08-hardening-operations` at `3f46509`. Every second-review finding except -signing/service-key rotation has an implemented control and enforced evidence. -Key rotation is deliberately deferred at the owner's direction; the runbook now -states that overlap rotation is unsupported and that emergency replacement -causes global reauthentication. It no longer describes a nonexistent control. - -The corrected stack now provides the following evidence: - -- Active-account status is enforced while sessions are created and resolved. - Account disablement atomically revokes browser sessions and refresh families - with its audit/event records. Database races cover disable-versus-login and - concurrent last-factor removal. -- OIDC authorization uses a bounded, single-use server-side continuation. The - SvelteKit login, authorization, and security flows support passkeys, GitHub, - Google, authenticated passkey enrollment, social-identity display, - authorization cancellation, and POST/CSRF logout. SvelteKit now generates a - nonce-aware CSP instead of blocking its own production hydration scripts. -- Traefik terminates TLS for the one `auth.piquel.fr` origin. Checked-in static - and dynamic configuration separates page and protocol routes, discards - untrusted forwarding headers, and keeps health and private RPC listeners off - the edge. Auth-service accepts client IP forwarding only from configured - Docker CIDRs and uses bounded incremental limiter eviction. -- Refresh rotation re-evaluates current client grants and emits a sanitized - replay audit/signal. Passkey authentication locks and conditionally updates - the credential row. Federation uses active verified-email ownership. The SDK - verifies ID-token signature, algorithm, issuer, audience, time, and the - single-use nonce before exposing a verified identity. -- Private RPC binds the assertion subject and service token subject to the - exact `spiffe://piquel.fr/service/` URI SAN. Administrative - service provisioning is atomic, token issuance is audited, replay state is - authoritative, and the client retries only the idempotent `GetUser` call once - after an authentication failure. A live mTLS/Tonic/PostgreSQL test proves CA - enforcement, missing and mismatched identities, assertion replay rejection, - successful token injection, and method-permission denial. -- Expired state has a bounded cleanup owner; health traffic is isolated; - synchronous secret checks cannot create unbounded blocking work; HTTP and - RPC drains are deadline bounded. Tonic 0.14 removes the withdrawn - `rustls-pemfile` dependency. - -CI now provisions PostgreSQL 17 and runs the formerly optional concurrency -suite plus black-box HTTP and mTLS RPC suites. It runs real Vitest and Chromium -flows, formatting, Clippy, all Rust tests, high-severity package audit, and -`cargo deny`. It also boots the production Traefik configuration with separate -backends and proves protocol/page path ownership and forwarded-header -sanitization. Local verification repeated these gates, including the isolated -PostgreSQL tests and Traefik composition. - -With key rotation recorded as an explicit accepted first-version limitation, -the second review's remaining findings are remediated. Live GitHub/Google -credentials, production certificates/secrets, backup restoration, and provider -callback drills remain release-environment checks; the repository does not -claim that local tests can substitute for those deployments. - -## Second review verdict (superseded by the remediation follow-up) - -**Do not merge or deploy the stack as a completed authentication service.** - -The rebuild replaces the original scaffolding with substantial executable -code, but the prior remediation follow-up overstates completion. The second -review found three release blockers and several P1 trust, concurrency, and -operability gaps. In particular, account disablement is not an authentication -invariant, signing-key rotation is both unsupported and destructive to refresh -tokens, and there is still no deployable end-to-end browser/OIDC flow. - -The findings below are based on the rebuilt implementation and supersede the -claims in **First remediation follow-up (superseded)**. - -### P0 — Disabled accounts can authenticate with passkeys - -Passkey authentication consumes and verifies a ceremony, updates a credential, -and creates a new session without loading the user or requiring an active -account (`apps/auth-service/src/passkey.rs:316-363`). Browser-session resolution -joins only `browser_session_secrets` and `sessions`, so an existing session for -a subsequently disabled account remains accepted by account endpoints -(`crates/database/src/repositories.rs:768-773`). Private RPC likewise reports a -session active from revocation and expiry alone -(`apps/auth-service/src/service_rpc.rs:207-229`). Federation checks account -status before session creation in a separate transaction, leaving a disable -race (`apps/auth-service/src/federation.rs:475-495,582-617`). - -OIDC code and refresh queries do require an active user, so the same account has -different status semantics at different trust boundaries. Administrative -disablement therefore does not reliably disable authentication or central -session use. - -**Required action:** enforce active account status transactionally whenever a -session is resolved or created. Make account disablement revoke sessions and -refresh families and append its audit/event records in the same transaction. -Make RPC session status include account status and add disable-versus-login race -tests. - -### P0 — Signing-key rotation is unsupported and invalidates refresh tokens - -The authority loads exactly one ES256 private key and publishes exactly one JWK -(`apps/auth-service/src/oidc.rs:58-110`). It also passes the signing PEM bytes -into OIDC construction and derives the authorization-code/refresh-token digest -key from those bytes (`apps/auth-service/src/main.rs:25-56` and -`apps/auth-service/src/oidc.rs:223-235`). Replacing the signing key therefore -removes the old public key immediately and invalidates every outstanding -authorization code and refresh token, despite refresh tokens being issued for -up to 30 days. - -This makes the overlap procedure in -`docs/operations/auth-key-rotation.md:3-7` impossible to perform and turns a -routine signing-key rotation into a global session outage. - -**Required action:** use an independently managed, stable digest key for opaque -tokens. Implement an active-plus-retired signing key ring that can publish old -and new JWKs concurrently, then prove new issuance, overlap, removal after the -last token expiry, and refresh continuity in an authority integration test. - -### P0 — No complete browser/OIDC authorization flow is deployable - -An unauthenticated `/oauth/authorize` request is redirected back to the client -with `login_required`; there is no server-side authorization transaction, -login continuation, or authorization/consent UX -(`apps/auth-service/src/oidc.rs:284-369`). The independently deployed SvelteKit -application calls relative API paths, but has no proxy or server routes and no -documented edge-routing contract that composes page and API routes on -`auth.piquel.fr` (`apps/auth-web/src/lib/webauthn.ts:21-22` and -`apps/auth-web/svelte.config.js:1-3`). - -The account-security page's “Add a passkey” link opens the new-account -registration flow; the backend has no authenticated enrollment ceremony -(`apps/auth-web/src/routes/security/+page.svelte:8` and -`apps/auth-service/src/passkey.rs:137-247`). Social-identity listing, OIDC -authorization presentation/cancellation, and continuation after authentication -are also absent. - -**Required action:** define the production edge/BFF routing contract, persist a -bounded server-side authorization continuation, implement the authenticated -enrollment and authorization UX, and prove passkey, federation, SSO -continuation, cancellation, and logout with browser tests through that topology. - -### P1 — Public transport and rate limiting depend on an undefined proxy - -Production configuration validates an advertised HTTPS issuer, but the public -server binds a plaintext `TcpListener` with `axum::serve` -(`apps/auth-service/src/main.rs:88-105`). Secure deployment therefore requires -an external TLS terminator and private backend network, neither of which is an -enforced or documented invariant. The limiter keys on the TCP peer address -(`apps/auth-service/src/hardening.rs:51-74`), so a reverse proxy collapses all -users into one 30-per-minute login/WebAuthn bucket. Health endpoints share the -public bucket, and more than 10,000 recent source keys cause a full map scan -under a mutex on each request. - -**Required action:** terminate TLS in process or specify and enforce a trusted -proxy/private-listener topology. Define authenticated client-IP propagation, -separate health traffic, and use bounded incremental limiter eviction. - -### P1 — Refresh rotation ignores current client policy - -Refresh consumption checks that the client remains enabled, but does not -require `allow_refresh` or verify that the family's stored audience and scopes -remain allowed (`crates/database/src/repositories.rs:401-455`). Rotation then -reissues those stored grants unchanged (`apps/auth-service/src/oidc.rs:479-533`). -Removing a client scope/audience or disabling refresh therefore has no effect on -existing families. - -**Required action:** reapply current client policy inside the locked rotation -transaction, or explicitly model immutable grants and atomically revoke affected -families whenever client policy is reduced. Add policy-reduction tests. - -### P1 — Passkey state changes have revocation and last-factor races - -Authentication reads credential state and later updates it without a row lock -or optimistic state condition. The handler ignores the boolean result of the -conditional `revoked_at IS NULL` update, so a credential revoked between lookup -and update can still produce a session -(`apps/auth-service/src/passkey.rs:335-362` and -`crates/database/src/repositories.rs:665-677`). Concurrent authentications can -also overwrite newer authenticator state. - -The “keep at least one passkey” rule is a list-then-delete sequence over separate -pool operations (`apps/auth-service/src/passkey.rs:488-510`). Two concurrent -deletions can each observe two credentials and leave the account with none. - -**Required action:** lock or compare-and-swap credential state through -authentication completion, require a successful update before creating a -session, and enforce last-factor removal in one transaction with the relevant -credential set locked. - -### P1 — The SDK returns an unvalidated ID token - -The OIDC SDK creates and stores a nonce, but callback exchange validates only -state and sends the token request. The nonce is never consumed, and the returned -ID token is exposed after only response-shape checks -(`crates/auth-sdk/src/lib.rs:118-192,236-315`). There is no ID-token verifier in -the SDK that checks signature, issuer, client audience, time claims, and nonce. - -**Required action:** validate the ID token against the trusted issuer/JWKS and -the single-use callback nonce before returning an authenticated result. Keep raw -token access separate from a verified identity type and add negative nonce, -audience, issuer, algorithm, and signature tests. - -### P1 — Required replay evidence and RPC hardening are absent - -Refresh replay revokes the family but writes no security-audit record and emits -no replay-specific bounded signal (`apps/auth-service/src/oidc.rs:487-495`). -This contradicts `docs/operations/auth-incidents.md:3-4` and the Plan 08 release -gate. Public HTTP limits do not cover Tonic; private RPC has no server-enforced -request deadline or concurrency bound and no mTLS/authentication/permission -integration test (`apps/auth-service/src/main.rs:107-125`). - -**Required action:** co-commit a sanitized replay audit record with family -revocation, emit a bounded replay metric, and test both. Add RPC deadlines, -concurrency limits, certificate/service-identity binding policy, and black-box -mTLS and permission tests. - -### P1 — Passing gates do not verify the implemented system - -The default Rust suite passes but the sole PostgreSQL integration test is -ignored unless `TEST_DATABASE_URL` is supplied, and `just ci` does not run it -(`crates/database/tests/identity.rs:40` and `justfile:19-24`). Auth-service HTTP -tests mount only health routes with all applications set to `None` -(`apps/auth-service/src/lib.rs:199-234`). There are no handler-level OIDC, -federation, startup, mTLS/RPC, or browser-flow tests. The web package's `test` -script is a production build (`apps/auth-web/package.json:8-10`), not a test. - -The second review reran formatting, Clippy, the default Rust suite, SvelteKit -checking, the production web build, and inspected the PostgreSQL concurrency -suite. Those gates pass or are structurally present, but they cannot support the -claim that a real authentication flow or production topology was exercised. -`cargo deny check advisories` now fails on unmaintained `rustls-pemfile 2.2.0` -through Tonic (`RUSTSEC-2025-0134`), and `pnpm audit` still reports the already -documented low-severity `cookie` advisory (`GHSA-pxg6-pf52-xh8x`). The follow-up -claim that the advisory gate passed is no longer current. - -**Required action:** make the isolated PostgreSQL suite mandatory in CI and add -black-box HTTP, RPC, and browser tests that start the production composition. -Tie every release-control claim to an enforced test rather than a helper or -build-only check. - -### Additional P2 findings - -- `/oidc/logout` mutates session state on GET without origin or CSRF validation, - so a cross-site top-level navigation can force logout - (`apps/auth-service/src/oidc.rs:654-689`). Use POST with an exact origin and - CSRF control; keep GET non-mutating if a confirmation page is required. -- The mTLS listener requires a CA-issued certificate but token issuance never - binds the verified peer certificate identity to the assertion's service ID - (`apps/auth-service/src/main.rs:106-125` and - `apps/auth-service/src/service_rpc.rs:62-109`). Define a SAN/SPIFFE-style - identity contract and require it to match the assertion subject. -- Expired sessions, browser secrets, WebAuthn ceremonies, authorization codes, - refresh records, and federation transactions have no bounded cleanup owner. - Public start endpoints can grow several of these stores indefinitely. Define - retention periods and a bounded purge mechanism. -- Federation initial linking queries all historical verified-email owners rather - than the active ownership row (`apps/auth-service/src/federation.rs:497-530` - and `crates/database/src/repositories.rs:188-224`). A disabled historical - owner can make an otherwise unambiguous active-account login fail. -- Client bootstrap accepts raw URI/scope/audience strings and performs its - replace operation as multiple statements without requiring a transaction - (`crates/database/src/repositories.rs:265-295`). Validate the registration at - a typed administrative boundary and make replacement atomic. -- HTTP handlers have a ten-second timeout, but the Tonic listener and overall - graceful drain have no server deadline. Secret readiness wraps synchronous - file reads in an async timeout that cannot preempt them. Bound both listener - drains and use a genuinely deadline-aware secret-provider boundary. - -## First remediation follow-up (superseded) - -The decision and findings below describe the originally reviewed commits. They -were accurate: the PRs had been presented as implementations even though most -contained only schemas, policy-shaped helpers, and UI/protocol scaffolding. The -stack was subsequently rebuilt on the same ordered branches and re-reviewed on -2026-07-14. The cause was an implementation/review failure, not a regression: -acceptance criteria were treated as file-shape requirements, tests exercised -helpers rather than flows, and completion was reported without tracing a real -request through HTTP, cryptography, persistence, and concurrency boundaries. - -The first follow-up claimed the release-blocking findings had been remediated as -follows. The second review above found these claims incomplete: - -- The authority now exposes and wires WebAuthn, OIDC discovery/JWKS/code/token/ - refresh/revoke/userinfo/logout, GitHub and Google login, account-security - operations, and a separate mTLS Tonic listener. -- Repositories now borrow a real pool or transaction executor. Conditional - `UPDATE ... RETURNING` consumption is used for ceremonies and codes; refresh - rotation locks records and revokes a family on replay. -- Static OIDC clients own exact redirect/post-logout URIs, scopes, audiences, - enabled state, refresh permission, and authentication method. Access and ID - tokens are ES256 and cryptographically separated by `typ` and audience. -- The SDK now validates a single Bearer value, fixed `at+jwt`/ES256/`kid`, a - trusted cached JWKS key, signature, exact issuer/audience, time claims, and - typed UUIDv7 claims. `AuthenticatedUser` is opaque outside the validator. -- Active verified-email ownership is represented by a unique lockable row and - is synchronized on account status changes. Federation uses verified provider - email only for the initial link and stores issuer/subject as the durable key. -- WebAuthn uses `webauthn-rs` with parsed exact origins and server-side, - single-use state. The three attacker-controlled origin examples in this - report are regression tests. -- Production public/database transport fails closed unless HTTPS and verified - PostgreSQL TLS are configured. Secret locators are allowlisted and redacted; - readiness resolves the signing, provider, and RPC TLS dependencies. -- Migration credentials are environment-only. Refresh/cookie secrets have - exact bounds, public bodies and handler time are bounded, sensitive endpoint - classes are rate limited, and SIGINT/SIGTERM coordinate graceful public and - private listener shutdown. - -Verification after remediation includes the full Rust format/test/clippy gates, -SvelteKit type checking and an adapter-node production build, real ES256 and -software-WebAuthn interoperability tests, JWKS failure/rotation tests, and an -empty PostgreSQL 17 database test using separate concurrent connections. The -database test proves rollback, verified-email claim/reactivation exclusion, -exactly-one WebAuthn/federation transaction consumption, duplicate credential -and provider-subject rejection, optimistic profile conflict, idempotent session -revocation, event ordering, and refresh one-winner/replay-family revocation. - -Remaining deployment work is environmental rather than a claim of an -implemented control: production must provision reviewed OIDC/service clients, -ES256 and mTLS key material, GitHub/Google applications, and exercise live -provider/browser and backup/restore drills before release. The in-process rate -limiter is per replica; a shared disposable limiter requires a separately -reviewed failure-mode design if aggregate limits are required. - -## Original review decision - -**Do not merge or deploy the stack as a completed authentication service.** - -The stack establishes useful types, schemas, and policy helpers, but it remains -foundation scaffolding. The executable serves only health endpoints, the -repository handles cannot execute persistence operations, the downstream SDK -does not validate tokens, and the private RPC surface is not implemented. The -current tests do not exercise a real authentication flow or PostgreSQL -invariant. - -## Release-blocking findings - -### P0 — The authentication authority is a health-only shell - -`apps/auth-service/src/lib.rs:9-24` suppresses dead-code warnings for every -policy module and `apps/auth-service/src/lib.rs:75-84` registers only liveness -and readiness. `apps/auth-service/src/main.rs:11-20` binds only the public -listener. There are no discovery, JWKS, authorization, token, revocation, -passkey, federation, session, logout, or account-management endpoints, and the -configured private listener is never bound. - -The frontend nevertheless links to login flows that return 404, while the -protobuf contract has no generated server/client, TLS listener, service-token -verification, or method authorization. - -**Required action:** relabel the stack as scaffolding or implement each planned -HTTP/RPC flow with its cryptographic and persistence dependencies. Require an -end-to-end test for every advertised flow before describing the service or -runbooks as operational. - -### P0 — Persistence and transactional invariants are not implemented - -Every type in `crates/database/src/repositories.rs:3-23` is an empty -`PhantomData` handle with no operations or executor. `Database` and -`DatabaseTransaction` create those handles without lending the pool or SQLx -transaction (`crates/database/src/connection.rs:84-113` and -`crates/database/src/transaction.rs:12-40`). - -Account creation, session revocation, event/audit co-commit, WebAuthn ceremony -consumption, authorization-code exchange, refresh rotation/replay response, and -federated linking therefore cannot be performed, let alone atomically. The -ceremony helper only inspects a copied `consumed` flag -(`apps/auth-service/src/passkey.rs:21-32`), so two replicas would both accept the -same unclaimed record if it were wired directly. - -**Required action:** make repository handles borrow a private pool/transaction -executor and implement typed persistence operations. Consume one-time records -with conditional `UPDATE ... RETURNING` statements and keep their security side -effects in deliberate transactions. Prove rollback and exactly-one-winner -behavior with multi-connection PostgreSQL tests. - -### P0 — The downstream SDK performs no JWT validation - -`AuthMiddleware` ends after configuration getters and bearer-string parsing at -`crates/auth-middleware/src/lib.rs:33-95`. It never validates `typ`, `alg`, -`kid`, signature, issuer, audience, `exp`, `nbf`, or `iat`, and it implements no -JWKS retrieval/cache/rotation behavior. Its advertised verified principal also -has publicly constructible fields (`crates/auth-middleware/src/lib.rs:7-14`) and -is re-exported to consumers. - -This makes the intended local-validation boundary unavailable and makes it easy -for a consumer to treat an unchecked, caller-constructed value as an -authenticated identity. - -**Required action:** implement a fixed-algorithm, fail-closed verifier with -bounded JWKS caching and exact claim validation. Make the principal opaque and -constructible only after successful verification; expose read-only accessors -and framework adapters that preserve authentication-versus-authorization error -semantics. - -### P1 — Active verified-email uniqueness is raceable and bypassable - -The trigger in -`crates/database/migrations/0002_identity_sessions.sql:24-41` claims to lock -matching rows but performs only an `EXISTS` query. Concurrent transactions can -both observe no committed owner and insert the same verified email for two -active accounts. Locking existing rows alone would still not serialize the -initial no-row case. - -The trigger also runs only for changes to `user_emails`. Two disabled accounts -may hold the same verified address and both may later transition to `active` -without rechecking the invariant. This makes verified-email federation linking -ambiguous and risks binding authentication to the wrong account. - -**Required action:** represent active email ownership with a transactionally -maintained row uniquely keyed by normalized email, or serialize claims and -reactivations with a per-email lock and checks covering both tables. Add -concurrent insert and disabled-to-active tests using separate connections. - -### P1 — WebAuthn RP validation accepts attacker origins - -`apps/auth-service/src/passkey.rs:45-54` accepts any string starting with -`https://` that contains the RP ID. For RP ID `example.com`, origins such as -`https://example.com.evil`, `https://evil.test/example.com`, and -`https://example.com@evil.test` pass. - -**Required action:** parse origins as URLs; reject userinfo, paths, query, -fragment, and non-HTTPS schemes; compare against an exact normalized origin -allowlist; and validate the RP ID against the hostname using DNS-label -boundaries and the WebAuthn rules. Add the examples above as negative tests. - -### P1 — OIDC client authorization policy has no authoritative model - -`crates/database/migrations/0004_oidc_tokens.sql:1-6` records only a client ID, -enabled state, and redirect URIs. It has no registered audiences, scopes, grant -types, client-authentication methods, or post-logout URIs. Authorization codes -store arbitrary scopes and audience, do not record the PKCE method, and do not -relationally bind their redirect to the client's registration. The -`exact_audience` helper accepts a slice from an unspecified caller -(`apps/auth-service/src/oidc.rs:61-69`). - -**Required action:** model static client authorization explicitly and load it -through typed repository operations. Derive allowed audience/scope solely from -that registration, persist `S256`, and atomically bind/consume codes and refresh -families. Test cross-client audience, scope, redirect, and replay failures. - -### P1 — Readiness does not test signing-key usability - -`SecretReference::parse` accepts any non-whitespace string and -`SecretReference::is_configured()` always returns true -(`crates/configuration/src/lib.rs:57-69`). `main` reduces the key dependency to -that boolean, and readiness combines it only with a database query -(`apps/auth-service/src/main.rs:15-18`, `apps/auth-service/src/lib.rs:86-96`). - -A missing, revoked, unauthorized, or unreachable key therefore reports ready -and continues receiving token traffic. - -**Required action:** resolve an allowlisted key-provider reference at startup, -validate an active asymmetric key and stable `kid`, and probe bounded provider -usability/rotation metadata from readiness without exposing key material. - -### P1 — The documented migration command leaks database credentials - -`justfile:23-24`, `crates/database/README.md:7`, and -`docs/operations/auth-release.md:3-5` pass `$DATABASE_URL` as a positional -argument to `just`. Credentials embedded in the URL can appear in process -listings, shell history, and command telemetry. - -**Required action:** make `just migrate` inherit `DATABASE_URL` from its -environment or accept a secret-provider reference; never put the URL in argv. - -## Additional security and operational findings - -- **P2 — insecure production transport is accepted.** - `crates/configuration/src/lib.rs:30-40` accepts HTTP for arbitrary public - hosts, and `crates/database/src/connection.rs:24-42` does not enforce verified - PostgreSQL TLS. Default to HTTPS and verified database TLS; allow loopback - exceptions only behind explicit development configuration. - -- **P2 — shutdown does not meet the runbook.** - `apps/auth-service/src/main.rs:19-26` listens only for Ctrl-C/SIGINT and puts no - deadline on draining. Handle SIGTERM, stop readiness/intake first, and bound - shutdown so orchestrator termination cannot drop transactions or hang. - -- **P2 — health and hardening signals are absent.** - The readiness database query has no explicit query deadline, failures are - silently collapsed to 503, and telemetry provides formatting but no bounded - auth/replay/rate-limit/key/RPC metrics. No endpoint rate limits or shared - replay controls exist. - -- **P3 — refresh parsing permits unbounded allocation.** - `apps/auth-service/src/oidc.rs:37-54` base64-decodes an arbitrary-size secret - before imposing only a minimum length. Require an exact encoded/decoded size - before allocation and enforce request-body limits. - -- **P3 — one low-severity JavaScript advisory is present.** - `pnpm audit` reports `GHSA-pxg6-pf52-xh8x` for transitive `cookie@0.6.0` via - SvelteKit. The current shell does not set application cookies, but the - dependency should be upgraded/overridden before cookie-backed auth is added. - -## Verification performed - -- `cargo fmt --check`: passed. -- `cargo clippy --workspace --all-targets --all-features -- -D warnings`: - passed. -- `cargo test --workspace`: passed; only 12 small unit tests ran, with no - database, HTTP, browser, cryptographic, multi-replica, or RPC integration - coverage. -- `pnpm install --frozen-lockfile`: passed. -- `pnpm -r check`: passed. -- `pnpm -r build`: passed; adapter-auto could not identify a production target. -- `cargo deny check advisories`: passed. -- `pnpm audit`: one low-severity advisory, described above. - -The exact redirect matcher, PKCE S256 computation, keyed refresh-token digest, -canonical UUID/text parsing, secret debug redaction, SQLx dependency boundary, -dependency-free liveness endpoint, and auth-web baseline CSP/referrer/cache -headers were also reviewed and did not produce additional findings. From 91e313acbe3975f8dfd25bd9b99feeca26c9cf4b Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 18:39:49 +0200 Subject: [PATCH 6/9] docs(auth): record final architecture and security review --- docs/security/auth-stack-review-2026-07-14.md | 324 ++++++++++++++++++ 1 file changed, 324 insertions(+) create mode 100644 docs/security/auth-stack-review-2026-07-14.md diff --git a/docs/security/auth-stack-review-2026-07-14.md b/docs/security/auth-stack-review-2026-07-14.md new file mode 100644 index 000000000..bda858f61 --- /dev/null +++ b/docs/security/auth-stack-review-2026-07-14.md @@ -0,0 +1,324 @@ +# Authentication stack architecture and security review + +Date: 2026-07-14 + +Review target: the cumulative implementation from `origin/main` at `e3fde34` +through `origin/auth/08-hardening-operations` at `365d160`. + +## Decision + +**Changes requested. Do not deploy this stack as the completed authentication +service yet.** + +The implementation has several sound foundations: exact OIDC redirect matching, +mandatory S256 PKCE, keyed opaque-token digests, transactional refresh replay +handling, server-side single-use WebAuthn state, exact JWT type/issuer/audience +checks at resource boundaries, account-status checks, mTLS plus SPIFFE-style RPC +identity binding, and bounded public request bodies and deadlines. + +Those controls do not offset the release blockers below. The most important are +a bypass in the production database TLS guard, durable account takeover through +email-only federation linking, a nonexistent signing-key rotation boundary, an +over-broad proxy trust boundary, a broken passkey-enrollment schema, and missing +production observability/deployment evidence. + +## Release blockers + +### High — PostgreSQL TLS validation can be downgraded + +`DatabaseConfig::validate` accepts a production URL when *any* query pair equals +`sslmode=verify-full` (`crates/database/src/connection.rs:60-83`), then stores and +later gives the unchanged string to SQLx (`crates/database/src/connection.rs:95-100`). +SQLx 0.8.6 processes connection query pairs sequentially, accepts both +`sslmode` and `ssl-mode`, and lets the last value win. + +Consequently, a URL such as +`postgres://db/app?sslmode=verify-full&sslmode=disable` passes this repository's +production guard while SQLx connects with TLS disabled. SQLx also accepts +query-level `host`/`hostaddr` overrides, so a development URL whose authority is +loopback can be redirected to a remote database. + +**Required action:** parse once into `PgConnectOptions`, reject duplicate/alias +security parameters and host overrides, validate the effective host and +`PgSslMode::VerifyFull`, and connect with those already-validated options. Add +regression tests for both parameter orders and host overrides. + +### High — email-only federation linking permits durable account takeover + +For a previously unseen provider subject, federation looks up an existing +active account solely by the provider-asserted verified email and inserts the +new external identity on that account (`apps/auth-service/src/federation.rs:536-605`). +The callback immediately creates a full browser session +(`apps/auth-service/src/federation.rs:247-272`). + +Verified email ownership is not immutable. If an address on an active Piquel +account is later reassigned—for example, a former employee's corporate address +is issued to a new employee—the new owner can authenticate through GitHub or +Google with a different provider subject and become linked to the former +owner's Piquel account. A fresh federation session is sufficient for passkey +management (`apps/auth-service/src/passkey.rs:386-478`), so the new owner can +add a credential and then remove the victim's credentials while retaining one +factor (`apps/auth-service/src/passkey.rs:535-564`). + +The design documents email auto-linking as an accepted first-version policy, +but the implementation makes the reassignment case a persistent full takeover, +not merely a profile-linking ambiguity. + +**Required action:** do not attach a new issuer/subject to an existing account +based only on email. Require a fresh session authenticated with an existing +factor, or route collisions through explicit recovery/administrative review. +Notify the existing account through an independent channel. + +### High — key rotation is not an implemented security boundary + +Production loads one exportable PKCS#8 key, uses it as the only JWT signing key, +publishes only its JWK, and also passes the same PEM bytes into OIDC as the root +for authorization-request, code, and refresh-token digests +(`apps/auth-service/src/main.rs:25-58`, `apps/auth-service/src/oidc.rs:88-111`, +`apps/auth-service/src/oidc.rs:224-238`). + +Replacing a compromised signing key therefore removes verification for +existing JWTs and invalidates every outstanding opaque credential. The runbook +acknowledges that routine overlap is unsupported and emergency replacement +requires global reauthentication (`docs/operations/auth-key-rotation.md:1-19`). +That is honest documentation, but it does not satisfy the hardening plan's key +lifecycle release gate. + +`SecretReference` also accepts `kms://` values while `resolve` deterministically +rejects them (`crates/configuration/src/lib.rs:81-125`), so the advertised +provider boundary cannot use a non-exportable production signing key. + +**Required action:** separate a stable opaque-token digest key from signing, +implement an active-plus-retired signing key ring and JWKS overlap, and define a +real signing-provider interface for KMS-backed signing. Prove routine rotation, +emergency retirement, refresh continuity, and downstream key-removal timing. + +### High — the trusted proxy identity is an entire shared network + +The release guide attaches Traefik, auth-service, and auth-web to the same edge +network and configures `AUTH_TRUSTED_PROXY_CIDRS` with that network CIDR +(`docs/operations/auth-release.md:9-18`). The application accepts the first +`X-Forwarded-For` value from any peer in that CIDR +(`apps/auth-service/src/hardening.rs:148-165`). + +A compromised sibling container, or any accidentally attached workload, can +connect directly to auth-service, choose arbitrary client IPs, and evade the +per-IP controls without passing through Traefik. The unit test proves only that +one CIDR is accepted and another is rejected; it does not prove that the peer is +Traefik (`apps/auth-service/src/hardening.rs:211-230`). + +**Required action:** use separate Traefik-to-web and +Traefik-to-auth-service networks with no sibling route, or authenticate the +proxy hop and identify Traefik specifically. Add a negative integration test +for direct requests from auth-web/the sibling network. + +### High — authenticated backup-passkey enrollment cannot work + +`/account/passkeys/enroll/start` inserts a ceremony with kind `enrollment`, and +the finish handler consumes the same kind +(`apps/auth-service/src/passkey.rs:412-424`, +`apps/auth-service/src/passkey.rs:443-446`). The database constraint allows only +`registration` and `authentication` +(`crates/database/migrations/0003_passkey_credentials.sql:19-29`). Every start +request therefore fails before the authenticator is invoked. + +The browser test masks this by stubbing the enrollment endpoint +(`apps/auth-web/tests/auth-flow.spec.ts:111-134`); no real Postgres-backed HTTP +test exercises passkey enrollment. + +**Required action:** add an immutable migration that represents enrollment +consistently, preferably with a typed ceremony kind, and add a real +start/finish enrollment flow through HTTP and PostgreSQL. + +### High — production TLS and security telemetry are not release-verifiable + +The Traefik routers enable `tls: {}`, but the checked-in static/dynamic config +contains no certificate resolver or certificate store +(`infra/traefik/auth-dynamic.yml:14,21`, +`infra/traefik/auth-static.yml:24-33`). The topology test always uses +`curl --insecure` and replaces both applications with `traefik/whoami` +(`.github/workflows/ci.yml:58-93`). It cannot detect a missing, expired, or +wrong-host certificate and does not compose the software being released. + +The hardening plan also requires bounded signals for authentication, replay, +signing, database, RPC, provider, and rate-limit outcomes. Telemetry currently +formats stderr logs only (`crates/telemetry/src/lib.rs:26-35`), and Traefik has +no access log, metrics, or tracing configuration. Most authentication outcomes +are absent, and the cleanup documentation asks operators to alert on failures +without exposing a signal that can drive such an alert +(`docs/security/auth-data-retention.md:25-27`). + +**Required action:** provision an explicit certificate source, test the HTTPS +edge with a trusted test CA and hostname verification, compose the real +auth-service/auth-web/PostgreSQL stack, and run Playwright/protocol checks +through that edge. Add bounded metrics/traces and alert simulations for the +outcomes named in Plan 08 before calling the service operable. + +## Additional security and architecture findings + +### Medium — issued claims bypass scope policy + +The authorization endpoint enforces each requested scope against the client's +allowlist (`apps/auth-service/src/oidc.rs:318-327`), but token issuance always +puts `preferred_username`, `name`, and `profile_version` in access and ID tokens +regardless of whether `profile` was granted +(`apps/auth-service/src/oidc.rs:733-757`). The advertised `email` scope never +produces an email claim, including from UserInfo. + +**Required action:** construct claim sets from granted scopes, add negative +tests proving omitted scopes omit their claims, and either implement verified +email claims or stop advertising `email`. + +### Medium — revocation races protected browser mutations + +Passkey enrollment, rename, removal, and authorization approval resolve the +browser session before opening the mutation transaction +(`apps/auth-service/src/passkey.rs:440-478`, +`apps/auth-service/src/passkey.rs:523-563`, +`apps/auth-service/src/oidc.rs:409-471`). They do not lock and re-check that +session in the transaction that performs the protected write. + +Logout or administrative revocation can therefore commit after the handler's +initial lookup while the passkey mutation or authorization-code issuance still +succeeds. This is material when revocation races completion of a previously +started enrollment from a stolen browser session. + +**Required action:** revalidate and lock the active session, user state, and +fresh-authentication requirement inside the protected transaction. Serialize +revocation on the same session row and add race tests. + +### Medium — abuse limits are neither replica-safe nor capacity-safe + +The public limiter is in process memory (`apps/auth-service/src/hardening.rs:23-50`). +N replicas permit N times the configured rate and restart/autoscaling resets +all windows. After 10,000 distinct `(IP, endpoint-class)` keys, every unseen +legitimate client receives 503 (`apps/auth-service/src/hardening.rs:85-93`). +Rotating IPv6 addresses or a botnet can reach that global new-client denial +state within one window. + +Private service-token issuance is outside this limiter. A CA-trusted but +compromised/looping service can multiply the per-connection concurrency limit +with new connections, cause database work for assertions, and append a durable +audit row for every rejected assertion (`apps/auth-service/src/main.rs:125-136`, +`apps/auth-service/src/service_rpc.rs:195-213`). + +**Required action:** place the authoritative aggregate limit at ingress or in +explicitly disposable shared coordination, retain a local circuit breaker, use +bounded eviction rather than global 503 for unseen clients, aggregate IPv6 +prefixes, and add global/per-service RPC concurrency and rate limits. + +### Medium — outstanding OIDC state survives policy removal + +Authorization-request and code consumption check that the client is enabled, +but do not revalidate the stored redirect URI, scopes, or audience against the +current client registration (`crates/database/src/repositories.rs:362-384`). +After an operator removes a compromised redirect or grant, an already-created +request can still approve and exchange the old policy snapshot until it +expires. Disabling the entire client is the only immediate stop. + +**Required action:** re-read and enforce current redirect/scope/audience policy +at approval and code exchange, or atomically revoke affected outstanding state +when policy changes. Add policy-reduction tests. + +### Medium — service assertion cleanup is unbounded on the issuance path + +Every accepted assertion first deletes *all* expired replay rows +(`crates/database/src/repositories.rs:739-758`). The bounded maintenance job +does not own this table (`crates/database/src/connection.rs:130-156`). A large +expired set turns token issuance into an unbounded delete/lock operation and can +exhaust the small shared database pool. + +**Required action:** make assertion recording a single insert and move indexed, +limited cleanup into the maintenance owner using bounded batches. + +### Medium — `prompt=none` and `max_age` do not implement their contract + +A negative `max_age` is stored and routed through login even though no session +can ever satisfy it (`apps/auth-service/src/oidc.rs:331-376`, +`apps/auth-service/src/oidc.rs:489-505`). With an active session, +`prompt=none` still redirects to the authorization UI, contrary to its +no-interaction meaning. + +**Required action:** reject negative/out-of-range values immediately and make +`prompt=none` either complete without UI under an explicit prior-consent policy +or return the appropriate OAuth error. + +### Medium — policy ownership is mostly nominal + +The account, session, audit, and event modules define validators and +transactional helpers, but the deployed handlers bypass them. Initial passkey +and federation flows insert users/sessions/audits/events directly; the policy +modules are kept behind `allow(dead_code)` in `apps/auth-service/src/lib.rs`. +That duplication already creates inconsistent audit coverage: account creation +through passkeys or federation does not use `account::create`, passkey rename is +not audited, and OIDC authorization/revocation/logout mutations do not produce +the security history implied by the architecture. + +**Required action:** make one application-service boundary own each account, +session, credential, and audit transition. Remove dead policy facades or route +all handlers through them, and test the expected audit/event record with every +security-sensitive mutation. + +### Low — backslash-relative return targets are open redirects + +Both return-target validators reject `//evil.example` but accept +`/\evil.example/path` (`apps/auth-service/src/federation.rs:275-284`, +`apps/auth-web/src/lib/navigation.ts:1-3`). WHATWG URL resolution treats the +backslash as a slash for an HTTPS URL, so the callback/navigation resolves to +`https://evil.example/path` (`apps/auth-service/src/federation.rs:257-261`). + +This does not leak the host-only session cookie, but it lets a crafted real +login terminate at an attacker-controlled phishing origin. + +**Required action:** resolve first against the configured base and require the +resulting origin to be exactly the auth origin. Reject backslashes and encoded +separator ambiguity, and add server and browser regression tests. + +### Low — a transient provider failure burns the login transaction + +Federation marks the state consumed before token exchange, provider API/JWKS +requests, identity linking, and session creation +(`apps/auth-service/src/federation.rs:237-256`, +`crates/database/src/repositories.rs:625-642`). A transient provider or database +failure makes the browser callback permanently unretryable. + +**Required action:** use claim/finalize state with bounded retry semantics, or +retain a short-lived claimed state and finalize it only after provider +verification and local commit. Do not hold a database transaction across the +provider network call. + +## Verification and review coverage + +Three independent passes covered architecture/concurrency, adversarial +authentication security, and web/edge/operations. The review traced public +inputs and authorization decisions across WebAuthn, OIDC, refresh rotation, +federation, JWT SDK/middleware, private mTLS RPC, PostgreSQL repositories, +SvelteKit, Traefik, configuration, CI, and runbooks. + +Locally executed checks: + +- `cargo fmt --all --check` +- `cargo clippy --workspace --all-targets --all-features -- -D warnings` +- `cargo test --workspace` +- `pnpm check:web` +- `pnpm test:web` +- `pnpm test:browser` +- `cargo deny check advisories` +- `pnpm audit --audit-level=high` + +Formatting, Clippy, workspace unit tests, Svelte checks, Vitest, and Chromium +flows pass. The dependency gates pass at their configured thresholds; +`pnpm audit` reports one low-severity advisory. The ignored PostgreSQL/HTTP/RPC +suites are enabled in GitHub CI and the current PR check is green, but the gaps +above show that those suites do not exercise backup-passkey enrollment, the +effective SQLx connection options, real services behind the HTTPS edge, key +rotation, distributed rate limiting, or operational alerting. + +## Merge criteria + +At minimum, resolve the six release blockers, add regression coverage for the +database TLS parser and passkey enrollment, remove email-only account linking, +and demonstrate signing-key overlap plus the real composed HTTPS deployment. +The medium findings should be fixed or explicitly accepted with owner, threat +model, compensating controls, and a tracked expiry; documentation alone is not +a compensating security control. From b79449cc94d3616a086fc3e4959dd57b8fedb377 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 19:15:52 +0200 Subject: [PATCH 7/9] fix(auth): harden database TLS and passkey enrollment --- apps/auth-service/src/lib.rs | 4 +- apps/auth-service/tests/http_flow.rs | 2 +- apps/auth-service/tests/rpc_flow.rs | 2 +- .../0007_passkey_enrollment_ceremony.sql | 6 ++ crates/database/src/bin/migrate.rs | 3 +- crates/database/src/connection.rs | 93 ++++++++++++++----- crates/database/tests/identity.rs | 22 ++++- 7 files changed, 104 insertions(+), 28 deletions(-) create mode 100644 crates/database/migrations/0007_passkey_enrollment_ceremony.sql diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index f863fd78b..2511de00a 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -81,9 +81,9 @@ impl AuthConfig { PublicUrl::parse(&required("AUTH_PUBLIC_BASE_URL")?)? }; let database = if development { - DatabaseConfig::new_development(database_url, 10, Duration::from_secs(5)) + DatabaseConfig::new_development(&database_url, 10, Duration::from_secs(5)) } else { - DatabaseConfig::new(database_url, 10, Duration::from_secs(5)) + DatabaseConfig::new(&database_url, 10, Duration::from_secs(5)) } .map_err(|_| ConfigurationError::Invalid { name: "AUTH_DATABASE_URL", diff --git a/apps/auth-service/tests/http_flow.rs b/apps/auth-service/tests/http_flow.rs index c71771de1..f083986c6 100644 --- a/apps/auth-service/tests/http_flow.rs +++ b/apps/auth-service/tests/http_flow.rs @@ -20,7 +20,7 @@ async fn database() -> Database { let url = env::var("TEST_DATABASE_URL") .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); Database::connect( - DatabaseConfig::new_development(url, 5, Duration::from_secs(5)) + DatabaseConfig::new_development(&url, 5, Duration::from_secs(5)) .expect("test database configuration"), ) .await diff --git a/apps/auth-service/tests/rpc_flow.rs b/apps/auth-service/tests/rpc_flow.rs index 0fd419587..356f854de 100644 --- a/apps/auth-service/tests/rpc_flow.rs +++ b/apps/auth-service/tests/rpc_flow.rs @@ -33,7 +33,7 @@ async fn database() -> Database { let url = env::var("TEST_DATABASE_URL") .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); Database::connect( - DatabaseConfig::new_development(url, 8, Duration::from_secs(5)) + DatabaseConfig::new_development(&url, 8, Duration::from_secs(5)) .expect("test database configuration"), ) .await diff --git a/crates/database/migrations/0007_passkey_enrollment_ceremony.sql b/crates/database/migrations/0007_passkey_enrollment_ceremony.sql new file mode 100644 index 000000000..40bdfa12d --- /dev/null +++ b/crates/database/migrations/0007_passkey_enrollment_ceremony.sql @@ -0,0 +1,6 @@ +ALTER TABLE webauthn_ceremonies + DROP CONSTRAINT webauthn_ceremonies_ceremony_kind_check; + +ALTER TABLE webauthn_ceremonies + ADD CONSTRAINT webauthn_ceremonies_ceremony_kind_check + CHECK (ceremony_kind IN ('registration', 'authentication', 'enrollment')); diff --git a/crates/database/src/bin/migrate.rs b/crates/database/src/bin/migrate.rs index b29209f99..851ba6b63 100644 --- a/crates/database/src/bin/migrate.rs +++ b/crates/database/src/bin/migrate.rs @@ -6,7 +6,8 @@ use std::{env, time::Duration}; #[tokio::main] async fn main() -> anyhow::Result<()> { let url = env::var("DATABASE_URL")?; - let database = Database::connect(DatabaseConfig::new(url, 1, Duration::from_secs(10))?).await?; + let database = + Database::connect(DatabaseConfig::new(&url, 1, Duration::from_secs(10))?).await?; database.run_migrations().await?; Ok(()) } diff --git a/crates/database/src/connection.rs b/crates/database/src/connection.rs index 2ea9bd4c8..ceffd6049 100644 --- a/crates/database/src/connection.rs +++ b/crates/database/src/connection.rs @@ -1,14 +1,17 @@ use crate::{ DatabaseConnectionError, DatabaseError, repositories::*, transaction::DatabaseTransaction, }; -use sqlx::{PgPool, postgres::PgPoolOptions}; -use std::{net::IpAddr, time::Duration}; +use sqlx::{ + PgPool, + postgres::{PgConnectOptions, PgPoolOptions, PgSslMode}, +}; +use std::{net::IpAddr, str::FromStr, time::Duration}; use url::Url; /// Validated database connection configuration. #[derive(Clone)] pub struct DatabaseConfig { - url: String, + options: PgConnectOptions, max_connections: u32, connect_timeout: Duration, } @@ -16,7 +19,7 @@ impl std::fmt::Debug for DatabaseConfig { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter .debug_struct("DatabaseConfig") - .field("url", &"[REDACTED]") + .field("options", &"[REDACTED]") .field("max_connections", &self.max_connections) .field("connect_timeout", &self.connect_timeout) .finish() @@ -25,13 +28,13 @@ impl std::fmt::Debug for DatabaseConfig { impl DatabaseConfig { /// Creates production configuration requiring verified `PostgreSQL` TLS. pub fn new( - url: String, + url: &str, max_connections: u32, connect_timeout: Duration, ) -> Result { - Self::validate(&url, max_connections, connect_timeout, false)?; + let options = Self::validate(url, max_connections, connect_timeout, false)?; Ok(Self { - url, + options, max_connections, connect_timeout, }) @@ -39,13 +42,13 @@ impl DatabaseConfig { /// Creates explicit local-development configuration for a loopback database. pub fn new_development( - url: String, + url: &str, max_connections: u32, connect_timeout: Duration, ) -> Result { - Self::validate(&url, max_connections, connect_timeout, true)?; + let options = Self::validate(url, max_connections, connect_timeout, true)?; Ok(Self { - url, + options, max_connections, connect_timeout, }) @@ -56,7 +59,7 @@ impl DatabaseConfig { max_connections: u32, connect_timeout: Duration, development: bool, - ) -> Result<(), DatabaseConnectionError> { + ) -> Result { let parsed = Url::parse(url).map_err(|_| DatabaseConnectionError::InvalidConfiguration)?; if !matches!(parsed.scheme(), "postgres" | "postgresql") || max_connections == 0 @@ -67,6 +70,18 @@ impl DatabaseConfig { let host = parsed .host_str() .ok_or(DatabaseConnectionError::InvalidConfiguration)?; + + let mut ssl_modes = parsed.query_pairs().filter_map(|(name, value)| { + matches!(name.as_ref(), "sslmode" | "ssl-mode").then_some(value) + }); + let ssl_mode = ssl_modes.next(); + if ssl_modes.next().is_some() + || parsed + .query_pairs() + .any(|(name, _)| matches!(name.as_ref(), "host" | "hostaddr")) + { + return Err(DatabaseConnectionError::InvalidConfiguration); + } if development { let loopback = host.eq_ignore_ascii_case("localhost") || host @@ -75,13 +90,19 @@ impl DatabaseConfig { if !loopback { return Err(DatabaseConnectionError::InvalidConfiguration); } - } else if !parsed - .query_pairs() - .any(|(name, value)| name == "sslmode" && value == "verify-full") - { + } else if ssl_mode.as_deref() != Some("verify-full") { return Err(DatabaseConnectionError::InvalidConfiguration); } - Ok(()) + + let options = PgConnectOptions::from_str(url) + .map_err(|_| DatabaseConnectionError::InvalidConfiguration)?; + Ok(if development { + options + } else { + // Keep the effective mode explicit even after validating the URL so + // future parser changes cannot silently weaken production TLS. + options.ssl_mode(PgSslMode::VerifyFull) + }) } } @@ -96,7 +117,7 @@ impl Database { let pool = PgPoolOptions::new() .max_connections(config.max_connections) .acquire_timeout(config.connect_timeout) - .connect(&config.url) + .connect_with(config.options) .await .map_err(|_| DatabaseConnectionError::Unavailable)?; Ok(Self { pool }) @@ -193,17 +214,20 @@ mod tests { #[test] fn production_requires_verified_tls() { + assert!( + DatabaseConfig::new("postgres://db.example/piquel", 1, Duration::from_secs(1)).is_err() + ); assert!( DatabaseConfig::new( - "postgres://db.example/piquel".into(), + "postgres://db.example/piquel?sslmode=verify-full", 1, Duration::from_secs(1) ) - .is_err() + .is_ok() ); assert!( DatabaseConfig::new( - "postgres://db.example/piquel?sslmode=verify-full".into(), + "postgres://db.example/piquel?ssl-mode=verify-full", 1, Duration::from_secs(1) ) @@ -211,11 +235,28 @@ mod tests { ); } + #[test] + fn production_rejects_ambiguous_tls_modes_and_host_overrides() { + for url in [ + "postgres://db.example/piquel?sslmode=verify-full&sslmode=disable", + "postgres://db.example/piquel?sslmode=disable&sslmode=verify-full", + "postgres://db.example/piquel?sslmode=verify-full&ssl-mode=disable", + "postgres://db.example/piquel?sslmode=verify-full&ssl-mode=verify-full", + "postgres://db.example/piquel?sslmode=verify-full&host=elsewhere.example", + "postgres://db.example/piquel?sslmode=verify-full&hostaddr=127.0.0.1", + ] { + assert!( + DatabaseConfig::new(url, 1, Duration::from_secs(1)).is_err(), + "accepted ambiguous database URL: {url}" + ); + } + } + #[test] fn development_is_loopback_only() { assert!( DatabaseConfig::new_development( - "postgres://localhost/piquel".into(), + "postgres://localhost/piquel", 1, Duration::from_secs(1) ) @@ -223,7 +264,15 @@ mod tests { ); assert!( DatabaseConfig::new_development( - "postgres://db.example/piquel".into(), + "postgres://db.example/piquel", + 1, + Duration::from_secs(1) + ) + .is_err() + ); + assert!( + DatabaseConfig::new_development( + "postgres://localhost/piquel?host=db.example", 1, Duration::from_secs(1) ) diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index 6124d4707..50af9c77d 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -13,7 +13,7 @@ use std::{env, time::Duration}; async fn database() -> Database { let url = env::var("TEST_DATABASE_URL") .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); - let config = DatabaseConfig::new_development(url, 10, Duration::from_secs(5)) + let config = DatabaseConfig::new_development(&url, 10, Duration::from_secs(5)) .expect("test database configuration"); let database = Database::connect(config) .await @@ -141,6 +141,26 @@ async fn identity_transactions_and_concurrency_hold() { ); assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); + let enrollment_id = TokenId::new(); + database + .passkeys() + .insert_ceremony(&InsertCeremony { + id: enrollment_id, + user_id: Some(first), + session_id: None, + kind: "enrollment".into(), + challenge_digest: vec![2; 32], + state: serde_json::json!({"enrollment":true}), + expires_at: Utc::now() + ChronoDuration::minutes(5), + }) + .await + .expect("enrollment ceremony"); + database + .passkeys() + .consume_ceremony(enrollment_id, "enrollment") + .await + .expect("consume enrollment ceremony"); + let refresh_session = SessionId::new(); database .sessions() From d94d377a991ec5001eabec63c509a107d3c1a855 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 19:21:18 +0200 Subject: [PATCH 8/9] update security audit --- docs/security/auth-stack-review-2026-07-14.md | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/docs/security/auth-stack-review-2026-07-14.md b/docs/security/auth-stack-review-2026-07-14.md index bda858f61..4c231f8a7 100644 --- a/docs/security/auth-stack-review-2026-07-14.md +++ b/docs/security/auth-stack-review-2026-07-14.md @@ -187,26 +187,6 @@ started enrollment from a stolen browser session. fresh-authentication requirement inside the protected transaction. Serialize revocation on the same session row and add race tests. -### Medium — abuse limits are neither replica-safe nor capacity-safe - -The public limiter is in process memory (`apps/auth-service/src/hardening.rs:23-50`). -N replicas permit N times the configured rate and restart/autoscaling resets -all windows. After 10,000 distinct `(IP, endpoint-class)` keys, every unseen -legitimate client receives 503 (`apps/auth-service/src/hardening.rs:85-93`). -Rotating IPv6 addresses or a botnet can reach that global new-client denial -state within one window. - -Private service-token issuance is outside this limiter. A CA-trusted but -compromised/looping service can multiply the per-connection concurrency limit -with new connections, cause database work for assertions, and append a durable -audit row for every rejected assertion (`apps/auth-service/src/main.rs:125-136`, -`apps/auth-service/src/service_rpc.rs:195-213`). - -**Required action:** place the authoritative aggregate limit at ingress or in -explicitly disposable shared coordination, retain a local circuit breaker, use -bounded eviction rather than global 503 for unseen clients, aggregate IPv6 -prefixes, and add global/per-service RPC concurrency and rate limits. - ### Medium — outstanding OIDC state survives policy removal Authorization-request and code consumption check that the client is enabled, From 32fa675cc0b1e1a9d0fcef1cb6619c2ee863731f Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 15 Jul 2026 13:46:00 +0200 Subject: [PATCH 9/9] fix(auth): preserve purpose flows across stack hardening --- apps/auth-service/src/account.rs | 2 +- apps/auth-service/src/passkey.rs | 6 ++++-- .../migrations/0007_passkey_enrollment_ceremony.sql | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/apps/auth-service/src/account.rs b/apps/auth-service/src/account.rs index d4fa87e3e..1c2f41c3e 100644 --- a/apps/auth-service/src/account.rs +++ b/apps/auth-service/src/account.rs @@ -236,7 +236,7 @@ mod tests { async fn profile_update_and_event_commit_together() { let url = env::var("TEST_DATABASE_URL") .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); - let config = DatabaseConfig::new_development(url, 5, Duration::from_secs(5)) + let config = DatabaseConfig::new_development(&url, 5, Duration::from_secs(5)) .expect("test database configuration"); let database = Database::connect(config).await.expect("connect database"); database.run_migrations().await.expect("run migrations"); diff --git a/apps/auth-service/src/passkey.rs b/apps/auth-service/src/passkey.rs index fa056a680..68c809af6 100644 --- a/apps/auth-service/src/passkey.rs +++ b/apps/auth-service/src/passkey.rs @@ -982,7 +982,9 @@ mod tests { ) -> Request { let mut builder = Request::builder().method(method).uri(uri); if let Some(cookie) = cookie { - builder = builder.header(header::COOKIE, cookie); + builder = builder + .header(header::COOKIE, cookie) + .header(header::ORIGIN, "https://auth.example.com"); } if let Some(token) = purpose_token { builder = builder.header(header::AUTHORIZATION, format!("Bearer {token}")); @@ -1129,7 +1131,7 @@ mod tests { let database_url = env::var("TEST_DATABASE_URL") .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); let database = Database::connect( - DatabaseConfig::new_development(database_url, 5, StdDuration::from_secs(5)) + DatabaseConfig::new_development(&database_url, 5, StdDuration::from_secs(5)) .expect("database configuration"), ) .await diff --git a/crates/database/migrations/0007_passkey_enrollment_ceremony.sql b/crates/database/migrations/0007_passkey_enrollment_ceremony.sql index 40bdfa12d..bb3288db8 100644 --- a/crates/database/migrations/0007_passkey_enrollment_ceremony.sql +++ b/crates/database/migrations/0007_passkey_enrollment_ceremony.sql @@ -3,4 +3,4 @@ ALTER TABLE webauthn_ceremonies ALTER TABLE webauthn_ceremonies ADD CONSTRAINT webauthn_ceremonies_ceremony_kind_check - CHECK (ceremony_kind IN ('registration', 'authentication', 'enrollment')); + CHECK (ceremony_kind IN ('registration', 'authentication', 'enrollment', 'purpose_authentication'));