From a79c7746a3640a39ad9a0b26ebfb0f9f5c6ee4ad Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 4 Nov 2026 11:33:19 +0100 Subject: [PATCH 1/3] refactor(tests): unit tests live in a sibling tests.rs, not an inline module Inline test blocks over 30 lines move to foo/tests.rs, turning foo.rs into foo/mod.rs. Smaller blocks stay inline, as do config.rs and oidc/authorize.rs, which are being split elsewhere. Co-Authored-By: Claude Opus 5.5 --- .../admin/{overview.rs => overview/mod.rs} | 42 +--- apps/auth-service/src/admin/overview/tests.rs | 39 +++ .../src/admin/{types.rs => types/mod.rs} | 65 +---- apps/auth-service/src/admin/types/tests.rs | 62 +++++ .../src/deletion/{export.rs => export/mod.rs} | 222 +----------------- .../auth-service/src/deletion/export/tests.rs | 219 +++++++++++++++++ .../auth-service/src/{jobs.rs => jobs/mod.rs} | 200 +--------------- apps/auth-service/src/jobs/tests.rs | 193 +++++++++++++++ apps/web/src/{site.rs => site/mod.rs} | 62 +---- apps/web/src/site/tests.rs | 59 +++++ crates/common/src/{email.rs => email/mod.rs} | 86 +------ crates/common/src/email/tests.rs | 83 +++++++ .../{challenge.rs => challenge/mod.rs} | 69 +----- crates/common/src/protocol/challenge/tests.rs | 66 ++++++ .../protocol/{step_up.rs => step_up/mod.rs} | 97 +------- crates/common/src/protocol/step_up/tests.rs | 94 ++++++++ .../crypto/src/{sealing.rs => sealing/mod.rs} | 50 +--- crates/crypto/src/sealing/tests.rs | 47 ++++ .../crypto/src/{signing.rs => signing/mod.rs} | 167 +------------ crates/crypto/src/signing/tests.rs | 164 +++++++++++++ .../{passkeys.rs => passkeys/mod.rs} | 51 +--- .../src/repositories/passkeys/tests.rs | 48 ++++ crates/telemetry/src/{http.rs => http/mod.rs} | 63 +---- crates/telemetry/src/http/tests.rs | 60 +++++ crates/ui/src/{login.rs => login/mod.rs} | 39 +-- crates/ui/src/login/tests.rs | 36 +++ .../ui/src/{recovery.rs => recovery/mod.rs} | 84 +------ crates/ui/src/recovery/tests.rs | 81 +++++++ 28 files changed, 1265 insertions(+), 1283 deletions(-) rename apps/auth-service/src/admin/{overview.rs => overview/mod.rs} (78%) create mode 100644 apps/auth-service/src/admin/overview/tests.rs rename apps/auth-service/src/admin/{types.rs => types/mod.rs} (76%) create mode 100644 apps/auth-service/src/admin/types/tests.rs rename apps/auth-service/src/deletion/{export.rs => export/mod.rs} (56%) create mode 100644 apps/auth-service/src/deletion/export/tests.rs rename apps/auth-service/src/{jobs.rs => jobs/mod.rs} (71%) create mode 100644 apps/auth-service/src/jobs/tests.rs rename apps/web/src/{site.rs => site/mod.rs} (73%) create mode 100644 apps/web/src/site/tests.rs rename crates/common/src/{email.rs => email/mod.rs} (70%) create mode 100644 crates/common/src/email/tests.rs rename crates/common/src/protocol/{challenge.rs => challenge/mod.rs} (86%) create mode 100644 crates/common/src/protocol/challenge/tests.rs rename crates/common/src/protocol/{step_up.rs => step_up/mod.rs} (54%) create mode 100644 crates/common/src/protocol/step_up/tests.rs rename crates/crypto/src/{sealing.rs => sealing/mod.rs} (61%) create mode 100644 crates/crypto/src/sealing/tests.rs rename crates/crypto/src/{signing.rs => signing/mod.rs} (66%) create mode 100644 crates/crypto/src/signing/tests.rs rename crates/database/src/repositories/{passkeys.rs => passkeys/mod.rs} (87%) create mode 100644 crates/database/src/repositories/passkeys/tests.rs rename crates/telemetry/src/{http.rs => http/mod.rs} (75%) create mode 100644 crates/telemetry/src/http/tests.rs rename crates/ui/src/{login.rs => login/mod.rs} (94%) create mode 100644 crates/ui/src/login/tests.rs rename crates/ui/src/{recovery.rs => recovery/mod.rs} (85%) create mode 100644 crates/ui/src/recovery/tests.rs diff --git a/apps/auth-service/src/admin/overview.rs b/apps/auth-service/src/admin/overview/mod.rs similarity index 78% rename from apps/auth-service/src/admin/overview.rs rename to apps/auth-service/src/admin/overview/mod.rs index 852420b94..10e7e6f7c 100644 --- a/apps/auth-service/src/admin/overview.rs +++ b/apps/auth-service/src/admin/overview/mod.rs @@ -154,44 +154,4 @@ impl AdminService { } #[cfg(test)] -mod tests { - //! The overview's arithmetic. - use super::*; - use piquel_common::{ - AuthenticationMethod, SessionId, - events::{DomainEvent, SignInFailure}, - }; - - /// The kinds counted are the tags the events are stored under. - #[test] - fn the_counted_kinds_are_the_stored_tags() { - let failed = DomainEvent::SignInFailed { - method: AuthenticationMethod::Passkey, - reason: SignInFailure::InvalidCredential, - }; - assert_eq!(failed.kind(), Kinds::FAILED); - let signed_in = DomainEvent::SignedIn { - session_id: SessionId::new(), - method: AuthenticationMethod::Passkey, - inline: None, - }; - assert_eq!(signed_in.kind(), Kinds::SIGNED_IN); - let grant = DomainEvent::GrantIssued { - client_id: "notes".parse().expect("client ID"), - family_id: None, - scopes: Vec::new(), - }; - assert_eq!(grant.kind(), Kinds::GRANT); - } - - /// A spike needs both a floor and a multiple of usual: a quiet week's first - /// failures are no alarm, and a busy service's usual failures are none either. - #[test] - fn a_spike_is_at_least_ten_and_over_three_times_usual() { - assert!(!Rate::new(9, 0).spikes()); - assert!(Rate::new(10, 0).spikes()); - assert!(!Rate::new(30, HOURS_PER_WEEK * 10).spikes()); - assert!(Rate::new(31, HOURS_PER_WEEK * 10).spikes()); - assert_eq!(Rate::new(0, 1).usual, 1, "a week's one failure rounds up"); - } -} +mod tests; diff --git a/apps/auth-service/src/admin/overview/tests.rs b/apps/auth-service/src/admin/overview/tests.rs new file mode 100644 index 000000000..1ab50898d --- /dev/null +++ b/apps/auth-service/src/admin/overview/tests.rs @@ -0,0 +1,39 @@ +//! The overview's arithmetic. +use super::*; +use piquel_common::{ + AuthenticationMethod, SessionId, + events::{DomainEvent, SignInFailure}, +}; + +/// The kinds counted are the tags the events are stored under. +#[test] +fn the_counted_kinds_are_the_stored_tags() { + let failed = DomainEvent::SignInFailed { + method: AuthenticationMethod::Passkey, + reason: SignInFailure::InvalidCredential, + }; + assert_eq!(failed.kind(), Kinds::FAILED); + let signed_in = DomainEvent::SignedIn { + session_id: SessionId::new(), + method: AuthenticationMethod::Passkey, + inline: None, + }; + assert_eq!(signed_in.kind(), Kinds::SIGNED_IN); + let grant = DomainEvent::GrantIssued { + client_id: "notes".parse().expect("client ID"), + family_id: None, + scopes: Vec::new(), + }; + assert_eq!(grant.kind(), Kinds::GRANT); +} + +/// A spike needs both a floor and a multiple of usual: a quiet week's first +/// failures are no alarm, and a busy service's usual failures are none either. +#[test] +fn a_spike_is_at_least_ten_and_over_three_times_usual() { + assert!(!Rate::new(9, 0).spikes()); + assert!(Rate::new(10, 0).spikes()); + assert!(!Rate::new(30, HOURS_PER_WEEK * 10).spikes()); + assert!(Rate::new(31, HOURS_PER_WEEK * 10).spikes()); + assert_eq!(Rate::new(0, 1).usual, 1, "a week's one failure rounds up"); +} diff --git a/apps/auth-service/src/admin/types.rs b/apps/auth-service/src/admin/types/mod.rs similarity index 76% rename from apps/auth-service/src/admin/types.rs rename to apps/auth-service/src/admin/types/mod.rs index 06335d631..ecdc097d8 100644 --- a/apps/auth-service/src/admin/types.rs +++ b/apps/auth-service/src/admin/types/mod.rs @@ -226,67 +226,4 @@ impl fmt::Display for UserRef { } #[cfg(test)] -mod tests { - //! Invitation lifetime parsing and reason bounds. - use super::*; - - /// Lifetimes accept a bounded number of minutes, hours or days and reject - /// malformed input, naming their bounds. - #[test] - fn lifetimes_accept_bounded_minutes_hours_and_days() { - for (value, duration) in [("24h", Duration::hours(24)), ("365d", Duration::days(365))] { - assert_eq!( - value - .parse::() - .map(InviteExpiry::duration) - .ok(), - Some(duration) - ); - } - for invalid in ["", "0", "d", "0d", "366d", "-1h", "7w", "7 d", "é"] { - assert!(invalid.parse::().is_err(), "{invalid}"); - } - for (value, duration) in [("0", Duration::zero()), ("90m", Duration::minutes(90))] { - assert_eq!( - value.parse::().map(GracePeriod::duration).ok(), - Some(duration) - ); - } - assert_eq!( - "31d" - .parse::() - .expect_err("too long") - .to_string(), - "must be a whole number followed by m, h or d, from 0 to 30d, e.g. 24h" - ); - } - - /// Each choice of the rotation form is the grace period it is written as. - #[test] - fn rotation_choices_are_the_periods_they_name() { - for grace in Grace::ALL { - assert_eq!( - Ok(GracePeriod::from(grace)), - grace - .as_str() - .parse::() - .map_err(|error| error.to_string()), - "{grace}" - ); - } - } - - /// Reasons count Unicode characters and reject blank or control input. - #[test] - fn reasons_are_bounded_visible_text() { - for valid in ["Spam".to_owned(), "é".repeat(500)] { - assert!(Reason::parse(valid).is_ok()); - } - for invalid in [String::new(), " \t ".into(), "a\nb".into(), "é".repeat(501)] { - assert!(matches!( - Reason::parse(invalid), - Err(AdminError::InvalidReason) - )); - } - } -} +mod tests; diff --git a/apps/auth-service/src/admin/types/tests.rs b/apps/auth-service/src/admin/types/tests.rs new file mode 100644 index 000000000..7d09878c9 --- /dev/null +++ b/apps/auth-service/src/admin/types/tests.rs @@ -0,0 +1,62 @@ +//! Invitation lifetime parsing and reason bounds. +use super::*; + +/// Lifetimes accept a bounded number of minutes, hours or days and reject +/// malformed input, naming their bounds. +#[test] +fn lifetimes_accept_bounded_minutes_hours_and_days() { + for (value, duration) in [("24h", Duration::hours(24)), ("365d", Duration::days(365))] { + assert_eq!( + value + .parse::() + .map(InviteExpiry::duration) + .ok(), + Some(duration) + ); + } + for invalid in ["", "0", "d", "0d", "366d", "-1h", "7w", "7 d", "é"] { + assert!(invalid.parse::().is_err(), "{invalid}"); + } + for (value, duration) in [("0", Duration::zero()), ("90m", Duration::minutes(90))] { + assert_eq!( + value.parse::().map(GracePeriod::duration).ok(), + Some(duration) + ); + } + assert_eq!( + "31d" + .parse::() + .expect_err("too long") + .to_string(), + "must be a whole number followed by m, h or d, from 0 to 30d, e.g. 24h" + ); +} + +/// Each choice of the rotation form is the grace period it is written as. +#[test] +fn rotation_choices_are_the_periods_they_name() { + for grace in Grace::ALL { + assert_eq!( + Ok(GracePeriod::from(grace)), + grace + .as_str() + .parse::() + .map_err(|error| error.to_string()), + "{grace}" + ); + } +} + +/// Reasons count Unicode characters and reject blank or control input. +#[test] +fn reasons_are_bounded_visible_text() { + for valid in ["Spam".to_owned(), "é".repeat(500)] { + assert!(Reason::parse(valid).is_ok()); + } + for invalid in [String::new(), " \t ".into(), "a\nb".into(), "é".repeat(501)] { + assert!(matches!( + Reason::parse(invalid), + Err(AdminError::InvalidReason) + )); + } +} diff --git a/apps/auth-service/src/deletion/export.rs b/apps/auth-service/src/deletion/export/mod.rs similarity index 56% rename from apps/auth-service/src/deletion/export.rs rename to apps/auth-service/src/deletion/export/mod.rs index 7ffcf3ed7..2dbb8246d 100644 --- a/apps/auth-service/src/deletion/export.rs +++ b/apps/auth-service/src/deletion/export/mod.rs @@ -311,224 +311,4 @@ impl AccountExport { } #[cfg(test)] -mod tests { - //! The export's JSON shape, which downloads keep across releases. - use super::*; - use crate::history::{ClientView, HistoryItem}; - use chrono::TimeZone; - use piquel_common::{ - AuthenticationMethod, ClientId, EmailId, EventId, TokenId, - events::{Browser, HistoryActor, HistoryEntry, Platform, UserAgentFamily}, - }; - use piquel_repository::{RecoveryPasskey, StoredSession}; - use serde_json::json; - - /// Every category serializes under its documented name and shape. - #[test] - #[expect( - clippy::too_many_lines, - reason = "One literal per category of the document." - )] - fn serializes_every_category_in_its_documented_shape() { - let at = Utc - .with_ymd_and_hms(2026, 10, 22, 9, 30, 0) - .single() - .expect("time"); - let user = UserId::new(); - let passkey = PasskeyId::new(); - let email = EmailId::new(); - let recovery = RecoveryId::new(); - let session = SessionId::new(); - let grant = TokenId::new(); - let event = EventId::new(); - let client: ClientId = "notes".parse().expect("client"); - let device = UserAgentFamily { - browser: Browser::Firefox, - platform: Platform::Linux, - }; - let export = AccountExport { - format: FORMAT, - version: VERSION, - exported_at: at, - profile: Profile { - id: user, - handle: "ada".parse().expect("handle"), - display_name: "Ada".into(), - status: AccountStatus::Active, - created_at: at, - updated_at: at, - }, - handles: vec![HandleHeld::from(StoredHandle { - handle: "ada".parse().expect("handle"), - user_id: Some(user), - claimed_at: at, - released_at: None, - })], - administrator: true, - dashboard_sessions: vec![DashboardSession::from(DashboardSignIn { - session_id: session, - created_at: at, - confirmed_at: Some(at), - })], - emails: vec![EmailView { - id: email, - address: "ada@example.com".into(), - verified: true, - primary: true, - }], - passkeys: vec![Passkey { - id: passkey, - friendly_name: "Laptop".into(), - created_at: at, - last_used_at: None, - backup_eligible: Some(true), - backed_up: Some(false), - }], - identities: vec![Identity { - provider: Provider::GitHub, - subject: "1234".into(), - linked_email: Some("ada@example.com".into()), - }], - sessions: vec![SessionItem::new( - StoredSession { - id: session, - user_id: user, - authentication_methods: vec![AuthenticationMethod::Passkey], - authenticated_at: at, - expires_at: at, - last_seen_at: at, - revoked_at: None, - passkey_confirmed_at: Some(at), - user_agent_family: Some(device), - last_seen_ip: Some([192, 0, 2, 1].into()), - }, - Some(session), - )], - consents: vec![Consent { - client_id: client.to_string(), - audience: "notes".into(), - scopes: vec!["openid".into()], - }], - grants: vec![StoredGrant { - id: grant, - client_id: client.clone(), - audience: "notes".into(), - scopes: vec!["openid".into(), "offline_access".into()], - created_at: at, - revoked_at: None, - }], - clients: Vec::new(), - recoveries: vec![Recovery::from(RecentRecovery { - id: recovery, - started_at: at, - expires_at: at, - completed_at: Some(at), - cancelled_at: None, - undone_at: None, - state: RecoveryState::Probation { settles_at: at }, - passkey: Some(RecoveryPasskey { - id: passkey, - friendly_name: Some("Laptop".into()), - active: true, - }), - })], - history: vec![HistoryItem { - id: event, - occurred_at: at, - entry: HistoryEntry::SignedIn { - method: AuthenticationMethod::Passkey, - origin: None, - }, - actor: HistoryActor::Account, - reason: None, - client: Some(ClientView { - id: client, - name: Some("Notes".into()), - }), - ip: Some([192, 0, 2, 1].into()), - device: Some(device), - erased: false, - }], - }; - assert_eq!(export.file_name(), "piquel-account-ada-2026-10-22.json"); - let time = "2026-10-22T09:30:00Z"; - assert_eq!( - serde_json::to_value(&export).expect("export"), - json!({ - "format": "piquel.account-export", - "version": 1, - "exported_at": time, - "profile": { - "id": user, - "handle": "ada", - "display_name": "Ada", - "status": "active", - "created_at": time, - "updated_at": time, - }, - "handles": [{"handle": "ada", "claimed_at": time, "released_at": null}], - "administrator": true, - "dashboard_sessions": [ - {"session_id": session, "created_at": time, "confirmed_at": time} - ], - "emails": [{"id": email, "address": "ada@example.com", "verified": true, "primary": true}], - "passkeys": [{ - "id": passkey, - "friendly_name": "Laptop", - "created_at": time, - "last_used_at": null, - "backup_eligible": true, - "backed_up": false, - }], - "identities": [{ - "provider": "github", - "subject": "1234", - "linked_email": "ada@example.com", - }], - "sessions": [{ - "id": session, - "current": true, - "device": {"browser": "firefox", "platform": "linux"}, - "ip": "192.0.2.1", - "methods": ["passkey"], - "authenticated_at": time, - "last_seen_at": time, - "expires_at": time, - }], - "consents": [{"client_id": "notes", "audience": "notes", "scopes": ["openid"]}], - "grants": [{ - "id": grant, - "client_id": "notes", - "audience": "notes", - "scopes": ["openid", "offline_access"], - "created_at": time, - "revoked_at": null, - }], - "clients": [], - "recoveries": [{ - "id": recovery, - "started_at": time, - "expires_at": time, - "completed_at": time, - "passkey_id": passkey, - "cancelled_at": null, - "undone_at": null, - "state": "probation", - "settles_at": time, - }], - "history": [{ - "id": event, - "occurred_at": time, - "kind": "session.signed_in", - "method": "passkey", - "actor": "account", - "reason": null, - "client": {"id": "notes", "name": "Notes"}, - "ip": "192.0.2.1", - "device": {"browser": "firefox", "platform": "linux"}, - "erased": false, - }], - }) - ); - } -} +mod tests; diff --git a/apps/auth-service/src/deletion/export/tests.rs b/apps/auth-service/src/deletion/export/tests.rs new file mode 100644 index 000000000..89e31bd35 --- /dev/null +++ b/apps/auth-service/src/deletion/export/tests.rs @@ -0,0 +1,219 @@ +//! The export's JSON shape, which downloads keep across releases. +use super::*; +use crate::history::{ClientView, HistoryItem}; +use chrono::TimeZone; +use piquel_common::{ + AuthenticationMethod, ClientId, EmailId, EventId, TokenId, + events::{Browser, HistoryActor, HistoryEntry, Platform, UserAgentFamily}, +}; +use piquel_repository::{RecoveryPasskey, StoredSession}; +use serde_json::json; + +/// Every category serializes under its documented name and shape. +#[test] +#[expect( + clippy::too_many_lines, + reason = "One literal per category of the document." +)] +fn serializes_every_category_in_its_documented_shape() { + let at = Utc + .with_ymd_and_hms(2026, 10, 22, 9, 30, 0) + .single() + .expect("time"); + let user = UserId::new(); + let passkey = PasskeyId::new(); + let email = EmailId::new(); + let recovery = RecoveryId::new(); + let session = SessionId::new(); + let grant = TokenId::new(); + let event = EventId::new(); + let client: ClientId = "notes".parse().expect("client"); + let device = UserAgentFamily { + browser: Browser::Firefox, + platform: Platform::Linux, + }; + let export = AccountExport { + format: FORMAT, + version: VERSION, + exported_at: at, + profile: Profile { + id: user, + handle: "ada".parse().expect("handle"), + display_name: "Ada".into(), + status: AccountStatus::Active, + created_at: at, + updated_at: at, + }, + handles: vec![HandleHeld::from(StoredHandle { + handle: "ada".parse().expect("handle"), + user_id: Some(user), + claimed_at: at, + released_at: None, + })], + administrator: true, + dashboard_sessions: vec![DashboardSession::from(DashboardSignIn { + session_id: session, + created_at: at, + confirmed_at: Some(at), + })], + emails: vec![EmailView { + id: email, + address: "ada@example.com".into(), + verified: true, + primary: true, + }], + passkeys: vec![Passkey { + id: passkey, + friendly_name: "Laptop".into(), + created_at: at, + last_used_at: None, + backup_eligible: Some(true), + backed_up: Some(false), + }], + identities: vec![Identity { + provider: Provider::GitHub, + subject: "1234".into(), + linked_email: Some("ada@example.com".into()), + }], + sessions: vec![SessionItem::new( + StoredSession { + id: session, + user_id: user, + authentication_methods: vec![AuthenticationMethod::Passkey], + authenticated_at: at, + expires_at: at, + last_seen_at: at, + revoked_at: None, + passkey_confirmed_at: Some(at), + user_agent_family: Some(device), + last_seen_ip: Some([192, 0, 2, 1].into()), + }, + Some(session), + )], + consents: vec![Consent { + client_id: client.to_string(), + audience: "notes".into(), + scopes: vec!["openid".into()], + }], + grants: vec![StoredGrant { + id: grant, + client_id: client.clone(), + audience: "notes".into(), + scopes: vec!["openid".into(), "offline_access".into()], + created_at: at, + revoked_at: None, + }], + clients: Vec::new(), + recoveries: vec![Recovery::from(RecentRecovery { + id: recovery, + started_at: at, + expires_at: at, + completed_at: Some(at), + cancelled_at: None, + undone_at: None, + state: RecoveryState::Probation { settles_at: at }, + passkey: Some(RecoveryPasskey { + id: passkey, + friendly_name: Some("Laptop".into()), + active: true, + }), + })], + history: vec![HistoryItem { + id: event, + occurred_at: at, + entry: HistoryEntry::SignedIn { + method: AuthenticationMethod::Passkey, + origin: None, + }, + actor: HistoryActor::Account, + reason: None, + client: Some(ClientView { + id: client, + name: Some("Notes".into()), + }), + ip: Some([192, 0, 2, 1].into()), + device: Some(device), + erased: false, + }], + }; + assert_eq!(export.file_name(), "piquel-account-ada-2026-10-22.json"); + let time = "2026-10-22T09:30:00Z"; + assert_eq!( + serde_json::to_value(&export).expect("export"), + json!({ + "format": "piquel.account-export", + "version": 1, + "exported_at": time, + "profile": { + "id": user, + "handle": "ada", + "display_name": "Ada", + "status": "active", + "created_at": time, + "updated_at": time, + }, + "handles": [{"handle": "ada", "claimed_at": time, "released_at": null}], + "administrator": true, + "dashboard_sessions": [ + {"session_id": session, "created_at": time, "confirmed_at": time} + ], + "emails": [{"id": email, "address": "ada@example.com", "verified": true, "primary": true}], + "passkeys": [{ + "id": passkey, + "friendly_name": "Laptop", + "created_at": time, + "last_used_at": null, + "backup_eligible": true, + "backed_up": false, + }], + "identities": [{ + "provider": "github", + "subject": "1234", + "linked_email": "ada@example.com", + }], + "sessions": [{ + "id": session, + "current": true, + "device": {"browser": "firefox", "platform": "linux"}, + "ip": "192.0.2.1", + "methods": ["passkey"], + "authenticated_at": time, + "last_seen_at": time, + "expires_at": time, + }], + "consents": [{"client_id": "notes", "audience": "notes", "scopes": ["openid"]}], + "grants": [{ + "id": grant, + "client_id": "notes", + "audience": "notes", + "scopes": ["openid", "offline_access"], + "created_at": time, + "revoked_at": null, + }], + "clients": [], + "recoveries": [{ + "id": recovery, + "started_at": time, + "expires_at": time, + "completed_at": time, + "passkey_id": passkey, + "cancelled_at": null, + "undone_at": null, + "state": "probation", + "settles_at": time, + }], + "history": [{ + "id": event, + "occurred_at": time, + "kind": "session.signed_in", + "method": "passkey", + "actor": "account", + "reason": null, + "client": {"id": "notes", "name": "Notes"}, + "ip": "192.0.2.1", + "device": {"browser": "firefox", "platform": "linux"}, + "erased": false, + }], + }) + ); +} diff --git a/apps/auth-service/src/jobs.rs b/apps/auth-service/src/jobs/mod.rs similarity index 71% rename from apps/auth-service/src/jobs.rs rename to apps/auth-service/src/jobs/mod.rs index a77ed5485..13df81005 100644 --- a/apps/auth-service/src/jobs.rs +++ b/apps/auth-service/src/jobs/mod.rs @@ -424,202 +424,4 @@ impl ExclusiveJob for AccountPurge { } #[cfg(test)] -mod tests { - //! Job runner failure isolation and exclusivity across runners. - use super::*; - use piquel_repository::DatabaseConfig; - use std::sync::{ - Mutex, - atomic::{AtomicU32, Ordering}, - }; - - /// Connects to the disposable database the `#[ignore]`d tests run against. - async fn database() -> Database { - let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") - .required() - .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); - Database::connect( - DatabaseConfig::new(&url, 2, Duration::from_secs(5)).expect("database configuration"), - ) - .await - .expect("database") - } - - /// Panics on its first run and counts every run. - struct PanicsOnce(Arc); - - impl ExclusiveJob for PanicsOnce { - const NAME: &'static str = "panics-once"; - const LOCK: LockKey = LockKey::Test; - const EVERY: Duration = Duration::from_millis(20); - type Error = DatabaseError; - - fn run( - &self, - _: &mut ExclusiveConnection, - _: &Shutdown, - ) -> impl Future> + Send { - assert_ne!(self.0.fetch_add(1, Ordering::SeqCst), 0, "first run panics"); - std::future::ready(Ok(())) - } - } - - /// A run that panics ends only that run: its lock is freed, the job runs again, - /// and shutdown reports nothing because the job's loop survived. - #[tokio::test] - #[ignore = "requires TEST_DATABASE_URL"] - async fn a_panicking_run_releases_its_lock_and_the_job_runs_again() { - let runs = Arc::new(AtomicU32::new(0)); - let mut jobs = Jobs::new(); - jobs.exclusive(PanicsOnce(Arc::clone(&runs)), database().await); - tokio::time::timeout(Duration::from_secs(5), async { - while runs.load(Ordering::SeqCst) < 2 { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("the job runs again after panicking"); - jobs.shutdown().await.expect("no job loop panicked"); - } - - /// A run of [`Held`] by the runner it names starting, finishing or being - /// cancelled. - #[derive(Clone, Debug)] - enum Event { - Started(usize), - Finished(usize), - Cancelled(usize), - } - - /// Every [`Event`] of the runners sharing it, in order. - #[derive(Default)] - struct Log(Mutex>); - - impl Log { - fn push(&self, event: Event) { - self.0.lock().expect("log").push(event); - } - - fn events(&self) -> Vec { - self.0.lock().expect("log").clone() - } - - /// Waits until `found` returns something for the events so far. - async fn wait_for(&self, found: impl Fn(&[Event]) -> Option) -> T { - tokio::time::timeout(Duration::from_secs(5), async { - loop { - if let Some(found) = found(&self.0.lock().expect("log")) { - break found; - } - tokio::time::sleep(Duration::from_millis(5)).await; - } - }) - .await - .unwrap_or_else(|_| panic!("the awaited events never happened: {:?}", self.events())) - } - } - - /// Holds its lock for [`Self::HOLD`], several periods, logging when each run - /// of `runner` starts and how it ends. - struct Held { - runner: usize, - log: Arc, - } - - impl Held { - const HOLD: Duration = Duration::from_millis(100); - } - - /// Logs how a [`Held`] run ended when dropped, so a cancelled run is logged - /// too. The run drops it before its connection, so before the lock is freed. - struct Running<'a> { - job: &'a Held, - finished: bool, - } - - impl Drop for Running<'_> { - fn drop(&mut self) { - let runner = self.job.runner; - self.job.log.push(if self.finished { - Event::Finished(runner) - } else { - Event::Cancelled(runner) - }); - } - } - - impl ExclusiveJob for Held { - const NAME: &'static str = "held"; - const LOCK: LockKey = LockKey::ExclusivityTest; - const EVERY: Duration = Duration::from_millis(20); - type Error = DatabaseError; - - async fn run( - &self, - _: &mut ExclusiveConnection, - _: &Shutdown, - ) -> Result<(), DatabaseError> { - self.log.push(Event::Started(self.runner)); - let mut running = Running { - job: self, - finished: false, - }; - tokio::time::sleep(Self::HOLD).await; - running.finished = true; - Ok(()) - } - } - - /// Two runners, as two replicas, never run the same exclusive job at once, - /// and dropping the one mid-run cancels its run, freeing the lock for the - /// other's next tick. - #[tokio::test] - #[ignore = "requires TEST_DATABASE_URL"] - async fn runners_never_overlap_and_a_dropped_holder_hands_over() { - let database = database().await; - let log = Arc::new(Log::default()); - let mut runners = [0, 1].map(|runner| { - let mut jobs = Jobs::new(); - let log = Arc::clone(&log); - jobs.exclusive(Held { runner, log }, database.clone()); - Some(jobs) - }); - // A few runs in, cancel whichever runner is mid-run. - let holder = log - .wait_for(|events| match events { - [.., Event::Started(holder)] if events.len() > 6 => Some(*holder), - _ => None, - }) - .await; - drop(runners[holder].take()); - let other = 1 - holder; - log.wait_for(|events| { - events - .windows(2) - .any(|pair| { - matches!( - pair, - [Event::Cancelled(cancelled), Event::Started(started)] - if *cancelled == holder && *started == other - ) - }) - .then_some(()) - }) - .await; - runners[other] - .take() - .expect("the other runner") - .shutdown() - .await - .expect("no job loop panicked"); - let events = log.events(); - assert!( - events.chunks(2).all(|run| matches!( - run, - [Event::Started(started), Event::Finished(ended) | Event::Cancelled(ended)] - if started == ended - )), - "runs overlapped: {events:?}" - ); - } -} +mod tests; diff --git a/apps/auth-service/src/jobs/tests.rs b/apps/auth-service/src/jobs/tests.rs new file mode 100644 index 000000000..88848c812 --- /dev/null +++ b/apps/auth-service/src/jobs/tests.rs @@ -0,0 +1,193 @@ +//! Job runner failure isolation and exclusivity across runners. +use super::*; +use piquel_repository::DatabaseConfig; +use std::sync::{ + Mutex, + atomic::{AtomicU32, Ordering}, +}; + +/// Connects to the disposable database the `#[ignore]`d tests run against. +async fn database() -> Database { + let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") + .required() + .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); + Database::connect( + DatabaseConfig::new(&url, 2, Duration::from_secs(5)).expect("database configuration"), + ) + .await + .expect("database") +} + +/// Panics on its first run and counts every run. +struct PanicsOnce(Arc); + +impl ExclusiveJob for PanicsOnce { + const NAME: &'static str = "panics-once"; + const LOCK: LockKey = LockKey::Test; + const EVERY: Duration = Duration::from_millis(20); + type Error = DatabaseError; + + fn run( + &self, + _: &mut ExclusiveConnection, + _: &Shutdown, + ) -> impl Future> + Send { + assert_ne!(self.0.fetch_add(1, Ordering::SeqCst), 0, "first run panics"); + std::future::ready(Ok(())) + } +} + +/// A run that panics ends only that run: its lock is freed, the job runs again, +/// and shutdown reports nothing because the job's loop survived. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_panicking_run_releases_its_lock_and_the_job_runs_again() { + let runs = Arc::new(AtomicU32::new(0)); + let mut jobs = Jobs::new(); + jobs.exclusive(PanicsOnce(Arc::clone(&runs)), database().await); + tokio::time::timeout(Duration::from_secs(5), async { + while runs.load(Ordering::SeqCst) < 2 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the job runs again after panicking"); + jobs.shutdown().await.expect("no job loop panicked"); +} + +/// A run of [`Held`] by the runner it names starting, finishing or being +/// cancelled. +#[derive(Clone, Debug)] +enum Event { + Started(usize), + Finished(usize), + Cancelled(usize), +} + +/// Every [`Event`] of the runners sharing it, in order. +#[derive(Default)] +struct Log(Mutex>); + +impl Log { + fn push(&self, event: Event) { + self.0.lock().expect("log").push(event); + } + + fn events(&self) -> Vec { + self.0.lock().expect("log").clone() + } + + /// Waits until `found` returns something for the events so far. + async fn wait_for(&self, found: impl Fn(&[Event]) -> Option) -> T { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(found) = found(&self.0.lock().expect("log")) { + break found; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("the awaited events never happened: {:?}", self.events())) + } +} + +/// Holds its lock for [`Self::HOLD`], several periods, logging when each run +/// of `runner` starts and how it ends. +struct Held { + runner: usize, + log: Arc, +} + +impl Held { + const HOLD: Duration = Duration::from_millis(100); +} + +/// Logs how a [`Held`] run ended when dropped, so a cancelled run is logged +/// too. The run drops it before its connection, so before the lock is freed. +struct Running<'a> { + job: &'a Held, + finished: bool, +} + +impl Drop for Running<'_> { + fn drop(&mut self) { + let runner = self.job.runner; + self.job.log.push(if self.finished { + Event::Finished(runner) + } else { + Event::Cancelled(runner) + }); + } +} + +impl ExclusiveJob for Held { + const NAME: &'static str = "held"; + const LOCK: LockKey = LockKey::ExclusivityTest; + const EVERY: Duration = Duration::from_millis(20); + type Error = DatabaseError; + + async fn run(&self, _: &mut ExclusiveConnection, _: &Shutdown) -> Result<(), DatabaseError> { + self.log.push(Event::Started(self.runner)); + let mut running = Running { + job: self, + finished: false, + }; + tokio::time::sleep(Self::HOLD).await; + running.finished = true; + Ok(()) + } +} + +/// Two runners, as two replicas, never run the same exclusive job at once, +/// and dropping the one mid-run cancels its run, freeing the lock for the +/// other's next tick. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn runners_never_overlap_and_a_dropped_holder_hands_over() { + let database = database().await; + let log = Arc::new(Log::default()); + let mut runners = [0, 1].map(|runner| { + let mut jobs = Jobs::new(); + let log = Arc::clone(&log); + jobs.exclusive(Held { runner, log }, database.clone()); + Some(jobs) + }); + // A few runs in, cancel whichever runner is mid-run. + let holder = log + .wait_for(|events| match events { + [.., Event::Started(holder)] if events.len() > 6 => Some(*holder), + _ => None, + }) + .await; + drop(runners[holder].take()); + let other = 1 - holder; + log.wait_for(|events| { + events + .windows(2) + .any(|pair| { + matches!( + pair, + [Event::Cancelled(cancelled), Event::Started(started)] + if *cancelled == holder && *started == other + ) + }) + .then_some(()) + }) + .await; + runners[other] + .take() + .expect("the other runner") + .shutdown() + .await + .expect("no job loop panicked"); + let events = log.events(); + assert!( + events.chunks(2).all(|run| matches!( + run, + [Event::Started(started), Event::Finished(ended) | Event::Cancelled(ended)] + if started == ended + )), + "runs overlapped: {events:?}" + ); +} diff --git a/apps/web/src/site.rs b/apps/web/src/site/mod.rs similarity index 73% rename from apps/web/src/site.rs rename to apps/web/src/site/mod.rs index b48903915..1d70b3924 100644 --- a/apps/web/src/site.rs +++ b/apps/web/src/site/mod.rs @@ -175,64 +175,4 @@ impl Site { } #[cfg(test)] -mod tests { - //! The site as a browser sees it. - use super::*; - use axum::body::{Body, to_bytes}; - use tower::ServiceExt; - - /// Auth's origin in tests. - const AUTH: &str = "https://auth.piquel.fr"; - - /// `path`'s answer. - async fn visit(path: &str) -> Response { - Site::new(AUTH.parse().expect("auth origin")) - .router() - .oneshot( - axum::http::Request::get(path) - .body(Body::empty()) - .expect("request"), - ) - .await - .expect("answer") - } - - /// The homepage and the policies are indexable pages that load nothing but the - /// stylesheet, and whose footer links the policies here. - #[tokio::test] - async fn serves_its_pages() { - for (page, heading) in [ - (Page::Home, "One passkey for every Piquel app."), - (Page::Privacy, "Privacy policy"), - (Page::Terms, "Terms of service"), - ] { - let response = visit(page.path()).await; - assert_eq!(response.status(), StatusCode::OK, "{page:?}"); - assert_eq!(response.headers()[header::CONTENT_SECURITY_POLICY], POLICY); - assert_eq!(response.headers()[header::X_FRAME_OPTIONS], "DENY"); - let body = to_bytes(response.into_body(), 1 << 20).await.expect("body"); - let html = String::from_utf8(body.to_vec()).expect("UTF-8"); - assert!(html.contains(heading), "{page:?}"); - assert!(!html.contains("noindex"), "{page:?}"); - assert!(html.contains(r#"href="/privacy""#), "{page:?}"); - assert!(html.contains(&STYLESHEET.path()), "{page:?}"); - } - for asset in ASSETS { - let served = visit(&asset.path()).await; - assert_eq!(served.status(), StatusCode::OK, "{}", asset.path()); - } - } - - /// Every other path, a sent settings link's included, goes on to auth with its - /// query, and nobody caches that. - #[tokio::test] - async fn sends_every_other_path_to_auth() { - let response = visit("/settings/emails/verify?remove=1").await; - assert_eq!(response.status(), StatusCode::TEMPORARY_REDIRECT); - assert_eq!( - response.headers()[header::LOCATION], - "https://auth.piquel.fr/settings/emails/verify?remove=1" - ); - assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store"); - } -} +mod tests; diff --git a/apps/web/src/site/tests.rs b/apps/web/src/site/tests.rs new file mode 100644 index 000000000..ee89ed30e --- /dev/null +++ b/apps/web/src/site/tests.rs @@ -0,0 +1,59 @@ +//! The site as a browser sees it. +use super::*; +use axum::body::{Body, to_bytes}; +use tower::ServiceExt; + +/// Auth's origin in tests. +const AUTH: &str = "https://auth.piquel.fr"; + +/// `path`'s answer. +async fn visit(path: &str) -> Response { + Site::new(AUTH.parse().expect("auth origin")) + .router() + .oneshot( + axum::http::Request::get(path) + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("answer") +} + +/// The homepage and the policies are indexable pages that load nothing but the +/// stylesheet, and whose footer links the policies here. +#[tokio::test] +async fn serves_its_pages() { + for (page, heading) in [ + (Page::Home, "One passkey for every Piquel app."), + (Page::Privacy, "Privacy policy"), + (Page::Terms, "Terms of service"), + ] { + let response = visit(page.path()).await; + assert_eq!(response.status(), StatusCode::OK, "{page:?}"); + assert_eq!(response.headers()[header::CONTENT_SECURITY_POLICY], POLICY); + assert_eq!(response.headers()[header::X_FRAME_OPTIONS], "DENY"); + let body = to_bytes(response.into_body(), 1 << 20).await.expect("body"); + let html = String::from_utf8(body.to_vec()).expect("UTF-8"); + assert!(html.contains(heading), "{page:?}"); + assert!(!html.contains("noindex"), "{page:?}"); + assert!(html.contains(r#"href="/privacy""#), "{page:?}"); + assert!(html.contains(&STYLESHEET.path()), "{page:?}"); + } + for asset in ASSETS { + let served = visit(&asset.path()).await; + assert_eq!(served.status(), StatusCode::OK, "{}", asset.path()); + } +} + +/// Every other path, a sent settings link's included, goes on to auth with its +/// query, and nobody caches that. +#[tokio::test] +async fn sends_every_other_path_to_auth() { + let response = visit("/settings/emails/verify?remove=1").await; + assert_eq!(response.status(), StatusCode::TEMPORARY_REDIRECT); + assert_eq!( + response.headers()[header::LOCATION], + "https://auth.piquel.fr/settings/emails/verify?remove=1" + ); + assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store"); +} diff --git a/crates/common/src/email.rs b/crates/common/src/email/mod.rs similarity index 70% rename from crates/common/src/email.rs rename to crates/common/src/email/mod.rs index 1378ca2f6..00bb3ded6 100644 --- a/crates/common/src/email.rs +++ b/crates/common/src/email/mod.rs @@ -183,88 +183,4 @@ impl fmt::Display for NormalizedEmail { } #[cfg(test)] -mod tests { - //! Focused coverage of the conservative equality and rejection policies. - use super::{InvalidEmail, NormalizedEmail}; - - /// Provider-specific dot and plus equivalence must never merge addresses. - #[test] - fn preserves_provider_specific_local_part_semantics() { - assert_eq!( - NormalizedEmail::parse("Ada+jobs@Example.COM") - .expect("valid email") - .as_str(), - "Ada+jobs@example.com" - ); - assert_ne!( - NormalizedEmail::parse("a.da@example.com"), - NormalizedEmail::parse("ada@example.com") - ); - } - - /// Case and plus tags of one mailbox fold together for sending limits only. - #[test] - fn mailbox_folds_case_and_plus_tags() { - let mailbox = |value| { - NormalizedEmail::parse(value) - .expect("valid email") - .mailbox() - }; - assert_eq!(mailbox("Ada+jobs@Example.COM"), "ada@example.com"); - assert_eq!(mailbox("ADA@example.com"), mailbox("ada+1@example.com")); - assert_ne!(mailbox("a.da@example.com"), mailbox("ada@example.com")); - } - - /// Ambiguous addresses fail with a useful policy reason. - #[test] - fn rejects_ambiguous_values() { - for (value, reason) in [ - ("", InvalidEmail::Empty), - ("not-an-email", InvalidEmail::MissingSeparator), - ("a@b@example.com", InvalidEmail::MultipleSeparators), - ("@example.com", InvalidEmail::EmptyLocalPart), - ("a..b@example.com", InvalidEmail::LocalPartDots), - ("a b@example.com", InvalidEmail::ForbiddenCharacter), - (" a@example.com", InvalidEmail::ForbiddenCharacter), - ("a@", InvalidEmail::EmptyDomain), - ( - "a@example..com", - InvalidEmail::EmptyDomainLabel("example..com".into()), - ), - ( - "a@-example.com", - InvalidEmail::DomainLabelHyphen("-example".into()), - ), - ( - "a@exa_mple.com", - InvalidEmail::DomainLabelCharacter("exa_mple".into()), - ), - ( - "a@localhost", - InvalidEmail::DomainWithoutSuffix("localhost".into()), - ), - ] { - assert_eq!(NormalizedEmail::parse(value), Err(reason)); - } - } - - /// Canonical Unicode composition and byte limits apply before storage. - #[test] - fn normalizes_unicode_and_enforces_component_limits() { - assert_eq!( - NormalizedEmail::parse("e\u{301}@EXAMPLE.COM") - .expect("email") - .as_str(), - "é@example.com" - ); - assert!(NormalizedEmail::parse(&format!("{}@example.com", "a".repeat(64))).is_ok()); - assert_eq!( - NormalizedEmail::parse(&format!("{}@example.com", "a".repeat(65))), - Err(InvalidEmail::LocalPartTooLong(65)) - ); - assert_eq!( - NormalizedEmail::parse(&format!("a@{}.com", "a".repeat(64))), - Err(InvalidEmail::DomainLabelTooLong("a".repeat(64))) - ); - } -} +mod tests; diff --git a/crates/common/src/email/tests.rs b/crates/common/src/email/tests.rs new file mode 100644 index 000000000..84788af69 --- /dev/null +++ b/crates/common/src/email/tests.rs @@ -0,0 +1,83 @@ +//! Focused coverage of the conservative equality and rejection policies. +use super::{InvalidEmail, NormalizedEmail}; + +/// Provider-specific dot and plus equivalence must never merge addresses. +#[test] +fn preserves_provider_specific_local_part_semantics() { + assert_eq!( + NormalizedEmail::parse("Ada+jobs@Example.COM") + .expect("valid email") + .as_str(), + "Ada+jobs@example.com" + ); + assert_ne!( + NormalizedEmail::parse("a.da@example.com"), + NormalizedEmail::parse("ada@example.com") + ); +} + +/// Case and plus tags of one mailbox fold together for sending limits only. +#[test] +fn mailbox_folds_case_and_plus_tags() { + let mailbox = |value| { + NormalizedEmail::parse(value) + .expect("valid email") + .mailbox() + }; + assert_eq!(mailbox("Ada+jobs@Example.COM"), "ada@example.com"); + assert_eq!(mailbox("ADA@example.com"), mailbox("ada+1@example.com")); + assert_ne!(mailbox("a.da@example.com"), mailbox("ada@example.com")); +} + +/// Ambiguous addresses fail with a useful policy reason. +#[test] +fn rejects_ambiguous_values() { + for (value, reason) in [ + ("", InvalidEmail::Empty), + ("not-an-email", InvalidEmail::MissingSeparator), + ("a@b@example.com", InvalidEmail::MultipleSeparators), + ("@example.com", InvalidEmail::EmptyLocalPart), + ("a..b@example.com", InvalidEmail::LocalPartDots), + ("a b@example.com", InvalidEmail::ForbiddenCharacter), + (" a@example.com", InvalidEmail::ForbiddenCharacter), + ("a@", InvalidEmail::EmptyDomain), + ( + "a@example..com", + InvalidEmail::EmptyDomainLabel("example..com".into()), + ), + ( + "a@-example.com", + InvalidEmail::DomainLabelHyphen("-example".into()), + ), + ( + "a@exa_mple.com", + InvalidEmail::DomainLabelCharacter("exa_mple".into()), + ), + ( + "a@localhost", + InvalidEmail::DomainWithoutSuffix("localhost".into()), + ), + ] { + assert_eq!(NormalizedEmail::parse(value), Err(reason)); + } +} + +/// Canonical Unicode composition and byte limits apply before storage. +#[test] +fn normalizes_unicode_and_enforces_component_limits() { + assert_eq!( + NormalizedEmail::parse("e\u{301}@EXAMPLE.COM") + .expect("email") + .as_str(), + "é@example.com" + ); + assert!(NormalizedEmail::parse(&format!("{}@example.com", "a".repeat(64))).is_ok()); + assert_eq!( + NormalizedEmail::parse(&format!("{}@example.com", "a".repeat(65))), + Err(InvalidEmail::LocalPartTooLong(65)) + ); + assert_eq!( + NormalizedEmail::parse(&format!("a@{}.com", "a".repeat(64))), + Err(InvalidEmail::DomainLabelTooLong("a".repeat(64))) + ); +} diff --git a/crates/common/src/protocol/challenge.rs b/crates/common/src/protocol/challenge/mod.rs similarity index 86% rename from crates/common/src/protocol/challenge.rs rename to crates/common/src/protocol/challenge/mod.rs index 14b8dc44c..afb382007 100644 --- a/crates/common/src/protocol/challenge.rs +++ b/crates/common/src/protocol/challenge/mod.rs @@ -443,71 +443,4 @@ impl<'a> Parser<'a> { } #[cfg(test)] -mod tests { - //! Challenge syntax at the parser's edges; the shared vectors cover the formats. - use super::*; - - /// Other schemes, `token68` credentials, escapes and unknown parameters do not hide - /// the Bearer challenge. - #[test] - fn finds_bearer_among_challenges() { - let challenge: BearerChallenge = - r#"Negotiate YWJjZA==, Basic realm="a, b", bearer error = invalid_token, error_description="say \'hi\'", foo=bar"# - .parse() - .expect("Bearer challenge"); - assert_eq!(challenge.error, Some(BearerError::InvalidToken)); - assert_eq!( - challenge - .error_description - .as_ref() - .map(ErrorDescription::as_str), - Some("say 'hi'") - ); - assert_eq!( - challenge.to_string(), - r#"Bearer error="invalid_token", error_description="say 'hi'""# - ); - } - - /// No value can break the header: control characters are written as `?`. - #[test] - fn formatting_never_emits_control_characters() { - let challenge = BearerChallenge::error(BearerError::from("new_error\r\nX-Test: yes")); - assert_eq!( - challenge.to_string(), - r#"Bearer error="new_error??X-Test: yes""# - ); - } - - /// Malformed, repeated or non-Bearer headers are rejected. - #[test] - fn rejects_invalid_headers() { - for (header, expected) in [ - ("Basic realm=\"x\"", ChallengeError::NotBearer), - ("Bearer error=\"unterminated", ChallengeError::Syntax(13)), - ("=x", ChallengeError::Syntax(0)), - ("Bearer error=\"a\"scope=\"b\"", ChallengeError::Syntax(16)), - ("Bearer error=\"a\r\nb\"", ChallengeError::Syntax(13)), - ("Negotiate abc==, error=x", ChallengeError::Syntax(17)), - ("Bearer,error=x", ChallengeError::Syntax(7)), - ( - "Bearer scope=\"a\tb\"", - ChallengeError::InvalidValue("scope"), - ), - ( - "Bearer scope=a, scope=b", - ChallengeError::Duplicate("scope".into()), - ), - ( - "Bearer max_age=soon", - ChallengeError::InvalidValue("max_age"), - ), - ( - "Bearer error_description=\"say \\\"hi\\\"\"", - ChallengeError::InvalidValue("error_description"), - ), - ] { - assert_eq!(header.parse::(), Err(expected), "{header}"); - } - } -} +mod tests; diff --git a/crates/common/src/protocol/challenge/tests.rs b/crates/common/src/protocol/challenge/tests.rs new file mode 100644 index 000000000..11028700f --- /dev/null +++ b/crates/common/src/protocol/challenge/tests.rs @@ -0,0 +1,66 @@ +//! Challenge syntax at the parser's edges; the shared vectors cover the formats. +use super::*; + +/// Other schemes, `token68` credentials, escapes and unknown parameters do not hide +/// the Bearer challenge. +#[test] +fn finds_bearer_among_challenges() { + let challenge: BearerChallenge = + r#"Negotiate YWJjZA==, Basic realm="a, b", bearer error = invalid_token, error_description="say \'hi\'", foo=bar"# + .parse() + .expect("Bearer challenge"); + assert_eq!(challenge.error, Some(BearerError::InvalidToken)); + assert_eq!( + challenge + .error_description + .as_ref() + .map(ErrorDescription::as_str), + Some("say 'hi'") + ); + assert_eq!( + challenge.to_string(), + r#"Bearer error="invalid_token", error_description="say 'hi'""# + ); +} + +/// No value can break the header: control characters are written as `?`. +#[test] +fn formatting_never_emits_control_characters() { + let challenge = BearerChallenge::error(BearerError::from("new_error\r\nX-Test: yes")); + assert_eq!( + challenge.to_string(), + r#"Bearer error="new_error??X-Test: yes""# + ); +} + +/// Malformed, repeated or non-Bearer headers are rejected. +#[test] +fn rejects_invalid_headers() { + for (header, expected) in [ + ("Basic realm=\"x\"", ChallengeError::NotBearer), + ("Bearer error=\"unterminated", ChallengeError::Syntax(13)), + ("=x", ChallengeError::Syntax(0)), + ("Bearer error=\"a\"scope=\"b\"", ChallengeError::Syntax(16)), + ("Bearer error=\"a\r\nb\"", ChallengeError::Syntax(13)), + ("Negotiate abc==, error=x", ChallengeError::Syntax(17)), + ("Bearer,error=x", ChallengeError::Syntax(7)), + ( + "Bearer scope=\"a\tb\"", + ChallengeError::InvalidValue("scope"), + ), + ( + "Bearer scope=a, scope=b", + ChallengeError::Duplicate("scope".into()), + ), + ( + "Bearer max_age=soon", + ChallengeError::InvalidValue("max_age"), + ), + ( + "Bearer error_description=\"say \\\"hi\\\"\"", + ChallengeError::InvalidValue("error_description"), + ), + ] { + assert_eq!(header.parse::(), Err(expected), "{header}"); + } +} diff --git a/crates/common/src/protocol/step_up.rs b/crates/common/src/protocol/step_up/mod.rs similarity index 54% rename from crates/common/src/protocol/step_up.rs rename to crates/common/src/protocol/step_up/mod.rs index d9036bd8d..4cc1794a7 100644 --- a/crates/common/src/protocol/step_up.rs +++ b/crates/common/src/protocol/step_up/mod.rs @@ -95,99 +95,4 @@ impl StepUpRequirement { } #[cfg(test)] -mod tests { - //! Requirement checks and the authorization parameters they produce. - use super::*; - - /// A passkey confirmation within five minutes, checked at a fixed `now`. - const RECENT_PASSKEY: StepUpRequirement = StepUpRequirement::passkey_within(300); - - /// The time `seconds` before a fixed `now`, and that `now`. - fn ago(seconds: i64) -> (Option>, DateTime) { - let now = DateTime::from_timestamp(1_800_000_000, 0).expect("timestamp"); - (Some(now - TimeDelta::seconds(seconds)), now) - } - - /// A social sign-in, or none at all, does not meet a `phr` requirement, however recent. - #[test] - fn weak_acr_fails() { - let (auth_time, now) = ago(10); - for acr in [Some(&Acr::Social), None] { - assert_eq!( - RECENT_PASSKEY.check(acr, auth_time, now), - Err(RECENT_PASSKEY) - ); - } - } - - /// An authentication older than `max_age`, even by part of a second, or with no - /// `auth_time`, fails. - #[test] - fn old_authentication_fails() { - let acr = Some(&Acr::PhishingResistant); - let (auth_time, now) = ago(300); - let late = now + TimeDelta::milliseconds(500); - assert_eq!( - RECENT_PASSKEY.check(acr, auth_time, late), - Err(RECENT_PASSKEY) - ); - let (auth_time, now) = ago(301); - assert_eq!( - RECENT_PASSKEY.check(acr, auth_time, now), - Err(RECENT_PASSKEY) - ); - assert_eq!(RECENT_PASSKEY.check(acr, None, now), Err(RECENT_PASSKEY)); - } - - /// A recent passkey meets both parts, up to `max_age` exactly, and `phr` meets a - /// social requirement too. - #[test] - fn strong_recent_authentication_passes() { - let acr = Some(&Acr::PhishingResistant); - for age in [0, 300] { - let (auth_time, now) = ago(age); - assert_eq!(RECENT_PASSKEY.check(acr, auth_time, now), Ok(())); - } - let social = StepUpRequirement { - acr: Some(Acr::Social), - max_age: None, - }; - assert_eq!(social.check(acr, None, ago(0).1), Ok(())); - assert_eq!( - StepUpRequirement::default().check(None, None, ago(0).1), - Ok(()) - ); - } - - /// `max_age=0` needs an authentication at `now` itself: it is a requirement, not - /// its absence. - #[test] - fn zero_max_age_needs_authentication_now() { - let now_only = StepUpRequirement { - acr: None, - max_age: Some(0), - }; - let (auth_time, now) = ago(0); - assert_eq!(now_only.check(None, auth_time, now), Ok(())); - let (auth_time, now) = ago(1); - assert_eq!(now_only.check(None, auth_time, now), Err(now_only)); - } - - /// Only the parts the requirement names become parameters. - #[test] - fn authorize_params_name_each_part() { - assert_eq!( - RECENT_PASSKEY.authorize_params().collect::>(), - [("acr_values", "phr".into()), ("max_age", "300".into())] - ); - let fresh = StepUpRequirement { - acr: None, - max_age: Some(0), - }; - assert_eq!( - fresh.authorize_params().collect::>(), - [("max_age", "0".into())] - ); - assert_eq!(StepUpRequirement::default().authorize_params().count(), 0); - } -} +mod tests; diff --git a/crates/common/src/protocol/step_up/tests.rs b/crates/common/src/protocol/step_up/tests.rs new file mode 100644 index 000000000..5d9fa57ae --- /dev/null +++ b/crates/common/src/protocol/step_up/tests.rs @@ -0,0 +1,94 @@ +//! Requirement checks and the authorization parameters they produce. +use super::*; + +/// A passkey confirmation within five minutes, checked at a fixed `now`. +const RECENT_PASSKEY: StepUpRequirement = StepUpRequirement::passkey_within(300); + +/// The time `seconds` before a fixed `now`, and that `now`. +fn ago(seconds: i64) -> (Option>, DateTime) { + let now = DateTime::from_timestamp(1_800_000_000, 0).expect("timestamp"); + (Some(now - TimeDelta::seconds(seconds)), now) +} + +/// A social sign-in, or none at all, does not meet a `phr` requirement, however recent. +#[test] +fn weak_acr_fails() { + let (auth_time, now) = ago(10); + for acr in [Some(&Acr::Social), None] { + assert_eq!( + RECENT_PASSKEY.check(acr, auth_time, now), + Err(RECENT_PASSKEY) + ); + } +} + +/// An authentication older than `max_age`, even by part of a second, or with no +/// `auth_time`, fails. +#[test] +fn old_authentication_fails() { + let acr = Some(&Acr::PhishingResistant); + let (auth_time, now) = ago(300); + let late = now + TimeDelta::milliseconds(500); + assert_eq!( + RECENT_PASSKEY.check(acr, auth_time, late), + Err(RECENT_PASSKEY) + ); + let (auth_time, now) = ago(301); + assert_eq!( + RECENT_PASSKEY.check(acr, auth_time, now), + Err(RECENT_PASSKEY) + ); + assert_eq!(RECENT_PASSKEY.check(acr, None, now), Err(RECENT_PASSKEY)); +} + +/// A recent passkey meets both parts, up to `max_age` exactly, and `phr` meets a +/// social requirement too. +#[test] +fn strong_recent_authentication_passes() { + let acr = Some(&Acr::PhishingResistant); + for age in [0, 300] { + let (auth_time, now) = ago(age); + assert_eq!(RECENT_PASSKEY.check(acr, auth_time, now), Ok(())); + } + let social = StepUpRequirement { + acr: Some(Acr::Social), + max_age: None, + }; + assert_eq!(social.check(acr, None, ago(0).1), Ok(())); + assert_eq!( + StepUpRequirement::default().check(None, None, ago(0).1), + Ok(()) + ); +} + +/// `max_age=0` needs an authentication at `now` itself: it is a requirement, not +/// its absence. +#[test] +fn zero_max_age_needs_authentication_now() { + let now_only = StepUpRequirement { + acr: None, + max_age: Some(0), + }; + let (auth_time, now) = ago(0); + assert_eq!(now_only.check(None, auth_time, now), Ok(())); + let (auth_time, now) = ago(1); + assert_eq!(now_only.check(None, auth_time, now), Err(now_only)); +} + +/// Only the parts the requirement names become parameters. +#[test] +fn authorize_params_name_each_part() { + assert_eq!( + RECENT_PASSKEY.authorize_params().collect::>(), + [("acr_values", "phr".into()), ("max_age", "300".into())] + ); + let fresh = StepUpRequirement { + acr: None, + max_age: Some(0), + }; + assert_eq!( + fresh.authorize_params().collect::>(), + [("max_age", "0".into())] + ); + assert_eq!(StepUpRequirement::default().authorize_params().count(), 0); +} diff --git a/crates/crypto/src/sealing.rs b/crates/crypto/src/sealing/mod.rs similarity index 61% rename from crates/crypto/src/sealing.rs rename to crates/crypto/src/sealing/mod.rs index 3481f8a5c..c37ef8f27 100644 --- a/crates/crypto/src/sealing.rs +++ b/crates/crypto/src/sealing/mod.rs @@ -86,52 +86,4 @@ impl fmt::Debug for KeyEncryptionKey { } #[cfg(test)] -mod tests { - //! Sealed values open only with their own KEK and associated data. - use super::*; - use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; - - /// A sealed value fails to open with another KEK, swapped associated data or - /// any modified byte, and parsing accepts only 32 bytes of unpadded base64url. - #[test] - fn sealed_values_open_only_with_their_key_and_associated_data() { - let kek = KeyEncryptionKey::generate().expect("KEK"); - let sealed = kek.seal(b"private key", b"kid-1rsa").expect("seal"); - assert_eq!( - kek.open(&sealed, b"kid-1rsa").expect("open"), - b"private key" - ); - let other = KeyEncryptionKey::generate().expect("other KEK"); - assert!(matches!( - other.open(&sealed, b"kid-1rsa"), - Err(CryptoError::Unsealable) - )); - assert!(matches!( - kek.open(&sealed, b"kid-2rsa"), - Err(CryptoError::Unsealable) - )); - for index in [0, NONCE_BYTES, sealed.len() - 1] { - let mut modified = sealed.clone(); - modified[index] ^= 1; - assert!(kek.open(&modified, b"kid-1rsa").is_err(), "byte {index}"); - } - assert!(kek.open(&sealed[..TAG_BYTES], b"kid-1rsa").is_err()); - - let encoded = Secret::generate().expect("secret").encoded(); - assert!(KeyEncryptionKey::parse(&encoded).is_ok()); - assert!(KeyEncryptionKey::parse(&format!("{encoded}\n")).is_ok()); - for invalid in [format!("{encoded}="), "not base64!".to_owned()] { - assert!(matches!( - KeyEncryptionKey::parse(&invalid), - Err(CryptoError::Encoding(_)) - )); - } - for bytes in [&[0; 31][..], &[0; 33]] { - assert!(matches!( - KeyEncryptionKey::parse(&URL_SAFE_NO_PAD.encode(bytes)), - Err(CryptoError::SecretLength) - )); - } - assert_eq!(format!("{kek:?}"), "KeyEncryptionKey(REDACTED)"); - } -} +mod tests; diff --git a/crates/crypto/src/sealing/tests.rs b/crates/crypto/src/sealing/tests.rs new file mode 100644 index 000000000..803691884 --- /dev/null +++ b/crates/crypto/src/sealing/tests.rs @@ -0,0 +1,47 @@ +//! Sealed values open only with their own KEK and associated data. +use super::*; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + +/// A sealed value fails to open with another KEK, swapped associated data or +/// any modified byte, and parsing accepts only 32 bytes of unpadded base64url. +#[test] +fn sealed_values_open_only_with_their_key_and_associated_data() { + let kek = KeyEncryptionKey::generate().expect("KEK"); + let sealed = kek.seal(b"private key", b"kid-1rsa").expect("seal"); + assert_eq!( + kek.open(&sealed, b"kid-1rsa").expect("open"), + b"private key" + ); + let other = KeyEncryptionKey::generate().expect("other KEK"); + assert!(matches!( + other.open(&sealed, b"kid-1rsa"), + Err(CryptoError::Unsealable) + )); + assert!(matches!( + kek.open(&sealed, b"kid-2rsa"), + Err(CryptoError::Unsealable) + )); + for index in [0, NONCE_BYTES, sealed.len() - 1] { + let mut modified = sealed.clone(); + modified[index] ^= 1; + assert!(kek.open(&modified, b"kid-1rsa").is_err(), "byte {index}"); + } + assert!(kek.open(&sealed[..TAG_BYTES], b"kid-1rsa").is_err()); + + let encoded = Secret::generate().expect("secret").encoded(); + assert!(KeyEncryptionKey::parse(&encoded).is_ok()); + assert!(KeyEncryptionKey::parse(&format!("{encoded}\n")).is_ok()); + for invalid in [format!("{encoded}="), "not base64!".to_owned()] { + assert!(matches!( + KeyEncryptionKey::parse(&invalid), + Err(CryptoError::Encoding(_)) + )); + } + for bytes in [&[0; 31][..], &[0; 33]] { + assert!(matches!( + KeyEncryptionKey::parse(&URL_SAFE_NO_PAD.encode(bytes)), + Err(CryptoError::SecretLength) + )); + } + assert_eq!(format!("{kek:?}"), "KeyEncryptionKey(REDACTED)"); +} diff --git a/crates/crypto/src/signing.rs b/crates/crypto/src/signing/mod.rs similarity index 66% rename from crates/crypto/src/signing.rs rename to crates/crypto/src/signing/mod.rs index 38dac2a9a..063463209 100644 --- a/crates/crypto/src/signing.rs +++ b/crates/crypto/src/signing/mod.rs @@ -421,169 +421,4 @@ impl KeySet { } #[cfg(test)] -mod tests { - //! JWT policy, tampering, protected-header trust boundaries and key selection. - use super::*; - use serde_json::json; - - /// Signing enforces token types, signatures, issuer and expiry, while logout permits expired hints. - #[test] - fn rsa_verifies_signatures_types_expiry_and_logout_hints() { - let keys = KeySet::single(Rs256Key::generate("test").expect("generate RSA test key")); - let now = Utc::now().timestamp(); - let claims = json!({"iss":"https://auth.example","sub":"user","aud":"client","iat":now-60,"exp":now-1}); - let expired = keys - .sign(TokenType::Id, &claims) - .expect("sign expired ID token hint"); - assert!( - keys.verify::(&expired, TokenType::Id, "https://auth.example") - .is_err() - ); - assert!( - keys.verify_id_token_hint(&expired, "https://auth.example") - .is_ok() - ); - assert!( - keys.verify_id_token_hint(&expired, "https://evil.example") - .is_err() - ); - let mut valid = claims; - valid["exp"] = json!(now + 300); - let token = keys - .sign(TokenType::Access, &valid) - .expect("sign access token"); - assert!( - keys.verify::(&token, TokenType::Access, "https://auth.example") - .is_ok() - ); - assert!( - keys.verify::(&token, TokenType::Id, "https://auth.example") - .is_err() - ); - let mut bytes = token.into_bytes(); - let n = bytes.len(); - bytes[n - 10] = if bytes[n - 10] == b'A' { b'B' } else { b'A' }; - assert!( - keys.verify::( - std::str::from_utf8(&bytes).expect("modified compact token remains ASCII"), - TokenType::Access, - "https://auth.example" - ) - .is_err() - ); - assert_eq!(keys.jwks().keys[0].kty, KeyType::Rsa); - } - - /// Even correctly RSA-signed inputs cannot choose an algorithm, type, key or critical extension. - #[test] - fn rejects_algorithm_confusion_and_unrecognized_headers() { - let keys = KeySet::single(Rs256Key::generate("headers").expect("RSA key")); - let key = keys.signer(); - let now = Utc::now().timestamp(); - let claims = json!({"iss":"https://auth.example", "iat":now, "exp":now+300}); - for (field, value) in [ - ("alg", json!("none")), - ("alg", json!("HS256")), - ("alg", json!("RS512")), - ("typ", json!("at+jwt")), - ("kid", json!("untrusted")), - ("crit", json!([])), - ("crit", json!(["b64"])), - ] { - let mut header = json!({"alg":Algorithm::Rs256.as_str(), "kid":key.kid, "typ":TokenType::Id.as_str()}); - header[field] = value; - let input = format!( - "{}.{}", - URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("header")), - URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).expect("claims")) - ); - // A valid RSA signature isolates header-policy rejection from signature failure. - let mut signer = Signer::new(MessageDigest::sha256(), &key.key).expect("signer"); - signer.update(input.as_bytes()).expect("input"); - let token = format!( - "{input}.{}", - URL_SAFE_NO_PAD.encode(signer.sign_to_vec().expect("signature")) - ); - assert!( - matches!( - keys.verify::(&token, TokenType::Id, "https://auth.example"), - Err(CryptoError::InvalidToken | CryptoError::UnknownKey | CryptoError::Json(_)) - ), - "accepted {field}" - ); - } - // HMAC with public-key bytes is the classic asymmetric/symmetric algorithm confusion. - let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256","kid":"headers","typ":"JWT"}"#); - let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).expect("claims")); - let input = format!("{header}.{payload}"); - let signature = - crate::Digest::hmac(&key.public_key_pem().expect("public key"), input.as_bytes()) - .expect("HMAC") - .encoded(); - let token = format!("{input}.{signature}"); - assert!(matches!( - keys.verify::(&token, TokenType::Id, "https://auth.example"), - Err(CryptoError::Json(_)) - )); - } - - /// During a rotation, tokens of every published key verify and JWKS lists them; - /// a retired key verifies only ID token hints, and a key outside the set nothing. - #[test] - fn key_set_verifies_by_kid_and_limits_retired_keys_to_hints() { - let [retiring, active, retired, unknown] = ["retiring", "active", "retired", "unknown"] - .map(|kid| Rs256Key::generate(kid).expect("key")); - let now = Utc::now().timestamp(); - let claims = - json!({"iss":"https://auth.example", "aud":"client", "iat":now, "exp":now+300}); - let [by_retiring, by_retired, by_unknown] = [&retiring, &retired, &unknown] - .map(|key| key.sign(TokenType::Id, &claims).expect("sign")); - // A signer must be published, or verifiers could not check its tokens. - assert!(matches!( - KeySet::new(unknown, vec![retiring.public_key().clone()], vec![]), - Err(CryptoError::KeySet) - )); - let published = vec![retiring.public_key().clone(), active.public_key().clone()]; - let keys = - KeySet::new(active, published, vec![retired.public_key().clone()]).expect("key set"); - let by_active = keys.sign(TokenType::Id, &claims).expect("sign"); - for token in [&by_active, &by_retiring] { - assert!( - keys.verify::(token, TokenType::Id, "https://auth.example") - .is_ok() - ); - assert!( - keys.verify_id_token_hint(token, "https://auth.example") - .is_ok() - ); - } - assert!(matches!( - keys.verify::(&by_retired, TokenType::Id, "https://auth.example"), - Err(CryptoError::UnknownKey) - )); - assert!( - keys.verify_id_token_hint(&by_retired, "https://auth.example") - .is_ok() - ); - assert!(matches!( - keys.verify_id_token_hint(&by_unknown, "https://auth.example"), - Err(CryptoError::UnknownKey) - )); - let kids: Vec<_> = keys - .jwks() - .keys - .iter() - .map(|key| key.kid.as_str()) - .collect(); - assert_eq!(kids, ["retiring", "active"]); - - // A repeated key identifier, even between published and retired keys, is refused. - let signer = Rs256Key::generate("same").expect("key"); - let twin = Rs256Key::generate("same").expect("key"); - let published = vec![signer.public_key().clone()]; - assert!(matches!( - KeySet::new(signer, published, vec![twin.public_key().clone()]), - Err(CryptoError::KeySet) - )); - } -} +mod tests; diff --git a/crates/crypto/src/signing/tests.rs b/crates/crypto/src/signing/tests.rs new file mode 100644 index 000000000..76c7c71dd --- /dev/null +++ b/crates/crypto/src/signing/tests.rs @@ -0,0 +1,164 @@ +//! JWT policy, tampering, protected-header trust boundaries and key selection. +use super::*; +use serde_json::json; + +/// Signing enforces token types, signatures, issuer and expiry, while logout permits expired hints. +#[test] +fn rsa_verifies_signatures_types_expiry_and_logout_hints() { + let keys = KeySet::single(Rs256Key::generate("test").expect("generate RSA test key")); + let now = Utc::now().timestamp(); + let claims = + json!({"iss":"https://auth.example","sub":"user","aud":"client","iat":now-60,"exp":now-1}); + let expired = keys + .sign(TokenType::Id, &claims) + .expect("sign expired ID token hint"); + assert!( + keys.verify::(&expired, TokenType::Id, "https://auth.example") + .is_err() + ); + assert!( + keys.verify_id_token_hint(&expired, "https://auth.example") + .is_ok() + ); + assert!( + keys.verify_id_token_hint(&expired, "https://evil.example") + .is_err() + ); + let mut valid = claims; + valid["exp"] = json!(now + 300); + let token = keys + .sign(TokenType::Access, &valid) + .expect("sign access token"); + assert!( + keys.verify::(&token, TokenType::Access, "https://auth.example") + .is_ok() + ); + assert!( + keys.verify::(&token, TokenType::Id, "https://auth.example") + .is_err() + ); + let mut bytes = token.into_bytes(); + let n = bytes.len(); + bytes[n - 10] = if bytes[n - 10] == b'A' { b'B' } else { b'A' }; + assert!( + keys.verify::( + std::str::from_utf8(&bytes).expect("modified compact token remains ASCII"), + TokenType::Access, + "https://auth.example" + ) + .is_err() + ); + assert_eq!(keys.jwks().keys[0].kty, KeyType::Rsa); +} + +/// Even correctly RSA-signed inputs cannot choose an algorithm, type, key or critical extension. +#[test] +fn rejects_algorithm_confusion_and_unrecognized_headers() { + let keys = KeySet::single(Rs256Key::generate("headers").expect("RSA key")); + let key = keys.signer(); + let now = Utc::now().timestamp(); + let claims = json!({"iss":"https://auth.example", "iat":now, "exp":now+300}); + for (field, value) in [ + ("alg", json!("none")), + ("alg", json!("HS256")), + ("alg", json!("RS512")), + ("typ", json!("at+jwt")), + ("kid", json!("untrusted")), + ("crit", json!([])), + ("crit", json!(["b64"])), + ] { + let mut header = + json!({"alg":Algorithm::Rs256.as_str(), "kid":key.kid, "typ":TokenType::Id.as_str()}); + header[field] = value; + let input = format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("header")), + URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).expect("claims")) + ); + // A valid RSA signature isolates header-policy rejection from signature failure. + let mut signer = Signer::new(MessageDigest::sha256(), &key.key).expect("signer"); + signer.update(input.as_bytes()).expect("input"); + let token = format!( + "{input}.{}", + URL_SAFE_NO_PAD.encode(signer.sign_to_vec().expect("signature")) + ); + assert!( + matches!( + keys.verify::(&token, TokenType::Id, "https://auth.example"), + Err(CryptoError::InvalidToken | CryptoError::UnknownKey | CryptoError::Json(_)) + ), + "accepted {field}" + ); + } + // HMAC with public-key bytes is the classic asymmetric/symmetric algorithm confusion. + let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256","kid":"headers","typ":"JWT"}"#); + let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).expect("claims")); + let input = format!("{header}.{payload}"); + let signature = + crate::Digest::hmac(&key.public_key_pem().expect("public key"), input.as_bytes()) + .expect("HMAC") + .encoded(); + let token = format!("{input}.{signature}"); + assert!(matches!( + keys.verify::(&token, TokenType::Id, "https://auth.example"), + Err(CryptoError::Json(_)) + )); +} + +/// During a rotation, tokens of every published key verify and JWKS lists them; +/// a retired key verifies only ID token hints, and a key outside the set nothing. +#[test] +fn key_set_verifies_by_kid_and_limits_retired_keys_to_hints() { + let [retiring, active, retired, unknown] = ["retiring", "active", "retired", "unknown"] + .map(|kid| Rs256Key::generate(kid).expect("key")); + let now = Utc::now().timestamp(); + let claims = json!({"iss":"https://auth.example", "aud":"client", "iat":now, "exp":now+300}); + let [by_retiring, by_retired, by_unknown] = + [&retiring, &retired, &unknown].map(|key| key.sign(TokenType::Id, &claims).expect("sign")); + // A signer must be published, or verifiers could not check its tokens. + assert!(matches!( + KeySet::new(unknown, vec![retiring.public_key().clone()], vec![]), + Err(CryptoError::KeySet) + )); + let published = vec![retiring.public_key().clone(), active.public_key().clone()]; + let keys = KeySet::new(active, published, vec![retired.public_key().clone()]).expect("key set"); + let by_active = keys.sign(TokenType::Id, &claims).expect("sign"); + for token in [&by_active, &by_retiring] { + assert!( + keys.verify::(token, TokenType::Id, "https://auth.example") + .is_ok() + ); + assert!( + keys.verify_id_token_hint(token, "https://auth.example") + .is_ok() + ); + } + assert!(matches!( + keys.verify::(&by_retired, TokenType::Id, "https://auth.example"), + Err(CryptoError::UnknownKey) + )); + assert!( + keys.verify_id_token_hint(&by_retired, "https://auth.example") + .is_ok() + ); + assert!(matches!( + keys.verify_id_token_hint(&by_unknown, "https://auth.example"), + Err(CryptoError::UnknownKey) + )); + let kids: Vec<_> = keys + .jwks() + .keys + .iter() + .map(|key| key.kid.as_str()) + .collect(); + assert_eq!(kids, ["retiring", "active"]); + + // A repeated key identifier, even between published and retired keys, is refused. + let signer = Rs256Key::generate("same").expect("key"); + let twin = Rs256Key::generate("same").expect("key"); + let published = vec![signer.public_key().clone()]; + assert!(matches!( + KeySet::new(signer, published, vec![twin.public_key().clone()]), + Err(CryptoError::KeySet) + )); +} diff --git a/crates/database/src/repositories/passkeys.rs b/crates/database/src/repositories/passkeys/mod.rs similarity index 87% rename from crates/database/src/repositories/passkeys.rs rename to crates/database/src/repositories/passkeys/mod.rs index 4c82eb9d7..a202a809c 100644 --- a/crates/database/src/repositories/passkeys.rs +++ b/crates/database/src/repositories/passkeys/mod.rs @@ -398,53 +398,4 @@ impl PasskeyRepository<'_> { /// Handle lookups against a running database. #[cfg(test)] -mod tests { - use super::{InsertPasskey, PasskeyRepository}; - use crate::{Database, InsertUser, repositories::UserRepository}; - use piquel_common::PasskeyId; - - /// A disabled account and an account whose only passkey is revoked list no - /// credentials, like a handle nobody holds. - #[tokio::test] - #[ignore = "requires a disposable TEST_DATABASE_URL"] - async fn handle_lookup_hides_disabled_accounts_and_revoked_passkeys() { - let pool = Database::test_pool().await; - let mut passkeys = PasskeyRepository::from_pool(&pool); - for disable in [true, false] { - let account = InsertUser::named("passkey"); - let user = account.id; - UserRepository::from_pool(&pool) - .insert(&account) - .await - .expect("user"); - let key = passkeys - .insert(&InsertPasskey { - id: PasskeyId::new(), - credential_id: user.as_uuid().as_bytes().to_vec(), - user_id: user, - credential: serde_json::json!({}), - friendly_name: "Passkey test".into(), - }) - .await - .expect("passkey"); - let listed = || async { - PasskeyRepository::from_pool(&pool) - .list_active_by_handle(&account.handle) - .await - .expect("lookup") - .len() - }; - assert_eq!(listed().await, 1); - if disable { - sqlx::query("UPDATE users SET status = 'disabled' WHERE id = $1") - .bind(user.as_uuid()) - .execute(&pool) - .await - .expect("disable"); - } else { - assert!(passkeys.revoke(key.id, user).await.expect("revoke")); - } - assert_eq!(listed().await, 0, "disable: {disable}"); - } - } -} +mod tests; diff --git a/crates/database/src/repositories/passkeys/tests.rs b/crates/database/src/repositories/passkeys/tests.rs new file mode 100644 index 000000000..f535f312d --- /dev/null +++ b/crates/database/src/repositories/passkeys/tests.rs @@ -0,0 +1,48 @@ +use super::{InsertPasskey, PasskeyRepository}; +use crate::{Database, InsertUser, repositories::UserRepository}; +use piquel_common::PasskeyId; + +/// A disabled account and an account whose only passkey is revoked list no +/// credentials, like a handle nobody holds. +#[tokio::test] +#[ignore = "requires a disposable TEST_DATABASE_URL"] +async fn handle_lookup_hides_disabled_accounts_and_revoked_passkeys() { + let pool = Database::test_pool().await; + let mut passkeys = PasskeyRepository::from_pool(&pool); + for disable in [true, false] { + let account = InsertUser::named("passkey"); + let user = account.id; + UserRepository::from_pool(&pool) + .insert(&account) + .await + .expect("user"); + let key = passkeys + .insert(&InsertPasskey { + id: PasskeyId::new(), + credential_id: user.as_uuid().as_bytes().to_vec(), + user_id: user, + credential: serde_json::json!({}), + friendly_name: "Passkey test".into(), + }) + .await + .expect("passkey"); + let listed = || async { + PasskeyRepository::from_pool(&pool) + .list_active_by_handle(&account.handle) + .await + .expect("lookup") + .len() + }; + assert_eq!(listed().await, 1); + if disable { + sqlx::query("UPDATE users SET status = 'disabled' WHERE id = $1") + .bind(user.as_uuid()) + .execute(&pool) + .await + .expect("disable"); + } else { + assert!(passkeys.revoke(key.id, user).await.expect("revoke")); + } + assert_eq!(listed().await, 0, "disable: {disable}"); + } +} diff --git a/crates/telemetry/src/http.rs b/crates/telemetry/src/http/mod.rs similarity index 75% rename from crates/telemetry/src/http.rs rename to crates/telemetry/src/http/mod.rs index 98646ca07..456d40b5e 100644 --- a/crates/telemetry/src/http.rs +++ b/crates/telemetry/src/http/mod.rs @@ -179,65 +179,4 @@ impl HttpTelemetry { } #[cfg(test)] -mod tests { - //! What the HTTP layer records of a request. - use super::*; - use axum::{body::Body, http::StatusCode, routing::get}; - use tower::ServiceExt; - - /// Sends `uri` to a router with one route that fails. - async fn send(uri: &str) -> Response { - let router = HttpTelemetry::default().wrap(Router::new().route( - "/items/{id}", - get(|| async { StatusCode::INTERNAL_SERVER_ERROR }), - )); - router - .oneshot( - Request::builder() - .uri(uri) - .body(Body::empty()) - .expect("request"), - ) - .await - .expect("response") - } - - /// A matched request is named by its route template and never records its - /// query; a failure is marked and returns its trace ID. - #[tokio::test] - async fn spans_name_the_route_and_mark_failures() { - let capture = Telemetry::capture("info"); - let response = send("/items/secret-id?token=secret-token").await; - let span = capture.spans().pop().expect("server span"); - assert_eq!(span.name, "GET /items/{id}"); - assert_eq!( - response.headers()[HttpTelemetry::TRACE_ID_HEADER], - span.span_context.trace_id().to_string() - ); - assert!(matches!( - span.status, - opentelemetry::trace::Status::Error { .. } - )); - let exported = capture.exported_text(); - assert!(exported.contains(&"http.route=/items/{id}".to_owned())); - assert!(exported.iter().all(|text| !text.contains("secret"))); - } - - /// An unmatched request records only its path, without the query. - #[tokio::test] - async fn unmatched_requests_record_their_path() { - let capture = Telemetry::capture("info"); - let response = send("/missing?token=secret-token").await; - assert_eq!(response.status(), StatusCode::NOT_FOUND); - assert!( - !response - .headers() - .contains_key(HttpTelemetry::TRACE_ID_HEADER) - ); - let span = capture.spans().pop().expect("server span"); - assert_eq!(span.name, "GET"); - let exported = capture.exported_text(); - assert!(exported.contains(&"url.path=/missing".to_owned())); - assert!(exported.iter().all(|text| !text.contains("secret"))); - } -} +mod tests; diff --git a/crates/telemetry/src/http/tests.rs b/crates/telemetry/src/http/tests.rs new file mode 100644 index 000000000..480aaead5 --- /dev/null +++ b/crates/telemetry/src/http/tests.rs @@ -0,0 +1,60 @@ +//! What the HTTP layer records of a request. +use super::*; +use axum::{body::Body, http::StatusCode, routing::get}; +use tower::ServiceExt; + +/// Sends `uri` to a router with one route that fails. +async fn send(uri: &str) -> Response { + let router = HttpTelemetry::default().wrap(Router::new().route( + "/items/{id}", + get(|| async { StatusCode::INTERNAL_SERVER_ERROR }), + )); + router + .oneshot( + Request::builder() + .uri(uri) + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response") +} + +/// A matched request is named by its route template and never records its +/// query; a failure is marked and returns its trace ID. +#[tokio::test] +async fn spans_name_the_route_and_mark_failures() { + let capture = Telemetry::capture("info"); + let response = send("/items/secret-id?token=secret-token").await; + let span = capture.spans().pop().expect("server span"); + assert_eq!(span.name, "GET /items/{id}"); + assert_eq!( + response.headers()[HttpTelemetry::TRACE_ID_HEADER], + span.span_context.trace_id().to_string() + ); + assert!(matches!( + span.status, + opentelemetry::trace::Status::Error { .. } + )); + let exported = capture.exported_text(); + assert!(exported.contains(&"http.route=/items/{id}".to_owned())); + assert!(exported.iter().all(|text| !text.contains("secret"))); +} + +/// An unmatched request records only its path, without the query. +#[tokio::test] +async fn unmatched_requests_record_their_path() { + let capture = Telemetry::capture("info"); + let response = send("/missing?token=secret-token").await; + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert!( + !response + .headers() + .contains_key(HttpTelemetry::TRACE_ID_HEADER) + ); + let span = capture.spans().pop().expect("server span"); + assert_eq!(span.name, "GET"); + let exported = capture.exported_text(); + assert!(exported.contains(&"url.path=/missing".to_owned())); + assert!(exported.iter().all(|text| !text.contains("secret"))); +} diff --git a/crates/ui/src/login.rs b/crates/ui/src/login/mod.rs similarity index 94% rename from crates/ui/src/login.rs rename to crates/ui/src/login/mod.rs index 83ab2ea1c..2f33e5c78 100644 --- a/crates/ui/src/login.rs +++ b/crates/ui/src/login/mod.rs @@ -577,41 +577,4 @@ async fn passkey_sign_in<'a>( } #[cfg(test)] -mod tests { - //! The sign-in pages' query. - use super::*; - - /// A field an old or edited link gets wrong reads as absent, never losing where - /// the browser goes on to; the invitation's old name still reads. - #[test] - fn a_wrong_field_keeps_the_rest_of_the_query() { - let query: LoginQuery = serde_urlencoded::from_str( - "transaction=t&acr=gold&return_to=%2Fsettings&invite=i&error=nope&social=maybe&handle=", - ) - .expect("query"); - assert_eq!( - query, - LoginQuery { - transaction: Some("t".into()), - return_to: Some("/settings".into()), - invitation: Some("i".into()), - handle: Checkbox(true), - ..LoginQuery::default() - } - ); - let known: LoginQuery = - serde_urlencoded::from_str("acr=phr&error=social_failed&social=link").expect("query"); - assert_eq!( - (known.acr, known.error, known.social), - ( - Some(Acr::PhishingResistant), - Some(CallbackError::Failed), - Some(PendingDestination::Link) - ) - ); - assert_eq!( - known.on("/login").expect("link"), - "/login?acr=phr&error=social_failed&social=link" - ); - } -} +mod tests; diff --git a/crates/ui/src/login/tests.rs b/crates/ui/src/login/tests.rs new file mode 100644 index 000000000..a0e48b112 --- /dev/null +++ b/crates/ui/src/login/tests.rs @@ -0,0 +1,36 @@ +//! The sign-in pages' query. +use super::*; + +/// A field an old or edited link gets wrong reads as absent, never losing where +/// the browser goes on to; the invitation's old name still reads. +#[test] +fn a_wrong_field_keeps_the_rest_of_the_query() { + let query: LoginQuery = serde_urlencoded::from_str( + "transaction=t&acr=gold&return_to=%2Fsettings&invite=i&error=nope&social=maybe&handle=", + ) + .expect("query"); + assert_eq!( + query, + LoginQuery { + transaction: Some("t".into()), + return_to: Some("/settings".into()), + invitation: Some("i".into()), + handle: Checkbox(true), + ..LoginQuery::default() + } + ); + let known: LoginQuery = + serde_urlencoded::from_str("acr=phr&error=social_failed&social=link").expect("query"); + assert_eq!( + (known.acr, known.error, known.social), + ( + Some(Acr::PhishingResistant), + Some(CallbackError::Failed), + Some(PendingDestination::Link) + ) + ); + assert_eq!( + known.on("/login").expect("link"), + "/login?acr=phr&error=social_failed&social=link" + ); +} diff --git a/crates/ui/src/recovery.rs b/crates/ui/src/recovery/mod.rs similarity index 85% rename from crates/ui/src/recovery.rs rename to crates/ui/src/recovery/mod.rs index 5d0a0f3a0..5a2310978 100644 --- a/crates/ui/src/recovery.rs +++ b/crates/ui/src/recovery/mod.rs @@ -462,86 +462,4 @@ pub async fn recovery_prompt<'a>( } #[cfg(test)] -mod tests { - //! The recovery pages' changes. - use super::*; - - /// The link forms send what the fragment fills in only as its own input, and a - /// recovery ID the fragment gets wrong reads as absent. An undo's outcome reads - /// as signing nobody in unless it says otherwise. - #[test] - fn link_forms_leave_their_values_to_the_fragment() { - let fields = |change: Fields| serde_urlencoded::to_string(change).expect("fields"); - assert_eq!( - fields( - RecoverChange::Open { - token: String::new() - } - .into() - ), - "action=open" - ); - assert_eq!( - fields(UndoChange::Open { recovery: None }.into()), - "action=open" - ); - let id = RecoveryId::new(); - for (form, expected) in [ - (format!("action=open&recovery={id}"), Some(id)), - ("action=open&recovery=".to_owned(), None), - ("action=open&recovery=nope".to_owned(), None), - ("action=open".to_owned(), None), - ] { - let change: UndoChange = serde_urlencoded::from_str(&form).expect("change"); - assert!( - matches!(change, UndoChange::Open { recovery } if recovery == expected), - "{form}" - ); - } - let token: RecoverChange = serde_urlencoded::from_str("action=open").expect("change"); - assert!(matches!(token, RecoverChange::Open { token } if token.is_empty())); - for (form, expected) in [ - ("action=undone&signed_in=true", true), - ("action=undone&signed_in=false", false), - ("action=undone&signed_in=nope", false), - ("action=undone", false), - ] { - let change: UndoChange = serde_urlencoded::from_str(form).expect("change"); - assert!( - matches!(change, UndoChange::Undone { signed_in } if signed_in == expected), - "{form}" - ); - } - } - - /// A "yes" holds for one session at one stage, and only until a passkey first - /// confirms the session. - #[test] - fn answers_hold_per_session_stage_and_confirmation() { - let at = DateTime::::UNIX_EPOCH; - let open = Recovery { - id: RecoveryId::new(), - started_at: at, - stage: RecoveryStage::Open { expires_at: at }, - undoable: true, - }; - let probation = Recovery { - stage: RecoveryStage::Probation { - completed_at: at, - settles_at: at, - passkey: None, - }, - ..open - }; - let session = SessionId::new(); - let keys = [ - open.dismiss_key(session, false), - open.dismiss_key(session, true), - probation.dismiss_key(session, false), - probation.dismiss_key(session, true), - open.dismiss_key(SessionId::new(), false), - ]; - let distinct: std::collections::BTreeSet<_> = keys.iter().collect(); - assert_eq!(distinct.len(), keys.len(), "{keys:?}"); - } -} +mod tests; diff --git a/crates/ui/src/recovery/tests.rs b/crates/ui/src/recovery/tests.rs new file mode 100644 index 000000000..6cb2c8166 --- /dev/null +++ b/crates/ui/src/recovery/tests.rs @@ -0,0 +1,81 @@ +//! The recovery pages' changes. +use super::*; + +/// The link forms send what the fragment fills in only as its own input, and a +/// recovery ID the fragment gets wrong reads as absent. An undo's outcome reads +/// as signing nobody in unless it says otherwise. +#[test] +fn link_forms_leave_their_values_to_the_fragment() { + let fields = |change: Fields| serde_urlencoded::to_string(change).expect("fields"); + assert_eq!( + fields( + RecoverChange::Open { + token: String::new() + } + .into() + ), + "action=open" + ); + assert_eq!( + fields(UndoChange::Open { recovery: None }.into()), + "action=open" + ); + let id = RecoveryId::new(); + for (form, expected) in [ + (format!("action=open&recovery={id}"), Some(id)), + ("action=open&recovery=".to_owned(), None), + ("action=open&recovery=nope".to_owned(), None), + ("action=open".to_owned(), None), + ] { + let change: UndoChange = serde_urlencoded::from_str(&form).expect("change"); + assert!( + matches!(change, UndoChange::Open { recovery } if recovery == expected), + "{form}" + ); + } + let token: RecoverChange = serde_urlencoded::from_str("action=open").expect("change"); + assert!(matches!(token, RecoverChange::Open { token } if token.is_empty())); + for (form, expected) in [ + ("action=undone&signed_in=true", true), + ("action=undone&signed_in=false", false), + ("action=undone&signed_in=nope", false), + ("action=undone", false), + ] { + let change: UndoChange = serde_urlencoded::from_str(form).expect("change"); + assert!( + matches!(change, UndoChange::Undone { signed_in } if signed_in == expected), + "{form}" + ); + } +} + +/// A "yes" holds for one session at one stage, and only until a passkey first +/// confirms the session. +#[test] +fn answers_hold_per_session_stage_and_confirmation() { + let at = DateTime::::UNIX_EPOCH; + let open = Recovery { + id: RecoveryId::new(), + started_at: at, + stage: RecoveryStage::Open { expires_at: at }, + undoable: true, + }; + let probation = Recovery { + stage: RecoveryStage::Probation { + completed_at: at, + settles_at: at, + passkey: None, + }, + ..open + }; + let session = SessionId::new(); + let keys = [ + open.dismiss_key(session, false), + open.dismiss_key(session, true), + probation.dismiss_key(session, false), + probation.dismiss_key(session, true), + open.dismiss_key(SessionId::new(), false), + ]; + let distinct: std::collections::BTreeSet<_> = keys.iter().collect(); + assert_eq!(distinct.len(), keys.len(), "{keys:?}"); +} From 18a1bf972c6eacb0f72989bf749492ad487390c3 Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 4 Nov 2026 11:51:45 +0100 Subject: [PATCH 2/3] refactor(tests): the largest auth-service test files split by flow oidc, passkey, recovery, clients, federation, admin and security tests each become a tests/ directory: mod.rs holds the shared fixtures, and each flow gets its own file. Test bodies are unchanged; doc references follow the new paths. Co-Authored-By: Claude Opus 5.5 --- apps/auth-service/src/admin/tests.rs | 1091 ------- apps/auth-service/src/admin/tests/accounts.rs | 120 + .../src/admin/tests/administrators.rs | 189 ++ .../src/admin/tests/deliveries.rs | 131 + apps/auth-service/src/admin/tests/handles.rs | 133 + .../src/admin/tests/invitations.rs | 95 + apps/auth-service/src/admin/tests/mod.rs | 190 ++ .../auth-service/src/admin/tests/mutations.rs | 101 + apps/auth-service/src/admin/tests/reads.rs | 160 ++ apps/auth-service/src/clients/tests.rs | 1195 -------- .../src/clients/tests/deletion.rs | 279 ++ apps/auth-service/src/clients/tests/mod.rs | 96 + .../auth-service/src/clients/tests/origins.rs | 147 + apps/auth-service/src/clients/tests/owners.rs | 272 ++ .../src/clients/tests/registry.rs | 416 +++ apps/auth-service/src/federation/tests.rs | 1160 -------- .../src/federation/tests/callback.rs | 159 ++ .../src/federation/tests/linking.rs | 141 + apps/auth-service/src/federation/tests/mod.rs | 303 ++ .../src/federation/tests/protocols.rs | 279 ++ .../src/federation/tests/sign_in.rs | 224 ++ .../src/federation/tests/signup.rs | 84 + apps/auth-service/src/oidc/tests.rs | 2498 ----------------- .../src/oidc/tests/app_removal.rs | 143 + .../src/oidc/tests/authorization.rs | 230 ++ apps/auth-service/src/oidc/tests/logout.rs | 133 + apps/auth-service/src/oidc/tests/mod.rs | 453 +++ apps/auth-service/src/oidc/tests/protocol.rs | 252 ++ apps/auth-service/src/oidc/tests/pushed.rs | 132 + .../auth-service/src/oidc/tests/sdk_client.rs | 140 + .../auth-service/src/oidc/tests/sdk_routes.rs | 438 +++ apps/auth-service/src/oidc/tests/step_up.rs | 189 ++ apps/auth-service/src/oidc/tests/tokens.rs | 427 +++ apps/auth-service/src/passkey/tests.rs | 1851 ------------ .../src/passkey/tests/confirmation.rs | 307 ++ .../src/passkey/tests/counters.rs | 137 + apps/auth-service/src/passkey/tests/mod.rs | 321 +++ .../src/passkey/tests/registration.rs | 140 + .../src/passkey/tests/related_pages.rs | 416 +++ .../auth-service/src/passkey/tests/sign_in.rs | 270 ++ .../src/passkey/tests/telemetry.rs | 197 ++ .../src/passkey/tests/validation.rs | 98 + apps/auth-service/src/recovery/tests.rs | 1372 --------- .../auth-service/src/recovery/tests/enroll.rs | 149 + apps/auth-service/src/recovery/tests/mod.rs | 366 +++ .../src/recovery/tests/probation.rs | 258 ++ apps/auth-service/src/recovery/tests/start.rs | 205 ++ apps/auth-service/src/recovery/tests/undo.rs | 411 +++ apps/auth-service/src/security/tests.rs | 1056 ------- .../src/security/tests/caching.rs | 85 + .../src/security/tests/forwarding.rs | 74 + apps/auth-service/src/security/tests/mod.rs | 204 ++ .../src/security/tests/origins.rs | 259 ++ .../src/security/tests/rate_limits.rs | 263 ++ .../src/security/tests/sessions.rs | 198 ++ docs/architecture/federation-providers.md | 10 +- docs/architecture/telemetry.md | 2 +- docs/security/account-recovery.md | 12 +- 58 files changed, 10426 insertions(+), 10235 deletions(-) delete mode 100644 apps/auth-service/src/admin/tests.rs create mode 100644 apps/auth-service/src/admin/tests/accounts.rs create mode 100644 apps/auth-service/src/admin/tests/administrators.rs create mode 100644 apps/auth-service/src/admin/tests/deliveries.rs create mode 100644 apps/auth-service/src/admin/tests/handles.rs create mode 100644 apps/auth-service/src/admin/tests/invitations.rs create mode 100644 apps/auth-service/src/admin/tests/mod.rs create mode 100644 apps/auth-service/src/admin/tests/mutations.rs create mode 100644 apps/auth-service/src/admin/tests/reads.rs delete mode 100644 apps/auth-service/src/clients/tests.rs create mode 100644 apps/auth-service/src/clients/tests/deletion.rs create mode 100644 apps/auth-service/src/clients/tests/mod.rs create mode 100644 apps/auth-service/src/clients/tests/origins.rs create mode 100644 apps/auth-service/src/clients/tests/owners.rs create mode 100644 apps/auth-service/src/clients/tests/registry.rs delete mode 100644 apps/auth-service/src/federation/tests.rs create mode 100644 apps/auth-service/src/federation/tests/callback.rs create mode 100644 apps/auth-service/src/federation/tests/linking.rs create mode 100644 apps/auth-service/src/federation/tests/mod.rs create mode 100644 apps/auth-service/src/federation/tests/protocols.rs create mode 100644 apps/auth-service/src/federation/tests/sign_in.rs create mode 100644 apps/auth-service/src/federation/tests/signup.rs delete mode 100644 apps/auth-service/src/oidc/tests.rs create mode 100644 apps/auth-service/src/oidc/tests/app_removal.rs create mode 100644 apps/auth-service/src/oidc/tests/authorization.rs create mode 100644 apps/auth-service/src/oidc/tests/logout.rs create mode 100644 apps/auth-service/src/oidc/tests/mod.rs create mode 100644 apps/auth-service/src/oidc/tests/protocol.rs create mode 100644 apps/auth-service/src/oidc/tests/pushed.rs create mode 100644 apps/auth-service/src/oidc/tests/sdk_client.rs create mode 100644 apps/auth-service/src/oidc/tests/sdk_routes.rs create mode 100644 apps/auth-service/src/oidc/tests/step_up.rs create mode 100644 apps/auth-service/src/oidc/tests/tokens.rs delete mode 100644 apps/auth-service/src/passkey/tests.rs create mode 100644 apps/auth-service/src/passkey/tests/confirmation.rs create mode 100644 apps/auth-service/src/passkey/tests/counters.rs create mode 100644 apps/auth-service/src/passkey/tests/mod.rs create mode 100644 apps/auth-service/src/passkey/tests/registration.rs create mode 100644 apps/auth-service/src/passkey/tests/related_pages.rs create mode 100644 apps/auth-service/src/passkey/tests/sign_in.rs create mode 100644 apps/auth-service/src/passkey/tests/telemetry.rs create mode 100644 apps/auth-service/src/passkey/tests/validation.rs delete mode 100644 apps/auth-service/src/recovery/tests.rs create mode 100644 apps/auth-service/src/recovery/tests/enroll.rs create mode 100644 apps/auth-service/src/recovery/tests/mod.rs create mode 100644 apps/auth-service/src/recovery/tests/probation.rs create mode 100644 apps/auth-service/src/recovery/tests/start.rs create mode 100644 apps/auth-service/src/recovery/tests/undo.rs delete mode 100644 apps/auth-service/src/security/tests.rs create mode 100644 apps/auth-service/src/security/tests/caching.rs create mode 100644 apps/auth-service/src/security/tests/forwarding.rs create mode 100644 apps/auth-service/src/security/tests/mod.rs create mode 100644 apps/auth-service/src/security/tests/origins.rs create mode 100644 apps/auth-service/src/security/tests/rate_limits.rs create mode 100644 apps/auth-service/src/security/tests/sessions.rs diff --git a/apps/auth-service/src/admin/tests.rs b/apps/auth-service/src/admin/tests.rs deleted file mode 100644 index c193dbc8d..000000000 --- a/apps/auth-service/src/admin/tests.rs +++ /dev/null @@ -1,1091 +0,0 @@ -//! Database-backed administration scenarios: who may run each operation, and -//! what it changes. - -use super::*; -use crate::AuditKeys; -use crate::config::LinkKeys; -use crate::deletion::DeletionError; -use crate::handles::HandlesError; -use crate::recovery::RecoveryLinks; -use crate::security::{CONFIRMATION_MAX_AGE, RequestContext, Session}; -use crate::tests::until_blocked; -use chrono::{Duration, Utc}; -use piquel_common::{ - AccountStatus, AuthenticationMethod, DeliveryId, Handle, HandleError, Personal, SessionId, - TokenId, UserId, - admin::EventSearch, - config::Origin, - events::{DomainEvent, RevocationReason}, - protocol::{claims::Acr, step_up::StepUpRequirement}, -}; -use piquel_crypto::Secret; -use piquel_repository::{ - Channel, Database, DatabaseConfig, DatabaseError, DatabaseTransaction, DeliveryStatus, - EventFilter, InsertUser, NewDelivery, -}; -use serde_json::json; -use std::mem::discriminant; - -/// A scenario account and its signed-in session. -#[derive(Clone, Copy)] -pub(crate) struct Account { - /// The account. - pub(crate) user_id: UserId, - /// Its session. - pub(crate) session_id: SessionId, -} - -impl Account { - /// Signs the account's session out in `tx`, as its browser would. - async fn sign_out(self, tx: &mut DatabaseTransaction<'_>) { - crate::tests::sign_out(tx, self.user_id, self.session_id) - .await - .expect("sign out"); - } -} - -/// The test database the scenarios run on. The shared account settings' and the -/// recoveries' tests use it too. -pub(crate) struct Harness { - /// The scenario database. - pub(crate) database: Database, -} - -impl Harness { - /// Connects to the migrated test database. - pub(crate) async fn new() -> Self { - let database = Database::connect(Self::config()).await.expect("database"); - database.run_migrations().await.expect("migrations"); - Self { database } - } - - /// Connects to a schema of its own, for a scenario that must know every - /// administrator, which the shared database's other tests keep adding. - async fn isolated() -> Self { - let database = Database::isolated(Self::config()) - .await - .expect("isolated database"); - Self { database } - } - - /// The test database's configuration. - fn config() -> DatabaseConfig { - let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") - .required() - .expect("TEST_DATABASE_URL must name a disposable PostgreSQL database"); - DatabaseConfig::new(&url, 5, std::time::Duration::from_secs(5)).expect("config") - } - - /// Creates an account with the handle `handle`, without a session. - async fn named(&self, handle: &str) -> UserId { - let user_id = UserId::new(); - self.database - .users() - .insert(&InsertUser { - id: user_id, - handle: Handle::parse(handle).expect("handle"), - display_name: "Admin test".into(), - }) - .await - .expect("user"); - user_id - } - - /// Creates an account signed in with a passkey. - pub(crate) async fn account(&self) -> Account { - self.signed_in(AuthenticationMethod::Passkey).await - } - - /// Creates an account signed in by `method`. - pub(crate) async fn signed_in(&self, method: AuthenticationMethod) -> Account { - let suffix = TokenId::new().to_string(); - let user_id = self.named(&format!("admin-{}", &suffix[24..])).await; - let mut tx = self.database.begin().await.expect("transaction"); - let secret = Session::create(&mut tx, RequestContext::TEST, user_id, method.into()) - .await - .expect("session"); - let session_id = tx - .sessions() - .find_active_by_browser_secret(secret.digest().as_bytes()) - .await - .expect("lookup") - .expect("session") - .id; - tx.commit().await.expect("commit"); - Account { - user_id, - session_id, - } - } - - /// The service under test. - fn service(&self) -> AdminService { - AdminService::new(self.database.clone(), true) - } - - /// Creates an administrator, granted by the CLI. - pub(crate) async fn admin(&self) -> Account { - let account = self.account().await; - self.grant(account).await - } - - /// Makes `account` an administrator, from the CLI. - pub(crate) async fn grant(&self, account: Account) -> Account { - self.service() - .grant_administrator(&cli(), account.user_id) - .await - .expect("grant"); - account - } - - /// The kinds of the events concerning `user_id`, newest first. - async fn events(&self, user_id: UserId) -> Vec { - self.database - .events() - .history_for_user(user_id, 100) - .await - .expect("history") - .into_iter() - .map(|stored| stored.event.known().cloned().expect("a known event")) - .collect() - } -} - -/// The operator of CLI-side changes. -pub(crate) fn cli() -> Operator { - Operator::Cli { - os_user: "tester".into(), - host: "test".into(), - } -} - -/// Auth's origin, which invitations link to. -fn origin() -> Origin { - "https://auth.piquel.fr".parse().expect("origin") -} - -/// `admin` signed in to the dashboard, as its session cookie finds them, with a -/// passkey confirmation of the dashboard at `confirmed_at`. -pub(crate) fn operator(admin: Account, confirmed_at: chrono::DateTime) -> Operator { - Operator::Admin(AdminSession { - user_id: admin.user_id, - session_id: admin.session_id, - confirmed_at: Some(confirmed_at), - context: RequestContext::TEST, - }) -} - -/// A reason any change accepts. -fn reason(text: &str) -> Reason { - Reason::parse(text.into()).expect("reason") -} - -/// Disabling an account ends its sessions at once and records why; enabling it -/// restores it, and both show in the events, attributed to the administrator. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn disabling_ends_sessions_and_is_recorded() { - let capture = piquel_telemetry::Telemetry::capture(crate::TELEMETRY_FILTER); - let harness = Harness::new().await; - let service = harness.service(); - let admin = harness.admin().await; - let user = harness.account().await; - let administrator = operator(admin, Utc::now()); - assert!(matches!( - Reason::parse(String::new()), - Err(AdminError::InvalidReason) - )); - service - .disable_user(&administrator, user.user_id, reason("Spam")) - .await - .expect("disable"); - let stored = harness - .database - .users() - .find_by_id(user.user_id) - .await - .expect("lookup") - .expect("user"); - assert_eq!(stored.status, AccountStatus::Disabled); - let id = admin.user_id.to_string(); - assert!( - capture.logs().iter().any(|log| { - let has = |key: &str, value: &str| { - log.attributes_iter().any(|(name, logged)| { - name.as_str() == key && format!("{logged:?}").contains(value) - }) - }; - has("event.kind", "account_disabled") && has("event.administrator", &id) - }), - "the disablement's log line names its administrator" - ); - assert!( - harness - .database - .sessions() - .find_by_id(user.session_id) - .await - .expect("lookup") - .expect("session") - .revoked_at - .is_some() - ); - service - .enable_user(&administrator, user.user_id) - .await - .expect("enable"); - assert_eq!( - harness.events(user.user_id).await[..3], - [ - DomainEvent::AccountEnabled {}, - DomainEvent::SessionRevoked { - session_id: user.session_id, - reason: RevocationReason::AccountDisabled, - }, - DomainEvent::AccountDisabled { - reason: Personal::Value("Spam".into()), - }, - ] - ); - let page = service - .events( - &administrator, - EventSearch { - user: Some(user.user_id), - kind: Some("account_disabled".into()), - page: None, - }, - ) - .await - .expect("events"); - assert_eq!(page.events[0].actor["user_id"], id); - assert_eq!( - page.events[0].event["data"]["reason"], - json!({"$personal": "Spam"}) - ); -} - -/// A handle rename records its reason with the change, as personal data the -/// owner sees in their history. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn handle_renames_record_their_reason() { - let harness = Harness::new().await; - let suffix = &TokenId::new().to_string()[24..]; - let account = harness.named(&format!("before-{suffix}")).await; - let after = Handle::parse(&format!("after-{suffix}")).expect("handle"); - harness - .service() - .rename_handle(&cli(), account, after, reason("Impersonation"), false) - .await - .expect("rename"); - let latest = harness.database.events().history_for_user(account, 1).await; - let latest = latest.expect("history"); - assert_eq!(latest[0].reason.as_deref(), Some("Impersonation")); -} - -/// Operators rename without the cooldown, but not to a taken, retired, look-alike, -/// reserved or unchanged handle. A released handle stays its former owner's until -/// an operator releases it; `handle check` lists reserved handles operators assign. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn operators_rename_and_release_handles() { - let harness = Harness::new().await; - let service = harness.service(); - let suffix = &TokenId::new().to_string()[24..]; - let handle = |name: &str| Handle::parse(&format!("{name}-{suffix}")).expect("handle"); - let first = harness.named(handle("first").as_str()).await; - let second = harness.named(handle("second").as_str()).await; - let rename = |user, handle: Handle, allow_reserved| { - let service = service.clone(); - async move { - service - .rename_handle(&cli(), user, handle, reason("Renamed"), allow_reserved) - .await - } - }; - let refused = |result: Result<(), AdminError>| match result { - Err(AdminError::Handle(error)) => error, - other => panic!("not a handle refusal: {other:?}"), - }; - assert!(matches!( - refused(rename(second, handle("first"), false).await), - HandlesError::Taken - )); - assert!(matches!( - refused(rename(second, Handle::parse(&format!("f1rst{suffix}")).expect("handle"), false).await), - HandlesError::Confusable(other) if other == handle("first") - )); - assert!(matches!( - refused(rename(second, Handle::parse("adm1n").expect("handle"), false).await), - HandlesError::Refused(HandleError::Reserved(_)) - )); - assert!(matches!( - refused(rename(second, handle("second"), false).await), - HandlesError::Current - )); - rename(second, handle("renamed"), false) - .await - .expect("rename"); - let renamed = harness - .database - .users() - .find_by_id(second) - .await - .expect("lookup") - .expect("user"); - assert_eq!(renamed.handle, handle("renamed")); - assert_eq!(renamed.profile_version, 2); - assert_eq!( - harness.events(second).await[..1], - [DomainEvent::HandleChanged { - old: Personal::Value(handle("second").to_string()), - new: Personal::Value(handle("renamed")), - }] - ); - // The old handle stays the second account's: the first cannot take it, but - // its owner can, at once, as operators skip the cooldown. - assert!(matches!( - refused(rename(first, handle("second"), false).await), - HandlesError::Retired - )); - rename(second, handle("second"), false) - .await - .expect("reclaim"); - assert!(matches!( - service.release_handle(&cli(), handle("second")).await, - Err(AdminError::HandleNotReleased) - )); - service - .release_handle(&cli(), handle("renamed")) - .await - .expect("release"); - assert_eq!( - harness.events(second).await[..1], - [DomainEvent::HandleReleased { - handle: Personal::Value(handle("renamed")), - }] - ); - rename(first, handle("renamed"), false) - .await - .expect("a released handle is free"); - // A reserved handle is listed while an account holds it. - let reserved = Handle::parse("piquel").expect("handle"); - let listed = || async { - service - .check_handles(&cli()) - .await - .expect("check") - .into_iter() - .any(|problem| problem.user_id == first) - }; - rename(first, reserved.clone(), true) - .await - .expect("reserved rename"); - assert!(listed().await); - rename(first, handle("first"), false) - .await - .expect("reclaim"); - assert!(!listed().await); - service - .release_handle(&cli(), reserved) - .await - .expect("release"); -} - -/// An event a newer release wrote, of a kind this one does not know, is listed -/// with its kind, version and data rather than failing the page. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn events_a_newer_release_wrote_are_listed() { - let harness = Harness::new().await; - let admin = harness.admin().await; - let user = harness.account().await; - let data = json!({"client_id": "deleted"}); - harness - .database - .events() - .insert_written_elsewhere(user.user_id, "from_a_newer_release", 1, &data) - .await - .expect("event"); - let filter = EventSearch { - user: Some(user.user_id), - ..EventSearch::default() - }; - let page = harness - .service() - .events(&operator(admin, Utc::now()), filter) - .await - .expect("events"); - assert_eq!( - page.events[0].event, - json!({"kind": "from_a_newer_release", "version": 1, "data": data}) - ); -} - -/// Administrator accounts are out of the dashboard's reach until their rights -/// are revoked, and nobody grants or revokes their own rights there. A -/// revocation applies to the revoked administrator's next request. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn administrators_are_protected_until_revoked() { - let harness = Harness::new().await; - let service = harness.service(); - let admin = harness.admin().await; - let other = harness.account().await; - let (by_admin, by_other) = (operator(admin, Utc::now()), operator(other, Utc::now())); - service - .grant_administrator(&by_admin, other.user_id) - .await - .expect("grant"); - service - .search_users(&by_other, "", None) - .await - .expect("the new administrator reads"); - let refused = service - .disable_user(&by_admin, other.user_id, reason("Compromised")) - .await; - assert!( - matches!(refused, Err(AdminError::AdministratorTarget)), - "{refused:?}" - ); - let refused = service.revoke_administrator(&by_admin, admin.user_id).await; - assert!(matches!(refused, Err(AdminError::OwnRights)), "{refused:?}"); - // Refused before any lock, so a grant queued behind the caller's own - // revocation cannot restore their rights. - let refused = service.grant_administrator(&by_admin, admin.user_id).await; - assert!(matches!(refused, Err(AdminError::OwnRights)), "{refused:?}"); - service - .revoke_administrator(&by_admin, other.user_id) - .await - .expect("revoke"); - let refused = service.search_users(&by_other, "", None).await; - assert!( - matches!(refused, Err(AdminError::NotAdministrator)), - "{refused:?}" - ); - service - .disable_user(&by_admin, other.user_id, reason("Compromised")) - .await - .expect("disable"); - assert_eq!( - harness.events(other.user_id).await[2..4], - [ - DomainEvent::AdministratorRevoked {}, - DomainEvent::AdministratorGranted {}, - ][..] - ); -} - -/// An invitation link works until an administrator revokes it, which also ends -/// its expiry, for the previous release; revoking it again finds nothing. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn revoked_invitations_cannot_be_redeemed() { - let harness = Harness::new().await; - let service = harness.service(); - let admin = operator(harness.admin().await, Utc::now()); - let created = service - .create_invitation(&admin, &origin(), "24h".parse().expect("expiry")) - .await - .expect("invitation"); - assert_eq!(created.url.path(), crate::routes::page::REGISTER); - let (_, encoded) = created - .url - .query_pairs() - .find(|(name, _)| name == "invitation") - .expect("invitation secret"); - let digest = Secret::parse(&encoded).expect("secret").digest(); - let active = || harness.database.security(); - assert!( - active() - .invitation_active(digest.as_bytes()) - .await - .expect("lookup") - ); - service - .revoke_invitation(&admin, created.id) - .await - .expect("revoke"); - assert!( - !active() - .invitation_active(digest.as_bytes()) - .await - .expect("lookup") - ); - let listed = service.list_invitations(&admin).await.expect("list"); - let revoked = listed - .iter() - .find(|listed| listed.id == created.id) - .expect("revoked invitation"); - assert!(Some(revoked.expires_at) <= revoked.revoked_at); - let again = service.revoke_invitation(&admin, created.id).await; - assert!( - matches!(again, Err(AdminError::InvitationNotFound)), - "{again:?}" - ); -} - -/// A mutation checks its caller's confirmation after its last write: one admitted -/// just inside the window, that then waited for a logout holding the target's -/// session, is refused with the step-up and changes nothing. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn mutations_recheck_the_confirmation_after_waiting() { - let harness = Harness::new().await; - let admin = harness.admin().await; - let user = harness.account().await; - let auth_time = Utc::now() - Duration::seconds(298); - let mut logout = harness.database.begin().await.expect("transaction"); - user.sign_out(&mut logout).await; - let service = harness.service(); - let reason = reason("Spam"); - let operator = operator(admin, auth_time); - let (result, ()) = tokio::join!( - service.disable_user(&operator, user.user_id, reason), - async { - until_blocked(&mut logout, 1).await; - let expired = auth_time + Duration::seconds(301) - Utc::now(); - tokio::time::sleep(expired.to_std().unwrap_or_default()).await; - logout.commit().await.expect("logout"); - } - ); - assert!( - matches!(result, Err(AdminError::StepUpRequired(_))), - "{result:?}" - ); - let stored = harness - .database - .users() - .find_by_id(user.user_id) - .await - .expect("lookup") - .expect("user"); - assert_eq!(stored.status, AccountStatus::Active); -} - -/// A mutation waiting for its target holds no lock of its caller's, so a sign-in -/// that locks the target's account and then revokes the caller's session, as -/// switching accounts does, finishes first. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn waiting_mutations_hold_no_caller_locks() { - let harness = Harness::new().await; - let admin = harness.admin().await; - let user = harness.account().await; - let mut switch = harness.database.begin().await.expect("transaction"); - switch - .users() - .find_active_by_id_for_update(user.user_id) - .await - .expect("target lock"); - let service = harness.service(); - let reason = reason("Spam"); - let operator = operator(admin, Utc::now()); - let (result, ()) = tokio::join!( - service.disable_user(&operator, user.user_id, reason), - async { - until_blocked(&mut switch, 1).await; - // The switch revokes the caller's session without a deadlock. - admin.sign_out(&mut switch).await; - switch.commit().await.expect("commit"); - } - ); - assert!( - matches!(result, Err(AdminError::SessionEnded)), - "{result:?}" - ); -} - -/// A mutation never waits for its caller's session, which the caller's own -/// sign-in or social linking may hold while it waits for the mutation's locks. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn mutations_never_wait_for_the_callers_session() { - let harness = Harness::new().await; - let admin = harness.admin().await; - let user = harness.account().await; - let mut linking = harness.database.begin().await.expect("transaction"); - linking - .sessions() - .find_active_by_id_for_update(admin.session_id) - .await - .expect("caller session lock"); - let reason = reason("Spam"); - let disabled = tokio::time::timeout( - std::time::Duration::from_secs(5), - harness - .service() - .disable_user(&operator(admin, Utc::now()), user.user_id, reason), - ) - .await - .expect("the mutation does not wait for the caller's session"); - assert!(disabled.is_ok(), "{disabled:?}"); - linking.rollback().await.expect("rollback"); -} - -/// Revoking an invitation that a signup is redeeming waits for the signup, which -/// may end the administrator's session as it signs the new account in on the -/// same browser. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn invitation_revocation_waits_for_signup() { - let harness = Harness::new().await; - let admin = harness.admin().await; - let service = harness.service(); - let invitation = service - .create_invitation(&cli(), &origin(), InviteExpiry::default()) - .await - .expect("invitation"); - let (_, encoded) = invitation - .url - .query_pairs() - .find(|(name, _)| name == "invitation") - .expect("invitation secret"); - let digest = piquel_crypto::Secret::parse(&encoded) - .expect("secret") - .digest(); - let mut signup = harness.database.begin().await.expect("transaction"); - assert!( - signup - .security() - .redeem_invitation(digest.as_bytes()) - .await - .expect("redeem") - ); - let operator = operator(admin, Utc::now()); - let (result, ()) = tokio::join!(service.revoke_invitation(&operator, invitation.id), async { - until_blocked(&mut signup, 1).await; - // The signup revokes the browser's session without a deadlock. - admin.sign_out(&mut signup).await; - signup.commit().await.expect("signup"); - }); - assert!( - matches!(result, Err(AdminError::InvitationNotFound)), - "{result:?}" - ); -} - -/// Two administrators acting on each other at once are both refused, rather than -/// deadlocking on each other's account lock. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn administrators_acting_on_each_other_are_refused() { - let harness = Harness::new().await; - let service = harness.service(); - let (a, b) = (harness.admin().await, harness.admin().await); - for _ in 0..10 { - let disable = |by: Account, target: Account| { - let service = service.clone(); - async move { - let by = operator(by, Utc::now()); - service - .disable_user(&by, target.user_id, reason("Rogue")) - .await - } - }; - let (first, second) = tokio::join!(disable(a, b), disable(b, a)); - for refused in [first, second] { - assert!( - matches!(refused, Err(AdminError::AdministratorTarget)), - "{refused:?}" - ); - } - } -} - -/// Nothing, the CLI included, revokes, disables or deletes the last active -/// administrator; a disabled administrator does not count. Two such changes -/// queued on the administrator lock cannot both pass: the second sees the first. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn the_last_active_administrator_stays() { - let harness = Harness::isolated().await; - let (service, cli) = (harness.service(), cli()); - let (a, b) = (harness.admin().await, harness.admin().await); - service - .disable_user(&cli, b.user_id, reason("Away")) - .await - .expect("disable"); - let last = AdminError::LastAdministrator; - let refusals = [ - ( - service.disable_user(&cli, a.user_id, reason("Away")).await, - &last, - "disable", - ), - ( - service - .schedule_deletion(&cli, a.user_id, reason("Away")) - .await, - &AdminError::Deletion(DeletionError::LastAdministrator), - "delete", - ), - ( - service.revoke_administrator(&cli, a.user_id).await, - &last, - "revoke", - ), - ]; - for (refused, expected, case) in refusals { - assert_refused(&refused.expect_err(case), expected, case); - } - - service.enable_user(&cli, b.user_id).await.expect("enable"); - let mut held = harness.database.begin().await.expect("transaction"); - held.administrators().lock().await.expect("lock"); - let (disabled, revoked, ()) = tokio::join!( - service.disable_user(&cli, a.user_id, reason("Away")), - service.revoke_administrator(&cli, b.user_id), - async { - until_blocked(&mut held, 2).await; - held.commit().await.expect("commit"); - } - ); - assert!( - matches!( - (&disabled, &revoked), - (Ok(()), Err(AdminError::LastAdministrator)) - | (Err(AdminError::LastAdministrator), Ok(())) - ), - "{disabled:?}, {revoked:?}" - ); -} - -/// Production's committed audit keys. -fn committed_keys() -> AuditKeys { - AuditKeys::committed(&"https://auth.piquel.fr".parse().expect("origin")).expect("keys") -} - -impl AdminOperation { - /// Runs the service methods behind this operation as `operator`, if it reads, - /// with arguments that need not exist, since a read checks its operator before - /// anything else. `None` for a change, which checks its operator before it - /// commits. The match is exhaustive, so a new operation must say which it is. - async fn read( - self, - service: &AdminService, - operator: &Operator, - ) -> Option>> { - let (user, client) = (UserId::new(), "notes"); - Some(match self { - Self::SearchUsers => vec![service.search_users(operator, "", None).await.map(drop)], - Self::ViewUser => vec![ - service - .find_user(operator, &UserRef::Id(user)) - .await - .map(drop), - service.view_user(operator, user).await.map(drop), - ], - Self::ListInvitations => vec![service.list_invitations(operator).await.map(drop)], - Self::ListClients => vec![ - service.list_clients(operator).await.map(drop), - service.list_related_origins(operator).await.map(drop), - ], - Self::ViewClient => vec![ - service - .client_details(operator, &client.parse().expect("client ID")) - .await - .map(drop), - ], - Self::ListEvents => vec![ - service - .events(operator, EventSearch::default()) - .await - .map(drop), - ], - Self::ListAdministrators => vec![service.list_administrators(operator).await.map(drop)], - Self::CheckHandles => vec![service.check_handles(operator).await.map(drop)], - Self::ListDeliveries => vec![ - service - .list_deliveries(operator, None, None, 1) - .await - .map(drop), - ], - Self::VerifyAuditChain => vec![ - service - .verify_audit_chain(operator, &committed_keys()) - .await - .map(drop), - service - .audit_page(operator, &committed_keys(), None) - .await - .map(drop), - ], - // Pruning checks its operator before anything else too. - Self::PruneAuditChain => vec![ - service - .prune_audit_chain(operator, &committed_keys(), 1) - .await - .map(drop), - ], - Self::DisableUser - | Self::EnableUser - | Self::ScheduleDeletion - | Self::RestoreUser - | Self::PurgeUser - | Self::RevokeUserSessions - | Self::RevokeSession - | Self::CreateInvitation - | Self::RevokeInvitation - | Self::CreateClient - | Self::ApplyClient - | Self::UpdateClient - | Self::EnableClient - | Self::DisableClient - | Self::SuspendClient - | Self::UnsuspendClient - | Self::DeleteClient - | Self::RotateClientSecret - | Self::ApproveRelatedOrigin - | Self::RemoveRelatedOrigin - | Self::GrantAdministrator - | Self::RevokeAdministrator - | Self::RenameHandle - | Self::ReleaseHandle - | Self::RetryDelivery - | Self::CancelDelivery - | Self::RecoverAccount - | Self::UndoRecovery => return None, - }) - } -} - -impl Harness { - /// Three administrators who may no longer read, with the refusal each gets: - /// one whose rights were revoked, one whose session ended, and one whose - /// session signed in without a passkey. - pub(crate) async fn refused_readers(&self) -> [(Operator, AdminError); 3] { - let (revoked, ended) = (self.admin().await, self.admin().await); - let social = self - .grant(self.signed_in(AuthenticationMethod::Federation).await) - .await; - self.service() - .revoke_administrator(&cli(), revoked.user_id) - .await - .expect("revoke"); - let mut tx = self.database.begin().await.expect("transaction"); - ended.sign_out(&mut tx).await; - tx.commit().await.expect("commit"); - // Any passkey sign-in, however old, as every read requires. - let passkey = StepUpRequirement { - acr: Some(Acr::PhishingResistant), - max_age: None, - }; - [ - (operator(revoked, Utc::now()), AdminError::NotAdministrator), - (operator(ended, Utc::now()), AdminError::SessionEnded), - ( - operator(social, Utc::now()), - AdminError::StepUpRequired(passkey), - ), - ] - } -} - -/// Asserts that `refused` is `expected`: the same variant and, for a step-up, the -/// same requirement. `case` names the scenario in a failure. -pub(crate) fn assert_refused(refused: &AdminError, expected: &AdminError, case: &str) { - match (refused, expected) { - (AdminError::StepUpRequired(actual), AdminError::StepUpRequired(expected)) => { - assert_eq!(actual, expected, "{case}"); - } - _ => assert_eq!( - discriminant(refused), - discriminant(expected), - "{case}: {refused:?}" - ), - } -} - -/// Every read checks its operator itself, as the dashboard calls the service -/// in-process: an administrator whose rights were revoked, whose session ended, -/// or whose session signed in without a passkey reads nothing. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn every_read_checks_its_administrator() { - let harness = Harness::new().await; - let service = harness.service(); - for (operator, refusal) in harness.refused_readers().await { - for read in AdminOperation::ALL { - let Some(results) = read.read(&service, &operator).await else { - continue; - }; - for result in results { - assert_refused( - &result.expect_err("refused"), - &refusal, - &format!("{read:?}"), - ); - } - } - } -} - -/// A delivery no worker sends, which the tests only retry and cancel. -struct Unsent; - -impl Channel for Unsent { - const NAME: &'static str = "test_admin_unsent"; - type Recipient = (); - type Payload = (); - - fn deliveries( - _: &DomainEvent, - _: Option, - _: &mut DatabaseTransaction<'_>, - ) -> impl Future>, DatabaseError>> + Send { - std::future::ready(Ok(vec![])) - } -} - -/// Retrying and cancelling a delivery check their administrator as every change -/// does, before committing: one whose rights were revoked, or whose confirmation -/// is stale, leaves the delivery as it was. A permitted change is recorded, since -/// cancelling one can hold back a notice to a user. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn delivery_changes_check_and_record_their_administrator() { - let harness = Harness::new().await; - let service = harness.service(); - let admin = harness.admin().await; - let revoked = harness.admin().await; - service - .revoke_administrator(&cli(), revoked.user_id) - .await - .expect("revoke"); - let stale = Utc::now() - Duration::minutes(10); - let step_up = StepUpRequirement::passkey_within(CONFIRMATION_MAX_AGE); - let queue = async || { - let delivery = NewDelivery:: { - destination: "https://receiver.example".into(), - recipient: (), - payload: (), - ordering_key: None, - }; - harness - .database - .deliveries() - .insert(None, delivery) - .await - .expect("insert") - }; - let status = async |id: DeliveryId| { - let listed = harness - .database - .deliveries() - .list(None, Some(Unsent::NAME), 1000) - .await; - let listed = listed.expect("list"); - listed - .into_iter() - .find(|delivery| delivery.id == id) - .expect("delivery") - .status - }; - let (pending, cancelled) = (queue().await, queue().await); - harness - .database - .deliveries() - .cancel(cancelled) - .await - .expect("cancel"); - for (operator, refusal) in [ - (operator(revoked, Utc::now()), AdminError::NotAdministrator), - (operator(admin, stale), AdminError::StepUpRequired(step_up)), - ] { - let refused = service - .cancel_delivery(&operator, pending) - .await - .expect_err("cancel"); - assert_refused(&refused, &refusal, "cancel"); - let refused = service - .retry_delivery(&operator, cancelled) - .await - .expect_err("retry"); - assert_refused(&refused, &refusal, "retry"); - } - assert_eq!(status(pending).await, DeliveryStatus::Pending); - assert_eq!(status(cancelled).await, DeliveryStatus::Cancelled); - - let admin = operator(admin, Utc::now()); - service - .cancel_delivery(&admin, pending) - .await - .expect("cancel"); - service - .retry_delivery(&admin, cancelled) - .await - .expect("retry"); - assert_eq!(status(pending).await, DeliveryStatus::Cancelled); - assert_eq!(status(cancelled).await, DeliveryStatus::Pending); - for (kind, delivery_id) in [ - ("delivery_cancelled", pending), - ("delivery_retried", cancelled), - ] { - let filter = EventFilter { - kind: Some(kind.into()), - ..EventFilter::default() - }; - let events = harness - .database - .events() - .list(&filter, 100) - .await - .expect("events"); - let recorded = events - .iter() - .find(|stored| { - matches!( - stored.event.known(), - Some(DomainEvent::DeliveryCancelled { delivery_id: id } - | DomainEvent::DeliveryRetried { delivery_id: id }) if *id == delivery_id - ) - }) - .unwrap_or_else(|| panic!("{kind} recorded")); - assert_eq!(recorded.actor, admin.context().actor, "{kind}"); - } -} - -/// Nobody is made an administrator while a recovery of the account can still be -/// undone, not even from the CLI: granted during its probation, the rights would -/// go live for whoever used its link once it settles. Once support undid it, -/// nothing is left to refuse. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn no_grant_while_a_recovery_can_be_undone() { - let harness = Harness::new().await; - let admin = harness.admin().await; - let target = harness.account().await.user_id; - let links = RecoveryLinks::new(origin(), LinkKeys::generate()); - let reason = || reason("Lost every passkey"); - let service = harness.service(); - service - .recover_account(&cli(), target, reason(), &links, None) - .await - .expect("recovery"); - - let refused = service - .grant_administrator(&operator(admin, Utc::now()), target) - .await; - assert!( - matches!(refused, Err(AdminError::GrantDuringRecovery)), - "the dashboard refuses" - ); - let refused = service.grant_administrator(&cli(), target).await; - assert!( - matches!(refused, Err(AdminError::GrantDuringRecovery)), - "the CLI too" - ); - let granted = harness.database.administrators().contains(target).await; - assert!(!granted.expect("rights"), "not granted"); - - service - .undo_recovery(&cli(), target, reason()) - .await - .expect("support cancels the unused link"); - service - .grant_administrator(&cli(), target) - .await - .expect("granted once nothing can be undone"); -} diff --git a/apps/auth-service/src/admin/tests/accounts.rs b/apps/auth-service/src/admin/tests/accounts.rs new file mode 100644 index 000000000..c5a8f93cf --- /dev/null +++ b/apps/auth-service/src/admin/tests/accounts.rs @@ -0,0 +1,120 @@ +//! Disabling and enabling an account, and reading its event history. + +use super::*; +use piquel_common::events::RevocationReason; +use serde_json::json; + +/// Disabling an account ends its sessions at once and records why; enabling it +/// restores it, and both show in the events, attributed to the administrator. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn disabling_ends_sessions_and_is_recorded() { + let capture = piquel_telemetry::Telemetry::capture(crate::TELEMETRY_FILTER); + let harness = Harness::new().await; + let service = harness.service(); + let admin = harness.admin().await; + let user = harness.account().await; + let administrator = operator(admin, Utc::now()); + assert!(matches!( + Reason::parse(String::new()), + Err(AdminError::InvalidReason) + )); + service + .disable_user(&administrator, user.user_id, reason("Spam")) + .await + .expect("disable"); + let stored = harness + .database + .users() + .find_by_id(user.user_id) + .await + .expect("lookup") + .expect("user"); + assert_eq!(stored.status, AccountStatus::Disabled); + let id = admin.user_id.to_string(); + assert!( + capture.logs().iter().any(|log| { + let has = |key: &str, value: &str| { + log.attributes_iter().any(|(name, logged)| { + name.as_str() == key && format!("{logged:?}").contains(value) + }) + }; + has("event.kind", "account_disabled") && has("event.administrator", &id) + }), + "the disablement's log line names its administrator" + ); + assert!( + harness + .database + .sessions() + .find_by_id(user.session_id) + .await + .expect("lookup") + .expect("session") + .revoked_at + .is_some() + ); + service + .enable_user(&administrator, user.user_id) + .await + .expect("enable"); + assert_eq!( + harness.events(user.user_id).await[..3], + [ + DomainEvent::AccountEnabled {}, + DomainEvent::SessionRevoked { + session_id: user.session_id, + reason: RevocationReason::AccountDisabled, + }, + DomainEvent::AccountDisabled { + reason: Personal::Value("Spam".into()), + }, + ] + ); + let page = service + .events( + &administrator, + EventSearch { + user: Some(user.user_id), + kind: Some("account_disabled".into()), + page: None, + }, + ) + .await + .expect("events"); + assert_eq!(page.events[0].actor["user_id"], id); + assert_eq!( + page.events[0].event["data"]["reason"], + json!({"$personal": "Spam"}) + ); +} + +/// An event a newer release wrote, of a kind this one does not know, is listed +/// with its kind, version and data rather than failing the page. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn events_a_newer_release_wrote_are_listed() { + let harness = Harness::new().await; + let admin = harness.admin().await; + let user = harness.account().await; + let data = json!({"client_id": "deleted"}); + harness + .database + .events() + .insert_written_elsewhere(user.user_id, "from_a_newer_release", 1, &data) + .await + .expect("event"); + let filter = EventSearch { + user: Some(user.user_id), + ..EventSearch::default() + }; + let page = harness + .service() + .events(&operator(admin, Utc::now()), filter) + .await + .expect("events"); + assert_eq!( + page.events[0].event, + json!({"kind": "from_a_newer_release", "version": 1, "data": data}) + ); +} diff --git a/apps/auth-service/src/admin/tests/administrators.rs b/apps/auth-service/src/admin/tests/administrators.rs new file mode 100644 index 000000000..cbff86131 --- /dev/null +++ b/apps/auth-service/src/admin/tests/administrators.rs @@ -0,0 +1,189 @@ +//! Granting and revoking administrator rights, and the protections around them. + +use super::*; +use crate::config::LinkKeys; +use crate::deletion::DeletionError; +use crate::recovery::RecoveryLinks; + +/// Administrator accounts are out of the dashboard's reach until their rights +/// are revoked, and nobody grants or revokes their own rights there. A +/// revocation applies to the revoked administrator's next request. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn administrators_are_protected_until_revoked() { + let harness = Harness::new().await; + let service = harness.service(); + let admin = harness.admin().await; + let other = harness.account().await; + let (by_admin, by_other) = (operator(admin, Utc::now()), operator(other, Utc::now())); + service + .grant_administrator(&by_admin, other.user_id) + .await + .expect("grant"); + service + .search_users(&by_other, "", None) + .await + .expect("the new administrator reads"); + let refused = service + .disable_user(&by_admin, other.user_id, reason("Compromised")) + .await; + assert!( + matches!(refused, Err(AdminError::AdministratorTarget)), + "{refused:?}" + ); + let refused = service.revoke_administrator(&by_admin, admin.user_id).await; + assert!(matches!(refused, Err(AdminError::OwnRights)), "{refused:?}"); + // Refused before any lock, so a grant queued behind the caller's own + // revocation cannot restore their rights. + let refused = service.grant_administrator(&by_admin, admin.user_id).await; + assert!(matches!(refused, Err(AdminError::OwnRights)), "{refused:?}"); + service + .revoke_administrator(&by_admin, other.user_id) + .await + .expect("revoke"); + let refused = service.search_users(&by_other, "", None).await; + assert!( + matches!(refused, Err(AdminError::NotAdministrator)), + "{refused:?}" + ); + service + .disable_user(&by_admin, other.user_id, reason("Compromised")) + .await + .expect("disable"); + assert_eq!( + harness.events(other.user_id).await[2..4], + [ + DomainEvent::AdministratorRevoked {}, + DomainEvent::AdministratorGranted {}, + ][..] + ); +} + +/// Two administrators acting on each other at once are both refused, rather than +/// deadlocking on each other's account lock. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn administrators_acting_on_each_other_are_refused() { + let harness = Harness::new().await; + let service = harness.service(); + let (a, b) = (harness.admin().await, harness.admin().await); + for _ in 0..10 { + let disable = |by: Account, target: Account| { + let service = service.clone(); + async move { + let by = operator(by, Utc::now()); + service + .disable_user(&by, target.user_id, reason("Rogue")) + .await + } + }; + let (first, second) = tokio::join!(disable(a, b), disable(b, a)); + for refused in [first, second] { + assert!( + matches!(refused, Err(AdminError::AdministratorTarget)), + "{refused:?}" + ); + } + } +} + +/// Nothing, the CLI included, revokes, disables or deletes the last active +/// administrator; a disabled administrator does not count. Two such changes +/// queued on the administrator lock cannot both pass: the second sees the first. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn the_last_active_administrator_stays() { + let harness = Harness::isolated().await; + let (service, cli) = (harness.service(), cli()); + let (a, b) = (harness.admin().await, harness.admin().await); + service + .disable_user(&cli, b.user_id, reason("Away")) + .await + .expect("disable"); + let last = AdminError::LastAdministrator; + let refusals = [ + ( + service.disable_user(&cli, a.user_id, reason("Away")).await, + &last, + "disable", + ), + ( + service + .schedule_deletion(&cli, a.user_id, reason("Away")) + .await, + &AdminError::Deletion(DeletionError::LastAdministrator), + "delete", + ), + ( + service.revoke_administrator(&cli, a.user_id).await, + &last, + "revoke", + ), + ]; + for (refused, expected, case) in refusals { + assert_refused(&refused.expect_err(case), expected, case); + } + + service.enable_user(&cli, b.user_id).await.expect("enable"); + let mut held = harness.database.begin().await.expect("transaction"); + held.administrators().lock().await.expect("lock"); + let (disabled, revoked, ()) = tokio::join!( + service.disable_user(&cli, a.user_id, reason("Away")), + service.revoke_administrator(&cli, b.user_id), + async { + until_blocked(&mut held, 2).await; + held.commit().await.expect("commit"); + } + ); + assert!( + matches!( + (&disabled, &revoked), + (Ok(()), Err(AdminError::LastAdministrator)) + | (Err(AdminError::LastAdministrator), Ok(())) + ), + "{disabled:?}, {revoked:?}" + ); +} + +/// Nobody is made an administrator while a recovery of the account can still be +/// undone, not even from the CLI: granted during its probation, the rights would +/// go live for whoever used its link once it settles. Once support undid it, +/// nothing is left to refuse. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn no_grant_while_a_recovery_can_be_undone() { + let harness = Harness::new().await; + let admin = harness.admin().await; + let target = harness.account().await.user_id; + let links = RecoveryLinks::new(origin(), LinkKeys::generate()); + let reason = || reason("Lost every passkey"); + let service = harness.service(); + service + .recover_account(&cli(), target, reason(), &links, None) + .await + .expect("recovery"); + + let refused = service + .grant_administrator(&operator(admin, Utc::now()), target) + .await; + assert!( + matches!(refused, Err(AdminError::GrantDuringRecovery)), + "the dashboard refuses" + ); + let refused = service.grant_administrator(&cli(), target).await; + assert!( + matches!(refused, Err(AdminError::GrantDuringRecovery)), + "the CLI too" + ); + let granted = harness.database.administrators().contains(target).await; + assert!(!granted.expect("rights"), "not granted"); + + service + .undo_recovery(&cli(), target, reason()) + .await + .expect("support cancels the unused link"); + service + .grant_administrator(&cli(), target) + .await + .expect("granted once nothing can be undone"); +} diff --git a/apps/auth-service/src/admin/tests/deliveries.rs b/apps/auth-service/src/admin/tests/deliveries.rs new file mode 100644 index 000000000..991917e6b --- /dev/null +++ b/apps/auth-service/src/admin/tests/deliveries.rs @@ -0,0 +1,131 @@ +//! Retrying and cancelling deliveries. + +use super::*; +use crate::security::CONFIRMATION_MAX_AGE; +use piquel_common::DeliveryId; +use piquel_repository::{Channel, DatabaseError, DeliveryStatus, EventFilter, NewDelivery}; + +/// A delivery no worker sends, which the tests only retry and cancel. +struct Unsent; + +impl Channel for Unsent { + const NAME: &'static str = "test_admin_unsent"; + type Recipient = (); + type Payload = (); + + fn deliveries( + _: &DomainEvent, + _: Option, + _: &mut DatabaseTransaction<'_>, + ) -> impl Future>, DatabaseError>> + Send { + std::future::ready(Ok(vec![])) + } +} + +/// Retrying and cancelling a delivery check their administrator as every change +/// does, before committing: one whose rights were revoked, or whose confirmation +/// is stale, leaves the delivery as it was. A permitted change is recorded, since +/// cancelling one can hold back a notice to a user. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn delivery_changes_check_and_record_their_administrator() { + let harness = Harness::new().await; + let service = harness.service(); + let admin = harness.admin().await; + let revoked = harness.admin().await; + service + .revoke_administrator(&cli(), revoked.user_id) + .await + .expect("revoke"); + let stale = Utc::now() - Duration::minutes(10); + let step_up = StepUpRequirement::passkey_within(CONFIRMATION_MAX_AGE); + let queue = async || { + let delivery = NewDelivery:: { + destination: "https://receiver.example".into(), + recipient: (), + payload: (), + ordering_key: None, + }; + harness + .database + .deliveries() + .insert(None, delivery) + .await + .expect("insert") + }; + let status = async |id: DeliveryId| { + let listed = harness + .database + .deliveries() + .list(None, Some(Unsent::NAME), 1000) + .await; + let listed = listed.expect("list"); + listed + .into_iter() + .find(|delivery| delivery.id == id) + .expect("delivery") + .status + }; + let (pending, cancelled) = (queue().await, queue().await); + harness + .database + .deliveries() + .cancel(cancelled) + .await + .expect("cancel"); + for (operator, refusal) in [ + (operator(revoked, Utc::now()), AdminError::NotAdministrator), + (operator(admin, stale), AdminError::StepUpRequired(step_up)), + ] { + let refused = service + .cancel_delivery(&operator, pending) + .await + .expect_err("cancel"); + assert_refused(&refused, &refusal, "cancel"); + let refused = service + .retry_delivery(&operator, cancelled) + .await + .expect_err("retry"); + assert_refused(&refused, &refusal, "retry"); + } + assert_eq!(status(pending).await, DeliveryStatus::Pending); + assert_eq!(status(cancelled).await, DeliveryStatus::Cancelled); + + let admin = operator(admin, Utc::now()); + service + .cancel_delivery(&admin, pending) + .await + .expect("cancel"); + service + .retry_delivery(&admin, cancelled) + .await + .expect("retry"); + assert_eq!(status(pending).await, DeliveryStatus::Cancelled); + assert_eq!(status(cancelled).await, DeliveryStatus::Pending); + for (kind, delivery_id) in [ + ("delivery_cancelled", pending), + ("delivery_retried", cancelled), + ] { + let filter = EventFilter { + kind: Some(kind.into()), + ..EventFilter::default() + }; + let events = harness + .database + .events() + .list(&filter, 100) + .await + .expect("events"); + let recorded = events + .iter() + .find(|stored| { + matches!( + stored.event.known(), + Some(DomainEvent::DeliveryCancelled { delivery_id: id } + | DomainEvent::DeliveryRetried { delivery_id: id }) if *id == delivery_id + ) + }) + .unwrap_or_else(|| panic!("{kind} recorded")); + assert_eq!(recorded.actor, admin.context().actor, "{kind}"); + } +} diff --git a/apps/auth-service/src/admin/tests/handles.rs b/apps/auth-service/src/admin/tests/handles.rs new file mode 100644 index 000000000..a8e02ad2f --- /dev/null +++ b/apps/auth-service/src/admin/tests/handles.rs @@ -0,0 +1,133 @@ +//! Operators renaming, releasing and checking handles. + +use super::*; +use crate::handles::HandlesError; +use piquel_common::HandleError; + +/// A handle rename records its reason with the change, as personal data the +/// owner sees in their history. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn handle_renames_record_their_reason() { + let harness = Harness::new().await; + let suffix = &TokenId::new().to_string()[24..]; + let account = harness.named(&format!("before-{suffix}")).await; + let after = Handle::parse(&format!("after-{suffix}")).expect("handle"); + harness + .service() + .rename_handle(&cli(), account, after, reason("Impersonation"), false) + .await + .expect("rename"); + let latest = harness.database.events().history_for_user(account, 1).await; + let latest = latest.expect("history"); + assert_eq!(latest[0].reason.as_deref(), Some("Impersonation")); +} + +/// Operators rename without the cooldown, but not to a taken, retired, look-alike, +/// reserved or unchanged handle. A released handle stays its former owner's until +/// an operator releases it; `handle check` lists reserved handles operators assign. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn operators_rename_and_release_handles() { + let harness = Harness::new().await; + let service = harness.service(); + let suffix = &TokenId::new().to_string()[24..]; + let handle = |name: &str| Handle::parse(&format!("{name}-{suffix}")).expect("handle"); + let first = harness.named(handle("first").as_str()).await; + let second = harness.named(handle("second").as_str()).await; + let rename = |user, handle: Handle, allow_reserved| { + let service = service.clone(); + async move { + service + .rename_handle(&cli(), user, handle, reason("Renamed"), allow_reserved) + .await + } + }; + let refused = |result: Result<(), AdminError>| match result { + Err(AdminError::Handle(error)) => error, + other => panic!("not a handle refusal: {other:?}"), + }; + assert!(matches!( + refused(rename(second, handle("first"), false).await), + HandlesError::Taken + )); + assert!(matches!( + refused(rename(second, Handle::parse(&format!("f1rst{suffix}")).expect("handle"), false).await), + HandlesError::Confusable(other) if other == handle("first") + )); + assert!(matches!( + refused(rename(second, Handle::parse("adm1n").expect("handle"), false).await), + HandlesError::Refused(HandleError::Reserved(_)) + )); + assert!(matches!( + refused(rename(second, handle("second"), false).await), + HandlesError::Current + )); + rename(second, handle("renamed"), false) + .await + .expect("rename"); + let renamed = harness + .database + .users() + .find_by_id(second) + .await + .expect("lookup") + .expect("user"); + assert_eq!(renamed.handle, handle("renamed")); + assert_eq!(renamed.profile_version, 2); + assert_eq!( + harness.events(second).await[..1], + [DomainEvent::HandleChanged { + old: Personal::Value(handle("second").to_string()), + new: Personal::Value(handle("renamed")), + }] + ); + // The old handle stays the second account's: the first cannot take it, but + // its owner can, at once, as operators skip the cooldown. + assert!(matches!( + refused(rename(first, handle("second"), false).await), + HandlesError::Retired + )); + rename(second, handle("second"), false) + .await + .expect("reclaim"); + assert!(matches!( + service.release_handle(&cli(), handle("second")).await, + Err(AdminError::HandleNotReleased) + )); + service + .release_handle(&cli(), handle("renamed")) + .await + .expect("release"); + assert_eq!( + harness.events(second).await[..1], + [DomainEvent::HandleReleased { + handle: Personal::Value(handle("renamed")), + }] + ); + rename(first, handle("renamed"), false) + .await + .expect("a released handle is free"); + // A reserved handle is listed while an account holds it. + let reserved = Handle::parse("piquel").expect("handle"); + let listed = || async { + service + .check_handles(&cli()) + .await + .expect("check") + .into_iter() + .any(|problem| problem.user_id == first) + }; + rename(first, reserved.clone(), true) + .await + .expect("reserved rename"); + assert!(listed().await); + rename(first, handle("first"), false) + .await + .expect("reclaim"); + assert!(!listed().await); + service + .release_handle(&cli(), reserved) + .await + .expect("release"); +} diff --git a/apps/auth-service/src/admin/tests/invitations.rs b/apps/auth-service/src/admin/tests/invitations.rs new file mode 100644 index 000000000..82f41ca6a --- /dev/null +++ b/apps/auth-service/src/admin/tests/invitations.rs @@ -0,0 +1,95 @@ +//! Creating and revoking invitations. + +use super::*; +use piquel_crypto::Secret; + +/// An invitation link works until an administrator revokes it, which also ends +/// its expiry, for the previous release; revoking it again finds nothing. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn revoked_invitations_cannot_be_redeemed() { + let harness = Harness::new().await; + let service = harness.service(); + let admin = operator(harness.admin().await, Utc::now()); + let created = service + .create_invitation(&admin, &origin(), "24h".parse().expect("expiry")) + .await + .expect("invitation"); + assert_eq!(created.url.path(), crate::routes::page::REGISTER); + let (_, encoded) = created + .url + .query_pairs() + .find(|(name, _)| name == "invitation") + .expect("invitation secret"); + let digest = Secret::parse(&encoded).expect("secret").digest(); + let active = || harness.database.security(); + assert!( + active() + .invitation_active(digest.as_bytes()) + .await + .expect("lookup") + ); + service + .revoke_invitation(&admin, created.id) + .await + .expect("revoke"); + assert!( + !active() + .invitation_active(digest.as_bytes()) + .await + .expect("lookup") + ); + let listed = service.list_invitations(&admin).await.expect("list"); + let revoked = listed + .iter() + .find(|listed| listed.id == created.id) + .expect("revoked invitation"); + assert!(Some(revoked.expires_at) <= revoked.revoked_at); + let again = service.revoke_invitation(&admin, created.id).await; + assert!( + matches!(again, Err(AdminError::InvitationNotFound)), + "{again:?}" + ); +} + +/// Revoking an invitation that a signup is redeeming waits for the signup, which +/// may end the administrator's session as it signs the new account in on the +/// same browser. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn invitation_revocation_waits_for_signup() { + let harness = Harness::new().await; + let admin = harness.admin().await; + let service = harness.service(); + let invitation = service + .create_invitation(&cli(), &origin(), InviteExpiry::default()) + .await + .expect("invitation"); + let (_, encoded) = invitation + .url + .query_pairs() + .find(|(name, _)| name == "invitation") + .expect("invitation secret"); + let digest = piquel_crypto::Secret::parse(&encoded) + .expect("secret") + .digest(); + let mut signup = harness.database.begin().await.expect("transaction"); + assert!( + signup + .security() + .redeem_invitation(digest.as_bytes()) + .await + .expect("redeem") + ); + let operator = operator(admin, Utc::now()); + let (result, ()) = tokio::join!(service.revoke_invitation(&operator, invitation.id), async { + until_blocked(&mut signup, 1).await; + // The signup revokes the browser's session without a deadlock. + admin.sign_out(&mut signup).await; + signup.commit().await.expect("signup"); + }); + assert!( + matches!(result, Err(AdminError::InvitationNotFound)), + "{result:?}" + ); +} diff --git a/apps/auth-service/src/admin/tests/mod.rs b/apps/auth-service/src/admin/tests/mod.rs new file mode 100644 index 000000000..8a4ae3f70 --- /dev/null +++ b/apps/auth-service/src/admin/tests/mod.rs @@ -0,0 +1,190 @@ +//! Database-backed administration scenarios: who may run each operation, and +//! what it changes. + +use super::*; +use crate::security::{RequestContext, Session}; +use crate::tests::until_blocked; +use chrono::{Duration, Utc}; +use piquel_common::{ + AccountStatus, AuthenticationMethod, Handle, Personal, SessionId, TokenId, UserId, + admin::EventSearch, config::Origin, events::DomainEvent, protocol::step_up::StepUpRequirement, +}; +use piquel_repository::{Database, DatabaseConfig, DatabaseTransaction, InsertUser}; +use std::mem::discriminant; + +mod accounts; +mod administrators; +mod deliveries; +mod handles; +mod invitations; +mod mutations; +mod reads; + +/// A scenario account and its signed-in session. +#[derive(Clone, Copy)] +pub(crate) struct Account { + /// The account. + pub(crate) user_id: UserId, + /// Its session. + pub(crate) session_id: SessionId, +} + +impl Account { + /// Signs the account's session out in `tx`, as its browser would. + async fn sign_out(self, tx: &mut DatabaseTransaction<'_>) { + crate::tests::sign_out(tx, self.user_id, self.session_id) + .await + .expect("sign out"); + } +} + +/// The test database the scenarios run on. The shared account settings' and the +/// recoveries' tests use it too. +pub(crate) struct Harness { + /// The scenario database. + pub(crate) database: Database, +} + +impl Harness { + /// Connects to the migrated test database. + pub(crate) async fn new() -> Self { + let database = Database::connect(Self::config()).await.expect("database"); + database.run_migrations().await.expect("migrations"); + Self { database } + } + + /// Connects to a schema of its own, for a scenario that must know every + /// administrator, which the shared database's other tests keep adding. + async fn isolated() -> Self { + let database = Database::isolated(Self::config()) + .await + .expect("isolated database"); + Self { database } + } + + /// The test database's configuration. + fn config() -> DatabaseConfig { + let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") + .required() + .expect("TEST_DATABASE_URL must name a disposable PostgreSQL database"); + DatabaseConfig::new(&url, 5, std::time::Duration::from_secs(5)).expect("config") + } + + /// Creates an account with the handle `handle`, without a session. + async fn named(&self, handle: &str) -> UserId { + let user_id = UserId::new(); + self.database + .users() + .insert(&InsertUser { + id: user_id, + handle: Handle::parse(handle).expect("handle"), + display_name: "Admin test".into(), + }) + .await + .expect("user"); + user_id + } + + /// Creates an account signed in with a passkey. + pub(crate) async fn account(&self) -> Account { + self.signed_in(AuthenticationMethod::Passkey).await + } + + /// Creates an account signed in by `method`. + pub(crate) async fn signed_in(&self, method: AuthenticationMethod) -> Account { + let suffix = TokenId::new().to_string(); + let user_id = self.named(&format!("admin-{}", &suffix[24..])).await; + let mut tx = self.database.begin().await.expect("transaction"); + let secret = Session::create(&mut tx, RequestContext::TEST, user_id, method.into()) + .await + .expect("session"); + let session_id = tx + .sessions() + .find_active_by_browser_secret(secret.digest().as_bytes()) + .await + .expect("lookup") + .expect("session") + .id; + tx.commit().await.expect("commit"); + Account { + user_id, + session_id, + } + } + + /// The service under test. + fn service(&self) -> AdminService { + AdminService::new(self.database.clone(), true) + } + + /// Creates an administrator, granted by the CLI. + pub(crate) async fn admin(&self) -> Account { + let account = self.account().await; + self.grant(account).await + } + + /// Makes `account` an administrator, from the CLI. + pub(crate) async fn grant(&self, account: Account) -> Account { + self.service() + .grant_administrator(&cli(), account.user_id) + .await + .expect("grant"); + account + } + + /// The kinds of the events concerning `user_id`, newest first. + async fn events(&self, user_id: UserId) -> Vec { + self.database + .events() + .history_for_user(user_id, 100) + .await + .expect("history") + .into_iter() + .map(|stored| stored.event.known().cloned().expect("a known event")) + .collect() + } +} + +/// The operator of CLI-side changes. +pub(crate) fn cli() -> Operator { + Operator::Cli { + os_user: "tester".into(), + host: "test".into(), + } +} + +/// Auth's origin, which invitations link to. +fn origin() -> Origin { + "https://auth.piquel.fr".parse().expect("origin") +} + +/// `admin` signed in to the dashboard, as its session cookie finds them, with a +/// passkey confirmation of the dashboard at `confirmed_at`. +pub(crate) fn operator(admin: Account, confirmed_at: chrono::DateTime) -> Operator { + Operator::Admin(AdminSession { + user_id: admin.user_id, + session_id: admin.session_id, + confirmed_at: Some(confirmed_at), + context: RequestContext::TEST, + }) +} + +/// A reason any change accepts. +fn reason(text: &str) -> Reason { + Reason::parse(text.into()).expect("reason") +} + +/// Asserts that `refused` is `expected`: the same variant and, for a step-up, the +/// same requirement. `case` names the scenario in a failure. +pub(crate) fn assert_refused(refused: &AdminError, expected: &AdminError, case: &str) { + match (refused, expected) { + (AdminError::StepUpRequired(actual), AdminError::StepUpRequired(expected)) => { + assert_eq!(actual, expected, "{case}"); + } + _ => assert_eq!( + discriminant(refused), + discriminant(expected), + "{case}: {refused:?}" + ), + } +} diff --git a/apps/auth-service/src/admin/tests/mutations.rs b/apps/auth-service/src/admin/tests/mutations.rs new file mode 100644 index 000000000..15be0c07c --- /dev/null +++ b/apps/auth-service/src/admin/tests/mutations.rs @@ -0,0 +1,101 @@ +//! How a change waits on locks and rechecks its caller after waiting. + +use super::*; + +/// A mutation checks its caller's confirmation after its last write: one admitted +/// just inside the window, that then waited for a logout holding the target's +/// session, is refused with the step-up and changes nothing. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn mutations_recheck_the_confirmation_after_waiting() { + let harness = Harness::new().await; + let admin = harness.admin().await; + let user = harness.account().await; + let auth_time = Utc::now() - Duration::seconds(298); + let mut logout = harness.database.begin().await.expect("transaction"); + user.sign_out(&mut logout).await; + let service = harness.service(); + let reason = reason("Spam"); + let operator = operator(admin, auth_time); + let (result, ()) = tokio::join!( + service.disable_user(&operator, user.user_id, reason), + async { + until_blocked(&mut logout, 1).await; + let expired = auth_time + Duration::seconds(301) - Utc::now(); + tokio::time::sleep(expired.to_std().unwrap_or_default()).await; + logout.commit().await.expect("logout"); + } + ); + assert!( + matches!(result, Err(AdminError::StepUpRequired(_))), + "{result:?}" + ); + let stored = harness + .database + .users() + .find_by_id(user.user_id) + .await + .expect("lookup") + .expect("user"); + assert_eq!(stored.status, AccountStatus::Active); +} + +/// A mutation waiting for its target holds no lock of its caller's, so a sign-in +/// that locks the target's account and then revokes the caller's session, as +/// switching accounts does, finishes first. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn waiting_mutations_hold_no_caller_locks() { + let harness = Harness::new().await; + let admin = harness.admin().await; + let user = harness.account().await; + let mut switch = harness.database.begin().await.expect("transaction"); + switch + .users() + .find_active_by_id_for_update(user.user_id) + .await + .expect("target lock"); + let service = harness.service(); + let reason = reason("Spam"); + let operator = operator(admin, Utc::now()); + let (result, ()) = tokio::join!( + service.disable_user(&operator, user.user_id, reason), + async { + until_blocked(&mut switch, 1).await; + // The switch revokes the caller's session without a deadlock. + admin.sign_out(&mut switch).await; + switch.commit().await.expect("commit"); + } + ); + assert!( + matches!(result, Err(AdminError::SessionEnded)), + "{result:?}" + ); +} + +/// A mutation never waits for its caller's session, which the caller's own +/// sign-in or social linking may hold while it waits for the mutation's locks. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn mutations_never_wait_for_the_callers_session() { + let harness = Harness::new().await; + let admin = harness.admin().await; + let user = harness.account().await; + let mut linking = harness.database.begin().await.expect("transaction"); + linking + .sessions() + .find_active_by_id_for_update(admin.session_id) + .await + .expect("caller session lock"); + let reason = reason("Spam"); + let disabled = tokio::time::timeout( + std::time::Duration::from_secs(5), + harness + .service() + .disable_user(&operator(admin, Utc::now()), user.user_id, reason), + ) + .await + .expect("the mutation does not wait for the caller's session"); + assert!(disabled.is_ok(), "{disabled:?}"); + linking.rollback().await.expect("rollback"); +} diff --git a/apps/auth-service/src/admin/tests/reads.rs b/apps/auth-service/src/admin/tests/reads.rs new file mode 100644 index 000000000..1d1e40f32 --- /dev/null +++ b/apps/auth-service/src/admin/tests/reads.rs @@ -0,0 +1,160 @@ +//! Every read checks its administrator. + +use super::*; +use crate::AuditKeys; +use piquel_common::protocol::claims::Acr; + +/// Production's committed audit keys. +fn committed_keys() -> AuditKeys { + AuditKeys::committed(&"https://auth.piquel.fr".parse().expect("origin")).expect("keys") +} + +impl AdminOperation { + /// Runs the service methods behind this operation as `operator`, if it reads, + /// with arguments that need not exist, since a read checks its operator before + /// anything else. `None` for a change, which checks its operator before it + /// commits. The match is exhaustive, so a new operation must say which it is. + async fn read( + self, + service: &AdminService, + operator: &Operator, + ) -> Option>> { + let (user, client) = (UserId::new(), "notes"); + Some(match self { + Self::SearchUsers => vec![service.search_users(operator, "", None).await.map(drop)], + Self::ViewUser => vec![ + service + .find_user(operator, &UserRef::Id(user)) + .await + .map(drop), + service.view_user(operator, user).await.map(drop), + ], + Self::ListInvitations => vec![service.list_invitations(operator).await.map(drop)], + Self::ListClients => vec![ + service.list_clients(operator).await.map(drop), + service.list_related_origins(operator).await.map(drop), + ], + Self::ViewClient => vec![ + service + .client_details(operator, &client.parse().expect("client ID")) + .await + .map(drop), + ], + Self::ListEvents => vec![ + service + .events(operator, EventSearch::default()) + .await + .map(drop), + ], + Self::ListAdministrators => vec![service.list_administrators(operator).await.map(drop)], + Self::CheckHandles => vec![service.check_handles(operator).await.map(drop)], + Self::ListDeliveries => vec![ + service + .list_deliveries(operator, None, None, 1) + .await + .map(drop), + ], + Self::VerifyAuditChain => vec![ + service + .verify_audit_chain(operator, &committed_keys()) + .await + .map(drop), + service + .audit_page(operator, &committed_keys(), None) + .await + .map(drop), + ], + // Pruning checks its operator before anything else too. + Self::PruneAuditChain => vec![ + service + .prune_audit_chain(operator, &committed_keys(), 1) + .await + .map(drop), + ], + Self::DisableUser + | Self::EnableUser + | Self::ScheduleDeletion + | Self::RestoreUser + | Self::PurgeUser + | Self::RevokeUserSessions + | Self::RevokeSession + | Self::CreateInvitation + | Self::RevokeInvitation + | Self::CreateClient + | Self::ApplyClient + | Self::UpdateClient + | Self::EnableClient + | Self::DisableClient + | Self::SuspendClient + | Self::UnsuspendClient + | Self::DeleteClient + | Self::RotateClientSecret + | Self::ApproveRelatedOrigin + | Self::RemoveRelatedOrigin + | Self::GrantAdministrator + | Self::RevokeAdministrator + | Self::RenameHandle + | Self::ReleaseHandle + | Self::RetryDelivery + | Self::CancelDelivery + | Self::RecoverAccount + | Self::UndoRecovery => return None, + }) + } +} + +impl Harness { + /// Three administrators who may no longer read, with the refusal each gets: + /// one whose rights were revoked, one whose session ended, and one whose + /// session signed in without a passkey. + pub(crate) async fn refused_readers(&self) -> [(Operator, AdminError); 3] { + let (revoked, ended) = (self.admin().await, self.admin().await); + let social = self + .grant(self.signed_in(AuthenticationMethod::Federation).await) + .await; + self.service() + .revoke_administrator(&cli(), revoked.user_id) + .await + .expect("revoke"); + let mut tx = self.database.begin().await.expect("transaction"); + ended.sign_out(&mut tx).await; + tx.commit().await.expect("commit"); + // Any passkey sign-in, however old, as every read requires. + let passkey = StepUpRequirement { + acr: Some(Acr::PhishingResistant), + max_age: None, + }; + [ + (operator(revoked, Utc::now()), AdminError::NotAdministrator), + (operator(ended, Utc::now()), AdminError::SessionEnded), + ( + operator(social, Utc::now()), + AdminError::StepUpRequired(passkey), + ), + ] + } +} + +/// Every read checks its operator itself, as the dashboard calls the service +/// in-process: an administrator whose rights were revoked, whose session ended, +/// or whose session signed in without a passkey reads nothing. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn every_read_checks_its_administrator() { + let harness = Harness::new().await; + let service = harness.service(); + for (operator, refusal) in harness.refused_readers().await { + for read in AdminOperation::ALL { + let Some(results) = read.read(&service, &operator).await else { + continue; + }; + for result in results { + assert_refused( + &result.expect_err("refused"), + &refusal, + &format!("{read:?}"), + ); + } + } + } +} diff --git a/apps/auth-service/src/clients/tests.rs b/apps/auth-service/src/clients/tests.rs deleted file mode 100644 index f49ddafd7..000000000 --- a/apps/auth-service/src/clients/tests.rs +++ /dev/null @@ -1,1195 +0,0 @@ -//! Client changes reach running replicas on their next request, and each records -//! its event as made by whoever made it. Owners find and change only their own -//! clients, confirming what needs it, and a deletion leaves a tombstone without -//! deadlocking the token grants it revokes. -use super::*; -use crate::{ - account::{AccountError, AccountService, Owner}, - security::{Session, SessionError}, - tests::{ - Browser, Replicas, change, operator, refresh_grant, register, registration, replace, - sign_out, until_blocked, - }, -}; -use axum::{ - Router, - body::Body, - http::{Method, Request, StatusCode, header}, - response::Response, -}; -use base64::Engine; -use piquel_common::{ - AuthenticationMethod, TokenId, UserId, - clients::{AllowedScopes, RedirectUris}, - events::Actor, -}; -use piquel_crypto::Secret; -use piquel_repository::{Database, RefreshRotationError}; -use tokio::task::JoinHandle; -use tower::ServiceExt; - -/// An account, and the owner's operations on its clients, over the test database. -struct Account { - /// The scenario database. - database: Database, - /// The owner's operations. - service: AccountService, - /// A browser signed in to the account with a passkey, so confirmed. - browser: Browser, -} - -impl Account { - /// Creates an account over a migrated test database. - async fn new() -> Self { - let database = Replicas::database().await; - Self { - service: AccountService::new(database.clone()), - browser: Browser::new_account(&database).await, - database, - } - } - - /// The owner, as the browser signed in with a passkey shows them. - async fn owner(&self) -> Owner { - self.browser.owner(&self.database).await - } - - /// Signs another browser in to the account socially, which never confirms - /// with a passkey. - async fn social(&self) -> Browser { - let federation = AuthenticationMethod::Federation; - Browser::sign_in_with(&self.database, self.browser.user_id, federation).await - } - - /// Registers a client of `kind` calling back to `https://notes.example` as the - /// confirmed owner, and returns its ID. - async fn create(&self, kind: ClientKind) -> ClientId { - let origin = "https://notes.example"; - self.browser - .register_app(&self.database, kind, origin) - .await - } - - /// The owner's client `id`, as `owner` finds it. - async fn find(&self, owner: Owner, id: &ClientId) -> OwnedClient { - let found = self.service.owned_client(owner, id.as_str()).await; - found.expect("the owner's client") - } - - /// Makes `change` to client `id` as the owner, from a social session that a - /// passkey confirms while the change waits for the account lock, and returns - /// its result. - async fn confirmed_while_waiting( - &self, - id: &ClientId, - change: impl AsyncFnOnce(&OwnedClient) -> Result<(), AccountError>, - ) -> Result<(), AccountError> { - let stale = self.social().await; - let client = self.find(stale.owner(&self.database).await, id).await; - let mut holder = self.database.begin().await.expect("transaction"); - holder - .users() - .find_active_by_id_for_update(stale.user_id) - .await - .expect("lock") - .expect("account"); - let (result, ()) = tokio::join!(change(&client), async { - until_blocked(&mut holder, 1).await; - let session = holder.sessions().find_by_id(stale.session_id).await; - let session = session.expect("lookup").expect("session"); - let passkey = AuthenticationMethod::Passkey.into(); - Session::reauthenticate(&mut holder, &session, passkey) - .await - .expect("confirm"); - holder.commit().await.expect("commit"); - }); - result - } -} - -/// A public client and an account holding refresh grants to it, which the -/// deletion scenarios race a deletion against. -struct Granting { - /// The scenario database. - database: Database, - /// The client, which an operator manages. - client: ClientId, - /// The account, signed in. - user: Browser, -} - -impl Granting { - /// Registers the client over a migrated test database, and signs the account - /// in. - async fn new() -> Self { - let database = Replicas::database().await; - let client = registration(ClientKind::Public, "https://notes.example"); - register(&database, &client).await.expect("client"); - Self { - user: Browser::new_account(&database).await, - client: client.id, - database, - } - } - - /// Issues the refresh grant `family` to the client from the account's session, - /// and returns its first refresh token's ID and digest. - async fn grant(&self, family: TokenId) -> (TokenId, Vec) { - let user = &self.user; - refresh_grant( - &self.database, - user.user_id, - user.session_id, - &self.client, - family, - ) - .await - } - - /// Deletes the client as an operator, in a task of its own. - fn delete(&self) -> JoinHandle> { - let (database, id) = (self.database.clone(), self.client.clone()); - tokio::spawn( - async move { change(&database, async |registry| registry.delete(&id).await).await }, - ) - } -} - -/// Sends `method` to `path` on `replica` from a browser page on `origin`, with an -/// optional form body and HTTP Basic credentials. -async fn send( - replica: &Router, - method: Method, - path: &str, - origin: &str, - form: &str, - basic: Option<(&ClientId, &str)>, -) -> Response { - let mut request = Request::builder() - .method(method.clone()) - .uri(path) - .header(header::ORIGIN, origin) - .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); - if method == Method::OPTIONS { - request = request.header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST"); - } - if let Some((id, secret)) = basic { - let credentials = - base64::engine::general_purpose::STANDARD.encode(format!("{id}:{secret}")); - request = request.header(header::AUTHORIZATION, format!("Basic {credentials}")); - } - replica - .clone() - .oneshot(request.body(Body::from(form.to_owned())).expect("request")) - .await - .expect("response") -} - -/// Whether a token-endpoint preflight from `origin` gets its CORS grant. -async fn cors(replica: &Router, origin: &str) -> bool { - let response = send(replica, Method::OPTIONS, "/oauth/token", origin, "", None).await; - response.status() == StatusCode::NO_CONTENT - && response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN] == origin -} - -/// Whether the token endpoint authenticates the public client `id`: an unusable -/// code then fails as a bad grant rather than a bad client. -async fn authenticates(replica: &Router, id: &ClientId, origin: &str) -> bool { - let form = format!("grant_type=authorization_code&code=unusable&client_id={id}"); - let response = send(replica, Method::POST, "/oauth/token", origin, &form, None).await; - response.status() != StatusCode::UNAUTHORIZED -} - -/// Creating, updating, disabling and enabling a public client changes CORS and -/// client authentication on the next request to either replica, with no restart. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn changes_apply_to_the_next_request_on_every_replica() { - let replicas = Replicas::new().await; - let database = Replicas::database().await; - let [first, second] = [(); 2].map(|()| format!("https://{}.example", UserId::new())); - let mut client = registration(ClientKind::Public, &first); - assert!(!cors(&replicas.a, &first).await, "not registered yet"); - - let secret = register(&database, &client).await.expect("create"); - assert!(secret.is_none(), "public clients have no secret"); - assert!(cors(&replicas.b, &first).await); - assert!(authenticates(&replicas.a, &client.id, &first).await); - - client.redirect_uris = - RedirectUris::new([format!("{second}/callback").parse().expect("callback")]) - .expect("one callback"); - replace(&database, &client).await.expect("update"); - assert!( - !cors(&replicas.a, &first).await, - "the old origin is dropped" - ); - assert!(cors(&replicas.b, &second).await); - - change(&database, async |registry| { - registry.set_enabled(&client.id, false).await - }) - .await - .expect("disable"); - assert!(!cors(&replicas.a, &second).await); - assert!(!authenticates(&replicas.b, &client.id, &second).await); - change(&database, async |registry| { - registry.set_enabled(&client.id, true).await - }) - .await - .expect("enable"); - assert!(authenticates(&replicas.a, &client.id, &second).await); - - let history = database - .events() - .history_for_client(&client.id, 10) - .await - .expect("history"); - assert!( - history - .iter() - .all(|event| event.actor == operator().context().actor) - ); - let client_id = client.id.clone(); - assert_eq!( - history - .into_iter() - .map(|stored| stored.event.known().cloned().expect("a known event")) - .collect::>(), - [ - DomainEvent::ClientEnabled { - client_id: client_id.clone() - }, - DomainEvent::ClientDisabled { - client_id: client_id.clone() - }, - DomainEvent::ClientUpdated { - client_id: client_id.clone(), - changed: vec![ClientField::RedirectUris], - }, - DomainEvent::ClientRegistered { - client_id, - kind: ClientKind::Public - }, - ] - ); -} - -/// During a rotation's grace period both secrets authenticate; once it ends, only -/// the newest does. A public client cannot be given a secret. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn rotated_secrets_overlap_until_their_grace_period_ends() { - let replicas = Replicas::new().await; - let database = Replicas::database().await; - let client = registration(ClientKind::Confidential, "https://api.example"); - // Revocation answers 200 for any token once the client authenticates. - let revokes = async |secret: &ClientSecret| { - send( - &replicas.a, - Method::POST, - "/oauth/revoke", - "https://api.example", - "token=unknown", - Some((&client.id, secret.expose())), - ) - .await - .status() - == StatusCode::OK - }; - let first = register(&database, &client) - .await - .expect("create") - .expect("confidential clients get a secret"); - assert!(revokes(&first).await); - - let rotate = async |id: &ClientId, grace: &str| { - let grace = grace.parse().expect("grace"); - change(&database, async |registry| { - registry.rotate_secret(id, grace).await - }) - .await - }; - let second = rotate(&client.id, "1h").await.expect("rotate"); - assert!(revokes(&first).await, "still in its grace period"); - assert!(revokes(&second).await); - - let third = rotate(&client.id, "0").await.expect("rotate and revoke"); - assert!(!revokes(&first).await); - assert!(!revokes(&second).await); - assert!(revokes(&third).await); - - let public = registration(ClientKind::Public, "https://web.example"); - register(&database, &public).await.expect("public client"); - assert!(matches!( - rotate(&public.id, "0").await, - Err(ClientRegistryError::Public(_)) - )); - assert!(matches!( - register(&database, &public).await, - Err(ClientRegistryError::Exists { .. }) - )); - assert!(matches!( - change(&database, async |registry| { - registry - .update(&public.id, |_| { - Ok(ClientRegistration { - kind: ClientKind::Confidential, - ..public.clone() - }) - }) - .await - }) - .await, - Err(ClientRegistryError::Immutable(_)) - )); - let unknown = "unknown-client".parse().expect("ID"); - assert!(matches!( - change(&database, async |registry| { - registry.set_enabled(&unknown, false).await - }) - .await, - Err(ClientRegistryError::Unknown(_)) - )); -} - -/// Applying a deployment's client registers it, then writes only what differs, so -/// each deploy can apply it again. A new secret overlaps with the previous ones for -/// the grace period, a previous secret applied again lasts, and a zero grace -/// revokes the others. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn apply_changes_only_what_differs() { - let replicas = Replicas::new().await; - let database = Replicas::database().await; - let origin = format!("https://{}.example", UserId::new()); - let mut client = registration(ClientKind::Confidential, &origin); - let [first, second] = [(); 2].map(|()| Secret::generate().expect("secret").encoded()); - let apply = async |client: &ClientRegistration, secret: Option<&str>, grace: &str| { - let secret = secret.map(|secret| ClientSecret::parse(secret).expect("secret")); - let grace = grace.parse().expect("grace"); - change(&database, async |registry| { - registry.apply(client, secret, grace).await - }) - .await - }; - let revokes = async |secret: &str| { - send( - &replicas.a, - Method::POST, - "/oauth/revoke", - &origin, - "token=unknown", - Some((&client.id, secret)), - ) - .await - .status() - == StatusCode::OK - }; - - assert_eq!( - apply(&client, Some(&first), "1h").await.expect("register"), - Applied::Registered - ); - assert!(revokes(&first).await); - let mut reordered = client.clone(); - reordered.allowed_scopes = - AllowedScopes::new(client.allowed_scopes.iter().rev().cloned()).expect("scopes"); - assert_eq!( - apply(&reordered, Some(&first), "1h").await.expect("again"), - Applied::Unchanged - ); - - client.display_name = "Renamed app".parse().expect("display name"); - assert_eq!( - apply(&client, Some(&first), "1h").await.expect("rename"), - Applied::Updated - ); - assert_eq!( - apply(&client, Some(&second), "1h") - .await - .expect("new secret"), - Applied::Updated - ); - assert!( - revokes(&first).await, - "the previous secret is in its grace period" - ); - assert!(revokes(&second).await); - - assert_eq!( - apply(&client, Some(&first), "1h").await.expect("back"), - Applied::Updated, - "a secret in its grace period is made lasting again" - ); - assert_eq!( - apply(&client, Some(&first), "0").await.expect("revoke"), - Applied::Updated - ); - assert!(revokes(&first).await); - assert!(!revokes(&second).await); - assert_eq!( - apply(&client, Some(&first), "0").await.expect("again"), - Applied::Unchanged - ); - - let history = database - .events() - .history_for_client(&client.id, 10) - .await - .expect("history"); - assert!(matches!( - history - .iter() - .map(|stored| stored.event.known().expect("a known event")) - .collect::>()[..], - [ - DomainEvent::ClientSecretRotated { .. }, - DomainEvent::ClientSecretRotated { .. }, - DomainEvent::ClientSecretRotated { .. }, - DomainEvent::ClientUpdated { .. }, - DomainEvent::ClientRegistered { .. }, - ] - )); -} - -/// Applying refuses a confidential client without its secret, a public one with a -/// secret, and a change of kind. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn apply_refuses_mismatched_secrets_and_kinds() { - let database = Replicas::database().await; - let client = registration(ClientKind::Confidential, "https://api.example"); - let first = Secret::generate().expect("secret").encoded(); - let apply = async |client: &ClientRegistration, secret: Option<&str>| { - let secret = secret.map(|secret| ClientSecret::parse(secret).expect("secret")); - let grace = "1h".parse().expect("grace"); - change(&database, async |registry| { - registry.apply(client, secret, grace).await - }) - .await - }; - apply(&client, Some(&first)).await.expect("register"); - assert!(matches!( - apply(&client, None).await, - Err(ClientRegistryError::MissingSecret(_)) - )); - let public = ClientRegistration { - kind: ClientKind::Public, - ..client.clone() - }; - assert!(matches!( - apply(&public, Some(&first)).await, - Err(ClientRegistryError::Public(_)) - )); - assert!(matches!( - apply(&public, None).await, - Err(ClientRegistryError::Immutable(_)) - )); -} - -/// Concurrent registrations by one account count one another: exactly -/// [`MAX_OWNED_CLIENTS`] succeed. Deleting one frees a place, until the account -/// registered [`MAX_DAILY_REGISTRATIONS`] clients that day. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -#[ignore = "requires TEST_DATABASE_URL"] -async fn the_quota_holds_under_concurrent_registrations() { - let database = Replicas::database().await; - let owner = Browser::new_account(&database).await.user_id; - let attempts = MAX_OWNED_CLIENTS + 4; - let mut registrations = tokio::task::JoinSet::new(); - for _ in 0..attempts { - let database = database.clone(); - registrations.spawn(async move { - let client = registration(ClientKind::Public, "https://quota.example"); - change(&database, async |registry| { - registry - .create(ClientOwner::Account(owner), &client, None) - .await - }) - .await - .map(|_| client.id) - }); - } - let (mut registered, mut refused) = (Vec::new(), 0); - while let Some(result) = registrations.join_next().await { - match result.expect("task") { - Ok(id) => registered.push(id), - Err(ClientRegistryError::QuotaExceeded) => refused += 1, - Err(error) => panic!("unexpected failure: {error}"), - } - } - assert_eq!(registered.len(), MAX_OWNED_CLIENTS as usize); - assert_eq!(refused, attempts - MAX_OWNED_CLIENTS); - assert_eq!( - database - .oidc() - .count_owned_clients(owner, chrono::Duration::days(1)) - .await - .expect("count") - .live, - u64::from(MAX_OWNED_CLIENTS) - ); - - // Deleting frees a place, but deleted clients still count against the - // daily limit, so an account cannot pile up tombstones. - for registration_number in MAX_OWNED_CLIENTS..=MAX_DAILY_REGISTRATIONS { - let freed = registered.pop().expect("a client to delete"); - change(&database, async |registry| registry.delete(&freed).await) - .await - .expect("delete"); - let client = registration(ClientKind::Public, "https://quota.example"); - let created = change(&database, async |registry| { - registry - .create(ClientOwner::Account(owner), &client, None) - .await - }) - .await; - if registration_number < MAX_DAILY_REGISTRATIONS { - created.expect("a deletion frees a place"); - registered.push(client.id); - } else { - assert!(matches!( - created, - Err(ClientRegistryError::DailyLimitExceeded) - )); - } - } -} - -/// An account lists and finds only its own live clients: another account's, an -/// operator's, an unknown ID and a malformed one are not found. Every operation -/// on one client takes what [`AccountService::owned_client`] found, so none -/// reaches them either. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn owners_find_only_their_own_clients() { - let account = Account::new().await; - let (alice, service) = (account.owner().await, &account.service); - let bob = Browser::new_account(&account.database).await; - let bob = bob.owner(&account.database).await; - let operated = registration(ClientKind::Public, "https://operated.example"); - register(&account.database, &operated) - .await - .expect("operator client"); - - let id = account.create(ClientKind::Confidential).await; - assert!(id.as_str().starts_with("c_"), "{id}"); - let listed = service.clients(&alice).await.expect("list"); - assert_eq!( - listed.iter().map(|client| &client.id).collect::>(), - [&id] - ); - let app = account.find(alice.clone(), &id).await; - let secrets = service.client_secrets(&app).await.expect("secrets"); - assert_eq!(secrets.len(), 1); - - assert_eq!(service.clients(&bob).await.expect("list"), []); - for (owner, id) in [ - (&bob, id.as_str()), - (&alice, operated.id.as_str()), - (&alice, "c_unknown"), - (&alice, "%FF"), - ] { - let found = service.owned_client(owner.clone(), id).await; - assert!( - matches!(found, Err(AccountError::Client(OwnedClientError::NotFound))), - "{id}" - ); - } -} - -/// Every change to a client needs a recent passkey confirmation: changing any -/// setting, pausing or resuming it. A refused change leaves the client as it was. -/// A confirmed owner rotates its secret and changes its settings. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn every_change_needs_a_confirmation() { - let account = Account::new().await; - let service = &account.service; - let id = account.create(ClientKind::Confidential).await; - let social = account.social().await.owner(&account.database).await; - let client = account.find(social, &id).await; - let logout = ClientPatch { - post_logout_uris: Some(vec!["https://attacker.example/".into()]), - ..ClientPatch::default() - }; - let rename = || ClientPatch { - display_name: Some("Renamed".into()), - ..ClientPatch::default() - }; - for refused in [ - service.update_client(&client, logout).await.map(drop), - service.update_client(&client, rename()).await.map(drop), - service.set_client_enabled(&client, false).await, - service.set_client_enabled(&client, true).await, - ] { - assert!( - matches!( - refused, - Err(AccountError::Owner(SessionError::StepUpRequired { .. })) - ), - "{refused:?}" - ); - } - let kept = account.database.oidc().find_client(id.as_str()).await; - let kept = kept.expect("lookup").expect("client"); - assert_eq!( - kept.display_name, "Notes", - "the refused changes were rolled back" - ); - assert_eq!(kept.post_logout_uris, Vec::::new()); - assert!(kept.enabled); - - let client = account.find(account.owner().await, &id).await; - let grace = "0".parse().expect("grace period"); - let secret = service.rotate_client_secret(&client, grace).await; - assert!(secret.expect("rotate").expose().starts_with("pqcs_")); - let patch = ClientPatch { - redirect_uris: Some(vec!["https://notes.example/auth".into()]), - ..rename() - }; - let changed = service.update_client(&client, patch).await.expect("change"); - assert_eq!(changed.display_name, "Renamed"); - assert_eq!(changed.redirect_uris, ["https://notes.example/auth"]); - service - .set_client_enabled(&client, false) - .await - .expect("disable"); -} - -/// An owner found from a cookie their session had before a passkey confirmation -/// never gains that confirmation, even when it commits while the change waits -/// for the account lock: the confirmation replaced the cookie. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "requires TEST_DATABASE_URL"] -async fn confirmations_never_reach_owners_found_before_them() { - let account = Account::new().await; - let service = &account.service; - let id = account.create(ClientKind::Confidential).await; - let redirect = ClientPatch { - redirect_uris: Some(vec!["https://attacker.example/callback".into()]), - ..ClientPatch::default() - }; - for result in [ - account - .confirmed_while_waiting(&id, async |client| { - service.update_client(client, redirect).await.map(drop) - }) - .await, - account - .confirmed_while_waiting(&id, async |client| { - let grace = GracePeriod::default(); - service.rotate_client_secret(client, grace).await.map(drop) - }) - .await, - account - .confirmed_while_waiting(&id, async |client| { - service.set_client_enabled(client, false).await - }) - .await, - account - .confirmed_while_waiting(&id, async |client| service.delete_client(client).await) - .await, - ] { - assert!( - matches!( - result, - Err(AccountError::Owner(SessionError::StepUpRequired { .. })) - ), - "{result:?}" - ); - } - let client = account.database.oidc().find_client(id.as_str()).await; - let client = client.expect("lookup").expect("client"); - assert_eq!(client.redirect_uris, ["https://notes.example/callback"]); - assert!(client.enabled && client.deleted_at.is_none()); - let secrets = account.database.oidc().client_secrets(&id).await; - assert_eq!(secrets.expect("secrets").len(), 1, "no secret was added"); -} - -/// An invalid setting names its field apart from what is wrong with it, so a -/// form can show the message beside it: owners grant only the standard scopes -/// and send browsers only to URIs auth accepts. Settings are checked before -/// anything else, so an unconfirmed owner's invalid registration is refused for -/// its settings rather than for the confirmation. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn invalid_settings_name_their_field_first() { - let account = Account::new().await; - let id = account.create(ClientKind::Public).await; - let client = account.find(account.owner().await, &id).await; - let social = account.social().await.owner(&account.database).await; - let blank = NewClient { - kind: ClientKind::Public, - settings: ClientSettings { - display_name: " ".into(), - ..ClientSettings::test("https://notes.example") - }, - }; - let invalid = |result: Result<(), AccountError>, field: ClientField| match result { - Err(AccountError::Client(OwnedClientError::InvalidSetting(error))) => { - assert_eq!(error.field(), &field); - assert_eq!(error.to_string(), format!("{field}: {}", error.reason())); - } - result => panic!("{field}: {result:?}"), - }; - let registered = account.service.create_client(&social, blank).await; - invalid(registered.map(drop), ClientField::DisplayName); - for (patch, field) in [ - ( - ClientPatch { - allowed_scopes: Some(vec!["openid".into(), "notes:read".into()]), - ..ClientPatch::default() - }, - ClientField::AllowedScopes, - ), - ( - ClientPatch { - redirect_uris: Some(vec!["http://notes.example/callback".into()]), - ..ClientPatch::default() - }, - ClientField::RedirectUris, - ), - ( - ClientPatch { - redirect_uris: Some(Vec::new()), - ..ClientPatch::default() - }, - ClientField::RedirectUris, - ), - ( - ClientPatch { - display_name: Some(" ".into()), - ..ClientPatch::default() - }, - ClientField::DisplayName, - ), - ] { - let changed = account.service.update_client(&client, patch).await; - invalid(changed.map(drop), field); - } -} - -/// Deleting a client revokes its refresh tokens, removes its secrets and leaves a -/// disabled tombstone, recorded as the owner's. Its ID can never be registered, -/// applied, enabled, changed or deleted again, by the account or an operator. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn deleted_clients_stay_deleted() { - let account = Account::new().await; - let (database, alice) = (&account.database, &account.browser); - let owner = account.owner().await; - let client_id = account.create(ClientKind::Confidential).await; - let (token, digest) = refresh_grant( - database, - alice.user_id, - alice.session_id, - &client_id, - TokenId::new(), - ) - .await; - - let client = account.find(owner.clone(), &client_id).await; - account - .service - .delete_client(&client) - .await - .expect("delete"); - let found = account - .service - .owned_client(owner.clone(), client_id.as_str()); - assert!(matches!( - found.await, - Err(AccountError::Client(OwnedClientError::NotFound)) - )); - assert_eq!(account.service.clients(&owner).await.expect("list"), []); - - let mut tx = database.begin().await.expect("transaction"); - assert!(matches!( - tx.tokens() - .consume_for_rotation(token, std::slice::from_ref(&digest), client_id.as_str()) - .await, - Err(RefreshRotationError::Invalid) - )); - drop(tx); - let oidc = &mut database.oidc(); - let tombstone = oidc.find_client(client_id.as_str()).await; - let tombstone = tombstone.expect("lookup").expect("row"); - assert!(tombstone.deleted_at.is_some() && !tombstone.enabled); - assert_eq!(oidc.client_secrets(&client_id).await.expect("secrets"), []); - let history = database - .events() - .history_for_client(&client_id, 1) - .await - .expect("history"); - assert_eq!( - (history[0].event.known(), &history[0].actor), - ( - Some(&DomainEvent::ClientDeleted { - client_id: client_id.clone() - }), - &Actor::User { - user_id: alice.user_id, - session_id: Some(alice.session_id), - } - ) - ); - - let reused = ClientRegistration { - id: client_id.clone(), - ..registration(ClientKind::Confidential, "https://notes.example") - }; - assert!(matches!( - register(database, &reused).await, - Err(ClientRegistryError::Exists { .. }) - )); - let secret = Some(ClientSecret::generate().expect("secret")); - assert!(matches!( - change(database, async |registry| { - registry - .apply(&reused, secret, GracePeriod::default()) - .await - }) - .await, - Err(ClientRegistryError::Deleted(_)) - )); - assert!(matches!( - change(database, async |registry| { - registry.set_enabled(&client_id, true).await - }) - .await, - Err(ClientRegistryError::Deleted(_)) - )); - assert!(matches!( - change(database, async |registry| { - registry.delete(&client_id).await - }) - .await, - Err(ClientRegistryError::Deleted(_)) - )); -} - -/// A deletion and a refresh rotation lock a family and the client in the same -/// order, so they never deadlock. Here a transaction holds one family of the -/// client while the deletion waits for it, then rotates another family, which -/// locks the client: the deletion must not be holding it yet. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "requires TEST_DATABASE_URL"] -async fn deletion_and_refresh_rotation_never_deadlock() { - let granting = Granting::new().await; - let (held, held_digest) = granting.grant(TokenId::new()).await; - let (rotated, rotated_digest) = granting.grant(TokenId::new()).await; - - let mut holder = granting.database.begin().await.expect("transaction"); - holder - .tokens() - .revoke_family_for_token(held, std::slice::from_ref(&held_digest)) - .await - .expect("hold the first family"); - let deletion = granting.delete(); - until_blocked(&mut holder, 1).await; - holder - .tokens() - .consume_for_rotation( - rotated, - std::slice::from_ref(&rotated_digest), - granting.client.as_str(), - ) - .await - .expect("the rotation locks the client while the deletion waits"); - holder.commit().await.expect("commit"); - deletion - .await - .expect("task") - .expect("the deletion follows the rotation"); - - let mut tx = granting.database.begin().await.expect("transaction"); - assert!(matches!( - tx.tokens() - .consume_for_rotation( - rotated, - std::slice::from_ref(&rotated_digest), - granting.client.as_str() - ) - .await, - Err(RefreshRotationError::Invalid | RefreshRotationError::Replay { .. }) - )); -} - -/// A family granted after a deletion locked the client's families is locked by -/// no one else but a rotation that will find the client deleted, so the deletion -/// skips it instead of waiting, which could deadlock with that rotation. Here the -/// deletion queues behind a held family while the grant commits, then a second -/// transaction holds the new family. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "requires TEST_DATABASE_URL"] -async fn deletion_skips_families_granted_while_it_waits() { - let granting = Granting::new().await; - let (held, fresh) = (TokenId::new(), TokenId::new()); - granting.grant(held).await; - let mut holder = granting.database.begin().await.expect("transaction"); - holder - .tokens() - .lock_family(held) - .await - .expect("hold the family"); - let deletion = granting.delete(); - until_blocked(&mut holder, 1).await; - let (token, digest) = granting.grant(fresh).await; - let mut rotation = granting.database.begin().await.expect("transaction"); - rotation - .tokens() - .lock_family(fresh) - .await - .expect("hold the fresh family"); - holder.commit().await.expect("commit"); - tokio::time::timeout(std::time::Duration::from_secs(10), deletion) - .await - .expect("the deletion does not wait for the fresh family") - .expect("task") - .expect("deletion"); - let id = granting.client.as_str(); - assert!(matches!( - rotation - .tokens() - .consume_for_rotation(token, std::slice::from_ref(&digest), id) - .await, - Err(RefreshRotationError::Invalid) - )); -} - -/// A deletion and a logout that share families lock them in the same order, so -/// they never deadlock. The families are inserted highest ID first, so a scan -/// meets them out of ID order; a transaction holds the lowest while the deletion, -/// then the logout, queue for it. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "requires TEST_DATABASE_URL"] -async fn deletion_and_logout_never_deadlock() { - let granting = Granting::new().await; - let (low, high) = (TokenId::new(), TokenId::new()); - for family in [high, low] { - granting.grant(family).await; - } - - let mut holder = granting.database.begin().await.expect("transaction"); - holder - .tokens() - .lock_family(low) - .await - .expect("hold the lowest family"); - let deletion = granting.delete(); - until_blocked(&mut holder, 1).await; - let logout = tokio::spawn({ - let database = granting.database.clone(); - let (user, session) = (granting.user.user_id, granting.user.session_id); - async move { - let mut tx = database.begin().await?; - sign_out(&mut tx, user, session).await?; - tx.commit().await - } - }); - until_blocked(&mut holder, 2).await; - holder.commit().await.expect("commit"); - deletion.await.expect("task").expect("deletion"); - logout.await.expect("task").expect("logout"); -} - -/// An operator's suspension disables a client, and its owner cannot enable it, -/// though they can still see and disable it. Lifting the suspension leaves it -/// disabled, for the owner to enable. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn owners_cannot_enable_a_suspended_client() { - let account = Account::new().await; - let (service, owner) = (&account.service, account.owner().await); - let id = account.create(ClientKind::Public).await; - let client = account.find(owner.clone(), &id).await; - let suspend = async |suspended: bool| { - change(&account.database, async |registry| { - registry.set_suspended(&id, suspended).await - }) - .await - .expect("suspension"); - }; - let shown = async || account.find(owner.clone(), &id).await; - suspend(true).await; - let suspended = shown().await; - let suspended = suspended.client(); - assert!(suspended.suspended_at.is_some() && !suspended.enabled); - let enabled = service.set_client_enabled(&client, true).await; - assert!( - matches!( - enabled, - Err(AccountError::Client(OwnedClientError::Registry( - ClientRegistryError::Suspended(_) - ))) - ), - "{enabled:?}" - ); - assert!(matches!( - change(&account.database, async |registry| { - registry.set_enabled(&id, true).await - }) - .await, - Err(ClientRegistryError::Suspended(_)), - )); - service - .set_client_enabled(&client, false) - .await - .expect("disable"); - - suspend(false).await; - let lifted = shown().await; - let lifted = lifted.client(); - assert!(lifted.suspended_at.is_none() && !lifted.enabled); - service - .set_client_enabled(&client, true) - .await - .expect("enable"); -} - -/// Browsers count a related origin by its registrable domain's first label, so -/// `example.co.uk` is `example`, also within auth's own domain. An origin without -/// a registrable domain counts none within auth's domain, and is refused elsewhere. -#[test] -fn related_origins_count_registrable_domain_labels() { - let domain = |origin: &str| { - ClientRegistry::domain(&origin.parse().expect("origin"), "auth.piquel.fr") - .expect("countable origin") - }; - assert_eq!( - domain("https://app.example.co.uk").as_deref(), - Some("example") - ); - assert_eq!( - domain("https://notes.alice.github.io").as_deref(), - Some("alice") - ); - assert_eq!(domain("https://piquel.fr").as_deref(), Some("piquel")); - assert_eq!( - domain("https://notes.auth.piquel.fr").as_deref(), - Some("piquel") - ); - let localhost = "https://localhost:4443".parse().expect("origin"); - assert_eq!( - ClientRegistry::domain(&localhost, "localhost").expect("countable origin"), - None - ); - for public in ["https://github.io", "https://localhost"] { - assert!(matches!( - ClientRegistry::domain(&public.parse().expect("origin"), "auth.piquel.fr"), - Err(ClientRegistryError::PublicSuffix(_)) - )); - } -} - -/// Only a trusted client's redirect origins are approved, each once, and approved -/// origins never span more domains than every browser honours. Deleting the client -/// removes its origins. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn origin_approval_needs_trust_a_redirect_origin_and_few_domains() { - let database = Replicas::database().await; - let unique = UserId::new(); - // Six registrable domains, then a second origin on the first one. - let mut origins: Vec = (0..6) - .map(|domain| format!("https://d{domain}-{unique}.example")) - .chain([format!("https://www.d0-{unique}.example")]) - .map(|origin| origin.parse().expect("origin")) - .collect(); - let inside: RelatedOrigin = format!("https://{unique}.auth.piquel.fr") - .parse() - .expect("origin"); - origins.push(inside.clone()); - let client = ClientRegistration { - redirect_uris: RedirectUris::new( - origins - .iter() - .map(|origin| format!("{origin}/callback").parse().expect("callback")), - ) - .expect("callbacks"), - ..registration(ClientKind::Public, inside.as_str()) - }; - register(&database, &client).await.expect("client"); - let approve = async |origin: &RelatedOrigin| { - change(&database, async |registry| { - registry - .approve_origin(&client.id, origin, "auth.piquel.fr") - .await - }) - .await - }; - let remove = async |origin: &RelatedOrigin| { - change(&database, async |registry| { - registry.remove_origin(&client.id, origin).await - }) - .await - }; - assert!(matches!( - approve(&inside).await, - Err(ClientRegistryError::Untrusted(_)) - )); - replace( - &database, - &ClientRegistration { - trusted: true, - ..client.clone() - }, - ) - .await - .expect("trusted"); - let elsewhere = format!("https://elsewhere-{unique}.auth.piquel.fr") - .parse() - .expect("origin"); - assert!(matches!( - approve(&elsewhere).await, - Err(ClientRegistryError::NotRedirectOrigin { .. }) - )); - approve(&inside) - .await - .expect("an origin within auth's domain"); - assert!(matches!( - approve(&inside).await, - Err(ClientRegistryError::OriginApproved { .. }) - )); - let mut approved = Vec::new(); - let error = loop { - match approve(&origins[approved.len()]).await { - Ok(()) => approved.push(origins[approved.len()].clone()), - Err(error) => break error, - } - }; - let ClientRegistryError::TooManyDomains(domains) = error else { - panic!("a sixth domain is refused, not {error}"); - }; - assert_eq!(domains.len(), MAX_RELATED_ORIGIN_DOMAINS + 1); - // Other tests' origins within auth's domain count as `piquel`, and a database - // other runs left full refuses the first domain. Otherwise another origin on an - // approved domain still fits. - if !approved.is_empty() { - approve(&origins[6]) - .await - .expect("an already counted domain"); - approved.push(origins[6].clone()); - } - approved.push(inside.clone()); - for origin in &approved { - remove(origin).await.expect("removed"); - } - assert!(matches!( - remove(&approved[0]).await, - Err(ClientRegistryError::OriginNotApproved { .. }) - )); - - // Clients are tombstoned, so a trigger, not the query, removes the origins of a - // deleted one, whichever release deleted it. - approve(&inside).await.expect("approved again"); - change(&database, async |registry| { - registry.delete(&client.id).await - }) - .await - .expect("deleted"); - let approved = database.oidc().related_origins().await.expect("origins"); - assert!(approved.iter().all(|origin| origin.client_id != client.id)); -} diff --git a/apps/auth-service/src/clients/tests/deletion.rs b/apps/auth-service/src/clients/tests/deletion.rs new file mode 100644 index 000000000..7ab05ae69 --- /dev/null +++ b/apps/auth-service/src/clients/tests/deletion.rs @@ -0,0 +1,279 @@ +//! Deleting a client: the tombstone it leaves, and the token grants it revokes +//! without deadlocking. +use super::*; +use crate::tests::{refresh_grant, sign_out}; +use piquel_common::{TokenId, events::Actor}; +use piquel_repository::RefreshRotationError; +use tokio::task::JoinHandle; + +/// A public client and an account holding refresh grants to it, which the +/// deletion scenarios race a deletion against. +struct Granting { + /// The scenario database. + database: Database, + /// The client, which an operator manages. + client: ClientId, + /// The account, signed in. + user: Browser, +} + +impl Granting { + /// Registers the client over a migrated test database, and signs the account + /// in. + async fn new() -> Self { + let database = Replicas::database().await; + let client = registration(ClientKind::Public, "https://notes.example"); + register(&database, &client).await.expect("client"); + Self { + user: Browser::new_account(&database).await, + client: client.id, + database, + } + } + + /// Issues the refresh grant `family` to the client from the account's session, + /// and returns its first refresh token's ID and digest. + async fn grant(&self, family: TokenId) -> (TokenId, Vec) { + let user = &self.user; + refresh_grant( + &self.database, + user.user_id, + user.session_id, + &self.client, + family, + ) + .await + } + + /// Deletes the client as an operator, in a task of its own. + fn delete(&self) -> JoinHandle> { + let (database, id) = (self.database.clone(), self.client.clone()); + tokio::spawn( + async move { change(&database, async |registry| registry.delete(&id).await).await }, + ) + } +} + +/// Deleting a client revokes its refresh tokens, removes its secrets and leaves a +/// disabled tombstone, recorded as the owner's. Its ID can never be registered, +/// applied, enabled, changed or deleted again, by the account or an operator. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn deleted_clients_stay_deleted() { + let account = Account::new().await; + let (database, alice) = (&account.database, &account.browser); + let owner = account.owner().await; + let client_id = account.create(ClientKind::Confidential).await; + let (token, digest) = refresh_grant( + database, + alice.user_id, + alice.session_id, + &client_id, + TokenId::new(), + ) + .await; + + let client = account.find(owner.clone(), &client_id).await; + account + .service + .delete_client(&client) + .await + .expect("delete"); + let found = account + .service + .owned_client(owner.clone(), client_id.as_str()); + assert!(matches!( + found.await, + Err(AccountError::Client(OwnedClientError::NotFound)) + )); + assert_eq!(account.service.clients(&owner).await.expect("list"), []); + + let mut tx = database.begin().await.expect("transaction"); + assert!(matches!( + tx.tokens() + .consume_for_rotation(token, std::slice::from_ref(&digest), client_id.as_str()) + .await, + Err(RefreshRotationError::Invalid) + )); + drop(tx); + let oidc = &mut database.oidc(); + let tombstone = oidc.find_client(client_id.as_str()).await; + let tombstone = tombstone.expect("lookup").expect("row"); + assert!(tombstone.deleted_at.is_some() && !tombstone.enabled); + assert_eq!(oidc.client_secrets(&client_id).await.expect("secrets"), []); + let history = database + .events() + .history_for_client(&client_id, 1) + .await + .expect("history"); + assert_eq!( + (history[0].event.known(), &history[0].actor), + ( + Some(&DomainEvent::ClientDeleted { + client_id: client_id.clone() + }), + &Actor::User { + user_id: alice.user_id, + session_id: Some(alice.session_id), + } + ) + ); + + let reused = ClientRegistration { + id: client_id.clone(), + ..registration(ClientKind::Confidential, "https://notes.example") + }; + assert!(matches!( + register(database, &reused).await, + Err(ClientRegistryError::Exists { .. }) + )); + let secret = Some(ClientSecret::generate().expect("secret")); + assert!(matches!( + change(database, async |registry| { + registry + .apply(&reused, secret, GracePeriod::default()) + .await + }) + .await, + Err(ClientRegistryError::Deleted(_)) + )); + assert!(matches!( + change(database, async |registry| { + registry.set_enabled(&client_id, true).await + }) + .await, + Err(ClientRegistryError::Deleted(_)) + )); + assert!(matches!( + change(database, async |registry| { + registry.delete(&client_id).await + }) + .await, + Err(ClientRegistryError::Deleted(_)) + )); +} + +/// A deletion and a refresh rotation lock a family and the client in the same +/// order, so they never deadlock. Here a transaction holds one family of the +/// client while the deletion waits for it, then rotates another family, which +/// locks the client: the deletion must not be holding it yet. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires TEST_DATABASE_URL"] +async fn deletion_and_refresh_rotation_never_deadlock() { + let granting = Granting::new().await; + let (held, held_digest) = granting.grant(TokenId::new()).await; + let (rotated, rotated_digest) = granting.grant(TokenId::new()).await; + + let mut holder = granting.database.begin().await.expect("transaction"); + holder + .tokens() + .revoke_family_for_token(held, std::slice::from_ref(&held_digest)) + .await + .expect("hold the first family"); + let deletion = granting.delete(); + until_blocked(&mut holder, 1).await; + holder + .tokens() + .consume_for_rotation( + rotated, + std::slice::from_ref(&rotated_digest), + granting.client.as_str(), + ) + .await + .expect("the rotation locks the client while the deletion waits"); + holder.commit().await.expect("commit"); + deletion + .await + .expect("task") + .expect("the deletion follows the rotation"); + + let mut tx = granting.database.begin().await.expect("transaction"); + assert!(matches!( + tx.tokens() + .consume_for_rotation( + rotated, + std::slice::from_ref(&rotated_digest), + granting.client.as_str() + ) + .await, + Err(RefreshRotationError::Invalid | RefreshRotationError::Replay { .. }) + )); +} + +/// A family granted after a deletion locked the client's families is locked by +/// no one else but a rotation that will find the client deleted, so the deletion +/// skips it instead of waiting, which could deadlock with that rotation. Here the +/// deletion queues behind a held family while the grant commits, then a second +/// transaction holds the new family. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires TEST_DATABASE_URL"] +async fn deletion_skips_families_granted_while_it_waits() { + let granting = Granting::new().await; + let (held, fresh) = (TokenId::new(), TokenId::new()); + granting.grant(held).await; + let mut holder = granting.database.begin().await.expect("transaction"); + holder + .tokens() + .lock_family(held) + .await + .expect("hold the family"); + let deletion = granting.delete(); + until_blocked(&mut holder, 1).await; + let (token, digest) = granting.grant(fresh).await; + let mut rotation = granting.database.begin().await.expect("transaction"); + rotation + .tokens() + .lock_family(fresh) + .await + .expect("hold the fresh family"); + holder.commit().await.expect("commit"); + tokio::time::timeout(std::time::Duration::from_secs(10), deletion) + .await + .expect("the deletion does not wait for the fresh family") + .expect("task") + .expect("deletion"); + let id = granting.client.as_str(); + assert!(matches!( + rotation + .tokens() + .consume_for_rotation(token, std::slice::from_ref(&digest), id) + .await, + Err(RefreshRotationError::Invalid) + )); +} + +/// A deletion and a logout that share families lock them in the same order, so +/// they never deadlock. The families are inserted highest ID first, so a scan +/// meets them out of ID order; a transaction holds the lowest while the deletion, +/// then the logout, queue for it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires TEST_DATABASE_URL"] +async fn deletion_and_logout_never_deadlock() { + let granting = Granting::new().await; + let (low, high) = (TokenId::new(), TokenId::new()); + for family in [high, low] { + granting.grant(family).await; + } + + let mut holder = granting.database.begin().await.expect("transaction"); + holder + .tokens() + .lock_family(low) + .await + .expect("hold the lowest family"); + let deletion = granting.delete(); + until_blocked(&mut holder, 1).await; + let logout = tokio::spawn({ + let database = granting.database.clone(); + let (user, session) = (granting.user.user_id, granting.user.session_id); + async move { + let mut tx = database.begin().await?; + sign_out(&mut tx, user, session).await?; + tx.commit().await + } + }); + until_blocked(&mut holder, 2).await; + holder.commit().await.expect("commit"); + deletion.await.expect("task").expect("deletion"); + logout.await.expect("task").expect("logout"); +} diff --git a/apps/auth-service/src/clients/tests/mod.rs b/apps/auth-service/src/clients/tests/mod.rs new file mode 100644 index 000000000..eac3dc636 --- /dev/null +++ b/apps/auth-service/src/clients/tests/mod.rs @@ -0,0 +1,96 @@ +//! Client changes reach running replicas on their next request, and each records +//! its event as made by whoever made it. Owners find and change only their own +//! clients, confirming what needs it, and a deletion leaves a tombstone without +//! deadlocking the token grants it revokes. +use super::*; +use crate::{ + account::{AccountError, AccountService, Owner}, + security::Session, + tests::{Browser, Replicas, change, register, registration, replace, until_blocked}, +}; +use piquel_common::{AuthenticationMethod, UserId, clients::RedirectUris}; +use piquel_repository::Database; + +mod deletion; +mod origins; +mod owners; +mod registry; + +/// An account, and the owner's operations on its clients, over the test database. +struct Account { + /// The scenario database. + database: Database, + /// The owner's operations. + service: AccountService, + /// A browser signed in to the account with a passkey, so confirmed. + browser: Browser, +} + +impl Account { + /// Creates an account over a migrated test database. + async fn new() -> Self { + let database = Replicas::database().await; + Self { + service: AccountService::new(database.clone()), + browser: Browser::new_account(&database).await, + database, + } + } + + /// The owner, as the browser signed in with a passkey shows them. + async fn owner(&self) -> Owner { + self.browser.owner(&self.database).await + } + + /// Signs another browser in to the account socially, which never confirms + /// with a passkey. + async fn social(&self) -> Browser { + let federation = AuthenticationMethod::Federation; + Browser::sign_in_with(&self.database, self.browser.user_id, federation).await + } + + /// Registers a client of `kind` calling back to `https://notes.example` as the + /// confirmed owner, and returns its ID. + async fn create(&self, kind: ClientKind) -> ClientId { + let origin = "https://notes.example"; + self.browser + .register_app(&self.database, kind, origin) + .await + } + + /// The owner's client `id`, as `owner` finds it. + async fn find(&self, owner: Owner, id: &ClientId) -> OwnedClient { + let found = self.service.owned_client(owner, id.as_str()).await; + found.expect("the owner's client") + } + + /// Makes `change` to client `id` as the owner, from a social session that a + /// passkey confirms while the change waits for the account lock, and returns + /// its result. + async fn confirmed_while_waiting( + &self, + id: &ClientId, + change: impl AsyncFnOnce(&OwnedClient) -> Result<(), AccountError>, + ) -> Result<(), AccountError> { + let stale = self.social().await; + let client = self.find(stale.owner(&self.database).await, id).await; + let mut holder = self.database.begin().await.expect("transaction"); + holder + .users() + .find_active_by_id_for_update(stale.user_id) + .await + .expect("lock") + .expect("account"); + let (result, ()) = tokio::join!(change(&client), async { + until_blocked(&mut holder, 1).await; + let session = holder.sessions().find_by_id(stale.session_id).await; + let session = session.expect("lookup").expect("session"); + let passkey = AuthenticationMethod::Passkey.into(); + Session::reauthenticate(&mut holder, &session, passkey) + .await + .expect("confirm"); + holder.commit().await.expect("commit"); + }); + result + } +} diff --git a/apps/auth-service/src/clients/tests/origins.rs b/apps/auth-service/src/clients/tests/origins.rs new file mode 100644 index 000000000..179b6f596 --- /dev/null +++ b/apps/auth-service/src/clients/tests/origins.rs @@ -0,0 +1,147 @@ +//! Related origins: counting their registrable domains, and approving them. +use super::*; + +/// Browsers count a related origin by its registrable domain's first label, so +/// `example.co.uk` is `example`, also within auth's own domain. An origin without +/// a registrable domain counts none within auth's domain, and is refused elsewhere. +#[test] +fn related_origins_count_registrable_domain_labels() { + let domain = |origin: &str| { + ClientRegistry::domain(&origin.parse().expect("origin"), "auth.piquel.fr") + .expect("countable origin") + }; + assert_eq!( + domain("https://app.example.co.uk").as_deref(), + Some("example") + ); + assert_eq!( + domain("https://notes.alice.github.io").as_deref(), + Some("alice") + ); + assert_eq!(domain("https://piquel.fr").as_deref(), Some("piquel")); + assert_eq!( + domain("https://notes.auth.piquel.fr").as_deref(), + Some("piquel") + ); + let localhost = "https://localhost:4443".parse().expect("origin"); + assert_eq!( + ClientRegistry::domain(&localhost, "localhost").expect("countable origin"), + None + ); + for public in ["https://github.io", "https://localhost"] { + assert!(matches!( + ClientRegistry::domain(&public.parse().expect("origin"), "auth.piquel.fr"), + Err(ClientRegistryError::PublicSuffix(_)) + )); + } +} + +/// Only a trusted client's redirect origins are approved, each once, and approved +/// origins never span more domains than every browser honours. Deleting the client +/// removes its origins. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn origin_approval_needs_trust_a_redirect_origin_and_few_domains() { + let database = Replicas::database().await; + let unique = UserId::new(); + // Six registrable domains, then a second origin on the first one. + let mut origins: Vec = (0..6) + .map(|domain| format!("https://d{domain}-{unique}.example")) + .chain([format!("https://www.d0-{unique}.example")]) + .map(|origin| origin.parse().expect("origin")) + .collect(); + let inside: RelatedOrigin = format!("https://{unique}.auth.piquel.fr") + .parse() + .expect("origin"); + origins.push(inside.clone()); + let client = ClientRegistration { + redirect_uris: RedirectUris::new( + origins + .iter() + .map(|origin| format!("{origin}/callback").parse().expect("callback")), + ) + .expect("callbacks"), + ..registration(ClientKind::Public, inside.as_str()) + }; + register(&database, &client).await.expect("client"); + let approve = async |origin: &RelatedOrigin| { + change(&database, async |registry| { + registry + .approve_origin(&client.id, origin, "auth.piquel.fr") + .await + }) + .await + }; + let remove = async |origin: &RelatedOrigin| { + change(&database, async |registry| { + registry.remove_origin(&client.id, origin).await + }) + .await + }; + assert!(matches!( + approve(&inside).await, + Err(ClientRegistryError::Untrusted(_)) + )); + replace( + &database, + &ClientRegistration { + trusted: true, + ..client.clone() + }, + ) + .await + .expect("trusted"); + let elsewhere = format!("https://elsewhere-{unique}.auth.piquel.fr") + .parse() + .expect("origin"); + assert!(matches!( + approve(&elsewhere).await, + Err(ClientRegistryError::NotRedirectOrigin { .. }) + )); + approve(&inside) + .await + .expect("an origin within auth's domain"); + assert!(matches!( + approve(&inside).await, + Err(ClientRegistryError::OriginApproved { .. }) + )); + let mut approved = Vec::new(); + let error = loop { + match approve(&origins[approved.len()]).await { + Ok(()) => approved.push(origins[approved.len()].clone()), + Err(error) => break error, + } + }; + let ClientRegistryError::TooManyDomains(domains) = error else { + panic!("a sixth domain is refused, not {error}"); + }; + assert_eq!(domains.len(), MAX_RELATED_ORIGIN_DOMAINS + 1); + // Other tests' origins within auth's domain count as `piquel`, and a database + // other runs left full refuses the first domain. Otherwise another origin on an + // approved domain still fits. + if !approved.is_empty() { + approve(&origins[6]) + .await + .expect("an already counted domain"); + approved.push(origins[6].clone()); + } + approved.push(inside.clone()); + for origin in &approved { + remove(origin).await.expect("removed"); + } + assert!(matches!( + remove(&approved[0]).await, + Err(ClientRegistryError::OriginNotApproved { .. }) + )); + + // Clients are tombstoned, so a trigger, not the query, removes the origins of a + // deleted one, whichever release deleted it. + approve(&inside).await.expect("approved again"); + change(&database, async |registry| { + registry.delete(&client.id).await + }) + .await + .expect("deleted"); + let approved = database.oidc().related_origins().await.expect("origins"); + assert!(approved.iter().all(|origin| origin.client_id != client.id)); +} diff --git a/apps/auth-service/src/clients/tests/owners.rs b/apps/auth-service/src/clients/tests/owners.rs new file mode 100644 index 000000000..f8e0e855c --- /dev/null +++ b/apps/auth-service/src/clients/tests/owners.rs @@ -0,0 +1,272 @@ +//! Owners finding and changing only their own clients, with a passkey +//! confirmation, valid settings, and never past an operator's suspension. +use super::*; +use crate::security::SessionError; + +/// An account lists and finds only its own live clients: another account's, an +/// operator's, an unknown ID and a malformed one are not found. Every operation +/// on one client takes what [`AccountService::owned_client`] found, so none +/// reaches them either. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn owners_find_only_their_own_clients() { + let account = Account::new().await; + let (alice, service) = (account.owner().await, &account.service); + let bob = Browser::new_account(&account.database).await; + let bob = bob.owner(&account.database).await; + let operated = registration(ClientKind::Public, "https://operated.example"); + register(&account.database, &operated) + .await + .expect("operator client"); + + let id = account.create(ClientKind::Confidential).await; + assert!(id.as_str().starts_with("c_"), "{id}"); + let listed = service.clients(&alice).await.expect("list"); + assert_eq!( + listed.iter().map(|client| &client.id).collect::>(), + [&id] + ); + let app = account.find(alice.clone(), &id).await; + let secrets = service.client_secrets(&app).await.expect("secrets"); + assert_eq!(secrets.len(), 1); + + assert_eq!(service.clients(&bob).await.expect("list"), []); + for (owner, id) in [ + (&bob, id.as_str()), + (&alice, operated.id.as_str()), + (&alice, "c_unknown"), + (&alice, "%FF"), + ] { + let found = service.owned_client(owner.clone(), id).await; + assert!( + matches!(found, Err(AccountError::Client(OwnedClientError::NotFound))), + "{id}" + ); + } +} + +/// Every change to a client needs a recent passkey confirmation: changing any +/// setting, pausing or resuming it. A refused change leaves the client as it was. +/// A confirmed owner rotates its secret and changes its settings. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn every_change_needs_a_confirmation() { + let account = Account::new().await; + let service = &account.service; + let id = account.create(ClientKind::Confidential).await; + let social = account.social().await.owner(&account.database).await; + let client = account.find(social, &id).await; + let logout = ClientPatch { + post_logout_uris: Some(vec!["https://attacker.example/".into()]), + ..ClientPatch::default() + }; + let rename = || ClientPatch { + display_name: Some("Renamed".into()), + ..ClientPatch::default() + }; + for refused in [ + service.update_client(&client, logout).await.map(drop), + service.update_client(&client, rename()).await.map(drop), + service.set_client_enabled(&client, false).await, + service.set_client_enabled(&client, true).await, + ] { + assert!( + matches!( + refused, + Err(AccountError::Owner(SessionError::StepUpRequired { .. })) + ), + "{refused:?}" + ); + } + let kept = account.database.oidc().find_client(id.as_str()).await; + let kept = kept.expect("lookup").expect("client"); + assert_eq!( + kept.display_name, "Notes", + "the refused changes were rolled back" + ); + assert_eq!(kept.post_logout_uris, Vec::::new()); + assert!(kept.enabled); + + let client = account.find(account.owner().await, &id).await; + let grace = "0".parse().expect("grace period"); + let secret = service.rotate_client_secret(&client, grace).await; + assert!(secret.expect("rotate").expose().starts_with("pqcs_")); + let patch = ClientPatch { + redirect_uris: Some(vec!["https://notes.example/auth".into()]), + ..rename() + }; + let changed = service.update_client(&client, patch).await.expect("change"); + assert_eq!(changed.display_name, "Renamed"); + assert_eq!(changed.redirect_uris, ["https://notes.example/auth"]); + service + .set_client_enabled(&client, false) + .await + .expect("disable"); +} + +/// An owner found from a cookie their session had before a passkey confirmation +/// never gains that confirmation, even when it commits while the change waits +/// for the account lock: the confirmation replaced the cookie. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires TEST_DATABASE_URL"] +async fn confirmations_never_reach_owners_found_before_them() { + let account = Account::new().await; + let service = &account.service; + let id = account.create(ClientKind::Confidential).await; + let redirect = ClientPatch { + redirect_uris: Some(vec!["https://attacker.example/callback".into()]), + ..ClientPatch::default() + }; + for result in [ + account + .confirmed_while_waiting(&id, async |client| { + service.update_client(client, redirect).await.map(drop) + }) + .await, + account + .confirmed_while_waiting(&id, async |client| { + let grace = GracePeriod::default(); + service.rotate_client_secret(client, grace).await.map(drop) + }) + .await, + account + .confirmed_while_waiting(&id, async |client| { + service.set_client_enabled(client, false).await + }) + .await, + account + .confirmed_while_waiting(&id, async |client| service.delete_client(client).await) + .await, + ] { + assert!( + matches!( + result, + Err(AccountError::Owner(SessionError::StepUpRequired { .. })) + ), + "{result:?}" + ); + } + let client = account.database.oidc().find_client(id.as_str()).await; + let client = client.expect("lookup").expect("client"); + assert_eq!(client.redirect_uris, ["https://notes.example/callback"]); + assert!(client.enabled && client.deleted_at.is_none()); + let secrets = account.database.oidc().client_secrets(&id).await; + assert_eq!(secrets.expect("secrets").len(), 1, "no secret was added"); +} + +/// An invalid setting names its field apart from what is wrong with it, so a +/// form can show the message beside it: owners grant only the standard scopes +/// and send browsers only to URIs auth accepts. Settings are checked before +/// anything else, so an unconfirmed owner's invalid registration is refused for +/// its settings rather than for the confirmation. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn invalid_settings_name_their_field_first() { + let account = Account::new().await; + let id = account.create(ClientKind::Public).await; + let client = account.find(account.owner().await, &id).await; + let social = account.social().await.owner(&account.database).await; + let blank = NewClient { + kind: ClientKind::Public, + settings: ClientSettings { + display_name: " ".into(), + ..ClientSettings::test("https://notes.example") + }, + }; + let invalid = |result: Result<(), AccountError>, field: ClientField| match result { + Err(AccountError::Client(OwnedClientError::InvalidSetting(error))) => { + assert_eq!(error.field(), &field); + assert_eq!(error.to_string(), format!("{field}: {}", error.reason())); + } + result => panic!("{field}: {result:?}"), + }; + let registered = account.service.create_client(&social, blank).await; + invalid(registered.map(drop), ClientField::DisplayName); + for (patch, field) in [ + ( + ClientPatch { + allowed_scopes: Some(vec!["openid".into(), "notes:read".into()]), + ..ClientPatch::default() + }, + ClientField::AllowedScopes, + ), + ( + ClientPatch { + redirect_uris: Some(vec!["http://notes.example/callback".into()]), + ..ClientPatch::default() + }, + ClientField::RedirectUris, + ), + ( + ClientPatch { + redirect_uris: Some(Vec::new()), + ..ClientPatch::default() + }, + ClientField::RedirectUris, + ), + ( + ClientPatch { + display_name: Some(" ".into()), + ..ClientPatch::default() + }, + ClientField::DisplayName, + ), + ] { + let changed = account.service.update_client(&client, patch).await; + invalid(changed.map(drop), field); + } +} + +/// An operator's suspension disables a client, and its owner cannot enable it, +/// though they can still see and disable it. Lifting the suspension leaves it +/// disabled, for the owner to enable. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn owners_cannot_enable_a_suspended_client() { + let account = Account::new().await; + let (service, owner) = (&account.service, account.owner().await); + let id = account.create(ClientKind::Public).await; + let client = account.find(owner.clone(), &id).await; + let suspend = async |suspended: bool| { + change(&account.database, async |registry| { + registry.set_suspended(&id, suspended).await + }) + .await + .expect("suspension"); + }; + let shown = async || account.find(owner.clone(), &id).await; + suspend(true).await; + let suspended = shown().await; + let suspended = suspended.client(); + assert!(suspended.suspended_at.is_some() && !suspended.enabled); + let enabled = service.set_client_enabled(&client, true).await; + assert!( + matches!( + enabled, + Err(AccountError::Client(OwnedClientError::Registry( + ClientRegistryError::Suspended(_) + ))) + ), + "{enabled:?}" + ); + assert!(matches!( + change(&account.database, async |registry| { + registry.set_enabled(&id, true).await + }) + .await, + Err(ClientRegistryError::Suspended(_)), + )); + service + .set_client_enabled(&client, false) + .await + .expect("disable"); + + suspend(false).await; + let lifted = shown().await; + let lifted = lifted.client(); + assert!(lifted.suspended_at.is_none() && !lifted.enabled); + service + .set_client_enabled(&client, true) + .await + .expect("enable"); +} diff --git a/apps/auth-service/src/clients/tests/registry.rs b/apps/auth-service/src/clients/tests/registry.rs new file mode 100644 index 000000000..9750094da --- /dev/null +++ b/apps/auth-service/src/clients/tests/registry.rs @@ -0,0 +1,416 @@ +//! The operator's registry: changes reaching every replica, secret rotation, +//! applying a deployment's client, and the registration quota. +use super::*; +use crate::tests::operator; +use axum::{ + Router, + body::Body, + http::{Method, Request, StatusCode, header}, + response::Response, +}; +use base64::Engine; +use piquel_common::clients::AllowedScopes; +use piquel_crypto::Secret; +use tower::ServiceExt; + +/// Sends `method` to `path` on `replica` from a browser page on `origin`, with an +/// optional form body and HTTP Basic credentials. +async fn send( + replica: &Router, + method: Method, + path: &str, + origin: &str, + form: &str, + basic: Option<(&ClientId, &str)>, +) -> Response { + let mut request = Request::builder() + .method(method.clone()) + .uri(path) + .header(header::ORIGIN, origin) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); + if method == Method::OPTIONS { + request = request.header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST"); + } + if let Some((id, secret)) = basic { + let credentials = + base64::engine::general_purpose::STANDARD.encode(format!("{id}:{secret}")); + request = request.header(header::AUTHORIZATION, format!("Basic {credentials}")); + } + replica + .clone() + .oneshot(request.body(Body::from(form.to_owned())).expect("request")) + .await + .expect("response") +} + +/// Whether a token-endpoint preflight from `origin` gets its CORS grant. +async fn cors(replica: &Router, origin: &str) -> bool { + let response = send(replica, Method::OPTIONS, "/oauth/token", origin, "", None).await; + response.status() == StatusCode::NO_CONTENT + && response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN] == origin +} + +/// Whether the token endpoint authenticates the public client `id`: an unusable +/// code then fails as a bad grant rather than a bad client. +async fn authenticates(replica: &Router, id: &ClientId, origin: &str) -> bool { + let form = format!("grant_type=authorization_code&code=unusable&client_id={id}"); + let response = send(replica, Method::POST, "/oauth/token", origin, &form, None).await; + response.status() != StatusCode::UNAUTHORIZED +} + +/// Creating, updating, disabling and enabling a public client changes CORS and +/// client authentication on the next request to either replica, with no restart. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn changes_apply_to_the_next_request_on_every_replica() { + let replicas = Replicas::new().await; + let database = Replicas::database().await; + let [first, second] = [(); 2].map(|()| format!("https://{}.example", UserId::new())); + let mut client = registration(ClientKind::Public, &first); + assert!(!cors(&replicas.a, &first).await, "not registered yet"); + + let secret = register(&database, &client).await.expect("create"); + assert!(secret.is_none(), "public clients have no secret"); + assert!(cors(&replicas.b, &first).await); + assert!(authenticates(&replicas.a, &client.id, &first).await); + + client.redirect_uris = + RedirectUris::new([format!("{second}/callback").parse().expect("callback")]) + .expect("one callback"); + replace(&database, &client).await.expect("update"); + assert!( + !cors(&replicas.a, &first).await, + "the old origin is dropped" + ); + assert!(cors(&replicas.b, &second).await); + + change(&database, async |registry| { + registry.set_enabled(&client.id, false).await + }) + .await + .expect("disable"); + assert!(!cors(&replicas.a, &second).await); + assert!(!authenticates(&replicas.b, &client.id, &second).await); + change(&database, async |registry| { + registry.set_enabled(&client.id, true).await + }) + .await + .expect("enable"); + assert!(authenticates(&replicas.a, &client.id, &second).await); + + let history = database + .events() + .history_for_client(&client.id, 10) + .await + .expect("history"); + assert!( + history + .iter() + .all(|event| event.actor == operator().context().actor) + ); + let client_id = client.id.clone(); + assert_eq!( + history + .into_iter() + .map(|stored| stored.event.known().cloned().expect("a known event")) + .collect::>(), + [ + DomainEvent::ClientEnabled { + client_id: client_id.clone() + }, + DomainEvent::ClientDisabled { + client_id: client_id.clone() + }, + DomainEvent::ClientUpdated { + client_id: client_id.clone(), + changed: vec![ClientField::RedirectUris], + }, + DomainEvent::ClientRegistered { + client_id, + kind: ClientKind::Public + }, + ] + ); +} + +/// During a rotation's grace period both secrets authenticate; once it ends, only +/// the newest does. A public client cannot be given a secret. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn rotated_secrets_overlap_until_their_grace_period_ends() { + let replicas = Replicas::new().await; + let database = Replicas::database().await; + let client = registration(ClientKind::Confidential, "https://api.example"); + // Revocation answers 200 for any token once the client authenticates. + let revokes = async |secret: &ClientSecret| { + send( + &replicas.a, + Method::POST, + "/oauth/revoke", + "https://api.example", + "token=unknown", + Some((&client.id, secret.expose())), + ) + .await + .status() + == StatusCode::OK + }; + let first = register(&database, &client) + .await + .expect("create") + .expect("confidential clients get a secret"); + assert!(revokes(&first).await); + + let rotate = async |id: &ClientId, grace: &str| { + let grace = grace.parse().expect("grace"); + change(&database, async |registry| { + registry.rotate_secret(id, grace).await + }) + .await + }; + let second = rotate(&client.id, "1h").await.expect("rotate"); + assert!(revokes(&first).await, "still in its grace period"); + assert!(revokes(&second).await); + + let third = rotate(&client.id, "0").await.expect("rotate and revoke"); + assert!(!revokes(&first).await); + assert!(!revokes(&second).await); + assert!(revokes(&third).await); + + let public = registration(ClientKind::Public, "https://web.example"); + register(&database, &public).await.expect("public client"); + assert!(matches!( + rotate(&public.id, "0").await, + Err(ClientRegistryError::Public(_)) + )); + assert!(matches!( + register(&database, &public).await, + Err(ClientRegistryError::Exists { .. }) + )); + assert!(matches!( + change(&database, async |registry| { + registry + .update(&public.id, |_| { + Ok(ClientRegistration { + kind: ClientKind::Confidential, + ..public.clone() + }) + }) + .await + }) + .await, + Err(ClientRegistryError::Immutable(_)) + )); + let unknown = "unknown-client".parse().expect("ID"); + assert!(matches!( + change(&database, async |registry| { + registry.set_enabled(&unknown, false).await + }) + .await, + Err(ClientRegistryError::Unknown(_)) + )); +} + +/// Applying a deployment's client registers it, then writes only what differs, so +/// each deploy can apply it again. A new secret overlaps with the previous ones for +/// the grace period, a previous secret applied again lasts, and a zero grace +/// revokes the others. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn apply_changes_only_what_differs() { + let replicas = Replicas::new().await; + let database = Replicas::database().await; + let origin = format!("https://{}.example", UserId::new()); + let mut client = registration(ClientKind::Confidential, &origin); + let [first, second] = [(); 2].map(|()| Secret::generate().expect("secret").encoded()); + let apply = async |client: &ClientRegistration, secret: Option<&str>, grace: &str| { + let secret = secret.map(|secret| ClientSecret::parse(secret).expect("secret")); + let grace = grace.parse().expect("grace"); + change(&database, async |registry| { + registry.apply(client, secret, grace).await + }) + .await + }; + let revokes = async |secret: &str| { + send( + &replicas.a, + Method::POST, + "/oauth/revoke", + &origin, + "token=unknown", + Some((&client.id, secret)), + ) + .await + .status() + == StatusCode::OK + }; + + assert_eq!( + apply(&client, Some(&first), "1h").await.expect("register"), + Applied::Registered + ); + assert!(revokes(&first).await); + let mut reordered = client.clone(); + reordered.allowed_scopes = + AllowedScopes::new(client.allowed_scopes.iter().rev().cloned()).expect("scopes"); + assert_eq!( + apply(&reordered, Some(&first), "1h").await.expect("again"), + Applied::Unchanged + ); + + client.display_name = "Renamed app".parse().expect("display name"); + assert_eq!( + apply(&client, Some(&first), "1h").await.expect("rename"), + Applied::Updated + ); + assert_eq!( + apply(&client, Some(&second), "1h") + .await + .expect("new secret"), + Applied::Updated + ); + assert!( + revokes(&first).await, + "the previous secret is in its grace period" + ); + assert!(revokes(&second).await); + + assert_eq!( + apply(&client, Some(&first), "1h").await.expect("back"), + Applied::Updated, + "a secret in its grace period is made lasting again" + ); + assert_eq!( + apply(&client, Some(&first), "0").await.expect("revoke"), + Applied::Updated + ); + assert!(revokes(&first).await); + assert!(!revokes(&second).await); + assert_eq!( + apply(&client, Some(&first), "0").await.expect("again"), + Applied::Unchanged + ); + + let history = database + .events() + .history_for_client(&client.id, 10) + .await + .expect("history"); + assert!(matches!( + history + .iter() + .map(|stored| stored.event.known().expect("a known event")) + .collect::>()[..], + [ + DomainEvent::ClientSecretRotated { .. }, + DomainEvent::ClientSecretRotated { .. }, + DomainEvent::ClientSecretRotated { .. }, + DomainEvent::ClientUpdated { .. }, + DomainEvent::ClientRegistered { .. }, + ] + )); +} + +/// Applying refuses a confidential client without its secret, a public one with a +/// secret, and a change of kind. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn apply_refuses_mismatched_secrets_and_kinds() { + let database = Replicas::database().await; + let client = registration(ClientKind::Confidential, "https://api.example"); + let first = Secret::generate().expect("secret").encoded(); + let apply = async |client: &ClientRegistration, secret: Option<&str>| { + let secret = secret.map(|secret| ClientSecret::parse(secret).expect("secret")); + let grace = "1h".parse().expect("grace"); + change(&database, async |registry| { + registry.apply(client, secret, grace).await + }) + .await + }; + apply(&client, Some(&first)).await.expect("register"); + assert!(matches!( + apply(&client, None).await, + Err(ClientRegistryError::MissingSecret(_)) + )); + let public = ClientRegistration { + kind: ClientKind::Public, + ..client.clone() + }; + assert!(matches!( + apply(&public, Some(&first)).await, + Err(ClientRegistryError::Public(_)) + )); + assert!(matches!( + apply(&public, None).await, + Err(ClientRegistryError::Immutable(_)) + )); +} + +/// Concurrent registrations by one account count one another: exactly +/// [`MAX_OWNED_CLIENTS`] succeed. Deleting one frees a place, until the account +/// registered [`MAX_DAILY_REGISTRATIONS`] clients that day. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires TEST_DATABASE_URL"] +async fn the_quota_holds_under_concurrent_registrations() { + let database = Replicas::database().await; + let owner = Browser::new_account(&database).await.user_id; + let attempts = MAX_OWNED_CLIENTS + 4; + let mut registrations = tokio::task::JoinSet::new(); + for _ in 0..attempts { + let database = database.clone(); + registrations.spawn(async move { + let client = registration(ClientKind::Public, "https://quota.example"); + change(&database, async |registry| { + registry + .create(ClientOwner::Account(owner), &client, None) + .await + }) + .await + .map(|_| client.id) + }); + } + let (mut registered, mut refused) = (Vec::new(), 0); + while let Some(result) = registrations.join_next().await { + match result.expect("task") { + Ok(id) => registered.push(id), + Err(ClientRegistryError::QuotaExceeded) => refused += 1, + Err(error) => panic!("unexpected failure: {error}"), + } + } + assert_eq!(registered.len(), MAX_OWNED_CLIENTS as usize); + assert_eq!(refused, attempts - MAX_OWNED_CLIENTS); + assert_eq!( + database + .oidc() + .count_owned_clients(owner, chrono::Duration::days(1)) + .await + .expect("count") + .live, + u64::from(MAX_OWNED_CLIENTS) + ); + + // Deleting frees a place, but deleted clients still count against the + // daily limit, so an account cannot pile up tombstones. + for registration_number in MAX_OWNED_CLIENTS..=MAX_DAILY_REGISTRATIONS { + let freed = registered.pop().expect("a client to delete"); + change(&database, async |registry| registry.delete(&freed).await) + .await + .expect("delete"); + let client = registration(ClientKind::Public, "https://quota.example"); + let created = change(&database, async |registry| { + registry + .create(ClientOwner::Account(owner), &client, None) + .await + }) + .await; + if registration_number < MAX_DAILY_REGISTRATIONS { + created.expect("a deletion frees a place"); + registered.push(client.id); + } else { + assert!(matches!( + created, + Err(ClientRegistryError::DailyLimitExceeded) + )); + } + } +} diff --git a/apps/auth-service/src/federation/tests.rs b/apps/auth-service/src/federation/tests.rs deleted file mode 100644 index 45ce28309..000000000 --- a/apps/auth-service/src/federation/tests.rs +++ /dev/null @@ -1,1160 +0,0 @@ -//! Federation protocol, browser-binding and transactional identity policy tests. - -use super::{ - providers::{GoogleClaims, GoogleProtocol, IdentityStrategy, ProviderEndpoints}, - *, -}; -use crate::{ - account::{AccountApplication, AccountError, AccountService}, - tests::{pending_sign_in, unusable_passkey}, -}; -use axum::{ - Json, - body::Body, - http::{HeaderValue, Method, Request, StatusCode, header}, - routing::post, -}; -use piquel_auth::{KeyCache, KeySet}; -use piquel_common::PasskeyId; -use piquel_common::{ - Handle, - protocol::jwt::{Algorithm, TokenType}, -}; -use piquel_crypto::Rs256Key; -use piquel_crypto::Secret; -use piquel_repository::{ - DatabaseConfig, DatabaseTransaction, InsertExternalIdentity, InsertUser, InsertVerifiedEmail, -}; -use std::collections::HashMap; -use tower::ServiceExt; -use tracing::Instrument; - -/// Isolated database fixture with replaceable provider endpoints and unique subjects. -struct TestApp { - /// Federation state whose back-channel requests use a local HTTP fixture. - app: FederationApplication, - /// Provider mock server, stopped when the fixture is dropped. - task: tokio::task::JoinHandle<()>, - /// Temporary provider secret deleted with the fixture. - secret_file: std::path::PathBuf, - /// Unique numeric subject returned by this fixture’s provider. - subject: String, -} -impl Drop for TestApp { - /// Stops the fixture server and attempts to remove its temporary secret. - fn drop(&mut self) { - self.task.abort(); - if let Err(error) = std::fs::remove_file(&self.secret_file) { - tracing::warn!(%error, "could not remove federation fixture secret"); - } - } -} -impl TestApp { - /// The federation routes and the shared settings, as the public listener - /// serves them. - fn routes(&self) -> axum::Router { - self.app - .clone() - .routes() - .merge(AccountApplication::new(self.app.database.clone()).routes()) - } - /// Creates a provider fixture with no verified contact address. - async fn new() -> Self { - Self::with_email(None).await - } - /// Creates unique provider evidence with an optional verified primary address. - async fn with_email(email: Option<&str>) -> Self { - let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") - .required() - .expect("TEST_DATABASE_URL must name an isolated migrated PostgreSQL database"); - let database = Database::connect( - DatabaseConfig::new(&url, 5, StdDuration::from_secs(5)) - .expect("database configuration"), - ) - .await - .expect("database"); - database.run_migrations().await.expect("migrations"); - let subject = u64::from_be_bytes( - piquel_crypto::Secret::generate() - .expect("random") - .as_bytes()[..8] - .try_into() - .expect("eight bytes"), - ) - .max(1); - let emails = email.map_or_else( - || serde_json::json!([]), - |email| serde_json::json!([{"email":email,"primary":true,"verified":true}]), - ); - let mock = Router::new() - .route( - "/token", - post(|| async { Json(serde_json::json!({"access_token":"mock-token"})) }), - ) - .route( - "/user", - get(move || async move { - Json(serde_json::json!({"id":subject,"name":"Social User","login":"social"})) - }), - ) - .route( - "/emails", - get(move || { - let emails = emails.clone(); - async move { Json(emails) } - }), - ); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("mock listener"); - let base = format!("http://{}", listener.local_addr().expect("mock address")); - let task = tokio::spawn(async move { - axum::serve(listener, mock).await.expect("mock server"); - }); - let secret_file = - std::env::temp_dir().join(format!("piquel-federation-test-{}", TokenId::new())); - std::fs::write(&secret_file, "test-secret").expect("mock provider secret"); - let config = ProviderConfig::test(&secret_file); - let mut app = FederationApplication::new( - database, - &FederationConfig { - origin: "https://auth.piquel.fr/" - .parse::() - .expect("origin"), - providers: BTreeMap::from([(Provider::GitHub, config)]), - }, - ) - .expect("federation"); - let endpoints = app - .endpoints - .get_mut(&Provider::GitHub) - .expect("GitHub facts"); - endpoints.token = format!("{base}/token"); - match &mut endpoints.identity { - IdentityStrategy::GitHub(protocol) => { - protocol.user = format!("{base}/user"); - protocol.emails = format!("{base}/emails"); - } - IdentityStrategy::Google(_) => panic!("GitHub must use OAuth profile fetching"), - } - Self { - app, - task, - secret_file, - subject: subject.to_string(), - } - } - /// Runs a complete GitHub authorization start and bound callback. - async fn callback(&self) -> Response { - self.callback_from(None).await - } - /// Starts a GitHub sign-in returning to `return_to`, as the sign-in page does, - /// and returns the provider's `state` and the browser's flow cookie pair. - async fn start(&self, return_to: &str) -> (String, String) { - let (url, FlowCookie(Flow::Started(browser))) = self - .app - .start_sign_in(Provider::GitHub, return_to) - .await - .expect("start") - else { - unreachable!("starting a sign-in sets the flow's cookie") - }; - let state = url - .query_pairs() - .find(|(name, _)| name == "state") - .expect("state") - .1 - .into_owned(); - let cookie = format!( - "{}={}", - BrowserCookie::Federation.as_str(), - browser.encoded() - ); - (state, cookie) - } - /// Runs [`Self::callback`] in a browser that may hold a `session` cookie pair. - async fn callback_from(&self, session: Option<&str>) -> Response { - let (state, mut cookie) = self.start(DEFAULT_RETURN_TO).await; - if let Some(session) = session { - cookie = format!("{cookie}; {session}"); - } - self.routes() - .oneshot(TestApp::request( - Method::GET, - &format!("/login/github/callback?state={state}&code=mock-code"), - Some(&cookie), - &serde_json::Value::Null, - )) - .await - .expect("callback") - } - /// Creates a unique account with optional verified email and passkey. - async fn user(&self, email: Option<&str>, with_key: bool) -> UserId { - let id = UserId::new(); - let mut tx = self.app.database.begin().await.expect("transaction"); - tx.users() - .insert(&InsertUser { - id, - handle: Handle::parse(&format!("fed-{}", &TokenId::new().to_string()[24..])) - .expect("handle"), - display_name: "Federation Test".into(), - }) - .await - .expect("user"); - if let Some(email) = email { - tx.emails() - .insert_verified(&InsertVerifiedEmail { - id: piquel_common::EmailId::new(), - user_id: id, - normalized_email: email.into(), - is_primary: true, - verified_at: Utc::now(), - }) - .await - .expect("email"); - } - if with_key { - self.key(&mut tx, id).await; - } - tx.commit().await.expect("commit"); - id - } - /// Adds passkey-presence evidence; ceremony cryptography is covered by passkey tests. - async fn key(&self, tx: &mut DatabaseTransaction<'_>, user_id: UserId) { - // Federation only checks key presence; cryptographic ceremony coverage lives in passkey tests. - tx.passkeys() - .insert(&unusable_passkey(user_id)) - .await - .expect("key"); - } - /// Stores browser-bound evidence optionally targeting an existing account. - async fn pending( - &self, - owner: Option, - email: Option<&str>, - ) -> (PendingFederation, HeaderMap) { - let secret = Secret::generate().expect("browser secret"); - let pending = PendingFederation { - email: email.map(str::to_owned), - link_user_id: owner, - ..pending_sign_in(&secret) - }; - self.app - .database - .federation() - .insert_pending(&pending) - .await - .expect("pending identity"); - let cookie = format!( - "{}={}", - BrowserCookie::FederationPending.as_str(), - secret.encoded() - ); - (pending, Self::cookies(&cookie)) - } - /// Creates a social browser session, optionally confirmed with a passkey now. - async fn session(&self, user_id: UserId, confirmed: bool) -> (SessionId, String) { - let mut tx = self.app.database.begin().await.expect("transaction"); - let cookie = security::Session::create( - &mut tx, - security::RequestContext::TEST, - user_id, - AuthenticationMethod::Federation.into(), - ) - .await - .expect("session"); - let raw = format!("{}={}", BrowserCookie::Session.as_str(), cookie.encoded()); - tx.commit().await.expect("commit"); - let session = security::Session::required(&self.app.database, &Self::cookies(&raw)) - .await - .expect("active session"); - if confirmed { - self.app - .database - .sessions() - .confirm_passkey(session.id, PasskeyId::new(), chrono::Utc::now()) - .await - .expect("confirm"); - } - (session.id, raw) - } - /// Links this fixture's provider subject to `user_id`. - async fn link(&self, user_id: UserId) { - self.app - .database - .federation() - .insert_identity(&InsertExternalIdentity { - id: TokenId::new(), - user_id, - provider: piquel_common::Provider::GitHub, - issuer: ProviderEndpoints::new(Provider::GitHub, &reqwest::Client::new()) - .expect("GitHub facts") - .issuer - .into(), - subject: self.subject.clone(), - linked_email: None, - }) - .await - .expect("known identity"); - } - /// The headers of a browser sending the `cookie` pairs. - fn cookies(cookie: &str) -> HeaderMap { - let mut headers = HeaderMap::new(); - headers.insert( - header::COOKIE, - HeaderValue::from_str(cookie).expect("cookie"), - ); - headers - } - /// Finds the active session a cookie pair names. - async fn active(&self, cookie: &str) -> Option { - security::Session::optional(&self.app.database, &Self::cookies(cookie)) - .await - .expect("session lookup") - } - /// Links this browser's pending evidence, its `pending` headers, to the account - /// of the session `cookie` names, as the sign-in page does. - async fn link_pending( - &self, - cookie: &str, - pending: &HeaderMap, - ) -> Result { - let account = AccountService::new(self.app.database.clone()); - let owner = account - .owner(security::RequestContext::TEST, &Self::cookies(cookie)) - .await - .expect("session lookup") - .expect("signed in"); - account - .link_identity(&owner, pending) - .await - .map(|(return_to, _)| return_to) - } - /// Borrows Google's replaceable verification facts from the fixture. - fn google_protocol(&self) -> &GoogleProtocol { - match &self.app.endpoints[&Provider::Google].identity { - IdentityStrategy::Google(protocol) => protocol, - IdentityStrategy::GitHub(_) => panic!("Google must use signed ID tokens"), - } - } - - /// Builds a JSON HTTP request with an optional browser-cookie header. - fn request( - method: Method, - path: &str, - cookie: Option<&str>, - body: &serde_json::Value, - ) -> Request { - let mut request = Request::builder() - .extension(crate::security::RequestContext::TEST) - .method(method) - .uri(path) - .header(header::CONTENT_TYPE, "application/json"); - if let Some(cookie) = cookie { - request = request.header(header::COOKIE, cookie); - } - request.body(Body::from(body.to_string())).expect("request") - } -} -/// Accepts auth paths only, and rejects duplicated pending-browser cookies. -#[test] -fn return_destinations_and_browser_bindings_are_strict() { - for value in [ - "//evil.test", - "/\\evil.test", - "https://evil.test", - "https://auth.piquel.fr/settings", - "/login#x", - "/\n/evil", - "settings", - "javascript:alert(1)", - "https:\\\\evil.test", - ] { - assert!(ReturnTo::parse(Some(value)).is_err(), "{value}"); - } - let path = "/oauth/authorize?request=abc"; - assert_eq!(ReturnTo::parse(Some(path)).expect(path).0, path); - assert_eq!( - ReturnTo::parse(None).expect("default return").0, - DEFAULT_RETURN_TO - ); - assert!(ReturnTo::parse(Some(&format!("/{}", "x".repeat(MAX_RETURN_TO_BYTES)))).is_err()); - let secret = Secret::generate().expect("browser secret"); - let mut headers = HeaderMap::new(); - headers.insert( - header::COOKIE, - HeaderValue::from_str(&format!( - "{0}={1}; {0}={1}", - BrowserCookie::FederationPending.as_str(), - secret.encoded() - )) - .expect("cookie"), - ); - assert!(BrowserCookie::FederationPending.read(&headers).is_none()); -} - -/// Callbacks require browser state and retain unregistered subjects as pending evidence. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn provider_mock_callback_requires_browser_state_and_stays_pending() { - let test = TestApp::new().await; - let router = test.routes(); - let (state, cookie) = test.start(DEFAULT_RETURN_TO).await; - let path = format!("/login/github/callback?code=mock-code&state={state}"); - let response = router - .clone() - .oneshot(TestApp::request( - Method::GET, - &path, - None, - &serde_json::Value::Null, - )) - .await - .expect("unbound callback"); - assert_eq!(response.status(), StatusCode::UNAUTHORIZED); - let response = router - .clone() - .oneshot(TestApp::request( - Method::GET, - &path, - Some(&cookie), - &serde_json::Value::Null, - )) - .await - .expect("callback"); - assert_eq!(response.status(), StatusCode::SEE_OTHER); - assert_eq!(response.headers()[header::LOCATION], "/login?social=signup"); - assert!( - !response - .headers() - .get_all(header::SET_COOKIE) - .iter() - .any(|value| value - .to_str() - .expect("cookie") - .starts_with("__Host-piquel_session=")) - ); - let response = router - .oneshot(TestApp::request( - Method::GET, - &path, - Some(&cookie), - &serde_json::Value::Null, - )) - .await - .expect("replay"); - assert_eq!(response.status(), StatusCode::BAD_REQUEST); -} - -/// Signup must create its first passkey and cannot claim an existing account’s email. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn onboarding_commits_only_with_first_key_and_browser_and_never_claims_existing_email() { - let test = TestApp::new().await; - let (pending, headers) = test.pending(None, None).await; - assert!( - FederationApplication::pending_signup(&test.app.database, &headers, TokenId::new()) - .await - .is_err(), - "registration must name the displayed pending signup" - ); - FederationApplication::pending_signup(&test.app.database, &headers, pending.id) - .await - .expect("pending signup"); - let user = test.user(None, false).await; - let mut tx = test.app.database.begin().await.expect("tx"); - assert!( - FederationApplication::attach_signup( - &mut tx, - &security::RequestContext::TEST.actor(piquel_common::events::Actor::Anonymous), - pending.id, - &headers, - user - ) - .await - .is_err() - ); - tx.rollback().await.expect("rollback"); - let mut tx = test.app.database.begin().await.expect("tx"); - test.key(&mut tx, user).await; - assert!( - FederationApplication::attach_signup( - &mut tx, - &security::RequestContext::TEST.actor(piquel_common::events::Actor::Anonymous), - pending.id, - &HeaderMap::new(), - user - ) - .await - .is_err() - ); - FederationApplication::attach_signup( - &mut tx, - &security::RequestContext::TEST.actor(piquel_common::events::Actor::Anonymous), - pending.id, - &headers, - user, - ) - .await - .expect("first key authorizes signup"); - tx.commit().await.expect("commit"); - assert_eq!( - test.app - .database - .federation() - .find_active(&pending.issuer, &pending.subject) - .await - .expect("identity") - .expect("linked") - .user_id, - user - ); - let email = format!("{}@example.com", TokenId::new()); - test.user(Some(&email), true).await; - let (pending, headers) = test.pending(None, Some(&email)).await; - let mut tx = test.app.database.begin().await.expect("tx"); - assert!( - FederationApplication::attach_signup( - &mut tx, - &security::RequestContext::TEST.actor(piquel_common::events::Actor::Anonymous), - pending.id, - &headers, - user - ) - .await - .is_err() - ); - tx.rollback().await.expect("rollback"); -} - -/// Linking and unlinking require the intended account’s recent passkey confirmation; -/// unlink frees the subject and preserves email. -#[expect( - clippy::too_many_lines, - reason = "Keep one pending link from rejection through linking and unlinking together." -)] -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn linking_requires_target_confirmation_and_unlink_releases_subject_without_changing_email() { - let test = TestApp::new().await; - let email = format!("{}@example.com", TokenId::new()); - let target = test.user(Some(&email), true).await; - let other = test.user(None, true).await; - let observed = format!("{}@example.com", TokenId::new()); - let (pending, pending_headers) = test.pending(Some(target), Some(&observed)).await; - let (_, other_cookie) = test.session(other, true).await; - let (target_session, target_cookie) = test.session(target, false).await; - let (other_session, _) = test.session(target, false).await; - let refused = test.link_pending(&other_cookie, &pending_headers).await; - assert!( - matches!( - refused, - Err(AccountError::Identity(FederationError::LinkAccountMismatch)) - ), - "another account's confirmation cannot link: {refused:?}" - ); - // Confirmation comes first, before the browser's pending cookie is read. - for pending in [&pending_headers, &HeaderMap::new()] { - let refused = test.link_pending(&target_cookie, pending).await; - assert!( - matches!( - refused, - Err(AccountError::Owner(SessionError::StepUpRequired { .. })) - ), - "an unconfirmed session cannot link: {refused:?}" - ); - } - let router = test.routes(); - let response = router - .clone() - .oneshot(TestApp::request( - Method::DELETE, - "/account/social-identities/github", - Some(&target_cookie), - &serde_json::json!({}), - )) - .await - .expect("unconfirmed rejection"); - security::tests::assert_step_up_required(response).await; - test.app - .database - .sessions() - .confirm_passkey(target_session, PasskeyId::new(), chrono::Utc::now()) - .await - .expect("confirm"); - let return_to = test - .link_pending(&target_cookie, &pending_headers) - .await - .expect("link"); - assert_eq!(return_to, pending.return_to); - assert!( - test.app - .database - .sessions() - .find_active_by_id(other_session) - .await - .expect("other session") - .is_some() - ); - assert_eq!( - test.app - .database - .emails() - .find_active_verified(&email) - .await - .expect("email") - .expect("owner") - .user_id, - target - ); - assert!( - test.app - .database - .emails() - .find_active_verified(&observed) - .await - .expect("observation") - .is_none() - ); - let response = router - .oneshot(TestApp::request( - Method::DELETE, - "/account/social-identities/github", - Some(&target_cookie), - &serde_json::json!({}), - )) - .await - .expect("unlink"); - assert_eq!(response.status(), StatusCode::NO_CONTENT); - assert!( - test.app - .database - .sessions() - .find_active_by_id(other_session) - .await - .expect("revoked other session") - .is_none() - ); - test.app - .database - .federation() - .insert_identity(&FederationApplication::identity(&pending, other)) - .await - .expect("unlinked subject reusable"); -} - -/// Google evidence requires trusted signatures and claims but does not require email. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn google_mock_validates_signature_audience_nonce_and_expiry_without_requiring_email() { - let mut test = TestApp::new().await; - let rsa = Rs256Key::generate("google-test").expect("RSA test key"); - let sign = |key: &Rs256Key, claims: &serde_json::Value| { - key.sign(TokenType::Id, claims).expect("signed token") - }; - let mut claims = serde_json::json!({"iss":"https://accounts.google.com","sub":"12345","aud":"test-client","iat":Utc::now().timestamp(),"exp":Utc::now().timestamp()+300,"nonce":"test-nonce"}); - let valid = sign(&rsa, &claims); - claims["aud"] = serde_json::json!("another-client"); - let wrong_audience = sign(&rsa, &claims); - claims["aud"] = serde_json::json!("test-client"); - claims["exp"] = serde_json::json!(Utc::now().timestamp() - 120); - let expired = sign(&rsa, &claims); - let other_rsa = Rs256Key::generate("google-test").expect("untrusted key"); - claims["exp"] = serde_json::json!(Utc::now().timestamp() + 300); - let wrong_signature = sign(&other_rsa, &claims); - let keys = rsa.jwks().clone(); - let tokens = Arc::new(HashMap::from([ - ("valid".to_owned(), valid), - ("wrong-audience".to_owned(), wrong_audience), - ("expired".to_owned(), expired), - ("wrong-signature".to_owned(), wrong_signature), - ])); - let mock = Router::new() - .route( - "/keys", - get(move || { - let keys = keys.clone(); - async move { Json(keys) } - }), - ) - .route( - "/token/{kind}", - get(move |Path(kind): Path| { - let tokens = tokens.clone(); - async move { Json(serde_json::json!({"id_token":tokens[&kind]})) } - }), - ); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("mock listener"); - let base = format!("http://{}", listener.local_addr().expect("address")); - let task = tokio::spawn(async move { - axum::serve(listener, mock).await.expect("mock server"); - }); - match &mut test - .app - .endpoints - .get_mut(&Provider::Google) - .expect("Google facts") - .identity - { - IdentityStrategy::Google(protocol) => { - protocol.keys = KeyCache::new( - format!("{base}/keys").parse().expect("mock key URL"), - reqwest::Client::new(), - ); - } - IdentityStrategy::GitHub(_) => panic!("Google must use signed ID tokens"), - } - let response = test - .app - .client - .get(format!("{base}/token/valid")) - .send() - .await - .expect("valid response"); - let identity = test - .app - .google_identity( - response, - "test-client", - "test-nonce", - test.google_protocol(), - ) - .await - .expect("valid Google identity without email"); - assert_eq!(identity.subject, "12345"); - assert!(identity.email.is_none()); - for (kind, nonce, expected) in [ - ("valid", "wrong-nonce", "nonce does not match"), - ("wrong-audience", "test-nonce", "not for this client"), - ("expired", "test-nonce", "has expired"), - ("wrong-signature", "test-nonce", "failed verification"), - ] { - let response = test - .app - .client - .get(format!("{base}/token/{kind}")) - .send() - .await - .expect("mock response"); - let error = test - .app - .google_identity(response, "test-client", nonce, test.google_protocol()) - .await - .err() - .expect("rejected"); - assert!(error.to_string().contains(expected), "{kind}: {error}"); - } - task.abort(); -} - -/// Fetching Google's signing keys is a client span of the request that needed them, -/// with its method, host and status only. -#[tokio::test] -async fn google_key_fetch_is_a_client_span_of_its_request() { - let capture = piquel_telemetry::Telemetry::capture(crate::TELEMETRY_FILTER); - let rsa = Rs256Key::generate("google-test").expect("RSA test key"); - let token = rsa - .sign(TokenType::Id, &serde_json::json!({})) - .expect("signed token"); - let keys = rsa.jwks().clone(); - let mock = Router::new().route("/keys", get(move || async move { Json(keys) })); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("mock listener"); - let url = format!( - "http://{}/keys?client=secret", - listener.local_addr().expect("address") - ); - let task = tokio::spawn(async move { - axum::serve(listener, mock).await.expect("mock server"); - }); - let cache = KeyCache::new(url.parse().expect("mock key URL"), reqwest::Client::new()); - let jws = piquel_auth::Jws::parse(&token).expect("JWS"); - let request = tracing::info_span!("request"); - cache - .verify(&jws, Algorithm::Rs256) - .instrument(request) - .await - .expect("verified"); - task.abort(); - - let spans = capture.spans(); - let request = spans - .iter() - .find(|span| span.name == "request") - .expect("request span"); - let fetch = spans - .iter() - .find(|span| span.name == "GET") - .expect("key fetch span"); - assert_eq!(fetch.parent_span_id, request.span_context.span_id()); - assert_eq!(format!("{:?}", fetch.span_kind), "Client"); - let attributes: Vec<_> = fetch - .attributes - .iter() - .map(|attribute| format!("{}={}", attribute.key, attribute.value)) - .collect(); - for expected in [ - "http.request.method=GET", - "http.response.status_code=200", - "server.address=127.0.0.1", - ] { - assert!( - attributes.iter().any(|a| a == expected), - "{expected}: {attributes:?}" - ); - } - assert!( - !attributes - .iter() - .any(|attribute| attribute.contains("/keys") || attribute.contains("secret")), - "no path or query: {attributes:?}" - ); - let status = fetch - .attributes - .iter() - .find(|attribute| attribute.key.as_str() == "http.response.status_code") - .expect("status"); - assert_eq!( - format!("{:?}", status.value), - "I64(200)", - "an integer status" - ); -} - -/// Stable provider subjects take priority over email observations and require an existing passkey. -#[expect( - clippy::too_many_lines, - reason = "Keep the callback precedence scenario and the session it yields together." -)] -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn callback_email_collision_never_links_and_known_subject_never_bootstraps_a_missing_key() { - let observed = format!("{}@example.com", TokenId::new()); - let original = format!("{}@example.com", TokenId::new()); - let test = TestApp::with_email(Some(&observed)).await; - let email_owner = test.user(Some(&observed), true).await; - let response = test.callback().await; - assert_eq!(response.status(), StatusCode::SEE_OTHER); - assert_eq!(response.headers()[header::LOCATION], "/login?social=link"); - assert!( - test.app - .database - .federation() - .find_active( - ProviderEndpoints::new(Provider::GitHub, &reqwest::Client::new()) - .expect("GitHub facts") - .issuer, - &test.subject - ) - .await - .expect("identity") - .is_none() - ); - let subject_owner = test.user(Some(&original), false).await; - test.app - .database - .federation() - .insert_identity(&InsertExternalIdentity { - id: TokenId::new(), - user_id: subject_owner, - provider: piquel_common::Provider::GitHub, - issuer: ProviderEndpoints::new(Provider::GitHub, &reqwest::Client::new()) - .expect("GitHub facts") - .issuer - .into(), - subject: test.subject.clone(), - linked_email: Some(original.clone()), - }) - .await - .expect("known identity"); - let response = test.callback().await; - assert_eq!( - response.status(), - StatusCode::UNAUTHORIZED, - "known accounts cannot bootstrap from social login" - ); - let mut tx = test.app.database.begin().await.expect("tx"); - test.key(&mut tx, subject_owner).await; - tx.commit().await.expect("commit"); - let response = test.callback().await; - assert_eq!(response.status(), StatusCode::SEE_OTHER); - assert_eq!(response.headers()[header::LOCATION], DEFAULT_RETURN_TO); - let session_cookie = response - .headers() - .get_all(header::SET_COOKIE) - .iter() - .map(|value| value.to_str().expect("cookie")) - .find(|cookie| cookie.starts_with("__Host-piquel_session=")) - .expect("session cookie") - .split(';') - .next() - .expect("cookie pair"); - let mut headers = HeaderMap::new(); - headers.insert( - header::COOKIE, - HeaderValue::from_str(session_cookie).expect("cookie"), - ); - let session = security::Session::required(&test.app.database, &headers) - .await - .expect("social session"); - assert_eq!( - session.user_id, subject_owner, - "stable subject takes priority over email observation" - ); - assert!( - session.passkey_confirmed_at.is_none(), - "social sign-in never confirms a passkey" - ); - let response = test - .routes() - .oneshot(TestApp::request( - Method::DELETE, - "/account/social-identities/github", - Some(session_cookie), - &serde_json::json!({}), - )) - .await - .expect("unlink"); - security::tests::assert_step_up_required(response).await; - assert_eq!( - test.app - .database - .emails() - .find_active_verified(&original) - .await - .expect("original email") - .expect("owner") - .user_id, - subject_owner - ); - assert_eq!( - test.app - .database - .emails() - .find_active_verified(&observed) - .await - .expect("observed email") - .expect("owner") - .user_id, - email_owner - ); -} - -/// ID-token verification rejects malformed claims, untrusted issuers and additional audiences. -#[tokio::test] -async fn google_signed_tokens_require_well_typed_trusted_issuer_and_audience() { - let rsa = Rs256Key::generate("google-test").expect("RSA key"); - let IdentityStrategy::Google(mut protocol) = - ProviderEndpoints::new(Provider::Google, &reqwest::Client::new()) - .expect("Google facts") - .identity - else { - panic!("Google must use signed ID tokens"); - }; - protocol.keys = KeyCache::fixed( - KeySet::parse(&serde_json::to_vec(&rsa.jwks()).expect("JWKS")).expect("key set"), - ); - let valid = serde_json::json!({"iss":"https://accounts.google.com","aud":"client","sub":"subject","iat":Utc::now().timestamp(),"exp":Utc::now().timestamp()+300,"nonce":"nonce"}); - let verify = async |claims: &serde_json::Value| { - let token = rsa.sign(TokenType::Id, claims).expect("signed token"); - GoogleClaims::verify(&token, &protocol, "client", "nonce").await - }; - assert!(verify(&valid).await.is_ok()); - for field in ["iss", "aud", "exp", "sub"] { - let mut claims = valid.clone(); - claims.as_object_mut().expect("object").remove(field); - assert!(verify(&claims).await.is_err(), "missing {field}"); - for value in [ - serde_json::Value::Null, - serde_json::json!(123), - serde_json::json!({}), - ] { - claims[field] = value; - // Numeric expiry is valid only while it lies in the future; 123 is expired. - assert!(verify(&claims).await.is_err(), "invalid {field}"); - } - } - for audience in [ - serde_json::json!([]), - serde_json::json!(["client", "untrusted"]), - serde_json::json!(["client", 123]), - serde_json::json!("other"), - ] { - let mut claims = valid.clone(); - claims["aud"] = audience; - assert!(verify(&claims).await.is_err()); - } - let mut claims = valid.clone(); - claims["aud"] = serde_json::json!(["client"]); - assert!(verify(&claims).await.is_ok()); - claims["iss"] = serde_json::json!("https://untrusted.example"); - assert!(verify(&claims).await.is_err()); - claims = valid; - claims["azp"] = serde_json::json!("other"); - assert!(verify(&claims).await.is_err()); -} - -/// Resolved credentials fail at startup with variable context and the original source. -#[test] -fn provider_secrets_fail_early_with_context() { - let path = std::env::temp_dir().join(format!("piquel-provider-secret-{}", TokenId::new())); - let config = || ProviderConfig::test(&path); - let error = config() - .resolve(Provider::GitHub) - .err() - .expect("missing file rejected"); - assert!( - error - .to_string() - .starts_with(ProviderConfig::variables(Provider::GitHub).1.name()) - ); - assert!(std::error::Error::source(&error).is_some()); - for contents in [b"".as_slice(), &[0xff]] { - std::fs::write(&path, contents).expect("secret file"); - assert!(config().resolve(Provider::Google).is_err()); - } - std::fs::write(&path, "secret").expect("secret file"); - let resolved = config().resolve(Provider::Google).expect("valid secret"); - std::fs::remove_file(path).expect("remove secret"); - assert_eq!(resolved.client_secret.expose_secret(), b"secret"); -} - -/// Cancelled or failed authorization preserves the original continuation and consumes state. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn failed_provider_preserves_stored_continuation_and_consumes_state() { - let mut test = TestApp::new().await; - test.app - .endpoints - .get_mut(&Provider::GitHub) - .expect("GitHub facts") - .token - .push_str("/missing"); - let router = test.routes(); - let destination = "/oauth/authorize/resume?transaction=trusted-transaction"; - for (callback_query, error) in [ - ("error=access_denied", "social_cancelled"), - ("code=invalid", "social_failed"), - ("code=", "social_failed"), - ("", "social_failed"), - ] { - let (state, cookie) = test.start(destination).await; - let path = format!( - "/login/github/callback?{callback_query}&state={state}&return_to=https://evil.example" - ); - let response = router - .clone() - .oneshot(TestApp::request( - Method::GET, - &path, - Some(&cookie), - &serde_json::Value::Null, - )) - .await - .expect("cancel"); - assert_eq!(response.status(), StatusCode::SEE_OTHER); - let target = Url::parse( - response.headers()[header::LOCATION] - .to_str() - .expect("location"), - ) - .expect("target"); - assert_eq!(target.origin(), test.app.origin.as_url().origin()); - assert!( - target - .query_pairs() - .any(|(key, value)| key == "return_to" && value == destination) - ); - assert!( - target - .query_pairs() - .any(|(key, value)| key == "error" && value == error) - ); - let response = router - .clone() - .oneshot(TestApp::request( - Method::GET, - &path, - Some(&cookie), - &serde_json::Value::Null, - )) - .await - .expect("replay"); - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - } -} - -/// Social sign-in re-authenticates the browser's own unconfirmed session in place, -/// refuses to re-authenticate one a passkey confirmed, and replaces another -/// account's session. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn social_sign_in_reauthenticates_only_unconfirmed_sessions() { - let test = TestApp::new().await; - let owner = test.user(None, true).await; - test.link(owner).await; - let session_cookie = |response: &Response| { - response - .headers() - .get_all(header::SET_COOKIE) - .iter() - .map(|value| value.to_str().expect("cookie")) - .find(|cookie| cookie.starts_with(BrowserCookie::Session.as_str())) - .expect("session cookie") - .split(';') - .next() - .expect("cookie pair") - .to_owned() - }; - - let (social, cookie) = test.session(owner, false).await; - let before = test.active(&cookie).await.expect("social session"); - let response = test.callback_from(Some(&cookie)).await; - assert_eq!(response.status(), StatusCode::SEE_OTHER); - let renewed = test - .active(&session_cookie(&response)) - .await - .expect("renewed session"); - assert_eq!(renewed.id, social, "the session ID is kept"); - assert!(renewed.authenticated_at > before.authenticated_at); - assert!(test.active(&cookie).await.is_none(), "old cookie ends"); - - let (confirmed, cookie) = test.session(owner, true).await; - let response = test.callback_from(Some(&cookie)).await; - assert_eq!(response.status(), StatusCode::SEE_OTHER); - assert!( - response.headers()[header::LOCATION] - .to_str() - .expect("location") - .contains("error=passkey_required") - ); - assert_eq!( - test.active(&cookie).await.expect("untouched session").id, - confirmed - ); - - let other = test.user(None, true).await; - let (replaced, cookie) = test.session(other, false).await; - let response = test.callback_from(Some(&cookie)).await; - let session = test - .active(&session_cookie(&response)) - .await - .expect("new session"); - assert_eq!(session.user_id, owner); - assert_ne!(session.id, replaced); - assert!( - test.app - .database - .sessions() - .find_by_id(replaced) - .await - .expect("lookup") - .expect("session") - .revoked_at - .is_some(), - "the other account's session is revoked" - ); -} diff --git a/apps/auth-service/src/federation/tests/callback.rs b/apps/auth-service/src/federation/tests/callback.rs new file mode 100644 index 000000000..1a240b308 --- /dev/null +++ b/apps/auth-service/src/federation/tests/callback.rs @@ -0,0 +1,159 @@ +//! The provider callback: strict return destinations and browser bindings, pending +//! evidence for unregistered subjects, and failed or cancelled authorizations. + +use super::*; + +/// Accepts auth paths only, and rejects duplicated pending-browser cookies. +#[test] +fn return_destinations_and_browser_bindings_are_strict() { + for value in [ + "//evil.test", + "/\\evil.test", + "https://evil.test", + "https://auth.piquel.fr/settings", + "/login#x", + "/\n/evil", + "settings", + "javascript:alert(1)", + "https:\\\\evil.test", + ] { + assert!(ReturnTo::parse(Some(value)).is_err(), "{value}"); + } + let path = "/oauth/authorize?request=abc"; + assert_eq!(ReturnTo::parse(Some(path)).expect(path).0, path); + assert_eq!( + ReturnTo::parse(None).expect("default return").0, + DEFAULT_RETURN_TO + ); + assert!(ReturnTo::parse(Some(&format!("/{}", "x".repeat(MAX_RETURN_TO_BYTES)))).is_err()); + let secret = Secret::generate().expect("browser secret"); + let mut headers = HeaderMap::new(); + headers.insert( + header::COOKIE, + HeaderValue::from_str(&format!( + "{0}={1}; {0}={1}", + BrowserCookie::FederationPending.as_str(), + secret.encoded() + )) + .expect("cookie"), + ); + assert!(BrowserCookie::FederationPending.read(&headers).is_none()); +} + +/// Callbacks require browser state and retain unregistered subjects as pending evidence. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn provider_mock_callback_requires_browser_state_and_stays_pending() { + let test = TestApp::new().await; + let router = test.routes(); + let (state, cookie) = test.start(DEFAULT_RETURN_TO).await; + let path = format!("/login/github/callback?code=mock-code&state={state}"); + let response = router + .clone() + .oneshot(TestApp::request( + Method::GET, + &path, + None, + &serde_json::Value::Null, + )) + .await + .expect("unbound callback"); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + let response = router + .clone() + .oneshot(TestApp::request( + Method::GET, + &path, + Some(&cookie), + &serde_json::Value::Null, + )) + .await + .expect("callback"); + assert_eq!(response.status(), StatusCode::SEE_OTHER); + assert_eq!(response.headers()[header::LOCATION], "/login?social=signup"); + assert!( + !response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .any(|value| value + .to_str() + .expect("cookie") + .starts_with("__Host-piquel_session=")) + ); + let response = router + .oneshot(TestApp::request( + Method::GET, + &path, + Some(&cookie), + &serde_json::Value::Null, + )) + .await + .expect("replay"); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); +} + +/// Cancelled or failed authorization preserves the original continuation and consumes state. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn failed_provider_preserves_stored_continuation_and_consumes_state() { + let mut test = TestApp::new().await; + test.app + .endpoints + .get_mut(&Provider::GitHub) + .expect("GitHub facts") + .token + .push_str("/missing"); + let router = test.routes(); + let destination = "/oauth/authorize/resume?transaction=trusted-transaction"; + for (callback_query, error) in [ + ("error=access_denied", "social_cancelled"), + ("code=invalid", "social_failed"), + ("code=", "social_failed"), + ("", "social_failed"), + ] { + let (state, cookie) = test.start(destination).await; + let path = format!( + "/login/github/callback?{callback_query}&state={state}&return_to=https://evil.example" + ); + let response = router + .clone() + .oneshot(TestApp::request( + Method::GET, + &path, + Some(&cookie), + &serde_json::Value::Null, + )) + .await + .expect("cancel"); + assert_eq!(response.status(), StatusCode::SEE_OTHER); + let target = Url::parse( + response.headers()[header::LOCATION] + .to_str() + .expect("location"), + ) + .expect("target"); + assert_eq!(target.origin(), test.app.origin.as_url().origin()); + assert!( + target + .query_pairs() + .any(|(key, value)| key == "return_to" && value == destination) + ); + assert!( + target + .query_pairs() + .any(|(key, value)| key == "error" && value == error) + ); + let response = router + .clone() + .oneshot(TestApp::request( + Method::GET, + &path, + Some(&cookie), + &serde_json::Value::Null, + )) + .await + .expect("replay"); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + } +} diff --git a/apps/auth-service/src/federation/tests/linking.rs b/apps/auth-service/src/federation/tests/linking.rs new file mode 100644 index 000000000..c42725779 --- /dev/null +++ b/apps/auth-service/src/federation/tests/linking.rs @@ -0,0 +1,141 @@ +//! Linking pending provider evidence to a confirmed account, and unlinking it. + +use super::*; +use crate::account::{AccountError, AccountService}; + +impl TestApp { + /// Links this browser's pending evidence, its `pending` headers, to the account + /// of the session `cookie` names, as the sign-in page does. + async fn link_pending( + &self, + cookie: &str, + pending: &HeaderMap, + ) -> Result { + let account = AccountService::new(self.app.database.clone()); + let owner = account + .owner(security::RequestContext::TEST, &Self::cookies(cookie)) + .await + .expect("session lookup") + .expect("signed in"); + account + .link_identity(&owner, pending) + .await + .map(|(return_to, _)| return_to) + } +} + +/// Linking and unlinking require the intended account’s recent passkey confirmation; +/// unlink frees the subject and preserves email. +#[expect( + clippy::too_many_lines, + reason = "Keep one pending link from rejection through linking and unlinking together." +)] +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn linking_requires_target_confirmation_and_unlink_releases_subject_without_changing_email() { + let test = TestApp::new().await; + let email = format!("{}@example.com", TokenId::new()); + let target = test.user(Some(&email), true).await; + let other = test.user(None, true).await; + let observed = format!("{}@example.com", TokenId::new()); + let (pending, pending_headers) = test.pending(Some(target), Some(&observed)).await; + let (_, other_cookie) = test.session(other, true).await; + let (target_session, target_cookie) = test.session(target, false).await; + let (other_session, _) = test.session(target, false).await; + let refused = test.link_pending(&other_cookie, &pending_headers).await; + assert!( + matches!( + refused, + Err(AccountError::Identity(FederationError::LinkAccountMismatch)) + ), + "another account's confirmation cannot link: {refused:?}" + ); + // Confirmation comes first, before the browser's pending cookie is read. + for pending in [&pending_headers, &HeaderMap::new()] { + let refused = test.link_pending(&target_cookie, pending).await; + assert!( + matches!( + refused, + Err(AccountError::Owner(SessionError::StepUpRequired { .. })) + ), + "an unconfirmed session cannot link: {refused:?}" + ); + } + let router = test.routes(); + let response = router + .clone() + .oneshot(TestApp::request( + Method::DELETE, + "/account/social-identities/github", + Some(&target_cookie), + &serde_json::json!({}), + )) + .await + .expect("unconfirmed rejection"); + security::tests::assert_step_up_required(response).await; + test.app + .database + .sessions() + .confirm_passkey(target_session, PasskeyId::new(), chrono::Utc::now()) + .await + .expect("confirm"); + let return_to = test + .link_pending(&target_cookie, &pending_headers) + .await + .expect("link"); + assert_eq!(return_to, pending.return_to); + assert!( + test.app + .database + .sessions() + .find_active_by_id(other_session) + .await + .expect("other session") + .is_some() + ); + assert_eq!( + test.app + .database + .emails() + .find_active_verified(&email) + .await + .expect("email") + .expect("owner") + .user_id, + target + ); + assert!( + test.app + .database + .emails() + .find_active_verified(&observed) + .await + .expect("observation") + .is_none() + ); + let response = router + .oneshot(TestApp::request( + Method::DELETE, + "/account/social-identities/github", + Some(&target_cookie), + &serde_json::json!({}), + )) + .await + .expect("unlink"); + assert_eq!(response.status(), StatusCode::NO_CONTENT); + assert!( + test.app + .database + .sessions() + .find_active_by_id(other_session) + .await + .expect("revoked other session") + .is_none() + ); + test.app + .database + .federation() + .insert_identity(&FederationApplication::identity(&pending, other)) + .await + .expect("unlinked subject reusable"); +} diff --git a/apps/auth-service/src/federation/tests/mod.rs b/apps/auth-service/src/federation/tests/mod.rs new file mode 100644 index 000000000..5877c7f4e --- /dev/null +++ b/apps/auth-service/src/federation/tests/mod.rs @@ -0,0 +1,303 @@ +//! Federation protocol, browser-binding and transactional identity policy tests. + +mod callback; +mod linking; +mod protocols; +mod sign_in; +mod signup; + +use super::{ + providers::{IdentityStrategy, ProviderEndpoints}, + *, +}; +use crate::{ + account::AccountApplication, + tests::{pending_sign_in, unusable_passkey}, +}; +use axum::{ + Json, + body::Body, + http::{HeaderValue, Method, Request, StatusCode, header}, + routing::post, +}; +use piquel_common::{Handle, PasskeyId}; +use piquel_crypto::Secret; +use piquel_repository::{DatabaseConfig, DatabaseTransaction, InsertUser, InsertVerifiedEmail}; +use tower::ServiceExt; + +/// Isolated database fixture with replaceable provider endpoints and unique subjects. +struct TestApp { + /// Federation state whose back-channel requests use a local HTTP fixture. + app: FederationApplication, + /// Provider mock server, stopped when the fixture is dropped. + task: tokio::task::JoinHandle<()>, + /// Temporary provider secret deleted with the fixture. + secret_file: std::path::PathBuf, + /// Unique numeric subject returned by this fixture’s provider. + subject: String, +} +impl Drop for TestApp { + /// Stops the fixture server and attempts to remove its temporary secret. + fn drop(&mut self) { + self.task.abort(); + if let Err(error) = std::fs::remove_file(&self.secret_file) { + tracing::warn!(%error, "could not remove federation fixture secret"); + } + } +} +impl TestApp { + /// The federation routes and the shared settings, as the public listener + /// serves them. + fn routes(&self) -> axum::Router { + self.app + .clone() + .routes() + .merge(AccountApplication::new(self.app.database.clone()).routes()) + } + /// Creates a provider fixture with no verified contact address. + async fn new() -> Self { + Self::with_email(None).await + } + /// Creates unique provider evidence with an optional verified primary address. + async fn with_email(email: Option<&str>) -> Self { + let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") + .required() + .expect("TEST_DATABASE_URL must name an isolated migrated PostgreSQL database"); + let database = Database::connect( + DatabaseConfig::new(&url, 5, StdDuration::from_secs(5)) + .expect("database configuration"), + ) + .await + .expect("database"); + database.run_migrations().await.expect("migrations"); + let subject = u64::from_be_bytes( + piquel_crypto::Secret::generate() + .expect("random") + .as_bytes()[..8] + .try_into() + .expect("eight bytes"), + ) + .max(1); + let emails = email.map_or_else( + || serde_json::json!([]), + |email| serde_json::json!([{"email":email,"primary":true,"verified":true}]), + ); + let mock = Router::new() + .route( + "/token", + post(|| async { Json(serde_json::json!({"access_token":"mock-token"})) }), + ) + .route( + "/user", + get(move || async move { + Json(serde_json::json!({"id":subject,"name":"Social User","login":"social"})) + }), + ) + .route( + "/emails", + get(move || { + let emails = emails.clone(); + async move { Json(emails) } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("mock listener"); + let base = format!("http://{}", listener.local_addr().expect("mock address")); + let task = tokio::spawn(async move { + axum::serve(listener, mock).await.expect("mock server"); + }); + let secret_file = + std::env::temp_dir().join(format!("piquel-federation-test-{}", TokenId::new())); + std::fs::write(&secret_file, "test-secret").expect("mock provider secret"); + let config = ProviderConfig::test(&secret_file); + let mut app = FederationApplication::new( + database, + &FederationConfig { + origin: "https://auth.piquel.fr/" + .parse::() + .expect("origin"), + providers: BTreeMap::from([(Provider::GitHub, config)]), + }, + ) + .expect("federation"); + let endpoints = app + .endpoints + .get_mut(&Provider::GitHub) + .expect("GitHub facts"); + endpoints.token = format!("{base}/token"); + match &mut endpoints.identity { + IdentityStrategy::GitHub(protocol) => { + protocol.user = format!("{base}/user"); + protocol.emails = format!("{base}/emails"); + } + IdentityStrategy::Google(_) => panic!("GitHub must use OAuth profile fetching"), + } + Self { + app, + task, + secret_file, + subject: subject.to_string(), + } + } + /// Runs a complete GitHub authorization start and bound callback. + async fn callback(&self) -> Response { + self.callback_from(None).await + } + /// Starts a GitHub sign-in returning to `return_to`, as the sign-in page does, + /// and returns the provider's `state` and the browser's flow cookie pair. + async fn start(&self, return_to: &str) -> (String, String) { + let (url, FlowCookie(Flow::Started(browser))) = self + .app + .start_sign_in(Provider::GitHub, return_to) + .await + .expect("start") + else { + unreachable!("starting a sign-in sets the flow's cookie") + }; + let state = url + .query_pairs() + .find(|(name, _)| name == "state") + .expect("state") + .1 + .into_owned(); + let cookie = format!( + "{}={}", + BrowserCookie::Federation.as_str(), + browser.encoded() + ); + (state, cookie) + } + /// Runs [`Self::callback`] in a browser that may hold a `session` cookie pair. + async fn callback_from(&self, session: Option<&str>) -> Response { + let (state, mut cookie) = self.start(DEFAULT_RETURN_TO).await; + if let Some(session) = session { + cookie = format!("{cookie}; {session}"); + } + self.routes() + .oneshot(TestApp::request( + Method::GET, + &format!("/login/github/callback?state={state}&code=mock-code"), + Some(&cookie), + &serde_json::Value::Null, + )) + .await + .expect("callback") + } + /// Creates a unique account with optional verified email and passkey. + async fn user(&self, email: Option<&str>, with_key: bool) -> UserId { + let id = UserId::new(); + let mut tx = self.app.database.begin().await.expect("transaction"); + tx.users() + .insert(&InsertUser { + id, + handle: Handle::parse(&format!("fed-{}", &TokenId::new().to_string()[24..])) + .expect("handle"), + display_name: "Federation Test".into(), + }) + .await + .expect("user"); + if let Some(email) = email { + tx.emails() + .insert_verified(&InsertVerifiedEmail { + id: piquel_common::EmailId::new(), + user_id: id, + normalized_email: email.into(), + is_primary: true, + verified_at: Utc::now(), + }) + .await + .expect("email"); + } + if with_key { + self.key(&mut tx, id).await; + } + tx.commit().await.expect("commit"); + id + } + /// Adds passkey-presence evidence; ceremony cryptography is covered by passkey tests. + async fn key(&self, tx: &mut DatabaseTransaction<'_>, user_id: UserId) { + // Federation only checks key presence; cryptographic ceremony coverage lives in passkey tests. + tx.passkeys() + .insert(&unusable_passkey(user_id)) + .await + .expect("key"); + } + /// Stores browser-bound evidence optionally targeting an existing account. + async fn pending( + &self, + owner: Option, + email: Option<&str>, + ) -> (PendingFederation, HeaderMap) { + let secret = Secret::generate().expect("browser secret"); + let pending = PendingFederation { + email: email.map(str::to_owned), + link_user_id: owner, + ..pending_sign_in(&secret) + }; + self.app + .database + .federation() + .insert_pending(&pending) + .await + .expect("pending identity"); + let cookie = format!( + "{}={}", + BrowserCookie::FederationPending.as_str(), + secret.encoded() + ); + (pending, Self::cookies(&cookie)) + } + /// Creates a social browser session, optionally confirmed with a passkey now. + async fn session(&self, user_id: UserId, confirmed: bool) -> (SessionId, String) { + let mut tx = self.app.database.begin().await.expect("transaction"); + let cookie = security::Session::create( + &mut tx, + security::RequestContext::TEST, + user_id, + AuthenticationMethod::Federation.into(), + ) + .await + .expect("session"); + let raw = format!("{}={}", BrowserCookie::Session.as_str(), cookie.encoded()); + tx.commit().await.expect("commit"); + let session = security::Session::required(&self.app.database, &Self::cookies(&raw)) + .await + .expect("active session"); + if confirmed { + self.app + .database + .sessions() + .confirm_passkey(session.id, PasskeyId::new(), chrono::Utc::now()) + .await + .expect("confirm"); + } + (session.id, raw) + } + /// The headers of a browser sending the `cookie` pairs. + fn cookies(cookie: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + header::COOKIE, + HeaderValue::from_str(cookie).expect("cookie"), + ); + headers + } + /// Builds a JSON HTTP request with an optional browser-cookie header. + fn request( + method: Method, + path: &str, + cookie: Option<&str>, + body: &serde_json::Value, + ) -> Request { + let mut request = Request::builder() + .extension(crate::security::RequestContext::TEST) + .method(method) + .uri(path) + .header(header::CONTENT_TYPE, "application/json"); + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, cookie); + } + request.body(Body::from(body.to_string())).expect("request") + } +} diff --git a/apps/auth-service/src/federation/tests/protocols.rs b/apps/auth-service/src/federation/tests/protocols.rs new file mode 100644 index 000000000..292f721d5 --- /dev/null +++ b/apps/auth-service/src/federation/tests/protocols.rs @@ -0,0 +1,279 @@ +//! Provider protocols: credential resolution and Google ID-token verification. + +use super::*; +use crate::federation::providers::{GoogleClaims, GoogleProtocol}; +use piquel_auth::{KeyCache, KeySet}; +use piquel_common::protocol::jwt::{Algorithm, TokenType}; +use piquel_crypto::Rs256Key; +use std::collections::HashMap; +use tracing::Instrument; + +impl TestApp { + /// Borrows Google's replaceable verification facts from the fixture. + fn google_protocol(&self) -> &GoogleProtocol { + match &self.app.endpoints[&Provider::Google].identity { + IdentityStrategy::Google(protocol) => protocol, + IdentityStrategy::GitHub(_) => panic!("Google must use signed ID tokens"), + } + } +} + +/// Google evidence requires trusted signatures and claims but does not require email. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn google_mock_validates_signature_audience_nonce_and_expiry_without_requiring_email() { + let mut test = TestApp::new().await; + let rsa = Rs256Key::generate("google-test").expect("RSA test key"); + let sign = |key: &Rs256Key, claims: &serde_json::Value| { + key.sign(TokenType::Id, claims).expect("signed token") + }; + let mut claims = serde_json::json!({"iss":"https://accounts.google.com","sub":"12345","aud":"test-client","iat":Utc::now().timestamp(),"exp":Utc::now().timestamp()+300,"nonce":"test-nonce"}); + let valid = sign(&rsa, &claims); + claims["aud"] = serde_json::json!("another-client"); + let wrong_audience = sign(&rsa, &claims); + claims["aud"] = serde_json::json!("test-client"); + claims["exp"] = serde_json::json!(Utc::now().timestamp() - 120); + let expired = sign(&rsa, &claims); + let other_rsa = Rs256Key::generate("google-test").expect("untrusted key"); + claims["exp"] = serde_json::json!(Utc::now().timestamp() + 300); + let wrong_signature = sign(&other_rsa, &claims); + let keys = rsa.jwks().clone(); + let tokens = Arc::new(HashMap::from([ + ("valid".to_owned(), valid), + ("wrong-audience".to_owned(), wrong_audience), + ("expired".to_owned(), expired), + ("wrong-signature".to_owned(), wrong_signature), + ])); + let mock = Router::new() + .route( + "/keys", + get(move || { + let keys = keys.clone(); + async move { Json(keys) } + }), + ) + .route( + "/token/{kind}", + get(move |Path(kind): Path| { + let tokens = tokens.clone(); + async move { Json(serde_json::json!({"id_token":tokens[&kind]})) } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("mock listener"); + let base = format!("http://{}", listener.local_addr().expect("address")); + let task = tokio::spawn(async move { + axum::serve(listener, mock).await.expect("mock server"); + }); + match &mut test + .app + .endpoints + .get_mut(&Provider::Google) + .expect("Google facts") + .identity + { + IdentityStrategy::Google(protocol) => { + protocol.keys = KeyCache::new( + format!("{base}/keys").parse().expect("mock key URL"), + reqwest::Client::new(), + ); + } + IdentityStrategy::GitHub(_) => panic!("Google must use signed ID tokens"), + } + let response = test + .app + .client + .get(format!("{base}/token/valid")) + .send() + .await + .expect("valid response"); + let identity = test + .app + .google_identity( + response, + "test-client", + "test-nonce", + test.google_protocol(), + ) + .await + .expect("valid Google identity without email"); + assert_eq!(identity.subject, "12345"); + assert!(identity.email.is_none()); + for (kind, nonce, expected) in [ + ("valid", "wrong-nonce", "nonce does not match"), + ("wrong-audience", "test-nonce", "not for this client"), + ("expired", "test-nonce", "has expired"), + ("wrong-signature", "test-nonce", "failed verification"), + ] { + let response = test + .app + .client + .get(format!("{base}/token/{kind}")) + .send() + .await + .expect("mock response"); + let error = test + .app + .google_identity(response, "test-client", nonce, test.google_protocol()) + .await + .err() + .expect("rejected"); + assert!(error.to_string().contains(expected), "{kind}: {error}"); + } + task.abort(); +} + +/// Fetching Google's signing keys is a client span of the request that needed them, +/// with its method, host and status only. +#[tokio::test] +async fn google_key_fetch_is_a_client_span_of_its_request() { + let capture = piquel_telemetry::Telemetry::capture(crate::TELEMETRY_FILTER); + let rsa = Rs256Key::generate("google-test").expect("RSA test key"); + let token = rsa + .sign(TokenType::Id, &serde_json::json!({})) + .expect("signed token"); + let keys = rsa.jwks().clone(); + let mock = Router::new().route("/keys", get(move || async move { Json(keys) })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("mock listener"); + let url = format!( + "http://{}/keys?client=secret", + listener.local_addr().expect("address") + ); + let task = tokio::spawn(async move { + axum::serve(listener, mock).await.expect("mock server"); + }); + let cache = KeyCache::new(url.parse().expect("mock key URL"), reqwest::Client::new()); + let jws = piquel_auth::Jws::parse(&token).expect("JWS"); + let request = tracing::info_span!("request"); + cache + .verify(&jws, Algorithm::Rs256) + .instrument(request) + .await + .expect("verified"); + task.abort(); + + let spans = capture.spans(); + let request = spans + .iter() + .find(|span| span.name == "request") + .expect("request span"); + let fetch = spans + .iter() + .find(|span| span.name == "GET") + .expect("key fetch span"); + assert_eq!(fetch.parent_span_id, request.span_context.span_id()); + assert_eq!(format!("{:?}", fetch.span_kind), "Client"); + let attributes: Vec<_> = fetch + .attributes + .iter() + .map(|attribute| format!("{}={}", attribute.key, attribute.value)) + .collect(); + for expected in [ + "http.request.method=GET", + "http.response.status_code=200", + "server.address=127.0.0.1", + ] { + assert!( + attributes.iter().any(|a| a == expected), + "{expected}: {attributes:?}" + ); + } + assert!( + !attributes + .iter() + .any(|attribute| attribute.contains("/keys") || attribute.contains("secret")), + "no path or query: {attributes:?}" + ); + let status = fetch + .attributes + .iter() + .find(|attribute| attribute.key.as_str() == "http.response.status_code") + .expect("status"); + assert_eq!( + format!("{:?}", status.value), + "I64(200)", + "an integer status" + ); +} + +/// ID-token verification rejects malformed claims, untrusted issuers and additional audiences. +#[tokio::test] +async fn google_signed_tokens_require_well_typed_trusted_issuer_and_audience() { + let rsa = Rs256Key::generate("google-test").expect("RSA key"); + let IdentityStrategy::Google(mut protocol) = + ProviderEndpoints::new(Provider::Google, &reqwest::Client::new()) + .expect("Google facts") + .identity + else { + panic!("Google must use signed ID tokens"); + }; + protocol.keys = KeyCache::fixed( + KeySet::parse(&serde_json::to_vec(&rsa.jwks()).expect("JWKS")).expect("key set"), + ); + let valid = serde_json::json!({"iss":"https://accounts.google.com","aud":"client","sub":"subject","iat":Utc::now().timestamp(),"exp":Utc::now().timestamp()+300,"nonce":"nonce"}); + let verify = async |claims: &serde_json::Value| { + let token = rsa.sign(TokenType::Id, claims).expect("signed token"); + GoogleClaims::verify(&token, &protocol, "client", "nonce").await + }; + assert!(verify(&valid).await.is_ok()); + for field in ["iss", "aud", "exp", "sub"] { + let mut claims = valid.clone(); + claims.as_object_mut().expect("object").remove(field); + assert!(verify(&claims).await.is_err(), "missing {field}"); + for value in [ + serde_json::Value::Null, + serde_json::json!(123), + serde_json::json!({}), + ] { + claims[field] = value; + // Numeric expiry is valid only while it lies in the future; 123 is expired. + assert!(verify(&claims).await.is_err(), "invalid {field}"); + } + } + for audience in [ + serde_json::json!([]), + serde_json::json!(["client", "untrusted"]), + serde_json::json!(["client", 123]), + serde_json::json!("other"), + ] { + let mut claims = valid.clone(); + claims["aud"] = audience; + assert!(verify(&claims).await.is_err()); + } + let mut claims = valid.clone(); + claims["aud"] = serde_json::json!(["client"]); + assert!(verify(&claims).await.is_ok()); + claims["iss"] = serde_json::json!("https://untrusted.example"); + assert!(verify(&claims).await.is_err()); + claims = valid; + claims["azp"] = serde_json::json!("other"); + assert!(verify(&claims).await.is_err()); +} + +/// Resolved credentials fail at startup with variable context and the original source. +#[test] +fn provider_secrets_fail_early_with_context() { + let path = std::env::temp_dir().join(format!("piquel-provider-secret-{}", TokenId::new())); + let config = || ProviderConfig::test(&path); + let error = config() + .resolve(Provider::GitHub) + .err() + .expect("missing file rejected"); + assert!( + error + .to_string() + .starts_with(ProviderConfig::variables(Provider::GitHub).1.name()) + ); + assert!(std::error::Error::source(&error).is_some()); + for contents in [b"".as_slice(), &[0xff]] { + std::fs::write(&path, contents).expect("secret file"); + assert!(config().resolve(Provider::Google).is_err()); + } + std::fs::write(&path, "secret").expect("secret file"); + let resolved = config().resolve(Provider::Google).expect("valid secret"); + std::fs::remove_file(path).expect("remove secret"); + assert_eq!(resolved.client_secret.expose_secret(), b"secret"); +} diff --git a/apps/auth-service/src/federation/tests/sign_in.rs b/apps/auth-service/src/federation/tests/sign_in.rs new file mode 100644 index 000000000..6310b63a4 --- /dev/null +++ b/apps/auth-service/src/federation/tests/sign_in.rs @@ -0,0 +1,224 @@ +//! Social sign-in: subject precedence over email, the passkey requirement, and +//! re-authenticating the browser's existing session. + +use super::*; +use piquel_repository::InsertExternalIdentity; + +impl TestApp { + /// Links this fixture's provider subject to `user_id`. + async fn link(&self, user_id: UserId) { + self.app + .database + .federation() + .insert_identity(&InsertExternalIdentity { + id: TokenId::new(), + user_id, + provider: piquel_common::Provider::GitHub, + issuer: ProviderEndpoints::new(Provider::GitHub, &reqwest::Client::new()) + .expect("GitHub facts") + .issuer + .into(), + subject: self.subject.clone(), + linked_email: None, + }) + .await + .expect("known identity"); + } + /// Finds the active session a cookie pair names. + async fn active(&self, cookie: &str) -> Option { + security::Session::optional(&self.app.database, &Self::cookies(cookie)) + .await + .expect("session lookup") + } +} + +/// Stable provider subjects take priority over email observations and require an existing passkey. +#[expect( + clippy::too_many_lines, + reason = "Keep the callback precedence scenario and the session it yields together." +)] +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn callback_email_collision_never_links_and_known_subject_never_bootstraps_a_missing_key() { + let observed = format!("{}@example.com", TokenId::new()); + let original = format!("{}@example.com", TokenId::new()); + let test = TestApp::with_email(Some(&observed)).await; + let email_owner = test.user(Some(&observed), true).await; + let response = test.callback().await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + assert_eq!(response.headers()[header::LOCATION], "/login?social=link"); + assert!( + test.app + .database + .federation() + .find_active( + ProviderEndpoints::new(Provider::GitHub, &reqwest::Client::new()) + .expect("GitHub facts") + .issuer, + &test.subject + ) + .await + .expect("identity") + .is_none() + ); + let subject_owner = test.user(Some(&original), false).await; + test.app + .database + .federation() + .insert_identity(&InsertExternalIdentity { + id: TokenId::new(), + user_id: subject_owner, + provider: piquel_common::Provider::GitHub, + issuer: ProviderEndpoints::new(Provider::GitHub, &reqwest::Client::new()) + .expect("GitHub facts") + .issuer + .into(), + subject: test.subject.clone(), + linked_email: Some(original.clone()), + }) + .await + .expect("known identity"); + let response = test.callback().await; + assert_eq!( + response.status(), + StatusCode::UNAUTHORIZED, + "known accounts cannot bootstrap from social login" + ); + let mut tx = test.app.database.begin().await.expect("tx"); + test.key(&mut tx, subject_owner).await; + tx.commit().await.expect("commit"); + let response = test.callback().await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + assert_eq!(response.headers()[header::LOCATION], DEFAULT_RETURN_TO); + let session_cookie = response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .map(|value| value.to_str().expect("cookie")) + .find(|cookie| cookie.starts_with("__Host-piquel_session=")) + .expect("session cookie") + .split(';') + .next() + .expect("cookie pair"); + let mut headers = HeaderMap::new(); + headers.insert( + header::COOKIE, + HeaderValue::from_str(session_cookie).expect("cookie"), + ); + let session = security::Session::required(&test.app.database, &headers) + .await + .expect("social session"); + assert_eq!( + session.user_id, subject_owner, + "stable subject takes priority over email observation" + ); + assert!( + session.passkey_confirmed_at.is_none(), + "social sign-in never confirms a passkey" + ); + let response = test + .routes() + .oneshot(TestApp::request( + Method::DELETE, + "/account/social-identities/github", + Some(session_cookie), + &serde_json::json!({}), + )) + .await + .expect("unlink"); + security::tests::assert_step_up_required(response).await; + assert_eq!( + test.app + .database + .emails() + .find_active_verified(&original) + .await + .expect("original email") + .expect("owner") + .user_id, + subject_owner + ); + assert_eq!( + test.app + .database + .emails() + .find_active_verified(&observed) + .await + .expect("observed email") + .expect("owner") + .user_id, + email_owner + ); +} + +/// Social sign-in re-authenticates the browser's own unconfirmed session in place, +/// refuses to re-authenticate one a passkey confirmed, and replaces another +/// account's session. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn social_sign_in_reauthenticates_only_unconfirmed_sessions() { + let test = TestApp::new().await; + let owner = test.user(None, true).await; + test.link(owner).await; + let session_cookie = |response: &Response| { + response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .map(|value| value.to_str().expect("cookie")) + .find(|cookie| cookie.starts_with(BrowserCookie::Session.as_str())) + .expect("session cookie") + .split(';') + .next() + .expect("cookie pair") + .to_owned() + }; + + let (social, cookie) = test.session(owner, false).await; + let before = test.active(&cookie).await.expect("social session"); + let response = test.callback_from(Some(&cookie)).await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + let renewed = test + .active(&session_cookie(&response)) + .await + .expect("renewed session"); + assert_eq!(renewed.id, social, "the session ID is kept"); + assert!(renewed.authenticated_at > before.authenticated_at); + assert!(test.active(&cookie).await.is_none(), "old cookie ends"); + + let (confirmed, cookie) = test.session(owner, true).await; + let response = test.callback_from(Some(&cookie)).await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + assert!( + response.headers()[header::LOCATION] + .to_str() + .expect("location") + .contains("error=passkey_required") + ); + assert_eq!( + test.active(&cookie).await.expect("untouched session").id, + confirmed + ); + + let other = test.user(None, true).await; + let (replaced, cookie) = test.session(other, false).await; + let response = test.callback_from(Some(&cookie)).await; + let session = test + .active(&session_cookie(&response)) + .await + .expect("new session"); + assert_eq!(session.user_id, owner); + assert_ne!(session.id, replaced); + assert!( + test.app + .database + .sessions() + .find_by_id(replaced) + .await + .expect("lookup") + .expect("session") + .revoked_at + .is_some(), + "the other account's session is revoked" + ); +} diff --git a/apps/auth-service/src/federation/tests/signup.rs b/apps/auth-service/src/federation/tests/signup.rs new file mode 100644 index 000000000..ea8a1d033 --- /dev/null +++ b/apps/auth-service/src/federation/tests/signup.rs @@ -0,0 +1,84 @@ +//! Signup from pending provider evidence, committed only with a first passkey. + +use super::*; + +/// Signup must create its first passkey and cannot claim an existing account’s email. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn onboarding_commits_only_with_first_key_and_browser_and_never_claims_existing_email() { + let test = TestApp::new().await; + let (pending, headers) = test.pending(None, None).await; + assert!( + FederationApplication::pending_signup(&test.app.database, &headers, TokenId::new()) + .await + .is_err(), + "registration must name the displayed pending signup" + ); + FederationApplication::pending_signup(&test.app.database, &headers, pending.id) + .await + .expect("pending signup"); + let user = test.user(None, false).await; + let mut tx = test.app.database.begin().await.expect("tx"); + assert!( + FederationApplication::attach_signup( + &mut tx, + &security::RequestContext::TEST.actor(piquel_common::events::Actor::Anonymous), + pending.id, + &headers, + user + ) + .await + .is_err() + ); + tx.rollback().await.expect("rollback"); + let mut tx = test.app.database.begin().await.expect("tx"); + test.key(&mut tx, user).await; + assert!( + FederationApplication::attach_signup( + &mut tx, + &security::RequestContext::TEST.actor(piquel_common::events::Actor::Anonymous), + pending.id, + &HeaderMap::new(), + user + ) + .await + .is_err() + ); + FederationApplication::attach_signup( + &mut tx, + &security::RequestContext::TEST.actor(piquel_common::events::Actor::Anonymous), + pending.id, + &headers, + user, + ) + .await + .expect("first key authorizes signup"); + tx.commit().await.expect("commit"); + assert_eq!( + test.app + .database + .federation() + .find_active(&pending.issuer, &pending.subject) + .await + .expect("identity") + .expect("linked") + .user_id, + user + ); + let email = format!("{}@example.com", TokenId::new()); + test.user(Some(&email), true).await; + let (pending, headers) = test.pending(None, Some(&email)).await; + let mut tx = test.app.database.begin().await.expect("tx"); + assert!( + FederationApplication::attach_signup( + &mut tx, + &security::RequestContext::TEST.actor(piquel_common::events::Actor::Anonymous), + pending.id, + &headers, + user + ) + .await + .is_err() + ); + tx.rollback().await.expect("rollback"); +} diff --git a/apps/auth-service/src/oidc/tests.rs b/apps/auth-service/src/oidc/tests.rs deleted file mode 100644 index d0b0482fa..000000000 --- a/apps/auth-service/src/oidc/tests.rs +++ /dev/null @@ -1,2498 +0,0 @@ -//! Focused parsing checks and database-backed OAuth/OIDC scenarios. - -use super::*; -use crate::config::{PolicyLinks, TokenDigestKey}; -use crate::deliveries::{BackchannelLogoutSender, OutboundClient, Sender}; -use crate::recovery::ProbationPasskey; -use crate::security::{BrowserCookie, Credential, RequestContext, Session}; -use crate::tests::{AUTH_ORIGIN, Replicas, TlsListener, location, parameter, until_blocked}; -use crate::{ - AuthConfig, federation::FederationApplication, passkey::PasskeyApplication, web::WebApplication, -}; -use axum::{ - body::{Body, to_bytes}, - http::{Method, Request, StatusCode}, - response::Response, -}; -use chrono::Utc; -use piquel_common::{ - AuthenticationMethod, Handle, UserId, - clients::{AllowedScopes, ClientKind, ClientOwner, ClientRegistration, RedirectUri, ScopeName}, - events::{Actor, DomainEvent, GrantRevocation, RevocationReason}, - protocol::{ - claims::{Acr, BACKCHANNEL_LOGOUT_EVENT, IdTokenClaims}, - step_up::StepUpRequirement, - }, -}; -use piquel_common::{PasskeyId, RecoveryId}; -use piquel_crypto::{KeySet, Rs256Key}; -use piquel_repository::{ - BackchannelLogout, DatabaseConfig, InsertPasskey, InsertRecovery, InsertUser, - InsertVerifiedEmail, SessionScope, -}; -use serde_json::{Value, json}; -use std::{ - collections::HashMap, - sync::{Arc, Mutex}, -}; -use tower::ServiceExt; -use url::Url; - -/// Database-backed OIDC scenario with a provisioned client and authenticated browser. -#[derive(Clone)] -struct Flow { - /// Application under test, sharing the scenario database. - app: OidcApplication, - /// Where requests go: the OIDC routes and their pages, or a replica of the whole - /// service. - router: axum::Router, - /// The scenario's client, registered through [`ClientRegistry`](crate::ClientRegistry). - client: ClientRegistration, - /// The secret of a confidential scenario client. - secret: Option, - /// Authenticated browser cookie pair sent by the scenario. - cookie: String, - /// Scenario account whose claims and grants are checked. - user_id: UserId, - /// Optional encoded credentials for a confidential scenario client. - basic: Option, -} -impl Flow { - /// Creates a disposable account, client registration and persistent-key OIDC application. - async fn new(confidential: bool, trusted: bool) -> Self { - Self::at(AUTH_ORIGIN, confidential, trusted).await - } - - /// Like [`Self::new`], for an issuer at `origin`. - async fn at(origin: &str, confidential: bool, trusted: bool) -> Self { - let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") - .required() - .expect("TEST_DATABASE_URL must name a disposable PostgreSQL database"); - let db = Database::connect( - DatabaseConfig::new(&url, 5, std::time::Duration::from_secs(5)) - .expect("valid local test database configuration"), - ) - .await - .expect("connect to the disposable PostgreSQL database"); - db.run_migrations() - .await - .expect("apply test database migrations"); - let user_id = UserId::new(); - let mut tx = db.begin().await.expect("begin test account transaction"); - tx.users() - .insert(&InsertUser { - id: user_id, - handle: Handle::parse(&format!("oidc-{}", &user_id.to_string()[24..])) - .expect("handle"), - display_name: "OIDC Test".into(), - }) - .await - .expect("insert test account"); - tx.emails() - .insert_verified(&InsertVerifiedEmail { - id: piquel_common::EmailId::new(), - user_id, - normalized_email: format!("{user_id}@example.com"), - is_primary: true, - verified_at: Utc::now(), - }) - .await - .expect("insert verified test email"); - let cookie = Session::create( - &mut tx, - RequestContext::TEST, - user_id, - AuthenticationMethod::Passkey.into(), - ) - .await - .expect("create test browser session"); - let cookie = format!("{}={}", BrowserCookie::Session.as_str(), cookie.encoded()); - tx.commit().await.expect("commit test account transaction"); - let client = ClientRegistration { - kind: if confidential { - ClientKind::Confidential - } else { - ClientKind::Public - }, - trusted, - ..crate::tests::registration(ClientKind::Public, "https://client.example") - }; - let secret = crate::tests::register(&db, &client) - .await - .expect("register test OIDC client") - .map(|secret| secret.expose().to_owned()); - let basic = secret.as_ref().map(|secret| { - format!( - "{} {}", - AuthScheme::Basic.as_str(), - base64::engine::general_purpose::STANDARD.encode(format!("{}:{secret}", client.id)) - ) - }); - let origin = origin - .parse::() - .expect("issuer"); - let config = AuthConfig::test(&origin); - let federation = - FederationApplication::new(db.clone(), &config.federation).expect("federation"); - let app = OidcApplication::new( - db.clone(), - &OidcConfig { - origin: origin.clone(), - digest_keys: Arc::new(TokenDigestKeys::new( - TokenDigestKey::derive(&[7; 32]).expect("digest key"), - None, - )), - policies: config.oidc.policies.clone(), - }, - SigningKeys::new(KeySet::single( - Rs256Key::generate("oidc-tests").expect("RSA signing key"), - )), - ) - .expect("OIDC application"); - let passkeys = - PasskeyApplication::new(db.clone(), &config.passkey, app.clone()).expect("passkeys"); - Self { - router: WebApplication::new(db, &config, app.clone(), federation, passkeys) - .routes() - .merge(app.clone().routes()), - app, - client, - secret, - cookie, - user_id, - basic, - } - } - /// The same scenario, sending its requests to `router`, such as one of [`Replicas`]. - fn on(&self, router: &axum::Router) -> Self { - Self { - router: router.clone(), - ..self.clone() - } - } - /// Signs the scenario's browser in again with `method`, as a new session. - async fn sign_in_again(&mut self, method: AuthenticationMethod) { - let mut tx = self.app.database.begin().await.expect("transaction"); - let session = Session::create(&mut tx, RequestContext::TEST, self.user_id, method.into()) - .await - .expect("session"); - tx.commit().await.expect("commit"); - self.cookie = format!("{}={}", BrowserCookie::Session.as_str(), session.encoded()); - } - /// Lists the events recorded about the scenario account, newest first. - async fn events(&self) -> Vec { - self.app - .database - .events() - .history_for_user(self.user_id, 100) - .await - .expect("history") - .into_iter() - .map(|stored| stored.event.known().cloned().expect("a known event")) - .collect() - } - - /// Dispatches an encoded protocol request, or a page's form, through the OIDC routes. - async fn request( - &self, - method: Method, - uri: &str, - form: &[(&str, &str)], - basic: Option<&str>, - ) -> Response { - let mut builder = Request::builder() - .extension(RequestContext::TEST) - .method(method) - .uri(uri) - .header(header::COOKIE, &self.cookie) - .header(header::ORIGIN, &self.app.issuer) - .header("x-piquel-csrf", "1"); - if let Some(basic) = basic { - builder = builder.header(header::AUTHORIZATION, basic); - } - let body = url::form_urlencoded::Serializer::new(String::new()) - .extend_pairs(form.iter().copied()) - .finish(); - let request = builder - .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") - .body(Body::from(body)) - .expect("build test HTTP request"); - self.router - .clone() - .oneshot(request) - .await - .expect("dispatch OIDC HTTP request") - } - /// Accepts query authorization requests and returns OAuth errors for malformed input. - async fn authorize(&self, scope: &str, prompt: Option<&str>) -> Response { - self.authorize_with(Method::GET, scope, prompt, &[]).await - } - /// Builds an authorization request with optional hint or security parameter overrides. - async fn authorize_with( - &self, - method: Method, - scope: &str, - prompt: Option<&str>, - extra: &[(&str, &str)], - ) -> Response { - let url = self.authorization_url(scope, prompt, extra); - if method == Method::POST { - self.post_query(&url, None).await - } else { - self.request( - method, - &format!( - "{}?{}", - url.path(), - url.query().expect("authorization query") - ), - &[], - None, - ) - .await - } - } - /// Pushes the scenario's authorization request with `basic` credentials. - async fn push(&self, scope: &str, prompt: Option<&str>, basic: Option<&str>) -> Response { - let mut url = self.authorization_url(scope, prompt, &[]); - url.set_path(routes::oidc::PAR); - self.post_query(&url, basic).await - } - /// Pushes the scenario's request with its credentials and returns its `request_uri`. - async fn pushed(&self, scope: &str, prompt: Option<&str>) -> String { - let response = self.push(scope, prompt, self.basic.as_deref()).await; - assert_eq!(response.status(), StatusCode::CREATED); - let body = Self::json(response).await; - assert_eq!(body["expires_in"], PUSHED_REQUEST_SECONDS); - body["request_uri"] - .as_str() - .expect("pushed request has a request_uri") - .to_owned() - } - /// Brings a `request_uri` to the authorization endpoint as `client_id`, along - /// with `extra` parameters, which must not override the pushed ones. - async fn claim(&self, client_id: &str, request_uri: &str, extra: &[(&str, &str)]) -> Response { - let mut url = Url::parse(&format!("{AUTH_ORIGIN}{}", routes::oidc::AUTHORIZE)) - .expect("parse authorization endpoint URL"); - url.query_pairs_mut() - .append_pair("client_id", client_id) - .append_pair("request_uri", request_uri) - .extend_pairs(extra.iter().copied()); - let uri = format!("{}?{}", url.path(), url.query().expect("query")); - self.request(Method::GET, &uri, &[], None).await - } - /// Posts `url`'s query as a form to its path. - async fn post_query(&self, url: &Url, basic: Option<&str>) -> Response { - let owned: Vec<_> = url.query_pairs().into_owned().collect(); - let fields: Vec<_> = owned - .iter() - .map(|(key, value)| (key.as_str(), value.as_str())) - .collect(); - self.request(Method::POST, url.path(), &fields, basic).await - } - /// The authorization endpoint with the scenario's request parameters, then `extra`. - fn authorization_url(&self, scope: &str, prompt: Option<&str>, extra: &[(&str, &str)]) -> Url { - let mut url = Url::parse(&format!("{AUTH_ORIGIN}/oauth/authorize")) - .expect("parse authorization endpoint URL"); - url.query_pairs_mut().extend_pairs([ - ("response_type", ResponseType::Code.as_str()), - ("client_id", self.client.id.as_str()), - ("redirect_uri", self.client.redirect_uris[0].as_str()), - ("scope", scope), - ("state", "test-state"), - ("nonce", "test-nonce"), - ("code_challenge_method", CodeChallengeMethod::S256.as_str()), - ( - "code_challenge", - &piquel_crypto::Pkce::challenge(Self::verifier()).expect("PKCE"), - ), - ]); - if let Some(prompt) = prompt { - url.query_pairs_mut().append_pair("prompt", prompt); - } - url.query_pairs_mut().extend_pairs(extra.iter().copied()); - url - } - /// Returns the valid PKCE verifier used by database-backed scenarios. - fn verifier() -> &'static str { - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" - } - /// Reads a redirect back to the client, which must name this issuer in `iss` (RFC 9207). - fn client_redirect(&self, response: &Response) -> Url { - self.issued(location(response)) - } - /// Returns an authorization response URL after checking its `iss`. - fn issued(&self, url: Url) -> Url { - assert_eq!(parameter(&url, "iss"), self.app.issuer); - url - } - /// Reads the scenario's text response. - async fn text(response: Response) -> String { - String::from_utf8( - to_bytes(response.into_body(), 1024 * 1024) - .await - .expect("read complete HTTP response body") - .to_vec(), - ) - .expect("UTF-8 response") - } - /// Reads and decodes the scenario’s JSON response. - async fn json(response: Response) -> Value { - serde_json::from_slice( - &to_bytes(response.into_body(), 1024 * 1024) - .await - .expect("read complete HTTP response body"), - ) - .expect("decode HTTP JSON response") - } - /// Completes explicit consent when needed and extracts the issued authorization code. - async fn code(&self, scopes: &str) -> String { - let response = self.authorize(scopes, None).await; - parameter(&self.consent(response).await, "code") - } - /// Follows an authorization response through consent, when needed, to the client - /// redirect, whose `iss` it checks. - async fn consent(&self, response: Response) -> Url { - assert_eq!(response.status(), StatusCode::SEE_OTHER); - let mut destination = location(&response); - if destination.path() == routes::page::CONSENT { - let transaction = parameter(&destination, "transaction"); - let response = self - .request( - Method::POST, - routes::page::CONSENT, - &[("transaction", &transaction), ("decision", APPROVE_CONSENT)], - None, - ) - .await; - assert_eq!(response.status(), StatusCode::SEE_OTHER); - destination = location(&response); - } - self.issued(destination) - } - /// Exchanges a scenario code with the requested verifier and client credentials. - async fn exchange(&self, code: &str, verifier: &str, basic: Option<&str>) -> Response { - self.request( - Method::POST, - "/oauth/token", - &[ - ("grant_type", GrantType::AuthorizationCode.as_str()), - ("client_id", self.client.id.as_str()), - ("redirect_uri", self.client.redirect_uris[0].as_str()), - ("code", code), - ("code_verifier", verifier), - ], - basic, - ) - .await - } - /// Verifies the ID token of a successful token response and returns the response - /// with the token's claims. - async fn id_token(&self, response: Response) -> (Value, Value) { - assert_eq!(response.status(), StatusCode::OK); - let tokens = Self::json(response).await; - let claims = self - .app - .keys - .current() - .expect("fresh keys") - .verify( - tokens["id_token"].as_str().expect("ID token"), - TokenType::Id, - &self.app.issuer, - ) - .expect("verify ID token"); - (tokens, claims) - } - /// The scenario's account, as the owner of its browser session. - async fn owner(&self) -> crate::account::Owner { - let mut headers = axum::http::HeaderMap::new(); - headers.insert(header::COOKIE, self.cookie.parse().expect("cookie")); - crate::account::AccountService::new(self.app.database.clone()) - .owner(RequestContext::TEST, &headers) - .await - .expect("session lookup") - .expect("signed in") - } - /// Asserts that a token response rejected its grant as `invalid_grant`. - async fn assert_invalid_grant(response: Response) { - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert_eq!( - Self::json(response).await["error"], - OAuthCode::InvalidGrant.as_str() - ); - } - /// Rotates a scenario refresh token using its registered client credentials. - async fn refresh(&self, token: &str) -> Response { - self.request( - Method::POST, - "/oauth/token", - &[ - ("grant_type", GrantType::RefreshToken.as_str()), - ("client_id", self.client.id.as_str()), - ("refresh_token", token), - ], - self.basic.as_deref(), - ) - .await - } -} - -/// Both well-known paths serve the same cacheable, typed document, and every endpoint -/// it advertises is routed on the issuer. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn metadata_is_one_document_whose_endpoints_are_routed() { - let flow = Flow::new(false, false).await; - let mut documents = vec![]; - let jwks = flow - .request(Method::GET, routes::oidc::JWKS, &[], None) - .await; - assert_eq!( - jwks.extensions().get::(), - Some(&PublicDocument::CACHE) - ); - for path in [routes::oidc::DISCOVERY, routes::oidc::OAUTH_METADATA] { - let response = flow.request(Method::GET, path, &[], None).await; - assert_eq!(response.status(), StatusCode::OK, "{path}"); - assert_eq!( - response.extensions().get::(), - Some(&PublicDocument::CACHE) - ); - documents.push( - to_bytes(response.into_body(), 1024 * 1024) - .await - .expect("read metadata"), - ); - } - assert_eq!(documents[0], documents[1]); - let metadata: ServerMetadata = serde_json::from_slice(&documents[0]).expect("typed metadata"); - assert_eq!(metadata.issuer, flow.app.issuer); - assert_eq!(metadata.acr_values_supported, Acr::ALL); - let Value::Object(fields) = serde_json::from_slice(&documents[0]).expect("metadata JSON") - else { - panic!("metadata is not a JSON object"); - }; - for (name, value) in fields { - if !(name.ends_with("_endpoint") || name == "jwks_uri") { - continue; - } - let url = Url::parse(value.as_str().expect("endpoint text")).expect("endpoint URL"); - assert_eq!( - url.origin().ascii_serialization(), - metadata.issuer, - "{name}" - ); - let response = flow.request(Method::GET, url.path(), &[], None).await; - assert_ne!(response.status(), StatusCode::NOT_FOUND, "{name}"); - } -} - -/// Checks public-client consent, PKCE, scoped claims and one-use authorization codes. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn public_consent_pkce_claim_scoping_and_replay() { - let flow = Flow::new(false, false).await; - let response = flow - .authorize(Scope::OpenId.as_str(), Some(Prompt::None.as_str())) - .await; - assert_eq!( - parameter(&flow.client_redirect(&response), "error"), - OAuthCode::ConsentRequired.as_str() - ); - let code = flow.code(Scope::OpenId.as_str()).await; - assert_eq!( - flow.exchange(&code, "wrong", None).await.status(), - StatusCode::BAD_REQUEST - ); - let response = flow.exchange(&code, Flow::verifier(), None).await; - assert_eq!(response.status(), StatusCode::OK); - let tokens = Flow::json(response).await; - let claims: IdTokenClaims = flow - .app - .keys - .current() - .expect("fresh keys") - .verify( - tokens["id_token"] - .as_str() - .expect("token response contains an ID token"), - TokenType::Id, - &flow.app.issuer, - ) - .expect("verify scoped ID token"); - assert_eq!(claims.nonce.as_deref(), Some("test-nonce")); - assert!(claims.profile.name.is_none()); - assert!(claims.profile.email.is_none()); - assert_eq!( - flow.exchange(&code, Flow::verifier(), None).await.status(), - StatusCode::BAD_REQUEST - ); - let response = flow - .authorize(Scope::OpenId.as_str(), Some(Prompt::None.as_str())) - .await; - assert!( - flow.client_redirect(&response) - .query_pairs() - .any(|(name, _)| name == "code") - ); - let response = flow - .authorize(EMAIL_SCOPES, Some(Prompt::None.as_str())) - .await; - assert_eq!( - parameter(&flow.client_redirect(&response), "error"), - OAuthCode::ConsentRequired.as_str() - ); - let response = flow - .authorize(Scope::OpenId.as_str(), Some(Prompt::Login.as_str())) - .await; - assert_eq!(location(&response).path(), "/login"); - let client_id = flow.client.id.clone(); - assert_eq!( - flow.events().await[..3], - [ - DomainEvent::CodeReplayed { - client_id: client_id.clone(), - }, - DomainEvent::GrantIssued { - client_id: client_id.clone(), - family_id: None, - scopes: vec![Scope::OpenId.as_str().into()], - }, - DomainEvent::ConsentGranted { - client_id, - scopes: vec![Scope::OpenId.as_str().into()], - }, - ], - "a failed exchange records nothing" - ); -} - -/// Checks refresh narrowing, replay revocation, client binding and logout. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -#[expect( - clippy::too_many_lines, - reason = "The scenario follows one refresh family through narrowing, replay and logout." -)] -async fn confidential_refresh_rotation_logout_and_client_binding() { - let flow = Flow::new(true, true).await; - let code = flow.code(EMAIL_REFRESH_SCOPES).await; - assert_eq!( - flow.exchange(&code, Flow::verifier(), None).await.status(), - StatusCode::UNAUTHORIZED - ); - 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 claims: IdTokenClaims = flow - .app - .keys - .current() - .expect("fresh keys") - .verify( - tokens["id_token"] - .as_str() - .expect("token response contains an ID token"), - TokenType::Id, - &flow.app.issuer, - ) - .expect("verify confidential client ID token"); - assert_eq!( - claims.profile.email, - Some(format!("{}@example.com", flow.user_id)) - ); - assert_eq!(claims.profile.email_verified, Some(true)); - let old = tokens["refresh_token"] - .as_str() - .expect("token response contains a refresh token"); - let other = Flow::new(false, true).await; - assert_eq!(other.refresh(old).await.status(), StatusCode::BAD_REQUEST); - let invalid = flow - .request( - Method::POST, - "/oauth/token", - &[ - ("grant_type", GrantType::RefreshToken.as_str()), - ("client_id", flow.client.id.as_str()), - ("refresh_token", old), - ("scope", UNGRANTED_SCOPES), - ], - flow.basic.as_deref(), - ) - .await; - assert_eq!(invalid.status(), StatusCode::BAD_REQUEST); - assert_eq!( - Flow::json(invalid).await["error"], - OAuthCode::InvalidScope.as_str() - ); - let response = flow - .request( - Method::POST, - "/oauth/token", - &[ - ("grant_type", GrantType::RefreshToken.as_str()), - ("client_id", flow.client.id.as_str()), - ("refresh_token", old), - ("scope", Scope::OpenId.as_str()), - ], - flow.basic.as_deref(), - ) - .await; - assert_eq!(response.status(), StatusCode::OK); - let narrowed = Flow::json(response).await; - assert_eq!(narrowed["scope"], Scope::OpenId.as_str()); - let narrowed_claims: IdTokenClaims = flow - .app - .keys - .current() - .expect("fresh keys") - .verify( - narrowed["id_token"] - .as_str() - .expect("refresh response contains an ID token"), - TokenType::Id, - &flow.app.issuer, - ) - .expect("verify narrowed ID token"); - assert!(narrowed_claims.profile.email.is_none()); - let fresh = narrowed["refresh_token"] - .as_str() - .expect("refresh response contains the rotated token") - .to_owned(); - assert_eq!(flow.refresh(old).await.status(), StatusCode::BAD_REQUEST); - assert_eq!(flow.refresh(&fresh).await.status(), StatusCode::BAD_REQUEST); - let code = flow.code(REFRESH_SCOPES).await; - let response = flow - .exchange(&code, Flow::verifier(), flow.basic.as_deref()) - .await; - let tokens = Flow::json(response).await; - let response = flow - .request( - Method::POST, - routes::page::LOGOUT, - &[ - ("client_id", flow.client.id.as_str()), - ( - "post_logout_redirect_uri", - flow.client.post_logout_uris[0].as_str(), - ), - ], - None, - ) - .await; - assert_eq!( - location(&response).as_str(), - flow.client.post_logout_uris[0].as_str() - ); - assert!( - response.headers()[header::SET_COOKIE] - .to_str() - .expect("Set-Cookie header is valid text") - .contains("Max-Age=0") - ); - assert_eq!( - flow.refresh( - tokens["refresh_token"] - .as_str() - .expect("token response contains a refresh token") - ) - .await - .status(), - StatusCode::BAD_REQUEST - ); - assert_eq!( - parameter( - &flow.client_redirect( - &flow - .authorize(Scope::OpenId.as_str(), Some(Prompt::None.as_str())) - .await - ), - "error" - ), - OAuthCode::LoginRequired.as_str() - ); - let events = flow.events().await; - assert!( - matches!( - &events[0], - DomainEvent::SessionRevoked { - reason: RevocationReason::RelyingPartyLogout { client_id }, - .. - } if *client_id == flow.client.id - ), - "{events:?}" - ); - assert!(events.iter().any(|event| matches!( - event, - DomainEvent::GrantRevoked { - reason: GrantRevocation::RefreshReplay, - .. - } - ))); -} - -/// A client's back-channel logout endpoint on a local HTTPS port: its URI, a client -/// that reaches it, and the logout tokens it received. -async fn logout_receiver() -> (RedirectUri, OutboundClient, Arc>>) { - let posted = Arc::new(Mutex::new(Vec::new())); - let receiver = axum::Router::new().route( - "/backchannel-logout", - axum::routing::post({ - let posted = Arc::clone(&posted); - async move |axum::Form(form): axum::Form>| { - posted - .lock() - .expect("posted tokens") - .push(form["logout_token"].clone()); - StatusCode::OK - } - }), - ); - let tcp = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind receiver"); - let uri = format!( - "https://localhost:{}/backchannel-logout", - tcp.local_addr().expect("address").port() - ) - .parse() - .expect("logout URI"); - let outbound = OutboundClient::local(TlsListener::serve(tcp, receiver)); - (uri, outbound, posted) -} - -/// Ending a session posts a logout token to each client that received tokens from it -/// and registered a back-channel logout URI (OIDC Back-Channel Logout 1.0 §2.4): -/// signed as `logout+jwt`, naming the client, the user and the ended session, with -/// the delivery's ID as `jti`, valid for two minutes, and never with a `nonce`. A -/// client that got no tokens from the session is not told. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn logout_posts_a_logout_token_to_the_clients_of_the_session() { - let flow = Flow::new(true, true).await; - let (uri, outbound, posted) = logout_receiver().await; - let sender = - BackchannelLogoutSender::new(flow.app.issuer.clone(), flow.app.keys.clone(), outbound); - let told = ClientRegistration { - backchannel_logout_uri: Some(uri.clone()), - ..flow.client.clone() - }; - let untold = ClientRegistration { - backchannel_logout_uri: Some(uri), - ..crate::tests::registration(ClientKind::Public, "https://untold.example") - }; - crate::tests::change(&flow.app.database, async |registry| { - registry - .update(&told.id, |_| { - Ok::<_, crate::ClientRegistryError>(told.clone()) - }) - .await?; - // A client without tokens from the session. - registry.create(ClientOwner::Operator, &untold, None).await - }) - .await - .expect("register the logout URIs"); - let code = flow.code(Scope::OpenId.as_str()).await; - let (_, id_token) = flow - .id_token( - flow.exchange(&code, Flow::verifier(), flow.basic.as_deref()) - .await, - ) - .await; - let response = flow - .request( - Method::POST, - routes::page::LOGOUT, - &[("client_id", told.id.as_str())], - None, - ) - .await; - assert_eq!(response.status(), StatusCode::SEE_OTHER); - - // Other scenarios share the database: send only this session's deliveries. - let mut sent = Vec::new(); - while let Some(delivery) = flow - .app - .database - .deliveries() - .claim::(std::time::Duration::from_mins(1)) - .await - .expect("claim") - { - if delivery.recipient.sid.to_string() == id_token["sid"] { - sender.send(&delivery).await.expect("the client accepts it"); - sent.push((delivery.id, delivery.recipient.client_id)); - } - } - let [(delivery, client)] = - <[_; 1]>::try_from(sent).expect("one delivery for the one client told"); - assert_eq!(client, told.id); - let [token] = <[_; 1]>::try_from(posted.lock().expect("posted tokens").clone()) - .expect("one token posted"); - let claims: Value = flow - .app - .keys - .current() - .expect("fresh keys") - .verify(&token, TokenType::Logout, &flow.app.issuer) - .expect("a logout token signed by auth"); - let issued_at = claims["iat"].as_i64().expect("iat"); - assert!( - (issued_at - Utc::now().timestamp()).abs() < 60, - "signed when sent" - ); - assert_eq!( - claims, - json!({ - "iss": flow.app.issuer, - "aud": told.id, - "iat": issued_at, - "exp": issued_at + 120, - "jti": delivery, - "sub": flow.user_id, - "sid": id_token["sid"], - "events": {BACKCHANNEL_LOGOUT_EVENT: {}}, - }) - ); -} - -/// An administrator removes an account's app with the owner's own operation: its -/// refresh grant ends, and the removal is recorded as the administrator's, with -/// the reason they gave. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn an_administrator_removes_an_app_with_a_reason() { - let flow = Flow::new(false, false).await; - let code = flow.code(REFRESH_SCOPES).await; - let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await; - let refresh = tokens["refresh_token"].as_str().expect("refresh token"); - let harness = crate::admin::tests::Harness { - database: flow.app.database.clone(), - }; - let admin = harness.admin().await; - let reason = "Reported as an impersonating app"; - let subject = crate::account::Subject::operator( - flow.user_id, - crate::admin::tests::operator(admin, Utc::now()), - crate::Reason::parse(reason.into()).expect("reason"), - ); - crate::account::AccountService::new(flow.app.database.clone()) - .remove_app(&subject, &flow.client.id) - .await - .expect("remove"); - Flow::assert_invalid_grant(flow.refresh(refresh).await).await; - let history = flow - .app - .database - .events() - .history_for_user(flow.user_id, 100) - .await - .expect("history"); - let removed = DomainEvent::ConsentRevoked { - client_id: flow.client.id.clone(), - }; - let stored = history - .iter() - .find(|stored| stored.event.known() == Some(&removed)) - .expect("recorded"); - let actor = Actor::Admin { - user_id: admin.user_id, - session_id: admin.session_id, - }; - assert_eq!(stored.actor, actor); - assert_eq!(stored.reason.as_deref(), Some(reason)); -} - -/// Removing an app from the account's settings ends its refresh grant and its -/// outstanding code, and forgets the consent, so it asks again. It is recorded -/// once, and listed no more. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn removing_an_app_ends_its_access() { - let flow = Flow::new(false, false).await; - let code = flow.code(REFRESH_SCOPES).await; - let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await; - let refresh = tokens["refresh_token"].as_str().expect("refresh token"); - let outstanding = flow.code(REFRESH_SCOPES).await; - let service = crate::account::AccountService::new(flow.app.database.clone()); - let owner = flow.owner().await; - let viewer = crate::account::Viewer::from(&owner); - let apps = service.apps(&viewer).await.expect("apps"); - assert_eq!(apps.len(), 1); - assert_eq!(apps[0].client_id, flow.client.id); - assert_eq!(apps[0].scopes, [Scope::OpenId.as_str()]); - assert!(apps[0].offline && !apps[0].first_party); - - service - .remove_app(&crate::account::Subject::from(owner), &flow.client.id) - .await - .expect("remove"); - assert!(service.apps(&viewer).await.expect("apps").is_empty()); - assert_eq!( - flow.events().await[0], - DomainEvent::ConsentRevoked { - client_id: flow.client.id.clone() - } - ); - Flow::assert_invalid_grant(flow.refresh(refresh).await).await; - Flow::assert_invalid_grant(flow.exchange(&outstanding, Flow::verifier(), None).await).await; - let response = flow - .authorize(REFRESH_SCOPES, Some(Prompt::None.as_str())) - .await; - assert_eq!( - parameter(&flow.client_redirect(&response), "error"), - OAuthCode::ConsentRequired.as_str() - ); -} - -/// A code issued before the user withdrew consent is not exchanged after it, -/// even when it is not expired, as one an authorization issued just as a removal -/// withdrew the consent is not. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn withdrawn_consent_stops_an_issued_code() { - let flow = Flow::new(false, false).await; - let code = flow.code(Scope::OpenId.as_str()).await; - flow.app - .database - .oidc() - .revoke_consents(flow.user_id, Some(&flow.client.id)) - .await - .expect("withdraw"); - Flow::assert_invalid_grant(flow.exchange(&code, Flow::verifier(), None).await).await; -} - -/// An exchange that starts while an app's removal holds the account waits for it, -/// before taking its code, so even a first-party app, which needs no consent, -/// finds its code expired rather than creating a refresh grant after the removal. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn an_exchange_waits_for_a_removal_and_finds_its_code_expired() { - let flow = Flow::new(false, true).await; - let code = flow.code(REFRESH_SCOPES).await; - let database = flow.app.database.clone(); - let mut removal = database.begin().await.expect("transaction"); - removal - .users() - .find_active_by_id_for_update(flow.user_id) - .await - .expect("lock") - .expect("user"); - let exchanging = flow.clone(); - let exchange = tokio::spawn(async move { - let response = exchanging.exchange(&code, Flow::verifier(), None).await; - (response.status(), Flow::json(response).await) - }); - until_blocked(&mut removal, 1).await; - removal - .oidc() - .expire_codes(flow.user_id, &flow.client.id) - .await - .expect("expire"); - removal.commit().await.expect("commit"); - - let (status, body) = exchange.await.expect("exchange"); - assert_eq!(status, StatusCode::BAD_REQUEST); - assert_eq!(body["error"], OAuthCode::InvalidGrant.as_str()); -} - -/// 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 - ); - let events = flow.events().await; - let [ - DomainEvent::GrantRevoked { - family_id: revoked, - reason: GrantRevocation::CodeReplay, - .. - }, - DomainEvent::CodeReplayed { .. }, - DomainEvent::GrantIssued { - family_id: Some(issued), - .. - }, - .., - ] = events.as_slice() - else { - panic!("{events:?}"); - }; - assert_eq!(revoked, issued, "the replay revoked the code's own family"); -} - -/// The same refresh token, rotated on two replicas at once, rotates exactly once. The -/// other attempt is a replay, which revokes the family. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn concurrent_refresh_across_replicas_rotates_once() { - let flow = Flow::new(true, true).await; - let replicas = Replicas::new().await; - let (a, b) = (flow.on(&replicas.a), flow.on(&replicas.b)); - let code = a.code(REFRESH_SCOPES).await; - let response = b - .exchange(&code, Flow::verifier(), b.basic.as_deref()) - .await; - assert_eq!(response.status(), StatusCode::OK); - let token = Flow::json(response).await["refresh_token"] - .as_str() - .expect("token response contains a refresh token") - .to_owned(); - let (first, second) = tokio::join!(a.refresh(&token), b.refresh(&token)); - let (rotated, replayed) = if first.status() == StatusCode::OK { - (first, second) - } else { - (second, first) - }; - assert_eq!(rotated.status(), StatusCode::OK); - assert_eq!(replayed.status(), StatusCode::BAD_REQUEST); - let rotated = Flow::json(rotated).await["refresh_token"] - .as_str() - .expect("refresh response contains the rotated token") - .to_owned(); - assert_eq!( - a.refresh(&rotated).await.status(), - StatusCode::BAD_REQUEST, - "the replay revoked the family" - ); -} - -/// A new signing key and a new token digest key leave outstanding codes and -/// refresh tokens valid, since the old digest key is still accepted. What -/// replaces them is digested under the new key alone. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn changing_keys_keeps_codes_and_refresh_tokens() { - let flow = Flow::new(true, true).await; - let code = flow.code(REFRESH_SCOPES).await; - let tokens = Flow::json( - flow.exchange( - &flow.code(REFRESH_SCOPES).await, - Flow::verifier(), - flow.basic.as_deref(), - ) - .await, - ) - .await; - let token = tokens["refresh_token"].as_str().expect("refresh token"); - let app = OidcApplication::new( - flow.app.database.clone(), - &OidcConfig { - origin: flow.app.issuer.parse().expect("issuer"), - digest_keys: Arc::new(TokenDigestKeys::new( - TokenDigestKey::derive(&[8; 32]).expect("new digest key"), - Some(TokenDigestKey::derive(&[7; 32]).expect("old digest key")), - )), - policies: PolicyLinks::on(&crate::tests::WEB_ORIGIN.parse().expect("web origin")), - }, - SigningKeys::new(KeySet::single( - Rs256Key::generate("rotated").expect("new signing key"), - )), - ) - .expect("OIDC application"); - let changed = Flow { - router: app.clone().routes(), - app, - ..flow.clone() - }; - let exchanged = changed - .exchange(&code, Flow::verifier(), changed.basic.as_deref()) - .await; - assert_eq!(exchanged.status(), StatusCode::OK); - let refreshed = changed.refresh(token).await; - assert_eq!(refreshed.status(), StatusCode::OK); - let rotated = Flow::json(refreshed).await["refresh_token"] - .as_str() - .expect("rotated refresh token") - .to_owned(); - assert_eq!( - flow.refresh(&rotated).await.status(), - StatusCode::BAD_REQUEST, - "only the new digest key made the rotated token" - ); - assert_eq!(changed.refresh(&rotated).await.status(), StatusCode::OK); -} - -/// Checks that policy reductions reject new requests and invalidate outstanding grants, -/// and that unsafe logout redirects are refused. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn policy_reduction_blocks_outstanding_codes_and_refresh() { - let mut flow = Flow::new(false, true).await; - let code = flow.code(EMAIL_SCOPES).await; - let database = flow.app.database.clone(); - flow.client.allowed_scopes = - AllowedScopes::new([Scope::OpenId, Scope::OfflineAccess].map(ScopeName::from)) - .expect("reduced scopes"); - let client = flow.client.clone(); - crate::tests::replace(&database, &client) - .await - .expect("apply reduced client scope policy"); - assert_eq!( - flow.exchange(&code, Flow::verifier(), None).await.status(), - StatusCode::BAD_REQUEST - ); - assert_eq!( - parameter( - &flow.client_redirect(&flow.authorize(EMAIL_SCOPES, None).await), - "error" - ), - OAuthCode::InvalidScope.as_str() - ); - let code = flow.code(REFRESH_SCOPES).await; - let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await; - flow.client.allow_refresh = false; - let client = flow.client.clone(); - crate::tests::replace(&database, &client) - .await - .expect("disable client refresh permission"); - assert_eq!( - flow.refresh( - tokens["refresh_token"] - .as_str() - .expect("token response contains a refresh token") - ) - .await - .status(), - StatusCode::BAD_REQUEST - ); - let response = flow - .request( - Method::GET, - "/oidc/logout?client_id=unknown&post_logout_redirect_uri=https%3A%2F%2Fevil.example", - &[], - None, - ) - .await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); -} - -/// Checks that ID hints bind the account across initial, resumed and consent requests. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn authorization_hints_bind_initial_resumed_and_consent_requests() { - let flow = Flow::new(false, true).await; - let now = Utc::now().timestamp(); - let claims = json!({"iss":flow.app.issuer,"sub":flow.user_id,"aud":flow.client.id,"iat":now-600,"exp":now-300}); - let hint = flow - .app - .keys - .current() - .expect("fresh keys") - .sign(TokenType::Id, &claims) - .expect("sign expired hint"); - let response = flow - .authorize_with( - Method::GET, - Scope::OpenId.as_str(), - Some(Prompt::None.as_str()), - &[("id_token_hint", &hint)], - ) - .await; - assert_ne!(parameter(&flow.client_redirect(&response), "code"), ""); - for (field, value) in [ - ("iss", json!("https://foreign.example")), - ("aud", json!("other-client")), - ] { - let mut invalid = claims.clone(); - invalid[field] = value; - let hint = flow - .app - .keys - .current() - .expect("fresh keys") - .sign(TokenType::Id, &invalid) - .expect("sign invalid hint"); - let response = flow - .authorize_with( - Method::GET, - Scope::OpenId.as_str(), - Some(Prompt::None.as_str()), - &[("id_token_hint", &hint)], - ) - .await; - assert_eq!( - parameter(&flow.client_redirect(&response), "error"), - OAuthCode::InvalidRequest.as_str() - ); - } - let mut other = claims; - other["sub"] = json!(UserId::new()); - let hint = flow - .app - .keys - .current() - .expect("fresh keys") - .sign(TokenType::Id, &other) - .expect("sign other account hint"); - let response = flow - .authorize_with( - Method::GET, - Scope::OpenId.as_str(), - Some(Prompt::None.as_str()), - &[("id_token_hint", &hint)], - ) - .await; - assert_eq!( - parameter(&flow.client_redirect(&response), "error"), - OAuthCode::LoginRequired.as_str() - ); - let response = flow - .authorize_with( - Method::GET, - Scope::OpenId.as_str(), - None, - &[("id_token_hint", &hint)], - ) - .await; - let login = location(&response); - assert_eq!(login.path(), "/login"); - let transaction = parameter(&login, "transaction"); - let response = flow - .request( - Method::GET, - &format!("/oauth/authorize/resume?transaction={transaction}"), - &[], - None, - ) - .await; - assert_eq!(location(&response).path(), "/login"); - let response = flow - .request( - Method::POST, - routes::page::CONSENT, - &[("transaction", &transaction), ("decision", APPROVE_CONSENT)], - None, - ) - .await; - assert_eq!(response.status(), StatusCode::UNAUTHORIZED); -} - -/// A consent that waits for the account lock while every session ends is not -/// saved: approving reads the session again under the lock. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn a_consent_whose_session_ended_while_waiting_is_not_saved() { - let flow = Flow::new(true, false).await; - let response = flow.authorize("openid", None).await; - let transaction = parameter(&location(&response), "transaction"); - let database = flow.app.database.clone(); - let mut holder = database.begin().await.expect("transaction"); - holder - .users() - .find_active_by_id_for_update(flow.user_id) - .await - .expect("lock") - .expect("user"); - let approving = flow.clone(); - let decision = tokio::spawn(async move { - let form = [ - ("transaction", transaction.as_str()), - ("decision", APPROVE_CONSENT), - ]; - let response = approving - .request(Method::POST, routes::page::CONSENT, &form, None) - .await; - response.status() - }); - until_blocked(&mut holder, 1).await; - let context = RequestContext::TEST.actor(Actor::Anonymous); - holder - .revoke_sessions( - &context, - flow.user_id, - SessionScope::All, - &RevocationReason::Admin, - ) - .await - .expect("every session ends"); - holder.commit().await.expect("commit"); - - assert_eq!(decision.await.expect("decision"), StatusCode::UNAUTHORIZED); - let consents = database.oidc().list_consents(flow.user_id).await; - assert!(consents.expect("consents").is_empty(), "not saved"); -} - -/// A rename bumps the profile version, and the next token carries the new -/// `preferred_username`. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn renames_reach_the_next_token() { - let flow = Flow::new(true, true).await; - let code = flow.code(PROFILE_REFRESH_SCOPES).await; - let (tokens, claims) = flow - .id_token( - flow.exchange(&code, Flow::verifier(), flow.basic.as_deref()) - .await, - ) - .await; - let database = &flow.app.database; - let user = database - .users() - .find_by_id(flow.user_id) - .await - .expect("lookup") - .expect("user"); - assert_eq!(claims["preferred_username"], user.handle.as_str()); - let renamed = - Handle::parse(&format!("renamed-{}", &flow.user_id.to_string()[24..])).expect("handle"); - let mut tx = database.begin().await.expect("transaction"); - assert!( - tx.rename_handle(flow.user_id, &renamed) - .await - .expect("rename") - ); - tx.commit().await.expect("commit"); - let (_, refreshed) = flow - .id_token( - flow.refresh(tokens["refresh_token"].as_str().expect("refresh token")) - .await, - ) - .await; - assert_eq!(refreshed["preferred_username"], renamed.as_str()); - assert_eq!(refreshed["profile_version"], user.profile_version + 1); -} - -/// Tokens report the class and time of the grant's authentication: a refresh keeps -/// them after the session re-authenticates, and `acr_values` makes a weaker session -/// sign in again while unknown values are ignored. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn acr_targets_and_grants_keep_their_authentication() { - let mut flow = Flow::new(true, true).await; - let code = flow.code(REFRESH_SCOPES).await; - let (tokens, claims) = flow - .id_token( - flow.exchange(&code, Flow::verifier(), flow.basic.as_deref()) - .await, - ) - .await; - assert_eq!(claims["acr"], Acr::PhishingResistant.as_str()); - assert_eq!(claims["amr"], json!(["pop", "mfa", "user"])); - let session = claims["sid"] - .as_str() - .expect("sid") - .parse() - .expect("session ID"); - flow.app - .database - .sessions() - .confirm_passkey( - session, - PasskeyId::new(), - Utc::now() + chrono::Duration::minutes(5), - ) - .await - .expect("re-authenticate"); - let (_, refreshed) = flow - .id_token( - flow.refresh(tokens["refresh_token"].as_str().expect("refresh token")) - .await, - ) - .await; - assert_eq!(refreshed["auth_time"], claims["auth_time"]); - assert_eq!(refreshed["acr"], claims["acr"]); - - flow.sign_in_again(AuthenticationMethod::Federation).await; - let phr = [("acr_values", "urn:example:gold phr")]; - let response = flow - .authorize_with( - Method::GET, - Scope::OpenId.as_str(), - Some(Prompt::None.as_str()), - &phr, - ) - .await; - assert_eq!( - parameter(&flow.client_redirect(&response), "error"), - OAuthCode::LoginRequired.as_str() - ); - let response = flow - .authorize_with(Method::GET, Scope::OpenId.as_str(), None, &phr) - .await; - let login = location(&response); - assert_eq!(login.path(), routes::page::LOGIN); - assert_eq!(parameter(&login, "acr"), Acr::PhishingResistant.as_str()); - for acr_values in ["urn:example:gold", "urn:piquel:acr:social phr"] { - let response = flow - .authorize_with( - Method::GET, - Scope::OpenId.as_str(), - Some(Prompt::None.as_str()), - &[("acr_values", acr_values)], - ) - .await; - let code = parameter(&flow.client_redirect(&response), "code"); - let (_, claims) = flow - .id_token( - flow.exchange(&code, Flow::verifier(), flow.basic.as_deref()) - .await, - ) - .await; - assert_eq!(claims["acr"], Acr::Social.as_str(), "{acr_values}"); - assert_eq!(claims["amr"], json!(["fed"])); - } -} - -/// A browser that signed in for an authorization with a recovered passkey during -/// its probation cannot reach `phr` by signing in again, so the client hears -/// `unmet_authentication_requirements` instead of its user looping through -/// sign-in. A social sign-in, which a passkey could still step up, and a -/// probation sign-in from before the request go to sign in, as before. Without a -/// target, a probation sign-in is enough. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn a_probation_sign_in_short_of_the_target_answers_the_client() { - let mut flow = Flow::new(true, true).await; - flow.sign_in_again(AuthenticationMethod::Federation).await; - let phr = [("acr_values", "phr")]; - let response = flow - .authorize_with(Method::GET, Scope::OpenId.as_str(), None, &phr) - .await; - let transaction = parameter(&location(&response), "transaction"); - let resume = format!( - "{}?transaction={transaction}", - routes::oidc::AUTHORIZE_RESUME - ); - - flow.sign_in_again(AuthenticationMethod::Federation).await; - let response = flow.request(Method::GET, &resume, &[], None).await; - assert_eq!(location(&response).path(), routes::page::LOGIN, "social"); - - let database = flow.app.database.clone(); - let passkey = PasskeyId::new(); - database - .passkeys() - .insert(&InsertPasskey { - id: passkey, - credential_id: passkey.as_uuid().as_bytes().to_vec(), - user_id: flow.user_id, - credential: json!({}), - friendly_name: "Recovered".into(), - }) - .await - .expect("passkey"); - let recovery = RecoveryId::new(); - database - .recoveries() - .insert(&InsertRecovery { - id: recovery, - user_id: flow.user_id, - secret_digest: &recovery.as_uuid().as_bytes().repeat(2), - expires_at: Utc::now() + chrono::Duration::hours(1), - }) - .await - .expect("recovery"); - let probation = crate::recovery::PROBATION; - let mut recoveries = database.recoveries(); - let completed = recoveries - .complete(flow.user_id, recovery, passkey, probation) - .await; - assert!(completed.expect("complete")); - let stored = recoveries - .find(recovery) - .await - .expect("lookup") - .expect("recovery"); - let credential = Credential::Probation(ProbationPasskey::of(&stored).expect("probation")); - let user_id = flow.user_id; - let probation_sign_in = || async { - let mut tx = database.begin().await.expect("transaction"); - let session = Session::create(&mut tx, RequestContext::TEST, user_id, credential).await; - tx.commit().await.expect("commit"); - let cookie = BrowserCookie::Session.as_str(); - format!("{cookie}={}", session.expect("session").encoded()) - }; - let before_the_request = probation_sign_in().await; - let response = flow - .authorize_with(Method::GET, Scope::OpenId.as_str(), None, &phr) - .await; - let transaction = parameter(&location(&response), "transaction"); - let resume = format!( - "{}?transaction={transaction}", - routes::oidc::AUTHORIZE_RESUME - ); - flow.cookie = before_the_request; - let response = flow.request(Method::GET, &resume, &[], None).await; - assert_eq!(location(&response).path(), routes::page::LOGIN, "not fresh"); - - flow.cookie = probation_sign_in().await; - let response = flow.request(Method::GET, &resume, &[], None).await; - assert_eq!( - parameter(&flow.client_redirect(&response), "error"), - OAuthCode::UnmetAuthenticationRequirements.as_str() - ); - // Signing in again for a request without a target is enough. - let response = flow.authorize(Scope::OpenId.as_str(), Some("login")).await; - let transaction = parameter(&location(&response), "transaction"); - let resume = format!( - "{}?transaction={transaction}", - routes::oidc::AUTHORIZE_RESUME - ); - flow.cookie = probation_sign_in().await; - let response = flow.request(Method::GET, &resume, &[], None).await; - let code = parameter(&flow.client_redirect(&response), "code"); - assert!(!code.is_empty(), "no target, no refusal"); -} - -/// Checks protocol POST parity and existing OAuth error and challenge formats. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn post_protocol_endpoints_and_error_contracts() { - let flow = Flow::new(false, true).await; - for (name, value, expected) in [ - ( - "id_token_hint", - "invalid", - OAuthCode::InvalidRequest.as_str(), - ), - ( - "request", - "ignored.jwt", - OAuthCode::RequestNotSupported.as_str(), - ), - ( - "response_mode", - "form_post", - OAuthCode::InvalidRequest.as_str(), - ), - ] { - let response = flow - .authorize_with( - Method::GET, - Scope::OpenId.as_str(), - Some(Prompt::None.as_str()), - &[(name, value)], - ) - .await; - assert_eq!( - parameter(&flow.client_redirect(&response), "error"), - expected - ); - } - let discovery = Flow::json( - flow.request(Method::GET, "/.well-known/openid-configuration", &[], None) - .await, - ) - .await; - assert_eq!(discovery["request_parameter_supported"], false); - assert_eq!(discovery["request_uri_parameter_supported"], false); - assert_eq!( - discovery["pushed_authorization_request_endpoint"], - format!("{}{}", flow.app.issuer, routes::oidc::PAR) - ); - // Only pushed requests have a request_uri, and no redirect URI is known for it. - let response = flow - .claim( - flow.client.id.as_str(), - "https://example.com/request.jwt", - &[], - ) - .await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert_eq!( - Flow::json(response).await["error"], - OAuthCode::InvalidRequestUri.as_str() - ); - assert_eq!( - discovery["authorization_response_iss_parameter_supported"], - true - ); - let response = flow - .authorize_with(Method::POST, PROFILE_SCOPES, None, &[]) - .await; - let code = parameter(&flow.client_redirect(&response), "code"); - let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await; - let bearer = format!( - "{} {}", - AuthScheme::Bearer.as_str(), - tokens["access_token"].as_str().expect("access token") - ); - let response = flow - .request(Method::POST, "/oidc/userinfo", &[], Some(&bearer)) - .await; - assert_eq!(response.status(), StatusCode::OK); - let userinfo = Flow::json(response).await; - assert_eq!(userinfo["sub"], json!(flow.user_id)); - assert!(userinfo["profile_version"].is_number()); - let response = flow - .request(Method::POST, "/oidc/userinfo", &[], None) - .await; - assert_eq!(response.status(), StatusCode::UNAUTHORIZED); - assert_eq!( - response.headers()[header::WWW_AUTHENTICATE], - "Bearer error=\"invalid_token\"" - ); - let response = flow - .request( - Method::POST, - "/oauth/token", - &[("client_id", flow.client.id.as_str())], - None, - ) - .await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert_eq!( - Flow::json(response).await["error"], - OAuthCode::InvalidRequest.as_str() - ); -} - -/// A pushed request is validated like a browser one, but answers in JSON. Its -/// `request_uri` is not a transaction: only its client can claim it, once, and the -/// query cannot override what was pushed, `prompt` included. A client required to -/// push cannot send plain requests. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn pushed_requests_are_one_time_client_bound_and_authoritative() { - let mut flow = Flow::new(true, false).await; - let id = flow.client.id.to_string(); - let response = flow.push(Scope::OpenId.as_str(), None, None).await; - assert_eq!(response.status(), StatusCode::UNAUTHORIZED); - let response = flow - .push("openid unregistered", None, flow.basic.as_deref()) - .await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert_eq!( - Flow::json(response).await["error"], - OAuthCode::InvalidScope.as_str() - ); - let request_uri = flow - .pushed(Scope::OpenId.as_str(), Some(Prompt::None.as_str())) - .await; - assert_eq!( - parameter( - &flow.client_redirect(&flow.claim(&id, &request_uri, &[]).await), - "error" - ), - OAuthCode::ConsentRequired.as_str() - ); - let request_uri = flow.pushed(Scope::OpenId.as_str(), None).await; - let transaction = request_uri - .strip_prefix("urn:ietf:params:oauth:request_uri:") - .expect("RFC 9126 request_uri"); - let response = flow - .request( - Method::GET, - &format!("/oauth/authorize/resume?transaction={transaction}"), - &[], - None, - ) - .await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - let rejected = async |client_id: &str, request_uri: &str| { - let response = flow.claim(client_id, request_uri, &[]).await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert_eq!( - Flow::json(response).await["error"], - OAuthCode::InvalidRequestUri.as_str() - ); - }; - let other = crate::tests::registration(ClientKind::Public, "https://other.example"); - crate::tests::register(&flow.app.database, &other) - .await - .expect("register another client"); - rejected(other.id.as_str(), &request_uri).await; - rejected(&id, "urn:ietf:params:oauth:request_uri:unknown").await; - rejected(&id, "https://client.example/request.jwt").await; - let response = flow - .claim( - &id, - &request_uri, - &[ - ("scope", EMAIL_SCOPES), - ("state", "forged-state"), - ("redirect_uri", "https://evil.example/callback"), - ("prompt", Prompt::None.as_str()), - ], - ) - .await; - let redirect = flow.consent(response).await; - assert_eq!( - redirect.origin(), - Url::parse(flow.client.redirect_uris[0].as_str()) - .expect("callback") - .origin() - ); - assert_eq!(parameter(&redirect, "state"), "test-state"); - let code = parameter(&redirect, "code"); - let response = flow - .exchange(&code, Flow::verifier(), flow.basic.as_deref()) - .await; - let (tokens, claims) = flow.id_token(response).await; - assert_eq!(tokens["scope"], Scope::OpenId.as_str()); - assert_eq!(claims["nonce"], "test-nonce"); - rejected(&id, &request_uri).await; - flow.client.require_pushed_authorization_requests = true; - let client = flow.client.clone(); - crate::tests::replace(&flow.app.database, &client) - .await - .expect("require pushed requests"); - assert_eq!( - parameter( - &flow.client_redirect(&flow.authorize(Scope::OpenId.as_str(), None).await), - "error" - ), - OAuthCode::InvalidRequest.as_str() - ); - let request_uri = flow.pushed(Scope::OpenId.as_str(), None).await; - // The user consented above, so the claim returns a code at once. - let response = flow.claim(&id, &request_uri, &[]).await; - parameter(&flow.client_redirect(&response), "code"); -} - -/// A pushed `prompt=login` needs a sign-in after the browser claims the request: -/// one between the push and the claim is not fresh. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn pushed_requests_count_sign_in_freshness_from_the_claim() { - let mut flow = Flow::new(true, false).await; - let request_uri = flow - .pushed(Scope::OpenId.as_str(), Some(Prompt::Login.as_str())) - .await; - flow.sign_in_again(AuthenticationMethod::Passkey).await; - let response = flow.claim(flow.client.id.as_str(), &request_uri, &[]).await; - let location = location(&response); - assert_eq!(location.path(), "/login"); - let transaction = parameter(&location, "transaction"); - flow.sign_in_again(AuthenticationMethod::Passkey).await; - let response = flow - .request( - Method::GET, - &format!("/oauth/authorize/resume?transaction={transaction}"), - &[], - None, - ) - .await; - parameter(&flow.consent(response).await, "code"); -} - -/// Checks redirect equality, PKCE rejection and opaque-token bounds. -#[test] -fn exact_redirect_and_pkce_and_refresh_bounds() { - let registered = ["https://a.example/cb".to_owned()]; - assert!(!registered.contains(&"https://a.example/cb.evil".to_owned())); - assert!(piquel_crypto::Pkce::verify("short", "x").is_err()); - let huge = format!( - "{}_{}.{:0200}", - TokenPrefix::RefreshToken, - TokenId::new(), - "x" - ); - assert!(OpaqueToken::parse(TokenPrefix::RefreshToken, &huge).is_err()); -} - -/// Checks case-insensitive scheme matching without changing credential bytes. -#[test] -fn authentication_schemes_are_case_insensitive() { - assert_eq!(AuthScheme::Bearer.credentials("bEaReR a.B"), Some("a.B")); - assert_eq!(AuthScheme::Basic.credentials("BASIC Zm9v"), Some("Zm9v")); - assert_eq!(AuthScheme::Basic.credentials("Bearer Zm9v"), None); - assert_eq!(AuthScheme::Bearer.credentials("Bearer"), None); -} - -/// Existing scope strings exercise the HTTP wire contract independently of enum serialization. -const EMAIL_REFRESH_SCOPES: &str = "openid email offline_access"; -/// Identity and session-bounded refresh requested together. -const REFRESH_SCOPES: &str = "openid offline_access"; -/// Public-profile scope fixture. -const PROFILE_SCOPES: &str = "openid profile"; -/// Profile claims with a refresh token. -const PROFILE_REFRESH_SCOPES: &str = "openid profile offline_access"; -/// Verified-email scope fixture. -const EMAIL_SCOPES: &str = "openid email"; -/// Unregistered extension scope fixture used to check rejection. -const UNGRANTED_SCOPES: &str = "openid admin"; - -/// Checks deduplication, lexical ordering and preservation of registered extension scopes. -#[test] -fn scope_sets_preserve_existing_wire_semantics() { - let scopes = Scopes::parse("profile openid profile custom.read email").expect("scope set"); - assert!(scopes.contains(Scope::OpenId)); - assert_eq!( - scopes.wire().to_string(), - "custom.read email openid profile" - ); - let stored = scopes.clone().into_stored(); - assert!(scopes.allowed_by(&stored)); - assert!(!scopes.allowed_by(&[Scope::OpenId.as_str().into()])); - assert_eq!(Scopes::from_stored(&stored), scopes); - assert!(Scopes::parse(" ").is_err()); - let too_many = (0..=MAX_SCOPES) - .map(|index| format!("scope{index}")) - .collect::>() - .join(" "); - assert!(Scopes::parse(&too_many).is_err()); -} - -/// Checks purpose binding and exact opaque envelope/secret round trips. -#[test] -fn opaque_tokens_preserve_envelopes_and_reject_wrong_purpose() { - for prefix in TokenPrefix::ALL { - let original = OpaqueToken::new(prefix).expect("random token"); - let encoded = original.encoded(); - let parsed = OpaqueToken::parse(prefix, &encoded).expect("parse envelope"); - assert_eq!(parsed.id, original.id); - assert_eq!(parsed.secret.as_bytes(), original.secret.as_bytes()); - assert_eq!(parsed.encoded(), encoded); - for other in TokenPrefix::ALL { - if prefix != other { - assert!(OpaqueToken::parse(other, &encoded).is_err()); - } - } - } -} - -/// Checks that protocol failures retain both internal and rejected-input source chains. -#[tokio::test] -async fn oauth_failures_preserve_sources_and_statuses() { - use axum::response::IntoResponse; - use std::error::Error; - let error = OAuthError::from(piquel_repository::DatabaseError::Operation(Box::new( - std::io::Error::other("internal diagnostic"), - ))); - assert_eq!( - error.source().expect("internal source").to_string(), - "internal diagnostic" - ); - assert_eq!( - error.into_response().status(), - StatusCode::INTERNAL_SERVER_ERROR - ); - let error = OAuthCode::InvalidGrant.reject_with( - "code is \"malformed\" \u{2014} retry", - piquel_crypto::CryptoError::SecretLength, - ); - assert!(error.source().is_some()); - let response = error.into_response(); - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - // The description reaches the client, restricted to the RFC 6749 character set. - assert_eq!( - Flow::json(response).await, - serde_json::json!({ - "error": "invalid_grant", - "error_description": "code is 'malformed' ? retry", - }) - ); -} - -/// Existing approve form spelling, independent of the JSON-only consent enum. -const APPROVE_CONSENT: &str = "approve"; - -/// The Rust SDK signs in, validates, refreshes, revokes and logs out against the real -/// provider over HTTPS, and rejects a mixed-up callback before any code exchange. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -#[expect( - clippy::too_many_lines, - reason = "The scenario follows one login from authorization through logout." -)] -async fn sdk_login_client_runs_against_the_provider() { - use piquel_auth::{ - AuthorizeRequest, CallbackParams, ClientConfig, Credentials, LoginError, OAuthError, - Resource, Scopes, Subject, - }; - let tcp = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind provider"); - let port = tcp.local_addr().expect("provider address").port(); - let origin = format!("https://localhost:{port}"); - let flow = Flow::at(&origin, true, false).await; - let certificate = TlsListener::serve(tcp, flow.app.clone().routes()); - let http = reqwest::Client::builder() - .add_root_certificate(certificate) - .redirect(reqwest::redirect::Policy::none()) - .build() - .expect("HTTP client"); - let issuer = piquel_auth::Issuer::builder() - .http_client(http) - .discover(&origin) - .await - .expect("discover the provider"); - let client = issuer.client(ClientConfig { - client_id: flow.client.id.clone(), - credentials: Credentials::Secret(flow.secret.clone().expect("confidential").into()), - redirect_uri: flow.client.redirect_uris[0] - .as_str() - .parse() - .expect("callback"), - }); - let (url, pending) = client - .authorize(&AuthorizeRequest { - scopes: "profile email offline_access".parse().expect("scopes"), - ..AuthorizeRequest::default() - }) - .await - .expect("authorization URL"); - - let mixed_up = CallbackParams { - code: Some("pac_v1_unused".into()), - state: Some(pending.state().into()), - iss: Some("https://evil.example".into()), - ..CallbackParams::default() - }; - assert!(matches!( - client.complete(pending.clone(), &mixed_up).await, - Err(LoginError::IssuerMismatch { .. }) - )); - - let browser = flow - .request( - Method::GET, - &format!("{}?{}", url.path(), url.query().expect("query")), - &[], - None, - ) - .await; - let callback = flow.consent(browser).await; - let parameters: CallbackParams = serde_json::from_value(Value::Object( - callback - .query_pairs() - .map(|(name, value)| (name.into_owned(), Value::String(value.into_owned()))) - .collect(), - )) - .expect("callback parameters"); - let tokens = client - .complete(pending, ¶meters) - .await - .expect("complete the login"); - let id_token = tokens.id_token.as_ref().expect("ID token"); - assert_eq!(id_token.user_id().expect("account"), flow.user_id); - - let access = issuer - .resource(Resource::new(flow.client.id.as_str()).expect("resource")) - .validate::(tokens.access_token.expose()) - .await - .expect("valid access token"); - assert_eq!(access.subject, Subject::User(flow.user_id)); - assert!(access.scopes.contains(Scope::OfflineAccess.as_str())); - - let user = client - .userinfo(&tokens.access_token) - .await - .expect("UserInfo"); - assert_eq!(user.sub, flow.user_id.to_string()); - assert!(user.profile.email.is_some()); - - let first = tokens.refresh_token.expect("refresh token"); - let rotated = client - .refresh(&first) - .await - .expect("refresh") - .refresh_token - .expect("rotated refresh token"); - assert_ne!(rotated.expose(), first.expose()); - client.revoke(&rotated).await.expect("revoke"); - assert!(matches!( - client.refresh(&rotated).await, - Err(OAuthError::Rejected { response, .. }) - if response.error == OAuthCode::InvalidGrant - )); - - let post_logout: Url = flow.client.post_logout_uris[0] - .as_str() - .parse() - .expect("post-logout URI"); - let logout = client.logout_url(id_token, Some(&post_logout)); - let confirmation = location( - &flow - .request( - Method::GET, - &format!("{}?{}", logout.path(), logout.query().expect("query")), - &[], - None, - ) - .await, - ); - assert_eq!(confirmation.path(), routes::page::LOGOUT); - let fields: Vec<(String, String)> = confirmation.query_pairs().into_owned().collect(); - let fields: Vec<_> = fields - .iter() - .map(|(name, value)| (name.as_str(), value.as_str())) - .collect(); - let confirmed = flow - .request(Method::POST, routes::page::LOGOUT, &fields, None) - .await; - assert_eq!(location(&confirmed), post_logout); -} - -/// A clock the SDK scenarios move by hand, to reach access token expiry. -#[derive(Clone)] -struct ManualClock(Arc>>); - -impl ManualClock { - /// Moves the clock forward. - fn advance(&self, seconds: i64) { - *self.0.lock().expect("clock") += chrono::TimeDelta::seconds(seconds); - } -} - -impl piquel_auth::Clock for ManualClock { - fn now(&self) -> chrono::DateTime { - *self.0.lock().expect("clock") - } -} - -/// An app using the SDK's login routes against the provider, served in-process. -struct LoginApp { - /// The provider scenario. - flow: Flow, - /// The app's routes; `/` shows the session's access token. - app: Router, - /// The SDK's clock. - clock: ManualClock, -} - -impl LoginApp { - /// Serves the provider over TLS and builds the app. - async fn start() -> Self { - use piquel_auth::{ - ClientConfig, Credentials, Resource, - axum::{BearerLayer, LoginRoutes, MemoryBackend, RequireAuthentication, SignedIn}, - protocol::challenge::BearerChallenge, - }; - let tcp = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind provider"); - let port = tcp.local_addr().expect("provider address").port(); - let origin = format!("https://localhost:{port}"); - let flow = Flow::at(&origin, true, false).await; - let certificate = TlsListener::serve(tcp, flow.app.clone().routes()); - let http = reqwest::Client::builder() - .add_root_certificate(certificate) - .redirect(reqwest::redirect::Policy::none()) - .build() - .expect("HTTP client"); - let clock = ManualClock(Arc::new(std::sync::Mutex::new(Utc::now()))); - let issuer = piquel_auth::Issuer::builder() - .http_client(http) - .clock(clock.clone()) - .discover(&origin) - .await - .expect("discover the provider"); - let client = issuer.client(ClientConfig { - client_id: flow.client.id.clone(), - credentials: Credentials::Secret(flow.secret.clone().expect("confidential").into()), - redirect_uri: flow.client.redirect_uris[0] - .as_str() - .parse() - .expect("callback"), - }); - // An API the app calls with the user's token: `/settings` needs a recent - // passkey, and `/stubborn` asks for a step-up, naming nothing, whatever the - // token holds. - let api = Router::new() - .route( - "/settings", - axum::routing::get(|_: RequireAuthentication| async { "settings" }), - ) - .route( - "/stubborn", - axum::routing::get(|| async { - let challenge = BearerChallenge::step_up(StepUpRequirement::default()); - ( - StatusCode::UNAUTHORIZED, - [(header::WWW_AUTHENTICATE, challenge.to_string())], - ) - }), - ) - .layer(BearerLayer::new(issuer.resource( - Resource::new(flow.client.id.as_str()).expect("resource"), - ))); - let call_api = move |path: &'static str| { - let api = api.clone(); - move |user: SignedIn| async move { - let request = Request::get(path) - .header( - header::AUTHORIZATION, - format!("Bearer {}", user.login().access_token.expose()), - ) - .body(Body::empty()) - .expect("API request"); - let answer = api.oneshot(request).await.expect("API response"); - let challenge = answer - .headers() - .get(header::WWW_AUTHENTICATE) - .and_then(|value| value.to_str().ok()) - .and_then(|value| value.parse::().ok()); - match challenge { - Some(challenge) => user.step_up(challenge.step_up).into_response(), - None => answer, - } - } - }; - let auth = LoginRoutes::new(client, MemoryBackend::default()) - .scopes("profile offline_access".parse().expect("scopes")) - .after_logout( - flow.client.post_logout_uris[0] - .as_str() - .parse() - .expect("logout URI"), - ); - let app = Router::new() - .route( - "/notes", - axum::routing::get(|user: SignedIn| async move { - user.login().access_token.expose().to_owned() - }), - ) - .route("/settings", axum::routing::get(call_api("/settings"))) - .route("/stubborn", axum::routing::get(call_api("/stubborn"))) - .nest("/auth", auth.router()) - .layer(auth.layer()); - Self { flow, app, clock } - } - - /// Sends a request to the app with an optional cookie. Posts carry the app's - /// `Origin`, as a browser on its pages sends. - async fn send(&self, method: Method, uri: &str, cookie: Option<&str>) -> Response { - let mut request = Request::builder().method(method.clone()).uri(uri); - if method == Method::POST { - let callback = - Url::parse(self.flow.client.redirect_uris[0].as_str()).expect("callback"); - request = request.header(header::ORIGIN, callback.origin().ascii_serialization()); - } - if let Some(cookie) = cookie { - request = request.header(header::COOKIE, cookie); - } - self.app - .clone() - .oneshot(request.body(Body::empty()).expect("request")) - .await - .expect("response") - } - - /// The `Set-Cookie` values of a response. - fn cookies(response: &Response) -> Vec { - response - .headers() - .get_all(header::SET_COOKIE) - .iter() - .map(|value| value.to_str().expect("cookie").to_owned()) - .collect() - } - - /// The `name=value` pair of the cookie `name` that `response` sets. - fn cookie(response: &Response, name: &str) -> String { - Self::cookies(response) - .into_iter() - .find(|cookie| cookie.starts_with(&format!("{name}="))) - .and_then(|cookie| cookie.split(';').next().map(str::to_owned)) - .expect("cookie set") - } - - /// The relative `Location` of an app redirect. - fn location(response: &Response) -> String { - assert_eq!(response.status(), StatusCode::SEE_OTHER); - response.headers()[header::LOCATION] - .to_str() - .expect("location") - .to_owned() - } - - /// Starts login at `login` (the app's login path and query): the pending login's - /// cookie, and the provider's authorization URL. - async fn start_login(&self, login: &str, session: Option<&str>) -> (String, Url) { - let start = self.send(Method::GET, login, session).await; - for cookie in Self::cookies(&start) { - assert!( - cookie.ends_with("; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=600"), - "{cookie}" - ); - } - ( - Self::cookie(&start, "__Host-piquel-login"), - Url::parse(&Self::location(&start)).expect("authorization URL"), - ) - } - - /// The provider's answer to the browser following `authorize`. - async fn authorize(&self, authorize: &Url) -> Response { - self.flow - .request( - Method::GET, - &format!("{}?{}", authorize.path(), authorize.query().expect("query")), - &[], - None, - ) - .await - } - - /// Consents at the provider and returns the app callback's response. - async fn finish_login( - &self, - browser: Response, - pending: String, - session: Option<&str>, - ) -> Response { - let callback = self.flow.consent(browser).await; - let cookies = match session { - Some(session) => format!("{pending}; {session}"), - None => pending, - }; - self.send( - Method::GET, - &format!("/auth/callback?{}", callback.query().expect("query")), - Some(&cookies), - ) - .await - } - - /// Starts login at `login`, signs in at the provider, and returns the callback's - /// response. - async fn sign_in(&self, login: &str, session: Option<&str>) -> Response { - let (pending, authorize) = self.start_login(login, session).await; - let browser = self.authorize(&authorize).await; - self.finish_login(browser, pending, session).await - } -} - -/// The SDK's login routes sign a user in through the provider, keep tokens in the -/// store, refresh them there, rotate the session on every sign-in, refuse open -/// redirects, and log out through the provider. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn sdk_login_routes_run_against_the_provider() { - let app = LoginApp::start().await; - let page = app.send(Method::GET, "/notes?page=2", None).await; - assert_eq!( - LoginApp::location(&page), - "/auth/login?return_to=%2Fnotes%3Fpage%3D2" - ); - - let callback = app.sign_in(&LoginApp::location(&page), None).await; - assert_eq!(LoginApp::location(&callback), "/notes?page=2"); - let cookies = LoginApp::cookies(&callback); - assert!( - cookies - .iter() - .any(|cookie| cookie.starts_with("__Host-piquel-session=") - && cookie.ends_with("; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=43200")) - ); - assert!(cookies.iter().any(|cookie| cookie - == "__Host-piquel-login=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0")); - let first = LoginApp::cookie(&callback, "__Host-piquel-session"); - let shown = app.send(Method::GET, "/notes", Some(&first)).await; - assert_eq!(shown.status(), StatusCode::OK); - let access = Flow::text(shown).await; - - // A second sign-in rotates the session and ends the first one. - let callback = app.sign_in("/auth/login", Some(&first)).await; - assert_eq!(LoginApp::location(&callback), "/"); - let second = LoginApp::cookie(&callback, "__Host-piquel-session"); - assert_ne!(first, second); - let stale = app.send(Method::GET, "/notes", Some(&first)).await; - assert_eq!(LoginApp::location(&stale), "/auth/login?return_to=%2Fnotes"); - - // Near expiry, the access token is refreshed in the store. - app.clock.advance(290); - let refreshed = app.send(Method::GET, "/notes", Some(&second)).await; - assert_eq!(refreshed.status(), StatusCode::OK); - assert_ne!(Flow::text(refreshed).await, access); - - // Open redirects are refused: login falls back to the home page. - let callback = app - .sign_in("/auth/login?return_to=%2F%2Fevil.example", None) - .await; - assert_eq!(LoginApp::location(&callback), "/"); - - let logout = app.send(Method::POST, "/auth/logout", Some(&second)).await; - let destination = Url::parse(&LoginApp::location(&logout)).expect("logout URL"); - assert_eq!(destination.path(), "/oidc/logout"); - assert_eq!( - parameter(&destination, "post_logout_redirect_uri"), - app.flow.client.post_logout_uris[0].as_str() - ); - assert!( - LoginApp::cookies(&logout) - .iter() - .any(|cookie| cookie.starts_with("__Host-piquel-session=;")) - ); - let after = app.send(Method::GET, "/notes", Some(&second)).await; - assert_eq!(after.status(), StatusCode::SEE_OTHER); -} - -/// A client required to push its authorization requests signs in through the SDK's -/// login routes, which push them, so the browser carries only the `request_uri`. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn sdk_login_routes_push_for_clients_that_must() { - let mut app = LoginApp::start().await; - app.flow.client.require_pushed_authorization_requests = true; - crate::tests::replace(&app.flow.app.database, &app.flow.client) - .await - .expect("require pushed requests"); - let (pending, authorize) = app.start_login("/auth/login", None).await; - let names: Vec<_> = authorize.query_pairs().map(|(name, _)| name).collect(); - assert_eq!(names, ["client_id", "request_uri"]); - let browser = app.authorize(&authorize).await; - let callback = app.finish_login(browser, pending, None).await; - assert_eq!(LoginApp::location(&callback), "/"); -} - -/// A passkey confirmation within five minutes. -struct RecentPasskey; - -impl piquel_auth::AuthenticationPolicy for RecentPasskey { - const REQUIREMENT: StepUpRequirement = StepUpRequirement::passkey_within(300); -} - -/// An app whose API needs a recent passkey sends a socially signed-in user through -/// the provider with the API's `acr_values` and `max_age`, then back to the page, -/// which now works. An API that still refuses after one step-up gets an error, not -/// another sign-in. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn sdk_step_up_runs_against_the_provider() { - let mut app = LoginApp::start().await; - app.flow - .sign_in_again(AuthenticationMethod::Federation) - .await; - let callback = app.sign_in("/auth/login", None).await; - let first = LoginApp::cookie(&callback, "__Host-piquel-session"); - - let page = app.send(Method::GET, "/settings", Some(&first)).await; - let login = LoginApp::location(&page); - assert_eq!( - login, - "/auth/login?return_to=%2Fsettings&acr_values=phr&max_age=300&step_up=true" - ); - // The pushed request carries `acr_values` and `max_age`: the social session is - // too weak for them, so the provider asks for a passkey. - let (pending, authorize) = app.start_login(&login, Some(&first)).await; - let prompt = app.authorize(&authorize).await; - assert_eq!(location(&prompt).path(), routes::page::LOGIN); - - let access = app.send(Method::GET, "/notes", Some(&first)).await; - let access = Flow::text(access).await; - let payload = access.split('.').nth(1).expect("JWT payload"); - let claims: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(payload) - .expect("base64url payload"), - ) - .expect("claims"); - let session = claims["sid"] - .as_str() - .expect("sid") - .parse() - .expect("session ID"); - app.flow - .app - .database - .sessions() - .confirm_passkey(session, PasskeyId::new(), Utc::now()) - .await - .expect("passkey confirmation"); - // The pushed request was claimed, so the browser resumes its transaction. - let transaction = parameter(&location(&prompt), "transaction"); - let browser = app - .flow - .request( - Method::GET, - &format!( - "{}?transaction={transaction}", - routes::oidc::AUTHORIZE_RESUME - ), - &[], - None, - ) - .await; - let callback = app.finish_login(browser, pending, Some(&first)).await; - assert_eq!(LoginApp::location(&callback), "/settings"); - let second = LoginApp::cookie(&callback, "__Host-piquel-session"); - let retry = LoginApp::cookie(&callback, "__Host-piquel-step-up"); - - let page = app - .send( - Method::GET, - "/settings", - Some(&format!("{second}; {retry}")), - ) - .await; - assert!( - LoginApp::cookies(&page) - .iter() - .any(|cookie| cookie.starts_with("__Host-piquel-step-up=;")), - "the retry marker is used up" - ); - assert_eq!(page.status(), StatusCode::OK); - assert_eq!(Flow::text(page).await, "settings"); - - // An API that refuses whatever the token holds gets one step-up sign-in, then an - // error on the retry instead of another redirect, even when its challenge names - // no requirement. - let page = app.send(Method::GET, "/stubborn", Some(&second)).await; - let login = LoginApp::location(&page); - assert_eq!(login, "/auth/login?return_to=%2Fstubborn&step_up=true"); - let callback = app.sign_in(&login, Some(&second)).await; - assert_eq!(LoginApp::location(&callback), "/stubborn"); - let third = LoginApp::cookie(&callback, "__Host-piquel-session"); - let retry = LoginApp::cookie(&callback, "__Host-piquel-step-up"); - let cookies = format!("{third}; {retry}"); - // Only the returning `GET` is the retry. - let other = app.send(Method::POST, "/stubborn", Some(&cookies)).await; - assert_eq!(LoginApp::cookies(&other), Vec::::new()); - let refused = app.send(Method::GET, "/stubborn", Some(&cookies)).await; - assert_eq!(refused.status(), StatusCode::FORBIDDEN); - - // An ordinary sign-in drops a marker its return never used. - let page = app.send(Method::GET, "/stubborn", Some(&third)).await; - let callback = app.sign_in(&LoginApp::location(&page), Some(&third)).await; - let fourth = LoginApp::cookie(&callback, "__Host-piquel-session"); - let unused = LoginApp::cookie(&callback, "__Host-piquel-step-up"); - let callback = app.sign_in("/auth/login", Some(&fourth)).await; - assert!( - LoginApp::cookies(&callback) - .iter() - .any(|cookie| cookie.starts_with("__Host-piquel-step-up=;")), - "the unused marker {unused} is dropped" - ); -} diff --git a/apps/auth-service/src/oidc/tests/app_removal.rs b/apps/auth-service/src/oidc/tests/app_removal.rs new file mode 100644 index 000000000..f37081c38 --- /dev/null +++ b/apps/auth-service/src/oidc/tests/app_removal.rs @@ -0,0 +1,143 @@ +//! Removing an app from an account ends its grants, codes and consent. + +use super::*; + +/// An administrator removes an account's app with the owner's own operation: its +/// refresh grant ends, and the removal is recorded as the administrator's, with +/// the reason they gave. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn an_administrator_removes_an_app_with_a_reason() { + let flow = Flow::new(false, false).await; + let code = flow.code(REFRESH_SCOPES).await; + let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await; + let refresh = tokens["refresh_token"].as_str().expect("refresh token"); + let harness = crate::admin::tests::Harness { + database: flow.app.database.clone(), + }; + let admin = harness.admin().await; + let reason = "Reported as an impersonating app"; + let subject = crate::account::Subject::operator( + flow.user_id, + crate::admin::tests::operator(admin, Utc::now()), + crate::Reason::parse(reason.into()).expect("reason"), + ); + crate::account::AccountService::new(flow.app.database.clone()) + .remove_app(&subject, &flow.client.id) + .await + .expect("remove"); + Flow::assert_invalid_grant(flow.refresh(refresh).await).await; + let history = flow + .app + .database + .events() + .history_for_user(flow.user_id, 100) + .await + .expect("history"); + let removed = DomainEvent::ConsentRevoked { + client_id: flow.client.id.clone(), + }; + let stored = history + .iter() + .find(|stored| stored.event.known() == Some(&removed)) + .expect("recorded"); + let actor = Actor::Admin { + user_id: admin.user_id, + session_id: admin.session_id, + }; + assert_eq!(stored.actor, actor); + assert_eq!(stored.reason.as_deref(), Some(reason)); +} + +/// Removing an app from the account's settings ends its refresh grant and its +/// outstanding code, and forgets the consent, so it asks again. It is recorded +/// once, and listed no more. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn removing_an_app_ends_its_access() { + let flow = Flow::new(false, false).await; + let code = flow.code(REFRESH_SCOPES).await; + let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await; + let refresh = tokens["refresh_token"].as_str().expect("refresh token"); + let outstanding = flow.code(REFRESH_SCOPES).await; + let service = crate::account::AccountService::new(flow.app.database.clone()); + let owner = flow.owner().await; + let viewer = crate::account::Viewer::from(&owner); + let apps = service.apps(&viewer).await.expect("apps"); + assert_eq!(apps.len(), 1); + assert_eq!(apps[0].client_id, flow.client.id); + assert_eq!(apps[0].scopes, [Scope::OpenId.as_str()]); + assert!(apps[0].offline && !apps[0].first_party); + + service + .remove_app(&crate::account::Subject::from(owner), &flow.client.id) + .await + .expect("remove"); + assert!(service.apps(&viewer).await.expect("apps").is_empty()); + assert_eq!( + flow.events().await[0], + DomainEvent::ConsentRevoked { + client_id: flow.client.id.clone() + } + ); + Flow::assert_invalid_grant(flow.refresh(refresh).await).await; + Flow::assert_invalid_grant(flow.exchange(&outstanding, Flow::verifier(), None).await).await; + let response = flow + .authorize(REFRESH_SCOPES, Some(Prompt::None.as_str())) + .await; + assert_eq!( + parameter(&flow.client_redirect(&response), "error"), + OAuthCode::ConsentRequired.as_str() + ); +} + +/// A code issued before the user withdrew consent is not exchanged after it, +/// even when it is not expired, as one an authorization issued just as a removal +/// withdrew the consent is not. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn withdrawn_consent_stops_an_issued_code() { + let flow = Flow::new(false, false).await; + let code = flow.code(Scope::OpenId.as_str()).await; + flow.app + .database + .oidc() + .revoke_consents(flow.user_id, Some(&flow.client.id)) + .await + .expect("withdraw"); + Flow::assert_invalid_grant(flow.exchange(&code, Flow::verifier(), None).await).await; +} + +/// An exchange that starts while an app's removal holds the account waits for it, +/// before taking its code, so even a first-party app, which needs no consent, +/// finds its code expired rather than creating a refresh grant after the removal. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn an_exchange_waits_for_a_removal_and_finds_its_code_expired() { + let flow = Flow::new(false, true).await; + let code = flow.code(REFRESH_SCOPES).await; + let database = flow.app.database.clone(); + let mut removal = database.begin().await.expect("transaction"); + removal + .users() + .find_active_by_id_for_update(flow.user_id) + .await + .expect("lock") + .expect("user"); + let exchanging = flow.clone(); + let exchange = tokio::spawn(async move { + let response = exchanging.exchange(&code, Flow::verifier(), None).await; + (response.status(), Flow::json(response).await) + }); + until_blocked(&mut removal, 1).await; + removal + .oidc() + .expire_codes(flow.user_id, &flow.client.id) + .await + .expect("expire"); + removal.commit().await.expect("commit"); + + let (status, body) = exchange.await.expect("exchange"); + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(body["error"], OAuthCode::InvalidGrant.as_str()); +} diff --git a/apps/auth-service/src/oidc/tests/authorization.rs b/apps/auth-service/src/oidc/tests/authorization.rs new file mode 100644 index 000000000..b31eb0384 --- /dev/null +++ b/apps/auth-service/src/oidc/tests/authorization.rs @@ -0,0 +1,230 @@ +//! Authorization requests: consent, PKCE, scoped claims and account hints. + +use super::*; +use piquel_repository::SessionScope; + +/// Checks public-client consent, PKCE, scoped claims and one-use authorization codes. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn public_consent_pkce_claim_scoping_and_replay() { + let flow = Flow::new(false, false).await; + let response = flow + .authorize(Scope::OpenId.as_str(), Some(Prompt::None.as_str())) + .await; + assert_eq!( + parameter(&flow.client_redirect(&response), "error"), + OAuthCode::ConsentRequired.as_str() + ); + let code = flow.code(Scope::OpenId.as_str()).await; + assert_eq!( + flow.exchange(&code, "wrong", None).await.status(), + StatusCode::BAD_REQUEST + ); + let response = flow.exchange(&code, Flow::verifier(), None).await; + assert_eq!(response.status(), StatusCode::OK); + let tokens = Flow::json(response).await; + let claims: IdTokenClaims = flow + .app + .keys + .current() + .expect("fresh keys") + .verify( + tokens["id_token"] + .as_str() + .expect("token response contains an ID token"), + TokenType::Id, + &flow.app.issuer, + ) + .expect("verify scoped ID token"); + assert_eq!(claims.nonce.as_deref(), Some("test-nonce")); + assert!(claims.profile.name.is_none()); + assert!(claims.profile.email.is_none()); + assert_eq!( + flow.exchange(&code, Flow::verifier(), None).await.status(), + StatusCode::BAD_REQUEST + ); + let response = flow + .authorize(Scope::OpenId.as_str(), Some(Prompt::None.as_str())) + .await; + assert!( + flow.client_redirect(&response) + .query_pairs() + .any(|(name, _)| name == "code") + ); + let response = flow + .authorize(EMAIL_SCOPES, Some(Prompt::None.as_str())) + .await; + assert_eq!( + parameter(&flow.client_redirect(&response), "error"), + OAuthCode::ConsentRequired.as_str() + ); + let response = flow + .authorize(Scope::OpenId.as_str(), Some(Prompt::Login.as_str())) + .await; + assert_eq!(location(&response).path(), "/login"); + let client_id = flow.client.id.clone(); + assert_eq!( + flow.events().await[..3], + [ + DomainEvent::CodeReplayed { + client_id: client_id.clone(), + }, + DomainEvent::GrantIssued { + client_id: client_id.clone(), + family_id: None, + scopes: vec![Scope::OpenId.as_str().into()], + }, + DomainEvent::ConsentGranted { + client_id, + scopes: vec![Scope::OpenId.as_str().into()], + }, + ], + "a failed exchange records nothing" + ); +} + +/// Checks that ID hints bind the account across initial, resumed and consent requests. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn authorization_hints_bind_initial_resumed_and_consent_requests() { + let flow = Flow::new(false, true).await; + let now = Utc::now().timestamp(); + let claims = json!({"iss":flow.app.issuer,"sub":flow.user_id,"aud":flow.client.id,"iat":now-600,"exp":now-300}); + let hint = flow + .app + .keys + .current() + .expect("fresh keys") + .sign(TokenType::Id, &claims) + .expect("sign expired hint"); + let response = flow + .authorize_with( + Method::GET, + Scope::OpenId.as_str(), + Some(Prompt::None.as_str()), + &[("id_token_hint", &hint)], + ) + .await; + assert_ne!(parameter(&flow.client_redirect(&response), "code"), ""); + for (field, value) in [ + ("iss", json!("https://foreign.example")), + ("aud", json!("other-client")), + ] { + let mut invalid = claims.clone(); + invalid[field] = value; + let hint = flow + .app + .keys + .current() + .expect("fresh keys") + .sign(TokenType::Id, &invalid) + .expect("sign invalid hint"); + let response = flow + .authorize_with( + Method::GET, + Scope::OpenId.as_str(), + Some(Prompt::None.as_str()), + &[("id_token_hint", &hint)], + ) + .await; + assert_eq!( + parameter(&flow.client_redirect(&response), "error"), + OAuthCode::InvalidRequest.as_str() + ); + } + let mut other = claims; + other["sub"] = json!(UserId::new()); + let hint = flow + .app + .keys + .current() + .expect("fresh keys") + .sign(TokenType::Id, &other) + .expect("sign other account hint"); + let response = flow + .authorize_with( + Method::GET, + Scope::OpenId.as_str(), + Some(Prompt::None.as_str()), + &[("id_token_hint", &hint)], + ) + .await; + assert_eq!( + parameter(&flow.client_redirect(&response), "error"), + OAuthCode::LoginRequired.as_str() + ); + let response = flow + .authorize_with( + Method::GET, + Scope::OpenId.as_str(), + None, + &[("id_token_hint", &hint)], + ) + .await; + let login = location(&response); + assert_eq!(login.path(), "/login"); + let transaction = parameter(&login, "transaction"); + let response = flow + .request( + Method::GET, + &format!("/oauth/authorize/resume?transaction={transaction}"), + &[], + None, + ) + .await; + assert_eq!(location(&response).path(), "/login"); + let response = flow + .request( + Method::POST, + routes::page::CONSENT, + &[("transaction", &transaction), ("decision", APPROVE_CONSENT)], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); +} + +/// A consent that waits for the account lock while every session ends is not +/// saved: approving reads the session again under the lock. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_consent_whose_session_ended_while_waiting_is_not_saved() { + let flow = Flow::new(true, false).await; + let response = flow.authorize("openid", None).await; + let transaction = parameter(&location(&response), "transaction"); + let database = flow.app.database.clone(); + let mut holder = database.begin().await.expect("transaction"); + holder + .users() + .find_active_by_id_for_update(flow.user_id) + .await + .expect("lock") + .expect("user"); + let approving = flow.clone(); + let decision = tokio::spawn(async move { + let form = [ + ("transaction", transaction.as_str()), + ("decision", APPROVE_CONSENT), + ]; + let response = approving + .request(Method::POST, routes::page::CONSENT, &form, None) + .await; + response.status() + }); + until_blocked(&mut holder, 1).await; + let context = RequestContext::TEST.actor(Actor::Anonymous); + holder + .revoke_sessions( + &context, + flow.user_id, + SessionScope::All, + &RevocationReason::Admin, + ) + .await + .expect("every session ends"); + holder.commit().await.expect("commit"); + + assert_eq!(decision.await.expect("decision"), StatusCode::UNAUTHORIZED); + let consents = database.oidc().list_consents(flow.user_id).await; + assert!(consents.expect("consents").is_empty(), "not saved"); +} diff --git a/apps/auth-service/src/oidc/tests/logout.rs b/apps/auth-service/src/oidc/tests/logout.rs new file mode 100644 index 000000000..4c6a17ac6 --- /dev/null +++ b/apps/auth-service/src/oidc/tests/logout.rs @@ -0,0 +1,133 @@ +//! Back-channel logout to the clients of an ended session. + +use super::*; +use crate::deliveries::{BackchannelLogoutSender, OutboundClient, Sender}; +use piquel_common::clients::{ClientOwner, RedirectUri}; +use piquel_common::protocol::claims::BACKCHANNEL_LOGOUT_EVENT; +use piquel_repository::BackchannelLogout; +use std::{collections::HashMap, sync::Mutex}; + +/// A client's back-channel logout endpoint on a local HTTPS port: its URI, a client +/// that reaches it, and the logout tokens it received. +async fn logout_receiver() -> (RedirectUri, OutboundClient, Arc>>) { + let posted = Arc::new(Mutex::new(Vec::new())); + let receiver = axum::Router::new().route( + "/backchannel-logout", + axum::routing::post({ + let posted = Arc::clone(&posted); + async move |axum::Form(form): axum::Form>| { + posted + .lock() + .expect("posted tokens") + .push(form["logout_token"].clone()); + StatusCode::OK + } + }), + ); + let tcp = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind receiver"); + let uri = format!( + "https://localhost:{}/backchannel-logout", + tcp.local_addr().expect("address").port() + ) + .parse() + .expect("logout URI"); + let outbound = OutboundClient::local(TlsListener::serve(tcp, receiver)); + (uri, outbound, posted) +} + +/// Ending a session posts a logout token to each client that received tokens from it +/// and registered a back-channel logout URI (OIDC Back-Channel Logout 1.0 §2.4): +/// signed as `logout+jwt`, naming the client, the user and the ended session, with +/// the delivery's ID as `jti`, valid for two minutes, and never with a `nonce`. A +/// client that got no tokens from the session is not told. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn logout_posts_a_logout_token_to_the_clients_of_the_session() { + let flow = Flow::new(true, true).await; + let (uri, outbound, posted) = logout_receiver().await; + let sender = + BackchannelLogoutSender::new(flow.app.issuer.clone(), flow.app.keys.clone(), outbound); + let told = ClientRegistration { + backchannel_logout_uri: Some(uri.clone()), + ..flow.client.clone() + }; + let untold = ClientRegistration { + backchannel_logout_uri: Some(uri), + ..crate::tests::registration(ClientKind::Public, "https://untold.example") + }; + crate::tests::change(&flow.app.database, async |registry| { + registry + .update(&told.id, |_| { + Ok::<_, crate::ClientRegistryError>(told.clone()) + }) + .await?; + // A client without tokens from the session. + registry.create(ClientOwner::Operator, &untold, None).await + }) + .await + .expect("register the logout URIs"); + let code = flow.code(Scope::OpenId.as_str()).await; + let (_, id_token) = flow + .id_token( + flow.exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await, + ) + .await; + let response = flow + .request( + Method::POST, + routes::page::LOGOUT, + &[("client_id", told.id.as_str())], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + + // Other scenarios share the database: send only this session's deliveries. + let mut sent = Vec::new(); + while let Some(delivery) = flow + .app + .database + .deliveries() + .claim::(std::time::Duration::from_mins(1)) + .await + .expect("claim") + { + if delivery.recipient.sid.to_string() == id_token["sid"] { + sender.send(&delivery).await.expect("the client accepts it"); + sent.push((delivery.id, delivery.recipient.client_id)); + } + } + let [(delivery, client)] = + <[_; 1]>::try_from(sent).expect("one delivery for the one client told"); + assert_eq!(client, told.id); + let [token] = <[_; 1]>::try_from(posted.lock().expect("posted tokens").clone()) + .expect("one token posted"); + let claims: Value = flow + .app + .keys + .current() + .expect("fresh keys") + .verify(&token, TokenType::Logout, &flow.app.issuer) + .expect("a logout token signed by auth"); + let issued_at = claims["iat"].as_i64().expect("iat"); + assert!( + (issued_at - Utc::now().timestamp()).abs() < 60, + "signed when sent" + ); + assert_eq!( + claims, + json!({ + "iss": flow.app.issuer, + "aud": told.id, + "iat": issued_at, + "exp": issued_at + 120, + "jti": delivery, + "sub": flow.user_id, + "sid": id_token["sid"], + "events": {BACKCHANNEL_LOGOUT_EVENT: {}}, + }) + ); +} diff --git a/apps/auth-service/src/oidc/tests/mod.rs b/apps/auth-service/src/oidc/tests/mod.rs new file mode 100644 index 000000000..49ec7d61c --- /dev/null +++ b/apps/auth-service/src/oidc/tests/mod.rs @@ -0,0 +1,453 @@ +//! Focused parsing checks and database-backed OAuth/OIDC scenarios. + +use super::*; +use crate::config::TokenDigestKey; +use crate::security::{BrowserCookie, RequestContext, Session}; +use crate::tests::{AUTH_ORIGIN, Replicas, TlsListener, location, parameter, until_blocked}; +use crate::{ + AuthConfig, federation::FederationApplication, passkey::PasskeyApplication, web::WebApplication, +}; +use axum::{ + body::{Body, to_bytes}, + http::{Method, Request, StatusCode}, + response::Response, +}; +use chrono::Utc; +use piquel_common::{ + AuthenticationMethod, Handle, PasskeyId, UserId, + clients::{ClientKind, ClientRegistration}, + events::{Actor, DomainEvent, RevocationReason}, + protocol::claims::{Acr, IdTokenClaims}, +}; +use piquel_crypto::{KeySet, Rs256Key}; +use piquel_repository::{DatabaseConfig, InsertUser, InsertVerifiedEmail}; +use serde_json::{Value, json}; +use std::sync::Arc; +use tower::ServiceExt; +use url::Url; + +mod app_removal; +mod authorization; +mod logout; +mod protocol; +mod pushed; +mod sdk_client; +mod sdk_routes; +mod step_up; +mod tokens; + +/// Database-backed OIDC scenario with a provisioned client and authenticated browser. +#[derive(Clone)] +struct Flow { + /// Application under test, sharing the scenario database. + app: OidcApplication, + /// Where requests go: the OIDC routes and their pages, or a replica of the whole + /// service. + router: axum::Router, + /// The scenario's client, registered through [`ClientRegistry`](crate::ClientRegistry). + client: ClientRegistration, + /// The secret of a confidential scenario client. + secret: Option, + /// Authenticated browser cookie pair sent by the scenario. + cookie: String, + /// Scenario account whose claims and grants are checked. + user_id: UserId, + /// Optional encoded credentials for a confidential scenario client. + basic: Option, +} +impl Flow { + /// Creates a disposable account, client registration and persistent-key OIDC application. + async fn new(confidential: bool, trusted: bool) -> Self { + Self::at(AUTH_ORIGIN, confidential, trusted).await + } + + /// Like [`Self::new`], for an issuer at `origin`. + async fn at(origin: &str, confidential: bool, trusted: bool) -> Self { + let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") + .required() + .expect("TEST_DATABASE_URL must name a disposable PostgreSQL database"); + let db = Database::connect( + DatabaseConfig::new(&url, 5, std::time::Duration::from_secs(5)) + .expect("valid local test database configuration"), + ) + .await + .expect("connect to the disposable PostgreSQL database"); + db.run_migrations() + .await + .expect("apply test database migrations"); + let user_id = UserId::new(); + let mut tx = db.begin().await.expect("begin test account transaction"); + tx.users() + .insert(&InsertUser { + id: user_id, + handle: Handle::parse(&format!("oidc-{}", &user_id.to_string()[24..])) + .expect("handle"), + display_name: "OIDC Test".into(), + }) + .await + .expect("insert test account"); + tx.emails() + .insert_verified(&InsertVerifiedEmail { + id: piquel_common::EmailId::new(), + user_id, + normalized_email: format!("{user_id}@example.com"), + is_primary: true, + verified_at: Utc::now(), + }) + .await + .expect("insert verified test email"); + let cookie = Session::create( + &mut tx, + RequestContext::TEST, + user_id, + AuthenticationMethod::Passkey.into(), + ) + .await + .expect("create test browser session"); + let cookie = format!("{}={}", BrowserCookie::Session.as_str(), cookie.encoded()); + tx.commit().await.expect("commit test account transaction"); + let client = ClientRegistration { + kind: if confidential { + ClientKind::Confidential + } else { + ClientKind::Public + }, + trusted, + ..crate::tests::registration(ClientKind::Public, "https://client.example") + }; + let secret = crate::tests::register(&db, &client) + .await + .expect("register test OIDC client") + .map(|secret| secret.expose().to_owned()); + let basic = secret.as_ref().map(|secret| { + format!( + "{} {}", + AuthScheme::Basic.as_str(), + base64::engine::general_purpose::STANDARD.encode(format!("{}:{secret}", client.id)) + ) + }); + let origin = origin + .parse::() + .expect("issuer"); + let config = AuthConfig::test(&origin); + let federation = + FederationApplication::new(db.clone(), &config.federation).expect("federation"); + let app = OidcApplication::new( + db.clone(), + &OidcConfig { + origin: origin.clone(), + digest_keys: Arc::new(TokenDigestKeys::new( + TokenDigestKey::derive(&[7; 32]).expect("digest key"), + None, + )), + policies: config.oidc.policies.clone(), + }, + SigningKeys::new(KeySet::single( + Rs256Key::generate("oidc-tests").expect("RSA signing key"), + )), + ) + .expect("OIDC application"); + let passkeys = + PasskeyApplication::new(db.clone(), &config.passkey, app.clone()).expect("passkeys"); + Self { + router: WebApplication::new(db, &config, app.clone(), federation, passkeys) + .routes() + .merge(app.clone().routes()), + app, + client, + secret, + cookie, + user_id, + basic, + } + } + /// The same scenario, sending its requests to `router`, such as one of [`Replicas`]. + fn on(&self, router: &axum::Router) -> Self { + Self { + router: router.clone(), + ..self.clone() + } + } + /// Signs the scenario's browser in again with `method`, as a new session. + async fn sign_in_again(&mut self, method: AuthenticationMethod) { + let mut tx = self.app.database.begin().await.expect("transaction"); + let session = Session::create(&mut tx, RequestContext::TEST, self.user_id, method.into()) + .await + .expect("session"); + tx.commit().await.expect("commit"); + self.cookie = format!("{}={}", BrowserCookie::Session.as_str(), session.encoded()); + } + /// Lists the events recorded about the scenario account, newest first. + async fn events(&self) -> Vec { + self.app + .database + .events() + .history_for_user(self.user_id, 100) + .await + .expect("history") + .into_iter() + .map(|stored| stored.event.known().cloned().expect("a known event")) + .collect() + } + + /// Dispatches an encoded protocol request, or a page's form, through the OIDC routes. + async fn request( + &self, + method: Method, + uri: &str, + form: &[(&str, &str)], + basic: Option<&str>, + ) -> Response { + let mut builder = Request::builder() + .extension(RequestContext::TEST) + .method(method) + .uri(uri) + .header(header::COOKIE, &self.cookie) + .header(header::ORIGIN, &self.app.issuer) + .header("x-piquel-csrf", "1"); + if let Some(basic) = basic { + builder = builder.header(header::AUTHORIZATION, basic); + } + let body = url::form_urlencoded::Serializer::new(String::new()) + .extend_pairs(form.iter().copied()) + .finish(); + let request = builder + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from(body)) + .expect("build test HTTP request"); + self.router + .clone() + .oneshot(request) + .await + .expect("dispatch OIDC HTTP request") + } + /// Accepts query authorization requests and returns OAuth errors for malformed input. + async fn authorize(&self, scope: &str, prompt: Option<&str>) -> Response { + self.authorize_with(Method::GET, scope, prompt, &[]).await + } + /// Builds an authorization request with optional hint or security parameter overrides. + async fn authorize_with( + &self, + method: Method, + scope: &str, + prompt: Option<&str>, + extra: &[(&str, &str)], + ) -> Response { + let url = self.authorization_url(scope, prompt, extra); + if method == Method::POST { + self.post_query(&url, None).await + } else { + self.request( + method, + &format!( + "{}?{}", + url.path(), + url.query().expect("authorization query") + ), + &[], + None, + ) + .await + } + } + /// Pushes the scenario's authorization request with `basic` credentials. + async fn push(&self, scope: &str, prompt: Option<&str>, basic: Option<&str>) -> Response { + let mut url = self.authorization_url(scope, prompt, &[]); + url.set_path(routes::oidc::PAR); + self.post_query(&url, basic).await + } + /// Pushes the scenario's request with its credentials and returns its `request_uri`. + async fn pushed(&self, scope: &str, prompt: Option<&str>) -> String { + let response = self.push(scope, prompt, self.basic.as_deref()).await; + assert_eq!(response.status(), StatusCode::CREATED); + let body = Self::json(response).await; + assert_eq!(body["expires_in"], PUSHED_REQUEST_SECONDS); + body["request_uri"] + .as_str() + .expect("pushed request has a request_uri") + .to_owned() + } + /// Brings a `request_uri` to the authorization endpoint as `client_id`, along + /// with `extra` parameters, which must not override the pushed ones. + async fn claim(&self, client_id: &str, request_uri: &str, extra: &[(&str, &str)]) -> Response { + let mut url = Url::parse(&format!("{AUTH_ORIGIN}{}", routes::oidc::AUTHORIZE)) + .expect("parse authorization endpoint URL"); + url.query_pairs_mut() + .append_pair("client_id", client_id) + .append_pair("request_uri", request_uri) + .extend_pairs(extra.iter().copied()); + let uri = format!("{}?{}", url.path(), url.query().expect("query")); + self.request(Method::GET, &uri, &[], None).await + } + /// Posts `url`'s query as a form to its path. + async fn post_query(&self, url: &Url, basic: Option<&str>) -> Response { + let owned: Vec<_> = url.query_pairs().into_owned().collect(); + let fields: Vec<_> = owned + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())) + .collect(); + self.request(Method::POST, url.path(), &fields, basic).await + } + /// The authorization endpoint with the scenario's request parameters, then `extra`. + fn authorization_url(&self, scope: &str, prompt: Option<&str>, extra: &[(&str, &str)]) -> Url { + let mut url = Url::parse(&format!("{AUTH_ORIGIN}/oauth/authorize")) + .expect("parse authorization endpoint URL"); + url.query_pairs_mut().extend_pairs([ + ("response_type", ResponseType::Code.as_str()), + ("client_id", self.client.id.as_str()), + ("redirect_uri", self.client.redirect_uris[0].as_str()), + ("scope", scope), + ("state", "test-state"), + ("nonce", "test-nonce"), + ("code_challenge_method", CodeChallengeMethod::S256.as_str()), + ( + "code_challenge", + &piquel_crypto::Pkce::challenge(Self::verifier()).expect("PKCE"), + ), + ]); + if let Some(prompt) = prompt { + url.query_pairs_mut().append_pair("prompt", prompt); + } + url.query_pairs_mut().extend_pairs(extra.iter().copied()); + url + } + /// Returns the valid PKCE verifier used by database-backed scenarios. + fn verifier() -> &'static str { + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + } + /// Reads a redirect back to the client, which must name this issuer in `iss` (RFC 9207). + fn client_redirect(&self, response: &Response) -> Url { + self.issued(location(response)) + } + /// Returns an authorization response URL after checking its `iss`. + fn issued(&self, url: Url) -> Url { + assert_eq!(parameter(&url, "iss"), self.app.issuer); + url + } + /// Reads the scenario's text response. + async fn text(response: Response) -> String { + String::from_utf8( + to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("read complete HTTP response body") + .to_vec(), + ) + .expect("UTF-8 response") + } + /// Reads and decodes the scenario’s JSON response. + async fn json(response: Response) -> Value { + serde_json::from_slice( + &to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("read complete HTTP response body"), + ) + .expect("decode HTTP JSON response") + } + /// Completes explicit consent when needed and extracts the issued authorization code. + async fn code(&self, scopes: &str) -> String { + let response = self.authorize(scopes, None).await; + parameter(&self.consent(response).await, "code") + } + /// Follows an authorization response through consent, when needed, to the client + /// redirect, whose `iss` it checks. + async fn consent(&self, response: Response) -> Url { + assert_eq!(response.status(), StatusCode::SEE_OTHER); + let mut destination = location(&response); + if destination.path() == routes::page::CONSENT { + let transaction = parameter(&destination, "transaction"); + let response = self + .request( + Method::POST, + routes::page::CONSENT, + &[("transaction", &transaction), ("decision", APPROVE_CONSENT)], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::SEE_OTHER); + destination = location(&response); + } + self.issued(destination) + } + /// Exchanges a scenario code with the requested verifier and client credentials. + async fn exchange(&self, code: &str, verifier: &str, basic: Option<&str>) -> Response { + self.request( + Method::POST, + "/oauth/token", + &[ + ("grant_type", GrantType::AuthorizationCode.as_str()), + ("client_id", self.client.id.as_str()), + ("redirect_uri", self.client.redirect_uris[0].as_str()), + ("code", code), + ("code_verifier", verifier), + ], + basic, + ) + .await + } + /// Verifies the ID token of a successful token response and returns the response + /// with the token's claims. + async fn id_token(&self, response: Response) -> (Value, Value) { + assert_eq!(response.status(), StatusCode::OK); + let tokens = Self::json(response).await; + let claims = self + .app + .keys + .current() + .expect("fresh keys") + .verify( + tokens["id_token"].as_str().expect("ID token"), + TokenType::Id, + &self.app.issuer, + ) + .expect("verify ID token"); + (tokens, claims) + } + /// The scenario's account, as the owner of its browser session. + async fn owner(&self) -> crate::account::Owner { + let mut headers = axum::http::HeaderMap::new(); + headers.insert(header::COOKIE, self.cookie.parse().expect("cookie")); + crate::account::AccountService::new(self.app.database.clone()) + .owner(RequestContext::TEST, &headers) + .await + .expect("session lookup") + .expect("signed in") + } + /// Asserts that a token response rejected its grant as `invalid_grant`. + async fn assert_invalid_grant(response: Response) { + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + Self::json(response).await["error"], + OAuthCode::InvalidGrant.as_str() + ); + } + /// Rotates a scenario refresh token using its registered client credentials. + async fn refresh(&self, token: &str) -> Response { + self.request( + Method::POST, + "/oauth/token", + &[ + ("grant_type", GrantType::RefreshToken.as_str()), + ("client_id", self.client.id.as_str()), + ("refresh_token", token), + ], + self.basic.as_deref(), + ) + .await + } +} + +/// Existing scope strings exercise the HTTP wire contract independently of enum serialization. +const EMAIL_REFRESH_SCOPES: &str = "openid email offline_access"; +/// Identity and session-bounded refresh requested together. +const REFRESH_SCOPES: &str = "openid offline_access"; +/// Public-profile scope fixture. +const PROFILE_SCOPES: &str = "openid profile"; +/// Profile claims with a refresh token. +const PROFILE_REFRESH_SCOPES: &str = "openid profile offline_access"; +/// Verified-email scope fixture. +const EMAIL_SCOPES: &str = "openid email"; +/// Unregistered extension scope fixture used to check rejection. +const UNGRANTED_SCOPES: &str = "openid admin"; + +/// Existing approve form spelling, independent of the JSON-only consent enum. +const APPROVE_CONSENT: &str = "approve"; diff --git a/apps/auth-service/src/oidc/tests/protocol.rs b/apps/auth-service/src/oidc/tests/protocol.rs new file mode 100644 index 000000000..32555ed2d --- /dev/null +++ b/apps/auth-service/src/oidc/tests/protocol.rs @@ -0,0 +1,252 @@ +//! Discovery metadata, POST parity, OAuth error formats and protocol parsing. + +use super::*; + +/// Both well-known paths serve the same cacheable, typed document, and every endpoint +/// it advertises is routed on the issuer. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn metadata_is_one_document_whose_endpoints_are_routed() { + let flow = Flow::new(false, false).await; + let mut documents = vec![]; + let jwks = flow + .request(Method::GET, routes::oidc::JWKS, &[], None) + .await; + assert_eq!( + jwks.extensions().get::(), + Some(&PublicDocument::CACHE) + ); + for path in [routes::oidc::DISCOVERY, routes::oidc::OAUTH_METADATA] { + let response = flow.request(Method::GET, path, &[], None).await; + assert_eq!(response.status(), StatusCode::OK, "{path}"); + assert_eq!( + response.extensions().get::(), + Some(&PublicDocument::CACHE) + ); + documents.push( + to_bytes(response.into_body(), 1024 * 1024) + .await + .expect("read metadata"), + ); + } + assert_eq!(documents[0], documents[1]); + let metadata: ServerMetadata = serde_json::from_slice(&documents[0]).expect("typed metadata"); + assert_eq!(metadata.issuer, flow.app.issuer); + assert_eq!(metadata.acr_values_supported, Acr::ALL); + let Value::Object(fields) = serde_json::from_slice(&documents[0]).expect("metadata JSON") + else { + panic!("metadata is not a JSON object"); + }; + for (name, value) in fields { + if !(name.ends_with("_endpoint") || name == "jwks_uri") { + continue; + } + let url = Url::parse(value.as_str().expect("endpoint text")).expect("endpoint URL"); + assert_eq!( + url.origin().ascii_serialization(), + metadata.issuer, + "{name}" + ); + let response = flow.request(Method::GET, url.path(), &[], None).await; + assert_ne!(response.status(), StatusCode::NOT_FOUND, "{name}"); + } +} + +/// Checks protocol POST parity and existing OAuth error and challenge formats. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn post_protocol_endpoints_and_error_contracts() { + let flow = Flow::new(false, true).await; + for (name, value, expected) in [ + ( + "id_token_hint", + "invalid", + OAuthCode::InvalidRequest.as_str(), + ), + ( + "request", + "ignored.jwt", + OAuthCode::RequestNotSupported.as_str(), + ), + ( + "response_mode", + "form_post", + OAuthCode::InvalidRequest.as_str(), + ), + ] { + let response = flow + .authorize_with( + Method::GET, + Scope::OpenId.as_str(), + Some(Prompt::None.as_str()), + &[(name, value)], + ) + .await; + assert_eq!( + parameter(&flow.client_redirect(&response), "error"), + expected + ); + } + let discovery = Flow::json( + flow.request(Method::GET, "/.well-known/openid-configuration", &[], None) + .await, + ) + .await; + assert_eq!(discovery["request_parameter_supported"], false); + assert_eq!(discovery["request_uri_parameter_supported"], false); + assert_eq!( + discovery["pushed_authorization_request_endpoint"], + format!("{}{}", flow.app.issuer, routes::oidc::PAR) + ); + // Only pushed requests have a request_uri, and no redirect URI is known for it. + let response = flow + .claim( + flow.client.id.as_str(), + "https://example.com/request.jwt", + &[], + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + Flow::json(response).await["error"], + OAuthCode::InvalidRequestUri.as_str() + ); + assert_eq!( + discovery["authorization_response_iss_parameter_supported"], + true + ); + let response = flow + .authorize_with(Method::POST, PROFILE_SCOPES, None, &[]) + .await; + let code = parameter(&flow.client_redirect(&response), "code"); + let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await; + let bearer = format!( + "{} {}", + AuthScheme::Bearer.as_str(), + tokens["access_token"].as_str().expect("access token") + ); + let response = flow + .request(Method::POST, "/oidc/userinfo", &[], Some(&bearer)) + .await; + assert_eq!(response.status(), StatusCode::OK); + let userinfo = Flow::json(response).await; + assert_eq!(userinfo["sub"], json!(flow.user_id)); + assert!(userinfo["profile_version"].is_number()); + let response = flow + .request(Method::POST, "/oidc/userinfo", &[], None) + .await; + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!( + response.headers()[header::WWW_AUTHENTICATE], + "Bearer error=\"invalid_token\"" + ); + let response = flow + .request( + Method::POST, + "/oauth/token", + &[("client_id", flow.client.id.as_str())], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + Flow::json(response).await["error"], + OAuthCode::InvalidRequest.as_str() + ); +} + +/// Checks redirect equality, PKCE rejection and opaque-token bounds. +#[test] +fn exact_redirect_and_pkce_and_refresh_bounds() { + let registered = ["https://a.example/cb".to_owned()]; + assert!(!registered.contains(&"https://a.example/cb.evil".to_owned())); + assert!(piquel_crypto::Pkce::verify("short", "x").is_err()); + let huge = format!( + "{}_{}.{:0200}", + TokenPrefix::RefreshToken, + TokenId::new(), + "x" + ); + assert!(OpaqueToken::parse(TokenPrefix::RefreshToken, &huge).is_err()); +} + +/// Checks case-insensitive scheme matching without changing credential bytes. +#[test] +fn authentication_schemes_are_case_insensitive() { + assert_eq!(AuthScheme::Bearer.credentials("bEaReR a.B"), Some("a.B")); + assert_eq!(AuthScheme::Basic.credentials("BASIC Zm9v"), Some("Zm9v")); + assert_eq!(AuthScheme::Basic.credentials("Bearer Zm9v"), None); + assert_eq!(AuthScheme::Bearer.credentials("Bearer"), None); +} + +/// Checks deduplication, lexical ordering and preservation of registered extension scopes. +#[test] +fn scope_sets_preserve_existing_wire_semantics() { + let scopes = Scopes::parse("profile openid profile custom.read email").expect("scope set"); + assert!(scopes.contains(Scope::OpenId)); + assert_eq!( + scopes.wire().to_string(), + "custom.read email openid profile" + ); + let stored = scopes.clone().into_stored(); + assert!(scopes.allowed_by(&stored)); + assert!(!scopes.allowed_by(&[Scope::OpenId.as_str().into()])); + assert_eq!(Scopes::from_stored(&stored), scopes); + assert!(Scopes::parse(" ").is_err()); + let too_many = (0..=MAX_SCOPES) + .map(|index| format!("scope{index}")) + .collect::>() + .join(" "); + assert!(Scopes::parse(&too_many).is_err()); +} + +/// Checks purpose binding and exact opaque envelope/secret round trips. +#[test] +fn opaque_tokens_preserve_envelopes_and_reject_wrong_purpose() { + for prefix in TokenPrefix::ALL { + let original = OpaqueToken::new(prefix).expect("random token"); + let encoded = original.encoded(); + let parsed = OpaqueToken::parse(prefix, &encoded).expect("parse envelope"); + assert_eq!(parsed.id, original.id); + assert_eq!(parsed.secret.as_bytes(), original.secret.as_bytes()); + assert_eq!(parsed.encoded(), encoded); + for other in TokenPrefix::ALL { + if prefix != other { + assert!(OpaqueToken::parse(other, &encoded).is_err()); + } + } + } +} + +/// Checks that protocol failures retain both internal and rejected-input source chains. +#[tokio::test] +async fn oauth_failures_preserve_sources_and_statuses() { + use axum::response::IntoResponse; + use std::error::Error; + let error = OAuthError::from(piquel_repository::DatabaseError::Operation(Box::new( + std::io::Error::other("internal diagnostic"), + ))); + assert_eq!( + error.source().expect("internal source").to_string(), + "internal diagnostic" + ); + assert_eq!( + error.into_response().status(), + StatusCode::INTERNAL_SERVER_ERROR + ); + let error = OAuthCode::InvalidGrant.reject_with( + "code is \"malformed\" \u{2014} retry", + piquel_crypto::CryptoError::SecretLength, + ); + assert!(error.source().is_some()); + let response = error.into_response(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + // The description reaches the client, restricted to the RFC 6749 character set. + assert_eq!( + Flow::json(response).await, + serde_json::json!({ + "error": "invalid_grant", + "error_description": "code is 'malformed' ? retry", + }) + ); +} diff --git a/apps/auth-service/src/oidc/tests/pushed.rs b/apps/auth-service/src/oidc/tests/pushed.rs new file mode 100644 index 000000000..f78c74430 --- /dev/null +++ b/apps/auth-service/src/oidc/tests/pushed.rs @@ -0,0 +1,132 @@ +//! Pushed authorization requests (RFC 9126). + +use super::*; + +/// A pushed request is validated like a browser one, but answers in JSON. Its +/// `request_uri` is not a transaction: only its client can claim it, once, and the +/// query cannot override what was pushed, `prompt` included. A client required to +/// push cannot send plain requests. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn pushed_requests_are_one_time_client_bound_and_authoritative() { + let mut flow = Flow::new(true, false).await; + let id = flow.client.id.to_string(); + let response = flow.push(Scope::OpenId.as_str(), None, None).await; + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + let response = flow + .push("openid unregistered", None, flow.basic.as_deref()) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + Flow::json(response).await["error"], + OAuthCode::InvalidScope.as_str() + ); + let request_uri = flow + .pushed(Scope::OpenId.as_str(), Some(Prompt::None.as_str())) + .await; + assert_eq!( + parameter( + &flow.client_redirect(&flow.claim(&id, &request_uri, &[]).await), + "error" + ), + OAuthCode::ConsentRequired.as_str() + ); + let request_uri = flow.pushed(Scope::OpenId.as_str(), None).await; + let transaction = request_uri + .strip_prefix("urn:ietf:params:oauth:request_uri:") + .expect("RFC 9126 request_uri"); + let response = flow + .request( + Method::GET, + &format!("/oauth/authorize/resume?transaction={transaction}"), + &[], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let rejected = async |client_id: &str, request_uri: &str| { + let response = flow.claim(client_id, request_uri, &[]).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + Flow::json(response).await["error"], + OAuthCode::InvalidRequestUri.as_str() + ); + }; + let other = crate::tests::registration(ClientKind::Public, "https://other.example"); + crate::tests::register(&flow.app.database, &other) + .await + .expect("register another client"); + rejected(other.id.as_str(), &request_uri).await; + rejected(&id, "urn:ietf:params:oauth:request_uri:unknown").await; + rejected(&id, "https://client.example/request.jwt").await; + let response = flow + .claim( + &id, + &request_uri, + &[ + ("scope", EMAIL_SCOPES), + ("state", "forged-state"), + ("redirect_uri", "https://evil.example/callback"), + ("prompt", Prompt::None.as_str()), + ], + ) + .await; + let redirect = flow.consent(response).await; + assert_eq!( + redirect.origin(), + Url::parse(flow.client.redirect_uris[0].as_str()) + .expect("callback") + .origin() + ); + assert_eq!(parameter(&redirect, "state"), "test-state"); + let code = parameter(&redirect, "code"); + let response = flow + .exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await; + let (tokens, claims) = flow.id_token(response).await; + assert_eq!(tokens["scope"], Scope::OpenId.as_str()); + assert_eq!(claims["nonce"], "test-nonce"); + rejected(&id, &request_uri).await; + flow.client.require_pushed_authorization_requests = true; + let client = flow.client.clone(); + crate::tests::replace(&flow.app.database, &client) + .await + .expect("require pushed requests"); + assert_eq!( + parameter( + &flow.client_redirect(&flow.authorize(Scope::OpenId.as_str(), None).await), + "error" + ), + OAuthCode::InvalidRequest.as_str() + ); + let request_uri = flow.pushed(Scope::OpenId.as_str(), None).await; + // The user consented above, so the claim returns a code at once. + let response = flow.claim(&id, &request_uri, &[]).await; + parameter(&flow.client_redirect(&response), "code"); +} + +/// A pushed `prompt=login` needs a sign-in after the browser claims the request: +/// one between the push and the claim is not fresh. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn pushed_requests_count_sign_in_freshness_from_the_claim() { + let mut flow = Flow::new(true, false).await; + let request_uri = flow + .pushed(Scope::OpenId.as_str(), Some(Prompt::Login.as_str())) + .await; + flow.sign_in_again(AuthenticationMethod::Passkey).await; + let response = flow.claim(flow.client.id.as_str(), &request_uri, &[]).await; + let location = location(&response); + assert_eq!(location.path(), "/login"); + let transaction = parameter(&location, "transaction"); + flow.sign_in_again(AuthenticationMethod::Passkey).await; + let response = flow + .request( + Method::GET, + &format!("/oauth/authorize/resume?transaction={transaction}"), + &[], + None, + ) + .await; + parameter(&flow.consent(response).await, "code"); +} diff --git a/apps/auth-service/src/oidc/tests/sdk_client.rs b/apps/auth-service/src/oidc/tests/sdk_client.rs new file mode 100644 index 000000000..75c9529c9 --- /dev/null +++ b/apps/auth-service/src/oidc/tests/sdk_client.rs @@ -0,0 +1,140 @@ +//! The Rust SDK's login client against the real provider. + +use super::*; + +/// The Rust SDK signs in, validates, refreshes, revokes and logs out against the real +/// provider over HTTPS, and rejects a mixed-up callback before any code exchange. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +#[expect( + clippy::too_many_lines, + reason = "The scenario follows one login from authorization through logout." +)] +async fn sdk_login_client_runs_against_the_provider() { + use piquel_auth::{ + AuthorizeRequest, CallbackParams, ClientConfig, Credentials, LoginError, OAuthError, + Resource, Scopes, Subject, + }; + let tcp = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind provider"); + let port = tcp.local_addr().expect("provider address").port(); + let origin = format!("https://localhost:{port}"); + let flow = Flow::at(&origin, true, false).await; + let certificate = TlsListener::serve(tcp, flow.app.clone().routes()); + let http = reqwest::Client::builder() + .add_root_certificate(certificate) + .redirect(reqwest::redirect::Policy::none()) + .build() + .expect("HTTP client"); + let issuer = piquel_auth::Issuer::builder() + .http_client(http) + .discover(&origin) + .await + .expect("discover the provider"); + let client = issuer.client(ClientConfig { + client_id: flow.client.id.clone(), + credentials: Credentials::Secret(flow.secret.clone().expect("confidential").into()), + redirect_uri: flow.client.redirect_uris[0] + .as_str() + .parse() + .expect("callback"), + }); + let (url, pending) = client + .authorize(&AuthorizeRequest { + scopes: "profile email offline_access".parse().expect("scopes"), + ..AuthorizeRequest::default() + }) + .await + .expect("authorization URL"); + + let mixed_up = CallbackParams { + code: Some("pac_v1_unused".into()), + state: Some(pending.state().into()), + iss: Some("https://evil.example".into()), + ..CallbackParams::default() + }; + assert!(matches!( + client.complete(pending.clone(), &mixed_up).await, + Err(LoginError::IssuerMismatch { .. }) + )); + + let browser = flow + .request( + Method::GET, + &format!("{}?{}", url.path(), url.query().expect("query")), + &[], + None, + ) + .await; + let callback = flow.consent(browser).await; + let parameters: CallbackParams = serde_json::from_value(Value::Object( + callback + .query_pairs() + .map(|(name, value)| (name.into_owned(), Value::String(value.into_owned()))) + .collect(), + )) + .expect("callback parameters"); + let tokens = client + .complete(pending, ¶meters) + .await + .expect("complete the login"); + let id_token = tokens.id_token.as_ref().expect("ID token"); + assert_eq!(id_token.user_id().expect("account"), flow.user_id); + + let access = issuer + .resource(Resource::new(flow.client.id.as_str()).expect("resource")) + .validate::(tokens.access_token.expose()) + .await + .expect("valid access token"); + assert_eq!(access.subject, Subject::User(flow.user_id)); + assert!(access.scopes.contains(Scope::OfflineAccess.as_str())); + + let user = client + .userinfo(&tokens.access_token) + .await + .expect("UserInfo"); + assert_eq!(user.sub, flow.user_id.to_string()); + assert!(user.profile.email.is_some()); + + let first = tokens.refresh_token.expect("refresh token"); + let rotated = client + .refresh(&first) + .await + .expect("refresh") + .refresh_token + .expect("rotated refresh token"); + assert_ne!(rotated.expose(), first.expose()); + client.revoke(&rotated).await.expect("revoke"); + assert!(matches!( + client.refresh(&rotated).await, + Err(OAuthError::Rejected { response, .. }) + if response.error == OAuthCode::InvalidGrant + )); + + let post_logout: Url = flow.client.post_logout_uris[0] + .as_str() + .parse() + .expect("post-logout URI"); + let logout = client.logout_url(id_token, Some(&post_logout)); + let confirmation = location( + &flow + .request( + Method::GET, + &format!("{}?{}", logout.path(), logout.query().expect("query")), + &[], + None, + ) + .await, + ); + assert_eq!(confirmation.path(), routes::page::LOGOUT); + let fields: Vec<(String, String)> = confirmation.query_pairs().into_owned().collect(); + let fields: Vec<_> = fields + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + .collect(); + let confirmed = flow + .request(Method::POST, routes::page::LOGOUT, &fields, None) + .await; + assert_eq!(location(&confirmed), post_logout); +} diff --git a/apps/auth-service/src/oidc/tests/sdk_routes.rs b/apps/auth-service/src/oidc/tests/sdk_routes.rs new file mode 100644 index 000000000..a1961ea56 --- /dev/null +++ b/apps/auth-service/src/oidc/tests/sdk_routes.rs @@ -0,0 +1,438 @@ +//! The Rust SDK's login routes, pushing and step-up against the real provider. + +use super::*; +use piquel_common::protocol::step_up::StepUpRequirement; + +/// A clock the SDK scenarios move by hand, to reach access token expiry. +#[derive(Clone)] +struct ManualClock(Arc>>); + +impl ManualClock { + /// Moves the clock forward. + fn advance(&self, seconds: i64) { + *self.0.lock().expect("clock") += chrono::TimeDelta::seconds(seconds); + } +} + +impl piquel_auth::Clock for ManualClock { + fn now(&self) -> chrono::DateTime { + *self.0.lock().expect("clock") + } +} + +/// An app using the SDK's login routes against the provider, served in-process. +struct LoginApp { + /// The provider scenario. + flow: Flow, + /// The app's routes; `/` shows the session's access token. + app: Router, + /// The SDK's clock. + clock: ManualClock, +} + +impl LoginApp { + /// Serves the provider over TLS and builds the app. + async fn start() -> Self { + use piquel_auth::{ + ClientConfig, Credentials, Resource, + axum::{BearerLayer, LoginRoutes, MemoryBackend, RequireAuthentication, SignedIn}, + protocol::challenge::BearerChallenge, + }; + let tcp = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind provider"); + let port = tcp.local_addr().expect("provider address").port(); + let origin = format!("https://localhost:{port}"); + let flow = Flow::at(&origin, true, false).await; + let certificate = TlsListener::serve(tcp, flow.app.clone().routes()); + let http = reqwest::Client::builder() + .add_root_certificate(certificate) + .redirect(reqwest::redirect::Policy::none()) + .build() + .expect("HTTP client"); + let clock = ManualClock(Arc::new(std::sync::Mutex::new(Utc::now()))); + let issuer = piquel_auth::Issuer::builder() + .http_client(http) + .clock(clock.clone()) + .discover(&origin) + .await + .expect("discover the provider"); + let client = issuer.client(ClientConfig { + client_id: flow.client.id.clone(), + credentials: Credentials::Secret(flow.secret.clone().expect("confidential").into()), + redirect_uri: flow.client.redirect_uris[0] + .as_str() + .parse() + .expect("callback"), + }); + // An API the app calls with the user's token: `/settings` needs a recent + // passkey, and `/stubborn` asks for a step-up, naming nothing, whatever the + // token holds. + let api = Router::new() + .route( + "/settings", + axum::routing::get(|_: RequireAuthentication| async { "settings" }), + ) + .route( + "/stubborn", + axum::routing::get(|| async { + let challenge = BearerChallenge::step_up(StepUpRequirement::default()); + ( + StatusCode::UNAUTHORIZED, + [(header::WWW_AUTHENTICATE, challenge.to_string())], + ) + }), + ) + .layer(BearerLayer::new(issuer.resource( + Resource::new(flow.client.id.as_str()).expect("resource"), + ))); + let call_api = move |path: &'static str| { + let api = api.clone(); + move |user: SignedIn| async move { + let request = Request::get(path) + .header( + header::AUTHORIZATION, + format!("Bearer {}", user.login().access_token.expose()), + ) + .body(Body::empty()) + .expect("API request"); + let answer = api.oneshot(request).await.expect("API response"); + let challenge = answer + .headers() + .get(header::WWW_AUTHENTICATE) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()); + match challenge { + Some(challenge) => user.step_up(challenge.step_up).into_response(), + None => answer, + } + } + }; + let auth = LoginRoutes::new(client, MemoryBackend::default()) + .scopes("profile offline_access".parse().expect("scopes")) + .after_logout( + flow.client.post_logout_uris[0] + .as_str() + .parse() + .expect("logout URI"), + ); + let app = Router::new() + .route( + "/notes", + axum::routing::get(|user: SignedIn| async move { + user.login().access_token.expose().to_owned() + }), + ) + .route("/settings", axum::routing::get(call_api("/settings"))) + .route("/stubborn", axum::routing::get(call_api("/stubborn"))) + .nest("/auth", auth.router()) + .layer(auth.layer()); + Self { flow, app, clock } + } + + /// Sends a request to the app with an optional cookie. Posts carry the app's + /// `Origin`, as a browser on its pages sends. + async fn send(&self, method: Method, uri: &str, cookie: Option<&str>) -> Response { + let mut request = Request::builder().method(method.clone()).uri(uri); + if method == Method::POST { + let callback = + Url::parse(self.flow.client.redirect_uris[0].as_str()).expect("callback"); + request = request.header(header::ORIGIN, callback.origin().ascii_serialization()); + } + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, cookie); + } + self.app + .clone() + .oneshot(request.body(Body::empty()).expect("request")) + .await + .expect("response") + } + + /// The `Set-Cookie` values of a response. + fn cookies(response: &Response) -> Vec { + response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .map(|value| value.to_str().expect("cookie").to_owned()) + .collect() + } + + /// The `name=value` pair of the cookie `name` that `response` sets. + fn cookie(response: &Response, name: &str) -> String { + Self::cookies(response) + .into_iter() + .find(|cookie| cookie.starts_with(&format!("{name}="))) + .and_then(|cookie| cookie.split(';').next().map(str::to_owned)) + .expect("cookie set") + } + + /// The relative `Location` of an app redirect. + fn location(response: &Response) -> String { + assert_eq!(response.status(), StatusCode::SEE_OTHER); + response.headers()[header::LOCATION] + .to_str() + .expect("location") + .to_owned() + } + + /// Starts login at `login` (the app's login path and query): the pending login's + /// cookie, and the provider's authorization URL. + async fn start_login(&self, login: &str, session: Option<&str>) -> (String, Url) { + let start = self.send(Method::GET, login, session).await; + for cookie in Self::cookies(&start) { + assert!( + cookie.ends_with("; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=600"), + "{cookie}" + ); + } + ( + Self::cookie(&start, "__Host-piquel-login"), + Url::parse(&Self::location(&start)).expect("authorization URL"), + ) + } + + /// The provider's answer to the browser following `authorize`. + async fn authorize(&self, authorize: &Url) -> Response { + self.flow + .request( + Method::GET, + &format!("{}?{}", authorize.path(), authorize.query().expect("query")), + &[], + None, + ) + .await + } + + /// Consents at the provider and returns the app callback's response. + async fn finish_login( + &self, + browser: Response, + pending: String, + session: Option<&str>, + ) -> Response { + let callback = self.flow.consent(browser).await; + let cookies = match session { + Some(session) => format!("{pending}; {session}"), + None => pending, + }; + self.send( + Method::GET, + &format!("/auth/callback?{}", callback.query().expect("query")), + Some(&cookies), + ) + .await + } + + /// Starts login at `login`, signs in at the provider, and returns the callback's + /// response. + async fn sign_in(&self, login: &str, session: Option<&str>) -> Response { + let (pending, authorize) = self.start_login(login, session).await; + let browser = self.authorize(&authorize).await; + self.finish_login(browser, pending, session).await + } +} + +/// The SDK's login routes sign a user in through the provider, keep tokens in the +/// store, refresh them there, rotate the session on every sign-in, refuse open +/// redirects, and log out through the provider. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn sdk_login_routes_run_against_the_provider() { + let app = LoginApp::start().await; + let page = app.send(Method::GET, "/notes?page=2", None).await; + assert_eq!( + LoginApp::location(&page), + "/auth/login?return_to=%2Fnotes%3Fpage%3D2" + ); + + let callback = app.sign_in(&LoginApp::location(&page), None).await; + assert_eq!(LoginApp::location(&callback), "/notes?page=2"); + let cookies = LoginApp::cookies(&callback); + assert!( + cookies + .iter() + .any(|cookie| cookie.starts_with("__Host-piquel-session=") + && cookie.ends_with("; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=43200")) + ); + assert!(cookies.iter().any(|cookie| cookie + == "__Host-piquel-login=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0")); + let first = LoginApp::cookie(&callback, "__Host-piquel-session"); + let shown = app.send(Method::GET, "/notes", Some(&first)).await; + assert_eq!(shown.status(), StatusCode::OK); + let access = Flow::text(shown).await; + + // A second sign-in rotates the session and ends the first one. + let callback = app.sign_in("/auth/login", Some(&first)).await; + assert_eq!(LoginApp::location(&callback), "/"); + let second = LoginApp::cookie(&callback, "__Host-piquel-session"); + assert_ne!(first, second); + let stale = app.send(Method::GET, "/notes", Some(&first)).await; + assert_eq!(LoginApp::location(&stale), "/auth/login?return_to=%2Fnotes"); + + // Near expiry, the access token is refreshed in the store. + app.clock.advance(290); + let refreshed = app.send(Method::GET, "/notes", Some(&second)).await; + assert_eq!(refreshed.status(), StatusCode::OK); + assert_ne!(Flow::text(refreshed).await, access); + + // Open redirects are refused: login falls back to the home page. + let callback = app + .sign_in("/auth/login?return_to=%2F%2Fevil.example", None) + .await; + assert_eq!(LoginApp::location(&callback), "/"); + + let logout = app.send(Method::POST, "/auth/logout", Some(&second)).await; + let destination = Url::parse(&LoginApp::location(&logout)).expect("logout URL"); + assert_eq!(destination.path(), "/oidc/logout"); + assert_eq!( + parameter(&destination, "post_logout_redirect_uri"), + app.flow.client.post_logout_uris[0].as_str() + ); + assert!( + LoginApp::cookies(&logout) + .iter() + .any(|cookie| cookie.starts_with("__Host-piquel-session=;")) + ); + let after = app.send(Method::GET, "/notes", Some(&second)).await; + assert_eq!(after.status(), StatusCode::SEE_OTHER); +} + +/// A client required to push its authorization requests signs in through the SDK's +/// login routes, which push them, so the browser carries only the `request_uri`. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn sdk_login_routes_push_for_clients_that_must() { + let mut app = LoginApp::start().await; + app.flow.client.require_pushed_authorization_requests = true; + crate::tests::replace(&app.flow.app.database, &app.flow.client) + .await + .expect("require pushed requests"); + let (pending, authorize) = app.start_login("/auth/login", None).await; + let names: Vec<_> = authorize.query_pairs().map(|(name, _)| name).collect(); + assert_eq!(names, ["client_id", "request_uri"]); + let browser = app.authorize(&authorize).await; + let callback = app.finish_login(browser, pending, None).await; + assert_eq!(LoginApp::location(&callback), "/"); +} + +/// A passkey confirmation within five minutes. +struct RecentPasskey; + +impl piquel_auth::AuthenticationPolicy for RecentPasskey { + const REQUIREMENT: StepUpRequirement = StepUpRequirement::passkey_within(300); +} + +/// An app whose API needs a recent passkey sends a socially signed-in user through +/// the provider with the API's `acr_values` and `max_age`, then back to the page, +/// which now works. An API that still refuses after one step-up gets an error, not +/// another sign-in. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn sdk_step_up_runs_against_the_provider() { + let mut app = LoginApp::start().await; + app.flow + .sign_in_again(AuthenticationMethod::Federation) + .await; + let callback = app.sign_in("/auth/login", None).await; + let first = LoginApp::cookie(&callback, "__Host-piquel-session"); + + let page = app.send(Method::GET, "/settings", Some(&first)).await; + let login = LoginApp::location(&page); + assert_eq!( + login, + "/auth/login?return_to=%2Fsettings&acr_values=phr&max_age=300&step_up=true" + ); + // The pushed request carries `acr_values` and `max_age`: the social session is + // too weak for them, so the provider asks for a passkey. + let (pending, authorize) = app.start_login(&login, Some(&first)).await; + let prompt = app.authorize(&authorize).await; + assert_eq!(location(&prompt).path(), routes::page::LOGIN); + + let access = app.send(Method::GET, "/notes", Some(&first)).await; + let access = Flow::text(access).await; + let payload = access.split('.').nth(1).expect("JWT payload"); + let claims: Value = serde_json::from_slice( + &base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload) + .expect("base64url payload"), + ) + .expect("claims"); + let session = claims["sid"] + .as_str() + .expect("sid") + .parse() + .expect("session ID"); + app.flow + .app + .database + .sessions() + .confirm_passkey(session, PasskeyId::new(), Utc::now()) + .await + .expect("passkey confirmation"); + // The pushed request was claimed, so the browser resumes its transaction. + let transaction = parameter(&location(&prompt), "transaction"); + let browser = app + .flow + .request( + Method::GET, + &format!( + "{}?transaction={transaction}", + routes::oidc::AUTHORIZE_RESUME + ), + &[], + None, + ) + .await; + let callback = app.finish_login(browser, pending, Some(&first)).await; + assert_eq!(LoginApp::location(&callback), "/settings"); + let second = LoginApp::cookie(&callback, "__Host-piquel-session"); + let retry = LoginApp::cookie(&callback, "__Host-piquel-step-up"); + + let page = app + .send( + Method::GET, + "/settings", + Some(&format!("{second}; {retry}")), + ) + .await; + assert!( + LoginApp::cookies(&page) + .iter() + .any(|cookie| cookie.starts_with("__Host-piquel-step-up=;")), + "the retry marker is used up" + ); + assert_eq!(page.status(), StatusCode::OK); + assert_eq!(Flow::text(page).await, "settings"); + + // An API that refuses whatever the token holds gets one step-up sign-in, then an + // error on the retry instead of another redirect, even when its challenge names + // no requirement. + let page = app.send(Method::GET, "/stubborn", Some(&second)).await; + let login = LoginApp::location(&page); + assert_eq!(login, "/auth/login?return_to=%2Fstubborn&step_up=true"); + let callback = app.sign_in(&login, Some(&second)).await; + assert_eq!(LoginApp::location(&callback), "/stubborn"); + let third = LoginApp::cookie(&callback, "__Host-piquel-session"); + let retry = LoginApp::cookie(&callback, "__Host-piquel-step-up"); + let cookies = format!("{third}; {retry}"); + // Only the returning `GET` is the retry. + let other = app.send(Method::POST, "/stubborn", Some(&cookies)).await; + assert_eq!(LoginApp::cookies(&other), Vec::::new()); + let refused = app.send(Method::GET, "/stubborn", Some(&cookies)).await; + assert_eq!(refused.status(), StatusCode::FORBIDDEN); + + // An ordinary sign-in drops a marker its return never used. + let page = app.send(Method::GET, "/stubborn", Some(&third)).await; + let callback = app.sign_in(&LoginApp::location(&page), Some(&third)).await; + let fourth = LoginApp::cookie(&callback, "__Host-piquel-session"); + let unused = LoginApp::cookie(&callback, "__Host-piquel-step-up"); + let callback = app.sign_in("/auth/login", Some(&fourth)).await; + assert!( + LoginApp::cookies(&callback) + .iter() + .any(|cookie| cookie.starts_with("__Host-piquel-step-up=;")), + "the unused marker {unused} is dropped" + ); +} diff --git a/apps/auth-service/src/oidc/tests/step_up.rs b/apps/auth-service/src/oidc/tests/step_up.rs new file mode 100644 index 000000000..95c960ade --- /dev/null +++ b/apps/auth-service/src/oidc/tests/step_up.rs @@ -0,0 +1,189 @@ +//! Authentication class targets (`acr_values`), recorded authentication and probation sign-ins. + +use super::*; +use crate::recovery::ProbationPasskey; +use crate::security::Credential; +use piquel_common::RecoveryId; +use piquel_repository::{InsertPasskey, InsertRecovery}; + +/// Tokens report the class and time of the grant's authentication: a refresh keeps +/// them after the session re-authenticates, and `acr_values` makes a weaker session +/// sign in again while unknown values are ignored. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn acr_targets_and_grants_keep_their_authentication() { + let mut flow = Flow::new(true, true).await; + let code = flow.code(REFRESH_SCOPES).await; + let (tokens, claims) = flow + .id_token( + flow.exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await, + ) + .await; + assert_eq!(claims["acr"], Acr::PhishingResistant.as_str()); + assert_eq!(claims["amr"], json!(["pop", "mfa", "user"])); + let session = claims["sid"] + .as_str() + .expect("sid") + .parse() + .expect("session ID"); + flow.app + .database + .sessions() + .confirm_passkey( + session, + PasskeyId::new(), + Utc::now() + chrono::Duration::minutes(5), + ) + .await + .expect("re-authenticate"); + let (_, refreshed) = flow + .id_token( + flow.refresh(tokens["refresh_token"].as_str().expect("refresh token")) + .await, + ) + .await; + assert_eq!(refreshed["auth_time"], claims["auth_time"]); + assert_eq!(refreshed["acr"], claims["acr"]); + + flow.sign_in_again(AuthenticationMethod::Federation).await; + let phr = [("acr_values", "urn:example:gold phr")]; + let response = flow + .authorize_with( + Method::GET, + Scope::OpenId.as_str(), + Some(Prompt::None.as_str()), + &phr, + ) + .await; + assert_eq!( + parameter(&flow.client_redirect(&response), "error"), + OAuthCode::LoginRequired.as_str() + ); + let response = flow + .authorize_with(Method::GET, Scope::OpenId.as_str(), None, &phr) + .await; + let login = location(&response); + assert_eq!(login.path(), routes::page::LOGIN); + assert_eq!(parameter(&login, "acr"), Acr::PhishingResistant.as_str()); + for acr_values in ["urn:example:gold", "urn:piquel:acr:social phr"] { + let response = flow + .authorize_with( + Method::GET, + Scope::OpenId.as_str(), + Some(Prompt::None.as_str()), + &[("acr_values", acr_values)], + ) + .await; + let code = parameter(&flow.client_redirect(&response), "code"); + let (_, claims) = flow + .id_token( + flow.exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await, + ) + .await; + assert_eq!(claims["acr"], Acr::Social.as_str(), "{acr_values}"); + assert_eq!(claims["amr"], json!(["fed"])); + } +} + +/// A browser that signed in for an authorization with a recovered passkey during +/// its probation cannot reach `phr` by signing in again, so the client hears +/// `unmet_authentication_requirements` instead of its user looping through +/// sign-in. A social sign-in, which a passkey could still step up, and a +/// probation sign-in from before the request go to sign in, as before. Without a +/// target, a probation sign-in is enough. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_probation_sign_in_short_of_the_target_answers_the_client() { + let mut flow = Flow::new(true, true).await; + flow.sign_in_again(AuthenticationMethod::Federation).await; + let phr = [("acr_values", "phr")]; + let response = flow + .authorize_with(Method::GET, Scope::OpenId.as_str(), None, &phr) + .await; + let transaction = parameter(&location(&response), "transaction"); + let resume = format!( + "{}?transaction={transaction}", + routes::oidc::AUTHORIZE_RESUME + ); + + flow.sign_in_again(AuthenticationMethod::Federation).await; + let response = flow.request(Method::GET, &resume, &[], None).await; + assert_eq!(location(&response).path(), routes::page::LOGIN, "social"); + + let database = flow.app.database.clone(); + let passkey = PasskeyId::new(); + database + .passkeys() + .insert(&InsertPasskey { + id: passkey, + credential_id: passkey.as_uuid().as_bytes().to_vec(), + user_id: flow.user_id, + credential: json!({}), + friendly_name: "Recovered".into(), + }) + .await + .expect("passkey"); + let recovery = RecoveryId::new(); + database + .recoveries() + .insert(&InsertRecovery { + id: recovery, + user_id: flow.user_id, + secret_digest: &recovery.as_uuid().as_bytes().repeat(2), + expires_at: Utc::now() + chrono::Duration::hours(1), + }) + .await + .expect("recovery"); + let probation = crate::recovery::PROBATION; + let mut recoveries = database.recoveries(); + let completed = recoveries + .complete(flow.user_id, recovery, passkey, probation) + .await; + assert!(completed.expect("complete")); + let stored = recoveries + .find(recovery) + .await + .expect("lookup") + .expect("recovery"); + let credential = Credential::Probation(ProbationPasskey::of(&stored).expect("probation")); + let user_id = flow.user_id; + let probation_sign_in = || async { + let mut tx = database.begin().await.expect("transaction"); + let session = Session::create(&mut tx, RequestContext::TEST, user_id, credential).await; + tx.commit().await.expect("commit"); + let cookie = BrowserCookie::Session.as_str(); + format!("{cookie}={}", session.expect("session").encoded()) + }; + let before_the_request = probation_sign_in().await; + let response = flow + .authorize_with(Method::GET, Scope::OpenId.as_str(), None, &phr) + .await; + let transaction = parameter(&location(&response), "transaction"); + let resume = format!( + "{}?transaction={transaction}", + routes::oidc::AUTHORIZE_RESUME + ); + flow.cookie = before_the_request; + let response = flow.request(Method::GET, &resume, &[], None).await; + assert_eq!(location(&response).path(), routes::page::LOGIN, "not fresh"); + + flow.cookie = probation_sign_in().await; + let response = flow.request(Method::GET, &resume, &[], None).await; + assert_eq!( + parameter(&flow.client_redirect(&response), "error"), + OAuthCode::UnmetAuthenticationRequirements.as_str() + ); + // Signing in again for a request without a target is enough. + let response = flow.authorize(Scope::OpenId.as_str(), Some("login")).await; + let transaction = parameter(&location(&response), "transaction"); + let resume = format!( + "{}?transaction={transaction}", + routes::oidc::AUTHORIZE_RESUME + ); + flow.cookie = probation_sign_in().await; + let response = flow.request(Method::GET, &resume, &[], None).await; + let code = parameter(&flow.client_redirect(&response), "code"); + assert!(!code.is_empty(), "no target, no refusal"); +} diff --git a/apps/auth-service/src/oidc/tests/tokens.rs b/apps/auth-service/src/oidc/tests/tokens.rs new file mode 100644 index 000000000..fe2034cf5 --- /dev/null +++ b/apps/auth-service/src/oidc/tests/tokens.rs @@ -0,0 +1,427 @@ +//! Token exchange and refresh: rotation, replay, concurrency, key changes, policy and claims. + +use super::*; +use crate::config::PolicyLinks; +use piquel_common::clients::{AllowedScopes, ScopeName}; +use piquel_common::events::GrantRevocation; + +/// Checks refresh narrowing, replay revocation, client binding and logout. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +#[expect( + clippy::too_many_lines, + reason = "The scenario follows one refresh family through narrowing, replay and logout." +)] +async fn confidential_refresh_rotation_logout_and_client_binding() { + let flow = Flow::new(true, true).await; + let code = flow.code(EMAIL_REFRESH_SCOPES).await; + assert_eq!( + flow.exchange(&code, Flow::verifier(), None).await.status(), + StatusCode::UNAUTHORIZED + ); + 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 claims: IdTokenClaims = flow + .app + .keys + .current() + .expect("fresh keys") + .verify( + tokens["id_token"] + .as_str() + .expect("token response contains an ID token"), + TokenType::Id, + &flow.app.issuer, + ) + .expect("verify confidential client ID token"); + assert_eq!( + claims.profile.email, + Some(format!("{}@example.com", flow.user_id)) + ); + assert_eq!(claims.profile.email_verified, Some(true)); + let old = tokens["refresh_token"] + .as_str() + .expect("token response contains a refresh token"); + let other = Flow::new(false, true).await; + assert_eq!(other.refresh(old).await.status(), StatusCode::BAD_REQUEST); + let invalid = flow + .request( + Method::POST, + "/oauth/token", + &[ + ("grant_type", GrantType::RefreshToken.as_str()), + ("client_id", flow.client.id.as_str()), + ("refresh_token", old), + ("scope", UNGRANTED_SCOPES), + ], + flow.basic.as_deref(), + ) + .await; + assert_eq!(invalid.status(), StatusCode::BAD_REQUEST); + assert_eq!( + Flow::json(invalid).await["error"], + OAuthCode::InvalidScope.as_str() + ); + let response = flow + .request( + Method::POST, + "/oauth/token", + &[ + ("grant_type", GrantType::RefreshToken.as_str()), + ("client_id", flow.client.id.as_str()), + ("refresh_token", old), + ("scope", Scope::OpenId.as_str()), + ], + flow.basic.as_deref(), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let narrowed = Flow::json(response).await; + assert_eq!(narrowed["scope"], Scope::OpenId.as_str()); + let narrowed_claims: IdTokenClaims = flow + .app + .keys + .current() + .expect("fresh keys") + .verify( + narrowed["id_token"] + .as_str() + .expect("refresh response contains an ID token"), + TokenType::Id, + &flow.app.issuer, + ) + .expect("verify narrowed ID token"); + assert!(narrowed_claims.profile.email.is_none()); + let fresh = narrowed["refresh_token"] + .as_str() + .expect("refresh response contains the rotated token") + .to_owned(); + assert_eq!(flow.refresh(old).await.status(), StatusCode::BAD_REQUEST); + assert_eq!(flow.refresh(&fresh).await.status(), StatusCode::BAD_REQUEST); + let code = flow.code(REFRESH_SCOPES).await; + let response = flow + .exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await; + let tokens = Flow::json(response).await; + let response = flow + .request( + Method::POST, + routes::page::LOGOUT, + &[ + ("client_id", flow.client.id.as_str()), + ( + "post_logout_redirect_uri", + flow.client.post_logout_uris[0].as_str(), + ), + ], + None, + ) + .await; + assert_eq!( + location(&response).as_str(), + flow.client.post_logout_uris[0].as_str() + ); + assert!( + response.headers()[header::SET_COOKIE] + .to_str() + .expect("Set-Cookie header is valid text") + .contains("Max-Age=0") + ); + assert_eq!( + flow.refresh( + tokens["refresh_token"] + .as_str() + .expect("token response contains a refresh token") + ) + .await + .status(), + StatusCode::BAD_REQUEST + ); + assert_eq!( + parameter( + &flow.client_redirect( + &flow + .authorize(Scope::OpenId.as_str(), Some(Prompt::None.as_str())) + .await + ), + "error" + ), + OAuthCode::LoginRequired.as_str() + ); + let events = flow.events().await; + assert!( + matches!( + &events[0], + DomainEvent::SessionRevoked { + reason: RevocationReason::RelyingPartyLogout { client_id }, + .. + } if *client_id == flow.client.id + ), + "{events:?}" + ); + assert!(events.iter().any(|event| matches!( + event, + DomainEvent::GrantRevoked { + reason: GrantRevocation::RefreshReplay, + .. + } + ))); +} + +/// 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 + ); + let events = flow.events().await; + let [ + DomainEvent::GrantRevoked { + family_id: revoked, + reason: GrantRevocation::CodeReplay, + .. + }, + DomainEvent::CodeReplayed { .. }, + DomainEvent::GrantIssued { + family_id: Some(issued), + .. + }, + .., + ] = events.as_slice() + else { + panic!("{events:?}"); + }; + assert_eq!(revoked, issued, "the replay revoked the code's own family"); +} + +/// The same refresh token, rotated on two replicas at once, rotates exactly once. The +/// other attempt is a replay, which revokes the family. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn concurrent_refresh_across_replicas_rotates_once() { + let flow = Flow::new(true, true).await; + let replicas = Replicas::new().await; + let (a, b) = (flow.on(&replicas.a), flow.on(&replicas.b)); + let code = a.code(REFRESH_SCOPES).await; + let response = b + .exchange(&code, Flow::verifier(), b.basic.as_deref()) + .await; + assert_eq!(response.status(), StatusCode::OK); + let token = Flow::json(response).await["refresh_token"] + .as_str() + .expect("token response contains a refresh token") + .to_owned(); + let (first, second) = tokio::join!(a.refresh(&token), b.refresh(&token)); + let (rotated, replayed) = if first.status() == StatusCode::OK { + (first, second) + } else { + (second, first) + }; + assert_eq!(rotated.status(), StatusCode::OK); + assert_eq!(replayed.status(), StatusCode::BAD_REQUEST); + let rotated = Flow::json(rotated).await["refresh_token"] + .as_str() + .expect("refresh response contains the rotated token") + .to_owned(); + assert_eq!( + a.refresh(&rotated).await.status(), + StatusCode::BAD_REQUEST, + "the replay revoked the family" + ); +} + +/// A new signing key and a new token digest key leave outstanding codes and +/// refresh tokens valid, since the old digest key is still accepted. What +/// replaces them is digested under the new key alone. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn changing_keys_keeps_codes_and_refresh_tokens() { + let flow = Flow::new(true, true).await; + let code = flow.code(REFRESH_SCOPES).await; + let tokens = Flow::json( + flow.exchange( + &flow.code(REFRESH_SCOPES).await, + Flow::verifier(), + flow.basic.as_deref(), + ) + .await, + ) + .await; + let token = tokens["refresh_token"].as_str().expect("refresh token"); + let app = OidcApplication::new( + flow.app.database.clone(), + &OidcConfig { + origin: flow.app.issuer.parse().expect("issuer"), + digest_keys: Arc::new(TokenDigestKeys::new( + TokenDigestKey::derive(&[8; 32]).expect("new digest key"), + Some(TokenDigestKey::derive(&[7; 32]).expect("old digest key")), + )), + policies: PolicyLinks::on(&crate::tests::WEB_ORIGIN.parse().expect("web origin")), + }, + SigningKeys::new(KeySet::single( + Rs256Key::generate("rotated").expect("new signing key"), + )), + ) + .expect("OIDC application"); + let changed = Flow { + router: app.clone().routes(), + app, + ..flow.clone() + }; + let exchanged = changed + .exchange(&code, Flow::verifier(), changed.basic.as_deref()) + .await; + assert_eq!(exchanged.status(), StatusCode::OK); + let refreshed = changed.refresh(token).await; + assert_eq!(refreshed.status(), StatusCode::OK); + let rotated = Flow::json(refreshed).await["refresh_token"] + .as_str() + .expect("rotated refresh token") + .to_owned(); + assert_eq!( + flow.refresh(&rotated).await.status(), + StatusCode::BAD_REQUEST, + "only the new digest key made the rotated token" + ); + assert_eq!(changed.refresh(&rotated).await.status(), StatusCode::OK); +} + +/// Checks that policy reductions reject new requests and invalidate outstanding grants, +/// and that unsafe logout redirects are refused. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn policy_reduction_blocks_outstanding_codes_and_refresh() { + let mut flow = Flow::new(false, true).await; + let code = flow.code(EMAIL_SCOPES).await; + let database = flow.app.database.clone(); + flow.client.allowed_scopes = + AllowedScopes::new([Scope::OpenId, Scope::OfflineAccess].map(ScopeName::from)) + .expect("reduced scopes"); + let client = flow.client.clone(); + crate::tests::replace(&database, &client) + .await + .expect("apply reduced client scope policy"); + assert_eq!( + flow.exchange(&code, Flow::verifier(), None).await.status(), + StatusCode::BAD_REQUEST + ); + assert_eq!( + parameter( + &flow.client_redirect(&flow.authorize(EMAIL_SCOPES, None).await), + "error" + ), + OAuthCode::InvalidScope.as_str() + ); + let code = flow.code(REFRESH_SCOPES).await; + let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await; + flow.client.allow_refresh = false; + let client = flow.client.clone(); + crate::tests::replace(&database, &client) + .await + .expect("disable client refresh permission"); + assert_eq!( + flow.refresh( + tokens["refresh_token"] + .as_str() + .expect("token response contains a refresh token") + ) + .await + .status(), + StatusCode::BAD_REQUEST + ); + let response = flow + .request( + Method::GET, + "/oidc/logout?client_id=unknown&post_logout_redirect_uri=https%3A%2F%2Fevil.example", + &[], + None, + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); +} + +/// A rename bumps the profile version, and the next token carries the new +/// `preferred_username`. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn renames_reach_the_next_token() { + let flow = Flow::new(true, true).await; + let code = flow.code(PROFILE_REFRESH_SCOPES).await; + let (tokens, claims) = flow + .id_token( + flow.exchange(&code, Flow::verifier(), flow.basic.as_deref()) + .await, + ) + .await; + let database = &flow.app.database; + let user = database + .users() + .find_by_id(flow.user_id) + .await + .expect("lookup") + .expect("user"); + assert_eq!(claims["preferred_username"], user.handle.as_str()); + let renamed = + Handle::parse(&format!("renamed-{}", &flow.user_id.to_string()[24..])).expect("handle"); + let mut tx = database.begin().await.expect("transaction"); + assert!( + tx.rename_handle(flow.user_id, &renamed) + .await + .expect("rename") + ); + tx.commit().await.expect("commit"); + let (_, refreshed) = flow + .id_token( + flow.refresh(tokens["refresh_token"].as_str().expect("refresh token")) + .await, + ) + .await; + assert_eq!(refreshed["preferred_username"], renamed.as_str()); + assert_eq!(refreshed["profile_version"], user.profile_version + 1); +} diff --git a/apps/auth-service/src/passkey/tests.rs b/apps/auth-service/src/passkey/tests.rs deleted file mode 100644 index c295439f6..000000000 --- a/apps/auth-service/src/passkey/tests.rs +++ /dev/null @@ -1,1851 +0,0 @@ -//! Focused name validation and database-backed `WebAuthn` ceremony invariants. - -use super::*; -use crate::{ - account::AccountApplication, - tests::{AUTH_ORIGIN, Browser, OWN_PAGE, Replicas, change, pending_sign_in, register}, -}; -use axum::{ - body::{Body, to_bytes}, - http::{Method, Request}, -}; -use piquel_common::{ - TokenId, - events::{RevocationReason, SignInFailure}, - protocol::claims::{Acr, Amr}, -}; -use piquel_crypto::Secret; -use piquel_repository::{DatabaseConfig, SessionAuthentication, StoredSession}; -use serde_json::json; -use tower::ServiceExt; -use url::Url; -use webauthn_authenticator_rs::{WebauthnAuthenticator, softpasskey::SoftPasskey}; - -/// Maximum JSON response accepted by the software browser fixture. -const MAX_RESPONSE_BYTES: usize = 64 * 1024; - -/// Names count Unicode characters, preserve spacing and reject blank/control input. -#[test] -fn display_and_passkey_names_share_unicode_validation() { - for valid in [" Alice ".to_owned(), "é".repeat(80)] { - assert_eq!( - DisplayName::parse(valid.clone()) - .expect("display name") - .as_str(), - valid - ); - assert_eq!( - PasskeyName::parse(valid.clone()) - .expect("passkey name") - .as_str(), - valid - ); - } - for invalid in [String::new(), " \t ".into(), "a\0b".into(), "é".repeat(81)] { - assert!(matches!( - DisplayName::parse(invalid.clone()), - Err(PasskeyError::InvalidDisplayName) - )); - assert!(matches!( - PasskeyName::parse(invalid), - Err(PasskeyError::InvalidPasskeyName) - )); - } -} - -/// Typed payloads retain the stored ceremony representation and reject wrong consumers. -#[test] -fn typed_ceremonies_preserve_persistence_and_check_the_expected_payload() { - use ceremonies::CeremonyState; - - let user_id = UserId::new(); - let session_id = piquel_common::SessionId::new(); - let origin = Url::parse("https://auth.piquel.fr").expect("origin"); - let webauthn = WebauthnBuilder::new("auth.piquel.fr", &origin) - .expect("builder") - .build() - .expect("WebAuthn"); - let (_, state) = webauthn - .start_discoverable_authentication() - .expect("challenge"); - let encoded_state = serde_json::to_value(&state).expect("state"); - let ceremony = Ceremony::Discover(DiscoverCeremony { state }); - assert_eq!( - ceremony.kind(), - piquel_repository::CeremonyKind::Authentication - ); - let encoded = serde_json::to_value(ceremony).expect("ceremony"); - assert_eq!(encoded, json!({"Discover":{"state":encoded_state}})); - let stored = || serde_json::from_value(encoded.clone()).expect("stored ceremony"); - assert!(AuthenticationCeremony::extract(stored()).is_some()); - assert!(RegistrationCeremony::extract(stored()).is_none()); - assert!(EnrollmentCeremony::extract(stored()).is_none()); - assert!(ConfirmationCeremony::extract(stored()).is_none()); - - let (_, state) = webauthn - .start_passkey_registration(user_id.as_uuid(), "alice", "Alice", None) - .expect("registration"); - let enrollment = Ceremony::Enroll(EnrollmentCeremony { - user_id, - session_id, - state, - }); - assert_eq!(enrollment.kind(), EnrollmentCeremony::KIND); - assert!(EnrollmentCeremony::extract(enrollment).is_some()); -} - -/// Sign-in and confirmation accept only an active account's passkey; the -/// owner's undo of a recovery accepts a disabled account's too, without a -/// credential to sign in with. An account being deleted has nothing to accept. -#[test] -fn only_an_undo_accepts_a_disabled_accounts_passkey() { - let passkey = PasskeyId::new(); - let credential = Credential::Passkey(passkey); - let signs_in = |status| ::accept(status, passkey, credential); - assert_eq!(signs_in(AccountStatus::Active).ok(), Some(credential)); - for status in [AccountStatus::Disabled, AccountStatus::Deleting] { - assert!(matches!( - signs_in(status), - Err(PasskeyError::AccountInactive) - )); - } - let undoes = |status| ::accept(status, passkey, credential); - assert!(matches!(undoes(AccountStatus::Active), Ok(Accepted::Active(id)) if id == passkey)); - assert!(matches!(undoes(AccountStatus::Disabled), Ok(Accepted::Disabled(id)) if id == passkey)); - assert!(matches!( - undoes(AccountStatus::Deleting), - Err(PasskeyError::AccountInactive) - )); -} - -/// Isolated account and counter-capable software authenticator for database -/// scenarios. The recovery scenarios use it too. -pub(crate) struct Fixture { - /// Routes and persistence under test. - app: PasskeyApplication, - /// Where requests go: the passkey routes, or a replica of the whole service. - router: axum::Router, - /// Software credential capable of user verification and monotonic counters. - authenticator: WebauthnAuthenticator, - /// HTTPS origin passed to the authenticator. - origin: Url, - /// Seeded account owning the software credential. - pub(crate) user_id: UserId, - /// Seeded passkey row used for rename and last-key removal checks. - pub(crate) key_id: PasskeyId, - /// Unique seeded username for identified authentication. - pub(crate) username: String, - /// The signing credential's ID, which an account picker's challenge lists. - credential_id: Vec, -} -impl Fixture { - /// Seeds an account and passkey in the explicitly configured isolated database. - pub(crate) async fn new() -> Self { - let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") - .required() - .expect("isolated test database"); - let database = Database::connect( - DatabaseConfig::new(&url, 5, std::time::Duration::from_secs(5)).expect("configuration"), - ) - .await - .expect("database"); - database.run_migrations().await.expect("migrations"); - let origin = Url::parse(AUTH_ORIGIN).expect("origin"); - let config = crate::AuthConfig::test(&AUTH_ORIGIN.parse().expect("origin")); - let keys = crate::KeyStore::new(database.clone(), Arc::clone(&config.key_encryption_key)) - .start() - .await - .expect("signing keys"); - let oidc = OidcApplication::new(database.clone(), &config.oidc, keys).expect("OIDC app"); - let app = PasskeyApplication::new(database, &config.passkey, oidc).expect("passkey app"); - let user_id = UserId::new(); - let username = format!("key-{}", &TokenId::new().to_string()[24..]); - app.database - .users() - .insert(&InsertUser { - id: user_id, - handle: Handle::parse(&username).expect("handle"), - display_name: "Test user".into(), - }) - .await - .expect("user"); - let (key_id, credential_id, authenticator) = - Self::seed_passkey(&app, &origin, user_id, &username, "Original key").await; - Self { - router: app - .clone() - .routes() - .merge(AccountApplication::new(app.database.clone()).routes()), - app, - authenticator, - origin, - user_id, - key_id, - username, - credential_id, - } - } - /// Stores a new software authenticator's passkey named `name` for `user_id`. - /// The authenticator supports UV and signed counters, but not resident - /// credentials. Browser tests cover production resident signup; this uses the - /// library's normal registration. - async fn seed_passkey( - app: &PasskeyApplication, - origin: &Url, - user_id: UserId, - username: &str, - name: &str, - ) -> (PasskeyId, Vec, WebauthnAuthenticator) { - let (challenge, state) = app - .webauthn - .start_passkey_registration(user_id.as_uuid(), username, "Test user", None) - .expect("registration"); - let mut authenticator = WebauthnAuthenticator::new(SoftPasskey::new(true)); - let registration = authenticator - .do_registration(origin.clone(), challenge) - .expect("software registration"); - let key = app - .webauthn - .finish_passkey_registration(®istration, &state) - .expect("verified registration"); - let id = PasskeyId::new(); - let credential_id = key.cred_id().as_ref().to_vec(); - app.database - .passkeys() - .insert(&InsertPasskey { - id, - credential_id: credential_id.clone(), - user_id, - credential: serde_json::to_value(key).expect("credential"), - friendly_name: name.into(), - }) - .await - .expect("stored key"); - (id, credential_id, authenticator) - } - /// Signs with `authenticator` from now on, and returns the one that signed - /// until now. - pub(crate) fn replace_authenticator( - &mut self, - authenticator: WebauthnAuthenticator, - ) -> WebauthnAuthenticator { - std::mem::replace(&mut self.authenticator, authenticator) - } - /// Stores another passkey named `name` on the account, and signs with it from - /// now on. - pub(crate) async fn switch_passkey(&mut self, name: &str) -> PasskeyId { - let (id, credential_id, authenticator) = - Self::seed_passkey(&self.app, &self.origin, self.user_id, &self.username, name).await; - self.authenticator = authenticator; - self.credential_id = credential_id; - id - } - /// Sends the next requests to `router`, such as one of [`Replicas`]. - fn on(&mut self, router: &axum::Router) -> &mut Self { - self.router = router.clone(); - self - } - /// The scenario database. - pub(crate) const fn database(&self) -> &Database { - &self.app.database - } - /// Sends a JSON request from the auth origin with the supplied cookies. - pub(crate) async fn request( - &self, - path: &str, - method: Method, - cookies: &str, - body: Value, - ) -> Response { - let request = Request::builder() - .method(method) - .uri(path) - .header(header::ORIGIN, AUTH_ORIGIN) - .header(header::CONTENT_TYPE, "application/json") - .header(header::COOKIE, cookies); - self.send(request, body.to_string()).await - } - /// Sends `request` with the CSRF header and `body`. - async fn send(&self, request: axum::http::request::Builder, body: String) -> Response { - self.router - .clone() - .oneshot( - request - .extension(crate::security::RequestContext::TEST) - .header("x-piquel-csrf", "1") - .body(Body::from(body)) - .expect("request"), - ) - .await - .expect("response") - } - /// Starts a ceremony and returns its challenge JSON and browser-binding cookie. - pub(crate) async fn start(&self, path: &str, cookies: &str, body: Value) -> (Value, String) { - let response = self.request(path, Method::POST, cookies, body).await; - assert_eq!(response.status(), StatusCode::OK); - let cookie = Self::cookie(&response); - (Self::json(response).await, cookie) - } - /// Reads a response's JSON body. - pub(crate) async fn json(response: Response) -> Value { - serde_json::from_slice( - &to_bytes(response.into_body(), MAX_RESPONSE_BYTES) - .await - .expect("body"), - ) - .expect("JSON") - } - /// Extracts the cookie pair from a response for the next simulated browser request. - pub(crate) fn cookie(response: &Response) -> String { - response.headers()[header::SET_COOKIE] - .to_str() - .expect("cookie") - .split(';') - .next() - .expect("cookie pair") - .to_owned() - } - /// Signs a started authentication challenge using the software credential. - pub(crate) fn assertion(&mut self, started: &Value) -> PublicKeyCredential { - self.assertion_for(self.origin.clone(), started) - } - /// Signs a started authentication challenge for a page on `origin`, within - /// auth's RP ID. The software credential is not discoverable, so an account - /// picker's challenge gets it listed, and the answer names its account as a - /// discoverable one would. - fn assertion_for(&mut self, origin: Url, started: &Value) -> PublicKeyCredential { - let mut challenge: RequestChallengeResponse = - serde_json::from_value(started["public_key"].clone()) - .expect("authentication challenge"); - let picker = challenge.public_key.allow_credentials.is_empty(); - if picker { - challenge.public_key.allow_credentials = vec![webauthn_rs_proto::AllowCredentials { - type_: "public-key".into(), - id: self.credential_id.clone().into(), - transports: None, - }]; - } - let mut credential = self - .authenticator - .do_authentication(origin, challenge) - .expect("software assertion"); - if picker { - credential.response.user_handle = - Some(self.user_id.as_uuid().as_bytes().to_vec().into()); - } - credential - } - /// Completes an identified login and returns the new session cookie. - async fn login(&mut self) -> String { - self.login_from("").await - } - /// Completes an identified login in a browser holding the `session` cookie pair, - /// if any, and returns the session cookie it sets. - async fn login_from(&mut self, session: &str) -> String { - let (started, browser) = self - .start( - "/webauthn/authenticate/start", - "", - json!({"handle":self.username}), - ) - .await; - let assertion = self.assertion(&started); - let response = self - .request( - "/webauthn/authenticate/finish", - Method::POST, - &format!("{session}; {browser}"), - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - Self::cookie(&response) - } - /// Finds the active session a cookie pair names. - pub(crate) async fn session(&self, cookie: &str) -> Option { - let secret = cookie - .split_once('=') - .and_then(|(_, value)| Secret::parse(value).ok()) - .expect("session cookie"); - self.app - .database - .sessions() - .find_active_by_browser_secret(secret.digest().as_bytes()) - .await - .expect("session lookup") - } - /// Lists the events recorded about the seeded account, newest first. - pub(crate) async fn events(&self) -> Vec { - self.app - .database - .events() - .history_for_user(self.user_id, 100) - .await - .expect("history") - .into_iter() - .map(|stored| stored.event.known().cloned().expect("a known event")) - .collect() - } - /// Answers a started registration challenge with a fresh software credential. - pub(crate) fn credential(&self, started: &Value) -> RegisterPublicKeyCredential { - self.new_authenticator(started).0 - } - /// Answers a started registration challenge with a new software - /// authenticator, and returns the credential and the authenticator, which can - /// sign with it once stored as [`Self::authenticator`]. - pub(crate) fn new_authenticator( - &self, - started: &Value, - ) -> ( - RegisterPublicKeyCredential, - WebauthnAuthenticator, - ) { - let challenge = - serde_json::from_value(started["public_key"].clone()).expect("registration challenge"); - let mut authenticator = WebauthnAuthenticator::new(SoftPasskey::new(true)); - let credential = authenticator - .do_registration(self.origin.clone(), challenge) - .expect("software registration"); - (credential, authenticator) - } - /// Registers a new account with a fresh software credential; returns the finish response. - async fn register(&self, cookies: &str, body: Value) -> Response { - let (started, browser) = self.start("/webauthn/register/start", cookies, body).await; - let credential = self.credential(&started); - self.request( - "/webauthn/register/finish", - Method::POST, - &format!("{cookies}; {browser}"), - json!({"ceremony_id":started["ceremony_id"],"credential":credential}), - ) - .await - } -} - -/// Signup normalizes the handle, and refuses invalid, reserved and taken ones with -/// their codes; whether a handle is taken, only once admitted. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn signup_applies_the_handle_rules() { - let mut fixture = Fixture::new().await; - for (handle, status, code) in [ - ("a_b", StatusCode::BAD_REQUEST, "handle_invalid"), - ("adm1n", StatusCode::BAD_REQUEST, "handle_reserved"), - ( - fixture.username.as_str(), - StatusCode::CONFLICT, - "handle_taken", - ), - ] { - let response = fixture - .request( - "/webauthn/register/start", - Method::POST, - "", - json!({"handle": handle}), - ) - .await; - assert_eq!(response.status(), status, "{handle}"); - assert_eq!(Fixture::json(response).await["code"], code, "{handle}"); - } - let (started, _) = fixture - .start( - "/webauthn/register/start", - "", - json!({"handle": " New-User "}), - ) - .await; - assert_eq!( - started["public_key"]["publicKey"]["user"]["name"], - "new-user" - ); - // Only an admitted signup learns whether a handle is held. - let invite_only = PasskeyApplication::new( - fixture.app.database.clone(), - &PasskeyConfig { - origin: AUTH_ORIGIN.parse().expect("origin"), - invite_required: true, - }, - fixture.app.oidc.clone(), - ) - .expect("passkey app"); - let taken = json!({"handle": fixture.username}); - let response = fixture - .on(&invite_only.routes()) - .request("/webauthn/register/start", Method::POST, "", taken) - .await; - assert_eq!(response.status(), StatusCode::FORBIDDEN); -} - -/// Checks that abandoned social signup state never attaches to unrelated registration. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn registration_attaches_a_pending_social_signup_only_when_it_names_it() { - let fixture = Fixture::new().await; - let secret = Secret::generate().expect("browser secret"); - let pending = pending_sign_in(&secret); - let database = fixture.app.database.clone(); - database - .federation() - .insert_pending(&pending) - .await - .expect("pending signup"); - let social = format!( - "{}={}", - BrowserCookie::FederationPending.as_str(), - secret.encoded() - ); - let response = fixture - .request( - "/webauthn/register/start", - Method::POST, - &social, - json!({"handle":"unrelated","pending_signup":TokenId::new()}), - ) - .await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - for (explicit, attached) in [(None, false), (Some(pending.id), true)] { - let username = format!("reg-{}", &TokenId::new().to_string()[24..]); - let response = fixture - .register( - &social, - json!({"handle":username,"pending_signup":explicit}), - ) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - let user = database - .users() - .find_active_by_handle(&Handle::parse(&username).expect("handle")) - .await - .expect("user") - .expect("registered"); - let owner = database - .federation() - .find_active(&pending.issuer, &pending.subject) - .await - .expect("identity") - .map(|identity| identity.user_id); - assert_eq!(owner, attached.then_some(user.id), "{username}"); - let passkeys = database.passkeys().list_active(user.id).await; - let sessions = database.sessions().list_active_for_user(user.id).await; - let [session] = &sessions.expect("sessions")[..] else { - panic!("one session"); - }; - let recorded = database.sessions().passkey(session.id).await; - let [passkey] = &passkeys.expect("passkeys")[..] else { - panic!("one passkey"); - }; - assert_eq!( - recorded.expect("passkey"), - Some(passkey.id), - "signed in by it" - ); - } -} - -/// Checks counter ordering under concurrent ceremony snapshots, records the -/// regression and prevents replay. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn overlapping_assertions_reject_old_counter_after_new_counter_commits() { - let mut fixture = Fixture::new().await; - let (older, browser) = fixture - .start( - "/webauthn/authenticate/start", - "", - json!({"handle":fixture.username}), - ) - .await; - let (newer, _) = fixture - .start( - "/webauthn/authenticate/start", - &browser, - json!({"handle":fixture.username}), - ) - .await; - let older_assertion = fixture.assertion(&older); - let newer_assertion = fixture.assertion(&newer); - let newer_body = json!({"ceremony_id":newer["ceremony_id"],"credential":newer_assertion}); - let response = fixture - .request( - "/webauthn/authenticate/finish", - Method::POST, - &browser, - newer_body.clone(), - ) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - let response = fixture - .request( - "/webauthn/authenticate/finish", - Method::POST, - &browser, - json!({"ceremony_id":older["ceremony_id"],"credential":older_assertion}), - ) - .await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert!(response.headers().get(header::SET_COOKIE).is_none()); - let response = fixture - .request( - "/webauthn/authenticate/finish", - Method::POST, - &browser, - newer_body, - ) - .await; - assert_eq!( - response.status(), - StatusCode::BAD_REQUEST, - "ceremony cannot replay" - ); - let keys = fixture - .app - .database - .passkeys() - .list_active(fixture.user_id) - .await - .expect("keys"); - assert_eq!( - keys[0].credential.pointer(CREDENTIAL_COUNTER_POINTER), - Some(&json!(2)) - ); - let events = fixture.events().await; - assert!( - matches!( - events.as_slice(), - [ - DomainEvent::SignInFailed { - method: AuthenticationMethod::Passkey, - reason: SignInFailure::CounterRegression, - }, - DomainEvent::SignedIn { - method: AuthenticationMethod::Passkey, - .. - }, - ] - ), - "the regression outlives its rolled-back authentication transaction; the replay is not recorded: {events:?}" - ); -} - -/// A copy of a passkey that signs behind the stored counter is rejected by `WebAuthn`'s -/// snapshot check, and the rejection is recorded like the locked check. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn lagging_counter_copy_is_rejected_and_recorded() { - let mut fixture = Fixture::new().await; - // Simulate the original authenticator having signed far ahead of this copy. - let mut passkeys = fixture.app.database.passkeys(); - let mut key = passkeys - .list_active(fixture.user_id) - .await - .expect("keys") - .remove(0); - *key.credential - .pointer_mut(CREDENTIAL_COUNTER_POINTER) - .expect("counter") = json!(100); - assert!( - passkeys - .update_after_authentication(&key.credential_id, &key.credential) - .await - .expect("advanced counter") - ); - let (started, browser) = fixture - .start( - "/webauthn/authenticate/start", - "", - json!({"handle":fixture.username}), - ) - .await; - let assertion = fixture.assertion(&started); - let response = fixture - .request( - "/webauthn/authenticate/finish", - Method::POST, - &browser, - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert!(response.headers().get(header::SET_COOKIE).is_none()); - assert_eq!( - fixture.events().await, - [DomainEvent::SignInFailed { - method: AuthenticationMethod::Passkey, - reason: SignInFailure::CounterRegression, - }] - ); -} - -/// Checks browser binding, and that a passkey confirmation belongs to one session, -/// counts from its own time and is required only where an action needs it. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -#[expect( - clippy::too_many_lines, - reason = "Keep one session's confirmation lifecycle in a single scenario." -)] -async fn ceremonies_require_browser_binding_and_confirmation_belongs_to_one_session() { - let mut fixture = Fixture::new().await; - let (started, _) = fixture - .start( - "/webauthn/authenticate/start", - "", - json!({"handle":fixture.username}), - ) - .await; - let assertion = fixture.assertion(&started); - let body = json!({"ceremony_id":started["ceremony_id"],"credential":assertion}); - for cookies in [ - String::new(), - format!( - "{}={}", - BrowserCookie::Ceremony.as_str(), - Secret::generate().expect("browser secret").encoded() - ), - ] { - let response = fixture - .request( - "/webauthn/authenticate/finish", - Method::POST, - &cookies, - body.clone(), - ) - .await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert!(response.headers().get(header::SET_COOKIE).is_none()); - } - // A passkey sign-in confirms its session, so enrollment right after it prompts once. - let signed_in = fixture.login().await; - fixture - .start("/account/passkeys/enroll/start", &signed_in, json!({})) - .await; - // Another session of the same account, from social sign-in, is not confirmed. - let mut tx = fixture.app.database.begin().await.expect("transaction"); - let secret = security::Session::create( - &mut tx, - security::RequestContext::TEST, - fixture.user_id, - AuthenticationMethod::Federation.into(), - ) - .await - .expect("social session"); - tx.commit().await.expect("commit"); - let social = format!("{}={}", BrowserCookie::Session.as_str(), secret.encoded()); - let session_id = fixture - .app - .database - .sessions() - .find_active_by_browser_secret(secret.digest().as_bytes()) - .await - .expect("lookup") - .expect("session") - .id; - let path = format!("/account/passkeys/{}", fixture.key_id); - for (path, method) in [ - ("/account/passkeys/enroll/start", Method::POST), - (path.as_str(), Method::DELETE), - ] { - security::tests::assert_step_up_required( - fixture.request(path, method, &social, json!({})).await, - ) - .await; - } - let response = fixture - .request( - &path, - Method::PATCH, - &social, - json!({"friendly_name":"Renamed"}), - ) - .await; - assert_eq!( - response.status(), - StatusCode::NO_CONTENT, - "renaming needs no confirmation" - ); - // A confirmation proves possession for the session that started it only. - let (started, browser) = fixture - .start("/account/passkeys/confirm/start", &social, json!({})) - .await; - let assertion = fixture.assertion(&started); - let response = fixture - .request( - "/account/passkeys/confirm/finish", - Method::POST, - &format!("{signed_in}; {browser}"), - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await; - assert_eq!( - response.status(), - StatusCode::BAD_REQUEST, - "confirmation is bound to the initiating session" - ); - let (started, browser) = fixture - .start("/account/passkeys/confirm/start", &social, json!({})) - .await; - let assertion = fixture.assertion(&started); - let response = fixture - .request( - "/account/passkeys/confirm/finish", - Method::POST, - &format!("{social}; {browser}"), - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - // The confirmation replaces the cookie, so a copy of the old one gains nothing. - let stale = social; - let social = Fixture::cookie(&response); - assert!(fixture.session(&stale).await.is_none()); - assert_eq!( - fixture.session(&social).await.expect("same session").id, - session_id - ); - assert_eq!( - fixture.events().await.first(), - Some(&DomainEvent::PasskeyConfirmed { session_id }) - ); - let confirming = fixture.app.database.sessions().passkey(session_id).await; - assert_eq!(confirming.expect("passkey"), Some(fixture.key_id)); - let confirmed_at = || async { - fixture - .app - .database - .sessions() - .find_active_by_id(session_id) - .await - .expect("lookup") - .expect("session") - .passkey_confirmed_at - .expect("confirmed") - }; - let confirmed = confirmed_at().await; - // Confirmed actions do not extend the confirmation. - let (started, browser) = fixture - .start("/account/passkeys/enroll/start", &social, json!({})) - .await; - // The confirmation authorized enrollment at start; its lapsing at the authenticator - // must not discard the new credential. - fixture - .app - .database - .sessions() - .confirm_passkey( - session_id, - PasskeyId::new(), - confirmed - chrono::Duration::hours(1), - ) - .await - .expect("stale confirmation"); - let credential = fixture.credential(&started); - let response = fixture - .request( - "/account/passkeys/enroll/finish", - Method::POST, - &format!("{social}; {browser}"), - json!({"ceremony_id":started["ceremony_id"],"friendly_name":"Second","credential":credential}), - ) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - fixture - .app - .database - .sessions() - .confirm_passkey(session_id, PasskeyId::new(), confirmed) - .await - .expect("restore confirmation"); - // Removal revokes both other sessions, the passkey sign-in and this one. - let mut tx = fixture.app.database.begin().await.expect("transaction"); - security::Session::create( - &mut tx, - security::RequestContext::TEST, - fixture.user_id, - AuthenticationMethod::Federation.into(), - ) - .await - .expect("third session"); - tx.commit().await.expect("commit"); - let response = fixture - .request(&path, Method::DELETE, &social, json!({})) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - assert_eq!(confirmed_at().await, confirmed); - let events = fixture.events().await; - let removed = events - .iter() - .position(|event| { - *event - == DomainEvent::PasskeyRemoved { - passkey_id: fixture.key_id, - } - }) - .expect("removal recorded"); - let mut revoked: Vec<_> = events[..removed] - .iter() - .map(|event| match event { - DomainEvent::SessionRevoked { - session_id, - reason: RevocationReason::CredentialRemoved, - } => *session_id, - event => panic!("unexpected {event:?}"), - }) - .collect(); - revoked.dedup(); - assert_eq!(revoked.len(), 2, "one revocation per other session"); - assert!(!revoked.contains(&session_id), "the acting session stays"); - let keys = fixture - .app - .database - .passkeys() - .list_active(fixture.user_id) - .await - .expect("keys"); - assert_eq!(keys.len(), 1); - let response = fixture - .request( - &format!("/account/passkeys/{}", keys[0].id), - Method::DELETE, - &social, - json!({}), - ) - .await; - assert_eq!( - response.status(), - StatusCode::BAD_REQUEST, - "last passkey cannot be removed" - ); - assert!( - fixture.session(&signed_in).await.is_none(), - "removing a passkey revokes other sessions" - ); -} - -/// Handles are public, so handle sign-in refuses a handle without an active -/// account, and text that is no handle, before starting any ceremony. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn handle_sign_in_refuses_a_handle_without_an_account_at_once() { - let fixture = Fixture::new().await; - for handle in [ - format!("none-{}", &TokenId::new().to_string()[24..]), - "@not a handle".to_owned(), - ] { - let response = fixture - .request( - routes::passkey::AUTHENTICATE_START, - Method::POST, - "", - json!({ "handle": handle }), - ) - .await; - assert_eq!(response.status(), StatusCode::NOT_FOUND, "{handle}"); - assert!(response.headers().get(header::SET_COOKIE).is_none()); - assert_eq!( - Fixture::json(response).await["error"], - "No active account has this handle." - ); - } -} - -/// Signing in with a passkey in a browser holding a social session of the same -/// account confirms that session, keeping its ID but replacing its cookie. A -/// session records the passkey that signed it in, or confirmed it since; a social -/// one names none. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn passkey_sign_in_confirms_the_browsers_session() { - let mut fixture = Fixture::new().await; - let mut tx = fixture.app.database.begin().await.expect("transaction"); - let secret = security::Session::create( - &mut tx, - security::RequestContext::TEST, - fixture.user_id, - AuthenticationMethod::Federation.into(), - ) - .await - .expect("social session"); - tx.commit().await.expect("commit"); - let social = format!("{}={}", BrowserCookie::Session.as_str(), secret.encoded()); - let before = fixture.session(&social).await.expect("social session"); - assert_eq!( - SessionAuthentication::from(&before).acr, - Acr::Social, - "social sign-in is not phishing-resistant" - ); - let cookie = fixture.login_from(&social).await; - assert!(fixture.session(&social).await.is_none(), "old cookie ends"); - let after = fixture.session(&cookie).await.expect("same session"); - assert_eq!(after.id, before.id); - let authentication = SessionAuthentication::from(&after); - assert_eq!(authentication.acr, Acr::PhishingResistant); - assert_eq!( - authentication.amr, - [Amr::Pop, Amr::Mfa, Amr::User, Amr::Fed], - "both methods are reported" - ); - assert!(authentication.auth_time > before.authenticated_at); - - let database = fixture.app.database.clone(); - let passkey = async |session| { - let mut sessions = database.sessions(); - sessions.passkey(session).await.expect("passkey") - }; - assert_eq!( - passkey(before.id).await, - Some(fixture.key_id), - "confirmed by it" - ); - let mut tx = fixture.app.database.begin().await.expect("transaction"); - let other = security::Session::create( - &mut tx, - security::RequestContext::TEST, - fixture.user_id, - AuthenticationMethod::Federation.into(), - ) - .await - .expect("another social session"); - tx.commit().await.expect("commit"); - let other = format!("{}={}", BrowserCookie::Session.as_str(), other.encoded()); - let other = fixture.session(&other).await.expect("social session").id; - assert_eq!(passkey(other).await, None, "a social sign-in names none"); - let fresh = fixture.login().await; - let fresh = fixture.session(&fresh).await.expect("new session").id; - assert_eq!( - passkey(fresh).await, - Some(fixture.key_id), - "signed in by it" - ); - - // With two passkeys, the asserting one is recorded: signing in with the - // newer one, and confirming with it a session the older one signed in. - let newer = fixture.switch_passkey("Newer key").await; - let signed_in = fixture.login().await; - let signed_in = fixture.session(&signed_in).await.expect("new session").id; - assert_eq!(passkey(signed_in).await, Some(newer), "signed in by it"); - let (started, browser) = fixture - .start("/account/passkeys/confirm/start", &cookie, json!({})) - .await; - let assertion = fixture.assertion(&started); - let response = fixture - .request( - "/account/passkeys/confirm/finish", - Method::POST, - &format!("{cookie}; {browser}"), - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - assert_eq!(passkey(before.id).await, Some(newer), "confirmed by it"); -} - -/// A sign-in started on one replica finishes on the other, and signing out on one -/// ends the session on both. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn sign_in_and_logout_span_replicas() { - let mut fixture = Fixture::new().await; - let replicas = Replicas::new().await; - let username = json!({"handle":fixture.username}); - let (started, browser) = fixture - .on(&replicas.a) - .start("/webauthn/authenticate/start", "", username) - .await; - let assertion = fixture.assertion(&started); - let finished = fixture - .on(&replicas.b) - .request( - "/webauthn/authenticate/finish", - Method::POST, - &browser, - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await; - assert_eq!(finished.status(), StatusCode::NO_CONTENT); - let session = Fixture::cookie(&finished); - fixture.on(&replicas.a); - let read = fixture.request(routes::passkey::LIST, Method::GET, &session, json!({})); - assert_eq!(read.await.status(), StatusCode::OK); - let browser = Browser { - cookie: session.clone(), - ..Browser::signed_out() - }; - let logout = browser - .submit(&replicas.a, routes::page::LOGOUT, &[], OWN_PAGE) - .await; - assert_eq!(logout.status(), StatusCode::SEE_OTHER); - fixture.on(&replicas.b); - let read = fixture.request(routes::passkey::LIST, Method::GET, &session, json!({})); - assert_eq!(read.await.status(), StatusCode::UNAUTHORIZED); -} - -impl Fixture { - /// Signs in with the passkey, and returns the session cookie pair and every - /// secret the ceremony carried: its cookie and ID, the challenge and signature. - async fn login_with_secrets(&mut self) -> (String, Vec) { - let username = json!({"handle": self.username}); - let (started, browser) = self - .start("/webauthn/authenticate/start", "", username) - .await; - let assertion = self.assertion(&started); - let signature = - serde_json::to_value(&assertion).expect("assertion")["response"]["signature"] - .as_str() - .expect("signature") - .to_owned(); - let finished = self - .request( - "/webauthn/authenticate/finish", - Method::POST, - &browser, - json!({"ceremony_id": started["ceremony_id"], "credential": assertion}), - ) - .await; - assert_eq!(finished.status(), StatusCode::NO_CONTENT); - let session = Self::cookie(&finished); - let cookie = |pair: &str| pair.split_once('=').expect("cookie pair").1.to_owned(); - let secrets = vec![ - cookie(&session), - cookie(&browser), - started["ceremony_id"] - .as_str() - .expect("ceremony") - .to_owned(), - started["public_key"]["publicKey"]["challenge"] - .as_str() - .expect("challenge") - .to_owned(), - signature, - ]; - (session, secrets) - } - - /// Authorizes the trusted `client` for the browser holding `session`, exchanges - /// the code, and returns every secret the flow carried: the authorization - /// query's state, nonce and PKCE challenge, the code, its verifier and the tokens. - async fn exchange_with_secrets( - &self, - session: &str, - client: &piquel_common::clients::ClientRegistration, - ) -> Vec { - let verifier = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - let challenge = piquel_crypto::Pkce::challenge(verifier).expect("PKCE"); - let mut authorize = Url::parse(&format!("{AUTH_ORIGIN}/oauth/authorize")).expect("URL"); - authorize.query_pairs_mut().extend_pairs([ - ("response_type", "code"), - ("client_id", client.id.as_str()), - ("redirect_uri", client.redirect_uris[0].as_str()), - ("scope", "openid offline_access"), - ("state", "state-in-the-query"), - ("nonce", "nonce-in-the-query"), - ("code_challenge_method", "S256"), - ("code_challenge", &challenge), - ]); - let send = |request: Request| self.router.clone().oneshot(request); - let authorized = send( - Request::builder() - .uri(format!( - "{}?{}", - authorize.path(), - authorize.query().expect("query") - )) - .header(header::COOKIE, session) - .body(Body::empty()) - .expect("request"), - ) - .await - .expect("response"); - assert_eq!(authorized.status(), StatusCode::SEE_OTHER); - let redirect = Url::parse( - authorized.headers()[header::LOCATION] - .to_str() - .expect("location"), - ) - .expect("redirect"); - let code = redirect - .query_pairs() - .find(|(name, _)| name == "code") - .expect("code") - .1 - .into_owned(); - let form = url::form_urlencoded::Serializer::new(String::new()) - .extend_pairs([ - ("grant_type", "authorization_code"), - ("client_id", client.id.as_str()), - ("redirect_uri", client.redirect_uris[0].as_str()), - ("code", &code), - ("code_verifier", verifier), - ]) - .finish(); - let exchanged = send( - Request::builder() - .method(Method::POST) - .uri("/oauth/token") - .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") - .body(Body::from(form)) - .expect("request"), - ) - .await - .expect("response"); - assert_eq!(exchanged.status(), StatusCode::OK); - let tokens = Self::json(exchanged).await; - let mut secrets = vec![ - "state-in-the-query".to_owned(), - "nonce-in-the-query".to_owned(), - challenge, - code, - verifier.to_owned(), - ]; - for token in ["access_token", "id_token", "refresh_token"] { - secrets.push(tokens[token].as_str().expect("token").to_owned()); - } - secrets - } -} - -/// A passkey sign-in, then an authorization code exchanged for tokens, through -/// replicas of the whole service, export no secret: no cookie, ceremony, `WebAuthn` -/// challenge or assertion, authorization query, code, PKCE verifier or token. Each -/// request is one trace holding its queries, and the events it records are logged -/// in it. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn telemetry_exports_no_secret_of_a_sign_in_and_code_exchange() { - use piquel_telemetry::Telemetry; - - let capture = Telemetry::capture(crate::TELEMETRY_FILTER); - let mut fixture = Fixture::new().await; - let replicas = Replicas::new().await; - let client = piquel_common::clients::ClientRegistration { - trusted: true, - ..crate::tests::registration( - piquel_common::clients::ClientKind::Public, - "https://client.example", - ) - }; - crate::tests::register(&fixture.app.database, &client) - .await - .expect("client"); - let (session, mut secrets) = fixture.on(&replicas.a).login_with_secrets().await; - secrets.extend( - fixture - .on(&replicas.b) - .exchange_with_secrets(&session, &client) - .await, - ); - let exported = capture.exported_text(); - for secret in &secrets { - assert!( - exported.iter().all(|text| !text.contains(secret.as_str())), - "telemetry exported {secret}" - ); - } - - let spans = capture.spans(); - let exchange = spans - .iter() - .find(|span| span.name == "POST /oauth/token") - .expect("token request span"); - let trace = exchange.span_context.trace_id(); - assert!( - spans.iter().any(|span| { - span.span_context.trace_id() == trace - && span - .attributes - .iter() - .any(|attribute| attribute.key.as_str() == "db.query.text") - }), - "the exchange's queries are spans of its trace" - ); - let logged = capture - .logs() - .into_iter() - .find(|log| { - log.attributes_iter().any(|(key, value)| { - key.as_str() == "event.kind" && format!("{value:?}").contains("grant_issued") - }) - }) - .expect("the issued grant is logged"); - assert_eq!( - logged.trace_context().map(|context| context.trace_id), - Some(trace), - "the event's log line links to the exchange's trace" - ); -} - -/// A passkey proof of a handoff to the admin dashboard counts for that handoff -/// only: its ceremony is bound to the browser and session that started it, is -/// used once, and leaves the session's own confirmation as it was. A ceremony -/// confirming the session is no proof of a handoff. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn an_admin_proof_counts_for_its_handoff_only() { - let mut fixture = Fixture::new().await; - let cookie = fixture.login().await; - let session = fixture.session(&cookie).await.expect("session"); - let headers = |cookies: &str| { - let mut headers = HeaderMap::new(); - headers.insert(header::COOKIE, cookies.parse().expect("cookies")); - headers - }; - let owner = AccountService::new(fixture.database().clone()) - .owner(RequestContext::TEST, &headers(&cookie)) - .await - .expect("lookup") - .expect("signed in"); - let prove = async |fixture: &mut Fixture, start: &str| { - let (started, browser) = fixture.start(start, &cookie, json!({})).await; - let credential = fixture.assertion(&started); - let assertion = json!({"ceremony_id": started["ceremony_id"], "credential": credential}); - (assertion.to_string(), format!("{cookie}; {browser}")) - }; - - let (confirmation, browser) = prove(&mut fixture, routes::passkey::CONFIRM_START).await; - let refused = fixture - .app - .verify_admin_proof(&headers(&browser), &owner, &confirmation) - .await; - assert!(refused.is_err(), "a confirmation of the session"); - - let (assertion, browser) = prove(&mut fixture, routes::passkey::ADMIN_PROOF_START).await; - let refused = fixture - .app - .verify_admin_proof(&headers(&cookie), &owner, &assertion) - .await; - assert!(refused.is_err(), "another browser"); - let proof = fixture - .app - .verify_admin_proof(&headers(&browser), &owner, &assertion) - .await - .expect("proved"); - assert_eq!(proof.session_id(), session.id); - let after = fixture.session(&cookie).await.expect("session"); - assert_eq!( - after.passkey_confirmed_at, session.passkey_confirmed_at, - "the session's own confirmation is as it was" - ); - let replayed = fixture - .app - .verify_admin_proof(&headers(&browser), &owner, &assertion) - .await; - assert!(replayed.is_err(), "once only"); -} - -/// A passkey sign-in to an account scheduled for deletion gets no session, but an -/// offer, in its own cookie, which the sign-in page restores the account with once, -/// signing in with that passkey, on any replica. A disabled account gets neither. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn signing_in_to_an_account_scheduled_for_deletion_offers_to_restore_it() { - let mut fixture = Fixture::new().await; - let replicas = Replicas::new().await; - let mut tx = fixture.app.database.begin().await.expect("transaction"); - tx.users() - .set_status(fixture.user_id, AccountStatus::Deleting) - .await - .expect("status"); - tx.deletions() - .schedule( - fixture.user_id, - chrono::Utc::now() + chrono::Duration::days(30), - ) - .await - .expect("schedule"); - tx.commit().await.expect("commit"); - - let username = json!({"username": fixture.username}); - let (started, browser) = fixture - .on(&replicas.a) - .start("/webauthn/authenticate/start", "", username.clone()) - .await; - let assertion = fixture.assertion(&started); - let offered = fixture - .request( - "/webauthn/authenticate/finish", - Method::POST, - &browser, - json!({"ceremony_id": started["ceremony_id"], "credential": assertion}), - ) - .await; - assert_eq!(offered.status(), StatusCode::NO_CONTENT); - let offer = Fixture::cookie(&offered); - assert!( - offer.starts_with(BrowserCookie::Restore.as_str()), - "an offer, and no session: {offer}" - ); - - let holder = Browser { - cookie: offer, - ..Browser::signed_out() - }; - let restore = [("action", "restore")]; - let restored = holder - .submit(&replicas.b, routes::page::LOGIN, &restore, OWN_PAGE) - .await; - assert_eq!(restored.status(), StatusCode::SEE_OTHER); - let session = restored - .headers() - .get_all(header::SET_COOKIE) - .iter() - .filter_map(|cookie| cookie.to_str().ok()) - .find(|cookie| cookie.starts_with(BrowserCookie::Session.as_str())) - .and_then(|cookie| cookie.split(';').next()) - .expect("signed in") - .to_owned(); - let session = fixture.session(&session).await.expect("session"); - assert_eq!(session.user_id, fixture.user_id); - assert_eq!( - fixture - .app - .database - .sessions() - .passkey(session.id) - .await - .expect("passkey"), - Some(fixture.key_id) - ); - assert_eq!(fixture.events().await[1], DomainEvent::AccountRestored {}); - let again = holder - .submit(&replicas.a, routes::page::LOGIN, &restore, OWN_PAGE) - .await; - assert_eq!( - again.status(), - StatusCode::BAD_REQUEST, - "an offer restores once" - ); - - // Disabled after the ceremony started, which still names the passkey. - let (started, browser) = fixture - .start("/webauthn/authenticate/start", "", username) - .await; - fixture - .app - .database - .users() - .set_status(fixture.user_id, AccountStatus::Disabled) - .await - .expect("disable"); - let assertion = fixture.assertion(&started); - let refused = fixture - .request( - "/webauthn/authenticate/finish", - Method::POST, - &browser, - json!({"ceremony_id": started["ceremony_id"], "credential": assertion}), - ) - .await; - assert_eq!(refused.status(), StatusCode::UNAUTHORIZED); -} - -/// PKCE verifier of the pushed requests related pages complete. -const PAGE_VERIFIER: &str = "related-page-verifier-0123456789-abcdefghijklmnop"; - -/// A trusted client whose page, on its approved origin, signs the fixture's account in. -struct RelatedPage { - /// The page's client. - client: piquel_common::clients::ClientRegistration, - /// The page's approved origin. - origin: RelatedOrigin, -} - -impl RelatedPage { - /// Registers a trusted public client on a fresh subdomain of auth's own domain, - /// which counts only as `piquel`, as every such origin does, and approves its origin. - async fn approved(database: &Database) -> Self { - let origin: RelatedOrigin = format!("https://{}.auth.piquel.fr", TokenId::new()) - .parse() - .expect("origin"); - let client = piquel_common::clients::ClientRegistration { - trusted: true, - ..crate::tests::registration( - piquel_common::clients::ClientKind::Public, - origin.as_str(), - ) - }; - register(database, &client).await.expect("client"); - change(database, async |registry| { - registry - .approve_origin(&client.id, &origin, "auth.piquel.fr") - .await - }) - .await - .expect("approved origin"); - Self { client, origin } - } -} - -impl Fixture { - /// Pushes `page`'s authorization request, with `extra` parameters, and returns - /// its `request_uri`. - async fn push(&self, page: &RelatedPage, extra: &[(&str, &str)]) -> String { - let challenge = piquel_crypto::Pkce::challenge(PAGE_VERIFIER).expect("PKCE"); - let form = url::form_urlencoded::Serializer::new(String::new()) - .extend_pairs([ - ("client_id", page.client.id.as_str()), - ("response_type", "code"), - ("redirect_uri", page.client.redirect_uris[0].as_str()), - ("scope", "openid"), - ("state", "page-state"), - ("code_challenge_method", "S256"), - ("code_challenge", &challenge), - ]) - .extend_pairs(extra.iter().copied()) - .finish(); - let request = Request::builder() - .method(Method::POST) - .uri(routes::oidc::PAR) - .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); - let response = self.send(request, form).await; - assert_eq!(response.status(), StatusCode::CREATED); - Self::json(response).await["request_uri"] - .as_str() - .expect("request_uri") - .to_owned() - } - /// Posts JSON from a page on `origin`, which sends no cookies. - async fn post_from(&self, origin: &str, path: &str, body: Value) -> Response { - let request = Request::builder() - .method(Method::POST) - .uri(path) - .header(header::ORIGIN, origin) - .header(header::CONTENT_TYPE, "application/json"); - self.send(request, body.to_string()).await - } - /// Starts `page`'s sign-in for `request_uri`. - async fn start_related(&self, page: &RelatedPage, request_uri: &str) -> Response { - self.post_from( - page.origin.as_str(), - routes::passkey::RELATED_START, - json!({"request_uri":request_uri}), - ) - .await - } - /// Signs `page`'s started sign-in for its own origin and finishes it from there. - async fn finish_related(&mut self, page: &RelatedPage, started: &Value) -> Response { - let assertion = self.assertion_for(page.origin.url().clone(), started); - self.post_from( - page.origin.as_str(), - routes::passkey::RELATED_FINISH, - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await - } - /// Redeems `code` for `page`'s client with `verifier`. - async fn redeem(&self, page: &RelatedPage, code: &str, verifier: &str) -> Response { - let form = url::form_urlencoded::Serializer::new(String::new()) - .extend_pairs([ - ("grant_type", "authorization_code"), - ("client_id", page.client.id.as_str()), - ("redirect_uri", page.client.redirect_uris[0].as_str()), - ("code", code), - ("code_verifier", verifier), - ]) - .finish(); - let request = Request::builder() - .method(Method::POST) - .uri(routes::oidc::TOKEN) - .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); - self.send(request, form).await - } - /// Lists the origins `/.well-known/webauthn` publishes. - async fn related_origins(&self) -> Vec { - let request = Request::builder() - .method(Method::GET) - .uri(routes::passkey::RELATED_ORIGINS); - let response = self.send(request, String::new()).await; - assert_eq!(response.status(), StatusCode::OK); - assert_eq!( - response.headers()[header::CACHE_CONTROL], - "public, max-age=300, no-transform" - ); - assert_eq!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); - serde_json::from_value(Self::json(response).await["origins"].take()).expect("origins") - } -} - -/// A page on an approved origin signs its account in without a cookie, and gets a -/// code that only its PKCE verifier redeems, once. The sign-in creates a session -/// recorded with the page's client and origin. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn related_pages_sign_in_for_pkce_bound_codes() { - let mut fixture = Fixture::new().await; - let replicas = Replicas::new().await; - fixture.on(&replicas.a); - let page = RelatedPage::approved(&fixture.app.database).await; - assert!( - fixture - .related_origins() - .await - .contains(&page.origin.to_string()) - ); - let mut codes = Vec::new(); - for _ in 0..2 { - let request_uri = fixture.push(&page, &[]).await; - let started = fixture.start_related(&page, &request_uri).await; - assert_eq!(started.status(), StatusCode::OK); - let headers = started.headers().clone(); - assert_eq!( - headers[header::ACCESS_CONTROL_ALLOW_ORIGIN], - page.origin.as_str() - ); - assert!( - headers - .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) - .is_none(), - "pages sign in without cookies" - ); - assert!(headers.get(header::SET_COOKIE).is_none()); - let started = Fixture::json(started).await; - // Signed on one replica, finished on the other. - let finished = fixture - .on(&replicas.b) - .finish_related(&page, &started) - .await; - assert_eq!(finished.status(), StatusCode::OK); - assert!(finished.headers().get(header::SET_COOKIE).is_none()); - let answer = Fixture::json(finished).await; - assert_eq!(answer["state"], "page-state"); - assert_eq!(answer["iss"], AUTH_ORIGIN); - codes.push(answer["code"].as_str().expect("code").to_owned()); - // The ceremony and its request are spent. - let assertion = fixture.assertion_for(page.origin.url().clone(), &started); - let replay = fixture - .post_from( - page.origin.as_str(), - routes::passkey::RELATED_FINISH, - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await; - assert_eq!(replay.status(), StatusCode::BAD_REQUEST); - let reused = fixture.start_related(&page, &request_uri).await; - assert_eq!(reused.status(), StatusCode::BAD_REQUEST); - } - let wrong = "another-verifier-0123456789-abcdefghijklmnopqrstu"; - let redeemed = fixture.redeem(&page, &codes[0], wrong).await; - assert_eq!(redeemed.status(), StatusCode::BAD_REQUEST); - let redeemed = fixture.redeem(&page, &codes[1], PAGE_VERIFIER).await; - assert_eq!(redeemed.status(), StatusCode::OK); - let DomainEvent::SignedIn { - session_id, - method: AuthenticationMethod::Passkey, - inline: Some(inline), - } = fixture - .events() - .await - .into_iter() - .find(|event| matches!(event, DomainEvent::SignedIn { .. })) - .expect("sign-in") - else { - panic!("an inline passkey sign-in"); - }; - assert_eq!(inline.client_id, page.client.id); - assert_eq!(inline.origin, page.origin.into(), "kept as personal data"); - let session = fixture - .app - .database - .sessions() - .find_active_by_id(session_id) - .await - .expect("session lookup") - .expect("active session"); - assert_eq!( - SessionAuthentication::from(&session).acr, - Acr::PhishingResistant - ); -} - -/// Sign-in is refused to unapproved origins, for another client's request, from -/// another origin than its start, for an assertion signed for another origin and -/// without user verification. A request needing auth's pages stays usable there. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn related_sign_in_refuses_other_origins_requests_and_unverified_users() { - let mut fixture = Fixture::new().await; - let replicas = Replicas::new().await; - fixture.on(&replicas.a); - let page = RelatedPage::approved(&fixture.app.database).await; - let other = RelatedPage::approved(&fixture.app.database).await; - - let request_uri = fixture.push(&page, &[]).await; - let unapproved = fixture - .post_from( - "https://unapproved.example", - routes::passkey::RELATED_START, - json!({"request_uri":request_uri}), - ) - .await; - assert_eq!(unapproved.status(), StatusCode::FORBIDDEN); - assert!( - unapproved - .headers() - .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) - .is_none() - ); - // Another client's page cannot claim the request, which stays its client's. - let claimed = fixture.start_related(&other, &request_uri).await; - assert_eq!(claimed.status(), StatusCode::BAD_REQUEST); - let started = fixture.start_related(&page, &request_uri).await; - assert_eq!(started.status(), StatusCode::OK); - let started = Fixture::json(started).await; - // The ceremony finishes only on the page that started it. - let assertion = fixture.assertion_for(other.origin.url().clone(), &started); - let moved = fixture - .post_from( - other.origin.as_str(), - routes::passkey::RELATED_FINISH, - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await; - assert_eq!(moved.status(), StatusCode::FORBIDDEN); - - // The verifier accepts auth's own origin too, but the page must have signed. - let started = Fixture::json( - fixture - .start_related(&page, &fixture.push(&page, &[]).await) - .await, - ) - .await; - let assertion = fixture.assertion(&started); - let elsewhere = fixture - .post_from( - page.origin.as_str(), - routes::passkey::RELATED_FINISH, - json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), - ) - .await; - assert_eq!(elsewhere.status(), StatusCode::BAD_REQUEST); - - let mut started = Fixture::json( - fixture - .start_related(&page, &fixture.push(&page, &[]).await) - .await, - ) - .await; - started["public_key"]["publicKey"]["userVerification"] = json!("discouraged"); - let unverified = fixture.finish_related(&page, &started).await; - assert_eq!(unverified.status(), StatusCode::BAD_REQUEST); - assert_eq!( - fixture.events().await.first(), - Some(&DomainEvent::SignInFailed { - method: AuthenticationMethod::Passkey, - reason: SignInFailure::InvalidCredential, - }) - ); - - // `prompt=consent` needs the consent page: the request is left for it. - let request_uri = fixture.push(&page, &[("prompt", "consent")]).await; - let refused = fixture.start_related(&page, &request_uri).await; - assert_eq!(refused.status(), StatusCode::BAD_REQUEST); - assert_eq!(Fixture::json(refused).await["code"], "interaction_required"); - let query = url::form_urlencoded::Serializer::new(String::new()) - .extend_pairs([ - ("client_id", page.client.id.as_str()), - ("request_uri", &request_uri), - ]) - .finish(); - let redirect = fixture - .request( - &format!("{}?{query}", routes::oidc::AUTHORIZE), - Method::GET, - "", - json!({}), - ) - .await; - assert_eq!(redirect.status(), StatusCode::SEE_OTHER); - - // A removed origin's pages stop at once. - change(&fixture.app.database, async |registry| { - registry.remove_origin(&page.client.id, &page.origin).await - }) - .await - .expect("removed"); - assert!( - !fixture - .related_origins() - .await - .contains(&page.origin.to_string()) - ); - let removed = fixture - .start_related(&page, &fixture.push(&page, &[]).await) - .await; - assert_eq!(removed.status(), StatusCode::FORBIDDEN); -} - -/// An account scheduled for deletion signs in on no related page: only auth's -/// sign-in page offers to restore it, so the page is told to send the user there. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn an_account_being_deleted_signs_in_on_auths_pages_only() { - let mut fixture = Fixture::new().await; - let replicas = Replicas::new().await; - fixture.on(&replicas.a); - let page = RelatedPage::approved(fixture.database()).await; - let mut tx = fixture.app.database.begin().await.expect("transaction"); - tx.users() - .set_status(fixture.user_id, AccountStatus::Deleting) - .await - .expect("status"); - tx.deletions() - .schedule( - fixture.user_id, - chrono::Utc::now() + chrono::Duration::days(30), - ) - .await - .expect("schedule"); - tx.commit().await.expect("commit"); - - let request_uri = fixture.push(&page, &[]).await; - let started = Fixture::json(fixture.start_related(&page, &request_uri).await).await; - let refused = fixture.finish_related(&page, &started).await; - assert_eq!(refused.status(), StatusCode::BAD_REQUEST); - assert!(refused.headers().get(header::SET_COOKIE).is_none()); - assert_eq!(Fixture::json(refused).await["code"], "interaction_required"); -} - -/// A recovered passkey during its probation signs in on a related page as on -/// auth's, without confirming the session, so a request for `phr` is refused with -/// `interaction_required`, for auth's pages to answer the client. Without that -/// target it signs in. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn a_probation_passkey_meets_no_phr_on_related_pages() { - let mut fixture = Fixture::new().await; - let replicas = Replicas::new().await; - fixture.on(&replicas.a); - let page = RelatedPage::approved(fixture.database()).await; - let recovery = piquel_common::RecoveryId::new(); - let mut recoveries = fixture.database().recoveries(); - recoveries - .insert(&piquel_repository::InsertRecovery { - id: recovery, - user_id: fixture.user_id, - secret_digest: &recovery.as_uuid().as_bytes().repeat(2), - expires_at: chrono::Utc::now() + chrono::Duration::hours(1), - }) - .await - .expect("recovery"); - let completed = recoveries - .complete( - fixture.user_id, - recovery, - fixture.key_id, - crate::recovery::PROBATION, - ) - .await; - assert!(completed.expect("complete")); - - let request_uri = fixture.push(&page, &[("acr_values", "phr")]).await; - let started = Fixture::json(fixture.start_related(&page, &request_uri).await).await; - let refused = fixture.finish_related(&page, &started).await; - assert_eq!(refused.status(), StatusCode::BAD_REQUEST); - assert_eq!(Fixture::json(refused).await["code"], "interaction_required"); - - let request_uri = fixture.push(&page, &[]).await; - let started = Fixture::json(fixture.start_related(&page, &request_uri).await).await; - assert_eq!( - fixture.finish_related(&page, &started).await.status(), - StatusCode::OK - ); -} diff --git a/apps/auth-service/src/passkey/tests/confirmation.rs b/apps/auth-service/src/passkey/tests/confirmation.rs new file mode 100644 index 000000000..031857989 --- /dev/null +++ b/apps/auth-service/src/passkey/tests/confirmation.rs @@ -0,0 +1,307 @@ +//! Browser binding, session confirmation and admin handoff proofs. + +use super::*; +use piquel_common::events::RevocationReason; + +/// Checks browser binding, and that a passkey confirmation belongs to one session, +/// counts from its own time and is required only where an action needs it. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +#[expect( + clippy::too_many_lines, + reason = "Keep one session's confirmation lifecycle in a single scenario." +)] +async fn ceremonies_require_browser_binding_and_confirmation_belongs_to_one_session() { + let mut fixture = Fixture::new().await; + let (started, _) = fixture + .start( + "/webauthn/authenticate/start", + "", + json!({"handle":fixture.username}), + ) + .await; + let assertion = fixture.assertion(&started); + let body = json!({"ceremony_id":started["ceremony_id"],"credential":assertion}); + for cookies in [ + String::new(), + format!( + "{}={}", + BrowserCookie::Ceremony.as_str(), + Secret::generate().expect("browser secret").encoded() + ), + ] { + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &cookies, + body.clone(), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(response.headers().get(header::SET_COOKIE).is_none()); + } + // A passkey sign-in confirms its session, so enrollment right after it prompts once. + let signed_in = fixture.login().await; + fixture + .start("/account/passkeys/enroll/start", &signed_in, json!({})) + .await; + // Another session of the same account, from social sign-in, is not confirmed. + let mut tx = fixture.app.database.begin().await.expect("transaction"); + let secret = security::Session::create( + &mut tx, + security::RequestContext::TEST, + fixture.user_id, + AuthenticationMethod::Federation.into(), + ) + .await + .expect("social session"); + tx.commit().await.expect("commit"); + let social = format!("{}={}", BrowserCookie::Session.as_str(), secret.encoded()); + let session_id = fixture + .app + .database + .sessions() + .find_active_by_browser_secret(secret.digest().as_bytes()) + .await + .expect("lookup") + .expect("session") + .id; + let path = format!("/account/passkeys/{}", fixture.key_id); + for (path, method) in [ + ("/account/passkeys/enroll/start", Method::POST), + (path.as_str(), Method::DELETE), + ] { + security::tests::assert_step_up_required( + fixture.request(path, method, &social, json!({})).await, + ) + .await; + } + let response = fixture + .request( + &path, + Method::PATCH, + &social, + json!({"friendly_name":"Renamed"}), + ) + .await; + assert_eq!( + response.status(), + StatusCode::NO_CONTENT, + "renaming needs no confirmation" + ); + // A confirmation proves possession for the session that started it only. + let (started, browser) = fixture + .start("/account/passkeys/confirm/start", &social, json!({})) + .await; + let assertion = fixture.assertion(&started); + let response = fixture + .request( + "/account/passkeys/confirm/finish", + Method::POST, + &format!("{signed_in}; {browser}"), + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!( + response.status(), + StatusCode::BAD_REQUEST, + "confirmation is bound to the initiating session" + ); + let (started, browser) = fixture + .start("/account/passkeys/confirm/start", &social, json!({})) + .await; + let assertion = fixture.assertion(&started); + let response = fixture + .request( + "/account/passkeys/confirm/finish", + Method::POST, + &format!("{social}; {browser}"), + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + // The confirmation replaces the cookie, so a copy of the old one gains nothing. + let stale = social; + let social = Fixture::cookie(&response); + assert!(fixture.session(&stale).await.is_none()); + assert_eq!( + fixture.session(&social).await.expect("same session").id, + session_id + ); + assert_eq!( + fixture.events().await.first(), + Some(&DomainEvent::PasskeyConfirmed { session_id }) + ); + let confirming = fixture.app.database.sessions().passkey(session_id).await; + assert_eq!(confirming.expect("passkey"), Some(fixture.key_id)); + let confirmed_at = || async { + fixture + .app + .database + .sessions() + .find_active_by_id(session_id) + .await + .expect("lookup") + .expect("session") + .passkey_confirmed_at + .expect("confirmed") + }; + let confirmed = confirmed_at().await; + // Confirmed actions do not extend the confirmation. + let (started, browser) = fixture + .start("/account/passkeys/enroll/start", &social, json!({})) + .await; + // The confirmation authorized enrollment at start; its lapsing at the authenticator + // must not discard the new credential. + fixture + .app + .database + .sessions() + .confirm_passkey( + session_id, + PasskeyId::new(), + confirmed - chrono::Duration::hours(1), + ) + .await + .expect("stale confirmation"); + let credential = fixture.credential(&started); + let response = fixture + .request( + "/account/passkeys/enroll/finish", + Method::POST, + &format!("{social}; {browser}"), + json!({"ceremony_id":started["ceremony_id"],"friendly_name":"Second","credential":credential}), + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + fixture + .app + .database + .sessions() + .confirm_passkey(session_id, PasskeyId::new(), confirmed) + .await + .expect("restore confirmation"); + // Removal revokes both other sessions, the passkey sign-in and this one. + let mut tx = fixture.app.database.begin().await.expect("transaction"); + security::Session::create( + &mut tx, + security::RequestContext::TEST, + fixture.user_id, + AuthenticationMethod::Federation.into(), + ) + .await + .expect("third session"); + tx.commit().await.expect("commit"); + let response = fixture + .request(&path, Method::DELETE, &social, json!({})) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + assert_eq!(confirmed_at().await, confirmed); + let events = fixture.events().await; + let removed = events + .iter() + .position(|event| { + *event + == DomainEvent::PasskeyRemoved { + passkey_id: fixture.key_id, + } + }) + .expect("removal recorded"); + let mut revoked: Vec<_> = events[..removed] + .iter() + .map(|event| match event { + DomainEvent::SessionRevoked { + session_id, + reason: RevocationReason::CredentialRemoved, + } => *session_id, + event => panic!("unexpected {event:?}"), + }) + .collect(); + revoked.dedup(); + assert_eq!(revoked.len(), 2, "one revocation per other session"); + assert!(!revoked.contains(&session_id), "the acting session stays"); + let keys = fixture + .app + .database + .passkeys() + .list_active(fixture.user_id) + .await + .expect("keys"); + assert_eq!(keys.len(), 1); + let response = fixture + .request( + &format!("/account/passkeys/{}", keys[0].id), + Method::DELETE, + &social, + json!({}), + ) + .await; + assert_eq!( + response.status(), + StatusCode::BAD_REQUEST, + "last passkey cannot be removed" + ); + assert!( + fixture.session(&signed_in).await.is_none(), + "removing a passkey revokes other sessions" + ); +} + +/// A passkey proof of a handoff to the admin dashboard counts for that handoff +/// only: its ceremony is bound to the browser and session that started it, is +/// used once, and leaves the session's own confirmation as it was. A ceremony +/// confirming the session is no proof of a handoff. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn an_admin_proof_counts_for_its_handoff_only() { + let mut fixture = Fixture::new().await; + let cookie = fixture.login().await; + let session = fixture.session(&cookie).await.expect("session"); + let headers = |cookies: &str| { + let mut headers = HeaderMap::new(); + headers.insert(header::COOKIE, cookies.parse().expect("cookies")); + headers + }; + let owner = AccountService::new(fixture.database().clone()) + .owner(RequestContext::TEST, &headers(&cookie)) + .await + .expect("lookup") + .expect("signed in"); + let prove = async |fixture: &mut Fixture, start: &str| { + let (started, browser) = fixture.start(start, &cookie, json!({})).await; + let credential = fixture.assertion(&started); + let assertion = json!({"ceremony_id": started["ceremony_id"], "credential": credential}); + (assertion.to_string(), format!("{cookie}; {browser}")) + }; + + let (confirmation, browser) = prove(&mut fixture, routes::passkey::CONFIRM_START).await; + let refused = fixture + .app + .verify_admin_proof(&headers(&browser), &owner, &confirmation) + .await; + assert!(refused.is_err(), "a confirmation of the session"); + + let (assertion, browser) = prove(&mut fixture, routes::passkey::ADMIN_PROOF_START).await; + let refused = fixture + .app + .verify_admin_proof(&headers(&cookie), &owner, &assertion) + .await; + assert!(refused.is_err(), "another browser"); + let proof = fixture + .app + .verify_admin_proof(&headers(&browser), &owner, &assertion) + .await + .expect("proved"); + assert_eq!(proof.session_id(), session.id); + let after = fixture.session(&cookie).await.expect("session"); + assert_eq!( + after.passkey_confirmed_at, session.passkey_confirmed_at, + "the session's own confirmation is as it was" + ); + let replayed = fixture + .app + .verify_admin_proof(&headers(&browser), &owner, &assertion) + .await; + assert!(replayed.is_err(), "once only"); +} diff --git a/apps/auth-service/src/passkey/tests/counters.rs b/apps/auth-service/src/passkey/tests/counters.rs new file mode 100644 index 000000000..ced33c6db --- /dev/null +++ b/apps/auth-service/src/passkey/tests/counters.rs @@ -0,0 +1,137 @@ +//! Signature counters: concurrent assertions and lagging copies of a passkey. + +use super::*; + +/// Checks counter ordering under concurrent ceremony snapshots, records the +/// regression and prevents replay. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn overlapping_assertions_reject_old_counter_after_new_counter_commits() { + let mut fixture = Fixture::new().await; + let (older, browser) = fixture + .start( + "/webauthn/authenticate/start", + "", + json!({"handle":fixture.username}), + ) + .await; + let (newer, _) = fixture + .start( + "/webauthn/authenticate/start", + &browser, + json!({"handle":fixture.username}), + ) + .await; + let older_assertion = fixture.assertion(&older); + let newer_assertion = fixture.assertion(&newer); + let newer_body = json!({"ceremony_id":newer["ceremony_id"],"credential":newer_assertion}); + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + newer_body.clone(), + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + json!({"ceremony_id":older["ceremony_id"],"credential":older_assertion}), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(response.headers().get(header::SET_COOKIE).is_none()); + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + newer_body, + ) + .await; + assert_eq!( + response.status(), + StatusCode::BAD_REQUEST, + "ceremony cannot replay" + ); + let keys = fixture + .app + .database + .passkeys() + .list_active(fixture.user_id) + .await + .expect("keys"); + assert_eq!( + keys[0].credential.pointer(CREDENTIAL_COUNTER_POINTER), + Some(&json!(2)) + ); + let events = fixture.events().await; + assert!( + matches!( + events.as_slice(), + [ + DomainEvent::SignInFailed { + method: AuthenticationMethod::Passkey, + reason: SignInFailure::CounterRegression, + }, + DomainEvent::SignedIn { + method: AuthenticationMethod::Passkey, + .. + }, + ] + ), + "the regression outlives its rolled-back authentication transaction; the replay is not recorded: {events:?}" + ); +} + +/// A copy of a passkey that signs behind the stored counter is rejected by `WebAuthn`'s +/// snapshot check, and the rejection is recorded like the locked check. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn lagging_counter_copy_is_rejected_and_recorded() { + let mut fixture = Fixture::new().await; + // Simulate the original authenticator having signed far ahead of this copy. + let mut passkeys = fixture.app.database.passkeys(); + let mut key = passkeys + .list_active(fixture.user_id) + .await + .expect("keys") + .remove(0); + *key.credential + .pointer_mut(CREDENTIAL_COUNTER_POINTER) + .expect("counter") = json!(100); + assert!( + passkeys + .update_after_authentication(&key.credential_id, &key.credential) + .await + .expect("advanced counter") + ); + let (started, browser) = fixture + .start( + "/webauthn/authenticate/start", + "", + json!({"handle":fixture.username}), + ) + .await; + let assertion = fixture.assertion(&started); + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(response.headers().get(header::SET_COOKIE).is_none()); + assert_eq!( + fixture.events().await, + [DomainEvent::SignInFailed { + method: AuthenticationMethod::Passkey, + reason: SignInFailure::CounterRegression, + }] + ); +} diff --git a/apps/auth-service/src/passkey/tests/mod.rs b/apps/auth-service/src/passkey/tests/mod.rs new file mode 100644 index 000000000..54e88b91a --- /dev/null +++ b/apps/auth-service/src/passkey/tests/mod.rs @@ -0,0 +1,321 @@ +//! Focused name validation and database-backed `WebAuthn` ceremony invariants. + +use super::*; +use crate::{ + account::AccountApplication, + tests::{AUTH_ORIGIN, Browser, Replicas}, +}; +use axum::{ + body::{Body, to_bytes}, + http::{Method, Request}, +}; +use piquel_common::{TokenId, events::SignInFailure, protocol::claims::Acr}; +use piquel_crypto::Secret; +use piquel_repository::{DatabaseConfig, SessionAuthentication, StoredSession}; +use serde_json::json; +use tower::ServiceExt; +use url::Url; +use webauthn_authenticator_rs::{WebauthnAuthenticator, softpasskey::SoftPasskey}; + +mod confirmation; +mod counters; +mod registration; +mod related_pages; +mod sign_in; +mod telemetry; +mod validation; + +/// Maximum JSON response accepted by the software browser fixture. +const MAX_RESPONSE_BYTES: usize = 64 * 1024; + +/// Isolated account and counter-capable software authenticator for database +/// scenarios. The recovery scenarios use it too. +pub(crate) struct Fixture { + /// Routes and persistence under test. + app: PasskeyApplication, + /// Where requests go: the passkey routes, or a replica of the whole service. + router: axum::Router, + /// Software credential capable of user verification and monotonic counters. + authenticator: WebauthnAuthenticator, + /// HTTPS origin passed to the authenticator. + origin: Url, + /// Seeded account owning the software credential. + pub(crate) user_id: UserId, + /// Seeded passkey row used for rename and last-key removal checks. + pub(crate) key_id: PasskeyId, + /// Unique seeded username for identified authentication. + pub(crate) username: String, + /// The signing credential's ID, which an account picker's challenge lists. + credential_id: Vec, +} +impl Fixture { + /// Seeds an account and passkey in the explicitly configured isolated database. + pub(crate) async fn new() -> Self { + let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") + .required() + .expect("isolated test database"); + let database = Database::connect( + DatabaseConfig::new(&url, 5, std::time::Duration::from_secs(5)).expect("configuration"), + ) + .await + .expect("database"); + database.run_migrations().await.expect("migrations"); + let origin = Url::parse(AUTH_ORIGIN).expect("origin"); + let config = crate::AuthConfig::test(&AUTH_ORIGIN.parse().expect("origin")); + let keys = crate::KeyStore::new(database.clone(), Arc::clone(&config.key_encryption_key)) + .start() + .await + .expect("signing keys"); + let oidc = OidcApplication::new(database.clone(), &config.oidc, keys).expect("OIDC app"); + let app = PasskeyApplication::new(database, &config.passkey, oidc).expect("passkey app"); + let user_id = UserId::new(); + let username = format!("key-{}", &TokenId::new().to_string()[24..]); + app.database + .users() + .insert(&InsertUser { + id: user_id, + handle: Handle::parse(&username).expect("handle"), + display_name: "Test user".into(), + }) + .await + .expect("user"); + let (key_id, credential_id, authenticator) = + Self::seed_passkey(&app, &origin, user_id, &username, "Original key").await; + Self { + router: app + .clone() + .routes() + .merge(AccountApplication::new(app.database.clone()).routes()), + app, + authenticator, + origin, + user_id, + key_id, + username, + credential_id, + } + } + /// Stores a new software authenticator's passkey named `name` for `user_id`. + /// The authenticator supports UV and signed counters, but not resident + /// credentials. Browser tests cover production resident signup; this uses the + /// library's normal registration. + async fn seed_passkey( + app: &PasskeyApplication, + origin: &Url, + user_id: UserId, + username: &str, + name: &str, + ) -> (PasskeyId, Vec, WebauthnAuthenticator) { + let (challenge, state) = app + .webauthn + .start_passkey_registration(user_id.as_uuid(), username, "Test user", None) + .expect("registration"); + let mut authenticator = WebauthnAuthenticator::new(SoftPasskey::new(true)); + let registration = authenticator + .do_registration(origin.clone(), challenge) + .expect("software registration"); + let key = app + .webauthn + .finish_passkey_registration(®istration, &state) + .expect("verified registration"); + let id = PasskeyId::new(); + let credential_id = key.cred_id().as_ref().to_vec(); + app.database + .passkeys() + .insert(&InsertPasskey { + id, + credential_id: credential_id.clone(), + user_id, + credential: serde_json::to_value(key).expect("credential"), + friendly_name: name.into(), + }) + .await + .expect("stored key"); + (id, credential_id, authenticator) + } + /// Signs with `authenticator` from now on, and returns the one that signed + /// until now. + pub(crate) fn replace_authenticator( + &mut self, + authenticator: WebauthnAuthenticator, + ) -> WebauthnAuthenticator { + std::mem::replace(&mut self.authenticator, authenticator) + } + /// Stores another passkey named `name` on the account, and signs with it from + /// now on. + pub(crate) async fn switch_passkey(&mut self, name: &str) -> PasskeyId { + let (id, credential_id, authenticator) = + Self::seed_passkey(&self.app, &self.origin, self.user_id, &self.username, name).await; + self.authenticator = authenticator; + self.credential_id = credential_id; + id + } + /// Sends the next requests to `router`, such as one of [`Replicas`]. + fn on(&mut self, router: &axum::Router) -> &mut Self { + self.router = router.clone(); + self + } + /// The scenario database. + pub(crate) const fn database(&self) -> &Database { + &self.app.database + } + /// Sends a JSON request from the auth origin with the supplied cookies. + pub(crate) async fn request( + &self, + path: &str, + method: Method, + cookies: &str, + body: Value, + ) -> Response { + let request = Request::builder() + .method(method) + .uri(path) + .header(header::ORIGIN, AUTH_ORIGIN) + .header(header::CONTENT_TYPE, "application/json") + .header(header::COOKIE, cookies); + self.send(request, body.to_string()).await + } + /// Sends `request` with the CSRF header and `body`. + async fn send(&self, request: axum::http::request::Builder, body: String) -> Response { + self.router + .clone() + .oneshot( + request + .extension(crate::security::RequestContext::TEST) + .header("x-piquel-csrf", "1") + .body(Body::from(body)) + .expect("request"), + ) + .await + .expect("response") + } + /// Starts a ceremony and returns its challenge JSON and browser-binding cookie. + pub(crate) async fn start(&self, path: &str, cookies: &str, body: Value) -> (Value, String) { + let response = self.request(path, Method::POST, cookies, body).await; + assert_eq!(response.status(), StatusCode::OK); + let cookie = Self::cookie(&response); + (Self::json(response).await, cookie) + } + /// Reads a response's JSON body. + pub(crate) async fn json(response: Response) -> Value { + serde_json::from_slice( + &to_bytes(response.into_body(), MAX_RESPONSE_BYTES) + .await + .expect("body"), + ) + .expect("JSON") + } + /// Extracts the cookie pair from a response for the next simulated browser request. + pub(crate) fn cookie(response: &Response) -> String { + response.headers()[header::SET_COOKIE] + .to_str() + .expect("cookie") + .split(';') + .next() + .expect("cookie pair") + .to_owned() + } + /// Signs a started authentication challenge using the software credential. + pub(crate) fn assertion(&mut self, started: &Value) -> PublicKeyCredential { + self.assertion_for(self.origin.clone(), started) + } + /// Signs a started authentication challenge for a page on `origin`, within + /// auth's RP ID. The software credential is not discoverable, so an account + /// picker's challenge gets it listed, and the answer names its account as a + /// discoverable one would. + fn assertion_for(&mut self, origin: Url, started: &Value) -> PublicKeyCredential { + let mut challenge: RequestChallengeResponse = + serde_json::from_value(started["public_key"].clone()) + .expect("authentication challenge"); + let picker = challenge.public_key.allow_credentials.is_empty(); + if picker { + challenge.public_key.allow_credentials = vec![webauthn_rs_proto::AllowCredentials { + type_: "public-key".into(), + id: self.credential_id.clone().into(), + transports: None, + }]; + } + let mut credential = self + .authenticator + .do_authentication(origin, challenge) + .expect("software assertion"); + if picker { + credential.response.user_handle = + Some(self.user_id.as_uuid().as_bytes().to_vec().into()); + } + credential + } + /// Completes an identified login and returns the new session cookie. + async fn login(&mut self) -> String { + self.login_from("").await + } + /// Completes an identified login in a browser holding the `session` cookie pair, + /// if any, and returns the session cookie it sets. + async fn login_from(&mut self, session: &str) -> String { + let (started, browser) = self + .start( + "/webauthn/authenticate/start", + "", + json!({"handle":self.username}), + ) + .await; + let assertion = self.assertion(&started); + let response = self + .request( + "/webauthn/authenticate/finish", + Method::POST, + &format!("{session}; {browser}"), + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + Self::cookie(&response) + } + /// Finds the active session a cookie pair names. + pub(crate) async fn session(&self, cookie: &str) -> Option { + let secret = cookie + .split_once('=') + .and_then(|(_, value)| Secret::parse(value).ok()) + .expect("session cookie"); + self.app + .database + .sessions() + .find_active_by_browser_secret(secret.digest().as_bytes()) + .await + .expect("session lookup") + } + /// Lists the events recorded about the seeded account, newest first. + pub(crate) async fn events(&self) -> Vec { + self.app + .database + .events() + .history_for_user(self.user_id, 100) + .await + .expect("history") + .into_iter() + .map(|stored| stored.event.known().cloned().expect("a known event")) + .collect() + } + /// Answers a started registration challenge with a fresh software credential. + pub(crate) fn credential(&self, started: &Value) -> RegisterPublicKeyCredential { + self.new_authenticator(started).0 + } + /// Answers a started registration challenge with a new software + /// authenticator, and returns the credential and the authenticator, which can + /// sign with it once stored as [`Self::authenticator`]. + pub(crate) fn new_authenticator( + &self, + started: &Value, + ) -> ( + RegisterPublicKeyCredential, + WebauthnAuthenticator, + ) { + let challenge = + serde_json::from_value(started["public_key"].clone()).expect("registration challenge"); + let mut authenticator = WebauthnAuthenticator::new(SoftPasskey::new(true)); + let credential = authenticator + .do_registration(self.origin.clone(), challenge) + .expect("software registration"); + (credential, authenticator) + } +} diff --git a/apps/auth-service/src/passkey/tests/registration.rs b/apps/auth-service/src/passkey/tests/registration.rs new file mode 100644 index 000000000..831e4bc0a --- /dev/null +++ b/apps/auth-service/src/passkey/tests/registration.rs @@ -0,0 +1,140 @@ +//! Signup: handle rules and attaching a pending social signup. + +use super::*; +use crate::tests::pending_sign_in; + +impl Fixture { + /// Registers a new account with a fresh software credential; returns the finish response. + async fn register(&self, cookies: &str, body: Value) -> Response { + let (started, browser) = self.start("/webauthn/register/start", cookies, body).await; + let credential = self.credential(&started); + self.request( + "/webauthn/register/finish", + Method::POST, + &format!("{cookies}; {browser}"), + json!({"ceremony_id":started["ceremony_id"],"credential":credential}), + ) + .await + } +} + +/// Signup normalizes the handle, and refuses invalid, reserved and taken ones with +/// their codes; whether a handle is taken, only once admitted. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn signup_applies_the_handle_rules() { + let mut fixture = Fixture::new().await; + for (handle, status, code) in [ + ("a_b", StatusCode::BAD_REQUEST, "handle_invalid"), + ("adm1n", StatusCode::BAD_REQUEST, "handle_reserved"), + ( + fixture.username.as_str(), + StatusCode::CONFLICT, + "handle_taken", + ), + ] { + let response = fixture + .request( + "/webauthn/register/start", + Method::POST, + "", + json!({"handle": handle}), + ) + .await; + assert_eq!(response.status(), status, "{handle}"); + assert_eq!(Fixture::json(response).await["code"], code, "{handle}"); + } + let (started, _) = fixture + .start( + "/webauthn/register/start", + "", + json!({"handle": " New-User "}), + ) + .await; + assert_eq!( + started["public_key"]["publicKey"]["user"]["name"], + "new-user" + ); + // Only an admitted signup learns whether a handle is held. + let invite_only = PasskeyApplication::new( + fixture.app.database.clone(), + &PasskeyConfig { + origin: AUTH_ORIGIN.parse().expect("origin"), + invite_required: true, + }, + fixture.app.oidc.clone(), + ) + .expect("passkey app"); + let taken = json!({"handle": fixture.username}); + let response = fixture + .on(&invite_only.routes()) + .request("/webauthn/register/start", Method::POST, "", taken) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); +} + +/// Checks that abandoned social signup state never attaches to unrelated registration. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn registration_attaches_a_pending_social_signup_only_when_it_names_it() { + let fixture = Fixture::new().await; + let secret = Secret::generate().expect("browser secret"); + let pending = pending_sign_in(&secret); + let database = fixture.app.database.clone(); + database + .federation() + .insert_pending(&pending) + .await + .expect("pending signup"); + let social = format!( + "{}={}", + BrowserCookie::FederationPending.as_str(), + secret.encoded() + ); + let response = fixture + .request( + "/webauthn/register/start", + Method::POST, + &social, + json!({"handle":"unrelated","pending_signup":TokenId::new()}), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + for (explicit, attached) in [(None, false), (Some(pending.id), true)] { + let username = format!("reg-{}", &TokenId::new().to_string()[24..]); + let response = fixture + .register( + &social, + json!({"handle":username,"pending_signup":explicit}), + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + let user = database + .users() + .find_active_by_handle(&Handle::parse(&username).expect("handle")) + .await + .expect("user") + .expect("registered"); + let owner = database + .federation() + .find_active(&pending.issuer, &pending.subject) + .await + .expect("identity") + .map(|identity| identity.user_id); + assert_eq!(owner, attached.then_some(user.id), "{username}"); + let passkeys = database.passkeys().list_active(user.id).await; + let sessions = database.sessions().list_active_for_user(user.id).await; + let [session] = &sessions.expect("sessions")[..] else { + panic!("one session"); + }; + let recorded = database.sessions().passkey(session.id).await; + let [passkey] = &passkeys.expect("passkeys")[..] else { + panic!("one passkey"); + }; + assert_eq!( + recorded.expect("passkey"), + Some(passkey.id), + "signed in by it" + ); + } +} diff --git a/apps/auth-service/src/passkey/tests/related_pages.rs b/apps/auth-service/src/passkey/tests/related_pages.rs new file mode 100644 index 000000000..bf75a1e83 --- /dev/null +++ b/apps/auth-service/src/passkey/tests/related_pages.rs @@ -0,0 +1,416 @@ +//! Sign-in from related pages on approved origins. + +use super::*; +use crate::tests::{change, register}; + +/// PKCE verifier of the pushed requests related pages complete. +const PAGE_VERIFIER: &str = "related-page-verifier-0123456789-abcdefghijklmnop"; + +/// A trusted client whose page, on its approved origin, signs the fixture's account in. +struct RelatedPage { + /// The page's client. + client: piquel_common::clients::ClientRegistration, + /// The page's approved origin. + origin: RelatedOrigin, +} + +impl RelatedPage { + /// Registers a trusted public client on a fresh subdomain of auth's own domain, + /// which counts only as `piquel`, as every such origin does, and approves its origin. + async fn approved(database: &Database) -> Self { + let origin: RelatedOrigin = format!("https://{}.auth.piquel.fr", TokenId::new()) + .parse() + .expect("origin"); + let client = piquel_common::clients::ClientRegistration { + trusted: true, + ..crate::tests::registration( + piquel_common::clients::ClientKind::Public, + origin.as_str(), + ) + }; + register(database, &client).await.expect("client"); + change(database, async |registry| { + registry + .approve_origin(&client.id, &origin, "auth.piquel.fr") + .await + }) + .await + .expect("approved origin"); + Self { client, origin } + } +} + +impl Fixture { + /// Pushes `page`'s authorization request, with `extra` parameters, and returns + /// its `request_uri`. + async fn push(&self, page: &RelatedPage, extra: &[(&str, &str)]) -> String { + let challenge = piquel_crypto::Pkce::challenge(PAGE_VERIFIER).expect("PKCE"); + let form = url::form_urlencoded::Serializer::new(String::new()) + .extend_pairs([ + ("client_id", page.client.id.as_str()), + ("response_type", "code"), + ("redirect_uri", page.client.redirect_uris[0].as_str()), + ("scope", "openid"), + ("state", "page-state"), + ("code_challenge_method", "S256"), + ("code_challenge", &challenge), + ]) + .extend_pairs(extra.iter().copied()) + .finish(); + let request = Request::builder() + .method(Method::POST) + .uri(routes::oidc::PAR) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); + let response = self.send(request, form).await; + assert_eq!(response.status(), StatusCode::CREATED); + Self::json(response).await["request_uri"] + .as_str() + .expect("request_uri") + .to_owned() + } + /// Posts JSON from a page on `origin`, which sends no cookies. + async fn post_from(&self, origin: &str, path: &str, body: Value) -> Response { + let request = Request::builder() + .method(Method::POST) + .uri(path) + .header(header::ORIGIN, origin) + .header(header::CONTENT_TYPE, "application/json"); + self.send(request, body.to_string()).await + } + /// Starts `page`'s sign-in for `request_uri`. + async fn start_related(&self, page: &RelatedPage, request_uri: &str) -> Response { + self.post_from( + page.origin.as_str(), + routes::passkey::RELATED_START, + json!({"request_uri":request_uri}), + ) + .await + } + /// Signs `page`'s started sign-in for its own origin and finishes it from there. + async fn finish_related(&mut self, page: &RelatedPage, started: &Value) -> Response { + let assertion = self.assertion_for(page.origin.url().clone(), started); + self.post_from( + page.origin.as_str(), + routes::passkey::RELATED_FINISH, + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await + } + /// Redeems `code` for `page`'s client with `verifier`. + async fn redeem(&self, page: &RelatedPage, code: &str, verifier: &str) -> Response { + let form = url::form_urlencoded::Serializer::new(String::new()) + .extend_pairs([ + ("grant_type", "authorization_code"), + ("client_id", page.client.id.as_str()), + ("redirect_uri", page.client.redirect_uris[0].as_str()), + ("code", code), + ("code_verifier", verifier), + ]) + .finish(); + let request = Request::builder() + .method(Method::POST) + .uri(routes::oidc::TOKEN) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); + self.send(request, form).await + } + /// Lists the origins `/.well-known/webauthn` publishes. + async fn related_origins(&self) -> Vec { + let request = Request::builder() + .method(Method::GET) + .uri(routes::passkey::RELATED_ORIGINS); + let response = self.send(request, String::new()).await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers()[header::CACHE_CONTROL], + "public, max-age=300, no-transform" + ); + assert_eq!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); + serde_json::from_value(Self::json(response).await["origins"].take()).expect("origins") + } +} + +/// A page on an approved origin signs its account in without a cookie, and gets a +/// code that only its PKCE verifier redeems, once. The sign-in creates a session +/// recorded with the page's client and origin. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn related_pages_sign_in_for_pkce_bound_codes() { + let mut fixture = Fixture::new().await; + let replicas = Replicas::new().await; + fixture.on(&replicas.a); + let page = RelatedPage::approved(&fixture.app.database).await; + assert!( + fixture + .related_origins() + .await + .contains(&page.origin.to_string()) + ); + let mut codes = Vec::new(); + for _ in 0..2 { + let request_uri = fixture.push(&page, &[]).await; + let started = fixture.start_related(&page, &request_uri).await; + assert_eq!(started.status(), StatusCode::OK); + let headers = started.headers().clone(); + assert_eq!( + headers[header::ACCESS_CONTROL_ALLOW_ORIGIN], + page.origin.as_str() + ); + assert!( + headers + .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) + .is_none(), + "pages sign in without cookies" + ); + assert!(headers.get(header::SET_COOKIE).is_none()); + let started = Fixture::json(started).await; + // Signed on one replica, finished on the other. + let finished = fixture + .on(&replicas.b) + .finish_related(&page, &started) + .await; + assert_eq!(finished.status(), StatusCode::OK); + assert!(finished.headers().get(header::SET_COOKIE).is_none()); + let answer = Fixture::json(finished).await; + assert_eq!(answer["state"], "page-state"); + assert_eq!(answer["iss"], AUTH_ORIGIN); + codes.push(answer["code"].as_str().expect("code").to_owned()); + // The ceremony and its request are spent. + let assertion = fixture.assertion_for(page.origin.url().clone(), &started); + let replay = fixture + .post_from( + page.origin.as_str(), + routes::passkey::RELATED_FINISH, + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(replay.status(), StatusCode::BAD_REQUEST); + let reused = fixture.start_related(&page, &request_uri).await; + assert_eq!(reused.status(), StatusCode::BAD_REQUEST); + } + let wrong = "another-verifier-0123456789-abcdefghijklmnopqrstu"; + let redeemed = fixture.redeem(&page, &codes[0], wrong).await; + assert_eq!(redeemed.status(), StatusCode::BAD_REQUEST); + let redeemed = fixture.redeem(&page, &codes[1], PAGE_VERIFIER).await; + assert_eq!(redeemed.status(), StatusCode::OK); + let DomainEvent::SignedIn { + session_id, + method: AuthenticationMethod::Passkey, + inline: Some(inline), + } = fixture + .events() + .await + .into_iter() + .find(|event| matches!(event, DomainEvent::SignedIn { .. })) + .expect("sign-in") + else { + panic!("an inline passkey sign-in"); + }; + assert_eq!(inline.client_id, page.client.id); + assert_eq!(inline.origin, page.origin.into(), "kept as personal data"); + let session = fixture + .app + .database + .sessions() + .find_active_by_id(session_id) + .await + .expect("session lookup") + .expect("active session"); + assert_eq!( + SessionAuthentication::from(&session).acr, + Acr::PhishingResistant + ); +} + +/// Sign-in is refused to unapproved origins, for another client's request, from +/// another origin than its start, for an assertion signed for another origin and +/// without user verification. A request needing auth's pages stays usable there. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn related_sign_in_refuses_other_origins_requests_and_unverified_users() { + let mut fixture = Fixture::new().await; + let replicas = Replicas::new().await; + fixture.on(&replicas.a); + let page = RelatedPage::approved(&fixture.app.database).await; + let other = RelatedPage::approved(&fixture.app.database).await; + + let request_uri = fixture.push(&page, &[]).await; + let unapproved = fixture + .post_from( + "https://unapproved.example", + routes::passkey::RELATED_START, + json!({"request_uri":request_uri}), + ) + .await; + assert_eq!(unapproved.status(), StatusCode::FORBIDDEN); + assert!( + unapproved + .headers() + .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) + .is_none() + ); + // Another client's page cannot claim the request, which stays its client's. + let claimed = fixture.start_related(&other, &request_uri).await; + assert_eq!(claimed.status(), StatusCode::BAD_REQUEST); + let started = fixture.start_related(&page, &request_uri).await; + assert_eq!(started.status(), StatusCode::OK); + let started = Fixture::json(started).await; + // The ceremony finishes only on the page that started it. + let assertion = fixture.assertion_for(other.origin.url().clone(), &started); + let moved = fixture + .post_from( + other.origin.as_str(), + routes::passkey::RELATED_FINISH, + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(moved.status(), StatusCode::FORBIDDEN); + + // The verifier accepts auth's own origin too, but the page must have signed. + let started = Fixture::json( + fixture + .start_related(&page, &fixture.push(&page, &[]).await) + .await, + ) + .await; + let assertion = fixture.assertion(&started); + let elsewhere = fixture + .post_from( + page.origin.as_str(), + routes::passkey::RELATED_FINISH, + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(elsewhere.status(), StatusCode::BAD_REQUEST); + + let mut started = Fixture::json( + fixture + .start_related(&page, &fixture.push(&page, &[]).await) + .await, + ) + .await; + started["public_key"]["publicKey"]["userVerification"] = json!("discouraged"); + let unverified = fixture.finish_related(&page, &started).await; + assert_eq!(unverified.status(), StatusCode::BAD_REQUEST); + assert_eq!( + fixture.events().await.first(), + Some(&DomainEvent::SignInFailed { + method: AuthenticationMethod::Passkey, + reason: SignInFailure::InvalidCredential, + }) + ); + + // `prompt=consent` needs the consent page: the request is left for it. + let request_uri = fixture.push(&page, &[("prompt", "consent")]).await; + let refused = fixture.start_related(&page, &request_uri).await; + assert_eq!(refused.status(), StatusCode::BAD_REQUEST); + assert_eq!(Fixture::json(refused).await["code"], "interaction_required"); + let query = url::form_urlencoded::Serializer::new(String::new()) + .extend_pairs([ + ("client_id", page.client.id.as_str()), + ("request_uri", &request_uri), + ]) + .finish(); + let redirect = fixture + .request( + &format!("{}?{query}", routes::oidc::AUTHORIZE), + Method::GET, + "", + json!({}), + ) + .await; + assert_eq!(redirect.status(), StatusCode::SEE_OTHER); + + // A removed origin's pages stop at once. + change(&fixture.app.database, async |registry| { + registry.remove_origin(&page.client.id, &page.origin).await + }) + .await + .expect("removed"); + assert!( + !fixture + .related_origins() + .await + .contains(&page.origin.to_string()) + ); + let removed = fixture + .start_related(&page, &fixture.push(&page, &[]).await) + .await; + assert_eq!(removed.status(), StatusCode::FORBIDDEN); +} + +/// An account scheduled for deletion signs in on no related page: only auth's +/// sign-in page offers to restore it, so the page is told to send the user there. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn an_account_being_deleted_signs_in_on_auths_pages_only() { + let mut fixture = Fixture::new().await; + let replicas = Replicas::new().await; + fixture.on(&replicas.a); + let page = RelatedPage::approved(fixture.database()).await; + let mut tx = fixture.app.database.begin().await.expect("transaction"); + tx.users() + .set_status(fixture.user_id, AccountStatus::Deleting) + .await + .expect("status"); + tx.deletions() + .schedule( + fixture.user_id, + chrono::Utc::now() + chrono::Duration::days(30), + ) + .await + .expect("schedule"); + tx.commit().await.expect("commit"); + + let request_uri = fixture.push(&page, &[]).await; + let started = Fixture::json(fixture.start_related(&page, &request_uri).await).await; + let refused = fixture.finish_related(&page, &started).await; + assert_eq!(refused.status(), StatusCode::BAD_REQUEST); + assert!(refused.headers().get(header::SET_COOKIE).is_none()); + assert_eq!(Fixture::json(refused).await["code"], "interaction_required"); +} + +/// A recovered passkey during its probation signs in on a related page as on +/// auth's, without confirming the session, so a request for `phr` is refused with +/// `interaction_required`, for auth's pages to answer the client. Without that +/// target it signs in. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_probation_passkey_meets_no_phr_on_related_pages() { + let mut fixture = Fixture::new().await; + let replicas = Replicas::new().await; + fixture.on(&replicas.a); + let page = RelatedPage::approved(fixture.database()).await; + let recovery = piquel_common::RecoveryId::new(); + let mut recoveries = fixture.database().recoveries(); + recoveries + .insert(&piquel_repository::InsertRecovery { + id: recovery, + user_id: fixture.user_id, + secret_digest: &recovery.as_uuid().as_bytes().repeat(2), + expires_at: chrono::Utc::now() + chrono::Duration::hours(1), + }) + .await + .expect("recovery"); + let completed = recoveries + .complete( + fixture.user_id, + recovery, + fixture.key_id, + crate::recovery::PROBATION, + ) + .await; + assert!(completed.expect("complete")); + + let request_uri = fixture.push(&page, &[("acr_values", "phr")]).await; + let started = Fixture::json(fixture.start_related(&page, &request_uri).await).await; + let refused = fixture.finish_related(&page, &started).await; + assert_eq!(refused.status(), StatusCode::BAD_REQUEST); + assert_eq!(Fixture::json(refused).await["code"], "interaction_required"); + + let request_uri = fixture.push(&page, &[]).await; + let started = Fixture::json(fixture.start_related(&page, &request_uri).await).await; + assert_eq!( + fixture.finish_related(&page, &started).await.status(), + StatusCode::OK + ); +} diff --git a/apps/auth-service/src/passkey/tests/sign_in.rs b/apps/auth-service/src/passkey/tests/sign_in.rs new file mode 100644 index 000000000..b0e98afa0 --- /dev/null +++ b/apps/auth-service/src/passkey/tests/sign_in.rs @@ -0,0 +1,270 @@ +//! Passkey sign-in on auth's own pages: handles, sessions, replicas and accounts +//! scheduled for deletion. + +use super::*; +use crate::tests::OWN_PAGE; +use piquel_common::protocol::claims::Amr; + +/// Handles are public, so handle sign-in refuses a handle without an active +/// account, and text that is no handle, before starting any ceremony. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn handle_sign_in_refuses_a_handle_without_an_account_at_once() { + let fixture = Fixture::new().await; + for handle in [ + format!("none-{}", &TokenId::new().to_string()[24..]), + "@not a handle".to_owned(), + ] { + let response = fixture + .request( + routes::passkey::AUTHENTICATE_START, + Method::POST, + "", + json!({ "handle": handle }), + ) + .await; + assert_eq!(response.status(), StatusCode::NOT_FOUND, "{handle}"); + assert!(response.headers().get(header::SET_COOKIE).is_none()); + assert_eq!( + Fixture::json(response).await["error"], + "No active account has this handle." + ); + } +} + +/// Signing in with a passkey in a browser holding a social session of the same +/// account confirms that session, keeping its ID but replacing its cookie. A +/// session records the passkey that signed it in, or confirmed it since; a social +/// one names none. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn passkey_sign_in_confirms_the_browsers_session() { + let mut fixture = Fixture::new().await; + let mut tx = fixture.app.database.begin().await.expect("transaction"); + let secret = security::Session::create( + &mut tx, + security::RequestContext::TEST, + fixture.user_id, + AuthenticationMethod::Federation.into(), + ) + .await + .expect("social session"); + tx.commit().await.expect("commit"); + let social = format!("{}={}", BrowserCookie::Session.as_str(), secret.encoded()); + let before = fixture.session(&social).await.expect("social session"); + assert_eq!( + SessionAuthentication::from(&before).acr, + Acr::Social, + "social sign-in is not phishing-resistant" + ); + let cookie = fixture.login_from(&social).await; + assert!(fixture.session(&social).await.is_none(), "old cookie ends"); + let after = fixture.session(&cookie).await.expect("same session"); + assert_eq!(after.id, before.id); + let authentication = SessionAuthentication::from(&after); + assert_eq!(authentication.acr, Acr::PhishingResistant); + assert_eq!( + authentication.amr, + [Amr::Pop, Amr::Mfa, Amr::User, Amr::Fed], + "both methods are reported" + ); + assert!(authentication.auth_time > before.authenticated_at); + + let database = fixture.app.database.clone(); + let passkey = async |session| { + let mut sessions = database.sessions(); + sessions.passkey(session).await.expect("passkey") + }; + assert_eq!( + passkey(before.id).await, + Some(fixture.key_id), + "confirmed by it" + ); + let mut tx = fixture.app.database.begin().await.expect("transaction"); + let other = security::Session::create( + &mut tx, + security::RequestContext::TEST, + fixture.user_id, + AuthenticationMethod::Federation.into(), + ) + .await + .expect("another social session"); + tx.commit().await.expect("commit"); + let other = format!("{}={}", BrowserCookie::Session.as_str(), other.encoded()); + let other = fixture.session(&other).await.expect("social session").id; + assert_eq!(passkey(other).await, None, "a social sign-in names none"); + let fresh = fixture.login().await; + let fresh = fixture.session(&fresh).await.expect("new session").id; + assert_eq!( + passkey(fresh).await, + Some(fixture.key_id), + "signed in by it" + ); + + // With two passkeys, the asserting one is recorded: signing in with the + // newer one, and confirming with it a session the older one signed in. + let newer = fixture.switch_passkey("Newer key").await; + let signed_in = fixture.login().await; + let signed_in = fixture.session(&signed_in).await.expect("new session").id; + assert_eq!(passkey(signed_in).await, Some(newer), "signed in by it"); + let (started, browser) = fixture + .start("/account/passkeys/confirm/start", &cookie, json!({})) + .await; + let assertion = fixture.assertion(&started); + let response = fixture + .request( + "/account/passkeys/confirm/finish", + Method::POST, + &format!("{cookie}; {browser}"), + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + assert_eq!(passkey(before.id).await, Some(newer), "confirmed by it"); +} + +/// A sign-in started on one replica finishes on the other, and signing out on one +/// ends the session on both. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn sign_in_and_logout_span_replicas() { + let mut fixture = Fixture::new().await; + let replicas = Replicas::new().await; + let username = json!({"handle":fixture.username}); + let (started, browser) = fixture + .on(&replicas.a) + .start("/webauthn/authenticate/start", "", username) + .await; + let assertion = fixture.assertion(&started); + let finished = fixture + .on(&replicas.b) + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert_eq!(finished.status(), StatusCode::NO_CONTENT); + let session = Fixture::cookie(&finished); + fixture.on(&replicas.a); + let read = fixture.request(routes::passkey::LIST, Method::GET, &session, json!({})); + assert_eq!(read.await.status(), StatusCode::OK); + let browser = Browser { + cookie: session.clone(), + ..Browser::signed_out() + }; + let logout = browser + .submit(&replicas.a, routes::page::LOGOUT, &[], OWN_PAGE) + .await; + assert_eq!(logout.status(), StatusCode::SEE_OTHER); + fixture.on(&replicas.b); + let read = fixture.request(routes::passkey::LIST, Method::GET, &session, json!({})); + assert_eq!(read.await.status(), StatusCode::UNAUTHORIZED); +} + +/// A passkey sign-in to an account scheduled for deletion gets no session, but an +/// offer, in its own cookie, which the sign-in page restores the account with once, +/// signing in with that passkey, on any replica. A disabled account gets neither. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn signing_in_to_an_account_scheduled_for_deletion_offers_to_restore_it() { + let mut fixture = Fixture::new().await; + let replicas = Replicas::new().await; + let mut tx = fixture.app.database.begin().await.expect("transaction"); + tx.users() + .set_status(fixture.user_id, AccountStatus::Deleting) + .await + .expect("status"); + tx.deletions() + .schedule( + fixture.user_id, + chrono::Utc::now() + chrono::Duration::days(30), + ) + .await + .expect("schedule"); + tx.commit().await.expect("commit"); + + let username = json!({"username": fixture.username}); + let (started, browser) = fixture + .on(&replicas.a) + .start("/webauthn/authenticate/start", "", username.clone()) + .await; + let assertion = fixture.assertion(&started); + let offered = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + json!({"ceremony_id": started["ceremony_id"], "credential": assertion}), + ) + .await; + assert_eq!(offered.status(), StatusCode::NO_CONTENT); + let offer = Fixture::cookie(&offered); + assert!( + offer.starts_with(BrowserCookie::Restore.as_str()), + "an offer, and no session: {offer}" + ); + + let holder = Browser { + cookie: offer, + ..Browser::signed_out() + }; + let restore = [("action", "restore")]; + let restored = holder + .submit(&replicas.b, routes::page::LOGIN, &restore, OWN_PAGE) + .await; + assert_eq!(restored.status(), StatusCode::SEE_OTHER); + let session = restored + .headers() + .get_all(header::SET_COOKIE) + .iter() + .filter_map(|cookie| cookie.to_str().ok()) + .find(|cookie| cookie.starts_with(BrowserCookie::Session.as_str())) + .and_then(|cookie| cookie.split(';').next()) + .expect("signed in") + .to_owned(); + let session = fixture.session(&session).await.expect("session"); + assert_eq!(session.user_id, fixture.user_id); + assert_eq!( + fixture + .app + .database + .sessions() + .passkey(session.id) + .await + .expect("passkey"), + Some(fixture.key_id) + ); + assert_eq!(fixture.events().await[1], DomainEvent::AccountRestored {}); + let again = holder + .submit(&replicas.a, routes::page::LOGIN, &restore, OWN_PAGE) + .await; + assert_eq!( + again.status(), + StatusCode::BAD_REQUEST, + "an offer restores once" + ); + + // Disabled after the ceremony started, which still names the passkey. + let (started, browser) = fixture + .start("/webauthn/authenticate/start", "", username) + .await; + fixture + .app + .database + .users() + .set_status(fixture.user_id, AccountStatus::Disabled) + .await + .expect("disable"); + let assertion = fixture.assertion(&started); + let refused = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + json!({"ceremony_id": started["ceremony_id"], "credential": assertion}), + ) + .await; + assert_eq!(refused.status(), StatusCode::UNAUTHORIZED); +} diff --git a/apps/auth-service/src/passkey/tests/telemetry.rs b/apps/auth-service/src/passkey/tests/telemetry.rs new file mode 100644 index 000000000..332109324 --- /dev/null +++ b/apps/auth-service/src/passkey/tests/telemetry.rs @@ -0,0 +1,197 @@ +//! Telemetry of a sign-in and code exchange exports no secret. + +use super::*; + +impl Fixture { + /// Signs in with the passkey, and returns the session cookie pair and every + /// secret the ceremony carried: its cookie and ID, the challenge and signature. + async fn login_with_secrets(&mut self) -> (String, Vec) { + let username = json!({"handle": self.username}); + let (started, browser) = self + .start("/webauthn/authenticate/start", "", username) + .await; + let assertion = self.assertion(&started); + let signature = + serde_json::to_value(&assertion).expect("assertion")["response"]["signature"] + .as_str() + .expect("signature") + .to_owned(); + let finished = self + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + json!({"ceremony_id": started["ceremony_id"], "credential": assertion}), + ) + .await; + assert_eq!(finished.status(), StatusCode::NO_CONTENT); + let session = Self::cookie(&finished); + let cookie = |pair: &str| pair.split_once('=').expect("cookie pair").1.to_owned(); + let secrets = vec![ + cookie(&session), + cookie(&browser), + started["ceremony_id"] + .as_str() + .expect("ceremony") + .to_owned(), + started["public_key"]["publicKey"]["challenge"] + .as_str() + .expect("challenge") + .to_owned(), + signature, + ]; + (session, secrets) + } + + /// Authorizes the trusted `client` for the browser holding `session`, exchanges + /// the code, and returns every secret the flow carried: the authorization + /// query's state, nonce and PKCE challenge, the code, its verifier and the tokens. + async fn exchange_with_secrets( + &self, + session: &str, + client: &piquel_common::clients::ClientRegistration, + ) -> Vec { + let verifier = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + let challenge = piquel_crypto::Pkce::challenge(verifier).expect("PKCE"); + let mut authorize = Url::parse(&format!("{AUTH_ORIGIN}/oauth/authorize")).expect("URL"); + authorize.query_pairs_mut().extend_pairs([ + ("response_type", "code"), + ("client_id", client.id.as_str()), + ("redirect_uri", client.redirect_uris[0].as_str()), + ("scope", "openid offline_access"), + ("state", "state-in-the-query"), + ("nonce", "nonce-in-the-query"), + ("code_challenge_method", "S256"), + ("code_challenge", &challenge), + ]); + let send = |request: Request| self.router.clone().oneshot(request); + let authorized = send( + Request::builder() + .uri(format!( + "{}?{}", + authorize.path(), + authorize.query().expect("query") + )) + .header(header::COOKIE, session) + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response"); + assert_eq!(authorized.status(), StatusCode::SEE_OTHER); + let redirect = Url::parse( + authorized.headers()[header::LOCATION] + .to_str() + .expect("location"), + ) + .expect("redirect"); + let code = redirect + .query_pairs() + .find(|(name, _)| name == "code") + .expect("code") + .1 + .into_owned(); + let form = url::form_urlencoded::Serializer::new(String::new()) + .extend_pairs([ + ("grant_type", "authorization_code"), + ("client_id", client.id.as_str()), + ("redirect_uri", client.redirect_uris[0].as_str()), + ("code", &code), + ("code_verifier", verifier), + ]) + .finish(); + let exchanged = send( + Request::builder() + .method(Method::POST) + .uri("/oauth/token") + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from(form)) + .expect("request"), + ) + .await + .expect("response"); + assert_eq!(exchanged.status(), StatusCode::OK); + let tokens = Self::json(exchanged).await; + let mut secrets = vec![ + "state-in-the-query".to_owned(), + "nonce-in-the-query".to_owned(), + challenge, + code, + verifier.to_owned(), + ]; + for token in ["access_token", "id_token", "refresh_token"] { + secrets.push(tokens[token].as_str().expect("token").to_owned()); + } + secrets + } +} + +/// A passkey sign-in, then an authorization code exchanged for tokens, through +/// replicas of the whole service, export no secret: no cookie, ceremony, `WebAuthn` +/// challenge or assertion, authorization query, code, PKCE verifier or token. Each +/// request is one trace holding its queries, and the events it records are logged +/// in it. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn telemetry_exports_no_secret_of_a_sign_in_and_code_exchange() { + use piquel_telemetry::Telemetry; + + let capture = Telemetry::capture(crate::TELEMETRY_FILTER); + let mut fixture = Fixture::new().await; + let replicas = Replicas::new().await; + let client = piquel_common::clients::ClientRegistration { + trusted: true, + ..crate::tests::registration( + piquel_common::clients::ClientKind::Public, + "https://client.example", + ) + }; + crate::tests::register(&fixture.app.database, &client) + .await + .expect("client"); + let (session, mut secrets) = fixture.on(&replicas.a).login_with_secrets().await; + secrets.extend( + fixture + .on(&replicas.b) + .exchange_with_secrets(&session, &client) + .await, + ); + let exported = capture.exported_text(); + for secret in &secrets { + assert!( + exported.iter().all(|text| !text.contains(secret.as_str())), + "telemetry exported {secret}" + ); + } + + let spans = capture.spans(); + let exchange = spans + .iter() + .find(|span| span.name == "POST /oauth/token") + .expect("token request span"); + let trace = exchange.span_context.trace_id(); + assert!( + spans.iter().any(|span| { + span.span_context.trace_id() == trace + && span + .attributes + .iter() + .any(|attribute| attribute.key.as_str() == "db.query.text") + }), + "the exchange's queries are spans of its trace" + ); + let logged = capture + .logs() + .into_iter() + .find(|log| { + log.attributes_iter().any(|(key, value)| { + key.as_str() == "event.kind" && format!("{value:?}").contains("grant_issued") + }) + }) + .expect("the issued grant is logged"); + assert_eq!( + logged.trace_context().map(|context| context.trace_id), + Some(trace), + "the event's log line links to the exchange's trace" + ); +} diff --git a/apps/auth-service/src/passkey/tests/validation.rs b/apps/auth-service/src/passkey/tests/validation.rs new file mode 100644 index 000000000..ddb18d535 --- /dev/null +++ b/apps/auth-service/src/passkey/tests/validation.rs @@ -0,0 +1,98 @@ +//! Name validation, typed ceremony payloads and the account states a passkey +//! is accepted for. + +use super::*; + +/// Names count Unicode characters, preserve spacing and reject blank/control input. +#[test] +fn display_and_passkey_names_share_unicode_validation() { + for valid in [" Alice ".to_owned(), "é".repeat(80)] { + assert_eq!( + DisplayName::parse(valid.clone()) + .expect("display name") + .as_str(), + valid + ); + assert_eq!( + PasskeyName::parse(valid.clone()) + .expect("passkey name") + .as_str(), + valid + ); + } + for invalid in [String::new(), " \t ".into(), "a\0b".into(), "é".repeat(81)] { + assert!(matches!( + DisplayName::parse(invalid.clone()), + Err(PasskeyError::InvalidDisplayName) + )); + assert!(matches!( + PasskeyName::parse(invalid), + Err(PasskeyError::InvalidPasskeyName) + )); + } +} + +/// Typed payloads retain the stored ceremony representation and reject wrong consumers. +#[test] +fn typed_ceremonies_preserve_persistence_and_check_the_expected_payload() { + use ceremonies::CeremonyState; + + let user_id = UserId::new(); + let session_id = piquel_common::SessionId::new(); + let origin = Url::parse("https://auth.piquel.fr").expect("origin"); + let webauthn = WebauthnBuilder::new("auth.piquel.fr", &origin) + .expect("builder") + .build() + .expect("WebAuthn"); + let (_, state) = webauthn + .start_discoverable_authentication() + .expect("challenge"); + let encoded_state = serde_json::to_value(&state).expect("state"); + let ceremony = Ceremony::Discover(DiscoverCeremony { state }); + assert_eq!( + ceremony.kind(), + piquel_repository::CeremonyKind::Authentication + ); + let encoded = serde_json::to_value(ceremony).expect("ceremony"); + assert_eq!(encoded, json!({"Discover":{"state":encoded_state}})); + let stored = || serde_json::from_value(encoded.clone()).expect("stored ceremony"); + assert!(AuthenticationCeremony::extract(stored()).is_some()); + assert!(RegistrationCeremony::extract(stored()).is_none()); + assert!(EnrollmentCeremony::extract(stored()).is_none()); + assert!(ConfirmationCeremony::extract(stored()).is_none()); + + let (_, state) = webauthn + .start_passkey_registration(user_id.as_uuid(), "alice", "Alice", None) + .expect("registration"); + let enrollment = Ceremony::Enroll(EnrollmentCeremony { + user_id, + session_id, + state, + }); + assert_eq!(enrollment.kind(), EnrollmentCeremony::KIND); + assert!(EnrollmentCeremony::extract(enrollment).is_some()); +} + +/// Sign-in and confirmation accept only an active account's passkey; the +/// owner's undo of a recovery accepts a disabled account's too, without a +/// credential to sign in with. An account being deleted has nothing to accept. +#[test] +fn only_an_undo_accepts_a_disabled_accounts_passkey() { + let passkey = PasskeyId::new(); + let credential = Credential::Passkey(passkey); + let signs_in = |status| ::accept(status, passkey, credential); + assert_eq!(signs_in(AccountStatus::Active).ok(), Some(credential)); + for status in [AccountStatus::Disabled, AccountStatus::Deleting] { + assert!(matches!( + signs_in(status), + Err(PasskeyError::AccountInactive) + )); + } + let undoes = |status| ::accept(status, passkey, credential); + assert!(matches!(undoes(AccountStatus::Active), Ok(Accepted::Active(id)) if id == passkey)); + assert!(matches!(undoes(AccountStatus::Disabled), Ok(Accepted::Disabled(id)) if id == passkey)); + assert!(matches!( + undoes(AccountStatus::Deleting), + Err(PasskeyError::AccountInactive) + )); +} diff --git a/apps/auth-service/src/recovery/tests.rs b/apps/auth-service/src/recovery/tests.rs deleted file mode 100644 index 71bef6a30..000000000 --- a/apps/auth-service/src/recovery/tests.rs +++ /dev/null @@ -1,1372 +0,0 @@ -//! Database-backed recovery scenarios: what starting one does and refuses, what a -//! link enrolls, what a probation passkey can and cannot do, who may undo a -//! recovery and what undoing it takes back, and what nobody may remove meanwhile. - -use super::*; -use crate::{ - AdminError, AdminService, - account::Subject, - admin::tests::{Harness, cli, operator}, - passkey::{VerifiedRecoveryUndo, tests::Fixture}, - security::{BrowserCookie, Credential, Session, SessionError}, - tests::{ - Browser, recovery_links, recovery_reason, recovery_token, refresh_grant, register, - registration, until_blocked, verified_address, - }, -}; -use axum::{ - http::{Method, StatusCode}, - response::Response, -}; -use piquel_common::{ - AuthenticationMethod, ClientId, EmailId, Provider, TokenId, - clients::ClientKind, - events::{RecoveryRevocation, SignInFailure}, - protocol::claims::Acr, -}; -use piquel_repository::{ - Database, InsertExternalIdentity, InsertUnverifiedEmail, SessionAuthentication, StoredSession, -}; -use serde_json::{Value, json}; -use std::collections::HashSet; -use webauthn_authenticator_rs::{WebauthnAuthenticator, softpasskey::SoftPasskey}; - -/// An error body's `code`. -async fn code(response: Response) -> Value { - Fixture::json(response).await["code"].clone() -} - -/// An account with a passkey, recovered by an operator at the terminal, and the -/// browsers that act on it. -struct Scenario { - /// The account, its original passkey and the routes. Its authenticator is the - /// one that signs. - keys: Fixture, - /// Derives the links. - links: RecoveryLinks, - /// The authenticator not signing now: the recovery's, or the original one - /// while the recovery's signs ([`Self::swap`]). - other: Option>, -} - -impl Scenario { - /// An account with one passkey, not recovered yet. - async fn new() -> Self { - Self { - keys: Fixture::new().await, - links: recovery_links(), - other: None, - } - } - - /// The scenario database. - fn database(&self) -> &Database { - self.keys.database() - } - - /// The account. - const fn user(&self) -> UserId { - self.keys.user_id - } - - /// The support operations. - fn admin(&self) -> AdminService { - AdminService::new(self.database().clone(), true) - } - - /// Starts recovering the account as an operator at the terminal, with - /// `revoke`, and returns the link it prints. - async fn start(&self, revoke: Option) -> Result { - let link = self - .admin() - .recover_account(&cli(), self.user(), recovery_reason(), &self.links, revoke) - .await?; - Ok(link.expect("the terminal sees the link")) - } - - /// Recovers the account as an operator at the terminal, and returns the - /// link's token. - async fn recover(&self) -> String { - recovery_token(&self.start(None).await.expect("recovery")) - } - - /// Whether the link holding `token` still works, as its page reads it. - async fn works(&self, token: &str) -> bool { - let service = AccountService::new(self.database().clone()); - service.open_recovery(token).await.is_ok() - } - - /// Enrolls a passkey with `token` from the browser holding `cookies`, keeping - /// its authenticator as [`Self::other`]. Returns the finish response. - async fn enroll_from(&mut self, token: &str, cookies: &str) -> Response { - let body = json!({ "token": token }); - let (started, browser) = self - .keys - .start(routes::recovery::START, cookies, body) - .await; - let (credential, authenticator) = self.keys.new_authenticator(&started); - self.other = Some(authenticator); - let body = json!({ - "ceremony_id": started["ceremony_id"], - "credential": credential, - "friendly_name": "Recovered", - }); - let cookies = format!("{cookies}; {browser}"); - self.keys - .request(routes::recovery::FINISH, Method::POST, &cookies, body) - .await - } - - /// Enrolls a passkey with `token` from a browser with no session, and returns - /// the session cookie it signs in with. - async fn enroll(&mut self, token: &str) -> String { - let response = self.enroll_from(token, "").await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - Fixture::cookie(&response) - } - - /// Signs with the other authenticator from now on: the recovery's after - /// [`Self::enroll`], then the original one again. - fn swap(&mut self) { - let other = self.other.take().expect("another authenticator"); - self.other = Some(self.keys.replace_authenticator(other)); - } - - /// Signs in with the signing authenticator from the browser holding - /// `session`. Returns the finish response. - async fn login(&mut self, session: &str) -> Response { - let body = json!({ "handle": self.keys.username }); - let (started, browser) = self - .keys - .start("/webauthn/authenticate/start", "", body) - .await; - let body = json!({ - "ceremony_id": started["ceremony_id"], - "credential": self.keys.assertion(&started), - }); - let cookies = format!("{session}; {browser}"); - self.keys - .request( - "/webauthn/authenticate/finish", - Method::POST, - &cookies, - body, - ) - .await - } - - /// Confirms the session of the browser holding `cookie` with the signing - /// authenticator. Returns the finish response. - async fn confirm(&mut self, cookie: &str) -> Response { - let (started, browser) = self - .keys - .start("/account/passkeys/confirm/start", cookie, json!({})) - .await; - let body = json!({ - "ceremony_id": started["ceremony_id"], - "credential": self.keys.assertion(&started), - }); - let cookies = format!("{cookie}; {browser}"); - self.keys - .request( - "/account/passkeys/confirm/finish", - Method::POST, - &cookies, - body, - ) - .await - } - - /// The account's recovery that can still be undone, as the browser holding - /// `cookie` sees it. - async fn status(&self, cookie: &str) -> Value { - let response = self - .keys - .request(routes::recovery::STATUS, Method::GET, cookie, Value::Null) - .await; - assert_eq!(response.status(), StatusCode::OK); - Fixture::json(response).await - } - - /// The account's latest recovery. - async fn latest(&self) -> StoredRecovery { - let latest = self.database().recoveries().latest(self.user()).await; - latest.expect("lookup").expect("a recovery") - } - - /// Starts undoing recovery `id` from a browser with no session. Returns the - /// refusal, or the challenge and the browser's ceremony cookie. - async fn undo_start(&self, id: RecoveryId) -> Result<(Value, String), StatusCode> { - let body = json!({ "recovery_id": id }); - let response = self - .keys - .request(routes::recovery::UNDO_START, Method::POST, "", body) - .await; - if response.status() != StatusCode::OK { - return Err(response.status()); - } - let browser = Fixture::cookie(&response); - Ok((Fixture::json(response).await, browser)) - } - - /// Undoes recovery `id` with the signing authenticator, from a browser with - /// no session. Returns the status, the body, and the session cookie it signs - /// in with, if any. - async fn undo(&mut self, id: RecoveryId) -> (StatusCode, Value, Option) { - let (started, browser) = match self.undo_start(id).await { - Ok(started) => started, - Err(status) => return (status, Value::Null, None), - }; - let body = json!({ - "ceremony_id": started["ceremony_id"], - "credential": self.keys.assertion(&started), - }); - let response = self - .keys - .request(routes::recovery::UNDO_FINISH, Method::POST, &browser, body) - .await; - let status = response.status(); - let cookie = response - .headers() - .contains_key(axum::http::header::SET_COOKIE) - .then(|| Fixture::cookie(&response)); - (status, Fixture::json(response).await, cookie) - } - - /// Removes `passkey` from the browser holding `cookie`. - async fn remove(&self, cookie: &str, passkey: PasskeyId) -> Response { - let path = routes::passkey::ITEM.replace("{id}", &passkey.to_string()); - self.keys - .request(&path, Method::DELETE, cookie, Value::Null) - .await - } - - /// Signs a browser in with `passkey`, which confirms its session, and returns - /// its session cookie. - async fn signed_in_with(&self, passkey: PasskeyId) -> String { - let mut tx = self.database().begin().await.expect("transaction"); - let credential = Credential::Passkey(passkey); - let secret = Session::create(&mut tx, RequestContext::TEST, self.user(), credential).await; - tx.commit().await.expect("commit"); - let secret = secret.expect("session").encoded(); - format!("{}={secret}", BrowserCookie::Session.as_str()) - } - - /// The live session of the browser holding `cookie`, if any. - async fn session(&self, cookie: &str) -> Option { - self.keys.session(cookie).await - } - - /// Registers a client at `origin` and records the account's consent to it. - async fn consent(&self, origin: &str) -> ClientId { - let client = registration(ClientKind::Public, origin); - register(self.database(), &client).await.expect("client"); - let scopes = ["openid".to_owned()]; - self.database() - .oidc() - .save_consent(self.user(), &client.id, client.id.as_str(), &scopes) - .await - .expect("consent"); - client.id - } - - /// The clients the account consented to. - async fn consents(&self) -> Vec { - let consents = self.database().oidc().list_consents(self.user()).await; - let consents = consents.expect("consents").into_iter(); - consents.map(|consent| consent.client_id).collect() - } - - /// The account's active passkeys. - async fn passkeys(&self) -> HashSet { - let passkeys = self.database().passkeys().list_active(self.user()).await; - let passkeys = passkeys.expect("passkeys").into_iter(); - passkeys.map(|passkey| passkey.id).collect() - } - - /// The providers of the account's linked identities. - async fn identities(&self) -> Vec { - let identities = self.database().federation().list_active(self.user()).await; - let identities = identities.expect("identities").into_iter(); - identities.map(|identity| identity.provider).collect() - } - - /// Links an identity of `provider` to the account. - async fn link(&self, provider: Provider) { - self.database() - .federation() - .insert_identity(&InsertExternalIdentity { - id: TokenId::new(), - user_id: self.user(), - provider, - issuer: format!("https://{provider}.example"), - subject: TokenId::new().to_string(), - linked_email: None, - }) - .await - .expect("identity"); - } - - /// Adds a verified address named `name`, primary if `is_primary`. - async fn address(&self, name: &str, is_primary: bool) -> EmailId { - let address = format!("{name}-{}@example.com", self.user()); - verified_address(self.database(), self.user(), &address, is_primary).await - } - - /// Adds an unverified address named `name`, and returns it and its - /// verification token. - async fn unverified(&self, name: &str) -> (EmailId, Secret) { - let id = EmailId::new(); - let token = Secret::generate().expect("token"); - let address = format!("{name}-{}@example.com", self.user()); - self.database() - .emails() - .insert_unverified(&InsertUnverifiedEmail { - id, - user_id: self.user(), - normalized_email: &address, - secret_digest: token.digest().as_bytes(), - expires_at: Utc::now() + Duration::hours(1), - }) - .await - .expect("unverified address"); - (id, token) - } - - /// How many messages were queued to the account's address `email`. - async fn sent(&self, email: EmailId) -> usize { - let destination = format!("account {}, address {email}", self.user()); - self.database() - .deliveries() - .list(None, Some("email"), 1000) - .await - .expect("deliveries") - .iter() - .filter(|delivery| delivery.destination == destination) - .count() - } - - /// The kinds of the messages queued to the account's address `email`, oldest - /// first, with whether a `--revoke` start's notice says a passkey was kept. - async fn messages(&self, email: EmailId) -> Vec<(String, Option)> { - let destination = format!("account {}, address {email}", self.user()); - let payloads = self.database().deliveries().payloads(&destination).await; - let payloads = payloads.expect("payloads").into_iter(); - payloads - .map(|payload| { - let kind = payload["type"].as_str().expect("type").to_owned(); - (kind, payload["kept"].as_bool()) - }) - .collect() - } - - /// The account's events, newest first. - async fn events(&self) -> Vec { - self.keys.events().await - } -} - -/// Starting a recovery signs the account out everywhere, ends its refresh grants -/// and removes its unverified addresses, so an older verification link stops -/// working. Its link goes to the primary address only. The link enrolls one -/// passkey, once, and signs in with it without confirming the session: no -/// confirmed change accepts it, and confirming with it is refused until the -/// recovery settles. Every verified address hears of it. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn a_link_enrolls_one_passkey_that_signs_in_without_confirming() { - let mut scenario = Scenario::new().await; - let primary = scenario.address("primary", true).await; - let other = scenario.address("other", false).await; - let (pending, _) = scenario.unverified("pending").await; - let before = scenario.signed_in_with(scenario.keys.key_id).await; - let before_id = scenario.session(&before).await.expect("session").id; - let client = scenario.consent("https://notes.example").await; - let family = TokenId::new(); - refresh_grant( - scenario.database(), - scenario.user(), - before_id, - &client, - family, - ) - .await; - - let token = scenario.recover().await; - assert!(scenario.session(&before).await.is_none(), "signed out"); - let mut tokens = scenario.database().tokens(); - let grants = tokens.revoke_for_user(scenario.user(), None).await; - assert_eq!(grants.expect("grants"), 0, "already ended"); - let emails = scenario.database().emails().list(scenario.user()).await; - let emails: Vec<_> = emails - .expect("emails") - .iter() - .map(|email| email.id) - .collect(); - assert!(!emails.contains(&pending), "the unverified address is gone"); - assert_eq!( - (scenario.sent(primary).await, scenario.sent(other).await), - (1, 0), - "the link goes to the primary address only" - ); - assert!(scenario.works(&token).await); - let service = AccountService::new(scenario.database().clone()); - let opened = service.open_recovery(&token).await.expect("open"); - let account = opened.account(); - assert_eq!( - account.handle.as_str(), - scenario.keys.username, - "names the account" - ); - - let cookie = scenario.enroll(&token).await; - let session = scenario.session(&cookie).await.expect("session"); - assert_eq!(session.passkey_confirmed_at, None, "not confirmed"); - assert_eq!(SessionAuthentication::from(&session).acr, Acr::Social); - let recovered = scenario.latest().await.passkey_id.expect("its passkey"); - let signed_by = scenario.database().sessions().passkey(session.id).await; - assert_eq!(signed_by.expect("passkey"), Some(recovered)); - assert_eq!( - (scenario.sent(primary).await, scenario.sent(other).await), - (2, 1), - "every verified address hears of it" - ); - assert!(!scenario.works(&token).await, "used"); - - let response = scenario - .keys - .request( - "/account/passkeys/enroll/start", - Method::POST, - &cookie, - json!({}), - ) - .await; - assert_eq!(response.status(), StatusCode::FORBIDDEN); - assert_eq!(code(response).await, "step_up_required"); - scenario.swap(); - let response = scenario.confirm(&cookie).await; - assert_eq!(response.status(), StatusCode::FORBIDDEN); - assert_eq!(code(response).await, "recovery_probation"); - let session = scenario.session(&cookie).await.expect("session"); - assert_eq!(session.passkey_confirmed_at, None, "still not confirmed"); - - // The probation lasts 15 days: a minute before, still refused; after, it - // settled. - let recovery = scenario.latest().await.id; - let database = scenario.database().clone(); - let almost = Duration::days(15) - Duration::minutes(1); - database - .recoveries() - .backdate_completion(recovery, almost) - .await - .expect("backdate"); - let response = scenario.confirm(&cookie).await; - assert_eq!(response.status(), StatusCode::FORBIDDEN, "a minute before"); - database - .recoveries() - .backdate_completion(recovery, Duration::minutes(2)) - .await - .expect("settle"); - let response = scenario.confirm(&cookie).await; - assert_eq!(response.status(), StatusCode::NO_CONTENT, "once settled"); -} - -/// A link enrolls one passkey even when two of its ceremonies started before -/// either finished: the second finish fails, stores no passkey, and leaves the -/// recovery bound to the first, which stays in probation. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn a_link_enrolls_once_however_many_ceremonies_started() { - let scenario = Scenario::new().await; - let token = scenario.recover().await; - let body = json!({ "token": token }); - let mut started = Vec::new(); - for _ in 0..2 { - let start = scenario - .keys - .start(routes::recovery::START, "", body.clone()) - .await; - started.push(start); - } - let finish = async |(started, browser): &(Value, String)| { - let body = json!({ - "ceremony_id": started["ceremony_id"], - "credential": scenario.keys.credential(started), - "friendly_name": "Recovered", - }); - scenario - .keys - .request(routes::recovery::FINISH, Method::POST, browser, body) - .await - }; - let first = finish(&started[0]).await; - assert_eq!(first.status(), StatusCode::NO_CONTENT); - let bound = scenario.latest().await.passkey_id; - let second = finish(&started[1]).await; - assert_eq!(second.status(), StatusCode::BAD_REQUEST); - assert_eq!(code(second).await, "invalid_link"); - assert_eq!(scenario.passkeys().await.len(), 2, "no second passkey"); - assert_eq!(scenario.latest().await.passkey_id, bound, "still the first"); -} - -/// A link signs its browser in with a new session, whatever session the browser -/// had. A probation passkey signing in again renews an unconfirmed session, -/// recording itself and its method without confirming it, and never downgrades a -/// confirmed one. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn a_probation_passkey_signs_in_anew_and_never_confirms() { - let mut scenario = Scenario::new().await; - let token = scenario.recover().await; - let social = Browser::sign_in_with( - scenario.database(), - scenario.user(), - AuthenticationMethod::Federation, - ) - .await; - let response = scenario.enroll_from(&token, &social.cookie).await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - let cookie = Fixture::cookie(&response); - let session = scenario.session(&cookie).await.expect("session"); - assert_ne!(session.id, social.session_id, "a new session"); - let social_session = scenario - .database() - .sessions() - .find_by_id(social.session_id) - .await; - let revoked = social_session.expect("lookup").expect("session").revoked_at; - assert!(revoked.is_some(), "the browser's session is revoked"); - let recovered = scenario.latest().await.passkey_id.expect("its passkey"); - scenario.swap(); - - let social = Browser::sign_in_with( - scenario.database(), - scenario.user(), - AuthenticationMethod::Federation, - ) - .await; - let response = scenario.login(&social.cookie).await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - let renewed = Fixture::cookie(&response); - let session = scenario.session(&renewed).await.expect("session"); - assert_eq!(session.id, social.session_id, "renewed"); - assert_eq!(session.passkey_confirmed_at, None, "not confirmed"); - assert_eq!( - session.authentication_methods, - [ - AuthenticationMethod::Federation, - AuthenticationMethod::Passkey - ] - ); - let signed_by = scenario.database().sessions().passkey(session.id).await; - assert_eq!(signed_by.expect("passkey"), Some(recovered)); - - let confirmed = scenario.signed_in_with(scenario.keys.key_id).await; - let response = scenario.login(&confirmed).await; - assert_eq!(response.status(), StatusCode::FORBIDDEN); - let body = Fixture::json(response).await; - assert_eq!(body["code"], "passkey_required"); - let says = body["error"].as_str().expect("message"); - assert!(says.ends_with("Sign out first."), "{says}"); - let session = scenario.session(&confirmed).await.expect("session"); - assert!(session.passkey_confirmed_at.is_some(), "not downgraded"); - - // A link used in a browser an older passkey confirmed still signs in anew. - let token = { - scenario.swap(); - let undoable = scenario.latest().await.id; - let (status, ..) = scenario.undo(undoable).await; - assert_eq!(status, StatusCode::OK); - scenario.recover().await - }; - let confirmed = scenario.signed_in_with(scenario.keys.key_id).await; - let response = scenario.enroll_from(&token, &confirmed).await; - assert_eq!( - response.status(), - StatusCode::NO_CONTENT, - "from a confirmed browser" - ); -} - -/// Undoing a recovery in probation, with a passkey from before it and no -/// session, takes back what whoever used its link could keep: its passkey, every -/// session and refresh grant, and every consent, old and new. It signs the -/// undoing browser in, and leaves nothing to undo. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn undo_takes_back_the_passkey_sessions_grants_and_consents() { - let mut scenario = Scenario::new().await; - scenario.consent("https://notes.example").await; - let token = scenario.recover().await; - let cookie = scenario.enroll(&token).await; - let recovery = scenario.latest().await; - let recovered = recovery.passkey_id.expect("its passkey"); - let probation_session = scenario.session(&cookie).await.expect("session").id; - let client = scenario.consent("https://photos.example").await; - let family = TokenId::new(); - refresh_grant( - scenario.database(), - scenario.user(), - probation_session, - &client, - family, - ) - .await; - - let status = scenario.status(&cookie).await; - assert_eq!(status["state"], "probation"); - assert_eq!(status["passkey"]["id"], json!(recovered)); - let undo_with: Vec<_> = status["undo_with"] - .as_array() - .expect("undo_with") - .iter() - .map(|passkey| passkey["id"].clone()) - .collect(); - assert_eq!(undo_with, [json!(scenario.keys.key_id)]); - - let (status, body, signed_in) = scenario.undo(recovery.id).await; - assert_eq!( - (status, body), - (StatusCode::OK, json!({ "signed_in": true })) - ); - assert_eq!( - scenario.passkeys().await, - HashSet::from([scenario.keys.key_id]) - ); - assert!(scenario.consents().await.is_empty(), "every consent"); - assert!(scenario.session(&cookie).await.is_none(), "signed out"); - let mut tokens = scenario.database().tokens(); - let grants = tokens.revoke_for_user(scenario.user(), None).await; - assert_eq!(grants.expect("grants"), 0, "already revoked"); - let events = scenario.events().await; - assert!(events.contains(&DomainEvent::PasskeyRemoved { - passkey_id: recovered - })); - assert!(events.contains(&DomainEvent::RecoveryUndone { - recovery_id: recovery.id - })); - let signed_in = signed_in.expect("signed in"); - assert_eq!( - scenario.status(&signed_in).await, - Value::Null, - "nothing left" - ); -} - -/// An undo and a client's deletion lock the account's refresh families before -/// its consents, so they never deadlock. Here a transaction locks the client's -/// families, as a deletion does first, while the undo waits for them, then -/// deletes the client and its consents: the undo must not be holding them yet. -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "requires TEST_DATABASE_URL"] -async fn an_undo_and_a_client_deletion_never_deadlock() { - let mut scenario = Scenario::new().await; - let token = scenario.recover().await; - let cookie = scenario.enroll(&token).await; - let session = scenario.session(&cookie).await.expect("session").id; - let client = scenario.consent("https://photos.example").await; - let (database, user) = (scenario.database(), scenario.user()); - refresh_grant(database, user, session, &client, TokenId::new()).await; - - let mut holder = database.begin().await.expect("transaction"); - holder - .tokens() - .lock_client_families(std::slice::from_ref(&client)) - .await - .expect("hold the client's families"); - let undo = tokio::spawn({ - let admin = scenario.admin(); - async move { admin.undo_recovery(&cli(), user, recovery_reason()).await } - }); - until_blocked(&mut holder, 1).await; - holder - .oidc() - .delete_client(&client) - .await - .expect("the undo holds no consent yet"); - holder.commit().await.expect("commit"); - undo.await - .expect("task") - .expect("the undo follows the deletion"); - assert!(scenario.consents().await.is_empty(), "every consent"); -} - -/// The pages read the account's recovery that can still be undone by its owner's -/// session, or by its ID alone, a disabled account's too: its stage, the passkey -/// its link enrolled, by ID and enrollment time only, and whether a passkey from -/// before it can undo it. Neither finds one that settled, nor an unknown one. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn pages_read_an_undoable_recovery_by_session_or_id() { - let mut scenario = Scenario::new().await; - let service = AccountService::new(scenario.database().clone()); - let token = scenario.recover().await; - let owner = Browser::sign_in(scenario.database(), scenario.user()) - .await - .owner(scenario.database()) - .await; - let read = async |id: RecoveryId| { - let by_session = service - .recovery_notice(&(&owner).into()) - .await - .expect("by session"); - let by_id = service.undoable_recovery(id).await.expect("by ID"); - assert_eq!(by_session, by_id, "the same either way"); - by_id - }; - let recovery = scenario.latest().await; - let open = RecoveryNotice { - id: recovery.id, - started_at: recovery.started_at, - stage: RecoveryStage::Open { - expires_at: recovery.expires_at, - }, - undoable: true, - }; - assert_eq!(read(recovery.id).await, Some(open)); - - scenario.enroll(&token).await; - let recovery = scenario.latest().await; - let passkey = recovery.passkey_id.expect("its passkey"); - let passkeys = scenario - .database() - .passkeys() - .list_active(scenario.user()) - .await; - let created_at = passkeys - .expect("passkeys") - .into_iter() - .find(|stored| stored.id == passkey) - .expect("active") - .created_at; - let probation = RecoveryNotice { - stage: RecoveryStage::Probation { - completed_at: recovery.completed_at.expect("completed"), - settles_at: recovery.settles_at.expect("in probation"), - passkey: Some(EnrolledPasskey { - id: passkey, - created_at, - }), - }, - ..open - }; - assert_eq!(read(recovery.id).await, Some(probation)); - let disabled = scenario - .database() - .users() - .set_status(scenario.user(), AccountStatus::Disabled) - .await; - assert!(disabled.expect("disable")); - assert_eq!( - service.undoable_recovery(recovery.id).await.expect("by ID"), - Some(probation), - "disabled" - ); - - let unknown = service.undoable_recovery(RecoveryId::new()).await; - assert_eq!(unknown.expect("by ID"), None, "unknown"); - let mut recoveries = scenario.database().recoveries(); - recoveries - .backdate_completion(recovery.id, PROBATION) - .await - .expect("settle"); - assert_eq!(read(recovery.id).await, None, "settled"); -} - -/// Only a passkey other than the recovery's own undoes it: the undo challenges -/// every other active one, a passkey enrolled during the probation by a session -/// an older passkey confirmed included, never the recovery's own, which the undo -/// refuses again under the lock. It finds nothing to undo once the recovery -/// settled, or for an unknown recovery. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn only_another_passkey_undoes_a_recovery() { - let mut scenario = Scenario::new().await; - let token = scenario.recover().await; - scenario.enroll(&token).await; - let recovery = scenario.latest().await; - let recovered = recovery.passkey_id.expect("its passkey"); - - let mut tx = scenario.database().begin().await.expect("transaction"); - let undo = VerifiedRecoveryUndo::unverified(scenario.user(), recovery.id, recovered); - let refused = AccountService::undo_recovery(&mut tx, RequestContext::TEST, &undo).await; - assert!( - matches!( - refused, - Err(AccountError::Recovery(RecoveryError::OlderPasskeyRequired)) - ), - "the recovery's own passkey" - ); - drop(tx); - - let confirmed = scenario.signed_in_with(scenario.keys.key_id).await; - let (started, browser) = scenario - .keys - .start("/account/passkeys/enroll/start", &confirmed, json!({})) - .await; - let body = json!({ - "ceremony_id": started["ceremony_id"], - "credential": scenario.keys.credential(&started), - "friendly_name": "Added during probation", - }); - let cookies = format!("{confirmed}; {browser}"); - let response = scenario - .keys - .request( - "/account/passkeys/enroll/finish", - Method::POST, - &cookies, - body, - ) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - let (started, _) = scenario.undo_start(recovery.id).await.expect("undo"); - let allowed = started["public_key"]["publicKey"]["allowCredentials"] - .as_array() - .map(Vec::len); - assert_eq!(allowed, Some(2), "every passkey but the recovery's"); - assert_eq!(scenario.passkeys().await.len(), 3); - - let (status, ..) = scenario.undo(RecoveryId::new()).await; - assert_eq!(status, StatusCode::NOT_FOUND, "unknown"); - let mut recoveries = scenario.database().recoveries(); - recoveries - .backdate_completion(recovery.id, PROBATION) - .await - .expect("settle"); - let (status, ..) = scenario.undo(recovery.id).await; - assert_eq!(status, StatusCode::NOT_FOUND, "settled"); -} - -/// Undoing a recovery whose link was not used only cancels the link: nobody got -/// in with it, so sessions and consents stay. An undo applies only to the -/// recovery its ceremony named. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn undoing_an_unused_link_only_cancels_it() { - let mut scenario = Scenario::new().await; - let token = scenario.recover().await; - let elsewhere = scenario.signed_in_with(scenario.keys.key_id).await; - scenario.consent("https://notes.example").await; - - let recovery = scenario.latest().await; - let (status, body, _) = scenario.undo(recovery.id).await; - assert_eq!( - (status, body), - (StatusCode::OK, json!({ "signed_in": true })) - ); - assert!(!scenario.works(&token).await, "cancelled"); - assert!( - scenario.session(&elsewhere).await.is_some(), - "still signed in" - ); - assert_eq!(scenario.consents().await.len(), 1, "consent kept"); - - // An undo started for a recovery that a newer one replaced before it - // finished undoes nothing: the proof names the recovery it was started for. - scenario.recover().await; - let replaced = scenario.latest().await.id; - let (started, browser) = scenario.undo_start(replaced).await.expect("undo"); - let token = scenario.recover().await; - let body = json!({ - "ceremony_id": started["ceremony_id"], - "credential": scenario.keys.assertion(&started), - }); - let response = scenario - .keys - .request(routes::recovery::UNDO_FINISH, Method::POST, &browser, body) - .await; - assert_eq!( - response.status(), - StatusCode::NOT_FOUND, - "replaced meanwhile" - ); - assert!(scenario.works(&token).await, "the newer one stands"); -} - -/// The owner undoes a recovery of a disabled account, so asking support to -/// disable it cannot outlast the undo: it signs nobody in, and the account stays -/// disabled, refusing a sign-in started before it was disabled. Once enabled, the -/// older passkey signs in. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn the_owner_undoes_a_disabled_accounts_recovery() { - let mut scenario = Scenario::new().await; - let token = scenario.recover().await; - scenario.enroll(&token).await; - let recovery = scenario.latest().await.id; - // A sign-in started before the account is disabled. - let body = json!({ "handle": scenario.keys.username }); - let login = scenario - .keys - .start("/webauthn/authenticate/start", "", body) - .await; - // Written as a release older than this one would, which knows nothing of - // recoveries. - let disabled = scenario - .database() - .users() - .set_status(scenario.user(), AccountStatus::Disabled) - .await; - assert!(disabled.expect("disable")); - - let (status, body, cookie) = scenario.undo(recovery).await; - assert_eq!( - (status, body), - (StatusCode::OK, json!({ "signed_in": false })) - ); - assert!(cookie.is_none(), "nobody signed in"); - assert_eq!( - scenario.passkeys().await, - HashSet::from([scenario.keys.key_id]) - ); - let user = scenario - .database() - .users() - .find_by_id(scenario.user()) - .await; - let status = user.expect("lookup").expect("user").status; - assert_eq!(status, AccountStatus::Disabled, "still disabled"); - let (started, browser) = login; - let body = json!({ - "ceremony_id": started["ceremony_id"], - "credential": scenario.keys.assertion(&started), - }); - let response = scenario - .keys - .request( - "/webauthn/authenticate/finish", - Method::POST, - &browser, - body, - ) - .await; - assert!(response.status().is_client_error(), "sign-in refused"); - let cookie = response.headers().get(axum::http::header::SET_COOKIE); - assert!(cookie.is_none(), "no session"); - let refused = DomainEvent::SignInFailed { - method: AuthenticationMethod::Passkey, - reason: SignInFailure::AccountUnavailable, - }; - assert!(scenario.events().await.contains(&refused), "recorded"); - - scenario - .admin() - .enable_user(&cli(), scenario.user()) - .await - .expect("enable"); - let response = scenario.login("").await; - assert_eq!(response.status(), StatusCode::NO_CONTENT, "once enabled"); -} - -/// Support undoes a recovery for an owner with no passkey left from before it, -/// and takes back its passkey even when it is the account's last; support then -/// starts another recovery. The listing shows the undone one. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn support_undoes_and_takes_the_last_passkey() { - let mut scenario = Scenario::new().await; - let address = scenario.address("address", true).await; - let link = scenario - .start(Some(Revoke::default())) - .await - .expect("recovery"); - let notice = ("recovery_revoked".to_owned(), Some(false)); - assert_eq!(scenario.messages(address).await, [notice], "nothing kept"); - scenario.enroll(&recovery_token(&link)).await; - assert_eq!(scenario.passkeys().await.len(), 1, "only the recovery's"); - let recovery = scenario.latest().await.id; - - scenario - .admin() - .undo_recovery(&cli(), scenario.user(), recovery_reason()) - .await - .expect("support undoes"); - assert!(scenario.passkeys().await.is_empty(), "the last one too"); - let recent = scenario - .admin() - .recent_recoveries(&cli(), scenario.user()) - .await; - let recent = recent.expect("recent"); - assert_eq!(recent[0].id, recovery); - assert_eq!(recent[0].state, RecoveryState::Ended); - assert!(recent[0].undone_at.is_some(), "listed as undone"); - scenario.recover().await; -} - -/// A recovery started with `--revoke` takes back every way in but the kept -/// passkeys, in its own transaction: every other passkey, every identity and -/// every consent. Its link is only printed, and every verified address hears of -/// it at once. A kept passkey can still cancel it. A kept passkey the account -/// does not have fails the whole start. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn revoke_takes_back_every_way_in_but_the_kept_passkeys() { - let mut scenario = Scenario::new().await; - let stolen = scenario.keys.key_id; - let primary = scenario.address("primary", true).await; - let other = scenario.address("other", false).await; - // The owner's other passkey, which signs from now on. - let kept = scenario.keys.switch_passkey("Kept").await; - scenario.link(Provider::GitHub).await; - scenario.consent("https://notes.example").await; - // A link already sent does not stand in the way. - scenario.recover().await; - - let unknown = Revoke { - keep: vec![PasskeyId::new()], - }; - let refused = scenario.start(Some(unknown)).await; - assert!(matches!(refused, Err(AdminError::UnknownPasskey(_)))); - assert_eq!(scenario.passkeys().await, HashSet::from([kept, stolen])); - - let (primary_before, other_before) = (scenario.sent(primary).await, scenario.sent(other).await); - scenario - .start(Some(Revoke { keep: vec![kept] })) - .await - .expect("recovery"); - assert_eq!(scenario.passkeys().await, HashSet::from([kept])); - assert!( - scenario.identities().await.is_empty(), - "identities unlinked" - ); - assert!(scenario.consents().await.is_empty(), "consents withdrawn"); - let recovery = scenario.latest().await.id; - let started = scenario - .events() - .await - .into_iter() - .find_map(|event| match event { - DomainEvent::RecoveryStarted { - recovery_id, - revoke, - .. - } if recovery_id == recovery => Some(revoke), - _ => None, - }); - let revocation = RecoveryRevocation { - revoked: vec![stolen], - kept: vec![kept], - }; - assert_eq!(started, Some(Some(revocation)), "recorded on the start"); - assert_eq!( - ( - scenario.sent(primary).await - primary_before, - scenario.sent(other).await - other_before, - ), - (1, 1), - "a notice to every verified address, and no link" - ); - let notice = ("recovery_revoked".to_owned(), Some(true)); - assert_eq!(scenario.messages(other).await.last(), Some(¬ice), "kept"); - - let (status, body, _) = scenario.undo(recovery).await; - assert_eq!( - (status, body), - (StatusCode::OK, json!({ "signed_in": true })) - ); - let cancelled = scenario.database().recoveries().find(recovery).await; - let cancelled = cancelled.expect("lookup").expect("recovery").cancelled_at; - assert!(cancelled.is_some(), "the kept passkey cancelled it"); -} - -/// While a recovery can be undone, nobody removes a passkey but the recovery's -/// own: not the owner from a session an older passkey confirmed, not support. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn nothing_removes_an_older_passkey_mid_recovery() { - let mut scenario = Scenario::new().await; - let older = scenario.keys.key_id; - let other = scenario.keys.switch_passkey("Other key").await; - let token = scenario.recover().await; - let confirmed = scenario.signed_in_with(older).await; - - let response = scenario.remove(&confirmed, other).await; - assert_eq!( - response.status(), - StatusCode::CONFLICT, - "while the link works" - ); - assert_eq!(code(response).await, "recovery_in_progress"); - let harness = Harness::new().await; - let admin = harness.admin().await; - let subject = Subject::operator( - scenario.user(), - operator(admin, Utc::now()), - recovery_reason(), - ); - let service = AccountService::new(scenario.database().clone()); - let refused = service.revoke_passkey(&subject, other).await; - assert!( - matches!( - refused, - Err(AccountError::Recovery(RecoveryError::InProgress)) - ), - "support either" - ); - - scenario.enroll(&token).await; - let recovered = scenario.latest().await.passkey_id.expect("its passkey"); - let response = scenario.remove(&confirmed, older).await; - assert_eq!( - response.status(), - StatusCode::CONFLICT, - "during the probation" - ); - let response = scenario.remove(&confirmed, recovered).await; - assert_eq!(response.status(), StatusCode::NO_CONTENT, "its own may go"); -} - -/// A start is refused while a recovery is in probation, for a disabled account, -/// and for an administrator; it replaces an unused link, expired or not. Only an -/// operator at the terminal starts one that would not be mailed. Disabling an -/// account cancels its unused link. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn what_a_start_replaces_and_refuses() { - let mut scenario = Scenario::new().await; - let first = scenario.recover().await; - let second = scenario.recover().await; - assert!(!scenario.works(&first).await, "replaced"); - assert!(scenario.works(&second).await); - let expired = scenario.latest().await.id; - let mut recoveries = scenario.database().recoveries(); - recoveries.expire(expired).await.expect("expire"); - let third = scenario.recover().await; - scenario.enroll(&third).await; - let refused = scenario.start(None).await; - assert!(matches!(refused, Err(AdminError::RecoveryInProbation))); - - let harness = Harness::new().await; - let admin = harness.admin().await; - let admin_id = admin.user_id; - let administrator = operator(admin, Utc::now()); - let account = harness.account().await.user_id; - let service = AdminService::new(harness.database.clone(), true); - let links = recovery_links(); - let unmailed = service - .recover_account(&administrator, account, recovery_reason(), &links, None) - .await; - assert!( - matches!(unmailed, Err(AdminError::RecoveryNeedsEmail)), - "no address" - ); - let address = format!("{account}@example.com"); - verified_address(&harness.database, account, &address, true).await; - let revoked = service - .recover_account( - &administrator, - account, - recovery_reason(), - &links, - Some(Revoke::default()), - ) - .await; - assert!( - matches!(revoked, Err(AdminError::RecoveryNeedsEmail)), - "printed only" - ); - let mailed = service - .recover_account(&administrator, account, recovery_reason(), &links, None) - .await; - assert_eq!( - mailed.expect("mailed"), - None, - "an administrator never sees it" - ); - let to_admin = service - .recover_account(&cli(), admin_id, recovery_reason(), &links, None) - .await; - assert!(matches!(to_admin, Err(AdminError::RecoveryOfAdministrator))); - - let link = service - .recover_account(&cli(), account, recovery_reason(), &links, None) - .await - .expect("recovery") - .expect("link"); - service - .disable_user(&cli(), account, recovery_reason()) - .await - .expect("disable"); - let disabled = service - .recover_account(&cli(), account, recovery_reason(), &links, None) - .await; - assert!(matches!( - disabled, - Err(AdminError::RecoveryOfDisabledAccount) - )); - service.enable_user(&cli(), account).await.expect("enable"); - let accounts = AccountService::new(harness.database.clone()); - let opened = accounts.open_recovery(&recovery_token(&link)).await; - assert!( - opened.is_err(), - "disabling cancelled it, so enabling does not revive it" - ); -} - -/// While email is disabled, a recovery whose link would only be mailed is -/// refused before anything changes: the account keeps its session, and nothing -/// starts. The terminal, which prints its link, still recovers it. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn no_recovery_starts_while_email_is_disabled() { - let harness = Harness::new().await; - let administrator = operator(harness.admin().await, Utc::now()); - let owner = harness.account().await; - let account = owner.user_id; - let address = format!("{account}@example.com"); - verified_address(&harness.database, account, &address, true).await; - let service = AdminService::new(harness.database.clone(), false); - let links = recovery_links(); - let refused = service - .recover_account(&administrator, account, recovery_reason(), &links, None) - .await; - assert!(matches!(refused, Err(AdminError::RecoveryNeedsEmail))); - let session = harness - .database - .sessions() - .find_by_id(owner.session_id) - .await - .expect("lookup") - .expect("session"); - assert!(session.revoked_at.is_none(), "still signed in"); - let recent = service - .recent_recoveries(&cli(), account) - .await - .expect("recoveries"); - assert!(recent.is_empty(), "nothing started"); - let printed = service - .recover_account(&cli(), account, recovery_reason(), &links, None) - .await - .expect("recovery"); - assert!(printed.is_some(), "the terminal prints its link"); -} - -/// A probation passkey's session never confirms, so it can neither download the -/// account's data nor delete the account: both require a recent passkey -/// confirmation, checked under the account lock. An account support scheduled -/// for deletion meanwhile is restored by its probation passkey into a session that -/// still confirms nothing. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn a_probation_passkey_neither_exports_nor_deletes_the_account() { - let mut scenario = Scenario::new().await; - let token = scenario.recover().await; - let cookie = scenario.enroll(&token).await; - let owner = Browser { - cookie, - ..Browser::signed_out() - } - .owner(scenario.database()) - .await; - let service = AccountService::new(scenario.database().clone()); - let refused = |result: Result<(), AccountError>| { - matches!( - result, - Err(AccountError::Owner(SessionError::StepUpRequired { .. })) - ) - }; - assert!(refused(service.export(&owner).await.map(drop))); - let handle = scenario.keys.username.clone(); - assert!(refused( - service.delete_account(&owner, &handle).await.map(drop) - )); - let account = scenario - .database() - .users() - .find_by_id(scenario.user()) - .await; - assert_eq!( - account.expect("lookup").expect("account").status, - AccountStatus::Active - ); - - scenario - .admin() - .schedule_deletion(&cli(), scenario.user(), recovery_reason()) - .await - .expect("support schedules the deletion"); - scenario.swap(); - let offered = scenario.login("").await; - assert_eq!(offered.status(), StatusCode::NO_CONTENT); - let offer = Fixture::cookie(&offered); - assert!( - offer.starts_with(BrowserCookie::Restore.as_str()), - "{offer}" - ); - let holder = Browser { - cookie: offer, - ..Browser::signed_out() - }; - let mut restored = axum::http::Response::new(()); - service - .restore(RequestContext::TEST, &holder.headers()) - .await - .expect("restore") - .set_on(&mut restored) - .expect("cookies"); - let session = restored - .headers() - .get_all(axum::http::header::SET_COOKIE) - .iter() - .filter_map(|cookie| cookie.to_str().ok()) - .find(|cookie| cookie.starts_with(BrowserCookie::Session.as_str())) - .and_then(|cookie| cookie.split(';').next()) - .expect("signed in") - .to_owned(); - let session = scenario.session(&session).await.expect("session"); - assert_eq!(session.passkey_confirmed_at, None, "still not confirmed"); -} - -/// An offer to restore an account scheduled for deletion restores nothing once -/// its passkey is revoked, as support undoing the recovery of a probation passkey -/// revokes it: otherwise restoring would sign in with it, confirmed. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn an_undone_recoverys_passkey_restores_nothing() { - let mut scenario = Scenario::new().await; - let token = scenario.recover().await; - scenario.enroll(&token).await; - scenario - .admin() - .schedule_deletion(&cli(), scenario.user(), recovery_reason()) - .await - .expect("support schedules the deletion"); - scenario.swap(); - let offered = scenario.login("").await; - assert_eq!(offered.status(), StatusCode::NO_CONTENT); - let holder = Browser { - cookie: Fixture::cookie(&offered), - ..Browser::signed_out() - }; - let service = AccountService::new(scenario.database().clone()); - let offer = service.restore_offer(&holder.headers()).await; - assert!(offer.expect("offer").is_some(), "offered"); - - scenario - .admin() - .undo_recovery(&cli(), scenario.user(), recovery_reason()) - .await - .expect("support undoes the recovery"); - let offer = service.restore_offer(&holder.headers()).await; - assert!(offer.expect("offer").is_none(), "withdrawn"); - assert!(matches!( - service - .restore(RequestContext::TEST, &holder.headers()) - .await - .map(drop), - Err(AccountError::Deletion( - crate::deletion::DeletionError::RestoreExpired - )) - )); - let account = scenario - .database() - .users() - .find_by_id(scenario.user()) - .await; - assert_eq!( - account.expect("lookup").expect("account").status, - AccountStatus::Deleting - ); -} diff --git a/apps/auth-service/src/recovery/tests/enroll.rs b/apps/auth-service/src/recovery/tests/enroll.rs new file mode 100644 index 000000000..420d65ed9 --- /dev/null +++ b/apps/auth-service/src/recovery/tests/enroll.rs @@ -0,0 +1,149 @@ +//! What a recovery link enrolls: one passkey, once, signed in without confirming. + +use super::*; +use piquel_common::protocol::claims::Acr; +use piquel_repository::SessionAuthentication; + +/// Starting a recovery signs the account out everywhere, ends its refresh grants +/// and removes its unverified addresses, so an older verification link stops +/// working. Its link goes to the primary address only. The link enrolls one +/// passkey, once, and signs in with it without confirming the session: no +/// confirmed change accepts it, and confirming with it is refused until the +/// recovery settles. Every verified address hears of it. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_link_enrolls_one_passkey_that_signs_in_without_confirming() { + let mut scenario = Scenario::new().await; + let primary = scenario.address("primary", true).await; + let other = scenario.address("other", false).await; + let (pending, _) = scenario.unverified("pending").await; + let before = scenario.signed_in_with(scenario.keys.key_id).await; + let before_id = scenario.session(&before).await.expect("session").id; + let client = scenario.consent("https://notes.example").await; + let family = TokenId::new(); + refresh_grant( + scenario.database(), + scenario.user(), + before_id, + &client, + family, + ) + .await; + + let token = scenario.recover().await; + assert!(scenario.session(&before).await.is_none(), "signed out"); + let mut tokens = scenario.database().tokens(); + let grants = tokens.revoke_for_user(scenario.user(), None).await; + assert_eq!(grants.expect("grants"), 0, "already ended"); + let emails = scenario.database().emails().list(scenario.user()).await; + let emails: Vec<_> = emails + .expect("emails") + .iter() + .map(|email| email.id) + .collect(); + assert!(!emails.contains(&pending), "the unverified address is gone"); + assert_eq!( + (scenario.sent(primary).await, scenario.sent(other).await), + (1, 0), + "the link goes to the primary address only" + ); + assert!(scenario.works(&token).await); + let service = AccountService::new(scenario.database().clone()); + let opened = service.open_recovery(&token).await.expect("open"); + let account = opened.account(); + assert_eq!( + account.handle.as_str(), + scenario.keys.username, + "names the account" + ); + + let cookie = scenario.enroll(&token).await; + let session = scenario.session(&cookie).await.expect("session"); + assert_eq!(session.passkey_confirmed_at, None, "not confirmed"); + assert_eq!(SessionAuthentication::from(&session).acr, Acr::Social); + let recovered = scenario.latest().await.passkey_id.expect("its passkey"); + let signed_by = scenario.database().sessions().passkey(session.id).await; + assert_eq!(signed_by.expect("passkey"), Some(recovered)); + assert_eq!( + (scenario.sent(primary).await, scenario.sent(other).await), + (2, 1), + "every verified address hears of it" + ); + assert!(!scenario.works(&token).await, "used"); + + let response = scenario + .keys + .request( + "/account/passkeys/enroll/start", + Method::POST, + &cookie, + json!({}), + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(code(response).await, "step_up_required"); + scenario.swap(); + let response = scenario.confirm(&cookie).await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(code(response).await, "recovery_probation"); + let session = scenario.session(&cookie).await.expect("session"); + assert_eq!(session.passkey_confirmed_at, None, "still not confirmed"); + + // The probation lasts 15 days: a minute before, still refused; after, it + // settled. + let recovery = scenario.latest().await.id; + let database = scenario.database().clone(); + let almost = Duration::days(15) - Duration::minutes(1); + database + .recoveries() + .backdate_completion(recovery, almost) + .await + .expect("backdate"); + let response = scenario.confirm(&cookie).await; + assert_eq!(response.status(), StatusCode::FORBIDDEN, "a minute before"); + database + .recoveries() + .backdate_completion(recovery, Duration::minutes(2)) + .await + .expect("settle"); + let response = scenario.confirm(&cookie).await; + assert_eq!(response.status(), StatusCode::NO_CONTENT, "once settled"); +} + +/// A link enrolls one passkey even when two of its ceremonies started before +/// either finished: the second finish fails, stores no passkey, and leaves the +/// recovery bound to the first, which stays in probation. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_link_enrolls_once_however_many_ceremonies_started() { + let scenario = Scenario::new().await; + let token = scenario.recover().await; + let body = json!({ "token": token }); + let mut started = Vec::new(); + for _ in 0..2 { + let start = scenario + .keys + .start(routes::recovery::START, "", body.clone()) + .await; + started.push(start); + } + let finish = async |(started, browser): &(Value, String)| { + let body = json!({ + "ceremony_id": started["ceremony_id"], + "credential": scenario.keys.credential(started), + "friendly_name": "Recovered", + }); + scenario + .keys + .request(routes::recovery::FINISH, Method::POST, browser, body) + .await + }; + let first = finish(&started[0]).await; + assert_eq!(first.status(), StatusCode::NO_CONTENT); + let bound = scenario.latest().await.passkey_id; + let second = finish(&started[1]).await; + assert_eq!(second.status(), StatusCode::BAD_REQUEST); + assert_eq!(code(second).await, "invalid_link"); + assert_eq!(scenario.passkeys().await.len(), 2, "no second passkey"); + assert_eq!(scenario.latest().await.passkey_id, bound, "still the first"); +} diff --git a/apps/auth-service/src/recovery/tests/mod.rs b/apps/auth-service/src/recovery/tests/mod.rs new file mode 100644 index 000000000..027956cc8 --- /dev/null +++ b/apps/auth-service/src/recovery/tests/mod.rs @@ -0,0 +1,366 @@ +//! Database-backed recovery scenarios: what starting one does and refuses, what a +//! link enrolls, what a probation passkey can and cannot do, who may undo a +//! recovery and what undoing it takes back, and what nobody may remove meanwhile. + +use super::*; +use crate::{ + AdminError, AdminService, + admin::tests::{Harness, cli, operator}, + passkey::tests::Fixture, + security::{BrowserCookie, Credential, Session}, + tests::{ + Browser, recovery_links, recovery_reason, recovery_token, refresh_grant, register, + registration, verified_address, + }, +}; +use axum::{ + http::{Method, StatusCode}, + response::Response, +}; +use piquel_common::{ + AuthenticationMethod, ClientId, EmailId, Provider, TokenId, clients::ClientKind, +}; +use piquel_repository::{Database, InsertExternalIdentity, InsertUnverifiedEmail, StoredSession}; +use serde_json::{Value, json}; +use std::collections::HashSet; +use webauthn_authenticator_rs::{WebauthnAuthenticator, softpasskey::SoftPasskey}; + +mod enroll; +mod probation; +mod start; +mod undo; + +/// An error body's `code`. +async fn code(response: Response) -> Value { + Fixture::json(response).await["code"].clone() +} + +/// An account with a passkey, recovered by an operator at the terminal, and the +/// browsers that act on it. +struct Scenario { + /// The account, its original passkey and the routes. Its authenticator is the + /// one that signs. + keys: Fixture, + /// Derives the links. + links: RecoveryLinks, + /// The authenticator not signing now: the recovery's, or the original one + /// while the recovery's signs ([`Self::swap`]). + other: Option>, +} + +impl Scenario { + /// An account with one passkey, not recovered yet. + async fn new() -> Self { + Self { + keys: Fixture::new().await, + links: recovery_links(), + other: None, + } + } + + /// The scenario database. + fn database(&self) -> &Database { + self.keys.database() + } + + /// The account. + const fn user(&self) -> UserId { + self.keys.user_id + } + + /// The support operations. + fn admin(&self) -> AdminService { + AdminService::new(self.database().clone(), true) + } + + /// Starts recovering the account as an operator at the terminal, with + /// `revoke`, and returns the link it prints. + async fn start(&self, revoke: Option) -> Result { + let link = self + .admin() + .recover_account(&cli(), self.user(), recovery_reason(), &self.links, revoke) + .await?; + Ok(link.expect("the terminal sees the link")) + } + + /// Recovers the account as an operator at the terminal, and returns the + /// link's token. + async fn recover(&self) -> String { + recovery_token(&self.start(None).await.expect("recovery")) + } + + /// Whether the link holding `token` still works, as its page reads it. + async fn works(&self, token: &str) -> bool { + let service = AccountService::new(self.database().clone()); + service.open_recovery(token).await.is_ok() + } + + /// Enrolls a passkey with `token` from the browser holding `cookies`, keeping + /// its authenticator as [`Self::other`]. Returns the finish response. + async fn enroll_from(&mut self, token: &str, cookies: &str) -> Response { + let body = json!({ "token": token }); + let (started, browser) = self + .keys + .start(routes::recovery::START, cookies, body) + .await; + let (credential, authenticator) = self.keys.new_authenticator(&started); + self.other = Some(authenticator); + let body = json!({ + "ceremony_id": started["ceremony_id"], + "credential": credential, + "friendly_name": "Recovered", + }); + let cookies = format!("{cookies}; {browser}"); + self.keys + .request(routes::recovery::FINISH, Method::POST, &cookies, body) + .await + } + + /// Enrolls a passkey with `token` from a browser with no session, and returns + /// the session cookie it signs in with. + async fn enroll(&mut self, token: &str) -> String { + let response = self.enroll_from(token, "").await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + Fixture::cookie(&response) + } + + /// Signs with the other authenticator from now on: the recovery's after + /// [`Self::enroll`], then the original one again. + fn swap(&mut self) { + let other = self.other.take().expect("another authenticator"); + self.other = Some(self.keys.replace_authenticator(other)); + } + + /// Signs in with the signing authenticator from the browser holding + /// `session`. Returns the finish response. + async fn login(&mut self, session: &str) -> Response { + let body = json!({ "handle": self.keys.username }); + let (started, browser) = self + .keys + .start("/webauthn/authenticate/start", "", body) + .await; + let body = json!({ + "ceremony_id": started["ceremony_id"], + "credential": self.keys.assertion(&started), + }); + let cookies = format!("{session}; {browser}"); + self.keys + .request( + "/webauthn/authenticate/finish", + Method::POST, + &cookies, + body, + ) + .await + } + + /// Confirms the session of the browser holding `cookie` with the signing + /// authenticator. Returns the finish response. + async fn confirm(&mut self, cookie: &str) -> Response { + let (started, browser) = self + .keys + .start("/account/passkeys/confirm/start", cookie, json!({})) + .await; + let body = json!({ + "ceremony_id": started["ceremony_id"], + "credential": self.keys.assertion(&started), + }); + let cookies = format!("{cookie}; {browser}"); + self.keys + .request( + "/account/passkeys/confirm/finish", + Method::POST, + &cookies, + body, + ) + .await + } + + /// The account's recovery that can still be undone, as the browser holding + /// `cookie` sees it. + async fn status(&self, cookie: &str) -> Value { + let response = self + .keys + .request(routes::recovery::STATUS, Method::GET, cookie, Value::Null) + .await; + assert_eq!(response.status(), StatusCode::OK); + Fixture::json(response).await + } + + /// The account's latest recovery. + async fn latest(&self) -> StoredRecovery { + let latest = self.database().recoveries().latest(self.user()).await; + latest.expect("lookup").expect("a recovery") + } + + /// Starts undoing recovery `id` from a browser with no session. Returns the + /// refusal, or the challenge and the browser's ceremony cookie. + async fn undo_start(&self, id: RecoveryId) -> Result<(Value, String), StatusCode> { + let body = json!({ "recovery_id": id }); + let response = self + .keys + .request(routes::recovery::UNDO_START, Method::POST, "", body) + .await; + if response.status() != StatusCode::OK { + return Err(response.status()); + } + let browser = Fixture::cookie(&response); + Ok((Fixture::json(response).await, browser)) + } + + /// Undoes recovery `id` with the signing authenticator, from a browser with + /// no session. Returns the status, the body, and the session cookie it signs + /// in with, if any. + async fn undo(&mut self, id: RecoveryId) -> (StatusCode, Value, Option) { + let (started, browser) = match self.undo_start(id).await { + Ok(started) => started, + Err(status) => return (status, Value::Null, None), + }; + let body = json!({ + "ceremony_id": started["ceremony_id"], + "credential": self.keys.assertion(&started), + }); + let response = self + .keys + .request(routes::recovery::UNDO_FINISH, Method::POST, &browser, body) + .await; + let status = response.status(); + let cookie = response + .headers() + .contains_key(axum::http::header::SET_COOKIE) + .then(|| Fixture::cookie(&response)); + (status, Fixture::json(response).await, cookie) + } + + /// Removes `passkey` from the browser holding `cookie`. + async fn remove(&self, cookie: &str, passkey: PasskeyId) -> Response { + let path = routes::passkey::ITEM.replace("{id}", &passkey.to_string()); + self.keys + .request(&path, Method::DELETE, cookie, Value::Null) + .await + } + + /// Signs a browser in with `passkey`, which confirms its session, and returns + /// its session cookie. + async fn signed_in_with(&self, passkey: PasskeyId) -> String { + let mut tx = self.database().begin().await.expect("transaction"); + let credential = Credential::Passkey(passkey); + let secret = Session::create(&mut tx, RequestContext::TEST, self.user(), credential).await; + tx.commit().await.expect("commit"); + let secret = secret.expect("session").encoded(); + format!("{}={secret}", BrowserCookie::Session.as_str()) + } + + /// The live session of the browser holding `cookie`, if any. + async fn session(&self, cookie: &str) -> Option { + self.keys.session(cookie).await + } + + /// Registers a client at `origin` and records the account's consent to it. + async fn consent(&self, origin: &str) -> ClientId { + let client = registration(ClientKind::Public, origin); + register(self.database(), &client).await.expect("client"); + let scopes = ["openid".to_owned()]; + self.database() + .oidc() + .save_consent(self.user(), &client.id, client.id.as_str(), &scopes) + .await + .expect("consent"); + client.id + } + + /// The clients the account consented to. + async fn consents(&self) -> Vec { + let consents = self.database().oidc().list_consents(self.user()).await; + let consents = consents.expect("consents").into_iter(); + consents.map(|consent| consent.client_id).collect() + } + + /// The account's active passkeys. + async fn passkeys(&self) -> HashSet { + let passkeys = self.database().passkeys().list_active(self.user()).await; + let passkeys = passkeys.expect("passkeys").into_iter(); + passkeys.map(|passkey| passkey.id).collect() + } + + /// The providers of the account's linked identities. + async fn identities(&self) -> Vec { + let identities = self.database().federation().list_active(self.user()).await; + let identities = identities.expect("identities").into_iter(); + identities.map(|identity| identity.provider).collect() + } + + /// Links an identity of `provider` to the account. + async fn link(&self, provider: Provider) { + self.database() + .federation() + .insert_identity(&InsertExternalIdentity { + id: TokenId::new(), + user_id: self.user(), + provider, + issuer: format!("https://{provider}.example"), + subject: TokenId::new().to_string(), + linked_email: None, + }) + .await + .expect("identity"); + } + + /// Adds a verified address named `name`, primary if `is_primary`. + async fn address(&self, name: &str, is_primary: bool) -> EmailId { + let address = format!("{name}-{}@example.com", self.user()); + verified_address(self.database(), self.user(), &address, is_primary).await + } + + /// Adds an unverified address named `name`, and returns it and its + /// verification token. + async fn unverified(&self, name: &str) -> (EmailId, Secret) { + let id = EmailId::new(); + let token = Secret::generate().expect("token"); + let address = format!("{name}-{}@example.com", self.user()); + self.database() + .emails() + .insert_unverified(&InsertUnverifiedEmail { + id, + user_id: self.user(), + normalized_email: &address, + secret_digest: token.digest().as_bytes(), + expires_at: Utc::now() + Duration::hours(1), + }) + .await + .expect("unverified address"); + (id, token) + } + + /// How many messages were queued to the account's address `email`. + async fn sent(&self, email: EmailId) -> usize { + let destination = format!("account {}, address {email}", self.user()); + self.database() + .deliveries() + .list(None, Some("email"), 1000) + .await + .expect("deliveries") + .iter() + .filter(|delivery| delivery.destination == destination) + .count() + } + + /// The kinds of the messages queued to the account's address `email`, oldest + /// first, with whether a `--revoke` start's notice says a passkey was kept. + async fn messages(&self, email: EmailId) -> Vec<(String, Option)> { + let destination = format!("account {}, address {email}", self.user()); + let payloads = self.database().deliveries().payloads(&destination).await; + let payloads = payloads.expect("payloads").into_iter(); + payloads + .map(|payload| { + let kind = payload["type"].as_str().expect("type").to_owned(); + (kind, payload["kept"].as_bool()) + }) + .collect() + } + + /// The account's events, newest first. + async fn events(&self) -> Vec { + self.keys.events().await + } +} diff --git a/apps/auth-service/src/recovery/tests/probation.rs b/apps/auth-service/src/recovery/tests/probation.rs new file mode 100644 index 000000000..56c2e11f3 --- /dev/null +++ b/apps/auth-service/src/recovery/tests/probation.rs @@ -0,0 +1,258 @@ +//! What a probation passkey can and cannot do, and what nobody may remove meanwhile. + +use super::*; +use crate::{account::Subject, security::SessionError}; + +/// A link signs its browser in with a new session, whatever session the browser +/// had. A probation passkey signing in again renews an unconfirmed session, +/// recording itself and its method without confirming it, and never downgrades a +/// confirmed one. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_probation_passkey_signs_in_anew_and_never_confirms() { + let mut scenario = Scenario::new().await; + let token = scenario.recover().await; + let social = Browser::sign_in_with( + scenario.database(), + scenario.user(), + AuthenticationMethod::Federation, + ) + .await; + let response = scenario.enroll_from(&token, &social.cookie).await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + let cookie = Fixture::cookie(&response); + let session = scenario.session(&cookie).await.expect("session"); + assert_ne!(session.id, social.session_id, "a new session"); + let social_session = scenario + .database() + .sessions() + .find_by_id(social.session_id) + .await; + let revoked = social_session.expect("lookup").expect("session").revoked_at; + assert!(revoked.is_some(), "the browser's session is revoked"); + let recovered = scenario.latest().await.passkey_id.expect("its passkey"); + scenario.swap(); + + let social = Browser::sign_in_with( + scenario.database(), + scenario.user(), + AuthenticationMethod::Federation, + ) + .await; + let response = scenario.login(&social.cookie).await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + let renewed = Fixture::cookie(&response); + let session = scenario.session(&renewed).await.expect("session"); + assert_eq!(session.id, social.session_id, "renewed"); + assert_eq!(session.passkey_confirmed_at, None, "not confirmed"); + assert_eq!( + session.authentication_methods, + [ + AuthenticationMethod::Federation, + AuthenticationMethod::Passkey + ] + ); + let signed_by = scenario.database().sessions().passkey(session.id).await; + assert_eq!(signed_by.expect("passkey"), Some(recovered)); + + let confirmed = scenario.signed_in_with(scenario.keys.key_id).await; + let response = scenario.login(&confirmed).await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let body = Fixture::json(response).await; + assert_eq!(body["code"], "passkey_required"); + let says = body["error"].as_str().expect("message"); + assert!(says.ends_with("Sign out first."), "{says}"); + let session = scenario.session(&confirmed).await.expect("session"); + assert!(session.passkey_confirmed_at.is_some(), "not downgraded"); + + // A link used in a browser an older passkey confirmed still signs in anew. + let token = { + scenario.swap(); + let undoable = scenario.latest().await.id; + let (status, ..) = scenario.undo(undoable).await; + assert_eq!(status, StatusCode::OK); + scenario.recover().await + }; + let confirmed = scenario.signed_in_with(scenario.keys.key_id).await; + let response = scenario.enroll_from(&token, &confirmed).await; + assert_eq!( + response.status(), + StatusCode::NO_CONTENT, + "from a confirmed browser" + ); +} + +/// While a recovery can be undone, nobody removes a passkey but the recovery's +/// own: not the owner from a session an older passkey confirmed, not support. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn nothing_removes_an_older_passkey_mid_recovery() { + let mut scenario = Scenario::new().await; + let older = scenario.keys.key_id; + let other = scenario.keys.switch_passkey("Other key").await; + let token = scenario.recover().await; + let confirmed = scenario.signed_in_with(older).await; + + let response = scenario.remove(&confirmed, other).await; + assert_eq!( + response.status(), + StatusCode::CONFLICT, + "while the link works" + ); + assert_eq!(code(response).await, "recovery_in_progress"); + let harness = Harness::new().await; + let admin = harness.admin().await; + let subject = Subject::operator( + scenario.user(), + operator(admin, Utc::now()), + recovery_reason(), + ); + let service = AccountService::new(scenario.database().clone()); + let refused = service.revoke_passkey(&subject, other).await; + assert!( + matches!( + refused, + Err(AccountError::Recovery(RecoveryError::InProgress)) + ), + "support either" + ); + + scenario.enroll(&token).await; + let recovered = scenario.latest().await.passkey_id.expect("its passkey"); + let response = scenario.remove(&confirmed, older).await; + assert_eq!( + response.status(), + StatusCode::CONFLICT, + "during the probation" + ); + let response = scenario.remove(&confirmed, recovered).await; + assert_eq!(response.status(), StatusCode::NO_CONTENT, "its own may go"); +} + +/// A probation passkey's session never confirms, so it can neither download the +/// account's data nor delete the account: both require a recent passkey +/// confirmation, checked under the account lock. An account support scheduled +/// for deletion meanwhile is restored by its probation passkey into a session that +/// still confirms nothing. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn a_probation_passkey_neither_exports_nor_deletes_the_account() { + let mut scenario = Scenario::new().await; + let token = scenario.recover().await; + let cookie = scenario.enroll(&token).await; + let owner = Browser { + cookie, + ..Browser::signed_out() + } + .owner(scenario.database()) + .await; + let service = AccountService::new(scenario.database().clone()); + let refused = |result: Result<(), AccountError>| { + matches!( + result, + Err(AccountError::Owner(SessionError::StepUpRequired { .. })) + ) + }; + assert!(refused(service.export(&owner).await.map(drop))); + let handle = scenario.keys.username.clone(); + assert!(refused( + service.delete_account(&owner, &handle).await.map(drop) + )); + let account = scenario + .database() + .users() + .find_by_id(scenario.user()) + .await; + assert_eq!( + account.expect("lookup").expect("account").status, + AccountStatus::Active + ); + + scenario + .admin() + .schedule_deletion(&cli(), scenario.user(), recovery_reason()) + .await + .expect("support schedules the deletion"); + scenario.swap(); + let offered = scenario.login("").await; + assert_eq!(offered.status(), StatusCode::NO_CONTENT); + let offer = Fixture::cookie(&offered); + assert!( + offer.starts_with(BrowserCookie::Restore.as_str()), + "{offer}" + ); + let holder = Browser { + cookie: offer, + ..Browser::signed_out() + }; + let mut restored = axum::http::Response::new(()); + service + .restore(RequestContext::TEST, &holder.headers()) + .await + .expect("restore") + .set_on(&mut restored) + .expect("cookies"); + let session = restored + .headers() + .get_all(axum::http::header::SET_COOKIE) + .iter() + .filter_map(|cookie| cookie.to_str().ok()) + .find(|cookie| cookie.starts_with(BrowserCookie::Session.as_str())) + .and_then(|cookie| cookie.split(';').next()) + .expect("signed in") + .to_owned(); + let session = scenario.session(&session).await.expect("session"); + assert_eq!(session.passkey_confirmed_at, None, "still not confirmed"); +} + +/// An offer to restore an account scheduled for deletion restores nothing once +/// its passkey is revoked, as support undoing the recovery of a probation passkey +/// revokes it: otherwise restoring would sign in with it, confirmed. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn an_undone_recoverys_passkey_restores_nothing() { + let mut scenario = Scenario::new().await; + let token = scenario.recover().await; + scenario.enroll(&token).await; + scenario + .admin() + .schedule_deletion(&cli(), scenario.user(), recovery_reason()) + .await + .expect("support schedules the deletion"); + scenario.swap(); + let offered = scenario.login("").await; + assert_eq!(offered.status(), StatusCode::NO_CONTENT); + let holder = Browser { + cookie: Fixture::cookie(&offered), + ..Browser::signed_out() + }; + let service = AccountService::new(scenario.database().clone()); + let offer = service.restore_offer(&holder.headers()).await; + assert!(offer.expect("offer").is_some(), "offered"); + + scenario + .admin() + .undo_recovery(&cli(), scenario.user(), recovery_reason()) + .await + .expect("support undoes the recovery"); + let offer = service.restore_offer(&holder.headers()).await; + assert!(offer.expect("offer").is_none(), "withdrawn"); + assert!(matches!( + service + .restore(RequestContext::TEST, &holder.headers()) + .await + .map(drop), + Err(AccountError::Deletion( + crate::deletion::DeletionError::RestoreExpired + )) + )); + let account = scenario + .database() + .users() + .find_by_id(scenario.user()) + .await; + assert_eq!( + account.expect("lookup").expect("account").status, + AccountStatus::Deleting + ); +} diff --git a/apps/auth-service/src/recovery/tests/start.rs b/apps/auth-service/src/recovery/tests/start.rs new file mode 100644 index 000000000..aeef804a7 --- /dev/null +++ b/apps/auth-service/src/recovery/tests/start.rs @@ -0,0 +1,205 @@ +//! Starting a recovery: what a start replaces and refuses, `--revoke`, and a disabled email. + +use super::*; +use piquel_common::events::RecoveryRevocation; + +/// A start is refused while a recovery is in probation, for a disabled account, +/// and for an administrator; it replaces an unused link, expired or not. Only an +/// operator at the terminal starts one that would not be mailed. Disabling an +/// account cancels its unused link. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn what_a_start_replaces_and_refuses() { + let mut scenario = Scenario::new().await; + let first = scenario.recover().await; + let second = scenario.recover().await; + assert!(!scenario.works(&first).await, "replaced"); + assert!(scenario.works(&second).await); + let expired = scenario.latest().await.id; + let mut recoveries = scenario.database().recoveries(); + recoveries.expire(expired).await.expect("expire"); + let third = scenario.recover().await; + scenario.enroll(&third).await; + let refused = scenario.start(None).await; + assert!(matches!(refused, Err(AdminError::RecoveryInProbation))); + + let harness = Harness::new().await; + let admin = harness.admin().await; + let admin_id = admin.user_id; + let administrator = operator(admin, Utc::now()); + let account = harness.account().await.user_id; + let service = AdminService::new(harness.database.clone(), true); + let links = recovery_links(); + let unmailed = service + .recover_account(&administrator, account, recovery_reason(), &links, None) + .await; + assert!( + matches!(unmailed, Err(AdminError::RecoveryNeedsEmail)), + "no address" + ); + let address = format!("{account}@example.com"); + verified_address(&harness.database, account, &address, true).await; + let revoked = service + .recover_account( + &administrator, + account, + recovery_reason(), + &links, + Some(Revoke::default()), + ) + .await; + assert!( + matches!(revoked, Err(AdminError::RecoveryNeedsEmail)), + "printed only" + ); + let mailed = service + .recover_account(&administrator, account, recovery_reason(), &links, None) + .await; + assert_eq!( + mailed.expect("mailed"), + None, + "an administrator never sees it" + ); + let to_admin = service + .recover_account(&cli(), admin_id, recovery_reason(), &links, None) + .await; + assert!(matches!(to_admin, Err(AdminError::RecoveryOfAdministrator))); + + let link = service + .recover_account(&cli(), account, recovery_reason(), &links, None) + .await + .expect("recovery") + .expect("link"); + service + .disable_user(&cli(), account, recovery_reason()) + .await + .expect("disable"); + let disabled = service + .recover_account(&cli(), account, recovery_reason(), &links, None) + .await; + assert!(matches!( + disabled, + Err(AdminError::RecoveryOfDisabledAccount) + )); + service.enable_user(&cli(), account).await.expect("enable"); + let accounts = AccountService::new(harness.database.clone()); + let opened = accounts.open_recovery(&recovery_token(&link)).await; + assert!( + opened.is_err(), + "disabling cancelled it, so enabling does not revive it" + ); +} + +/// While email is disabled, a recovery whose link would only be mailed is +/// refused before anything changes: the account keeps its session, and nothing +/// starts. The terminal, which prints its link, still recovers it. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn no_recovery_starts_while_email_is_disabled() { + let harness = Harness::new().await; + let administrator = operator(harness.admin().await, Utc::now()); + let owner = harness.account().await; + let account = owner.user_id; + let address = format!("{account}@example.com"); + verified_address(&harness.database, account, &address, true).await; + let service = AdminService::new(harness.database.clone(), false); + let links = recovery_links(); + let refused = service + .recover_account(&administrator, account, recovery_reason(), &links, None) + .await; + assert!(matches!(refused, Err(AdminError::RecoveryNeedsEmail))); + let session = harness + .database + .sessions() + .find_by_id(owner.session_id) + .await + .expect("lookup") + .expect("session"); + assert!(session.revoked_at.is_none(), "still signed in"); + let recent = service + .recent_recoveries(&cli(), account) + .await + .expect("recoveries"); + assert!(recent.is_empty(), "nothing started"); + let printed = service + .recover_account(&cli(), account, recovery_reason(), &links, None) + .await + .expect("recovery"); + assert!(printed.is_some(), "the terminal prints its link"); +} + +/// A recovery started with `--revoke` takes back every way in but the kept +/// passkeys, in its own transaction: every other passkey, every identity and +/// every consent. Its link is only printed, and every verified address hears of +/// it at once. A kept passkey can still cancel it. A kept passkey the account +/// does not have fails the whole start. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn revoke_takes_back_every_way_in_but_the_kept_passkeys() { + let mut scenario = Scenario::new().await; + let stolen = scenario.keys.key_id; + let primary = scenario.address("primary", true).await; + let other = scenario.address("other", false).await; + // The owner's other passkey, which signs from now on. + let kept = scenario.keys.switch_passkey("Kept").await; + scenario.link(Provider::GitHub).await; + scenario.consent("https://notes.example").await; + // A link already sent does not stand in the way. + scenario.recover().await; + + let unknown = Revoke { + keep: vec![PasskeyId::new()], + }; + let refused = scenario.start(Some(unknown)).await; + assert!(matches!(refused, Err(AdminError::UnknownPasskey(_)))); + assert_eq!(scenario.passkeys().await, HashSet::from([kept, stolen])); + + let (primary_before, other_before) = (scenario.sent(primary).await, scenario.sent(other).await); + scenario + .start(Some(Revoke { keep: vec![kept] })) + .await + .expect("recovery"); + assert_eq!(scenario.passkeys().await, HashSet::from([kept])); + assert!( + scenario.identities().await.is_empty(), + "identities unlinked" + ); + assert!(scenario.consents().await.is_empty(), "consents withdrawn"); + let recovery = scenario.latest().await.id; + let started = scenario + .events() + .await + .into_iter() + .find_map(|event| match event { + DomainEvent::RecoveryStarted { + recovery_id, + revoke, + .. + } if recovery_id == recovery => Some(revoke), + _ => None, + }); + let revocation = RecoveryRevocation { + revoked: vec![stolen], + kept: vec![kept], + }; + assert_eq!(started, Some(Some(revocation)), "recorded on the start"); + assert_eq!( + ( + scenario.sent(primary).await - primary_before, + scenario.sent(other).await - other_before, + ), + (1, 1), + "a notice to every verified address, and no link" + ); + let notice = ("recovery_revoked".to_owned(), Some(true)); + assert_eq!(scenario.messages(other).await.last(), Some(¬ice), "kept"); + + let (status, body, _) = scenario.undo(recovery).await; + assert_eq!( + (status, body), + (StatusCode::OK, json!({ "signed_in": true })) + ); + let cancelled = scenario.database().recoveries().find(recovery).await; + let cancelled = cancelled.expect("lookup").expect("recovery").cancelled_at; + assert!(cancelled.is_some(), "the kept passkey cancelled it"); +} diff --git a/apps/auth-service/src/recovery/tests/undo.rs b/apps/auth-service/src/recovery/tests/undo.rs new file mode 100644 index 000000000..450e67db3 --- /dev/null +++ b/apps/auth-service/src/recovery/tests/undo.rs @@ -0,0 +1,411 @@ +//! Undoing a recovery: who may, what it takes back, and what the pages read of it. + +use super::*; +use crate::{passkey::VerifiedRecoveryUndo, tests::until_blocked}; +use piquel_common::events::SignInFailure; + +/// Undoing a recovery in probation, with a passkey from before it and no +/// session, takes back what whoever used its link could keep: its passkey, every +/// session and refresh grant, and every consent, old and new. It signs the +/// undoing browser in, and leaves nothing to undo. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn undo_takes_back_the_passkey_sessions_grants_and_consents() { + let mut scenario = Scenario::new().await; + scenario.consent("https://notes.example").await; + let token = scenario.recover().await; + let cookie = scenario.enroll(&token).await; + let recovery = scenario.latest().await; + let recovered = recovery.passkey_id.expect("its passkey"); + let probation_session = scenario.session(&cookie).await.expect("session").id; + let client = scenario.consent("https://photos.example").await; + let family = TokenId::new(); + refresh_grant( + scenario.database(), + scenario.user(), + probation_session, + &client, + family, + ) + .await; + + let status = scenario.status(&cookie).await; + assert_eq!(status["state"], "probation"); + assert_eq!(status["passkey"]["id"], json!(recovered)); + let undo_with: Vec<_> = status["undo_with"] + .as_array() + .expect("undo_with") + .iter() + .map(|passkey| passkey["id"].clone()) + .collect(); + assert_eq!(undo_with, [json!(scenario.keys.key_id)]); + + let (status, body, signed_in) = scenario.undo(recovery.id).await; + assert_eq!( + (status, body), + (StatusCode::OK, json!({ "signed_in": true })) + ); + assert_eq!( + scenario.passkeys().await, + HashSet::from([scenario.keys.key_id]) + ); + assert!(scenario.consents().await.is_empty(), "every consent"); + assert!(scenario.session(&cookie).await.is_none(), "signed out"); + let mut tokens = scenario.database().tokens(); + let grants = tokens.revoke_for_user(scenario.user(), None).await; + assert_eq!(grants.expect("grants"), 0, "already revoked"); + let events = scenario.events().await; + assert!(events.contains(&DomainEvent::PasskeyRemoved { + passkey_id: recovered + })); + assert!(events.contains(&DomainEvent::RecoveryUndone { + recovery_id: recovery.id + })); + let signed_in = signed_in.expect("signed in"); + assert_eq!( + scenario.status(&signed_in).await, + Value::Null, + "nothing left" + ); +} + +/// An undo and a client's deletion lock the account's refresh families before +/// its consents, so they never deadlock. Here a transaction locks the client's +/// families, as a deletion does first, while the undo waits for them, then +/// deletes the client and its consents: the undo must not be holding them yet. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires TEST_DATABASE_URL"] +async fn an_undo_and_a_client_deletion_never_deadlock() { + let mut scenario = Scenario::new().await; + let token = scenario.recover().await; + let cookie = scenario.enroll(&token).await; + let session = scenario.session(&cookie).await.expect("session").id; + let client = scenario.consent("https://photos.example").await; + let (database, user) = (scenario.database(), scenario.user()); + refresh_grant(database, user, session, &client, TokenId::new()).await; + + let mut holder = database.begin().await.expect("transaction"); + holder + .tokens() + .lock_client_families(std::slice::from_ref(&client)) + .await + .expect("hold the client's families"); + let undo = tokio::spawn({ + let admin = scenario.admin(); + async move { admin.undo_recovery(&cli(), user, recovery_reason()).await } + }); + until_blocked(&mut holder, 1).await; + holder + .oidc() + .delete_client(&client) + .await + .expect("the undo holds no consent yet"); + holder.commit().await.expect("commit"); + undo.await + .expect("task") + .expect("the undo follows the deletion"); + assert!(scenario.consents().await.is_empty(), "every consent"); +} + +/// The pages read the account's recovery that can still be undone by its owner's +/// session, or by its ID alone, a disabled account's too: its stage, the passkey +/// its link enrolled, by ID and enrollment time only, and whether a passkey from +/// before it can undo it. Neither finds one that settled, nor an unknown one. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn pages_read_an_undoable_recovery_by_session_or_id() { + let mut scenario = Scenario::new().await; + let service = AccountService::new(scenario.database().clone()); + let token = scenario.recover().await; + let owner = Browser::sign_in(scenario.database(), scenario.user()) + .await + .owner(scenario.database()) + .await; + let read = async |id: RecoveryId| { + let by_session = service + .recovery_notice(&(&owner).into()) + .await + .expect("by session"); + let by_id = service.undoable_recovery(id).await.expect("by ID"); + assert_eq!(by_session, by_id, "the same either way"); + by_id + }; + let recovery = scenario.latest().await; + let open = RecoveryNotice { + id: recovery.id, + started_at: recovery.started_at, + stage: RecoveryStage::Open { + expires_at: recovery.expires_at, + }, + undoable: true, + }; + assert_eq!(read(recovery.id).await, Some(open)); + + scenario.enroll(&token).await; + let recovery = scenario.latest().await; + let passkey = recovery.passkey_id.expect("its passkey"); + let passkeys = scenario + .database() + .passkeys() + .list_active(scenario.user()) + .await; + let created_at = passkeys + .expect("passkeys") + .into_iter() + .find(|stored| stored.id == passkey) + .expect("active") + .created_at; + let probation = RecoveryNotice { + stage: RecoveryStage::Probation { + completed_at: recovery.completed_at.expect("completed"), + settles_at: recovery.settles_at.expect("in probation"), + passkey: Some(EnrolledPasskey { + id: passkey, + created_at, + }), + }, + ..open + }; + assert_eq!(read(recovery.id).await, Some(probation)); + let disabled = scenario + .database() + .users() + .set_status(scenario.user(), AccountStatus::Disabled) + .await; + assert!(disabled.expect("disable")); + assert_eq!( + service.undoable_recovery(recovery.id).await.expect("by ID"), + Some(probation), + "disabled" + ); + + let unknown = service.undoable_recovery(RecoveryId::new()).await; + assert_eq!(unknown.expect("by ID"), None, "unknown"); + let mut recoveries = scenario.database().recoveries(); + recoveries + .backdate_completion(recovery.id, PROBATION) + .await + .expect("settle"); + assert_eq!(read(recovery.id).await, None, "settled"); +} + +/// Only a passkey other than the recovery's own undoes it: the undo challenges +/// every other active one, a passkey enrolled during the probation by a session +/// an older passkey confirmed included, never the recovery's own, which the undo +/// refuses again under the lock. It finds nothing to undo once the recovery +/// settled, or for an unknown recovery. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn only_another_passkey_undoes_a_recovery() { + let mut scenario = Scenario::new().await; + let token = scenario.recover().await; + scenario.enroll(&token).await; + let recovery = scenario.latest().await; + let recovered = recovery.passkey_id.expect("its passkey"); + + let mut tx = scenario.database().begin().await.expect("transaction"); + let undo = VerifiedRecoveryUndo::unverified(scenario.user(), recovery.id, recovered); + let refused = AccountService::undo_recovery(&mut tx, RequestContext::TEST, &undo).await; + assert!( + matches!( + refused, + Err(AccountError::Recovery(RecoveryError::OlderPasskeyRequired)) + ), + "the recovery's own passkey" + ); + drop(tx); + + let confirmed = scenario.signed_in_with(scenario.keys.key_id).await; + let (started, browser) = scenario + .keys + .start("/account/passkeys/enroll/start", &confirmed, json!({})) + .await; + let body = json!({ + "ceremony_id": started["ceremony_id"], + "credential": scenario.keys.credential(&started), + "friendly_name": "Added during probation", + }); + let cookies = format!("{confirmed}; {browser}"); + let response = scenario + .keys + .request( + "/account/passkeys/enroll/finish", + Method::POST, + &cookies, + body, + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + let (started, _) = scenario.undo_start(recovery.id).await.expect("undo"); + let allowed = started["public_key"]["publicKey"]["allowCredentials"] + .as_array() + .map(Vec::len); + assert_eq!(allowed, Some(2), "every passkey but the recovery's"); + assert_eq!(scenario.passkeys().await.len(), 3); + + let (status, ..) = scenario.undo(RecoveryId::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND, "unknown"); + let mut recoveries = scenario.database().recoveries(); + recoveries + .backdate_completion(recovery.id, PROBATION) + .await + .expect("settle"); + let (status, ..) = scenario.undo(recovery.id).await; + assert_eq!(status, StatusCode::NOT_FOUND, "settled"); +} + +/// Undoing a recovery whose link was not used only cancels the link: nobody got +/// in with it, so sessions and consents stay. An undo applies only to the +/// recovery its ceremony named. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn undoing_an_unused_link_only_cancels_it() { + let mut scenario = Scenario::new().await; + let token = scenario.recover().await; + let elsewhere = scenario.signed_in_with(scenario.keys.key_id).await; + scenario.consent("https://notes.example").await; + + let recovery = scenario.latest().await; + let (status, body, _) = scenario.undo(recovery.id).await; + assert_eq!( + (status, body), + (StatusCode::OK, json!({ "signed_in": true })) + ); + assert!(!scenario.works(&token).await, "cancelled"); + assert!( + scenario.session(&elsewhere).await.is_some(), + "still signed in" + ); + assert_eq!(scenario.consents().await.len(), 1, "consent kept"); + + // An undo started for a recovery that a newer one replaced before it + // finished undoes nothing: the proof names the recovery it was started for. + scenario.recover().await; + let replaced = scenario.latest().await.id; + let (started, browser) = scenario.undo_start(replaced).await.expect("undo"); + let token = scenario.recover().await; + let body = json!({ + "ceremony_id": started["ceremony_id"], + "credential": scenario.keys.assertion(&started), + }); + let response = scenario + .keys + .request(routes::recovery::UNDO_FINISH, Method::POST, &browser, body) + .await; + assert_eq!( + response.status(), + StatusCode::NOT_FOUND, + "replaced meanwhile" + ); + assert!(scenario.works(&token).await, "the newer one stands"); +} + +/// The owner undoes a recovery of a disabled account, so asking support to +/// disable it cannot outlast the undo: it signs nobody in, and the account stays +/// disabled, refusing a sign-in started before it was disabled. Once enabled, the +/// older passkey signs in. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn the_owner_undoes_a_disabled_accounts_recovery() { + let mut scenario = Scenario::new().await; + let token = scenario.recover().await; + scenario.enroll(&token).await; + let recovery = scenario.latest().await.id; + // A sign-in started before the account is disabled. + let body = json!({ "handle": scenario.keys.username }); + let login = scenario + .keys + .start("/webauthn/authenticate/start", "", body) + .await; + // Written as a release older than this one would, which knows nothing of + // recoveries. + let disabled = scenario + .database() + .users() + .set_status(scenario.user(), AccountStatus::Disabled) + .await; + assert!(disabled.expect("disable")); + + let (status, body, cookie) = scenario.undo(recovery).await; + assert_eq!( + (status, body), + (StatusCode::OK, json!({ "signed_in": false })) + ); + assert!(cookie.is_none(), "nobody signed in"); + assert_eq!( + scenario.passkeys().await, + HashSet::from([scenario.keys.key_id]) + ); + let user = scenario + .database() + .users() + .find_by_id(scenario.user()) + .await; + let status = user.expect("lookup").expect("user").status; + assert_eq!(status, AccountStatus::Disabled, "still disabled"); + let (started, browser) = login; + let body = json!({ + "ceremony_id": started["ceremony_id"], + "credential": scenario.keys.assertion(&started), + }); + let response = scenario + .keys + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + body, + ) + .await; + assert!(response.status().is_client_error(), "sign-in refused"); + let cookie = response.headers().get(axum::http::header::SET_COOKIE); + assert!(cookie.is_none(), "no session"); + let refused = DomainEvent::SignInFailed { + method: AuthenticationMethod::Passkey, + reason: SignInFailure::AccountUnavailable, + }; + assert!(scenario.events().await.contains(&refused), "recorded"); + + scenario + .admin() + .enable_user(&cli(), scenario.user()) + .await + .expect("enable"); + let response = scenario.login("").await; + assert_eq!(response.status(), StatusCode::NO_CONTENT, "once enabled"); +} + +/// Support undoes a recovery for an owner with no passkey left from before it, +/// and takes back its passkey even when it is the account's last; support then +/// starts another recovery. The listing shows the undone one. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn support_undoes_and_takes_the_last_passkey() { + let mut scenario = Scenario::new().await; + let address = scenario.address("address", true).await; + let link = scenario + .start(Some(Revoke::default())) + .await + .expect("recovery"); + let notice = ("recovery_revoked".to_owned(), Some(false)); + assert_eq!(scenario.messages(address).await, [notice], "nothing kept"); + scenario.enroll(&recovery_token(&link)).await; + assert_eq!(scenario.passkeys().await.len(), 1, "only the recovery's"); + let recovery = scenario.latest().await.id; + + scenario + .admin() + .undo_recovery(&cli(), scenario.user(), recovery_reason()) + .await + .expect("support undoes"); + assert!(scenario.passkeys().await.is_empty(), "the last one too"); + let recent = scenario + .admin() + .recent_recoveries(&cli(), scenario.user()) + .await; + let recent = recent.expect("recent"); + assert_eq!(recent[0].id, recovery); + assert_eq!(recent[0].state, RecoveryState::Ended); + assert!(recent[0].undone_at.is_some(), "listed as undone"); + scenario.recover().await; +} diff --git a/apps/auth-service/src/security/tests.rs b/apps/auth-service/src/security/tests.rs deleted file mode 100644 index 82ce7fd0d..000000000 --- a/apps/auth-service/src/security/tests.rs +++ /dev/null @@ -1,1056 +0,0 @@ -//! Focused persistence and security contract tests. - -use super::*; -use crate::routes::{audit, federation, passkey}; -use crate::tests::{REQUESTS_PER_MINUTE, Replicas}; -use axum::{Router, body::Body, http::Request as HttpRequest, middleware, routing::any}; -use piquel_common::{ - Handle, TokenId, - clients::{ClientKind, ClientOwner}, - events::{Browser, Platform}, -}; -use piquel_crypto::Secret; -use piquel_repository::{DatabaseConfig, InsertSession, InsertUser}; -use std::net::{IpAddr, Ipv6Addr}; -use tower::ServiceExt; - -impl RequestContext { - /// The context of a request from a documentation address, for handler tests - /// that bypass [`HttpSecurity::protect`]. - pub(crate) const TEST: Self = Self { - client_ip: IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 1)), - user_agent_family: UserAgentFamily { - browser: Browser::Firefox, - platform: Platform::Linux, - }, - }; - - /// The context of a request from `client_ip`, for handler tests that keep - /// their per-IP limits apart from other tests'. - pub(crate) const fn from_ip(client_ip: IpAddr) -> Self { - Self { - client_ip, - ..Self::TEST - } - } -} - -/// Asserts that `response` asks the frontend to confirm the session with a passkey -/// at most [`CONFIRMATION_MAX_AGE`] seconds old, in the stable JSON shape. -pub(crate) async fn assert_step_up_required(response: Response) { - assert_eq!(response.status(), StatusCode::FORBIDDEN); - let body: serde_json::Value = serde_json::from_slice( - &axum::body::to_bytes(response.into_body(), 4096) - .await - .expect("body"), - ) - .expect("JSON"); - assert_eq!( - body, - serde_json::json!({ - "error": "Confirm with your passkey to continue.", - "code": "step_up_required", - "max_age": CONFIRMATION_MAX_AGE, - }) - ); -} - -/// An isolated request router and database for HTTP trust-boundary scenarios. -struct SecurityFixture { - /// Dummy routes protected by the production middleware. - router: Router, - /// Unique peer address separates concurrent test budgets. - peer: SocketAddr, - /// Editable policy for proxy and deadline scenarios. - policy: HttpSecurity, -} -impl SecurityFixture { - /// Connects an isolated test pool with caller-selected acquisition bounds. - async fn database(max_connections: u32, timeout: std::time::Duration) -> Database { - let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") - .required() - .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); - Database::connect( - DatabaseConfig::new(&url, max_connections, timeout).expect("database configuration"), - ) - .await - .expect("database") - } - /// Builds a test policy with exact browser origins and unique client buckets. - /// A public client calls back to `https://external.example`. - async fn new() -> Self { - let database = Self::database(5, std::time::Duration::from_secs(5)).await; - database.run_migrations().await.expect("migrations"); - database - .oidc() - .create_client( - &crate::tests::registration(ClientKind::Public, "https://external.example"), - ClientOwner::Operator, - ) - .await - .expect("public client"); - let policy = HttpSecurity { - trusted_proxies: Arc::new(vec![]), - request_timeout: std::time::Duration::from_secs(30), - requests_per_minute: REQUESTS_PER_MINUTE, - database, - origin: site(), - listener: Listener::Public, - }; - let mut router = Router::new(); - for path in [ - "/account/passkeys", - "/webauthn/authenticate/start", - "/.well-known/openid-configuration", - "/.well-known/oauth-authorization-server", - "/.well-known/jwks.json", - "/audit/checkpoints", - "/audit/checkpoints/latest", - "/oauth/token", - "/oauth/authorize", - "/oauth/revoke", - "/oidc/userinfo", - "/oidc/logout", - ] { - router = router.route(path, any(|| async { StatusCode::ACCEPTED })); - } - let peer = SocketAddr::new( - IpAddr::V6(Ipv6Addr::from(UserId::new().as_uuid().as_u128())), - 4321, - ); - Self { - router: router.layer(middleware::from_fn_with_state( - policy.clone(), - HttpSecurity::protect, - )), - peer, - policy, - } - } - /// Sends a request with selected browser proof and explicit peer metadata. - async fn request( - &self, - method: Method, - path: &str, - origin: Option<&str>, - csrf: bool, - ) -> Response { - let mut request = HttpRequest::builder().method(method.clone()).uri(path); - if let Some(origin) = origin { - request = request.header(header::ORIGIN, origin); - } - if csrf { - request = request.header("x-piquel-csrf", "1"); - } - if method == Method::OPTIONS { - request = request - .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST") - .header( - header::ACCESS_CONTROL_REQUEST_HEADERS, - "content-type, x-piquel-csrf", - ); - } - let mut request = request.body(Body::empty()).expect("request"); - request.extensions_mut().insert(ConnectInfo(self.peer)); - self.router - .clone() - .oneshot(request) - .await - .expect("response") - } - /// Checks CORS reflects exactly the approved origin, without the browser's - /// cookies. - fn exact_cors(response: &Response, origin: &str) { - assert_eq!( - response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], - origin - ); - assert!( - !response - .headers() - .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) - ); - assert_eq!(response.headers()[header::VARY], "Origin"); - assert_ne!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); - } - /// Checks rejected origins receive browser isolation headers and no CORS grant. - fn denied(response: &Response) { - assert_eq!(response.status(), StatusCode::FORBIDDEN); - assert!( - response - .headers() - .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) - .is_none() - ); - assert_eq!( - response.headers()[header::CACHE_CONTROL], - "no-store, no-transform" - ); - assert_eq!( - response.headers()[header::X_CONTENT_TYPE_OPTIONS], - "nosniff" - ); - } -} -/// Exercises exact-origin, CSRF and public-client boundaries across endpoint families. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -#[expect( - clippy::too_many_lines, - reason = "Keep this complete browser-origin trust-boundary scenario together." -)] -async fn router_enforces_exact_browser_origins_csrf_and_public_client_cors_boundaries() { - let fixture = SecurityFixture::new().await; - let own = "https://auth.piquel.fr"; - let response = fixture - .request(Method::POST, "/account/passkeys", Some(own), true) - .await; - assert_eq!(response.status(), StatusCode::ACCEPTED); - SecurityFixture::exact_cors(&response, own); - let response = fixture - .request(Method::POST, "/account/passkeys", Some(own), false) - .await; - assert_eq!( - response.status(), - StatusCode::FORBIDDEN, - "approved origin still needs CSRF header" - ); - for origin in [ - None, - Some("null"), - Some("https://evil.example"), - Some("https://piquel.fr"), - Some("https://auth.piquel.fr.evil.example"), - Some("https://auth.piquel.fr:444"), - Some("http://auth.piquel.fr"), - ] { - let response = fixture - .request(Method::POST, "/account/passkeys", origin, true) - .await; - SecurityFixture::denied(&response); - } - let response = fixture - .request( - Method::POST, - "/webauthn/authenticate/start", - Some("https://piquel.fr"), - true, - ) - .await; - SecurityFixture::denied(&response); - let response = fixture - .request( - Method::POST, - "/webauthn/authenticate/start", - Some(own), - true, - ) - .await; - assert_eq!(response.status(), StatusCode::ACCEPTED); - - // Any page may read the public metadata, keys and audit checkpoints, without - // credentials. - for path in [ - "/.well-known/openid-configuration", - "/.well-known/oauth-authorization-server", - "/.well-known/jwks.json", - "/audit/checkpoints", - "/audit/checkpoints/latest", - ] { - for (method, status) in [ - (Method::GET, StatusCode::ACCEPTED), - (Method::OPTIONS, StatusCode::NO_CONTENT), - ] { - let response = fixture - .request(method, path, Some("https://tool.example"), false) - .await; - assert_eq!(response.status(), status, "{path}"); - assert_eq!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); - assert!( - response - .headers() - .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) - .is_none() - ); - } - } - // OIDC endpoints authenticate their own tokens/client credentials. Browser - // clients can call protocol APIs, never settings. - for (method, path) in [ - (Method::POST, "/oauth/token"), - (Method::POST, "/oauth/revoke"), - (Method::GET, "/oidc/userinfo"), - (Method::POST, "/oidc/userinfo"), - ] { - let response = fixture - .request(method, path, Some("https://external.example"), false) - .await; - assert_eq!(response.status(), StatusCode::ACCEPTED, "{path}"); - SecurityFixture::exact_cors(&response, "https://external.example"); - } - // A browser form navigation from an RP does not use the settings CSRF header. - let response = fixture - .request( - Method::POST, - "/oauth/authorize", - Some("https://external.example"), - false, - ) - .await; - assert_eq!(response.status(), StatusCode::ACCEPTED); - assert!( - response - .headers() - .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) - .is_none() - ); - for method in [Method::GET, Method::POST, Method::OPTIONS] { - let response = fixture - .request( - method, - "/account/passkeys", - Some("https://external.example"), - true, - ) - .await; - SecurityFixture::denied(&response); - } - let response = fixture - .request(Method::OPTIONS, "/account/passkeys", Some(own), false) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - SecurityFixture::exact_cors(&response, own); - // A public client sends its codes and tokens, never cookies or Piquel's CSRF header. - let response = fixture - .request( - Method::OPTIONS, - "/oauth/token", - Some("https://external.example"), - false, - ) - .await; - assert_eq!(response.status(), StatusCode::NO_CONTENT); - SecurityFixture::exact_cors(&response, "https://external.example"); - assert_eq!( - response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS], - "content-type, authorization" - ); - assert_eq!( - response.headers()[header::ACCESS_CONTROL_ALLOW_METHODS], - "GET, POST, OPTIONS" - ); - for origin in [ - None, - Some("null"), - Some("https://evil.example"), - Some("https://piquel.fr"), - ] { - let response = fixture - .request(Method::OPTIONS, "/account/passkeys", origin, false) - .await; - SecurityFixture::denied(&response); - } - // External RP-initiated logout reaches its own validating handler. This - // dummy handler only proves delegation and cannot log out a real session. - let response = fixture - .request( - Method::GET, - "/oidc/logout", - Some("https://external.example"), - false, - ) - .await; - assert_eq!(response.status(), StatusCode::ACCEPTED); - assert!( - response - .headers() - .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) - .is_none() - ); -} -/// A session lookup failure stays a server error rather than becoming an anonymous session. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn optional_session_preserves_database_failure_instead_of_reporting_signed_out() { - // The timeout also bounds the first connection, so it leaves room for - // connecting while other database tests run. - let database = SecurityFixture::database(1, std::time::Duration::from_secs(1)).await; - // Exhaust only this test's private pool; the database and all other tests - // remain usable. A well-formed session cookie must trigger a real lookup. - let transaction = database.begin().await.expect("hold sole connection"); - assert!( - Session::optional(&database, &HeaderMap::new()) - .await - .expect("no cookie requires no lookup") - .is_none() - ); - let mut headers = HeaderMap::new(); - headers.insert( - header::COOKIE, - HeaderValue::from_str(&format!( - "__Host-piquel_session={}", - Secret::generate().expect("browser secret").encoded() - )) - .expect("cookie"), - ); - let error = Session::optional(&database, &headers) - .await - .expect_err("database timeout must propagate"); - assert_eq!( - ApiError::from(error).into_response().status(), - StatusCode::INTERNAL_SERVER_ERROR - ); - transaction.rollback().await.expect("release connection"); -} -/// Only configured ingress peers may supply a single forwarded client address. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn forwarded_addresses_require_an_explicit_trusted_peer() { - let mut fixture = SecurityFixture::new().await; - let mut request = HttpRequest::builder() - .header("x-forwarded-for", "192.0.2.7") - .body(Body::empty()) - .expect("request"); - request.extensions_mut().insert(ConnectInfo(fixture.peer)); - assert_eq!( - fixture.policy.client_ip(&request).expect("direct peer"), - fixture.peer.ip() - ); - fixture.policy.trusted_proxies = Arc::new(vec![IpNet::from(fixture.peer.ip())]); - assert_eq!( - fixture.policy.client_ip(&request).expect("trusted header"), - "192.0.2.7".parse::().expect("IP") - ); - request - .headers_mut() - .append("x-forwarded-for", HeaderValue::from_static("192.0.2.8")); - assert!(fixture.policy.client_ip(&request).is_err()); - request.headers_mut().remove("x-forwarded-for"); - assert!(fixture.policy.client_ip(&request).is_err()); - request.headers_mut().insert( - "x-forwarded-for", - HeaderValue::from_static("192.0.2.7, 192.0.2.8"), - ); - assert!(fixture.policy.client_ip(&request).is_err()); -} -/// The request deadline also bounds waiting for a locked rate-limit bucket. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn rate_limit_deadline_includes_a_blocked_database_query() { - let mut fixture = SecurityFixture::new().await; - let bucket = Digest::sha256(format!("token:{}", fixture.peer.ip()).as_bytes()); - let mut transaction = fixture.policy.database.begin().await.expect("transaction"); - transaction - .security() - .allow_request(bucket.as_bytes(), 120, std::time::Duration::from_mins(1)) - .await - .expect("hold bucket lock"); - // The deadline also bounds the request after the lock is released, so it - // leaves room for queries while other database tests run. - fixture.policy.request_timeout = std::time::Duration::from_secs(1); - fixture.router = Router::new() - .route("/oauth/token", any(|| async { StatusCode::ACCEPTED })) - .layer(middleware::from_fn_with_state( - fixture.policy.clone(), - HttpSecurity::protect, - )); - let response = tokio::time::timeout( - std::time::Duration::from_secs(5), - fixture.request(Method::POST, "/oauth/token", None, false), - ) - .await - .expect("whole request is bounded"); - assert_eq!(response.status(), StatusCode::GATEWAY_TIMEOUT); - transaction.rollback().await.expect("release lock"); - assert_eq!( - fixture - .request(Method::POST, "/oauth/token", None, false) - .await - .status(), - StatusCode::ACCEPTED - ); -} -/// Unknown paths do not drain budgets and login remains available after token exhaustion. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn rate_budgets_are_separate_and_unknown_paths_do_not_consume_them() { - let fixture = SecurityFixture::new().await; - for _ in 0..125 { - assert_eq!( - fixture - .request(Method::GET, "/login/nonexistent", None, false) - .await - .status(), - StatusCode::NOT_FOUND - ); - } - let bucket = Digest::sha256(format!("token:{}", fixture.peer.ip()).as_bytes()); - for _ in 0..120 { - fixture - .policy - .database - .security() - .allow_request(bucket.as_bytes(), 120, std::time::Duration::from_mins(1)) - .await - .expect("fill token budget"); - } - assert_eq!( - fixture - .request(Method::POST, "/oauth/token", None, false) - .await - .status(), - StatusCode::TOO_MANY_REQUESTS - ); - assert_eq!( - fixture - .request( - Method::POST, - "/webauthn/authenticate/start", - Some("https://auth.piquel.fr"), - true - ) - .await - .status(), - StatusCode::ACCEPTED - ); -} -/// Reads spend their budget and then get a retry delay, without draining other budgets. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn reads_exhaust_their_own_budget() { - let fixture = SecurityFixture::new().await; - for _ in 0..REQUESTS_PER_MINUTE { - assert_eq!( - fixture - .request(Method::GET, "/oidc/userinfo", None, false) - .await - .status(), - StatusCode::ACCEPTED - ); - } - let response = fixture - .request(Method::GET, "/oidc/userinfo", None, false) - .await; - assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS); - assert_eq!(response.headers()[header::RETRY_AFTER], "60"); - assert_eq!( - fixture - .request(Method::GET, passkey::LIST, None, false) - .await - .status(), - StatusCode::ACCEPTED - ); -} -/// One client's budget is shared across replicas: alternating between them, the -/// request after the budget is still rejected. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn replicas_share_one_budget() { - let replicas = Replicas::new().await; - let status = async |router: &Router| { - let request = HttpRequest::get(passkey::LIST) - .body(Body::empty()) - .expect("request"); - router - .clone() - .oneshot(request) - .await - .expect("response") - .status() - }; - for index in 0..REQUESTS_PER_MINUTE { - let router = if index % 2 == 0 { - &replicas.a - } else { - &replicas.b - }; - assert_eq!(status(router).await, StatusCode::UNAUTHORIZED); - } - assert_eq!(status(&replicas.a).await, StatusCode::TOO_MANY_REQUESTS); -} -/// A trusted proxy shares each budget by forwarded client IP rather than ingress IP. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn trusted_proxy_clients_have_independent_budgets() { - let mut fixture = SecurityFixture::new().await; - fixture.policy.trusted_proxies = Arc::new(vec![IpNet::from(fixture.peer.ip())]); - let bucket = Digest::sha256(b"token:192.0.2.17"); - for _ in 0..120 { - fixture - .policy - .database - .security() - .allow_request(bucket.as_bytes(), 120, std::time::Duration::from_mins(1)) - .await - .expect("fill first client's budget"); - } - let router = Router::new() - .route("/oauth/token", any(|| async { StatusCode::ACCEPTED })) - .layer(middleware::from_fn_with_state( - fixture.policy, - HttpSecurity::protect, - )); - for (client, expected) in [ - ("192.0.2.17", StatusCode::TOO_MANY_REQUESTS), - ("192.0.2.18", StatusCode::ACCEPTED), - ] { - let mut request = HttpRequest::builder() - .method(Method::POST) - .uri("/oauth/token") - .header("x-forwarded-for", client) - .body(Body::empty()) - .expect("request"); - request.extensions_mut().insert(ConnectInfo(fixture.peer)); - assert_eq!( - router - .clone() - .oneshot(request) - .await - .expect("response") - .status(), - expected - ); - } -} - -/// Every route that verifies a token or queries the database has a budget, reads -/// included; only in-memory discovery and health probes are free. -#[test] -fn routes_doing_real_work_have_budgets() { - for (path, budget) in [ - (service::LIVE, None), - (service::READY, None), - (oidc::DISCOVERY, None), - (oidc::OAUTH_METADATA, None), - (oidc::JWKS, None), - (audit::CHECKPOINTS, Some(RateCategory::Audit)), - (audit::LATEST_CHECKPOINT, Some(RateCategory::Audit)), - (oidc::TOKEN, Some(RateCategory::Token)), - (oidc::PAR, Some(RateCategory::Token)), - (oidc::USERINFO, Some(RateCategory::UserInfo)), - (oidc::LOGOUT, Some(RateCategory::Login)), - (oidc::AUTHORIZE, Some(RateCategory::Login)), - (oidc::AUTHORIZE_RESUME, Some(RateCategory::Login)), - (passkey::LIST, Some(RateCategory::Account)), - (federation::IDENTITIES, Some(RateCategory::Account)), - (passkey::AUTHENTICATE_START, Some(RateCategory::Login)), - (federation::CALLBACK, Some(RateCategory::Login)), - ] { - assert_eq!(Endpoint::classify(path).rate_category(), budget, "{path}"); - } - // The root and a page's path ending in a slash only redirect to a page. - let redirects = page::ALL.map(|path| format!("{path}/")); - for path in page::ALL - .into_iter() - .chain([page::ROOT]) - .chain(redirects.iter().map(String::as_str)) - { - assert_eq!( - Endpoint::classify(path).rate_category(), - Some(RateCategory::Page), - "{path}" - ); - } -} - -/// A request is classified by the route it matched, so the pages of an app, whose -/// path names it, and their twins ending in a slash are pages. A request no route -/// matched is classified by its path. -#[tokio::test] -async fn requests_are_classified_by_their_route() { - // Answers whether the request is a page's. - let classified = || { - any(|request: Request| async move { - if Endpoint::of(&request).rate_category() == Some(RateCategory::Page) { - StatusCode::ACCEPTED - } else { - StatusCode::NO_CONTENT - } - }) - }; - let router = page::ALL - .into_iter() - .fold(Router::new(), |router, path| { - router - .route(path, classified()) - .route(&format!("{path}/"), classified()) - }) - .fallback(classified()); - for (path, status) in [ - ("/developers/clients/c_any", StatusCode::ACCEPTED), - ("/developers/clients/c_any/settings", StatusCode::ACCEPTED), - ("/developers/clients/c_any/secrets/", StatusCode::ACCEPTED), - ( - "/developers/clients/c_any/elsewhere", - StatusCode::NO_CONTENT, - ), - ] { - let request = HttpRequest::get(path).body(Body::empty()).expect("request"); - let response = router.clone().oneshot(request).await.expect("response"); - assert_eq!(response.status(), status, "{path}"); - } -} - -/// The origin of auth's own pages in the policy tests. -fn site() -> url::Origin { - url::Url::parse("https://auth.piquel.fr") - .expect("URL") - .origin() -} - -/// Browser origin and mutation proof are required everywhere except protocol -/// endpoints, and pages, which have their own rule. -#[test] -fn endpoint_policy_requires_browser_proof_outside_protocol_endpoints() { - let site = site(); - let check = |endpoint, headers: &HeaderMap, allowed, mutation| { - HttpSecurity::check_browser(endpoint, headers, allowed, mutation, &site).is_ok() - }; - for (endpoint, protocol) in [ - (Endpoint::OAuthBackChannel, true), - (Endpoint::UserInfo, true), - (Endpoint::Discovery, false), - (Endpoint::Checkpoints, false), - (Endpoint::Health, false), - (Endpoint::Authorize, true), - (Endpoint::Logout, true), - (Endpoint::Account, false), - (Endpoint::Other, false), - ] { - assert_eq!(endpoint.is_protocol(), protocol); - let anonymous = HeaderMap::new(); - let mut browser = HeaderMap::new(); - browser.insert( - header::ORIGIN, - HeaderValue::from_static("https://evil.example"), - ); - // Unapproved mutations and cross-origin reads only reach protocol handlers. - assert_eq!(check(endpoint, &anonymous, false, true), protocol); - assert_eq!(check(endpoint, &browser, false, false), protocol); - assert!(check(endpoint, &anonymous, false, false)); - // Approved mutations still need CSRF proof. - assert_eq!(check(endpoint, &browser, true, true), protocol); - browser.insert(CSRF_HEADER, HeaderValue::from_static("1")); - assert!(check(endpoint, &browser, true, true)); - } -} - -/// Anyone may navigate to a page, but only auth's own pages may post its form: -/// `Sec-Fetch-Site` decides when the browser sends it, then `Origin`. A form on a -/// `no-referrer` page sends `Origin: null`, and the CSRF header changes nothing. -#[test] -fn pages_take_forms_only_from_auth_pages() { - let own = Some("https://auth.piquel.fr"); - for (fetch_site, origin, csrf, mutation, accepted) in [ - (None, None, false, false, true), - ( - Some("cross-site"), - Some("https://evil.example"), - false, - false, - true, - ), - (Some("same-origin"), Some("null"), false, true, true), - (Some("same-origin"), None, false, true, true), - (None, own, false, true, true), - (Some("same-site"), own, false, true, false), - (Some("cross-site"), Some("null"), true, true, false), - (Some("none"), None, false, true, false), - (None, Some("null"), false, true, false), - (None, None, true, true, false), - ] { - let mut headers = HeaderMap::new(); - if let Some(fetch_site) = fetch_site { - headers.insert(FETCH_SITE_HEADER, HeaderValue::from_static(fetch_site)); - } - if let Some(origin) = origin { - headers.insert(header::ORIGIN, HeaderValue::from_static(origin)); - } - if csrf { - headers.insert(CSRF_HEADER, HeaderValue::from_static("1")); - } - assert_eq!( - HttpSecurity::check_browser(Endpoint::Page, &headers, true, mutation, &site()).is_ok(), - accepted, - "{fetch_site:?} {origin:?} csrf={csrf} mutation={mutation}" - ); - } -} - -/// Forwarded addresses accept one IP and retain diagnostics for malformed header text or syntax. -#[test] -fn forwarded_address_parser_requires_one_address_and_preserves_causes() { - let mut headers = HeaderMap::new(); - assert!(matches!( - HttpSecurity::forwarded_ip(&headers), - Err(HttpSecurityError::MissingForwardedAddress) - )); - for valid in ["192.0.2.7", "2001:db8::7"] { - headers.insert( - FORWARDED_FOR_HEADER, - HeaderValue::from_str(valid).expect("header"), - ); - assert_eq!( - HttpSecurity::forwarded_ip(&headers).expect("forwarded address"), - valid.parse::().expect("IP") - ); - } - headers.append(FORWARDED_FOR_HEADER, HeaderValue::from_static("192.0.2.8")); - assert!(matches!( - HttpSecurity::forwarded_ip(&headers), - Err(HttpSecurityError::MultipleForwardedHeaders) - )); - headers.insert( - FORWARDED_FOR_HEADER, - HeaderValue::from_static("192.0.2.7, 192.0.2.8"), - ); - let error = HttpSecurity::forwarded_ip(&headers).expect_err("one address required"); - assert!(matches!(error, HttpSecurityError::ForwardedAddress(_))); - assert!(std::error::Error::source(&error).is_some()); - headers.insert( - FORWARDED_FOR_HEADER, - HeaderValue::from_bytes(&[0xff]).expect("opaque header"), - ); - let error = HttpSecurity::forwarded_ip(&headers).expect_err("HTTP text required"); - assert!(matches!(error, HttpSecurityError::ForwardedHeader(_))); - assert!(std::error::Error::source(&error).is_some()); -} - -/// A confirmation counts from its own timestamp, against each action's maximum age. -#[test] -fn confirmation_age_is_fixed_from_its_timestamp() { - let session = |age: Option| { - let now = Utc::now(); - StoredSession { - id: SessionId::new(), - user_id: UserId::new(), - authentication_methods: vec![AuthenticationMethod::Passkey], - authenticated_at: now - Duration::days(1), - expires_at: now + Duration::days(1), - last_seen_at: now, - revoked_at: None, - passkey_confirmed_at: age.map(|age| now - Duration::seconds(age)), - user_agent_family: None, - last_seen_ip: None, - } - }; - assert!(Confirmed::::check(&session(Some(290))).is_ok()); - for age in [None, Some(310), Some(86_400)] { - assert!(matches!( - Confirmed::::check(&session(age)), - Err(SessionError::StepUpRequired { - max_age: CONFIRMATION_MAX_AGE - }) - )); - } - assert!(matches!( - Confirmed::<60>::check(&session(Some(90))), - Err(SessionError::StepUpRequired { max_age: 60 }) - )); -} - -/// A confirmed change holds the session row, so a racing logout waits for it, and a -/// change after logout fails. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn confirmed_changes_serialize_with_logout() { - let database = SecurityFixture::database(5, std::time::Duration::from_secs(5)).await; - database.run_migrations().await.expect("migrations"); - let user_id = UserId::new(); - let mut tx = database.begin().await.expect("transaction"); - tx.users() - .insert(&InsertUser { - id: user_id, - handle: Handle::parse(&format!("lock-{}", &TokenId::new().to_string()[24..])) - .expect("handle"), - display_name: "Lock test".into(), - }) - .await - .expect("user"); - let secret = Session::create( - &mut tx, - RequestContext::TEST, - user_id, - AuthenticationMethod::Passkey.into(), - ) - .await - .expect("session"); - tx.commit().await.expect("commit"); - let session = database - .sessions() - .find_active_by_browser_secret(secret.digest().as_bytes()) - .await - .expect("lookup") - .expect("session"); - let id = session.id; - let mut change = database.begin().await.expect("change transaction"); - let locked = Session::lock(&mut change, &session).await.expect("lock"); - ::check(&locked).expect("passkey sign-in confirms"); - let logout = tokio::spawn({ - let database = database.clone(); - async move { - let context = RequestContext::TEST.actor(Actor::User { - user_id, - session_id: Some(id), - }); - let mut logout = database.begin().await?; - let revoked = logout - .revoke_sessions( - &context, - user_id, - SessionScope::One(id), - &RevocationReason::Logout, - ) - .await?; - logout.commit().await.map(|()| revoked) - } - }); - tokio::time::sleep(std::time::Duration::from_millis(200)).await; - assert!(!logout.is_finished(), "logout must wait for the change"); - change.commit().await.expect("commit change"); - assert_eq!(logout.await.expect("logout task").expect("logout"), [id]); - let mut change = database.begin().await.expect("change transaction"); - assert!(matches!( - Session::lock(&mut change, &session).await, - Err(SessionError::Missing) - )); -} - -/// A session that expires while a change waits for the account lock is rejected once -/// the lock is acquired, even though the lookup compares with the transaction's start. -#[tokio::test] -#[ignore = "requires TEST_DATABASE_URL"] -async fn session_lock_rechecks_expiry_after_waiting() { - let database = SecurityFixture::database(5, std::time::Duration::from_secs(5)).await; - database.run_migrations().await.expect("migrations"); - let user_id = UserId::new(); - let now = Utc::now(); - let mut tx = database.begin().await.expect("transaction"); - tx.users() - .insert(&InsertUser { - id: user_id, - handle: Handle::parse(&format!("lock-{}", &TokenId::new().to_string()[24..])) - .expect("handle"), - display_name: "Lock test".into(), - }) - .await - .expect("user"); - let session = tx - .sessions() - .insert(&InsertSession { - id: SessionId::new(), - user_id, - authentication_methods: vec![AuthenticationMethod::Passkey], - authenticated_at: now, - expires_at: now + Duration::seconds(1), - user_agent_family: RequestContext::TEST.user_agent_family, - ip: RequestContext::TEST.client_ip, - passkey_confirmed_at: Some(now), - passkey_id: None, - }) - .await - .expect("session"); - tx.commit().await.expect("commit"); - let mut holder = database.begin().await.expect("holder transaction"); - holder - .users() - .find_active_by_id_for_update(user_id) - .await - .expect("account lock") - .expect("active account"); - let change = tokio::spawn({ - let database = database.clone(); - async move { - let mut change = database.begin().await.expect("change transaction"); - Session::lock(&mut change, &session).await.map(drop) - } - }); - tokio::time::sleep(std::time::Duration::from_millis(1500)).await; - holder.rollback().await.expect("release account"); - assert!(matches!( - change.await.expect("change task"), - Err(SessionError::Missing) - )); -} - -/// Decorates `response` as [`HttpSecurity::protect`] does on the given CORS `grant`. -fn decorated(response: impl IntoResponse, grant: Option) -> Response { - let mut response = response.into_response(); - HttpSecurity::decorate(&mut response, grant); - response -} - -/// The CORS grant of an approved origin, such as a public client's. -fn client() -> CorsGrant { - CorsGrant::Client(HeaderValue::from_static("https://external.example")) -} - -/// Each class sends its own `Cache-Control`. -#[test] -fn cached_responses_carry_their_class() { - for (class, cache_control) in [ - ( - CacheClass::Immutable, - "public, max-age=31536000, immutable, no-transform", - ), - ( - CacheClass::Public { - max_age: std::time::Duration::from_secs(3600), - }, - "public, max-age=3600, no-transform", - ), - ] { - let response = decorated(Cached(class, StatusCode::OK), None); - assert_eq!( - response.headers()[header::CACHE_CONTROL], - cache_control, - "{class:?}" - ); - } -} - -/// Only a classed success without cookies may be stored: anything -/// else is `no-store`, whatever the handler set. -#[test] -fn unclassed_errors_and_cookie_responses_are_not_stored() { - let class = CacheClass::Public { - max_age: std::time::Duration::from_secs(3600), - }; - for response in [ - decorated(Cached(class, [(header::SET_COOKIE, "a=b")]), None), - decorated(Cached(class, StatusCode::FORBIDDEN), None), - decorated(Cached(class, StatusCode::NOT_FOUND), None), - decorated(Cached(class, StatusCode::TOO_MANY_REQUESTS), None), - decorated([(header::CACHE_CONTROL, "public, max-age=60")], None), - ] { - assert_eq!( - response.headers()[header::CACHE_CONTROL], - "no-store, no-transform" - ); - } -} - -/// Public data is readable from every origin without credentials, so one cached copy -/// serves them all; an embedded file has no CORS headers, even for an approved -/// origin. -#[test] -fn cached_responses_are_the_same_for_every_origin() { - let public = CacheClass::Public { - max_age: std::time::Duration::from_secs(3600), - }; - for grant in [None, Some(client())] { - let response = decorated(Cached(public, StatusCode::OK), grant); - let headers = response.headers(); - assert_eq!(headers[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); - assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assert!(!headers.contains_key(header::VARY)); - } - let response = decorated( - Cached(CacheClass::Immutable, StatusCode::OK), - Some(client()), - ); - let headers = response.headers(); - assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)); - assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assert!(!headers.contains_key(header::VARY)); -} diff --git a/apps/auth-service/src/security/tests/caching.rs b/apps/auth-service/src/security/tests/caching.rs new file mode 100644 index 000000000..fa7db2998 --- /dev/null +++ b/apps/auth-service/src/security/tests/caching.rs @@ -0,0 +1,85 @@ +//! The `Cache-Control` and CORS headers cached responses carry. + +use super::*; + +/// Decorates `response` as [`HttpSecurity::protect`] does on the given CORS `grant`. +fn decorated(response: impl IntoResponse, grant: Option) -> Response { + let mut response = response.into_response(); + HttpSecurity::decorate(&mut response, grant); + response +} + +/// The CORS grant of an approved origin, such as a public client's. +fn client() -> CorsGrant { + CorsGrant::Client(HeaderValue::from_static("https://external.example")) +} + +/// Each class sends its own `Cache-Control`. +#[test] +fn cached_responses_carry_their_class() { + for (class, cache_control) in [ + ( + CacheClass::Immutable, + "public, max-age=31536000, immutable, no-transform", + ), + ( + CacheClass::Public { + max_age: std::time::Duration::from_secs(3600), + }, + "public, max-age=3600, no-transform", + ), + ] { + let response = decorated(Cached(class, StatusCode::OK), None); + assert_eq!( + response.headers()[header::CACHE_CONTROL], + cache_control, + "{class:?}" + ); + } +} + +/// Only a classed success without cookies may be stored: anything +/// else is `no-store`, whatever the handler set. +#[test] +fn unclassed_errors_and_cookie_responses_are_not_stored() { + let class = CacheClass::Public { + max_age: std::time::Duration::from_secs(3600), + }; + for response in [ + decorated(Cached(class, [(header::SET_COOKIE, "a=b")]), None), + decorated(Cached(class, StatusCode::FORBIDDEN), None), + decorated(Cached(class, StatusCode::NOT_FOUND), None), + decorated(Cached(class, StatusCode::TOO_MANY_REQUESTS), None), + decorated([(header::CACHE_CONTROL, "public, max-age=60")], None), + ] { + assert_eq!( + response.headers()[header::CACHE_CONTROL], + "no-store, no-transform" + ); + } +} + +/// Public data is readable from every origin without credentials, so one cached copy +/// serves them all; an embedded file has no CORS headers, even for an approved +/// origin. +#[test] +fn cached_responses_are_the_same_for_every_origin() { + let public = CacheClass::Public { + max_age: std::time::Duration::from_secs(3600), + }; + for grant in [None, Some(client())] { + let response = decorated(Cached(public, StatusCode::OK), grant); + let headers = response.headers(); + assert_eq!(headers[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); + assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assert!(!headers.contains_key(header::VARY)); + } + let response = decorated( + Cached(CacheClass::Immutable, StatusCode::OK), + Some(client()), + ); + let headers = response.headers(); + assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)); + assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assert!(!headers.contains_key(header::VARY)); +} diff --git a/apps/auth-service/src/security/tests/forwarding.rs b/apps/auth-service/src/security/tests/forwarding.rs new file mode 100644 index 000000000..b856ebf49 --- /dev/null +++ b/apps/auth-service/src/security/tests/forwarding.rs @@ -0,0 +1,74 @@ +//! Which peers may supply a forwarded client address, and how it is parsed. + +use super::*; + +/// Only configured ingress peers may supply a single forwarded client address. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn forwarded_addresses_require_an_explicit_trusted_peer() { + let mut fixture = SecurityFixture::new().await; + let mut request = HttpRequest::builder() + .header("x-forwarded-for", "192.0.2.7") + .body(Body::empty()) + .expect("request"); + request.extensions_mut().insert(ConnectInfo(fixture.peer)); + assert_eq!( + fixture.policy.client_ip(&request).expect("direct peer"), + fixture.peer.ip() + ); + fixture.policy.trusted_proxies = Arc::new(vec![IpNet::from(fixture.peer.ip())]); + assert_eq!( + fixture.policy.client_ip(&request).expect("trusted header"), + "192.0.2.7".parse::().expect("IP") + ); + request + .headers_mut() + .append("x-forwarded-for", HeaderValue::from_static("192.0.2.8")); + assert!(fixture.policy.client_ip(&request).is_err()); + request.headers_mut().remove("x-forwarded-for"); + assert!(fixture.policy.client_ip(&request).is_err()); + request.headers_mut().insert( + "x-forwarded-for", + HeaderValue::from_static("192.0.2.7, 192.0.2.8"), + ); + assert!(fixture.policy.client_ip(&request).is_err()); +} + +/// Forwarded addresses accept one IP and retain diagnostics for malformed header text or syntax. +#[test] +fn forwarded_address_parser_requires_one_address_and_preserves_causes() { + let mut headers = HeaderMap::new(); + assert!(matches!( + HttpSecurity::forwarded_ip(&headers), + Err(HttpSecurityError::MissingForwardedAddress) + )); + for valid in ["192.0.2.7", "2001:db8::7"] { + headers.insert( + FORWARDED_FOR_HEADER, + HeaderValue::from_str(valid).expect("header"), + ); + assert_eq!( + HttpSecurity::forwarded_ip(&headers).expect("forwarded address"), + valid.parse::().expect("IP") + ); + } + headers.append(FORWARDED_FOR_HEADER, HeaderValue::from_static("192.0.2.8")); + assert!(matches!( + HttpSecurity::forwarded_ip(&headers), + Err(HttpSecurityError::MultipleForwardedHeaders) + )); + headers.insert( + FORWARDED_FOR_HEADER, + HeaderValue::from_static("192.0.2.7, 192.0.2.8"), + ); + let error = HttpSecurity::forwarded_ip(&headers).expect_err("one address required"); + assert!(matches!(error, HttpSecurityError::ForwardedAddress(_))); + assert!(std::error::Error::source(&error).is_some()); + headers.insert( + FORWARDED_FOR_HEADER, + HeaderValue::from_bytes(&[0xff]).expect("opaque header"), + ); + let error = HttpSecurity::forwarded_ip(&headers).expect_err("HTTP text required"); + assert!(matches!(error, HttpSecurityError::ForwardedHeader(_))); + assert!(std::error::Error::source(&error).is_some()); +} diff --git a/apps/auth-service/src/security/tests/mod.rs b/apps/auth-service/src/security/tests/mod.rs new file mode 100644 index 000000000..f7cd26d50 --- /dev/null +++ b/apps/auth-service/src/security/tests/mod.rs @@ -0,0 +1,204 @@ +//! Focused persistence and security contract tests. + +use super::*; +use crate::tests::REQUESTS_PER_MINUTE; +use axum::{Router, body::Body, http::Request as HttpRequest, middleware, routing::any}; +use piquel_common::{ + clients::{ClientKind, ClientOwner}, + events::{Browser, Platform}, +}; +use piquel_repository::DatabaseConfig; +use std::net::{IpAddr, Ipv6Addr}; +use tower::ServiceExt; + +mod caching; +mod forwarding; +mod origins; +mod rate_limits; +mod sessions; + +impl RequestContext { + /// The context of a request from a documentation address, for handler tests + /// that bypass [`HttpSecurity::protect`]. + pub(crate) const TEST: Self = Self { + client_ip: IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 1)), + user_agent_family: UserAgentFamily { + browser: Browser::Firefox, + platform: Platform::Linux, + }, + }; + + /// The context of a request from `client_ip`, for handler tests that keep + /// their per-IP limits apart from other tests'. + pub(crate) const fn from_ip(client_ip: IpAddr) -> Self { + Self { + client_ip, + ..Self::TEST + } + } +} + +/// Asserts that `response` asks the frontend to confirm the session with a passkey +/// at most [`CONFIRMATION_MAX_AGE`] seconds old, in the stable JSON shape. +pub(crate) async fn assert_step_up_required(response: Response) { + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let body: serde_json::Value = serde_json::from_slice( + &axum::body::to_bytes(response.into_body(), 4096) + .await + .expect("body"), + ) + .expect("JSON"); + assert_eq!( + body, + serde_json::json!({ + "error": "Confirm with your passkey to continue.", + "code": "step_up_required", + "max_age": CONFIRMATION_MAX_AGE, + }) + ); +} + +/// An isolated request router and database for HTTP trust-boundary scenarios. +struct SecurityFixture { + /// Dummy routes protected by the production middleware. + router: Router, + /// Unique peer address separates concurrent test budgets. + peer: SocketAddr, + /// Editable policy for proxy and deadline scenarios. + policy: HttpSecurity, +} +impl SecurityFixture { + /// Connects an isolated test pool with caller-selected acquisition bounds. + async fn database(max_connections: u32, timeout: std::time::Duration) -> Database { + let url = piquel_common::config::Variable::new("TEST_DATABASE_URL") + .required() + .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); + Database::connect( + DatabaseConfig::new(&url, max_connections, timeout).expect("database configuration"), + ) + .await + .expect("database") + } + /// Builds a test policy with exact browser origins and unique client buckets. + /// A public client calls back to `https://external.example`. + async fn new() -> Self { + let database = Self::database(5, std::time::Duration::from_secs(5)).await; + database.run_migrations().await.expect("migrations"); + database + .oidc() + .create_client( + &crate::tests::registration(ClientKind::Public, "https://external.example"), + ClientOwner::Operator, + ) + .await + .expect("public client"); + let policy = HttpSecurity { + trusted_proxies: Arc::new(vec![]), + request_timeout: std::time::Duration::from_secs(30), + requests_per_minute: REQUESTS_PER_MINUTE, + database, + origin: site(), + listener: Listener::Public, + }; + let mut router = Router::new(); + for path in [ + "/account/passkeys", + "/webauthn/authenticate/start", + "/.well-known/openid-configuration", + "/.well-known/oauth-authorization-server", + "/.well-known/jwks.json", + "/audit/checkpoints", + "/audit/checkpoints/latest", + "/oauth/token", + "/oauth/authorize", + "/oauth/revoke", + "/oidc/userinfo", + "/oidc/logout", + ] { + router = router.route(path, any(|| async { StatusCode::ACCEPTED })); + } + let peer = SocketAddr::new( + IpAddr::V6(Ipv6Addr::from(UserId::new().as_uuid().as_u128())), + 4321, + ); + Self { + router: router.layer(middleware::from_fn_with_state( + policy.clone(), + HttpSecurity::protect, + )), + peer, + policy, + } + } + /// Sends a request with selected browser proof and explicit peer metadata. + async fn request( + &self, + method: Method, + path: &str, + origin: Option<&str>, + csrf: bool, + ) -> Response { + let mut request = HttpRequest::builder().method(method.clone()).uri(path); + if let Some(origin) = origin { + request = request.header(header::ORIGIN, origin); + } + if csrf { + request = request.header("x-piquel-csrf", "1"); + } + if method == Method::OPTIONS { + request = request + .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST") + .header( + header::ACCESS_CONTROL_REQUEST_HEADERS, + "content-type, x-piquel-csrf", + ); + } + let mut request = request.body(Body::empty()).expect("request"); + request.extensions_mut().insert(ConnectInfo(self.peer)); + self.router + .clone() + .oneshot(request) + .await + .expect("response") + } + /// Checks CORS reflects exactly the approved origin, without the browser's + /// cookies. + fn exact_cors(response: &Response, origin: &str) { + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], + origin + ); + assert!( + !response + .headers() + .contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) + ); + assert_eq!(response.headers()[header::VARY], "Origin"); + assert_ne!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); + } + /// Checks rejected origins receive browser isolation headers and no CORS grant. + fn denied(response: &Response) { + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert!( + response + .headers() + .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) + .is_none() + ); + assert_eq!( + response.headers()[header::CACHE_CONTROL], + "no-store, no-transform" + ); + assert_eq!( + response.headers()[header::X_CONTENT_TYPE_OPTIONS], + "nosniff" + ); + } +} + +/// The origin of auth's own pages in the policy tests. +fn site() -> url::Origin { + url::Url::parse("https://auth.piquel.fr") + .expect("URL") + .origin() +} diff --git a/apps/auth-service/src/security/tests/origins.rs b/apps/auth-service/src/security/tests/origins.rs new file mode 100644 index 000000000..946bad119 --- /dev/null +++ b/apps/auth-service/src/security/tests/origins.rs @@ -0,0 +1,259 @@ +//! The browser-origin, CSRF and CORS rules each endpoint family enforces. + +use super::*; + +/// Exercises exact-origin, CSRF and public-client boundaries across endpoint families. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +#[expect( + clippy::too_many_lines, + reason = "Keep this complete browser-origin trust-boundary scenario together." +)] +async fn router_enforces_exact_browser_origins_csrf_and_public_client_cors_boundaries() { + let fixture = SecurityFixture::new().await; + let own = "https://auth.piquel.fr"; + let response = fixture + .request(Method::POST, "/account/passkeys", Some(own), true) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED); + SecurityFixture::exact_cors(&response, own); + let response = fixture + .request(Method::POST, "/account/passkeys", Some(own), false) + .await; + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "approved origin still needs CSRF header" + ); + for origin in [ + None, + Some("null"), + Some("https://evil.example"), + Some("https://piquel.fr"), + Some("https://auth.piquel.fr.evil.example"), + Some("https://auth.piquel.fr:444"), + Some("http://auth.piquel.fr"), + ] { + let response = fixture + .request(Method::POST, "/account/passkeys", origin, true) + .await; + SecurityFixture::denied(&response); + } + let response = fixture + .request( + Method::POST, + "/webauthn/authenticate/start", + Some("https://piquel.fr"), + true, + ) + .await; + SecurityFixture::denied(&response); + let response = fixture + .request( + Method::POST, + "/webauthn/authenticate/start", + Some(own), + true, + ) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED); + + // Any page may read the public metadata, keys and audit checkpoints, without + // credentials. + for path in [ + "/.well-known/openid-configuration", + "/.well-known/oauth-authorization-server", + "/.well-known/jwks.json", + "/audit/checkpoints", + "/audit/checkpoints/latest", + ] { + for (method, status) in [ + (Method::GET, StatusCode::ACCEPTED), + (Method::OPTIONS, StatusCode::NO_CONTENT), + ] { + let response = fixture + .request(method, path, Some("https://tool.example"), false) + .await; + assert_eq!(response.status(), status, "{path}"); + assert_eq!(response.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); + assert!( + response + .headers() + .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS) + .is_none() + ); + } + } + // OIDC endpoints authenticate their own tokens/client credentials. Browser + // clients can call protocol APIs, never settings. + for (method, path) in [ + (Method::POST, "/oauth/token"), + (Method::POST, "/oauth/revoke"), + (Method::GET, "/oidc/userinfo"), + (Method::POST, "/oidc/userinfo"), + ] { + let response = fixture + .request(method, path, Some("https://external.example"), false) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED, "{path}"); + SecurityFixture::exact_cors(&response, "https://external.example"); + } + // A browser form navigation from an RP does not use the settings CSRF header. + let response = fixture + .request( + Method::POST, + "/oauth/authorize", + Some("https://external.example"), + false, + ) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED); + assert!( + response + .headers() + .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) + .is_none() + ); + for method in [Method::GET, Method::POST, Method::OPTIONS] { + let response = fixture + .request( + method, + "/account/passkeys", + Some("https://external.example"), + true, + ) + .await; + SecurityFixture::denied(&response); + } + let response = fixture + .request(Method::OPTIONS, "/account/passkeys", Some(own), false) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + SecurityFixture::exact_cors(&response, own); + // A public client sends its codes and tokens, never cookies or Piquel's CSRF header. + let response = fixture + .request( + Method::OPTIONS, + "/oauth/token", + Some("https://external.example"), + false, + ) + .await; + assert_eq!(response.status(), StatusCode::NO_CONTENT); + SecurityFixture::exact_cors(&response, "https://external.example"); + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_HEADERS], + "content-type, authorization" + ); + assert_eq!( + response.headers()[header::ACCESS_CONTROL_ALLOW_METHODS], + "GET, POST, OPTIONS" + ); + for origin in [ + None, + Some("null"), + Some("https://evil.example"), + Some("https://piquel.fr"), + ] { + let response = fixture + .request(Method::OPTIONS, "/account/passkeys", origin, false) + .await; + SecurityFixture::denied(&response); + } + // External RP-initiated logout reaches its own validating handler. This + // dummy handler only proves delegation and cannot log out a real session. + let response = fixture + .request( + Method::GET, + "/oidc/logout", + Some("https://external.example"), + false, + ) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED); + assert!( + response + .headers() + .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) + .is_none() + ); +} + +/// Browser origin and mutation proof are required everywhere except protocol +/// endpoints, and pages, which have their own rule. +#[test] +fn endpoint_policy_requires_browser_proof_outside_protocol_endpoints() { + let site = site(); + let check = |endpoint, headers: &HeaderMap, allowed, mutation| { + HttpSecurity::check_browser(endpoint, headers, allowed, mutation, &site).is_ok() + }; + for (endpoint, protocol) in [ + (Endpoint::OAuthBackChannel, true), + (Endpoint::UserInfo, true), + (Endpoint::Discovery, false), + (Endpoint::Checkpoints, false), + (Endpoint::Health, false), + (Endpoint::Authorize, true), + (Endpoint::Logout, true), + (Endpoint::Account, false), + (Endpoint::Other, false), + ] { + assert_eq!(endpoint.is_protocol(), protocol); + let anonymous = HeaderMap::new(); + let mut browser = HeaderMap::new(); + browser.insert( + header::ORIGIN, + HeaderValue::from_static("https://evil.example"), + ); + // Unapproved mutations and cross-origin reads only reach protocol handlers. + assert_eq!(check(endpoint, &anonymous, false, true), protocol); + assert_eq!(check(endpoint, &browser, false, false), protocol); + assert!(check(endpoint, &anonymous, false, false)); + // Approved mutations still need CSRF proof. + assert_eq!(check(endpoint, &browser, true, true), protocol); + browser.insert(CSRF_HEADER, HeaderValue::from_static("1")); + assert!(check(endpoint, &browser, true, true)); + } +} + +/// Anyone may navigate to a page, but only auth's own pages may post its form: +/// `Sec-Fetch-Site` decides when the browser sends it, then `Origin`. A form on a +/// `no-referrer` page sends `Origin: null`, and the CSRF header changes nothing. +#[test] +fn pages_take_forms_only_from_auth_pages() { + let own = Some("https://auth.piquel.fr"); + for (fetch_site, origin, csrf, mutation, accepted) in [ + (None, None, false, false, true), + ( + Some("cross-site"), + Some("https://evil.example"), + false, + false, + true, + ), + (Some("same-origin"), Some("null"), false, true, true), + (Some("same-origin"), None, false, true, true), + (None, own, false, true, true), + (Some("same-site"), own, false, true, false), + (Some("cross-site"), Some("null"), true, true, false), + (Some("none"), None, false, true, false), + (None, Some("null"), false, true, false), + (None, None, true, true, false), + ] { + let mut headers = HeaderMap::new(); + if let Some(fetch_site) = fetch_site { + headers.insert(FETCH_SITE_HEADER, HeaderValue::from_static(fetch_site)); + } + if let Some(origin) = origin { + headers.insert(header::ORIGIN, HeaderValue::from_static(origin)); + } + if csrf { + headers.insert(CSRF_HEADER, HeaderValue::from_static("1")); + } + assert_eq!( + HttpSecurity::check_browser(Endpoint::Page, &headers, true, mutation, &site()).is_ok(), + accepted, + "{fetch_site:?} {origin:?} csrf={csrf} mutation={mutation}" + ); + } +} diff --git a/apps/auth-service/src/security/tests/rate_limits.rs b/apps/auth-service/src/security/tests/rate_limits.rs new file mode 100644 index 000000000..edefddeb9 --- /dev/null +++ b/apps/auth-service/src/security/tests/rate_limits.rs @@ -0,0 +1,263 @@ +//! Rate-limit budgets: which routes spend them, how they are shared and bounded. + +use super::*; +use crate::routes::{audit, federation, passkey}; +use crate::tests::Replicas; + +/// The request deadline also bounds waiting for a locked rate-limit bucket. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn rate_limit_deadline_includes_a_blocked_database_query() { + let mut fixture = SecurityFixture::new().await; + let bucket = Digest::sha256(format!("token:{}", fixture.peer.ip()).as_bytes()); + let mut transaction = fixture.policy.database.begin().await.expect("transaction"); + transaction + .security() + .allow_request(bucket.as_bytes(), 120, std::time::Duration::from_mins(1)) + .await + .expect("hold bucket lock"); + // The deadline also bounds the request after the lock is released, so it + // leaves room for queries while other database tests run. + fixture.policy.request_timeout = std::time::Duration::from_secs(1); + fixture.router = Router::new() + .route("/oauth/token", any(|| async { StatusCode::ACCEPTED })) + .layer(middleware::from_fn_with_state( + fixture.policy.clone(), + HttpSecurity::protect, + )); + let response = tokio::time::timeout( + std::time::Duration::from_secs(5), + fixture.request(Method::POST, "/oauth/token", None, false), + ) + .await + .expect("whole request is bounded"); + assert_eq!(response.status(), StatusCode::GATEWAY_TIMEOUT); + transaction.rollback().await.expect("release lock"); + assert_eq!( + fixture + .request(Method::POST, "/oauth/token", None, false) + .await + .status(), + StatusCode::ACCEPTED + ); +} +/// Unknown paths do not drain budgets and login remains available after token exhaustion. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn rate_budgets_are_separate_and_unknown_paths_do_not_consume_them() { + let fixture = SecurityFixture::new().await; + for _ in 0..125 { + assert_eq!( + fixture + .request(Method::GET, "/login/nonexistent", None, false) + .await + .status(), + StatusCode::NOT_FOUND + ); + } + let bucket = Digest::sha256(format!("token:{}", fixture.peer.ip()).as_bytes()); + for _ in 0..120 { + fixture + .policy + .database + .security() + .allow_request(bucket.as_bytes(), 120, std::time::Duration::from_mins(1)) + .await + .expect("fill token budget"); + } + assert_eq!( + fixture + .request(Method::POST, "/oauth/token", None, false) + .await + .status(), + StatusCode::TOO_MANY_REQUESTS + ); + assert_eq!( + fixture + .request( + Method::POST, + "/webauthn/authenticate/start", + Some("https://auth.piquel.fr"), + true + ) + .await + .status(), + StatusCode::ACCEPTED + ); +} +/// Reads spend their budget and then get a retry delay, without draining other budgets. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn reads_exhaust_their_own_budget() { + let fixture = SecurityFixture::new().await; + for _ in 0..REQUESTS_PER_MINUTE { + assert_eq!( + fixture + .request(Method::GET, "/oidc/userinfo", None, false) + .await + .status(), + StatusCode::ACCEPTED + ); + } + let response = fixture + .request(Method::GET, "/oidc/userinfo", None, false) + .await; + assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS); + assert_eq!(response.headers()[header::RETRY_AFTER], "60"); + assert_eq!( + fixture + .request(Method::GET, passkey::LIST, None, false) + .await + .status(), + StatusCode::ACCEPTED + ); +} +/// One client's budget is shared across replicas: alternating between them, the +/// request after the budget is still rejected. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn replicas_share_one_budget() { + let replicas = Replicas::new().await; + let status = async |router: &Router| { + let request = HttpRequest::get(passkey::LIST) + .body(Body::empty()) + .expect("request"); + router + .clone() + .oneshot(request) + .await + .expect("response") + .status() + }; + for index in 0..REQUESTS_PER_MINUTE { + let router = if index % 2 == 0 { + &replicas.a + } else { + &replicas.b + }; + assert_eq!(status(router).await, StatusCode::UNAUTHORIZED); + } + assert_eq!(status(&replicas.a).await, StatusCode::TOO_MANY_REQUESTS); +} +/// A trusted proxy shares each budget by forwarded client IP rather than ingress IP. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn trusted_proxy_clients_have_independent_budgets() { + let mut fixture = SecurityFixture::new().await; + fixture.policy.trusted_proxies = Arc::new(vec![IpNet::from(fixture.peer.ip())]); + let bucket = Digest::sha256(b"token:192.0.2.17"); + for _ in 0..120 { + fixture + .policy + .database + .security() + .allow_request(bucket.as_bytes(), 120, std::time::Duration::from_mins(1)) + .await + .expect("fill first client's budget"); + } + let router = Router::new() + .route("/oauth/token", any(|| async { StatusCode::ACCEPTED })) + .layer(middleware::from_fn_with_state( + fixture.policy, + HttpSecurity::protect, + )); + for (client, expected) in [ + ("192.0.2.17", StatusCode::TOO_MANY_REQUESTS), + ("192.0.2.18", StatusCode::ACCEPTED), + ] { + let mut request = HttpRequest::builder() + .method(Method::POST) + .uri("/oauth/token") + .header("x-forwarded-for", client) + .body(Body::empty()) + .expect("request"); + request.extensions_mut().insert(ConnectInfo(fixture.peer)); + assert_eq!( + router + .clone() + .oneshot(request) + .await + .expect("response") + .status(), + expected + ); + } +} + +/// Every route that verifies a token or queries the database has a budget, reads +/// included; only in-memory discovery and health probes are free. +#[test] +fn routes_doing_real_work_have_budgets() { + for (path, budget) in [ + (service::LIVE, None), + (service::READY, None), + (oidc::DISCOVERY, None), + (oidc::OAUTH_METADATA, None), + (oidc::JWKS, None), + (audit::CHECKPOINTS, Some(RateCategory::Audit)), + (audit::LATEST_CHECKPOINT, Some(RateCategory::Audit)), + (oidc::TOKEN, Some(RateCategory::Token)), + (oidc::PAR, Some(RateCategory::Token)), + (oidc::USERINFO, Some(RateCategory::UserInfo)), + (oidc::LOGOUT, Some(RateCategory::Login)), + (oidc::AUTHORIZE, Some(RateCategory::Login)), + (oidc::AUTHORIZE_RESUME, Some(RateCategory::Login)), + (passkey::LIST, Some(RateCategory::Account)), + (federation::IDENTITIES, Some(RateCategory::Account)), + (passkey::AUTHENTICATE_START, Some(RateCategory::Login)), + (federation::CALLBACK, Some(RateCategory::Login)), + ] { + assert_eq!(Endpoint::classify(path).rate_category(), budget, "{path}"); + } + // The root and a page's path ending in a slash only redirect to a page. + let redirects = page::ALL.map(|path| format!("{path}/")); + for path in page::ALL + .into_iter() + .chain([page::ROOT]) + .chain(redirects.iter().map(String::as_str)) + { + assert_eq!( + Endpoint::classify(path).rate_category(), + Some(RateCategory::Page), + "{path}" + ); + } +} + +/// A request is classified by the route it matched, so the pages of an app, whose +/// path names it, and their twins ending in a slash are pages. A request no route +/// matched is classified by its path. +#[tokio::test] +async fn requests_are_classified_by_their_route() { + // Answers whether the request is a page's. + let classified = || { + any(|request: Request| async move { + if Endpoint::of(&request).rate_category() == Some(RateCategory::Page) { + StatusCode::ACCEPTED + } else { + StatusCode::NO_CONTENT + } + }) + }; + let router = page::ALL + .into_iter() + .fold(Router::new(), |router, path| { + router + .route(path, classified()) + .route(&format!("{path}/"), classified()) + }) + .fallback(classified()); + for (path, status) in [ + ("/developers/clients/c_any", StatusCode::ACCEPTED), + ("/developers/clients/c_any/settings", StatusCode::ACCEPTED), + ("/developers/clients/c_any/secrets/", StatusCode::ACCEPTED), + ( + "/developers/clients/c_any/elsewhere", + StatusCode::NO_CONTENT, + ), + ] { + let request = HttpRequest::get(path).body(Body::empty()).expect("request"); + let response = router.clone().oneshot(request).await.expect("response"); + assert_eq!(response.status(), status, "{path}"); + } +} diff --git a/apps/auth-service/src/security/tests/sessions.rs b/apps/auth-service/src/security/tests/sessions.rs new file mode 100644 index 000000000..164930498 --- /dev/null +++ b/apps/auth-service/src/security/tests/sessions.rs @@ -0,0 +1,198 @@ +//! Session lookup, passkey confirmation age and session locking against logout. + +use super::*; +use piquel_common::{Handle, TokenId}; +use piquel_crypto::Secret; +use piquel_repository::{InsertSession, InsertUser}; + +/// A session lookup failure stays a server error rather than becoming an anonymous session. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn optional_session_preserves_database_failure_instead_of_reporting_signed_out() { + // The timeout also bounds the first connection, so it leaves room for + // connecting while other database tests run. + let database = SecurityFixture::database(1, std::time::Duration::from_secs(1)).await; + // Exhaust only this test's private pool; the database and all other tests + // remain usable. A well-formed session cookie must trigger a real lookup. + let transaction = database.begin().await.expect("hold sole connection"); + assert!( + Session::optional(&database, &HeaderMap::new()) + .await + .expect("no cookie requires no lookup") + .is_none() + ); + let mut headers = HeaderMap::new(); + headers.insert( + header::COOKIE, + HeaderValue::from_str(&format!( + "__Host-piquel_session={}", + Secret::generate().expect("browser secret").encoded() + )) + .expect("cookie"), + ); + let error = Session::optional(&database, &headers) + .await + .expect_err("database timeout must propagate"); + assert_eq!( + ApiError::from(error).into_response().status(), + StatusCode::INTERNAL_SERVER_ERROR + ); + transaction.rollback().await.expect("release connection"); +} + +/// A confirmation counts from its own timestamp, against each action's maximum age. +#[test] +fn confirmation_age_is_fixed_from_its_timestamp() { + let session = |age: Option| { + let now = Utc::now(); + StoredSession { + id: SessionId::new(), + user_id: UserId::new(), + authentication_methods: vec![AuthenticationMethod::Passkey], + authenticated_at: now - Duration::days(1), + expires_at: now + Duration::days(1), + last_seen_at: now, + revoked_at: None, + passkey_confirmed_at: age.map(|age| now - Duration::seconds(age)), + user_agent_family: None, + last_seen_ip: None, + } + }; + assert!(Confirmed::::check(&session(Some(290))).is_ok()); + for age in [None, Some(310), Some(86_400)] { + assert!(matches!( + Confirmed::::check(&session(age)), + Err(SessionError::StepUpRequired { + max_age: CONFIRMATION_MAX_AGE + }) + )); + } + assert!(matches!( + Confirmed::<60>::check(&session(Some(90))), + Err(SessionError::StepUpRequired { max_age: 60 }) + )); +} + +/// A confirmed change holds the session row, so a racing logout waits for it, and a +/// change after logout fails. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn confirmed_changes_serialize_with_logout() { + let database = SecurityFixture::database(5, std::time::Duration::from_secs(5)).await; + database.run_migrations().await.expect("migrations"); + let user_id = UserId::new(); + let mut tx = database.begin().await.expect("transaction"); + tx.users() + .insert(&InsertUser { + id: user_id, + handle: Handle::parse(&format!("lock-{}", &TokenId::new().to_string()[24..])) + .expect("handle"), + display_name: "Lock test".into(), + }) + .await + .expect("user"); + let secret = Session::create( + &mut tx, + RequestContext::TEST, + user_id, + AuthenticationMethod::Passkey.into(), + ) + .await + .expect("session"); + tx.commit().await.expect("commit"); + let session = database + .sessions() + .find_active_by_browser_secret(secret.digest().as_bytes()) + .await + .expect("lookup") + .expect("session"); + let id = session.id; + let mut change = database.begin().await.expect("change transaction"); + let locked = Session::lock(&mut change, &session).await.expect("lock"); + ::check(&locked).expect("passkey sign-in confirms"); + let logout = tokio::spawn({ + let database = database.clone(); + async move { + let context = RequestContext::TEST.actor(Actor::User { + user_id, + session_id: Some(id), + }); + let mut logout = database.begin().await?; + let revoked = logout + .revoke_sessions( + &context, + user_id, + SessionScope::One(id), + &RevocationReason::Logout, + ) + .await?; + logout.commit().await.map(|()| revoked) + } + }); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + assert!(!logout.is_finished(), "logout must wait for the change"); + change.commit().await.expect("commit change"); + assert_eq!(logout.await.expect("logout task").expect("logout"), [id]); + let mut change = database.begin().await.expect("change transaction"); + assert!(matches!( + Session::lock(&mut change, &session).await, + Err(SessionError::Missing) + )); +} + +/// A session that expires while a change waits for the account lock is rejected once +/// the lock is acquired, even though the lookup compares with the transaction's start. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn session_lock_rechecks_expiry_after_waiting() { + let database = SecurityFixture::database(5, std::time::Duration::from_secs(5)).await; + database.run_migrations().await.expect("migrations"); + let user_id = UserId::new(); + let now = Utc::now(); + let mut tx = database.begin().await.expect("transaction"); + tx.users() + .insert(&InsertUser { + id: user_id, + handle: Handle::parse(&format!("lock-{}", &TokenId::new().to_string()[24..])) + .expect("handle"), + display_name: "Lock test".into(), + }) + .await + .expect("user"); + let session = tx + .sessions() + .insert(&InsertSession { + id: SessionId::new(), + user_id, + authentication_methods: vec![AuthenticationMethod::Passkey], + authenticated_at: now, + expires_at: now + Duration::seconds(1), + user_agent_family: RequestContext::TEST.user_agent_family, + ip: RequestContext::TEST.client_ip, + passkey_confirmed_at: Some(now), + passkey_id: None, + }) + .await + .expect("session"); + tx.commit().await.expect("commit"); + let mut holder = database.begin().await.expect("holder transaction"); + holder + .users() + .find_active_by_id_for_update(user_id) + .await + .expect("account lock") + .expect("active account"); + let change = tokio::spawn({ + let database = database.clone(); + async move { + let mut change = database.begin().await.expect("change transaction"); + Session::lock(&mut change, &session).await.map(drop) + } + }); + tokio::time::sleep(std::time::Duration::from_millis(1500)).await; + holder.rollback().await.expect("release account"); + assert!(matches!( + change.await.expect("change task"), + Err(SessionError::Missing) + )); +} diff --git a/docs/architecture/federation-providers.md b/docs/architecture/federation-providers.md index 4ea5d30ad..99e970fb3 100644 --- a/docs/architecture/federation-providers.md +++ b/docs/architecture/federation-providers.md @@ -107,11 +107,11 @@ provider by that name, so they need no other change. ## 7. Test it -Add tests to `apps/auth-service/src/federation/tests.rs`, serving the provider's -endpoints from a local mock (see the GitHub fixture in `TestApp` and the Google -mock test). Cover the evidence the provider must reject, such as a wrong -audience, a wrong nonce, an expired token or a bad signature, not only the -successful sign-in. +Add tests to `apps/auth-service/src/federation/tests/protocols.rs`, serving the +provider's endpoints from a local mock (see the GitHub fixture in `TestApp`, in +`tests/mod.rs`, and the Google mock test). Cover the evidence the provider must +reject, such as a wrong audience, a wrong nonce, an expired token or a bad +signature, not only the successful sign-in. ## 8. Register and enable it diff --git a/docs/architecture/telemetry.md b/docs/architecture/telemetry.md index f320acdf4..8a83c3553 100644 --- a/docs/architecture/telemetry.md +++ b/docs/architecture/telemetry.md @@ -92,7 +92,7 @@ under their own retention rules. User IDs are pseudonymous, so they are allowed on spans and log lines. The collector also deletes `url.query`, `url.full`, `client.address` and `http.*.header.*` attributes, as a second line of defense. -`passkey::tests::telemetry_exports_no_secret_of_a_sign_in_and_code_exchange` +`passkey::tests::telemetry::telemetry_exports_no_secret_of_a_sign_in_and_code_exchange` runs a passkey sign-in and a code exchange through the production layers, with `Telemetry::capture`, and fails if any of their secrets is exported. Extend it when a flow handles a new kind of secret. diff --git a/docs/security/account-recovery.md b/docs/security/account-recovery.md index 477705b28..89b2854b0 100644 --- a/docs/security/account-recovery.md +++ b/docs/security/account-recovery.md @@ -41,7 +41,7 @@ undo), `AdminService::recover_account`, `recent_recoveries` and `undo_recovery` `crates/ui/src/recovery.rs`), migration `0019_account_recoveries`, the CLI's `user recover` and `user undo-recovery`, and the dashboard's Recover and Undo recovery pages (`apps/auth-service/src/web/admin/users.rs`). Tests named below -live in `apps/auth-service/src/recovery/tests.rs` unless another file is given; +live in `apps/auth-service/src/recovery/tests/` unless another file is given; `crates/database/tests/recoveries.rs` is shortened to `db:`. ## States @@ -115,7 +115,7 @@ link is only mailed, so `--revoke` stays at the terminal. recovery can be undone, with no override. Granted during a probation, they would go live for whoever used the link once it settles (`what_a_start_replaces_and_refuses`, - `admin::tests::no_grant_while_a_recovery_can_be_undone`, + `admin::tests::administrators::no_grant_while_a_recovery_can_be_undone`, `db: no_grant_while_a_recovery_can_be_undone`). ## The link @@ -237,7 +237,7 @@ link is only mailed, so `--revoke` stays at the terminal. answers the client `unmet_authentication_requirements` (OpenID Connect Unmet Authentication Requirements 1.0). A social sign-in, which a passkey could still step up, goes to sign in as before - (`oidc::tests::a_probation_sign_in_short_of_the_target_answers_the_client`). + (`oidc::tests::step_up::a_probation_sign_in_short_of_the_target_answers_the_client`). `Acr::select`'s documentation says an account may not reach every class. - **P5.** Probation lasts 15 days. A session lasts up to 30, so the session the link signed in can outlive it: it stays unconfirmed until the recovery's passkey @@ -303,8 +303,8 @@ on a disabled account (U4a) which carries no credential to sign in with, while sign-in and confirmation still refuse a disabled account. A disable written by a release older than this one doesn't change that (`the_owner_undoes_a_disabled_accounts_recovery`, - `passkey::tests::only_an_undo_accepts_a_disabled_accounts_passkey`). Disabling - still cancels an unused link (`what_a_start_replaces_and_refuses`). + `passkey::tests::validation::only_an_undo_accepts_a_disabled_accounts_passkey`). + Disabling still cancels an unused link (`what_a_start_replaces_and_refuses`). - **U5.** Support undoes for an owner with no passkey left from before it, or whose account is disabled: `auth-service user undo-recovery --reason "…"`, or the dashboard's Undo recovery page. It is the same U2 or U3, recorded @@ -313,7 +313,7 @@ on a disabled account (U4a) restores nothing it revoked (`support_undoes_and_takes_the_last_passkey`). - **U6.** A consent, code exchange or refresh that waited for the account lock while an undo ran doesn't survive it: each re-reads its session under the lock - (`oidc::tests::a_consent_whose_session_ended_while_waiting_is_not_saved`, and + (`oidc::tests::authorization::a_consent_whose_session_ended_while_waiting_is_not_saved`, and the code exchange's and rotation's own session checks). What undo doesn't reach: what the link holder did inside apps that don't ask for From 0b75a5aa6dc049c3287ef997169405e695e9b27e Mon Sep 17 00:00:00 2001 From: piquel Date: Wed, 4 Nov 2026 11:58:31 +0100 Subject: [PATCH 3/3] docs: paths follow the moved modules, and the test layout rule is written down Co-Authored-By: Claude Opus 5.5 --- docs/architecture/rust-conventions.md | 9 +++++++-- docs/security/account-recovery.md | 2 +- infra/README.md | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/architecture/rust-conventions.md b/docs/architecture/rust-conventions.md index 9a3c1d2fa..75e77abe5 100644 --- a/docs/architecture/rust-conventions.md +++ b/docs/architecture/rust-conventions.md @@ -263,8 +263,8 @@ owner operation looks the client up as the owner's first, so any other client is not found, and nothing checks ownership again. Clients are read from the database on each request and nothing is cached, so changes apply at once on every replica. -Periodic work implements `ExclusiveJob` in `apps/auth-service/src/jobs.rs`, and -`Jobs::start` schedules it. A job receives only its locked `ExclusiveConnection`, +Periodic work implements `ExclusiveJob` in `apps/auth-service/src/jobs/mod.rs`, +and `Jobs::start` schedules it. A job receives only its locked `ExclusiveConnection`, never the `Database`, so everything it does happens while it holds the lock. Messages for other systems are never sent from handlers: the event's channels queue them, and delivery workers send them. See [the delivery queue](delivery-queue.md). @@ -321,3 +321,8 @@ security reasoning, protocol quirks, ordering and locking where they are not obv Keep documentation current. Tests should cover meaningful logic and boundaries; avoid repeated smoke tests. Run checks relevant to changed code while iterating, then the required workspace checks before handing over an integration change. + +Unit tests live in `#[cfg(test)] mod tests;` with a sibling `tests.rs`, so a +module with tests is `foo/mod.rs` and `foo/tests.rs`. A test block of 30 lines or +fewer may stay inline. A test file that outgrows one read becomes a `tests/` +directory: `tests/mod.rs` holds the shared fixtures, and each flow gets a file. diff --git a/docs/security/account-recovery.md b/docs/security/account-recovery.md index 89b2854b0..13c064c86 100644 --- a/docs/security/account-recovery.md +++ b/docs/security/account-recovery.md @@ -38,7 +38,7 @@ undo), `AdminService::recover_account`, `recent_recoveries` and `undo_recovery` (`apps/auth-service/src/admin/service.rs`), the passkey routes (`apps/auth-service/src/passkey`), the pages `/recover` and `/recover/undo` (`apps/auth-service/src/web/auth/recovery`, with their views in -`crates/ui/src/recovery.rs`), migration `0019_account_recoveries`, the CLI's +`crates/ui/src/recovery/mod.rs`), migration `0019_account_recoveries`, the CLI's `user recover` and `user undo-recovery`, and the dashboard's Recover and Undo recovery pages (`apps/auth-service/src/web/admin/users.rs`). Tests named below live in `apps/auth-service/src/recovery/tests/` unless another file is given; diff --git a/infra/README.md b/infra/README.md index c9df077ac..f8bdfb0a3 100644 --- a/infra/README.md +++ b/infra/README.md @@ -221,7 +221,7 @@ removes the restart gap after a crash; it adds no capacity. clients, and the public-client origins CORS allows, are read from the database on each request, so a client change reaches every replica at once. - **Background work.** Jobs run through one runner - (`apps/auth-service/src/jobs.rs`). An exclusive job, such as expired-state + (`apps/auth-service/src/jobs/mod.rs`). An exclusive job, such as expired-state cleanup or the purge of deleted accounts, each every five minutes, or audit sealing every five seconds, holds a PostgreSQL advisory lock while it runs, so one replica at a time runs it and the others skip that run. A run that fails