diff --git a/apps/auth-service/src/oidc/error.rs b/apps/auth-service/src/oidc/error.rs index 9d64aa056..bc83c0ca6 100644 --- a/apps/auth-service/src/oidc/error.rs +++ b/apps/auth-service/src/oidc/error.rs @@ -261,6 +261,27 @@ impl From for OAuthError { } } +impl From for OAuthError { + /// Redemption failures reject the grant; persistence failures retain their internal status. + fn from(error: piquel_repository::CodeRedemptionError) -> Self { + match error { + piquel_repository::CodeRedemptionError::Database(source) => source.into(), + error @ piquel_repository::CodeRedemptionError::Invalid => OAuthCode::InvalidGrant + .reject_with( + "code is unknown or expired, or its client, account or sign-in session no \ + longer allows it", + error, + ), + error @ piquel_repository::CodeRedemptionError::Replay { .. } => { + OAuthCode::InvalidGrant.reject_with( + "code was already used, so any refresh tokens issued from it are revoked", + error, + ) + } + } + } +} + impl From for OAuthError { /// Rotation failures reject the grant; persistence failures retain their internal status. fn from(error: piquel_repository::RefreshRotationError) -> Self { diff --git a/apps/auth-service/src/oidc/tests.rs b/apps/auth-service/src/oidc/tests.rs index c6c8be13a..089dfb4eb 100644 --- a/apps/auth-service/src/oidc/tests.rs +++ b/apps/auth-service/src/oidc/tests.rs @@ -493,6 +493,57 @@ async fn confidential_refresh_rotation_logout_and_client_binding() { ); } +/// Replaying a redeemed code revokes the refresh family it produced, while the same +/// code ID with a guessed secret revokes nothing. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn code_replay_revokes_its_refresh_family() { + let flow = Flow::new(true, true).await; + let code = flow.code(REFRESH_SCOPES).await; + let response = flow + .exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await; + assert_eq!(response.status(), StatusCode::OK); + let tokens = Flow::json(response).await; + let guessed = OpaqueToken { + id: OpaqueToken::parse(TokenPrefix::AuthorizationCode, &code) + .expect("issued code parses") + .id, + ..OpaqueToken::new(TokenPrefix::AuthorizationCode).expect("random secret") + } + .encoded(); + assert_eq!( + flow.exchange(&guessed, Flow::verifier(), flow.basic.as_deref()) + .await + .status(), + StatusCode::BAD_REQUEST + ); + let response = flow + .refresh( + tokens["refresh_token"] + .as_str() + .expect("token response contains a refresh token"), + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "a guess revokes nothing"); + let rotated = Flow::json(response).await["refresh_token"] + .as_str() + .expect("refresh response contains the rotated token") + .to_owned(); + let replay = flow + .exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await; + assert_eq!(replay.status(), StatusCode::BAD_REQUEST); + assert_eq!( + Flow::json(replay).await["error"], + OAuthCode::InvalidGrant.as_str() + ); + assert_eq!( + flow.refresh(&rotated).await.status(), + StatusCode::BAD_REQUEST + ); +} + /// Checks that policy reductions reject new requests and invalidate outstanding grants, /// and that unsafe logout redirects are refused. #[tokio::test] diff --git a/apps/auth-service/src/oidc/token.rs b/apps/auth-service/src/oidc/token.rs index a2d281e31..18f8a1ba2 100644 --- a/apps/auth-service/src/oidc/token.rs +++ b/apps/auth-service/src/oidc/token.rs @@ -10,9 +10,11 @@ use axum::{ http::{HeaderMap, StatusCode, header}, }; use chrono::Utc; -use piquel_auth_protocol::{SessionId, TokenId, UserId}; +use piquel_auth_protocol::{TokenId, UserId}; use piquel_repository::{ - AppendAuditEvent, InsertRefreshFamily, InsertRefreshToken, RefreshRotationError, StoredSession, + AppendAuditEvent, AuditAction, AuditMetadata, AuditOutcome, CodeRedemptionError, + ConsumedAuthorizationCode, DatabaseError, DatabaseTransaction, InsertRefreshFamily, + InsertRefreshToken, RefreshRotationError, StoredSession, }; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -180,7 +182,8 @@ impl OidcApplication { } /// Exchanges a one-use code for the authenticated client after checking its client, - /// redirect and PKCE binding. + /// redirect and PKCE binding. A replayed code has its refresh family revoked and + /// committed before the rejection. async fn exchange_code( &self, form: TokenForm, @@ -194,17 +197,14 @@ impl OidcApplication { )?; let digest = self.token_digest(&opaque)?; let mut tx = self.database.begin().await?; - let code = tx + let code = match tx .oidc() - .consume_code(opaque.id, digest.as_bytes()) + .consume_code(opaque.id, digest.as_bytes(), client_id) .await - .map_err(|error| { - OAuthError::database( - error, - OAuthCode::InvalidGrant, - "code is unknown, expired or already used", - ) - })?; + { + Ok(code) => code, + Err(error) => return Err(Self::code_rejection(tx, error).await), + }; if code.client_id != client_id { return Err(OAuthCode::InvalidGrant.reject("code was issued to another client")); } @@ -247,17 +247,7 @@ impl OidcApplication { } .issue(self, &user, &session, email.as_deref())?; let refresh = if client.allow_refresh && scopes.contains(Scope::OfflineAccess) { - Some( - self.create_refresh( - &mut tx, - code.user_id, - code.session_id, - client.id, - code.audience, - code.scopes, - ) - .await?, - ) + Some(self.create_refresh(&mut tx, code).await?) } else { None }; @@ -289,7 +279,7 @@ impl OidcApplication { .await { Ok(value) => value, - Err(error) => return Err(self.refresh_rejection(tx, error).await), + Err(error) => return Err(Self::refresh_rejection(tx, error).await), }; if rotated.client_id != client_id { return Err( @@ -331,19 +321,16 @@ impl OidcApplication { Ok(tokens) } - /// Creates a refresh family and first token bounded by the browser session lifetime. + /// Creates the refresh family of a redeemed code, linked to the code so a replay + /// can revoke it, and its first token bounded by the browser session lifetime. async fn create_refresh( &self, - tx: &mut piquel_repository::DatabaseTransaction<'_>, - user_id: UserId, - session_id: SessionId, - client_id: String, - audience: String, - scopes: Vec, + tx: &mut DatabaseTransaction<'_>, + code: ConsumedAuthorizationCode, ) -> Result { let session = tx .sessions() - .find_active_by_id(session_id) + .find_active_by_id(code.session_id) .await? .ok_or_else(|| OAuthCode::InvalidGrant.reject(SESSION_ENDED))?; let family_id = TokenId::new(); @@ -354,11 +341,12 @@ impl OidcApplication { .insert_family( &InsertRefreshFamily { id: family_id, - user_id, - client_id, - session_id, - audience, - scopes, + user_id: code.user_id, + client_id: code.client_id, + session_id: code.session_id, + authorization_code_id: code.id, + audience: code.audience, + scopes: code.scopes, }, &InsertRefreshToken { id: opaque.id, @@ -469,35 +457,19 @@ impl OidcApplication { /// Persists replay/policy rejection before returning the preserved rotation failure. async fn refresh_rejection( - &self, - mut tx: piquel_repository::DatabaseTransaction<'_>, + tx: DatabaseTransaction<'_>, error: RefreshRotationError, ) -> OAuthError { - use piquel_repository::{AuditAction, AuditMetadata, AuditOutcome}; let (user_id, action) = match error { RefreshRotationError::Replay { user_id } => (user_id, AuditAction::RefreshReplay), RefreshRotationError::Policy { user_id } => { (user_id, AuditAction::RefreshPolicyRejected) } - RefreshRotationError::Invalid => { + RefreshRotationError::Invalid | RefreshRotationError::Database(_) => { return error.into(); } - RefreshRotationError::Database(_) => return error.into(), }; - let audit = async { - tx.audit_events() - .append(&AppendAuditEvent { - id: TokenId::new(), - user_id: Some(user_id), - action, - outcome: AuditOutcome::Rejected, - request_metadata: AuditMetadata::default(), - }) - .await?; - tx.commit().await - } - .await; - if let Err(source) = audit { + if let Err(source) = Self::commit_rejection(tx, user_id, action).await { return source.into(); } if action == AuditAction::RefreshReplay { @@ -508,6 +480,51 @@ impl OidcApplication { } error.into() } + + /// Persists the family revocation of a replayed code before returning the + /// preserved redemption failure. Access tokens already issued from the code + /// cannot be revoked and simply expire. + /// + /// The browser session behind the code stays signed in: a leaked code exposes + /// the client's callback, not the session cookie, and anyone holding the code + /// could otherwise sign the user out of every application. + async fn code_rejection(tx: DatabaseTransaction<'_>, error: CodeRedemptionError) -> OAuthError { + let user_id = match error { + CodeRedemptionError::Replay { user_id } => user_id, + CodeRedemptionError::Invalid | CodeRedemptionError::Database(_) => { + return error.into(); + } + }; + if let Err(source) = + Self::commit_rejection(tx, user_id, AuditAction::AuthorizationCodeReplay).await + { + return source.into(); + } + tracing::warn!( + event = CODE_REPLAY_EVENT, + "authorization code replay rejected" + ); + error.into() + } + + /// Commits the revocation a rejected grant already made in `tx`, together with + /// its rejected audit event. + async fn commit_rejection( + mut tx: DatabaseTransaction<'_>, + user_id: UserId, + action: AuditAction, + ) -> Result<(), DatabaseError> { + tx.audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: Some(user_id), + action, + outcome: AuditOutcome::Rejected, + request_metadata: AuditMetadata::default(), + }) + .await?; + tx.commit().await + } } /// Rejection of a grant whose account was disabled. @@ -517,3 +534,5 @@ const SESSION_ENDED: &str = "the sign-in session behind this grant has ended"; /// Stable telemetry event name for refresh-token replay rejection. const REFRESH_REPLAY_EVENT: &str = "auth.refresh_replay"; +/// Stable telemetry event name for authorization-code replay rejection. +const CODE_REPLAY_EVENT: &str = "auth.code_replay"; diff --git a/crates/database/.sqlx/query-79aec728b9a281b7e93059a9affdaa4753f274ac2e351564d53a356c1752f916.json b/crates/database/.sqlx/query-233f188a5b0a6b6a244c2b888ed5f05b12420a632d5b08c41859032992fbb254.json similarity index 80% rename from crates/database/.sqlx/query-79aec728b9a281b7e93059a9affdaa4753f274ac2e351564d53a356c1752f916.json rename to crates/database/.sqlx/query-233f188a5b0a6b6a244c2b888ed5f05b12420a632d5b08c41859032992fbb254.json index e4ed50046..a6facdc60 100644 --- a/crates/database/.sqlx/query-79aec728b9a281b7e93059a9affdaa4753f274ac2e351564d53a356c1752f916.json +++ b/crates/database/.sqlx/query-233f188a5b0a6b6a244c2b888ed5f05b12420a632d5b08c41859032992fbb254.json @@ -1,45 +1,50 @@ { "db_name": "PostgreSQL", - "query": "UPDATE authorization_codes c\n SET consumed_at = now()\n FROM oidc_clients cl, sessions s, users u\n WHERE c.id = $1\n AND c.secret_digest = $2\n AND c.consumed_at IS NULL\n AND c.expires_at > now()\n AND cl.id = c.client_id\n AND cl.enabled\n AND cl.allowed_scopes @> c.scopes\n AND cl.allowed_audiences ? c.audience\n AND EXISTS (\n SELECT 1\n FROM oidc_redirect_uris d\n WHERE d.client_id = cl.id\n AND d.kind = 'authorization'\n AND d.uri = c.redirect_uri\n )\n AND s.id = c.session_id\n AND s.revoked_at IS NULL\n AND s.expires_at > now()\n AND u.id = c.user_id\n AND u.status = 'active'\n RETURNING\n c.client_id, c.user_id AS \"user_id: UserId\",\n c.session_id AS \"session_id: SessionId\", c.redirect_uri, c.pkce_challenge,\n c.nonce, c.scopes AS \"scopes: JsonArray\", c.audience", + "query": "UPDATE authorization_codes c\n SET consumed_at = now()\n FROM oidc_clients cl, sessions s, users u\n WHERE c.id = $1\n AND c.secret_digest = $2\n AND c.consumed_at IS NULL\n AND c.expires_at > now()\n AND cl.id = c.client_id\n AND cl.enabled\n AND cl.allowed_scopes @> c.scopes\n AND cl.allowed_audiences ? c.audience\n AND EXISTS (\n SELECT 1\n FROM oidc_redirect_uris d\n WHERE d.client_id = cl.id\n AND d.kind = 'authorization'\n AND d.uri = c.redirect_uri\n )\n AND s.id = c.session_id\n AND s.revoked_at IS NULL\n AND s.expires_at > now()\n AND u.id = c.user_id\n AND u.status = 'active'\n RETURNING\n c.id AS \"id: TokenId\", c.client_id, c.user_id AS \"user_id: UserId\",\n c.session_id AS \"session_id: SessionId\", c.redirect_uri, c.pkce_challenge,\n c.nonce, c.scopes AS \"scopes: JsonArray\", c.audience", "describe": { "columns": [ { "ordinal": 0, + "name": "id: TokenId", + "type_info": "Uuid" + }, + { + "ordinal": 1, "name": "client_id", "type_info": "Text" }, { - "ordinal": 1, + "ordinal": 2, "name": "user_id: UserId", "type_info": "Uuid" }, { - "ordinal": 2, + "ordinal": 3, "name": "session_id: SessionId", "type_info": "Uuid" }, { - "ordinal": 3, + "ordinal": 4, "name": "redirect_uri", "type_info": "Text" }, { - "ordinal": 4, + "ordinal": 5, "name": "pkce_challenge", "type_info": "Text" }, { - "ordinal": 5, + "ordinal": 6, "name": "nonce", "type_info": "Text" }, { - "ordinal": 6, + "ordinal": 7, "name": "scopes: JsonArray", "type_info": "Jsonb" }, { - "ordinal": 7, + "ordinal": 8, "name": "audience", "type_info": "Text" } @@ -56,10 +61,11 @@ false, false, false, + false, true, false, false ] }, - "hash": "79aec728b9a281b7e93059a9affdaa4753f274ac2e351564d53a356c1752f916" + "hash": "233f188a5b0a6b6a244c2b888ed5f05b12420a632d5b08c41859032992fbb254" } diff --git a/crates/database/.sqlx/query-e8852e9aecf149224978b2270ff7671dce0adc4825f5413b0c3dab9efdb7b2bc.json b/crates/database/.sqlx/query-49ebbb7a6bfa7a32e79ed96cb44c9e23d8bb40244af86adb5248bdfabc03bf8a.json similarity index 56% rename from crates/database/.sqlx/query-e8852e9aecf149224978b2270ff7671dce0adc4825f5413b0c3dab9efdb7b2bc.json rename to crates/database/.sqlx/query-49ebbb7a6bfa7a32e79ed96cb44c9e23d8bb40244af86adb5248bdfabc03bf8a.json index 6809c5d14..80f030025 100644 --- a/crates/database/.sqlx/query-e8852e9aecf149224978b2270ff7671dce0adc4825f5413b0c3dab9efdb7b2bc.json +++ b/crates/database/.sqlx/query-49ebbb7a6bfa7a32e79ed96cb44c9e23d8bb40244af86adb5248bdfabc03bf8a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO refresh_token_families (\n id, user_id, client_id, session_id, audience, scopes\n ) VALUES ($1, $2, $3, $4, $5, $6)", + "query": "INSERT INTO refresh_token_families (\n id, user_id, client_id, session_id, authorization_code_id, audience, scopes\n ) VALUES ($1, $2, $3, $4, $5, $6, $7)", "describe": { "columns": [], "parameters": { @@ -9,11 +9,12 @@ "Uuid", "Text", "Uuid", + "Uuid", "Text", "Jsonb" ] }, "nullable": [] }, - "hash": "e8852e9aecf149224978b2270ff7671dce0adc4825f5413b0c3dab9efdb7b2bc" + "hash": "49ebbb7a6bfa7a32e79ed96cb44c9e23d8bb40244af86adb5248bdfabc03bf8a" } diff --git a/crates/database/.sqlx/query-4d12d852d8493c27ec4f7763febfdfc922c6ff16d796a7afecc5a73558f8f2ae.json b/crates/database/.sqlx/query-4d12d852d8493c27ec4f7763febfdfc922c6ff16d796a7afecc5a73558f8f2ae.json deleted file mode 100644 index 14cf7bfc0..000000000 --- a/crates/database/.sqlx/query-4d12d852d8493c27ec4f7763febfdfc922c6ff16d796a7afecc5a73558f8f2ae.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM authorization_codes\n WHERE ctid IN (\n SELECT ctid\n FROM authorization_codes\n WHERE expires_at < now()\n OR consumed_at < now() - interval '1 day'\n LIMIT $1\n FOR UPDATE SKIP LOCKED\n )", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8" - ] - }, - "nullable": [] - }, - "hash": "4d12d852d8493c27ec4f7763febfdfc922c6ff16d796a7afecc5a73558f8f2ae" -} diff --git a/crates/database/.sqlx/query-9acf1acac4c212893c641b7f0531c982478ddadcc096ad0eb010ef3fc228a34d.json b/crates/database/.sqlx/query-9acf1acac4c212893c641b7f0531c982478ddadcc096ad0eb010ef3fc228a34d.json new file mode 100644 index 000000000..5b873ad4f --- /dev/null +++ b/crates/database/.sqlx/query-9acf1acac4c212893c641b7f0531c982478ddadcc096ad0eb010ef3fc228a34d.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM authorization_codes c\n WHERE c.ctid IN (\n SELECT code.ctid\n FROM authorization_codes code\n WHERE (code.consumed_at IS NULL AND code.expires_at < now())\n OR (\n code.consumed_at < now() - interval '1 day'\n AND NOT EXISTS (\n SELECT 1\n FROM refresh_token_families family\n JOIN sessions session ON session.id = family.session_id\n WHERE family.authorization_code_id = code.id\n AND family.revoked_at IS NULL\n AND session.revoked_at IS NULL\n AND session.expires_at > now()\n )\n )\n LIMIT $1\n FOR UPDATE OF code SKIP LOCKED\n )", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [] + }, + "hash": "9acf1acac4c212893c641b7f0531c982478ddadcc096ad0eb010ef3fc228a34d" +} diff --git a/crates/database/.sqlx/query-cd1a45795caa5857b020db1f77349f5f9ebc136e4556462196fff080d263db3f.json b/crates/database/.sqlx/query-cd1a45795caa5857b020db1f77349f5f9ebc136e4556462196fff080d263db3f.json new file mode 100644 index 000000000..4f1cda65a --- /dev/null +++ b/crates/database/.sqlx/query-cd1a45795caa5857b020db1f77349f5f9ebc136e4556462196fff080d263db3f.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT user_id AS \"user_id: UserId\", consumed_at IS NOT NULL AS \"consumed!\"\n FROM authorization_codes\n WHERE id = $1\n AND secret_digest = $2\n AND client_id = $3\n FOR SHARE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "user_id: UserId", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "consumed!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Bytea", + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "cd1a45795caa5857b020db1f77349f5f9ebc136e4556462196fff080d263db3f" +} diff --git a/crates/database/.sqlx/query-ceba390bc188ed3137bdc46794d109689a7a1ac4272c8f02eca32a639edc2b80.json b/crates/database/.sqlx/query-ceba390bc188ed3137bdc46794d109689a7a1ac4272c8f02eca32a639edc2b80.json new file mode 100644 index 000000000..cd4df7523 --- /dev/null +++ b/crates/database/.sqlx/query-ceba390bc188ed3137bdc46794d109689a7a1ac4272c8f02eca32a639edc2b80.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE refresh_token_families\n SET revoked_at = now()\n WHERE authorization_code_id = $1\n AND revoked_at IS NULL", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "ceba390bc188ed3137bdc46794d109689a7a1ac4272c8f02eca32a639edc2b80" +} diff --git a/crates/database/README.md b/crates/database/README.md index 9a2924c8b..560650f33 100644 --- a/crates/database/README.md +++ b/crates/database/README.md @@ -3,7 +3,7 @@ Typed PostgreSQL persistence for the authentication service. SQLx pools and SQL remain private; callers use repositories or a `DatabaseTransaction`. -The schema is a single migration, `migrations/0001_initial.sql`. Each repository +The schema lives in numbered, immutable files under `migrations/`. Each repository module in `src/repositories/` owns its methods and record types; `mod.rs` holds only shared plumbing. See [database architecture](../../docs/architecture/database-crate.md) for the layout and invariants. Run migrations through the single service binary: diff --git a/crates/database/migrations/0002_refresh_family_authorization_code.sql b/crates/database/migrations/0002_refresh_family_authorization_code.sql new file mode 100644 index 000000000..09a0c82fe --- /dev/null +++ b/crates/database/migrations/0002_refresh_family_authorization_code.sql @@ -0,0 +1,12 @@ +-- Links each refresh family to the authorization code it was redeemed from, so +-- redeeming that code again revokes the family (RFC 6749 section 4.1.2). +-- Families created before this migration have no link. Cleanup keeps a redeemed +-- code while a family it produced can still refresh; purging it afterwards +-- clears the link rather than failing on it. +ALTER TABLE refresh_token_families + ADD COLUMN authorization_code_id UUID REFERENCES authorization_codes(id) ON DELETE SET NULL; +-- Serves replay revocation, cleanup's live-family check and the ON DELETE SET +-- NULL lookup when codes are purged. +CREATE INDEX refresh_families_authorization_code_idx ON refresh_token_families (authorization_code_id); +-- Lets cleanup find redeemed codes past their grace period without a full scan. +CREATE INDEX authorization_codes_consumed_idx ON authorization_codes (consumed_at) WHERE consumed_at IS NOT NULL; diff --git a/crates/database/src/connection/mod.rs b/crates/database/src/connection/mod.rs index 5234ac8bc..3ba3d26ea 100644 --- a/crates/database/src/connection/mod.rs +++ b/crates/database/src/connection/mod.rs @@ -210,8 +210,9 @@ impl Database { /// rows per table. /// /// Each table's batch commits on its own and skips rows that live requests have - /// locked, so cleanup never holds locks across tables. Deleting a session can - /// still wait briefly on a locked child row it cascades to. + /// locked, so cleanup never holds locks across tables. Deleting a session or an + /// authorization code can still wait briefly on a locked child row it cascades + /// to or unlinks. /// /// # Errors /// @@ -283,14 +284,31 @@ impl Database { LIMIT $1 FOR UPDATE SKIP LOCKED )", - "DELETE FROM authorization_codes - WHERE ctid IN ( - SELECT ctid - FROM authorization_codes - WHERE expires_at < now() - OR consumed_at < now() - interval '1 day' + // A redeemed code stays while a replay could still revoke something: an + // unrevoked family it produced whose session is live (refresh tokens expire + // with the session). The first day after redemption is kept regardless, so + // replays are still audited even for codes that produced no refresh family. + // Retained codes are rechecked on every pass, so this scan grows with + // every redeemed code past its first day, not only with purgeable ones. + "DELETE FROM authorization_codes c + WHERE c.ctid IN ( + SELECT code.ctid + FROM authorization_codes code + WHERE (code.consumed_at IS NULL AND code.expires_at < now()) + OR ( + code.consumed_at < now() - interval '1 day' + AND NOT EXISTS ( + SELECT 1 + FROM refresh_token_families family + JOIN sessions session ON session.id = family.session_id + WHERE family.authorization_code_id = code.id + AND family.revoked_at IS NULL + AND session.revoked_at IS NULL + AND session.expires_at > now() + ) + ) LIMIT $1 - FOR UPDATE SKIP LOCKED + FOR UPDATE OF code SKIP LOCKED )", "DELETE FROM refresh_tokens t WHERE t.ctid IN ( diff --git a/crates/database/src/connection/tests.rs b/crates/database/src/connection/tests.rs index 7e3ca96c0..d9de4c0e1 100644 --- a/crates/database/src/connection/tests.rs +++ b/crates/database/src/connection/tests.rs @@ -149,6 +149,71 @@ async fn cleanup_skips_rows_locked_by_requests() { request.rollback().await.expect("rollback request"); } +/// A redeemed code outlives its one-day grace while its refresh family can still +/// refresh, so a late replay can revoke it; cleanup purges it once the session ends. +#[tokio::test] +#[ignore = "requires a disposable TEST_DATABASE_URL"] +async fn cleanup_keeps_redeemed_codes_while_their_session_is_live() { + let pool = Database::test_pool().await; + let database = Database { pool: pool.clone() }; + let [user, session, code, family] = [(); 4].map(|()| uuid::Uuid::now_v7()); + let client = format!("purge_{user}"); + // One statement keeps the fixture short; foreign keys are checked at its end. + sqlx::query( + "WITH account AS ( + INSERT INTO users (id, username, display_name) VALUES ($1, $5, 'Purge') + ), browser AS ( + INSERT INTO sessions ( + id, user_id, authentication_methods, authenticated_at, expires_at, last_seen_at + ) VALUES ($2, $1, '[]', now(), now() + interval '30 days', now()) + ), registration AS ( + INSERT INTO oidc_clients (id, display_name, allowed_scopes, allowed_audiences) + VALUES ($5, 'Purge', '[]', '[]') + ), redeemed AS ( + INSERT INTO authorization_codes ( + id, secret_digest, client_id, user_id, session_id, redirect_uri, + pkce_challenge, scopes, audience, expires_at, consumed_at + ) VALUES ($3, convert_to($3::text, 'UTF8'), $5, $1, $2, 'https://client.example', + 'challenge', '[]', 'test', now() - interval '2 days', now() - interval '2 days') + ) + INSERT INTO refresh_token_families ( + id, user_id, client_id, session_id, authorization_code_id, audience, scopes + ) VALUES ($4, $1, $5, $2, $3, 'test', '[]')", + ) + .bind(user) + .bind(session) + .bind(code) + .bind(family) + .bind(&client) + .execute(&pool) + .await + .expect("redeemed grant"); + let link = || async { + sqlx::query_scalar::<_, Option>( + "SELECT authorization_code_id FROM refresh_token_families WHERE id = $1", + ) + .bind(family) + .fetch_one(&pool) + .await + .expect("family link") + }; + database + .purge_expired_auth_state(1000) + .await + .expect("purge"); + assert_eq!(link().await, Some(code), "a live grant keeps its code"); + sqlx::query("UPDATE sessions SET revoked_at = now() WHERE id = $1") + .bind(session) + .execute(&pool) + .await + .expect("end session"); + database + .purge_expired_auth_state(1000) + .await + .expect("purge"); + assert_eq!(link().await, None, "an ended session releases its code"); +} + /// Startup failures identify the invalid transport or pool setting without printing credentials. #[test] fn configuration_errors_name_the_constraint_and_preserve_parsers() { diff --git a/crates/database/src/lib.rs b/crates/database/src/lib.rs index b67fa347f..65ae7a8c2 100644 --- a/crates/database/src/lib.rs +++ b/crates/database/src/lib.rs @@ -23,9 +23,9 @@ pub use repositories::{ PendingFederation, StoredExternalIdentity, }, oidc::{ - BootstrapOidcClient, ClientConfigurationError, ConsumedAuthorizationCode, - InsertAuthorizationCode, InsertAuthorizationRequest, OidcRedirectKind, - StoredAuthorizationRequest, StoredOidcClient, + BootstrapOidcClient, ClientConfigurationError, CodeRedemptionError, + ConsumedAuthorizationCode, InsertAuthorizationCode, InsertAuthorizationRequest, + OidcRedirectKind, StoredAuthorizationRequest, StoredOidcClient, }, passkeys::{CeremonyKind, ConsumedCeremony, InsertCeremony, InsertPasskey, StoredPasskey}, sessions::{InsertSession, StoredSession}, diff --git a/crates/database/src/repositories/audit.rs b/crates/database/src/repositories/audit.rs index d7484945d..d7152239d 100644 --- a/crates/database/src/repositories/audit.rs +++ b/crates/database/src/repositories/audit.rs @@ -30,6 +30,8 @@ piquel_common::str_enum! { RefreshReplay = "refresh.replay", /// Refresh token policy rejected rotation. RefreshPolicyRejected = "refresh.policy_rejected", + /// A redeemed authorization code was redeemed again. + AuthorizationCodeReplay = "authorization_code.replay", } } piquel_common::str_enum! { diff --git a/crates/database/src/repositories/oidc.rs b/crates/database/src/repositories/oidc.rs index c3779eec9..1ccfd4abc 100644 --- a/crates/database/src/repositories/oidc.rs +++ b/crates/database/src/repositories/oidc.rs @@ -299,6 +299,8 @@ pub struct InsertAuthorizationCode { /// the client, redirect URI and PKCE verifier against it. #[derive(Clone, Debug)] pub struct ConsumedAuthorizationCode { + /// Code identifier, recorded on the refresh family the exchange creates. + pub id: TokenId, /// Client the code was issued to. pub client_id: String, /// Authorizing account. @@ -317,6 +319,25 @@ pub struct ConsumedAuthorizationCode { pub audience: String, } +/// Why [`OidcRepository::consume_code`] could not redeem a code. +#[derive(Debug, thiserror::Error)] +pub enum CodeRedemptionError { + /// The database failed. + #[error(transparent)] + Database(#[from] DatabaseError), + /// The code is unknown or expired, or its client, session or account no + /// longer allows it. + #[error("the authorization code is invalid")] + Invalid, + /// The code was already redeemed; any refresh families issued from it are + /// now revoked. + #[error("the authorization code was replayed")] + Replay { + /// Account whose grant was revoked. + user_id: UserId, + }, +} + impl OidcRepository<'_> { /// Disables every client. Startup provisioning calls it in the same /// transaction as [`Self::bootstrap_client`], so removed clients fail closed. @@ -597,18 +618,30 @@ impl OidcRepository<'_> { /// Consumes an unexpired code once. The client's current policy must still /// allow it, and its session and account must still be active. /// + /// Redeeming an already consumed code with its secret, as the authenticated + /// `client_id` it was issued to, is a replay (RFC 6749 section 4.1.2): the + /// refresh families issued from the code are revoked in this transaction, which + /// the caller commits even though the exchange fails. The caller still checks + /// the returned code's client, so `client_id` only scopes replay detection. + /// /// # Errors /// - /// Returns [`DatabaseError::NotFound`] if no such code exists, or another - /// [`DatabaseError`] if the query fails. + /// Returns [`CodeRedemptionError::Replay`] after revoking the code's refresh + /// families, [`CodeRedemptionError::Invalid`] if the code is otherwise not + /// usable, or [`CodeRedemptionError::Database`] if a query fails. pub async fn consume_code( &mut self, id: TokenId, digest: &[u8], - ) -> Result { - run!( + client_id: &str, + ) -> Result { + // If the code still looks redeemable, this update waits on a concurrent + // first redemption's row lock, then re-reads the row and skips it if that + // exchange committed. Otherwise it skips the row without waiting, and the + // replay lookup below waits instead. + let code = run!( self, - fetch_one, + fetch_optional, sqlx::query_as!( ConsumedAuthorizationCode, r#"UPDATE authorization_codes c @@ -635,13 +668,73 @@ impl OidcRepository<'_> { AND u.id = c.user_id AND u.status = 'active' RETURNING - c.client_id, c.user_id AS "user_id: UserId", + c.id AS "id: TokenId", c.client_id, c.user_id AS "user_id: UserId", c.session_id AS "session_id: SessionId", c.redirect_uri, c.pkce_challenge, c.nonce, c.scopes AS "scopes: JsonArray", c.audience"#, id.as_uuid(), digest, ) - ) + )?; + match code { + Some(code) => Ok(code), + None => Err( + match self.revoke_replayed_code(id, digest, client_id).await? { + Some(user_id) => CodeRedemptionError::Replay { user_id }, + None => CodeRedemptionError::Invalid, + }, + ), + } + } + + /// Revokes the refresh families issued from an already consumed code and + /// returns its account, or `None` if `id`, `digest` and `client_id` match no + /// consumed code. Matching the secret digest and client means neither a guessed + /// code ID nor a leaked code presented by another client can revoke a grant. + async fn revoke_replayed_code( + &mut self, + id: TokenId, + digest: &[u8], + client_id: &str, + ) -> Result, DatabaseError> { + // The row qualifies whether or not it is consumed, so FOR SHARE waits for + // an in-flight first redemption and then reads the committed row, together + // with its family. Filtering on `consumed_at` would test this statement's + // snapshot, where an uncommitted redemption is invisible, and skip the wait. + // The lock also stops cleanup from purging the code, and unlinking the + // family, before this transaction commits. + let Some(code) = run!( + self, + fetch_optional, + sqlx::query!( + r#"SELECT user_id AS "user_id: UserId", consumed_at IS NOT NULL AS "consumed!" + FROM authorization_codes + WHERE id = $1 + AND secret_digest = $2 + AND client_id = $3 + FOR SHARE"#, + id.as_uuid(), + digest, + client_id, + ) + )? + .filter(|code| code.consumed) else { + return Ok(None); + }; + // A separate statement takes a fresh snapshot, which includes a family + // committed while the lock above waited. Only the family lock is taken, so + // this stays within the user -> session -> family order of rotation. + run!( + self, + execute, + sqlx::query!( + "UPDATE refresh_token_families + SET revoked_at = now() + WHERE authorization_code_id = $1 + AND revoked_at IS NULL", + id.as_uuid(), + ) + )?; + Ok(Some(code.user_id)) } /// Reports whether the user already consented to all of `scopes` for this diff --git a/crates/database/src/repositories/tokens/mod.rs b/crates/database/src/repositories/tokens/mod.rs index e982639b3..10a6b4d48 100644 --- a/crates/database/src/repositories/tokens/mod.rs +++ b/crates/database/src/repositories/tokens/mod.rs @@ -18,6 +18,9 @@ pub struct InsertRefreshFamily { pub client_id: String, /// Session the grant came from; revoking it revokes the family. pub session_id: SessionId, + /// Authorization code the grant was redeemed from; replaying the code + /// revokes the family. + pub authorization_code_id: TokenId, /// Granted token audience. pub audience: String, /// Granted scopes. @@ -95,12 +98,13 @@ impl TokenRepository<'_> { execute, sqlx::query!( "INSERT INTO refresh_token_families ( - id, user_id, client_id, session_id, audience, scopes - ) VALUES ($1, $2, $3, $4, $5, $6)", + id, user_id, client_id, session_id, authorization_code_id, audience, scopes + ) VALUES ($1, $2, $3, $4, $5, $6, $7)", family.id.as_uuid(), family.user_id.as_uuid(), family.client_id, family.session_id.as_uuid(), + family.authorization_code_id.as_uuid(), family.audience, Json(&family.scopes) as _, ) diff --git a/crates/database/src/repositories/tokens/tests.rs b/crates/database/src/repositories/tokens/tests.rs index 60ee3404b..32db074a3 100644 --- a/crates/database/src/repositories/tokens/tests.rs +++ b/crates/database/src/repositories/tokens/tests.rs @@ -3,74 +3,175 @@ use crate::Database; use super::{InsertRefreshFamily, InsertRefreshToken, RefreshRotationError}; use crate::repositories::{OidcRepository, TokenRepository}; +use crate::{CodeRedemptionError, DatabaseTransaction}; use chrono::{Duration, Utc}; use piquel_auth_protocol::{SessionId, TokenId, UserId}; -use sqlx::PgPool; +use sqlx::{PgConnection, PgPool}; use std::time::Duration as Wait; -/// Creates a committed refresh grant and browser session for concurrent rotation scenarios. -async fn family(pool: &PgPool, client: &str) -> (TokenId, Vec, SessionId) { - let user = UserId::new(); - let session = SessionId::new(); - let family = TokenId::new(); - let token = TokenId::new(); - let digest = token.as_uuid().as_bytes().repeat(2); - let mut tx = pool.begin().await.expect("transaction"); - sqlx::query("INSERT INTO users(id,username,display_name) VALUES($1,$2,'Lock test')") - .bind(user.as_uuid()) - .bind(format!("lock_{user}")) - .execute(&mut *tx) - .await - .expect("user"); + +/// Authorization callback registered for every fixture client. +const REDIRECT_URI: &str = "https://client.example/callback"; + +/// Registers a refresh-capable client whose policy allows fixture codes. +async fn client(pool: &PgPool) -> String { + let client = format!("locks_{}", UserId::new()); + sqlx::query( + "INSERT INTO oidc_clients ( + id, display_name, allowed_scopes, allowed_audiences, allow_refresh + ) VALUES ($1, 'Lock test', '[\"openid\"]', '[\"test\"]', true)", + ) + .bind(&client) + .execute(pool) + .await + .expect("client"); sqlx::query( - "INSERT INTO sessions ( - id, user_id, authentication_methods, authenticated_at, expires_at, last_seen_at - ) VALUES ($1, $2, '[]', now(), now() + interval '1 hour', now())", + "INSERT INTO oidc_redirect_uris (client_id, uri, kind) VALUES ($1, $2, 'authorization')", ) - .bind(session.as_uuid()) - .bind(user.as_uuid()) - .execute(&mut *tx) + .bind(&client) + .bind(REDIRECT_URI) + .execute(pool) .await - .expect("session"); - TokenRepository::from_connection(&mut tx) - .insert_family( - &InsertRefreshFamily { - id: family, - user_id: user, - session_id: session, - client_id: client.into(), - audience: "test".into(), - scopes: vec!["openid".into()], - }, - &InsertRefreshToken { - id: token, - family_id: family, - secret_digest: digest.clone(), - expires_at: Utc::now() + Duration::hours(1), - }, + .expect("redirect"); + client +} + +/// Returns the server process of a connection, to observe its lock waits. +async fn backend(connection: &mut PgConnection) -> i32 { + sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(connection) + .await + .expect("backend pid") +} + +/// Waits until the server process `backend` is blocked on a lock. +async fn wait_for_lock(pool: &PgPool, backend: i32) { + tokio::time::timeout(Wait::from_secs(2), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS ( + SELECT 1 + FROM pg_stat_activity + WHERE pid = $1 + AND wait_event_type = 'Lock' + )", + ) + .bind(backend) + .fetch_one(pool) + .await + .expect("wait state"); + if waiting { + break; + } + tokio::time::sleep(Wait::from_millis(10)).await; + } + }) + .await + .expect("the transaction waits for a lock"); +} + +/// A committed account, browser session and unredeemed authorization code. +struct Grant { + /// Account the code was issued to. + user: UserId, + /// Session that authorized the code. + session: SessionId, + /// Authorization code identifier. + code: TokenId, + /// Digest of the code secret. + code_digest: Vec, +} + +impl Grant { + /// Commits a fresh account, session and code issued to `client`. + async fn new(pool: &PgPool, client: &str) -> Self { + let grant = Self { + user: UserId::new(), + session: SessionId::new(), + code: TokenId::new(), + code_digest: TokenId::new().as_uuid().as_bytes().repeat(2), + }; + let mut tx = pool.begin().await.expect("transaction"); + sqlx::query("INSERT INTO users(id,username,display_name) VALUES($1,$2,'Lock test')") + .bind(grant.user.as_uuid()) + .bind(format!("lock_{}", grant.user)) + .execute(&mut *tx) + .await + .expect("user"); + sqlx::query( + "INSERT INTO sessions ( + id, user_id, authentication_methods, authenticated_at, expires_at, last_seen_at + ) VALUES ($1, $2, '[]', now(), now() + interval '1 hour', now())", + ) + .bind(grant.session.as_uuid()) + .bind(grant.user.as_uuid()) + .execute(&mut *tx) + .await + .expect("session"); + sqlx::query( + "INSERT INTO authorization_codes ( + id, secret_digest, client_id, user_id, session_id, redirect_uri, + pkce_challenge, scopes, audience, expires_at + ) VALUES ($1, $2, $3, $4, $5, $6, 'challenge', '[\"openid\"]', 'test', + now() + interval '1 minute')", ) + .bind(grant.code.as_uuid()) + .bind(&grant.code_digest) + .bind(client) + .bind(grant.user.as_uuid()) + .bind(grant.session.as_uuid()) + .bind(REDIRECT_URI) + .execute(&mut *tx) .await - .expect("family"); - tx.commit().await.expect("commit"); - (token, digest, session) + .expect("code"); + tx.commit().await.expect("commit"); + grant + } + + /// Creates a refresh family redeemed from this grant's code and returns its + /// first token with that token's digest. + async fn family(&self, tokens: &mut TokenRepository<'_>, client: &str) -> (TokenId, Vec) { + let family = TokenId::new(); + let token = TokenId::new(); + let digest = token.as_uuid().as_bytes().repeat(2); + tokens + .insert_family( + &InsertRefreshFamily { + id: family, + user_id: self.user, + session_id: self.session, + client_id: client.into(), + authorization_code_id: self.code, + audience: "test".into(), + scopes: vec!["openid".into()], + }, + &InsertRefreshToken { + id: token, + family_id: family, + secret_digest: digest.clone(), + expires_at: Utc::now() + Duration::hours(1), + }, + ) + .await + .expect("family"); + (token, digest) + } } + /// Shared client policy permits independent refreshes while logout waits in the /// documented lock order. #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { let pool = Database::test_pool().await; - let client = format!("locks_{}", UserId::new()); - sqlx::query( - "INSERT INTO oidc_clients ( - id, display_name, allowed_scopes, allowed_audiences, allow_refresh - ) VALUES ($1, 'Lock test', '[\"openid\"]', '[\"test\"]', true)", - ) - .bind(&client) - .execute(&pool) - .await - .expect("client"); - let (first, digest_first, session) = family(&pool, &client).await; - let (second, digest_second, _) = family(&pool, &client).await; + let client = client(&pool).await; + let grant = Grant::new(&pool, &client).await; + let (first, digest_first) = grant + .family(&mut TokenRepository::from_pool(&pool), &client) + .await; + let (second, digest_second) = Grant::new(&pool, &client) + .await + .family(&mut TokenRepository::from_pool(&pool), &client) + .await; let mut first_tx = pool.begin().await.expect("first transaction"); TokenRepository::from_connection(&mut first_tx) .consume_for_rotation(first, &digest_first, &client) @@ -93,15 +194,12 @@ async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { let mut logout = pool.begin().await.expect("logout transaction"); sqlx::query("UPDATE sessions SET revoked_at=now() WHERE id=$1") - .bind(session.as_uuid()) + .bind(grant.session.as_uuid()) .execute(&mut *logout) .await .expect("lock session"); let mut rotation = pool.begin().await.expect("rotation transaction"); - let backend: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") - .fetch_one(&mut *rotation) - .await - .expect("backend pid"); + let rotation_backend = backend(&mut rotation).await; let rotation_task = tokio::spawn(async move { let result = TokenRepository::from_connection(&mut rotation) .consume_for_rotation(first, &digest_first, &client) @@ -109,31 +207,10 @@ async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { rotation.rollback().await.expect("rollback rotation"); result }); - tokio::time::timeout(Wait::from_secs(2), async { - loop { - let waiting: bool = sqlx::query_scalar( - "SELECT EXISTS ( - SELECT 1 - FROM pg_stat_activity - WHERE pid = $1 - AND wait_event_type = 'Lock' - )", - ) - .bind(backend) - .fetch_one(&pool) - .await - .expect("wait state"); - if waiting { - break; - } - tokio::time::sleep(Wait::from_millis(10)).await; - } - }) - .await - .expect("rotation waits for logout session lock"); + wait_for_lock(&pool, rotation_backend).await; tokio::time::timeout( Wait::from_secs(2), - OidcRepository::from_connection(&mut logout).revoke_session(session), + OidcRepository::from_connection(&mut logout).revoke_session(grant.session), ) .await .expect("logout must not wait for refresh family locks") @@ -152,17 +229,11 @@ async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn replay_revokes_family_despite_invalid_scopes() { let pool = Database::test_pool().await; - let client = format!("replay_{}", UserId::new()); - sqlx::query( - "INSERT INTO oidc_clients ( - id, display_name, allowed_scopes, allowed_audiences, allow_refresh - ) VALUES ($1, 'Replay test', '[\"openid\"]', '[\"test\"]', true)", - ) - .bind(&client) - .execute(&pool) - .await - .expect("client"); - let (token, digest, _) = family(&pool, &client).await; + let client = client(&pool).await; + let (token, digest) = Grant::new(&pool, &client) + .await + .family(&mut TokenRepository::from_pool(&pool), &client) + .await; for statement in [ "UPDATE refresh_tokens SET consumed_at=now() WHERE id=$1", "UPDATE refresh_token_families SET scopes='[1]' @@ -195,3 +266,86 @@ async fn replay_revokes_family_despite_invalid_scopes() { .expect("family"); assert!(revoked); } + +/// A replay racing the first redemption waits for it, then revokes the family +/// that redemption committed. While the code still looks redeemable the replay's +/// consuming update waits; once the client drops the code's redirect URI that +/// update skips the row without waiting, so the replay lookup must wait instead. +#[tokio::test] +#[ignore = "requires a disposable TEST_DATABASE_URL"] +async fn code_replay_waits_for_first_redemption_and_revokes_its_family() { + let pool = Database::test_pool().await; + for redeemable in [true, false] { + let client = client(&pool).await; + let grant = Grant::new(&pool, &client).await; + let mut first = DatabaseTransaction::new(pool.begin().await.expect("first redemption")); + first + .oidc() + .consume_code(grant.code, &grant.code_digest, &client) + .await + .expect("first redemption"); + let (token, digest) = grant.family(&mut first.tokens(), &client).await; + if !redeemable { + sqlx::query("DELETE FROM oidc_redirect_uris WHERE client_id = $1") + .bind(&client) + .execute(&pool) + .await + .expect("remove redirect URI"); + } + let mut replay = DatabaseTransaction::new(pool.begin().await.expect("replay")); + let replay_backend = backend(&mut replay.inner).await; + let (code, code_digest, replay_client) = + (grant.code, grant.code_digest.clone(), client.clone()); + let replay_task = tokio::spawn(async move { + let result = replay + .oidc() + .consume_code(code, &code_digest, &replay_client) + .await; + replay.commit().await.expect("commit replay"); + result + }); + wait_for_lock(&pool, replay_backend).await; + first.commit().await.expect("commit first redemption"); + let result = replay_task.await.expect("replay task"); + assert!( + matches!(result, Err(CodeRedemptionError::Replay { user_id }) if user_id == grant.user), + "redeemable {redeemable}: {result:?}" + ); + let mut rotation = pool.begin().await.expect("rotation transaction"); + let result = TokenRepository::from_connection(&mut rotation) + .consume_for_rotation(token, &digest, &client) + .await; + assert!( + matches!(result, Err(RefreshRotationError::Invalid)), + "redeemable {redeemable}: {result:?}" + ); + } +} + +/// A redeemed code presented by another client is invalid and revokes nothing. +#[tokio::test] +#[ignore = "requires a disposable TEST_DATABASE_URL"] +async fn code_replay_by_another_client_revokes_nothing() { + let pool = Database::test_pool().await; + let client = client(&pool).await; + let grant = Grant::new(&pool, &client).await; + let mut oidc = OidcRepository::from_pool(&pool); + oidc.consume_code(grant.code, &grant.code_digest, &client) + .await + .expect("first redemption"); + let (token, digest) = grant + .family(&mut TokenRepository::from_pool(&pool), &client) + .await; + let result = oidc + .consume_code(grant.code, &grant.code_digest, "another-client") + .await; + assert!( + matches!(result, Err(CodeRedemptionError::Invalid)), + "{result:?}" + ); + let mut rotation = pool.begin().await.expect("rotation transaction"); + TokenRepository::from_connection(&mut rotation) + .consume_for_rotation(token, &digest, &client) + .await + .expect("the family still rotates"); +} diff --git a/docs/architecture/database-crate.md b/docs/architecture/database-crate.md index e1c687272..77275edcf 100644 --- a/docs/architecture/database-crate.md +++ b/docs/architecture/database-crate.md @@ -74,8 +74,14 @@ Important invariants: - Authorization codes are single-use and bound to client, redirect and PKCE. Refresh tokens rotate transactionally, remain bound to their client/session, and reuse revokes the family. +- Each refresh family records the code it was redeemed from. Redeeming that code + again with its secret, as the same client, revokes the family and audits the + replay; a wrong secret or client revokes nothing. The browser session stays + signed in. Cleanup keeps a redeemed code for at least a day, and for as long as + a family it produced is unrevoked and its session live, so a replay is detected + while it could still revoke tokens. -The schema is a single initial migration, `migrations/0001_initial.sql`. The +The schema starts with the initial migration, `migrations/0001_initial.sql`. The prototype schema is disposable and the release requires a fresh database. Released migrations are immutable; later schema changes go in new numbered files. Run migrations with `just db migrate` (`auth-service migrate` in deployed images); startup does not silently mutate the schema.