diff --git a/apps/auth-service/src/audit/sealer.rs b/apps/auth-service/src/audit/sealer.rs index fcbc55ab6..86957632c 100644 --- a/apps/auth-service/src/audit/sealer.rs +++ b/apps/auth-service/src/audit/sealer.rs @@ -13,9 +13,7 @@ use sourceorigin_common::{ events::{EventContext, JobName}, }; use sourceorigin_crypto::NoteKey; -use sourceorigin_repository::{ - ChainLink, Checkpoint, EventContent, ExclusiveConnection, LockKey, SealedEvent, -}; +use sourceorigin_repository::{ChainLink, Checkpoint, ExclusiveConnection, LockKey, SealedEvent}; use sourceorigin_telemetry::Counter; use std::{ sync::{Arc, Mutex, PoisonError}, @@ -44,8 +42,6 @@ pub(crate) struct Sealer { checkpoint_every: TimeDelta, /// Events sealed per transaction. batch: u32, - /// The canonical format events are sealed in. - format: i16, /// When an attempt to sign a checkpoint last ended in failure. The next try /// waits as long as the interval, so a broken chain is not recomputed on /// every pass. @@ -54,21 +50,19 @@ pub(crate) struct Sealer { impl Sealer { /// Events sealed per transaction in production: few enough that a batch of - /// the largest events migration 0035 allows still fits in memory. + /// the largest events the schema allows still fits in memory. const BATCH: u32 = 100; /// The least time between two checkpoints in production. const CHECKPOINT_EVERY: TimeDelta = TimeDelta::minutes(5); /// A sealer signing with `audit`'s key, and building only on checkpoints its - /// keys verify. It seals in [`EventContent::NEWEST_FORMAT`], which the release - /// before this one verifies too. + /// keys verify. pub(crate) fn new(audit: &AuditConfig) -> Self { Self { key: audit.key.clone(), keys: audit.keys.clone(), checkpoint_every: Self::CHECKPOINT_EVERY, batch: Self::BATCH, - format: EventContent::NEWEST_FORMAT, failed_at: Mutex::new(None), } } @@ -91,14 +85,10 @@ impl Sealer { } } - /// This sealer, sealing `batch` events per transaction, in `format`, for tests. + /// This sealer, sealing `batch` events per transaction, for tests. #[cfg(test)] - pub(crate) fn sealing(self, batch: u32, format: i16) -> Self { - Self { - batch, - format, - ..self - } + pub(crate) fn sealing(self, batch: u32) -> Self { + Self { batch, ..self } } /// Seals up to [`Self::batch`] events after the head in one transaction, and @@ -113,7 +103,7 @@ impl Sealer { let mut tx = connection.begin().await?; let mut head = tx.audit().head().await?.unwrap_or(ChainLink::GENESIS); let mut sealed = Vec::new(); - for content in tx.audit().unsealed(self.batch, self.format).await? { + for content in tx.audit().unsealed(self.batch).await? { head = head.extend(&content)?; sealed.push(SealedEvent { link: head, diff --git a/apps/auth-service/src/audit/tests.rs b/apps/auth-service/src/audit/tests.rs index f8845b84c..fe5a466e4 100644 --- a/apps/auth-service/src/audit/tests.rs +++ b/apps/auth-service/src/audit/tests.rs @@ -1046,7 +1046,7 @@ async fn sealing_goes_on_when_a_checkpoint_fails() { let refused = fixture.sealer.pass(&mut lock, None).await; assert!(matches!(refused, Err(AuditError::Broken(_))), "{refused:?}"); fixture.seal_with(&mut lock).await; - fixture.sealer = fixture.sealer.sealing(2, EventContent::UNTAGGED); + fixture.sealer = fixture.sealer.sealing(2); let database = fixture.database.clone(); let mut tx = database.begin().await.expect("transaction"); for _ in 0..5 { @@ -1139,7 +1139,7 @@ async fn a_failed_checkpoint_is_retried_after_the_interval() { #[ignore = "requires TEST_DATABASE_URL"] async fn checkpoints_keep_their_interval_while_batches_stay_full() { let mut fixture = Fixture::new().await; - fixture.sealer = fixture.sealer.sealing(2, EventContent::UNTAGGED); + fixture.sealer = fixture.sealer.sealing(2); // One transaction, so all five become ready to seal at once. let database = fixture.database.clone(); let mut tx = database.begin().await.expect("transaction"); @@ -1173,29 +1173,17 @@ async fn checkpoints_keep_their_interval_while_batches_stay_full() { ); } -/// Auth seals format 2, which names itself in the canonical form, and events -/// sealed before in the untagged format keep hashing without it; one chain holds -/// both and verifies. +/// Auth seals in its newest format, which the canonical event names, so a later +/// format can add a field without breaking the hashes of events sealed before it. #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] -async fn the_chain_format_is_per_event() { +async fn the_canonical_event_names_its_format() { let mut fixture = Fixture::new().await; - let sealer = std::mem::replace( - &mut fixture.sealer, - Sealer::eager(&fixture.audit).sealing(1_000, EventContent::UNTAGGED), - ); - fixture.record(1).await; - fixture.seal().await; - fixture.sealer = sealer; fixture.record(1).await; fixture.seal().await; let chain = fixture.database.audit().chain(0, 10).await.expect("chain"); - let canonical = chain - .iter() - .map(|event| serde_json::to_value(&event.sealed.content).expect("content")) - .collect::>(); - assert_eq!(canonical[0].get("format"), None); - assert_eq!(canonical[1]["format"], 2); + let canonical = serde_json::to_value(&chain[0].sealed.content).expect("content"); + assert_eq!(canonical["format"], EventContent::NEWEST_FORMAT); assert_eq!(fixture.verify().await.broken, None); } diff --git a/apps/auth-service/src/audit/verify.rs b/apps/auth-service/src/audit/verify.rs index 620ae6058..4d24463d4 100644 --- a/apps/auth-service/src/audit/verify.rs +++ b/apps/auth-service/src/audit/verify.rs @@ -134,8 +134,8 @@ impl AuditKeys { } impl AuditChain { - /// Rows read per query: few enough that a page of the largest events migration - /// 0035 allows still fits in memory. + /// Rows read per query: few enough that a page of the largest events the + /// schema allows still fits in memory. const BATCH: u32 = 100; /// Checkpoints per [`AuditPage`]. const PAGE: u32 = 100; diff --git a/apps/auth-service/src/cli/audit.rs b/apps/auth-service/src/cli/audit.rs index a2920135c..0ea57889c 100644 --- a/apps/auth-service/src/cli/audit.rs +++ b/apps/auth-service/src/cli/audit.rs @@ -208,7 +208,6 @@ impl ListEvents { Ok(Actor::Client { client_id }) => format!("client {client_id}"), Ok(Actor::System { job }) => format!("job {job:?}"), Ok(Actor::Anonymous) => "anonymous".to_owned(), - Ok(Actor::Unrecorded) => "unrecorded".to_owned(), Err(_) => event.actor.to_string(), } } diff --git a/apps/auth-service/src/cli/keys.rs b/apps/auth-service/src/cli/keys.rs index ee9931a9d..8d1118069 100644 --- a/apps/auth-service/src/cli/keys.rs +++ b/apps/auth-service/src/cli/keys.rs @@ -191,7 +191,7 @@ impl KeysCommand { .await? .into_iter() .map(|usage| KeyUsage { - key: keys.name(usage.digest_key.as_deref()), + key: keys.name(&usage.digest_key), usage, }) .collect(); @@ -243,7 +243,7 @@ struct KeyUsage { /// The count. #[serde(flatten)] usage: DigestUsage, - /// `current`, `accepted`, `unrecorded` or `unknown`. + /// `current`, `accepted` or `unknown`. key: &'static str, } @@ -256,7 +256,7 @@ report!([KeyUsage], self, out, { [ Cell::new(usage.secret), Cell::new(key), - usage.digest_key.as_deref().into(), + usage.digest_key.as_str().into(), usage.stored.into(), ] }), diff --git a/apps/auth-service/src/config/keys.rs b/apps/auth-service/src/config/keys.rs index 3c28df50e..18cc42fbd 100644 --- a/apps/auth-service/src/config/keys.rs +++ b/apps/auth-service/src/config/keys.rs @@ -326,13 +326,10 @@ impl TokenDigestKeys { .collect() } - /// Names the key a stored fingerprint belongs to: `current`, `accepted`, - /// `unrecorded` for digests made before fingerprints were stored, or `unknown`. + /// Names the key a stored fingerprint belongs to: `current`, `accepted` or + /// `unknown`. #[must_use] - pub fn name(&self, fingerprint: Option<&str>) -> &'static str { - let Some(fingerprint) = fingerprint else { - return "unrecorded"; - }; + pub fn name(&self, fingerprint: &str) -> &'static str { if fingerprint == self.current.fingerprint { "current" } else if self diff --git a/apps/auth-service/src/history/mod.rs b/apps/auth-service/src/history/mod.rs index 8d62233eb..fa3bb94f8 100644 --- a/apps/auth-service/src/history/mod.rs +++ b/apps/auth-service/src/history/mod.rs @@ -209,7 +209,7 @@ impl Activity { /// feed agree, as far as a count by kind can: a refresh grant's revocation /// is left out, since the history shows only a replay's, and a session's /// expiry is counted, since the history hides only that reason. - const SECURITY: [&'static str; 32] = [ + const SECURITY: [&'static str; 31] = [ "account_created", "signed_in", "session_revoked", @@ -241,7 +241,6 @@ impl Activity { "account_deletion_scheduled", "account_restored", "compromise_reported", - "imported", ]; } diff --git a/apps/auth-service/src/recovery/mod.rs b/apps/auth-service/src/recovery/mod.rs index f08385037..817988166 100644 --- a/apps/auth-service/src/recovery/mod.rs +++ b/apps/auth-service/src/recovery/mod.rs @@ -22,8 +22,8 @@ //! unused or its probation running, no passkey but its own is removed, by anyone, so nothing takes that ability away //! ([`AccountService::refuse_mid_recovery`]). Support undoes for an owner with //! none (`AdminService::undo_recovery`). The database backs the probation and -//! that rule for every writer, an older release included: see migration -//! `0019_account_recoveries`. +//! that rule for every writer, whatever it is granted: see the account +//! recoveries section of the initial migration. /// Recovery failures and their browser response mapping. mod error; diff --git a/apps/auth-service/src/recovery/tests/undo.rs b/apps/auth-service/src/recovery/tests/undo.rs index 1d1d1f6a4..fb6bfd2fe 100644 --- a/apps/auth-service/src/recovery/tests/undo.rs +++ b/apps/auth-service/src/recovery/tests/undo.rs @@ -317,8 +317,7 @@ async fn the_owner_undoes_a_disabled_accounts_recovery() { .keys .start("/webauthn/authenticate/start", "", body) .await; - // Written as a release older than this one would, which knows nothing of - // recoveries. + // Written directly, as a code path that knows nothing of recoveries would. let disabled = scenario .database() .users() diff --git a/crates/common/src/admin.rs b/crates/common/src/admin.rs index 64af9d459..695486f38 100644 --- a/crates/common/src/admin.rs +++ b/crates/common/src/admin.rs @@ -1020,7 +1020,7 @@ pub struct SigningKey { pub key_type: SigningKeyType, /// Where it is in its lifecycle. pub state: SigningKeyState, - /// When it was generated or imported. + /// When it was generated. pub created_at: DateTime, /// When it started signing. pub activated_at: Option>, diff --git a/crates/common/src/events/context.rs b/crates/common/src/events/context.rs index b3045fe19..b59b93173 100644 --- a/crates/common/src/events/context.rs +++ b/crates/common/src/events/context.rs @@ -46,8 +46,6 @@ pub enum Actor { }, /// An unauthenticated browser, e.g. one failing to sign in. Anonymous, - /// Unknown: imported audit rows never recorded who acted. - Unrecorded, } impl Actor { @@ -60,8 +58,7 @@ impl Actor { | Self::Admin { .. } | Self::Cli { .. } | Self::System { .. } - | Self::Anonymous - | Self::Unrecorded => None, + | Self::Anonymous => None, } } @@ -71,11 +68,7 @@ impl Actor { match self { Self::User { session_id, .. } => *session_id, Self::Admin { session_id, .. } => Some(*session_id), - Self::Cli { .. } - | Self::Client { .. } - | Self::System { .. } - | Self::Anonymous - | Self::Unrecorded => None, + Self::Cli { .. } | Self::Client { .. } | Self::System { .. } | Self::Anonymous => None, } } } diff --git a/crates/common/src/events/history.rs b/crates/common/src/events/history.rs index b98279625..aace93727 100644 --- a/crates/common/src/events/history.rs +++ b/crates/common/src/events/history.rs @@ -129,10 +129,6 @@ impl DomainEvent { purge_after: *purge_after, }, Self::AccountRestored {} => HistoryEntry::AccountRestored, - Self::Imported(audit) => HistoryEntry::Legacy { - action: audit.action.clone(), - outcome: audit.outcome.clone(), - }, Self::SignInFailed { .. } | Self::PasskeyConfirmed { .. } | Self::GrantIssued { .. } @@ -389,14 +385,6 @@ pub enum HistoryEntry { /// The account was restored before its deletion. #[serde(rename = "account.restored")] AccountRestored, - /// A row of the audit log that preceded typed events. - #[serde(rename = "legacy")] - Legacy { - /// The logged action, e.g. `passkey.login`. - action: String, - /// `success`, `failure` or `rejected`. - outcome: String, - }, } } @@ -445,8 +433,7 @@ impl HistoryEntry { | Self::SignedOutEverywhere | Self::NotificationPreferenceChanged(_) | Self::DeletionScheduled { .. } - | Self::AccountRestored - | Self::Legacy { .. } => true, + | Self::AccountRestored => true, } } @@ -498,8 +485,7 @@ impl HistoryEntry { | Self::SignedOutEverywhere | Self::NotificationPreferenceChanged(_) | Self::DeletionScheduled { .. } - | Self::AccountRestored - | Self::Legacy { .. } => None, + | Self::AccountRestored => None, } } } @@ -542,8 +528,6 @@ crate::str_enum! { System = "system", /// An unauthenticated browser. Anonymous = "anonymous", - /// Unknown: imported audit rows never recorded who acted. - Unrecorded = "unrecorded", } } @@ -557,7 +541,6 @@ impl From<&Actor> for HistoryActor { Actor::Client { .. } => Self::Client, Actor::System { .. } => Self::System, Actor::Anonymous => Self::Anonymous, - Actor::Unrecorded => Self::Unrecorded, } } } diff --git a/crates/common/src/events/mod.rs b/crates/common/src/events/mod.rs index ac1aaf85e..74a48529c 100644 --- a/crates/common/src/events/mod.rs +++ b/crates/common/src/events/mod.rs @@ -20,8 +20,8 @@ pub use context::{ }; pub use history::{FollowUp, HistoryActor, HistoryEntry}; pub use payload::{ - CodeRedemptionFailure, GrantRevocation, ImportedAudit, InlineSignIn, RecordedOrigin, - RecoveryRevocation, RevocationReason, SignInFailure, SigningKeyChange, + CodeRedemptionFailure, GrantRevocation, InlineSignIn, RecordedOrigin, RecoveryRevocation, + RevocationReason, SignInFailure, SigningKeyChange, }; use crate::{ @@ -505,9 +505,6 @@ pub enum DomainEvent { /// The owner turned a category of notifications' email on or off, in their /// settings or with an email's unsubscribe link. NotificationPreferenceChanged(NotificationPreference), - /// A row of the security audit log that preceded typed events. Only - /// migrations write these; its fields are private, so one is only ever read back. - Imported(ImportedAudit), } impl DomainEvent { @@ -623,8 +620,7 @@ impl DomainEvent { | Self::AlertRaised { .. } | Self::AlertUpdated { .. } | Self::AlertCleared { .. } - | Self::NotificationPreferenceChanged(_) - | Self::Imported(_) => None, + | Self::NotificationPreferenceChanged(_) => None, } } @@ -699,8 +695,7 @@ impl DomainEvent { | Self::AlertRaised { .. } | Self::AlertUpdated { .. } | Self::AlertCleared { .. } - | Self::NotificationPreferenceChanged(_) - | Self::Imported(_) => None, + | Self::NotificationPreferenceChanged(_) => None, } } @@ -776,7 +771,6 @@ impl DomainEvent { Self::AlertUpdated { .. } => "alert_updated", Self::AlertCleared { .. } => "alert_cleared", Self::NotificationPreferenceChanged(_) => "notification_preference_changed", - Self::Imported(_) => "imported", } } } @@ -789,7 +783,6 @@ impl SigningKeyChange { pub const fn version(self) -> i16 { match self { Self::Generated - | Self::Imported | Self::Activated | Self::Retiring | Self::Retired diff --git a/crates/common/src/events/payload.rs b/crates/common/src/events/payload.rs index f980593a7..afcda928d 100644 --- a/crates/common/src/events/payload.rs +++ b/crates/common/src/events/payload.rs @@ -1,10 +1,9 @@ //! The values event payloads carry beside IDs: how a sign-in, revocation or -//! recovery went, the origins they name, and imported audit rows. +//! recovery went, and the origins they name. use super::DomainEvent; use crate::{ClientId, PasskeyId, Personal, clients::RelatedOrigin}; use serde::{Deserialize, Serialize}; -use serde_json::Value; /// What a recovery started with `--revoke` revoked and kept: every passkey the /// owner did not vouch for went, and the kept ones can still undo it. @@ -156,9 +155,6 @@ crate::str_enum! { /// A key was generated: published as `next`, or signing at once when no /// key signed or the key it replaces was revoked. Generated = "generated", - /// A key was imported from the deployment's PEM key, signing at once. - /// Only earlier releases imported keys; this one reads their events. - Imported = "imported", /// A `next` key started signing. Activated = "activated", /// A key stopped signing; it stays published for tokens it signed. @@ -174,34 +170,3 @@ crate::str_enum! { Rewrapped = "rewrapped", } } - -/// A security audit log row, kept verbatim by the migrations to typed events. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ImportedAudit { - /// The logged action, e.g. `passkey.login`. - pub(super) action: String, - /// `success`, `failure` or `rejected`. - pub(super) outcome: String, - /// The logged metadata, e.g. `{"provider": "github"}`. - metadata: Value, -} - -impl ImportedAudit { - /// The logged action, e.g. `passkey.login`. - #[must_use] - pub fn action(&self) -> &str { - &self.action - } - - /// `success`, `failure` or `rejected`. - #[must_use] - pub fn outcome(&self) -> &str { - &self.outcome - } - - /// The logged metadata, e.g. `{"provider": "github"}`. - #[must_use] - pub const fn metadata(&self) -> &Value { - &self.metadata - } -} diff --git a/crates/common/src/notifications/mod.rs b/crates/common/src/notifications/mod.rs index dd1bd2bc9..4088e8a47 100644 --- a/crates/common/src/notifications/mod.rs +++ b/crates/common/src/notifications/mod.rs @@ -317,8 +317,7 @@ impl DomainEvent { // Administrators follow an alert on the dashboard's Alerts tab, or // with `auth-service alerts list`, once it is raised. | Self::AlertUpdated { .. } - | Self::AlertCleared { .. } - | Self::Imported(_) => return None, + | Self::AlertCleared { .. } => return None, }) } } diff --git a/crates/common/src/tests.rs b/crates/common/src/tests.rs index a901d9c4b..c35b7cf94 100644 --- a/crates/common/src/tests.rs +++ b/crates/common/src/tests.rs @@ -101,7 +101,6 @@ fn event_kinds_match_their_serde_tags() { SigningKeyChange, }; use serde::Deserialize; - use serde_json::json; /// Captures the variant names serde expects when it reads an unknown tag. #[derive(Debug)] @@ -129,10 +128,6 @@ fn event_kinds_match_their_serde_tags() { position: 1, problem: admin::ChainProblem::EventChanged, }); - let imported = serde_json::from_value(json!({ - "action": "passkey.login", "outcome": "success", "metadata": {} - })) - .expect("imported audit row"); let events = [ DomainEvent::AccountCreated { method: AuthenticationMethod::Passkey, @@ -356,7 +351,6 @@ fn event_kinds_match_their_serde_tags() { category: crate::notifications::EmailCategory::Announcements, email: false, }), - DomainEvent::Imported(imported), ]; let mut kinds: Vec<&str> = events.iter().map(DomainEvent::kind).collect(); for event in events { diff --git a/crates/database/.sqlx/query-8eb59f8b76139a0f4f0ffa381ee1b688a62e2b78f3e10f436d5a1b1172b529b2.json b/crates/database/.sqlx/query-494455c0e245ebe29680a5658e7653c1f91ec55aa6979046f1005949e0141013.json similarity index 52% rename from crates/database/.sqlx/query-8eb59f8b76139a0f4f0ffa381ee1b688a62e2b78f3e10f436d5a1b1172b529b2.json rename to crates/database/.sqlx/query-494455c0e245ebe29680a5658e7653c1f91ec55aa6979046f1005949e0141013.json index 5f6776fe5..cd01320f5 100644 --- a/crates/database/.sqlx/query-8eb59f8b76139a0f4f0ffa381ee1b688a62e2b78f3e10f436d5a1b1172b529b2.json +++ b/crates/database/.sqlx/query-494455c0e245ebe29680a5658e7653c1f91ec55aa6979046f1005949e0141013.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO domain_events (\n id, kind, version, payload, actor, chain_position, chain_hash\n )\n SELECT $2, 'imported', 1, '{}', '{\"type\": \"unrecorded\"}', $1::bigint, chain_hash\n FROM domain_events WHERE chain_position = $1::bigint + 1", + "query": "INSERT INTO domain_events (\n id, kind, version, payload, actor, chain_position, chain_hash\n )\n SELECT $2, 'forged', 1, '{}', '{\"type\": \"anonymous\"}', $1::bigint, chain_hash\n FROM domain_events WHERE chain_position = $1::bigint + 1", "describe": { "columns": [], "parameters": { @@ -11,5 +11,5 @@ }, "nullable": [] }, - "hash": "8eb59f8b76139a0f4f0ffa381ee1b688a62e2b78f3e10f436d5a1b1172b529b2" + "hash": "494455c0e245ebe29680a5658e7653c1f91ec55aa6979046f1005949e0141013" } diff --git a/crates/database/.sqlx/query-564e9b1ce7cb468f78cb854239c5448fe3f4cc7d5870dbbbc7bcf40788919844.json b/crates/database/.sqlx/query-564e9b1ce7cb468f78cb854239c5448fe3f4cc7d5870dbbbc7bcf40788919844.json new file mode 100644 index 000000000..27860bc2c --- /dev/null +++ b/crates/database/.sqlx/query-564e9b1ce7cb468f78cb854239c5448fe3f4cc7d5870dbbbc7bcf40788919844.json @@ -0,0 +1,32 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT\n secret AS \"secret!: DigestedSecret\", digest_key AS \"digest_key!\",\n count(*) AS \"stored!: Unsigned\"\n FROM (\n SELECT 'authorization_request' AS secret, digest_key\n FROM authorization_requests\n UNION ALL\n SELECT 'authorization_code', digest_key\n FROM authorization_codes\n UNION ALL\n SELECT 'refresh_token', digest_key\n FROM refresh_tokens\n ) digests\n GROUP BY secret, digest_key\n ORDER BY secret, digest_key", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "secret!: DigestedSecret", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "digest_key!", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "stored!: Unsigned", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null, + null, + null + ] + }, + "hash": "564e9b1ce7cb468f78cb854239c5448fe3f4cc7d5870dbbbc7bcf40788919844" +} diff --git a/crates/database/.sqlx/query-58efe40b8d8fd9f229e34655f6ec57f30356010782b3b365466116e43d62b0e4.json b/crates/database/.sqlx/query-58efe40b8d8fd9f229e34655f6ec57f30356010782b3b365466116e43d62b0e4.json deleted file mode 100644 index c0ad43f0b..000000000 --- a/crates/database/.sqlx/query-58efe40b8d8fd9f229e34655f6ec57f30356010782b3b365466116e43d62b0e4.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT\n secret AS \"secret!: DigestedSecret\", digest_key,\n count(*) AS \"stored!: Unsigned\"\n FROM (\n SELECT 'authorization_request' AS secret, digest_key\n FROM authorization_requests\n UNION ALL\n SELECT 'authorization_code', digest_key\n FROM authorization_codes\n UNION ALL\n SELECT 'refresh_token', digest_key\n FROM refresh_tokens\n ) digests\n GROUP BY secret, digest_key\n ORDER BY secret, digest_key", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "secret!: DigestedSecret", - "type_info": "Text" - }, - { - "ordinal": 1, - "name": "digest_key", - "type_info": "Text" - }, - { - "ordinal": 2, - "name": "stored!: Unsigned", - "type_info": "Int8" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null, - null, - null - ] - }, - "hash": "58efe40b8d8fd9f229e34655f6ec57f30356010782b3b365466116e43d62b0e4" -} diff --git a/crates/database/migrations/0001_initial.sql b/crates/database/migrations/0001_initial.sql index 1fd6af6da..c889742d0 100644 --- a/crates/database/migrations/0001_initial.sql +++ b/crates/database/migrations/0001_initial.sql @@ -1,20 +1,103 @@ --- Initial authentication schema. Released migrations are immutable; later --- schema changes go in new numbered files. +-- The authentication schema. Released migrations are immutable; later schema +-- changes go in new numbered files. ---------------------------------------------------------------------------- --- Accounts and verified email ownership +-- Accounts ---------------------------------------------------------------------------- +-- A 'deleting' account waits out its grace period in account_deletions. +-- handle_changed_at is NULL until the handle first changes: a new account may +-- correct the handle it chose at signup at once, and the rename cooldown counts +-- only from a change. CREATE TABLE users ( id UUID PRIMARY KEY, - username TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, profile_version BIGINT NOT NULL DEFAULT 1 CHECK (profile_version > 0), - status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')), + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled', 'deleting')), created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT now() + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + handle_changed_at TIMESTAMPTZ ); +-- The confusable skeleton `Handle::skeleton` computes, which a test pins to it: +-- hyphens dropped, `0` read as `o`, `1` and `i` as `l`, `5` as `s`, then `rn` as +-- `m` and `vv` as `w`. +CREATE FUNCTION handle_skeleton(handle TEXT) RETURNS TEXT + LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE + SET search_path = pg_catalog, public, pg_temp + RETURN replace(replace(translate(handle, '01i5-', 'olls'), 'rn', 'm'), 'vv', 'w'); + +-- One table holds every account's current handle, the ones it held before and +-- the ones of purged accounts, so PostgreSQL keeps all of them unique, along with +-- their look-alikes. Only its former owner may claim a released handle again, +-- until an operator deletes it, or, for a purged account's, until cleanup frees +-- it a year after the purge. +CREATE TABLE handles ( + handle TEXT PRIMARY KEY + CHECK (length(handle) BETWEEN 3 AND 32 AND handle ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + skeleton TEXT NOT NULL UNIQUE GENERATED ALWAYS AS (handle_skeleton(handle)) STORED, + -- NULL once the account is purged. + user_id UUID REFERENCES users(id) ON DELETE SET NULL, + claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- NULL while it is the account's current handle. + released_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX handles_current_idx ON handles (user_id) WHERE released_at IS NULL; +CREATE INDEX handles_user_idx ON handles (user_id); +CREATE INDEX handles_purged_idx ON handles (released_at) WHERE user_id IS NULL; + +-- Purging an account sets its handles' user_id to NULL, which releases them all +-- at the purge, overwriting when an older one was renamed away, so each is freed +-- a year after the purge. +CREATE FUNCTION release_purged_handle() RETURNS trigger +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + NEW.released_at := now(); + RETURN NEW; +END $$; +CREATE TRIGGER handles_release_purged + BEFORE UPDATE OF user_id ON handles + FOR EACH ROW WHEN (OLD.user_id IS NOT NULL AND NEW.user_id IS NULL) + EXECUTE FUNCTION release_purged_handle(); + +-- Handles administrators reserve, on top of the names the handle rules build in: +-- signup and the settings refuse them and their look-alikes, as they do built-in +-- ones, until an administrator gives one to an account or removes it from the +-- list. The reason says who or what it is kept for. Accounts already holding one +-- keep it, and `handle check` lists them. +CREATE TABLE reserved_handles ( + handle TEXT PRIMARY KEY + CHECK (length(handle) BETWEEN 3 AND 32 AND handle ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + skeleton TEXT NOT NULL UNIQUE GENERATED ALWAYS AS (handle_skeleton(handle)) STORED, + reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 500), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- Each account's profile picture: the JPEG auth re-encoded from the upload, never +-- the uploaded bytes. `id` names it in its URL and is new on every upload, so the +-- image at a URL never changes and caches keep it for good; replacing or removing +-- the picture stops that URL at once. +CREATE TABLE profile_pictures ( + user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + id UUID NOT NULL UNIQUE, + image BYTEA NOT NULL CHECK (octet_length(image) BETWEEN 1 AND 131072), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +-- JPEG does not compress further: keep images out of line without trying. +ALTER TABLE profile_pictures ALTER COLUMN image SET STORAGE EXTERNAL; + +-- Administrator accounts. A separate table, rather than a role column, keeps +-- administrator rights out of tokens and out of a future groups model. Who +-- granted the rights is recorded by the AdministratorGranted event. +CREATE TABLE administrators ( + user_id UUID PRIMARY KEY REFERENCES users(id), + granted_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +---------------------------------------------------------------------------- +-- Email addresses +---------------------------------------------------------------------------- + CREATE TABLE user_emails ( id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, @@ -28,16 +111,20 @@ CREATE INDEX user_emails_user_id_idx ON user_emails (user_id); CREATE INDEX user_emails_verified_lookup_idx ON user_emails (normalized_email) WHERE verified_at IS NOT NULL; CREATE UNIQUE INDEX user_emails_one_primary_verified_idx ON user_emails (user_id) WHERE is_primary AND verified_at IS NOT NULL; --- One row per verified address of an active account. The normalized address is --- the unique lockable key, which makes concurrent first claims safe. Triggers --- below keep it in sync with user_emails and users.status. +-- One row per verified address of an active or deleting account. The normalized +-- address is the unique lockable key, which makes concurrent first claims safe. +-- Triggers below keep it in sync with user_emails and users.status. A 'deleting' +-- account keeps its addresses, so restoring it can never collide; deleting the +-- row at its purge releases them. CREATE TABLE active_verified_email_ownership ( normalized_email TEXT PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE ); +CREATE INDEX active_verified_email_ownership_user_idx ON active_verified_email_ownership (user_id); -- Claims ownership when an active account gains a verified address. -CREATE FUNCTION claim_active_verified_email() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +CREATE FUNCTION claim_active_verified_email() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ DECLARE account_active BOOLEAN; BEGIN IF NEW.verified_at IS NOT NULL THEN @@ -65,7 +152,8 @@ CREATE TRIGGER user_emails_claim_active_verified -- Releases ownership once no verified row of the owner still holds the address. -- AFTER triggers see the updated table, including an unchanged verified row. -CREATE FUNCTION release_active_verified_email() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +CREATE FUNCTION release_active_verified_email() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ BEGIN IF OLD.verified_at IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM user_emails e JOIN users u ON u.id=e.user_id @@ -83,7 +171,8 @@ CREATE TRIGGER user_emails_release_active_verified -- Disabling an account releases its addresses; reactivating reclaims them and -- fails if another active account claimed one in the meantime. -CREATE FUNCTION synchronize_user_email_ownership() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +CREATE FUNCTION synchronize_user_email_ownership() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ DECLARE address TEXT; BEGIN IF NEW.status='disabled' THEN @@ -105,7 +194,8 @@ CREATE TRIGGER users_synchronize_email_ownership FOR EACH ROW EXECUTE FUNCTION synchronize_user_email_ownership(); -- An account with verified emails has exactly one verified primary, checked at commit. -CREATE FUNCTION enforce_primary_verified_email() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +CREATE FUNCTION enforce_primary_verified_email() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ DECLARE affected UUID; affected_users UUID[]; @@ -128,11 +218,86 @@ CREATE CONSTRAINT TRIGGER user_emails_exactly_one_primary DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION enforce_primary_verified_email(); +-- Users add their own email addresses, which stay unverified until someone +-- follows the link sent to them. Auth derives the link's token from the address's +-- ID with a server key, so the token itself is stored nowhere: only its SHA-256 +-- digest, to look the address up. Verifying deletes the row; cleanup deletes +-- expired rows together with the unverified addresses they belong to. +CREATE TABLE email_verification_secrets ( + email_id UUID PRIMARY KEY REFERENCES user_emails(id) ON DELETE CASCADE, + secret_digest BYTEA NOT NULL UNIQUE CHECK (octet_length(secret_digest) = 32), + expires_at TIMESTAMPTZ NOT NULL +); +CREATE INDEX email_verification_secrets_expires_idx ON email_verification_secrets (expires_at); + ---------------------------------------------------------------------------- --- Sessions and audit +-- Account deletion ---------------------------------------------------------------------------- --- management_expires_at is a short, session-bound window for account changes. +-- A user, administrator or operator schedules an account's deletion; the account +-- then waits in status 'deleting' for its grace period, during which a passkey +-- can restore it, and the purge job deletes it once the period ends. Its handles +-- stay in `handles` without an owner. +-- +-- One row per account scheduled for deletion, removed when it is restored or +-- purged. A passkey sign-in to the account stores the digest of a single-use, +-- short-lived restore token here, with the passkey that signed in; the token +-- restores the account and signs in with that passkey. +-- +-- A purge that fails is retried with a backoff, so accounts that keep failing +-- never hold back every other due account. next_attempt_at is NULL until the +-- first failure: the purge is due at purge_after until then. last_error is the +-- error's message chain, never a value from the account. +CREATE TABLE account_deletions ( + user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + requested_at TIMESTAMPTZ NOT NULL DEFAULT now(), + purge_after TIMESTAMPTZ NOT NULL, + restore_token_digest BYTEA UNIQUE CHECK (octet_length(restore_token_digest) = 32), + restore_token_expires_at TIMESTAMPTZ, + restore_passkey_id UUID, + attempts INT NOT NULL DEFAULT 0, + last_error TEXT, + next_attempt_at TIMESTAMPTZ, + CHECK ((restore_token_digest IS NULL) = (restore_token_expires_at IS NULL)), + CHECK ((restore_token_digest IS NULL) = (restore_passkey_id IS NULL)), + CHECK ((attempts = 0) = (last_error IS NULL)), + CHECK ((last_error IS NULL) = (next_attempt_at IS NULL)) +); +-- The purge job reads due accounts in the order they became due. greatest() +-- ignores a NULL next_attempt_at. +CREATE INDEX account_deletions_due_idx + ON account_deletions ((greatest(next_attempt_at, purge_after))); + +-- An account that stops being 'deleting' is no longer scheduled, however it left: +-- restored, enabled or disabled. Otherwise the purge would skip it forever, and +-- it could never be scheduled again. +CREATE FUNCTION end_account_deletion() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + DELETE FROM account_deletions WHERE user_id = NEW.id; + RETURN NULL; +END $$; +CREATE TRIGGER users_end_account_deletion + AFTER UPDATE OF status ON users + FOR EACH ROW WHEN (OLD.status = 'deleting' AND NEW.status <> 'deleting') + EXECUTE FUNCTION end_account_deletion(); + +---------------------------------------------------------------------------- +-- Sessions and devices +---------------------------------------------------------------------------- + +-- passkey_confirmed_at is when the session last proved possession of a passkey; +-- each protected action states the maximum age it accepts. A session is +-- phishing-resistant exactly when it has one, and then lists passkeys among its +-- methods. passkey_id is the passkey that last proved it: the one that signed it +-- in, or confirmed it since; NULL for a social sign-in never confirmed. Undoing +-- an account recovery needs a session of a passkey enrolled before it, so NULL +-- never counts. It is no foreign key: it is only compared with passkeys, and a +-- purge may delete either row first. +-- +-- user_agent_family is the coarse browser and platform, `browser/platform`, e.g. +-- `firefox/linux`. The IPs, for the account's list of signed-in devices, live +-- only as long as the session row. CREATE TABLE sessions ( id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id), @@ -143,10 +308,14 @@ CREATE TABLE sessions ( user_agent_family TEXT, revoked_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - management_expires_at TIMESTAMPTZ, + passkey_confirmed_at TIMESTAMPTZ, + created_ip INET, + last_seen_ip INET, + passkey_id UUID, CHECK (expires_at > authenticated_at) ); CREATE INDEX sessions_active_user_idx ON sessions (user_id, expires_at) WHERE revoked_at IS NULL; +CREATE INDEX sessions_user_idx ON sessions (user_id); -- Browser cookies are stored only as digests. CREATE TABLE browser_session_secrets ( @@ -155,15 +324,21 @@ CREATE TABLE browser_session_secrets ( created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -CREATE TABLE security_audit_log ( - id UUID PRIMARY KEY, - user_id UUID REFERENCES users(id), - action TEXT NOT NULL, - outcome TEXT NOT NULL CHECK (outcome IN ('success', 'failure', 'rejected')), - request_metadata JSONB NOT NULL DEFAULT '{}'::jsonb, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() +-- The browsers each account has signed in from, so a sign-in from any other +-- one alerts its owner. A browser is known by the digest of its device cookie, +-- a random secret it keeps for 400 days, apart from its session cookie, so +-- signing out does not forget it. Maintenance deletes a device unused for 400 +-- days, and deleting the account deletes its devices. +CREATE TABLE known_devices ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + device_digest BYTEA NOT NULL CHECK (octet_length(device_digest) = 32), + user_agent_family TEXT, + first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(), + last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, device_digest) ); -CREATE INDEX security_audit_log_user_created_idx ON security_audit_log (user_id, created_at DESC); +-- Maintenance finds the devices unused for 400 days. +CREATE INDEX known_devices_last_seen_idx ON known_devices (last_seen_at); ---------------------------------------------------------------------------- -- Passkeys @@ -180,14 +355,43 @@ CREATE TABLE passkey_credentials ( revoked_at TIMESTAMPTZ ); CREATE INDEX passkey_credentials_active_user_idx ON passkey_credentials (user_id, created_at) WHERE revoked_at IS NULL; +CREATE INDEX passkey_credentials_user_idx ON passkey_credentials (user_id); +-- Cleanup deletes passkeys revoked 90 days ago. +CREATE INDEX passkey_credentials_revoked_idx ON passkey_credentials (revoked_at) + WHERE revoked_at IS NOT NULL; + +-- An account keeps at most 100 active passkeys, so the recovery event listing +-- them stays well under the event payload bound below. Nobody needs more. +-- Concurrent registrations can pass it by a few, which the bound still fits. +CREATE FUNCTION limit_passkeys() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +BEGIN + IF ( + SELECT count(*) FROM passkey_credentials + WHERE user_id = NEW.user_id AND revoked_at IS NULL + ) < 100 THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'account % already has 100 active passkeys', NEW.user_id + USING ERRCODE = 'check_violation'; +END $$; +CREATE TRIGGER passkey_credentials_limit + BEFORE INSERT ON passkey_credentials + FOR EACH ROW EXECUTE FUNCTION limit_passkeys(); -- Ceremony state includes the challenge and is stored server-side until expiry. --- It is never accepted twice and must never appear in logs. +-- It is never accepted twice and must never appear in logs. A +-- 'related_authentication' is a passkey sign-in on a related origin, bound to +-- its origin and the pushed authorization request it completes, rather than to a +-- browser cookie. CREATE TABLE webauthn_ceremonies ( id UUID PRIMARY KEY, user_id UUID REFERENCES users(id) ON DELETE CASCADE, session_id UUID REFERENCES sessions(id) ON DELETE CASCADE, - ceremony_kind TEXT NOT NULL CHECK (ceremony_kind IN ('registration', 'authentication', 'enrollment', 'purpose_authentication')), + ceremony_kind TEXT NOT NULL CHECK (ceremony_kind IN ( + 'registration', 'authentication', 'enrollment', 'purpose_authentication', + 'related_authentication' + )), challenge_digest BYTEA NOT NULL, state JSONB NOT NULL, expires_at TIMESTAMPTZ NOT NULL, @@ -197,51 +401,308 @@ CREATE TABLE webauthn_ceremonies ( CREATE INDEX webauthn_ceremonies_expiry_idx ON webauthn_ceremonies (expires_at) WHERE consumed_at IS NULL; ---------------------------------------------------------------------------- --- OIDC clients, authorization and consent +-- Account recoveries +---------------------------------------------------------------------------- + +-- Recoveries an operator started for an account whose owner lost their +-- passkeys. Each sends its owner a link that enrolls one passkey, once, within a +-- day. The link's token is derived from the recovery's ID, so only its digest is +-- stored. For 15 days after the link is used, the recovery is in probation: its +-- passkey signs in but never confirms a session, and a passkey from before it +-- can undo it. +CREATE TABLE account_recoveries ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + secret_digest BYTEA NOT NULL UNIQUE, + started_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + expires_at TIMESTAMPTZ NOT NULL, + -- When its link enrolled a passkey, which one, and when its probation ends. + -- `settles_at` is computed by auth from its probation length, so SQL never + -- repeats the constant. + completed_at TIMESTAMPTZ, + passkey_id UUID, + settles_at TIMESTAMPTZ, + -- When a newer recovery, the account's disabling or its owner's undo cancelled + -- it before its link was used. + cancelled_at TIMESTAMPTZ, + -- When it was undone after its link was used, by its owner or by support. + undone_at TIMESTAMPTZ, + CHECK ((completed_at IS NULL) = (passkey_id IS NULL)), + CHECK ((completed_at IS NULL) = (settles_at IS NULL)), + CHECK (cancelled_at IS NULL OR (completed_at IS NULL AND undone_at IS NULL)), + CHECK (undone_at IS NULL OR completed_at IS NOT NULL) +); +CREATE INDEX account_recoveries_user_idx ON account_recoveries (user_id, started_at DESC); +CREATE UNIQUE INDEX account_recoveries_passkey_idx ON account_recoveries (passkey_id); +-- At most one recovery per account whose link was not used, cancelled or undone. +-- An expired one counts until the next start cancels it. +CREATE UNIQUE INDEX account_recoveries_one_open_idx ON account_recoveries (user_id) + WHERE completed_at IS NULL AND cancelled_at IS NULL AND undone_at IS NULL; + +-- The account's recovery that can still be undone, if any: its link still works, +-- or it is in probation (its rows with `completed_at` set). The one SQL copy of +-- auth's `RecoveryState`; only the trigger functions below call it, as their +-- owner. +CREATE FUNCTION undoable_recovery(account UUID) RETURNS SETOF account_recoveries +LANGUAGE sql VOLATILE SET search_path = pg_catalog, public, pg_temp AS $$ + SELECT * FROM public.account_recoveries + WHERE user_id = account + AND undone_at IS NULL AND cancelled_at IS NULL + AND (settles_at > clock_timestamp() + OR (completed_at IS NULL AND expires_at > clock_timestamp())) +$$; +REVOKE EXECUTE ON FUNCTION undoable_recovery(UUID) FROM PUBLIC; + +-- The triggers below hold the recovery's rules for every role that writes their +-- tables. They run as their owner, so a role not granted `account_recoveries` +-- cannot get past them, and no one else may execute them. + +-- A probation passkey never confirms a session. A confirmation that names no +-- passkey fails closed while the account is in probation. +CREATE FUNCTION sessions_no_probation_confirmation() RETURNS trigger +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF NEW.passkey_confirmed_at IS NOT NULL AND EXISTS ( + SELECT 1 FROM public.undoable_recovery(NEW.user_id) + WHERE completed_at IS NOT NULL + AND (NEW.passkey_id IS NULL OR passkey_id = NEW.passkey_id) + ) THEN + NEW.passkey_confirmed_at := NULL; + END IF; + RETURN NEW; +END $$; +REVOKE EXECUTE ON FUNCTION sessions_no_probation_confirmation() FROM PUBLIC; +CREATE TRIGGER sessions_no_probation_confirmation + BEFORE INSERT OR UPDATE OF passkey_confirmed_at, passkey_id ON sessions + FOR EACH ROW EXECUTE FUNCTION sessions_no_probation_confirmation(); + +-- No account is made an administrator while a recovery of it can be undone: +-- the rights would go live for whoever holds its passkey once it settles. +CREATE FUNCTION administrators_no_grant_mid_recovery() RETURNS trigger +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM public.undoable_recovery(NEW.user_id)) THEN + RAISE EXCEPTION 'account % has a recovery that can still be undone', NEW.user_id + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END $$; +REVOKE EXECUTE ON FUNCTION administrators_no_grant_mid_recovery() FROM PUBLIC; +CREATE TRIGGER administrators_no_grant_mid_recovery + BEFORE INSERT ON administrators + FOR EACH ROW EXECUTE FUNCTION administrators_no_grant_mid_recovery(); + +-- While a recovery can be undone, no passkey but its own is revoked, by anyone, +-- so nothing takes away the passkeys that can undo it. +CREATE FUNCTION passkeys_kept_mid_recovery() RETURNS trigger +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM public.undoable_recovery(OLD.user_id) + WHERE passkey_id IS DISTINCT FROM OLD.id + ) THEN + RAISE EXCEPTION 'account % has a recovery that can still be undone', OLD.user_id + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END $$; +REVOKE EXECUTE ON FUNCTION passkeys_kept_mid_recovery() FROM PUBLIC; +CREATE TRIGGER passkeys_kept_mid_recovery + BEFORE UPDATE OF revoked_at ON passkey_credentials + FOR EACH ROW WHEN (OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL) + EXECUTE FUNCTION passkeys_kept_mid_recovery(); + +---------------------------------------------------------------------------- +-- OIDC clients ---------------------------------------------------------------------------- --- Clients are provisioned from static configuration at startup. +-- Operators manage clients with `auth-service client`, and accounts manage the +-- ones they register through the account API. owner_id is NULL for operators' +-- clients, which the account API never shows. created_via records which path +-- registered the client; 'registration' is reserved for dynamic client +-- registration (#44). +-- +-- Deletion is a tombstone: the row stays, so its ID, which tokens carry as `aud`, +-- is never reused, and cleanup never deletes it. A tombstone is always disabled, +-- so no path can bring it back. +-- +-- A suspension is an operator's block: the client is disabled, and its owner +-- cannot enable it until an operator lifts the suspension. +-- +-- Purging an account keeps its clients' tombstones, without their owner. Its live +-- clients must be deleted first: the owner check refuses to turn them into clients +-- no account manages. +-- +-- last_used_at moves at most once an hour, when a token is issued to the client. +-- backchannel_logout_uri is NULL for clients that are not told when a session +-- ends (OIDC Back-Channel Logout 1.0). CREATE TABLE oidc_clients ( id TEXT PRIMARY KEY, display_name TEXT NOT NULL, enabled BOOLEAN NOT NULL DEFAULT TRUE, - client_secret_hash BYTEA CHECK (client_secret_hash IS NULL OR octet_length(client_secret_hash)=32), trusted BOOLEAN NOT NULL DEFAULT FALSE, allowed_scopes JSONB NOT NULL, allowed_audiences JSONB NOT NULL, allow_refresh BOOLEAN NOT NULL DEFAULT FALSE, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + client_type TEXT NOT NULL DEFAULT 'public' CHECK (client_type IN ('public', 'confidential')), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- Clients that may start an authorization only from a pushed request. + require_pushed_authorization_requests BOOLEAN NOT NULL DEFAULT FALSE, + owner_id UUID REFERENCES users(id) ON DELETE SET NULL, + created_via TEXT NOT NULL DEFAULT 'cli' CHECK (created_via IN ('cli', 'account', 'registration')), + deleted_at TIMESTAMPTZ, + suspended_at TIMESTAMPTZ, + last_used_at TIMESTAMPTZ, + backchannel_logout_uri TEXT, + CONSTRAINT oidc_clients_tombstone_disabled CHECK (deleted_at IS NULL OR NOT enabled), + CONSTRAINT oidc_clients_suspended_disabled CHECK (suspended_at IS NULL OR NOT enabled), + CONSTRAINT oidc_clients_owned_until_deleted + CHECK (created_via <> 'account' OR owner_id IS NOT NULL OR deleted_at IS NOT NULL) ); +-- Counts an owner's live clients for the quota, and the clients, deleted or not, +-- they registered recently for the daily registration limit. +CREATE INDEX oidc_clients_owner_idx ON oidc_clients (owner_id, created_at); +-- A client may hold several secrets at once: rotating one caps the expiry of the +-- previous secrets, so the client keeps working while it redeploys. Only SHA-256 +-- digests are stored; auth generates every secret with 256 random bits. +CREATE TABLE oidc_client_secrets ( + id UUID PRIMARY KEY, + client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, + secret_digest BYTEA NOT NULL CHECK (octet_length(secret_digest) = 32), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- NULL until a rotation sets it on the previous secrets. + expires_at TIMESTAMPTZ +); +CREATE INDEX oidc_client_secrets_client_idx ON oidc_client_secrets (client_id); + +-- origin is the redirect URI's origin, as browsers send it in an Origin header, +-- which auth computes on write. A public client's authorization redirect origins +-- may call the token and UserInfo endpoints, which look them up per request. CREATE TABLE oidc_redirect_uris ( client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, uri TEXT NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('authorization', 'post_logout')), + origin TEXT NOT NULL, PRIMARY KEY (client_id, uri, kind) ); +CREATE INDEX oidc_redirect_uris_origin_idx ON oidc_redirect_uris (origin) + WHERE kind = 'authorization'; + +-- A deleted client keeps only its ID, settings that identify nobody, and its +-- lifecycle dates: its name, redirect URIs and back-channel logout URI may name a +-- person or their domain. Its name becomes empty. +CREATE FUNCTION scrub_deleted_client() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + NEW.display_name := ''; + NEW.backchannel_logout_uri := NULL; + DELETE FROM oidc_redirect_uris WHERE client_id = NEW.id; + RETURN NEW; +END $$; +CREATE TRIGGER oidc_clients_scrub_deleted + BEFORE UPDATE OF deleted_at ON oidc_clients + FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) + EXECUTE FUNCTION scrub_deleted_client(); + +-- Origins whose pages may sign users in with their auth passkeys (WebAuthn +-- related origins). `/.well-known/webauthn` lists them, so browsers let those +-- pages use auth's RP ID. Only operators approve them: browsers honour few +-- distinct domains, and the client must be trusted and have a redirect URI on +-- the origin. The origin is written as browsers send it, e.g. https://app.example. +CREATE TABLE client_webauthn_origins ( + origin TEXT PRIMARY KEY, + client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, + approved_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX client_webauthn_origins_client_idx ON client_webauthn_origins (client_id); + +-- A deleted client's origins go with it: clients are tombstoned, so the foreign +-- key never cascades. +CREATE FUNCTION remove_deleted_client_origins() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + DELETE FROM client_webauthn_origins WHERE client_id = NEW.id; + RETURN NULL; +END $$; +CREATE TRIGGER oidc_clients_remove_related_origins + AFTER UPDATE OF deleted_at ON oidc_clients + FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) + EXECUTE FUNCTION remove_deleted_client_origins(); + +-- Signing keys. Every replica reloads them each minute; one replica at a time +-- advances their rotation, under a transaction-level advisory lock that the +-- `keys` commands take too. A key is published as `next`, signs as `active`, stays +-- published as `retiring`, then verifies only `id_token_hint`s as `retired` until +-- it is deleted. Its PKCS#8 private key is sealed with AES-256-GCM under the +-- key-encryption key from configuration, with `id || key_type` as associated +-- data, and erased once it retires. +CREATE TABLE signing_keys ( + id TEXT PRIMARY KEY CHECK (length(id) BETWEEN 1 AND 128), + key_type TEXT NOT NULL CHECK (key_type IN ('rsa')), + state TEXT NOT NULL CHECK (state IN ('next', 'active', 'retiring', 'retired')), + public_jwk JSONB NOT NULL, + sealed_private_key BYTEA, + created_at TIMESTAMPTZ NOT NULL, + -- When it started signing, stopped signing, and left the key set. + activated_at TIMESTAMPTZ, + deactivated_at TIMESTAMPTZ, + retired_at TIMESTAMPTZ, + CHECK ((state = 'retired') = (sealed_private_key IS NULL)), + CHECK ((state = 'next') = (activated_at IS NULL)), + CHECK ((state IN ('next', 'active')) = (deactivated_at IS NULL)), + CHECK ((state = 'retired') = (retired_at IS NOT NULL)) +); +CREATE UNIQUE INDEX signing_keys_one_active ON signing_keys (key_type) WHERE state = 'active'; +CREATE UNIQUE INDEX signing_keys_one_next ON signing_keys (key_type) WHERE state = 'next'; + +---------------------------------------------------------------------------- +-- Authorization, consent and refresh tokens +---------------------------------------------------------------------------- + +-- Every secret digest records the fingerprint of the token digest key it was +-- made with (`digest_key`), so `auth-service keys digest-usage` can tell when no +-- stored digest needs an old key. -- A validated authorization request, resumed across login and consent. --- hinted_user_id keeps the requested subject across that resumption. +-- hinted_user_id keeps the requested subject across that resumption. client_state +-- is NULL when the client sent no state (RFC 6749 §4.1.1), and pkce_challenge +-- when a confidential client left PKCE out (RFC 9700). target_acr is the class +-- the client asked for with `acr_values`, if it named a known one. interaction is +-- the request's `prompt`: `none` excludes `login` and `consent`. +-- +-- A pushed authorization request (RFC 9126) is stored by its client through the +-- back channel, then claimed once by the browser with the returned request_uri. +-- It is not a pending authorization until it is claimed: claiming replaces its +-- secret, so the request_uri itself never continues one. CREATE TABLE authorization_requests ( id UUID PRIMARY KEY, secret_digest BYTEA NOT NULL UNIQUE, client_id TEXT NOT NULL REFERENCES oidc_clients(id), redirect_uri TEXT NOT NULL, - client_state TEXT NOT NULL, + client_state TEXT, nonce TEXT, - pkce_challenge TEXT NOT NULL, + pkce_challenge TEXT, scopes JSONB NOT NULL, audience TEXT NOT NULL, - force_login BOOLEAN NOT NULL, - force_consent BOOLEAN NOT NULL, max_age BIGINT, expires_at TIMESTAMPTZ NOT NULL, consumed_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - hinted_user_id UUID + hinted_user_id UUID, + target_acr TEXT, + pushed BOOLEAN NOT NULL DEFAULT FALSE, + claimed_at TIMESTAMPTZ, + digest_key TEXT NOT NULL, + interaction TEXT NOT NULL + CHECK (interaction IN ('as_needed', 'login', 'consent', 'login_consent', 'none')) ); CREATE INDEX authorization_requests_active_idx ON authorization_requests (expires_at) WHERE consumed_at IS NULL; +-- authentication is `SessionAuthentication` as JSON: `acr`, `auth_time` and +-- `amr`, from when the code was issued, so later re-authentication of the +-- session never changes what the grant reports (OIDC Core 12.2). CREATE TABLE authorization_codes ( id UUID PRIMARY KEY, secret_digest BYTEA NOT NULL UNIQUE, @@ -249,15 +710,19 @@ CREATE TABLE authorization_codes ( user_id UUID NOT NULL REFERENCES users(id), session_id UUID NOT NULL REFERENCES sessions(id), redirect_uri TEXT NOT NULL, - pkce_challenge TEXT NOT NULL, + pkce_challenge TEXT, nonce TEXT, scopes JSONB NOT NULL, audience TEXT NOT NULL, expires_at TIMESTAMPTZ NOT NULL, consumed_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + authentication JSONB NOT NULL, + digest_key TEXT NOT NULL ); CREATE INDEX authorization_codes_active_idx ON authorization_codes (expires_at) WHERE consumed_at IS NULL; +-- Lets cleanup find redeemed codes past their grace period without a full scan. +CREATE INDEX authorization_codes_consumed_idx ON authorization_codes (consumed_at) WHERE consumed_at IS NOT NULL; CREATE TABLE oidc_consents ( user_id UUID NOT NULL REFERENCES users(id), @@ -266,12 +731,44 @@ CREATE TABLE oidc_consents ( scopes JSONB NOT NULL, PRIMARY KEY (user_id, client_id, audience) ); +-- Deleting a client deletes its consents. +CREATE INDEX oidc_consents_client_idx ON oidc_consents (client_id); ----------------------------------------------------------------------------- --- Refresh tokens ----------------------------------------------------------------------------- +-- Which clients received tokens from which session, so that when the session +-- ends auth posts a logout token to the back-channel logout URI of each. +CREATE TABLE oidc_session_clients ( + session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, + first_issued_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (session_id, client_id) +); + +-- Every redeemed code records its client. An exchange that fails rolls back the +-- redemption, so only clients that received tokens are recorded. It runs as its +-- owner, so it records the client for every role that redeems a code. No one +-- else may execute it: on a temporary table of its own, with a type whose cast to +-- uuid it wrote, the runtime role would run that cast as the owner. A trigger +-- already attached still fires. +CREATE FUNCTION oidc_session_clients_record_redeemed_code() RETURNS trigger +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + INSERT INTO oidc_session_clients (session_id, client_id) + VALUES (NEW.session_id, NEW.client_id) + ON CONFLICT DO NOTHING; + RETURN NULL; +END +$$; +REVOKE ALL ON FUNCTION oidc_session_clients_record_redeemed_code() FROM PUBLIC; +CREATE TRIGGER authorization_codes_record_session_client +AFTER UPDATE OF consumed_at ON authorization_codes +FOR EACH ROW WHEN (OLD.consumed_at IS NULL AND NEW.consumed_at IS NOT NULL) +EXECUTE FUNCTION oidc_session_clients_record_redeemed_code(); --- A family groups every rotation of one grant; revoking it ends the grant. +-- A family groups every rotation of one grant; revoking it ends the grant. It +-- keeps the authentication of the code it was redeemed from, and links to that +-- code, so redeeming the code again revokes the family (RFC 6749 section 4.1.2). +-- Cleanup keeps a redeemed code while a family it produced can still refresh; +-- purging it afterwards clears the link rather than failing on it. CREATE TABLE refresh_token_families ( id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id), @@ -280,18 +777,33 @@ CREATE TABLE refresh_token_families ( audience TEXT NOT NULL, scopes JSONB NOT NULL, revoked_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + authorization_code_id UUID REFERENCES authorization_codes(id) ON DELETE SET NULL, + authentication JSONB NOT NULL ); CREATE INDEX refresh_families_session_idx ON refresh_token_families (session_id); CREATE INDEX refresh_families_active_user_idx ON refresh_token_families (user_id) WHERE revoked_at IS NULL; +CREATE INDEX refresh_families_user_idx ON refresh_token_families (user_id); +-- A client's deletion locks, then revokes, its live families. +CREATE INDEX refresh_families_active_client_idx ON refresh_token_families (client_id) + WHERE revoked_at IS NULL; +-- Serves replay revocation, cleanup's live-family check and the ON DELETE SET +-- NULL lookup when codes are purged. +CREATE INDEX refresh_families_authorization_code_idx ON refresh_token_families (authorization_code_id); +-- A rotated refresh token names the token it replaced, so a public client that +-- presents that token again moments later, from a second tab or as a retry, is +-- answered with this successor instead of having its family revoked as a +-- replay. A token has at most one successor. CREATE TABLE refresh_tokens ( id UUID PRIMARY KEY, family_id UUID NOT NULL REFERENCES refresh_token_families(id) ON DELETE CASCADE, secret_digest BYTEA NOT NULL UNIQUE, expires_at TIMESTAMPTZ NOT NULL, issued_at TIMESTAMPTZ NOT NULL DEFAULT now(), - consumed_at TIMESTAMPTZ + consumed_at TIMESTAMPTZ, + digest_key TEXT NOT NULL, + predecessor_id UUID UNIQUE REFERENCES refresh_tokens(id) ON DELETE SET NULL ); CREATE INDEX refresh_tokens_family_idx ON refresh_tokens (family_id); @@ -313,6 +825,10 @@ CREATE TABLE external_login_identities ( -- Unlinking releases a provider subject, but keeps its audit history. CREATE UNIQUE INDEX external_identity_active_subject ON external_login_identities (issuer, subject) WHERE revoked_at IS NULL; CREATE UNIQUE INDEX external_identity_active_provider ON external_login_identities (user_id, provider_name) WHERE revoked_at IS NULL; +CREATE INDEX external_login_identities_user_idx ON external_login_identities (user_id); +-- Cleanup deletes identities unlinked 90 days ago. +CREATE INDEX external_login_identities_revoked_idx ON external_login_identities (revoked_at) + WHERE revoked_at IS NOT NULL; -- An in-flight provider redirect, bound to the initiating browser. CREATE TABLE federation_transactions ( @@ -334,6 +850,9 @@ CREATE INDEX federation_transactions_expiry_idx ON federation_transactions (expi -- No user or normal session exists while social signup is pending. The browser -- must finish its first passkey before this identity can be committed. +-- picture_url is the profile picture the provider reported, which the signup +-- imports once the account exists. email_authoritative says whether the +-- provider is authoritative for the address, so it is imported verified. CREATE TABLE pending_federation ( id UUID PRIMARY KEY, browser_digest BYTEA NOT NULL UNIQUE CHECK (octet_length(browser_digest)=32), @@ -348,7 +867,10 @@ CREATE TABLE pending_federation ( expires_at TIMESTAMPTZ NOT NULL, consumed_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - CHECK (link_session_id IS NULL OR link_user_id IS NOT NULL) + picture_url TEXT CHECK (char_length(picture_url) <= 2048), + email_authoritative BOOLEAN NOT NULL DEFAULT false, + CHECK (link_session_id IS NULL OR link_user_id IS NOT NULL), + CHECK (email IS NOT NULL OR NOT email_authoritative) ); CREATE INDEX pending_federation_expiry_idx ON pending_federation (expires_at); @@ -356,11 +878,21 @@ CREATE INDEX pending_federation_expiry_idx ON pending_federation (expires_at); -- Invitations and rate limits ---------------------------------------------------------------------------- +-- Administrators list and revoke invitations by ID, without knowing their +-- secret; a revoked invitation can no longer be redeemed. An invitation may be +-- mailed to the person it invites: it remembers their normalized address, which +-- their account starts with, verified, when they sign up with it. Its link's +-- token is derived from its ID, so the email sender rebuilds the link from the +-- stored digest, as it does a recovery's. Cleanup deletes the address with its +-- invitation, once it expires or a day after it is redeemed. CREATE TABLE invitations ( - secret_digest BYTEA PRIMARY KEY CHECK (octet_length(secret_digest) = 32), + id UUID PRIMARY KEY, + secret_digest BYTEA NOT NULL UNIQUE CHECK (octet_length(secret_digest) = 32), expires_at TIMESTAMPTZ NOT NULL, redeemed_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + revoked_at TIMESTAMPTZ, + email TEXT ); -- Fixed-window request counters shared by every service process. @@ -369,3 +901,570 @@ CREATE TABLE request_limits ( requests INTEGER NOT NULL, expires_at TIMESTAMPTZ NOT NULL ); + +---------------------------------------------------------------------------- +-- Domain events and the audit chain +---------------------------------------------------------------------------- + +-- Typed domain events. domain_events holds only non-identifying content: the +-- event kind and payload, its actor, and the subject, client and session it +-- concerns. Anything that identifies a person outside auth (client IP, user agent +-- family, and every Personal value of the payload) lives in event_personal_data, +-- which retention and account purges delete without touching the event. +-- +-- subject_user_id has no foreign key: history outlives the account it describes. +-- +-- The history is tamper-evident: a hash chain over sealed events, and signed +-- checkpoints of its head. See docs/dev/security/audit-history.md. The sealer, one +-- replica at a time, gives each event its chain position and hash after its +-- transaction and every older one have finished; events are inserted unsealed. +-- Each sealed event records the format of the canonical event its hash covers, +-- which the canonical event names, so a later format can add fields without +-- breaking the hashes of events sealed before it. Only known formats are allowed, +-- so a forged one is reported where it is rather than taken for a newer +-- release's; the release that adds a format widens the check. +CREATE TABLE domain_events ( + id UUID PRIMARY KEY, + txid XID8 NOT NULL DEFAULT pg_current_xact_id(), + sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, + occurred_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + kind TEXT NOT NULL, + version SMALLINT NOT NULL, + payload JSONB NOT NULL, + actor JSONB NOT NULL, + subject_user_id UUID, + client_id TEXT, + session_id UUID, + -- The request's trace ID, which links the event to its telemetry. + trace_id TEXT, + chain_position BIGINT UNIQUE CHECK (chain_position > 0), + -- SHA-256(previous chain_hash || SHA-256(canonical event)). + chain_hash BYTEA CHECK (octet_length(chain_hash) = 32), + chain_format SMALLINT NOT NULL DEFAULT 1 CHECK (chain_format IN (1)), + CHECK ((chain_position IS NULL) = (chain_hash IS NULL)) +); +-- Consumers read in (txid, sequence) order; see EventRepository::read_after. +CREATE INDEX domain_events_cursor_idx ON domain_events (txid, sequence); +-- The sealer reads unsealed events in that order too. +CREATE INDEX domain_events_unsealed_idx ON domain_events (txid, sequence) + WHERE chain_position IS NULL; +-- Histories list events in the order they are sealed in, (txid, sequence), which +-- verification checks against the chain, rather than by sequence alone, which the +-- chain does not cover. +CREATE INDEX domain_events_subject_order_idx + ON domain_events (subject_user_id, txid DESC, sequence DESC); +-- A purge erases the personal data of the events the account acted in, found by +-- the actor's user ID. The index is not partial: PostgreSQL keeps no statistics +-- on a partial index's expression, and without them it estimates so many matches +-- that it scans every event's personal data instead. +CREATE INDEX domain_events_actor_user_idx ON domain_events ((actor ->> 'user_id')); +-- Purging an owner erases its clients' related origins from the events about them. +CREATE INDEX domain_events_client_idx ON domain_events (client_id) + WHERE client_id IS NOT NULL; +-- The overviews count events of a kind over the last hour and week, across +-- every account: the dashboard's failed and successful sign-ins and code +-- exchanges, against what an hour usually brings. +CREATE INDEX domain_events_kind_time_idx ON domain_events (kind, occurred_at); + +-- Auth's runtime role writes history only the way auth does (#250), so a +-- compromised auth can neither forge history nor plant rows that freeze it. With +-- the column grants of runtime_role.sql, it cannot set an event's transaction, +-- time, sequence or chain columns when inserting it. The guards below refuse the +-- rest, for every role: an event auth could not read back, personal data +-- attached to another transaction's event, a seal that skips a position, and a +-- checkpoint for anything but a sealed event's hash, or dated in the future. A +-- huge position, an unreadable event or a future checkpoint would otherwise stop +-- sealing or signing until the schema owner repaired it. SQL cannot check a hash +-- or a checkpoint's signature; the sealer and `audit verify` do, and a seal with +-- a wrong one still stops signing until the owner repairs the chain. +-- +-- An event the sealer could not read would fail every sealing pass, which loads +-- up to 100 events at once. serde_json refuses numbers beyond a double's range +-- and nesting past 128 levels, and a huge event would exhaust the sealer's memory +-- or time: parsed, JSON can take about 100 times its text. So an event's payload +-- stays under 8 KiB, its actor under 1 KiB and its text columns under 256 bytes, +-- about 95 MB for a batch at worst. Real events are a few hundred bytes, the +-- largest a recovery listing an account's passkeys, which the passkey limit +-- keeps around 4 KiB. Sealing an event updates it and checks it again. +CREATE FUNCTION auth_reads_json(value JSONB, bytes INT) RETURNS BOOLEAN +LANGUAGE sql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$ + SELECT octet_length(value::text) <= bytes AND NOT ( + value @? '$.** ? (@.type() == "number" && (@ > 1e308 || @ < -1e308))' + OR value @? '$.**{64 to last}' + ) +$$; +ALTER TABLE domain_events ADD CONSTRAINT domain_events_readable CHECK ( + auth_reads_json(payload, 8192) AND auth_reads_json(actor, 1024) + AND octet_length(kind) <= 256 AND octet_length(client_id) <= 256 + AND octet_length(trace_id) <= 256 +); + +-- details maps the JSON pointer of each Personal payload value to that value. +-- user_agent_family holds the browser of the event's user agent, and platform its +-- platform. reason is why an administrator or operator changed someone's +-- account, as they wrote it: free text may name people. +CREATE TABLE event_personal_data ( + event_id UUID PRIMARY KEY REFERENCES domain_events(id) ON DELETE CASCADE, + client_ip INET, + user_agent_family TEXT, + details JSONB NOT NULL DEFAULT '{}', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + platform TEXT, + reason TEXT +); +-- Lets cleanup find personal data past its retention without a full scan. +CREATE INDEX event_personal_data_created_idx ON event_personal_data (created_at); + +-- Personal data is recorded with its event, never attached to an older one: with +-- the deletes retention needs, that would let it be rewritten. +CREATE FUNCTION guard_personal_data_insert() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT FROM domain_events WHERE id = NEW.event_id AND txid = pg_current_xact_id() + ) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'personal data of event % can only be recorded with the event', NEW.event_id + USING ERRCODE = 'integrity_constraint_violation'; +END $$; +CREATE TRIGGER event_personal_data_guard_insert + BEFORE INSERT ON event_personal_data + FOR EACH ROW EXECUTE FUNCTION guard_personal_data_insert(); + +-- An event keeps personal data only while every account it names, as subject or +-- actor, exists: a request still in flight when its account is purged must not +-- store it again. Each named account is key-share locked, which only deleting +-- the account conflicts with: either the purge's delete waits, then erases this +-- row, or this insert waits, finds the account gone and is skipped. +CREATE FUNCTION skip_personal_data_of_purged_accounts() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF EXISTS ( + SELECT FROM domain_events e + CROSS JOIN LATERAL ( + VALUES (e.subject_user_id), ((e.actor ->> 'user_id')::uuid) + ) AS named(id) + WHERE e.id = NEW.event_id + AND named.id IS NOT NULL + AND NOT EXISTS (SELECT FROM users WHERE id = named.id FOR KEY SHARE) + ) THEN + RETURN NULL; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER event_personal_data_skip_purged_accounts + BEFORE INSERT ON event_personal_data + FOR EACH ROW EXECUTE FUNCTION skip_personal_data_of_purged_accounts(); + +-- Personal data is erased, never rewritten. Purging an app's owner erases the +-- app's related origins from other people's events by removing them from +-- `details`, the only column the runtime role may update; any other update fails. +CREATE FUNCTION guard_personal_data_erasure() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF NOT EXISTS ( + SELECT FROM jsonb_each(NEW.details) kept + WHERE OLD.details -> kept.key IS DISTINCT FROM kept.value + ) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'personal data of event % can only be erased', OLD.event_id + USING ERRCODE = 'integrity_constraint_violation'; +END $$; +CREATE TRIGGER event_personal_data_guard_erasure + BEFORE UPDATE ON event_personal_data + FOR EACH ROW EXECUTE FUNCTION guard_personal_data_erasure(); + +-- Signed checkpoints of the chain head, in the C2SP signed-note format. Never +-- pruned: pruned events stay covered by the checkpoints that signed them. +CREATE TABLE audit_checkpoints ( + position BIGINT PRIMARY KEY CHECK (position > 0), + head BYTEA NOT NULL CHECK (octet_length(head) = 32), + created_at TIMESTAMPTZ NOT NULL, + note TEXT NOT NULL +); + +-- The checkpoint the chain was last pruned through, if it ever was. The first +-- remaining event chains from its head instead of from 32 zero bytes. +CREATE TABLE audit_anchor ( + singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton), + position BIGINT NOT NULL REFERENCES audit_checkpoints (position) +); + +-- Guards sealed history: a sealed event is never updated, and only pruning, which +-- sets sourceorigin.audit_prune for its transaction, deletes one. Checkpoints are never +-- updated or deleted, and neither table is truncated. The runtime role cannot +-- drop these triggers, and may update only unsealed events' chain columns (see +-- runtime_role.sql); the schema owner can, and the chain is what detects that. +CREATE FUNCTION guard_sealed_events() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF OLD.chain_position IS NULL + OR (TG_OP = 'DELETE' AND current_setting('sourceorigin.audit_prune', true) = 'on') THEN + RETURN CASE TG_OP WHEN 'DELETE' THEN OLD ELSE NEW END; + END IF; + RAISE EXCEPTION 'sealed event at chain position % cannot be changed', OLD.chain_position + USING ERRCODE = 'integrity_constraint_violation'; +END; +$$; +CREATE TRIGGER domain_events_guard_sealed + BEFORE UPDATE OR DELETE ON domain_events + FOR EACH ROW EXECUTE FUNCTION guard_sealed_events(); + +CREATE FUNCTION refuse_audit_history_change() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + RAISE EXCEPTION '% on % would change sealed audit history', TG_OP, TG_TABLE_NAME + USING ERRCODE = 'integrity_constraint_violation'; +END; +$$; +CREATE TRIGGER audit_checkpoints_guard + BEFORE UPDATE OR DELETE ON audit_checkpoints + FOR EACH ROW EXECUTE FUNCTION refuse_audit_history_change(); +CREATE TRIGGER domain_events_guard_truncate + BEFORE TRUNCATE ON domain_events + FOR EACH STATEMENT EXECUTE FUNCTION refuse_audit_history_change(); +CREATE TRIGGER audit_checkpoints_guard_truncate + BEFORE TRUNCATE ON audit_checkpoints + FOR EACH STATEMENT EXECUTE FUNCTION refuse_audit_history_change(); +CREATE TRIGGER audit_anchor_guard_truncate + BEFORE TRUNCATE ON audit_anchor + FOR EACH STATEMENT EXECUTE FUNCTION refuse_audit_history_change(); + +-- The anchor moves only forward, and only while pruning, so it cannot hide events +-- left at or before it, and concurrent prunes cannot move it back. +CREATE FUNCTION guard_audit_anchor() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + IF TG_OP <> 'DELETE' AND current_setting('sourceorigin.audit_prune', true) = 'on' THEN + IF TG_OP = 'INSERT' THEN + RETURN NEW; + END IF; + IF NEW.position > OLD.position THEN + RETURN NEW; + END IF; + END IF; + RAISE EXCEPTION 'the audit anchor only moves forward, by pruning' + USING ERRCODE = 'integrity_constraint_violation'; +END; +$$; +CREATE TRIGGER audit_anchor_guard + BEFORE INSERT OR UPDATE OR DELETE ON audit_anchor + FOR EACH ROW EXECUTE FUNCTION guard_audit_anchor(); + +-- Each sealed position follows a sealed one, or the anchor, or starts the chain, +-- so no seal leaves a gap or jumps ahead. It runs once the statement has sealed +-- its whole batch, whatever order the rows were updated in. A wrong hash is for +-- verification to find: SQL cannot compute one. +-- +-- Sealing must read committed data, as the sealer does: an older snapshot could +-- still show events a concurrent prune deleted, and seal behind the anchor. Read +-- committed, the check sees every committed prune, and a prune still deleting the +-- position makes the seal wait for it on the unique index first. +CREATE FUNCTION guard_seal_order() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'events are sealed only in read committed transactions' + USING ERRCODE = 'integrity_constraint_violation'; + END IF; + IF NEW.chain_position - 1 = coalesce((SELECT position FROM audit_anchor), 0) + OR EXISTS (SELECT FROM domain_events WHERE chain_position = NEW.chain_position - 1) + THEN + RETURN NULL; + END IF; + RAISE EXCEPTION 'event % cannot be sealed at position %: the position before is not sealed', + NEW.id, NEW.chain_position + USING ERRCODE = 'integrity_constraint_violation'; +END $$; +CREATE TRIGGER domain_events_guard_seal_order + AFTER UPDATE OF chain_position ON domain_events + FOR EACH ROW WHEN (OLD.chain_position IS NULL AND NEW.chain_position IS NOT NULL) + EXECUTE FUNCTION guard_seal_order(); + +-- A checkpoint is of a sealed event's chain hash, and dated at a finite time +-- not in the future: auth cannot read an infinite one back. A minute of leeway +-- covers auth's clock running ahead of the database's. Its note, which auth reads +-- and checks a signature line by line, stays under 1 KiB; auth's are about 300 +-- bytes. +CREATE FUNCTION guard_new_checkpoint() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +BEGIN + IF isfinite(NEW.created_at) AND octet_length(NEW.note) <= 1024 + AND NEW.created_at <= clock_timestamp() + INTERVAL '1 minute' AND EXISTS ( + SELECT FROM domain_events WHERE chain_position = NEW.position AND chain_hash = NEW.head + ) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'checkpoint at position % is not of the sealed chain as of now', + NEW.position + USING ERRCODE = 'integrity_constraint_violation'; +END $$; +CREATE TRIGGER audit_checkpoints_guard_insert + BEFORE INSERT ON audit_checkpoints + FOR EACH ROW EXECUTE FUNCTION guard_new_checkpoint(); + +---------------------------------------------------------------------------- +-- Deliveries +---------------------------------------------------------------------------- + +-- The outbound delivery queue: messages for other systems, such as back-channel +-- logout tokens or emails. DatabaseTransaction::record creates them in the +-- transaction of the event that causes them, and workers send them with leases. +-- See docs/dev/architecture/delivery-queue.md. +-- +-- event_id has no foreign key, like domain_events.subject_user_id: audit pruning +-- deletes events, and a delivery must never depend on rows that can change after +-- it is created. destination and recipient copy everything a send needs. +CREATE TABLE deliveries ( + -- Also the delivery's identity for receivers: a jti or Message-ID. + id UUID PRIMARY KEY, + -- The event that caused it, when there is one. + event_id UUID, + channel TEXT NOT NULL, + destination TEXT NOT NULL, + recipient JSONB NOT NULL, + -- Never a plaintext secret. + payload JSONB NOT NULL, + status TEXT NOT NULL CHECK (status IN ('pending', 'succeeded', 'failed', 'cancelled')), + attempts INT NOT NULL DEFAULT 0, + next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- Set by the worker sending it. Only the holder of claim_token records the + -- outcome; cancelling clears it. + claim_token UUID, + leased_until TIMESTAMPTZ, + -- A status code or an error kind, never a response body. + last_error TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- When an operator last retried it; the channel's maximum age counts from here. + retried_at TIMESTAMPTZ, + finished_at TIMESTAMPTZ +); +-- Workers poll for due deliveries. +CREATE INDEX deliveries_due_idx ON deliveries (next_attempt_at) WHERE status = 'pending'; +-- Cleanup finds finished deliveries past their retention. +CREATE INDEX deliveries_finished_idx ON deliveries (finished_at) WHERE status <> 'pending'; +-- A purge deletes the emails and announcements addressed to the account. +CREATE INDEX deliveries_email_recipient_idx ON deliveries (recipient) + WHERE channel = 'email'; +CREATE INDEX deliveries_announcement_recipient_idx ON deliveries (recipient) + WHERE channel = 'announcement'; +-- The dashboard counts an announcement's emails by status while the queue keeps +-- them: their payload is the announcement's ID. +CREATE INDEX deliveries_announcement_idx ON deliveries (payload) + WHERE channel = 'announcement'; + +---------------------------------------------------------------------------- +-- Notifications and announcements +---------------------------------------------------------------------------- + +-- What each account's owner is told about their account, in their settings +-- inbox. A notification is written in the transaction of the event it comes +-- from, if any, and holds no personal data: it renders from its payload alone, +-- so it outlives its event's personal data and the event itself, which audit +-- pruning may delete. `event_id` is no foreign key for that reason. Purging the +-- account deletes its notifications with it. +CREATE TABLE notifications ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + event_id UUID, + payload JSONB NOT NULL CHECK (jsonb_typeof(payload -> 'kind') = 'string'), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + read_at TIMESTAMPTZ, + -- When the "sign me out everywhere" link of its email was used. The link + -- works once, within 7 days of the notification. + signed_out_at TIMESTAMPTZ +); +-- The inbox, newest first. Notifications written in one transaction share +-- `now()`, so pages continue after `(created_at, id)`. +CREATE INDEX notifications_inbox_idx ON notifications (user_id, created_at DESC, id DESC); +-- The unread count every settings page shows. +CREATE INDEX notifications_unread_idx ON notifications (user_id) WHERE read_at IS NULL; +-- Cleanup deletes notifications a year after they arrive. +CREATE INDEX notifications_created_idx ON notifications (created_at); +-- How many of an announcement's recipients read it, which its page shows. +CREATE INDEX notifications_announcement_idx ON notifications ((payload ->> 'announcement_id')) + WHERE payload ->> 'kind' = 'announcement'; + +-- Whether each account receives a category of notifications by email. Only +-- categories whose email the owner may turn off have rows, and no row means +-- the category's default: everything about the account itself is always +-- emailed. Deleting an account deletes its rows. +CREATE TABLE notification_preferences ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + category TEXT NOT NULL CHECK (category IN ('announcements')), + email BOOLEAN NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, category) +); + +-- Announcements administrators send to accounts, such as a security incident or +-- a change to the privacy policy: emailed to each recipient's primary verified +-- address, and written to each recipient's inbox as a notification. +-- +-- An announcement is a draft until it is sent, and only a draft changes. Its +-- text is written for everyone it goes to, so it is no one's personal data, +-- except that an announcement to chosen accounts may concern them: a purge +-- deletes it with its last recipient. +CREATE TABLE announcements ( + id UUID PRIMARY KEY, + subject TEXT NOT NULL CHECK (subject <> ''), + body TEXT NOT NULL CHECK (body <> ''), + -- Whether it goes to every account, rather than to the chosen ones. + everyone BOOLEAN NOT NULL, + -- Counts the draft's changes. Sending names the revision that was checked, + -- so a change made meanwhile is checked again before anything is sent. + revision BIGINT NOT NULL DEFAULT 1, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + sent_at TIMESTAMPTZ, + -- An essential announcement, such as a security incident or a change to the + -- privacy policy or terms, is emailed to every recipient whatever their + -- preference. Its sender chooses so on the draft. + essential BOOLEAN NOT NULL DEFAULT false +); +CREATE INDEX announcements_recent_idx ON announcements (created_at DESC, id DESC); + +-- What was sent stays as it was sent: the audit history names the announcement, +-- not its text. +CREATE FUNCTION guard_sent_announcement() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ +BEGIN + RAISE EXCEPTION 'announcement % was sent, so it can no longer change', OLD.id + USING ERRCODE = 'integrity_constraint_violation'; +END $$; +CREATE TRIGGER announcements_sent_unchanged + BEFORE UPDATE ON announcements + FOR EACH ROW WHEN (OLD.sent_at IS NOT NULL) + EXECUTE FUNCTION guard_sent_announcement(); + +-- The accounts an announcement goes to: the chosen ones from the draft on, or +-- every account, added when it is sent. Accounts created later never get it. +-- Deleting an account deletes its rows. +CREATE TABLE announcement_recipients ( + announcement_id UUID NOT NULL REFERENCES announcements(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (announcement_id, user_id) +); +-- A purge finds the announcements an account received, and the cascade its rows. +CREATE INDEX announcement_recipients_user_idx ON announcement_recipients (user_id); + +-- Whether `account` receives announcements that are not essential by email: +-- unless its owner turned them off. +CREATE FUNCTION announcements_emailed(account UUID) RETURNS BOOLEAN +LANGUAGE sql STABLE SET search_path = pg_catalog, public, pg_temp AS $$ + SELECT NOT EXISTS ( + SELECT FROM notification_preferences p + WHERE p.user_id = account AND p.category = 'announcements' AND NOT p.email + ) +$$; + +---------------------------------------------------------------------------- +-- Alerts +---------------------------------------------------------------------------- + +-- What needs an administrator's attention, such as a broken audit chain: a +-- condition auth found, which concerns no account. An alert is current from when +-- it is raised until its condition clears, and open until then too, unless an +-- administrator acknowledges it first: auth then raises it again only once its +-- condition clears or changes. At most one alert of each kind is current. Like +-- an event's payload, it holds no personal data, and its events tell who +-- acknowledged it. +CREATE TABLE alerts ( + id UUID PRIMARY KEY, + payload JSONB NOT NULL CHECK (jsonb_typeof(payload -> 'kind') = 'string'), + -- The payload's version, as an event's: a release reads one it does not + -- write as an alert it cannot show. + version SMALLINT NOT NULL, + raised_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- When auth last found its condition holding. + seen_at TIMESTAMPTZ NOT NULL DEFAULT now(), + acknowledged_at TIMESTAMPTZ, + cleared_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX alerts_current_idx ON alerts ((payload ->> 'kind')) WHERE cleared_at IS NULL; + +-- What administrators post on an alert while they handle it: where its handling +-- stands. The first acknowledges the alert, which then needs no attention while +-- its condition holds as it says. The author is the administrator or operator, as +-- an event's actor. Each update records an `alert_updated` event, `event_id`, +-- whose reason holds its note: the note is personal data, deleted with the +-- event's after 90 days or when its author's account is purged. No foreign key +-- holds `event_id`, since pruning the audit chain deletes events, and the update +-- outlives its event. An update is stamped when it is written, after its alert's +-- row is locked, not when its transaction began: updates sort in the order they +-- were posted even when their transactions overlap. +CREATE TABLE alert_updates ( + id UUID PRIMARY KEY, + alert_id UUID NOT NULL REFERENCES alerts(id) ON DELETE CASCADE, + status TEXT NOT NULL CHECK (status IN ('investigating', 'fixing', 'monitoring')), + event_id UUID NOT NULL UNIQUE, + author JSONB NOT NULL CHECK (author ->> 'type' IN ('admin', 'cli')), + posted_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); +-- An alert's updates, oldest first. +CREATE INDEX alert_updates_alert_idx ON alert_updates (alert_id, posted_at, id); + +---------------------------------------------------------------------------- +-- Admin dashboard sign-ins +---------------------------------------------------------------------------- + +-- Sign-ins to the admin dashboard, which auth serves on its admin listener. An +-- administrator's passkey session on auth hands off to the dashboard with a +-- single-use code, which the dashboard redeems for a session of its own. Only +-- digests of the code and of the dashboard's cookies are stored. +CREATE TABLE dashboard_handoffs ( + code_digest BYTEA PRIMARY KEY, + -- The auth session handing off, whose sign-in the dashboard session rests on. + session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + -- The digest of the dashboard's state cookie in the browser that asked, which + -- must present it to redeem the code. + state_digest BYTEA NOT NULL, + -- The dashboard path the browser goes on to once signed in. + return_to TEXT NOT NULL, + -- When a passkey confirmed the handoff, in a ceremony started for it. + confirmed_at TIMESTAMPTZ, + expires_at TIMESTAMPTZ NOT NULL +); +CREATE INDEX dashboard_handoffs_session_idx ON dashboard_handoffs (session_id); + +-- The dashboard's own sessions. Each lasts while its auth session does, and +-- keeps its own passkey confirmation: one done for auth's pages never counts. +-- It also ends after 30 minutes without a request, and 12 hours after its +-- sign-in however busy, so an unattended browser or a stolen cookie stops +-- working within a working day. Auth sets `expires_at` on each sign-in, and +-- refreshes `last_used_at` on each request. +CREATE TABLE dashboard_sessions ( + secret_digest BYTEA PRIMARY KEY, + session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + confirmed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + last_used_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL +); +CREATE INDEX dashboard_sessions_session_idx ON dashboard_sessions (session_id); +-- Cleanup deletes the sessions that ended. +CREATE INDEX dashboard_sessions_expires_idx ON dashboard_sessions (expires_at); + +---------------------------------------------------------------------------- +-- Function search paths +---------------------------------------------------------------------------- + +-- These functions look tables up in the schema this migration runs in, with +-- pg_temp last: public when deployed, a test's own schema in tests. The others +-- pin their search path above. +DO $$ +DECLARE + guard TEXT; +BEGIN + FOREACH guard IN ARRAY ARRAY[ + 'guard_personal_data_insert', 'guard_seal_order', 'guard_new_checkpoint', + 'limit_passkeys' + ] LOOP + EXECUTE format( + 'ALTER FUNCTION %I() SET search_path = pg_catalog, %I, pg_temp', + guard, current_schema() + ); + END LOOP; +END $$; diff --git a/crates/database/migrations/0002_refresh_family_authorization_code.sql b/crates/database/migrations/0002_refresh_family_authorization_code.sql deleted file mode 100644 index 09a0c82fe..000000000 --- a/crates/database/migrations/0002_refresh_family_authorization_code.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Links each refresh family to the authorization code it was redeemed from, so --- redeeming that code again revokes the family (RFC 6749 section 4.1.2). --- Families created before this migration have no link. Cleanup keeps a redeemed --- code while a family it produced can still refresh; purging it afterwards --- clears the link rather than failing on it. -ALTER TABLE refresh_token_families - ADD COLUMN authorization_code_id UUID REFERENCES authorization_codes(id) ON DELETE SET NULL; --- Serves replay revocation, cleanup's live-family check and the ON DELETE SET --- NULL lookup when codes are purged. -CREATE INDEX refresh_families_authorization_code_idx ON refresh_token_families (authorization_code_id); --- Lets cleanup find redeemed codes past their grace period without a full scan. -CREATE INDEX authorization_codes_consumed_idx ON authorization_codes (consumed_at) WHERE consumed_at IS NOT NULL; diff --git a/crates/database/migrations/0003_session_passkey_confirmation.sql b/crates/database/migrations/0003_session_passkey_confirmation.sql deleted file mode 100644 index a7b7e3e1d..000000000 --- a/crates/database/migrations/0003_session_passkey_confirmation.sql +++ /dev/null @@ -1,7 +0,0 @@ --- Replaces the explicit two-minute management window with the time the session --- last proved possession of a passkey. Each protected action states the maximum --- age it accepts. Open windows lasted two minutes, so none are carried over. -ALTER TABLE sessions DROP COLUMN management_expires_at; -ALTER TABLE sessions ADD COLUMN passkey_confirmed_at TIMESTAMPTZ; --- The audited event is the same passkey proof under its new name. -UPDATE security_audit_log SET action = 'session.passkey_confirmed' WHERE action = 'settings.unlock'; diff --git a/crates/database/migrations/0004_authentication_claims.sql b/crates/database/migrations/0004_authentication_claims.sql deleted file mode 100644 index 5fa4b88bc..000000000 --- a/crates/database/migrations/0004_authentication_claims.sql +++ /dev/null @@ -1,53 +0,0 @@ --- Tokens report how and when the session behind a grant authenticated: `acr`, --- `amr` and `auth_time`, derived from the session. Codes and refresh families --- keep the values from when the code was issued, so later re-authentication of --- the session never changes what an existing grant reports (OIDC Core 12.2). - --- The class the client asked for with `acr_values`, if it named a known one. -ALTER TABLE authorization_requests ADD COLUMN target_acr TEXT; - --- `SessionAuthentication` as JSON: `acr`, `auth_time` and `amr`. -ALTER TABLE authorization_codes ADD COLUMN authentication JSONB; -ALTER TABLE refresh_token_families ADD COLUMN authentication JSONB; - --- Existing grants keep reporting their session's sign-in, as they did before: its --- time and methods. A passkey confirmation may postdate the grant, so it is --- ignored, and the class follows the sign-in method. -CREATE FUNCTION pg_temp.sign_in_authentication(s sessions) RETURNS JSONB LANGUAGE SQL AS $$ - SELECT jsonb_build_object( - 'acr', CASE WHEN s.authentication_methods ? 'passkey' THEN 'phr' ELSE 'urn:sourceorigin:acr:social' END, - 'auth_time', to_jsonb(s.authenticated_at), - 'amr', ( - SELECT COALESCE(jsonb_agg(DISTINCT amr.value), '[]'::jsonb) - FROM jsonb_array_elements_text(s.authentication_methods) AS method(name), - LATERAL jsonb_array_elements_text( - CASE method.name WHEN 'passkey' THEN '["pop", "mfa", "user"]' ELSE '["fed"]' END::jsonb - ) AS amr(value) - ) - ) -$$; -UPDATE authorization_codes c -SET authentication = pg_temp.sign_in_authentication(s) -FROM sessions s -WHERE s.id = c.session_id; -UPDATE refresh_token_families f -SET authentication = pg_temp.sign_in_authentication(s) -FROM sessions s -WHERE s.id = f.session_id; - -ALTER TABLE authorization_codes ALTER COLUMN authentication SET NOT NULL; -ALTER TABLE refresh_token_families ALTER COLUMN authentication SET NOT NULL; - --- A session is phishing-resistant exactly when it has a passkey confirmation, and --- then lists passkeys among its methods. Passkey sessions from before 0003 have no --- confirmation, though their sign-in was one, and confirmations made before this --- migration did not record the method. -UPDATE sessions -SET passkey_confirmed_at = authenticated_at -WHERE passkey_confirmed_at IS NULL -AND authentication_methods ? 'passkey' -AND revoked_at IS NULL; -UPDATE sessions -SET authentication_methods = authentication_methods || '["passkey"]' -WHERE passkey_confirmed_at IS NOT NULL -AND NOT authentication_methods ? 'passkey'; diff --git a/crates/database/migrations/0005_domain_events.sql b/crates/database/migrations/0005_domain_events.sql deleted file mode 100644 index 4decbf1c5..000000000 --- a/crates/database/migrations/0005_domain_events.sql +++ /dev/null @@ -1,65 +0,0 @@ --- Replaces the free-form security audit log with typed domain events. --- --- domain_events holds only non-identifying content: the event kind and payload, --- its actor, and the subject, client and session it concerns. Anything that --- identifies a person outside auth (client IP, user agent family, and every --- Personal value of the payload) lives in event_personal_data, which retention --- and account purges delete without touching the event. --- --- subject_user_id has no foreign key: history outlives the account it describes. -CREATE TABLE domain_events ( - id UUID PRIMARY KEY, - txid XID8 NOT NULL DEFAULT pg_current_xact_id(), - sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, - occurred_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - kind TEXT NOT NULL, - version SMALLINT NOT NULL, - payload JSONB NOT NULL, - actor JSONB NOT NULL, - subject_user_id UUID, - client_id TEXT, - session_id UUID, - -- Filled once requests carry a trace ID. - trace_id TEXT -); -CREATE INDEX domain_events_subject_idx ON domain_events (subject_user_id, sequence DESC); --- Consumers read in (txid, sequence) order; see EventRepository::read_after. -CREATE INDEX domain_events_cursor_idx ON domain_events (txid, sequence); - --- details maps the JSON pointer of each Personal payload value to that value. -CREATE TABLE event_personal_data ( - event_id UUID PRIMARY KEY REFERENCES domain_events(id) ON DELETE CASCADE, - client_ip INET, - user_agent_family TEXT, - details JSONB NOT NULL DEFAULT '{}', - created_at TIMESTAMPTZ NOT NULL DEFAULT now() -); --- Lets cleanup find personal data past its retention without a full scan. -CREATE INDEX event_personal_data_created_idx ON event_personal_data (created_at); - --- How far each named consumer has read. -CREATE TABLE event_consumers ( - name TEXT PRIMARY KEY, - txid XID8 NOT NULL, - sequence BIGINT NOT NULL -); - --- Existing audit rows become imported events with the same IDs, oldest first, --- keeping their action, outcome and metadata verbatim. The metadata holds only --- provider names, which are not personal data. The log never recorded who acted. --- --- PENDING CONTRACT: security_audit_log stays, because the previous release writes to --- it until this one replaces it. Once no deployed release writes to it, a new --- migration must import the rows written since, skipping IDs already in --- domain_events, then DROP TABLE security_audit_log. -INSERT INTO domain_events (id, occurred_at, kind, version, payload, actor, subject_user_id) -SELECT - id, - created_at, - 'imported', - 1, - jsonb_build_object('action', action, 'outcome', outcome, 'metadata', request_metadata), - '{"type": "unrecorded"}', - user_id -FROM security_audit_log -ORDER BY created_at, id; diff --git a/crates/database/migrations/0006_deliveries.sql b/crates/database/migrations/0006_deliveries.sql deleted file mode 100644 index 1f0eec958..000000000 --- a/crates/database/migrations/0006_deliveries.sql +++ /dev/null @@ -1,49 +0,0 @@ --- The outbound delivery queue: messages for other systems, such as back-channel --- logout tokens or SCIM requests. DatabaseTransaction::record creates them in the --- transaction of the event that causes them, and workers send them with leases. --- See docs/architecture/delivery-queue.md. --- --- event_id has no foreign key, like domain_events.subject_user_id: nothing deletes --- events, and a delivery must never depend on rows that can change after it is --- created. destination and recipient copy everything a send needs. -CREATE TABLE deliveries ( - -- Also the delivery's identity for receivers: a jti or Message-ID. - id UUID PRIMARY KEY, - -- The event that caused it, when there is one. - event_id UUID, - channel TEXT NOT NULL, - destination TEXT NOT NULL, - recipient JSONB NOT NULL, - -- Deliveries sharing a key are sent one at a time, in ordinal order. NULL is unordered. - ordering_key TEXT, - ordinal BIGINT, - -- Never a plaintext secret. - payload JSONB NOT NULL, - status TEXT NOT NULL CHECK (status IN ('pending', 'succeeded', 'failed', 'cancelled')), - attempts INT NOT NULL DEFAULT 0, - next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(), - -- Set by the worker sending it. Only the holder of claim_token records the outcome. - -- Cancelling clears claim_token but keeps leased_until, so an attempt in progress - -- holds back the deliveries ordered after it until its lease expires. - claim_token UUID, - leased_until TIMESTAMPTZ, - -- A status code or an error kind, never a response body. - last_error TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - -- When an operator last retried it; the channel's maximum age counts from here. - retried_at TIMESTAMPTZ, - finished_at TIMESTAMPTZ, - UNIQUE (ordering_key, ordinal), - CHECK ((ordering_key IS NULL) = (ordinal IS NULL)) -); --- Workers poll for due deliveries. -CREATE INDEX deliveries_due_idx ON deliveries (next_attempt_at) WHERE status = 'pending'; --- Cleanup finds finished deliveries past their retention. -CREATE INDEX deliveries_finished_idx ON deliveries (finished_at) WHERE status <> 'pending'; - --- The next ordinal of each ordering key. Taking one locks the row until commit, so --- ordinals follow commit order. -CREATE TABLE delivery_orderings ( - ordering_key TEXT PRIMARY KEY, - next_ordinal BIGINT NOT NULL -); diff --git a/crates/database/migrations/0007_administrators.sql b/crates/database/migrations/0007_administrators.sql deleted file mode 100644 index a937a88e5..000000000 --- a/crates/database/migrations/0007_administrators.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Administrator accounts. A separate table, rather than a role column, keeps --- administrator rights out of tokens and out of a future groups model. Who --- granted the rights is recorded by the AdministratorGranted event. -CREATE TABLE administrators ( - user_id UUID PRIMARY KEY REFERENCES users(id), - granted_at TIMESTAMPTZ NOT NULL DEFAULT now() -); - --- Invitations gain an ID, so administrators can list and revoke them without --- knowing their secret. The default fills existing rows and keeps the previous --- release's inserts working; the service passes its own IDs. A revoked --- invitation can no longer be redeemed. -ALTER TABLE invitations - ADD COLUMN id UUID NOT NULL DEFAULT uuidv7(), - ADD COLUMN revoked_at TIMESTAMPTZ; -ALTER TABLE invitations DROP CONSTRAINT invitations_pkey; -ALTER TABLE invitations ADD PRIMARY KEY (id); -ALTER TABLE invitations ADD CONSTRAINT invitations_secret_digest_key UNIQUE (secret_digest); diff --git a/crates/database/migrations/0008_oidc_client_registry.sql b/crates/database/migrations/0008_oidc_client_registry.sql deleted file mode 100644 index d5b1f079a..000000000 --- a/crates/database/migrations/0008_oidc_client_registry.sql +++ /dev/null @@ -1,82 +0,0 @@ --- OIDC clients live in the database instead of AUTH_CLIENTS_FILE, so operators --- change them at runtime with `auth-service client`. --- --- A client may hold several secrets at once: rotating one caps the expiry of the --- previous secrets, so the client keeps working while it redeploys. Only SHA-256 --- digests are stored; auth generates every secret with 256 random bits. -CREATE TABLE oidc_client_secrets ( - id UUID PRIMARY KEY, - client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, - secret_digest BYTEA NOT NULL CHECK (octet_length(secret_digest) = 32), - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - -- NULL until a rotation sets it on the previous secrets. - expires_at TIMESTAMPTZ -); -CREATE INDEX oidc_client_secrets_client_idx ON oidc_client_secrets (client_id); - --- The client type is explicit instead of "has a secret hash". -ALTER TABLE oidc_clients - ADD COLUMN client_type TEXT NOT NULL DEFAULT 'public' - CHECK (client_type IN ('public', 'confidential')), - ADD COLUMN updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); - -UPDATE oidc_clients SET client_type = 'confidential' WHERE client_secret_hash IS NOT NULL; -INSERT INTO oidc_client_secrets (id, client_id, secret_digest, created_at) -SELECT uuidv7(), id, client_secret_hash, created_at -FROM oidc_clients -WHERE client_secret_hash IS NOT NULL; - --- The previous release keeps writing client_secret_hash directly while it runs: --- at startup it registers its file's clients, and an old replica may restart during --- a deploy or after a rollback. Mirror those writes, so the new release never takes --- a confidential client for a public one. Auth's own writes insert the secret row in --- the same statement, so they match a current secret and change nothing here. A --- legacy write of any other hash, even one that expired, as when a rollback restores --- an older clients file, replaces the previous secrets at once, as it used to: both --- releases then accept the same secret. --- A legacy write that clears the hash changes nothing: the client stays --- confidential, and fails closed. -CREATE FUNCTION oidc_clients_mirror_legacy_secret() RETURNS trigger -LANGUAGE plpgsql AS $$ -BEGIN - IF NOT EXISTS ( - SELECT 1 FROM oidc_client_secrets - WHERE client_id = NEW.id - AND secret_digest = NEW.client_secret_hash - AND expires_at IS NULL - ) THEN - UPDATE oidc_clients SET client_type = 'confidential' WHERE id = NEW.id; - UPDATE oidc_client_secrets SET expires_at = now() - WHERE client_id = NEW.id AND (expires_at IS NULL OR expires_at > now()); - INSERT INTO oidc_client_secrets (id, client_id, secret_digest) - VALUES (uuidv7(), NEW.id, NEW.client_secret_hash); - END IF; - RETURN NULL; -END -$$; -CREATE TRIGGER oidc_clients_mirror_legacy_secret -AFTER INSERT OR UPDATE OF client_secret_hash ON oidc_clients -FOR EACH ROW WHEN (NEW.client_secret_hash IS NOT NULL) -EXECUTE FUNCTION oidc_clients_mirror_legacy_secret(); - --- The origin of each redirect URI, as browsers send it in an Origin header. A --- public client's authorization redirect origins may call the token and UserInfo --- endpoints, which look them up per request. Auth computes it on write. Existing --- rows, and rows the previous release writes, have none: `auth-service migrate` --- fills them in after the migrations, with the URL parser browsers' origins follow --- (`OidcRepository::fill_redirect_origins`), which SQL cannot reproduce. -ALTER TABLE oidc_redirect_uris ADD COLUMN origin TEXT; -CREATE INDEX oidc_redirect_uris_origin_idx ON oidc_redirect_uris (origin) - WHERE kind = 'authorization'; - --- The previous release still disables every client it does not find in its --- AUTH_CLIENTS_FILE whenever it starts, and writes back its file's settings and --- secrets. Register or change clients with the new release only once no previous --- replica can restart, and re-enable them after a rollback. --- --- PENDING CONTRACT: oidc_clients.client_secret_hash stays, and auth keeps it equal --- to a confidential client's newest secret, because the previous release --- authenticates clients with it, and would take a confidential client without it --- for a public one. Once no deployed release reads or writes it, a new migration --- must drop the oidc_clients_mirror_legacy_secret trigger and function, DROP COLUMN --- client_secret_hash, and make oidc_redirect_uris.origin NOT NULL. diff --git a/crates/database/migrations/0009_pushed_authorization_requests.sql b/crates/database/migrations/0009_pushed_authorization_requests.sql deleted file mode 100644 index 038c0eee4..000000000 --- a/crates/database/migrations/0009_pushed_authorization_requests.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Pushed authorization requests (RFC 9126). A client stores its request through --- the back channel, then the browser claims it once with the returned --- request_uri. A pushed row is not a pending authorization until it is claimed: --- claiming replaces its secret, so the request_uri itself never continues one. --- The previous release does not know the flag, and would take an unclaimed --- pushed request_uri as a transaction; it only learns one from a client that --- already holds it, so this needs no extra step during the deploy. -ALTER TABLE authorization_requests - ADD COLUMN pushed BOOLEAN NOT NULL DEFAULT FALSE, - ADD COLUMN claimed_at TIMESTAMPTZ, - -- `prompt=none`, kept so a pushed request answers silently when claimed. - ADD COLUMN prompt_none BOOLEAN NOT NULL DEFAULT FALSE; - --- Clients that may start an authorization only from a pushed request. -ALTER TABLE oidc_clients - ADD COLUMN require_pushed_authorization_requests BOOLEAN NOT NULL DEFAULT FALSE; diff --git a/crates/database/migrations/0010_session_devices.sql b/crates/database/migrations/0010_session_devices.sql deleted file mode 100644 index 773f4d31d..000000000 --- a/crates/database/migrations/0010_session_devices.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Where each session signed in from and was last seen, for the account's list of --- signed-in devices. The IPs live only as long as the session row. The existing --- user_agent_family column now holds the coarse browser and platform as --- `browser/platform`, e.g. `firefox/linux`; no release wrote it before. -ALTER TABLE sessions - ADD COLUMN created_ip INET, - ADD COLUMN last_seen_ip INET; - --- The platform half of an event's user agent family. user_agent_family keeps only --- the browser, the one value previous releases read there. -ALTER TABLE event_personal_data ADD COLUMN platform TEXT; diff --git a/crates/database/migrations/0011_pin_function_search_path.sql b/crates/database/migrations/0011_pin_function_search_path.sql deleted file mode 100644 index 01e48403e..000000000 --- a/crates/database/migrations/0011_pin_function_search_path.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Functions run with the caller's search_path, which looks in pg_temp first unless --- it lists it. auth's runtime role may create temporary tables, so a temporary --- `users` could shadow the table these triggers read. Each function pins its own --- path, which a session cannot override, with pg_temp last. -ALTER FUNCTION claim_active_verified_email() SET search_path = pg_catalog, public, pg_temp; -ALTER FUNCTION release_active_verified_email() SET search_path = pg_catalog, public, pg_temp; -ALTER FUNCTION synchronize_user_email_ownership() SET search_path = pg_catalog, public, pg_temp; -ALTER FUNCTION enforce_primary_verified_email() SET search_path = pg_catalog, public, pg_temp; -ALTER FUNCTION oidc_clients_mirror_legacy_secret() SET search_path = pg_catalog, public, pg_temp; diff --git a/crates/database/migrations/0012_client_owners.sql b/crates/database/migrations/0012_client_owners.sql deleted file mode 100644 index 8f76bdb35..000000000 --- a/crates/database/migrations/0012_client_owners.sql +++ /dev/null @@ -1,40 +0,0 @@ --- Clients an account registers and manages through the account API (#43). --- --- owner_id is NULL for clients operators manage with `auth-service client`; the --- account API never shows those. created_via records which path registered the --- client; 'registration' is reserved for dynamic client registration (#44). --- --- Deletion is a tombstone: the row stays, so its ID, which tokens carry as `aud`, --- is never reused, and cleanup never deletes it. A tombstone is always disabled, --- so no path can bring it back; the previous release, which never deletes, could --- violate the check only by enabling a client this release deleted. --- --- A suspension is an operator's block: the client is disabled, and its owner --- cannot enable it until an operator lifts the suspension. Like a tombstone, a --- suspended client is always disabled, so the previous release, which does not --- know suspensions, still refuses it, and cannot enable it. --- --- Purging an account keeps its clients' tombstones, without their owner. Its live --- clients must be deleted first: the owner check refuses to turn them into clients --- no account manages. --- --- last_used_at moves at most once an hour, when a token is issued to the client. -ALTER TABLE oidc_clients - ADD COLUMN owner_id UUID REFERENCES users(id) ON DELETE SET NULL, - ADD COLUMN created_via TEXT NOT NULL DEFAULT 'cli' - CHECK (created_via IN ('cli', 'account', 'registration')), - ADD COLUMN deleted_at TIMESTAMPTZ, - ADD COLUMN suspended_at TIMESTAMPTZ, - ADD COLUMN last_used_at TIMESTAMPTZ, - ADD CONSTRAINT oidc_clients_tombstone_disabled CHECK (deleted_at IS NULL OR NOT enabled), - ADD CONSTRAINT oidc_clients_suspended_disabled CHECK (suspended_at IS NULL OR NOT enabled), - ADD CONSTRAINT oidc_clients_owned_until_deleted - CHECK (created_via <> 'account' OR owner_id IS NOT NULL OR deleted_at IS NOT NULL); - --- Counts an owner's live clients for the quota, and the clients, deleted or not, --- they registered recently for the daily registration limit. -CREATE INDEX oidc_clients_owner_idx ON oidc_clients (owner_id, created_at); - --- A deletion locks, then revokes, the client's live families. -CREATE INDEX refresh_families_active_client_idx ON refresh_token_families (client_id) - WHERE revoked_at IS NULL; diff --git a/crates/database/migrations/0013_backchannel_logout.sql b/crates/database/migrations/0013_backchannel_logout.sql deleted file mode 100644 index f6b61c338..000000000 --- a/crates/database/migrations/0013_backchannel_logout.sql +++ /dev/null @@ -1,55 +0,0 @@ --- OIDC Back-Channel Logout 1.0: when a session ends, auth posts a logout token to --- the back-channel logout URI of every client that received tokens from it. - --- NULL for clients that are not told. -ALTER TABLE oidc_clients ADD COLUMN backchannel_logout_uri TEXT; - --- Which clients received tokens from which session. -CREATE TABLE oidc_session_clients ( - session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, - client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, - first_issued_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY (session_id, client_id) -); - --- Every redeemed code records its client, whichever release redeems it: the --- previous one during a deploy or after a rollback too. An exchange that fails --- rolls back the redemption, so only clients that received tokens are recorded. --- It runs as its owner: `migrate` grants the runtime role this table only after --- the migrations, and the previous release keeps redeeming codes meanwhile. No one --- else may execute it: on a temporary table of its own, with a type whose cast to --- uuid it wrote, the runtime role would run that cast as the owner. A trigger --- already attached still fires. -CREATE FUNCTION oidc_session_clients_record_redeemed_code() RETURNS trigger -LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - INSERT INTO oidc_session_clients (session_id, client_id) - VALUES (NEW.session_id, NEW.client_id) - ON CONFLICT DO NOTHING; - RETURN NULL; -END -$$; -REVOKE ALL ON FUNCTION oidc_session_clients_record_redeemed_code() FROM PUBLIC; -CREATE TRIGGER authorization_codes_record_session_client -AFTER UPDATE OF consumed_at ON authorization_codes -FOR EACH ROW WHEN (OLD.consumed_at IS NULL AND NEW.consumed_at IS NOT NULL) -EXECUTE FUNCTION oidc_session_clients_record_redeemed_code(); - --- Live sessions that already redeemed codes: every redeemed code cleanup still --- keeps, and every refresh family, records one. A session that only redeemed codes --- cleanup has deleted, without refresh, is not found. -INSERT INTO oidc_session_clients (session_id, client_id, first_issued_at) -SELECT issued.session_id, issued.client_id, min(issued.created_at) -FROM ( - SELECT session_id, client_id, created_at FROM refresh_token_families - UNION ALL - SELECT session_id, client_id, created_at FROM authorization_codes - WHERE consumed_at IS NOT NULL -) issued -JOIN sessions s ON s.id = issued.session_id -WHERE s.revoked_at IS NULL AND s.expires_at > now() -GROUP BY issued.session_id, issued.client_id; - --- Still untold: sessions the previous release ends during a deploy or after a --- rollback, since it queues no logout tokens, and logout tokens still queued at a --- rollback, which are sent only if this release returns within their hour. diff --git a/crates/database/migrations/0014_email_verification.sql b/crates/database/migrations/0014_email_verification.sql deleted file mode 100644 index 8b81dd3f7..000000000 --- a/crates/database/migrations/0014_email_verification.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Users add their own email addresses, which stay unverified until someone --- follows the link sent to them. Auth derives the link's token from the address's --- ID with a server key, so the token itself is stored nowhere: only its SHA-256 --- digest, to look the address up. Verifying deletes the row; cleanup deletes --- expired rows together with the unverified addresses they belong to. -CREATE TABLE email_verification_secrets ( - email_id UUID PRIMARY KEY REFERENCES user_emails(id) ON DELETE CASCADE, - secret_digest BYTEA NOT NULL UNIQUE CHECK (octet_length(secret_digest) = 32), - expires_at TIMESTAMPTZ NOT NULL -); -CREATE INDEX email_verification_secrets_expires_idx ON email_verification_secrets (expires_at); diff --git a/crates/database/migrations/0015_event_reasons.sql b/crates/database/migrations/0015_event_reasons.sql deleted file mode 100644 index 63669a8e4..000000000 --- a/crates/database/migrations/0015_event_reasons.sql +++ /dev/null @@ -1,4 +0,0 @@ --- Why an administrator or operator changed someone's account, as they wrote it. --- Free text may name people, so it is personal data: it lives beside the request --- origin and is deleted with it. -ALTER TABLE event_personal_data ADD COLUMN reason TEXT; diff --git a/crates/database/migrations/0016_session_passkeys.sql b/crates/database/migrations/0016_session_passkeys.sql deleted file mode 100644 index 380222983..000000000 --- a/crates/database/migrations/0016_session_passkeys.sql +++ /dev/null @@ -1,7 +0,0 @@ --- The passkey that last proved possession for each session: the one that signed --- it in, or confirmed it since; NULL for a social sign-in never confirmed, and for --- sessions from before this column until their next passkey sign-in or --- confirmation. Undoing an account recovery needs a session of a passkey enrolled --- before it, so NULL never counts. Not a foreign key: it is only compared with --- passkeys, and a purge may delete either row first. -ALTER TABLE sessions ADD COLUMN passkey_id UUID; diff --git a/crates/database/migrations/0017_signing_keys.sql b/crates/database/migrations/0017_signing_keys.sql deleted file mode 100644 index 0f7440739..000000000 --- a/crates/database/migrations/0017_signing_keys.sql +++ /dev/null @@ -1,33 +0,0 @@ --- Signing keys (#48). Every replica reloads them each minute; one replica at a --- time advances their rotation, under a transaction-level advisory lock that the --- `keys` commands take too. A key is published as `next`, signs as `active`, stays --- published as `retiring`, then verifies only `id_token_hint`s as `retired` until --- it is deleted. Its PKCS#8 private key is sealed with AES-256-GCM under the --- key-encryption key from configuration, with `id || key_type` as associated --- data, and erased once it retires. -CREATE TABLE signing_keys ( - id TEXT PRIMARY KEY CHECK (length(id) BETWEEN 1 AND 128), - key_type TEXT NOT NULL CHECK (key_type IN ('rsa')), - state TEXT NOT NULL CHECK (state IN ('next', 'active', 'retiring', 'retired')), - public_jwk JSONB NOT NULL, - sealed_private_key BYTEA, - created_at TIMESTAMPTZ NOT NULL, - -- When it started signing, stopped signing, and left the key set. - activated_at TIMESTAMPTZ, - deactivated_at TIMESTAMPTZ, - retired_at TIMESTAMPTZ, - CHECK ((state = 'retired') = (sealed_private_key IS NULL)), - CHECK ((state = 'next') = (activated_at IS NULL)), - CHECK ((state IN ('next', 'active')) = (deactivated_at IS NULL)), - CHECK ((state = 'retired') = (retired_at IS NOT NULL)) -); -CREATE UNIQUE INDEX signing_keys_one_active ON signing_keys (key_type) WHERE state = 'active'; -CREATE UNIQUE INDEX signing_keys_one_next ON signing_keys (key_type) WHERE state = 'next'; - --- The fingerprint of the token digest key each stored secret digest was made --- with, so `auth-service keys digest-usage` can tell when no stored digest --- needs an old key. NULL: made before this migration, or by the previous --- release during this deploy, under the key derived from the PEM signing key. -ALTER TABLE authorization_requests ADD COLUMN digest_key TEXT; -ALTER TABLE authorization_codes ADD COLUMN digest_key TEXT; -ALTER TABLE refresh_tokens ADD COLUMN digest_key TEXT; diff --git a/crates/database/migrations/0018_contract_audit_log_and_legacy_secrets.sql b/crates/database/migrations/0018_contract_audit_log_and_legacy_secrets.sql deleted file mode 100644 index e1b06a6e0..000000000 --- a/crates/database/migrations/0018_contract_audit_log_and_legacy_secrets.sql +++ /dev/null @@ -1,33 +0,0 @@ --- Contracts what migrations 0005 (#135) and 0008 (#143) kept for the releases --- before them, which no environment runs anymore. - --- Migration 0005 imported security_audit_log into domain_events, but kept the --- table for the previous release to write to during the deploy. Import what it --- wrote since, as 0005 did, then drop the log. -INSERT INTO domain_events (id, occurred_at, kind, version, payload, actor, subject_user_id) -SELECT - id, - created_at, - 'imported', - 1, - jsonb_build_object('action', action, 'outcome', outcome, 'metadata', request_metadata), - '{"type": "unrecorded"}', - user_id -FROM security_audit_log a -WHERE NOT EXISTS (SELECT 1 FROM domain_events e WHERE e.id = a.id) -ORDER BY created_at, id; -DROP TABLE security_audit_log; - --- Migration 0008 mirrored the previous release's writes to --- oidc_clients.client_secret_hash into oidc_client_secrets. Every deployed release --- writes oidc_client_secrets itself. -DROP TRIGGER oidc_clients_mirror_legacy_secret ON oidc_clients; -DROP FUNCTION oidc_clients_mirror_legacy_secret(); - --- Every deployed release computes a redirect URI's origin on write, and --- `auth-service migrate` filled in the ones from before. -ALTER TABLE oidc_redirect_uris ALTER COLUMN origin SET NOT NULL; - --- PENDING CONTRACT: oidc_clients.client_secret_hash stays, because the previous --- release still writes it, though nothing reads it. Once no deployed release --- writes it, a new migration must DROP COLUMN client_secret_hash. diff --git a/crates/database/migrations/0019_account_recoveries.sql b/crates/database/migrations/0019_account_recoveries.sql deleted file mode 100644 index 1cda5fef6..000000000 --- a/crates/database/migrations/0019_account_recoveries.sql +++ /dev/null @@ -1,107 +0,0 @@ --- Recoveries an operator started for an account whose owner lost their --- passkeys. Each sends its owner a link that enrolls one passkey, once, within a --- day. The link's token is derived from the recovery's ID, so only its digest is --- stored. For 15 days after the link is used, the recovery is in probation: its --- passkey signs in but never confirms a session, and a passkey from before it --- can undo it. -CREATE TABLE account_recoveries ( - id UUID PRIMARY KEY, - user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, - secret_digest BYTEA NOT NULL UNIQUE, - started_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - expires_at TIMESTAMPTZ NOT NULL, - -- When its link enrolled a passkey, which one, and when its probation ends. - -- `settles_at` is computed by auth from its probation length, so SQL never - -- repeats the constant. - completed_at TIMESTAMPTZ, - passkey_id UUID, - settles_at TIMESTAMPTZ, - -- When a newer recovery, the account's disabling or its owner's undo cancelled - -- it before its link was used. - cancelled_at TIMESTAMPTZ, - -- When it was undone after its link was used, by its owner or by support. - undone_at TIMESTAMPTZ, - CHECK ((completed_at IS NULL) = (passkey_id IS NULL)), - CHECK ((completed_at IS NULL) = (settles_at IS NULL)), - CHECK (cancelled_at IS NULL OR (completed_at IS NULL AND undone_at IS NULL)), - CHECK (undone_at IS NULL OR completed_at IS NOT NULL) -); -CREATE INDEX account_recoveries_user_idx ON account_recoveries (user_id, started_at DESC); -CREATE UNIQUE INDEX account_recoveries_passkey_idx ON account_recoveries (passkey_id); --- At most one recovery per account whose link was not used, cancelled or undone. --- An expired one counts until the next start cancels it. -CREATE UNIQUE INDEX account_recoveries_one_open_idx ON account_recoveries (user_id) - WHERE completed_at IS NULL AND cancelled_at IS NULL AND undone_at IS NULL; - --- The account's recovery that can still be undone, if any: its link still works, --- or it is in probation (its rows with `completed_at` set). The one SQL copy of --- auth's `RecoveryState`; only the trigger functions below call it, as their --- owner. -CREATE FUNCTION undoable_recovery(account UUID) RETURNS SETOF account_recoveries -LANGUAGE sql VOLATILE SET search_path = pg_catalog, public, pg_temp AS $$ - SELECT * FROM public.account_recoveries - WHERE user_id = account - AND undone_at IS NULL AND cancelled_at IS NULL - AND (settles_at > clock_timestamp() - OR (completed_at IS NULL AND expires_at > clock_timestamp())) -$$; -REVOKE EXECUTE ON FUNCTION undoable_recovery(UUID) FROM PUBLIC; - --- A probation passkey never confirms a session, whichever release writes it: --- the previous one during a deploy confirms every passkey sign-in, and a --- release rolled back below this one would too. A confirmation that names no --- passkey fails closed while the account is in probation. The trigger functions --- run as their owner, because the previous release fires them before the --- runtime role is granted `account_recoveries`. -CREATE FUNCTION sessions_no_probation_confirmation() RETURNS trigger -LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - IF NEW.passkey_confirmed_at IS NOT NULL AND EXISTS ( - SELECT 1 FROM public.undoable_recovery(NEW.user_id) - WHERE completed_at IS NOT NULL - AND (NEW.passkey_id IS NULL OR passkey_id = NEW.passkey_id) - ) THEN - NEW.passkey_confirmed_at := NULL; - END IF; - RETURN NEW; -END $$; -REVOKE EXECUTE ON FUNCTION sessions_no_probation_confirmation() FROM PUBLIC; -CREATE TRIGGER sessions_no_probation_confirmation - BEFORE INSERT OR UPDATE OF passkey_confirmed_at, passkey_id ON sessions - FOR EACH ROW EXECUTE FUNCTION sessions_no_probation_confirmation(); - --- No account is made an administrator while a recovery of it can be undone: --- the rights would go live for whoever holds its passkey once it settles. -CREATE FUNCTION administrators_no_grant_mid_recovery() RETURNS trigger -LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - IF EXISTS (SELECT 1 FROM public.undoable_recovery(NEW.user_id)) THEN - RAISE EXCEPTION 'account % has a recovery that can still be undone', NEW.user_id - USING ERRCODE = 'check_violation'; - END IF; - RETURN NEW; -END $$; -REVOKE EXECUTE ON FUNCTION administrators_no_grant_mid_recovery() FROM PUBLIC; -CREATE TRIGGER administrators_no_grant_mid_recovery - BEFORE INSERT ON administrators - FOR EACH ROW EXECUTE FUNCTION administrators_no_grant_mid_recovery(); - --- While a recovery can be undone, no passkey but its own is revoked, by anyone, --- so nothing takes away the passkeys that can undo it. -CREATE FUNCTION passkeys_kept_mid_recovery() RETURNS trigger -LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - IF EXISTS ( - SELECT 1 FROM public.undoable_recovery(OLD.user_id) - WHERE passkey_id IS DISTINCT FROM OLD.id - ) THEN - RAISE EXCEPTION 'account % has a recovery that can still be undone', OLD.user_id - USING ERRCODE = 'check_violation'; - END IF; - RETURN NEW; -END $$; -REVOKE EXECUTE ON FUNCTION passkeys_kept_mid_recovery() FROM PUBLIC; -CREATE TRIGGER passkeys_kept_mid_recovery - BEFORE UPDATE OF revoked_at ON passkey_credentials - FOR EACH ROW WHEN (OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL) - EXECUTE FUNCTION passkeys_kept_mid_recovery(); diff --git a/crates/database/migrations/0020_dashboard_sessions.sql b/crates/database/migrations/0020_dashboard_sessions.sql deleted file mode 100644 index 2f03d542e..000000000 --- a/crates/database/migrations/0020_dashboard_sessions.sql +++ /dev/null @@ -1,50 +0,0 @@ --- Sign-ins to the admin dashboard, which auth serves on its admin listener. An --- administrator's passkey session on auth hands off to the dashboard with a --- single-use code, which the dashboard redeems for a session of its own. Only --- digests of the code and of the dashboard's cookies are stored. -CREATE TABLE dashboard_handoffs ( - code_digest BYTEA PRIMARY KEY, - -- The auth session handing off, whose sign-in the dashboard session rests on. - session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, - -- The digest of the dashboard's state cookie in the browser that asked, which - -- must present it to redeem the code. - state_digest BYTEA NOT NULL, - -- The dashboard path the browser goes on to once signed in. - return_to TEXT NOT NULL, - -- When a passkey confirmed the handoff, in a ceremony started for it. - confirmed_at TIMESTAMPTZ, - expires_at TIMESTAMPTZ NOT NULL -); -CREATE INDEX dashboard_handoffs_session_idx ON dashboard_handoffs (session_id); - --- The dashboard's own sessions. Each lasts while its auth session does, and --- keeps its own passkey confirmation: one done for auth's pages never counts. -CREATE TABLE dashboard_sessions ( - secret_digest BYTEA PRIMARY KEY, - session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, - confirmed_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT now() -); -CREATE INDEX dashboard_sessions_session_idx ON dashboard_sessions (session_id); - --- The dashboard was the OIDC client `sourceorigin-admin` until auth served it. It is --- deleted as `auth-service client delete` would, so no deployment keeps it: --- disabled and marked deleted, its secrets and consents removed, and its refresh --- grants revoked. Unlike the command, this records no `client_deleted` event: --- only the service writes events. -WITH client AS ( - UPDATE oidc_clients - SET deleted_at = now(), enabled = FALSE, updated_at = now() - WHERE id = 'sourceorigin-admin' AND deleted_at IS NULL - RETURNING id -), -secrets AS ( - DELETE FROM oidc_client_secrets s USING client WHERE s.client_id = client.id -), -consents AS ( - DELETE FROM oidc_consents c USING client WHERE c.client_id = client.id -) -UPDATE refresh_token_families f -SET revoked_at = now() -FROM client -WHERE f.client_id = client.id AND f.revoked_at IS NULL; diff --git a/crates/database/migrations/0021_handles.sql b/crates/database/migrations/0021_handles.sql deleted file mode 100644 index be6825c4a..000000000 --- a/crates/database/migrations/0021_handles.sql +++ /dev/null @@ -1,57 +0,0 @@ --- Handles replace usernames. One table holds every account's current handle, the --- ones it held before and the ones of purged accounts, so PostgreSQL keeps all of --- them unique, along with their look-alikes. A released row stays forever: only --- its former owner may claim it again, until an operator deletes it. --- --- This drops users.username, which the previous release reads: its replicas fail --- until this release replaces them. Accounts are few and invite-only, and the --- alternative, keeping both columns in sync for a release, would let a signup on --- an old replica create an account without a handle. - --- The confusable skeleton `Handle::skeleton` computes, which a test pins to it: --- hyphens dropped, `0` read as `o`, `1` and `i` as `l`, `5` as `s`, then `rn` as --- `m` and `vv` as `w`. -CREATE FUNCTION handle_skeleton(handle TEXT) RETURNS TEXT - LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE - SET search_path = pg_catalog, public, pg_temp - RETURN replace(replace(translate(handle, '01i5-', 'olls'), 'rn', 'm'), 'vv', 'w'); - --- Every username must already be a valid handle without a look-alike: the previous --- release's `auth-service handle check` lists the ones to rename. -DO $$ -DECLARE offending TEXT; -BEGIN - SELECT string_agg(username, ', ' ORDER BY username) INTO offending - FROM users - WHERE length(username) NOT BETWEEN 3 AND 32 - OR username !~ '^[a-z0-9]+(-[a-z0-9]+)*$' - OR handle_skeleton(username) IN ( - SELECT handle_skeleton(username) FROM users GROUP BY 1 HAVING count(*) > 1 - ); - IF offending IS NOT NULL THEN - RAISE EXCEPTION 'these usernames are not valid, distinct handles: %', offending - USING HINT = 'Rename them with the previous release''s `auth-service handle rename`, ' - 'which `auth-service handle check` guides.'; - END IF; -END $$; - -CREATE TABLE handles ( - handle TEXT PRIMARY KEY - CHECK (length(handle) BETWEEN 3 AND 32 AND handle ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), - skeleton TEXT NOT NULL UNIQUE GENERATED ALWAYS AS (handle_skeleton(handle)) STORED, - -- NULL once the account is purged. - user_id UUID REFERENCES users(id) ON DELETE SET NULL, - claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(), - -- NULL while it is the account's current handle. - released_at TIMESTAMPTZ -); -CREATE UNIQUE INDEX handles_current_idx ON handles (user_id) WHERE released_at IS NULL; - -INSERT INTO handles (handle, user_id, claimed_at) -SELECT username, id, created_at FROM users; - --- When the handle last changed, for the rename cooldown. Reclaiming an old handle --- keeps its row's claimed_at, so the cooldown cannot read that. -ALTER TABLE users ADD COLUMN handle_changed_at TIMESTAMPTZ NOT NULL DEFAULT now(); -UPDATE users SET handle_changed_at = created_at; -ALTER TABLE users DROP COLUMN username; diff --git a/crates/database/migrations/0022_account_deletion.sql b/crates/database/migrations/0022_account_deletion.sql deleted file mode 100644 index 6e621a8dc..000000000 --- a/crates/database/migrations/0022_account_deletion.sql +++ /dev/null @@ -1,71 +0,0 @@ --- Account deletion (#84). A user, administrator or operator schedules it; the --- account then waits in status 'deleting' for its grace period, during which a --- passkey can restore it, and the purge job deletes it once the period ends. --- --- A 'deleting' account keeps its verified emails: the ownership triggers only --- release them for 'disabled', so restoring it can never collide. Deleting the row --- at purge releases them. Its handles stay in `handles` without an owner, as --- migration 0021 has it, so nobody claims them again. --- --- The previous release already reads 'deleting' and the purge job's actor, though --- it never writes them, so it keeps working beside this one and after a rollback. -ALTER TABLE users DROP CONSTRAINT users_status_check, - ADD CONSTRAINT users_status_check CHECK (status IN ('active', 'disabled', 'deleting')); - --- One row per account scheduled for deletion, removed when it is restored or --- purged. A passkey sign-in to the account stores the digest of a single-use, --- short-lived restore token here, with the passkey that signed in; the token --- restores the account and signs in with that passkey. -CREATE TABLE account_deletions ( - user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - requested_at TIMESTAMPTZ NOT NULL DEFAULT now(), - purge_after TIMESTAMPTZ NOT NULL, - restore_token_digest BYTEA UNIQUE CHECK (octet_length(restore_token_digest) = 32), - restore_token_expires_at TIMESTAMPTZ, - restore_passkey_id UUID, - CHECK ((restore_token_digest IS NULL) = (restore_token_expires_at IS NULL)), - CHECK ((restore_token_digest IS NULL) = (restore_passkey_id IS NULL)) -); --- The purge job finds accounts past their grace period. -CREATE INDEX account_deletions_purge_idx ON account_deletions (purge_after); - --- An account that stops being 'deleting' is no longer scheduled, however it left: --- restored, or enabled or disabled by the previous release, which does not know --- the schedule. Otherwise the purge would skip it forever, and it could never be --- scheduled again. -CREATE FUNCTION end_account_deletion() RETURNS TRIGGER -LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - DELETE FROM account_deletions WHERE user_id = NEW.id; - RETURN NULL; -END $$; -CREATE TRIGGER users_end_account_deletion - AFTER UPDATE OF status ON users - FOR EACH ROW WHEN (OLD.status = 'deleting' AND NEW.status <> 'deleting') - EXECUTE FUNCTION end_account_deletion(); - --- An event keeps personal data only while every account it names, as subject or --- actor, exists: a request still in flight when its account is purged must not --- store it again, whichever release recorded it. Each named account is --- key-share locked, which the purge's lock on the account conflicts with: either --- the purge waits, then deletes this row, or this insert waits, finds the account --- gone and is skipped. -CREATE FUNCTION skip_personal_data_of_purged_accounts() RETURNS TRIGGER -LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - IF EXISTS ( - SELECT FROM domain_events e - CROSS JOIN LATERAL ( - VALUES (e.subject_user_id), ((e.actor ->> 'user_id')::uuid) - ) AS named(id) - WHERE e.id = NEW.event_id - AND named.id IS NOT NULL - AND NOT EXISTS (SELECT FROM users WHERE id = named.id FOR KEY SHARE) - ) THEN - RETURN NULL; - END IF; - RETURN NEW; -END $$; -CREATE TRIGGER event_personal_data_skip_purged_accounts - BEFORE INSERT ON event_personal_data - FOR EACH ROW EXECUTE FUNCTION skip_personal_data_of_purged_accounts(); diff --git a/crates/database/migrations/0023_related_origins.sql b/crates/database/migrations/0023_related_origins.sql deleted file mode 100644 index aea93e347..000000000 --- a/crates/database/migrations/0023_related_origins.sql +++ /dev/null @@ -1,35 +0,0 @@ --- Origins whose pages may sign users in with their auth passkeys (WebAuthn --- related origins). `/.well-known/webauthn` lists them, so browsers let those --- pages use auth's RP ID. Only operators approve them: browsers honour few --- distinct domains, and the client must be trusted and have a redirect URI on --- the origin. The origin is written as browsers send it, e.g. https://app.example. -CREATE TABLE client_webauthn_origins ( - origin TEXT PRIMARY KEY, - client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, - approved_at TIMESTAMPTZ NOT NULL DEFAULT now() -); -CREATE INDEX client_webauthn_origins_client_idx ON client_webauthn_origins (client_id); - --- A deleted client's origins go with it, whichever release deleted it: clients --- are tombstoned, so the foreign key never cascades, and the previous release, --- including its account purge, does not know this table. -CREATE FUNCTION remove_deleted_client_origins() RETURNS TRIGGER -LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - DELETE FROM client_webauthn_origins WHERE client_id = NEW.id; - RETURN NULL; -END $$; -CREATE TRIGGER oidc_clients_remove_related_origins - AFTER UPDATE OF deleted_at ON oidc_clients - FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) - EXECUTE FUNCTION remove_deleted_client_origins(); - --- A passkey sign-in on a related origin. It is bound to its origin and the --- pushed authorization request it completes, rather than to a browser cookie. --- The previous release never consumes one: it looks ceremonies up by kind. -ALTER TABLE webauthn_ceremonies DROP CONSTRAINT webauthn_ceremonies_ceremony_kind_check; -ALTER TABLE webauthn_ceremonies ADD CONSTRAINT webauthn_ceremonies_ceremony_kind_check - CHECK (ceremony_kind IN ( - 'registration', 'authentication', 'enrollment', 'purpose_authentication', - 'related_authentication' - )); diff --git a/crates/database/migrations/0024_audit_chain.sql b/crates/database/migrations/0024_audit_chain.sql deleted file mode 100644 index 01aa9356e..000000000 --- a/crates/database/migrations/0024_audit_chain.sql +++ /dev/null @@ -1,97 +0,0 @@ --- Makes the event history tamper-evident: a hash chain over sealed events, and --- signed checkpoints of its head. See docs/security/audit-history.md. --- --- The sealer, one replica at a time, gives each event its chain position and hash --- after its transaction and every older one have finished. Events are inserted --- unsealed, so the previous release keeps writing them unchanged. -ALTER TABLE domain_events - ADD COLUMN chain_position BIGINT UNIQUE CHECK (chain_position > 0), - -- SHA-256(previous chain_hash || SHA-256(canonical event)). - ADD COLUMN chain_hash BYTEA CHECK (octet_length(chain_hash) = 32), - ADD CHECK ((chain_position IS NULL) = (chain_hash IS NULL)); --- The sealer reads unsealed events in consumer order, (txid, sequence). -CREATE INDEX domain_events_unsealed_idx ON domain_events (txid, sequence) - WHERE chain_position IS NULL; - --- Signed checkpoints of the chain head, in the C2SP signed-note format. Never --- pruned: pruned events stay covered by the checkpoints that signed them. -CREATE TABLE audit_checkpoints ( - position BIGINT PRIMARY KEY CHECK (position > 0), - head BYTEA NOT NULL CHECK (octet_length(head) = 32), - created_at TIMESTAMPTZ NOT NULL, - note TEXT NOT NULL -); - --- The checkpoint the chain was last pruned through, if it ever was. The first --- remaining event chains from its head instead of from 32 zero bytes. -CREATE TABLE audit_anchor ( - singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton), - position BIGINT NOT NULL REFERENCES audit_checkpoints (position) -); - --- Guards sealed history: a sealed event is never updated, and only pruning, which --- sets sourceorigin.audit_prune for its transaction, deletes one. Checkpoints are never --- updated or deleted, and neither table is truncated. The runtime role cannot --- drop these triggers, and may update only unsealed events' chain columns (see --- runtime_role.sql); the schema owner can, and the chain is what detects that. -CREATE FUNCTION guard_sealed_events() RETURNS TRIGGER LANGUAGE plpgsql -SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - IF OLD.chain_position IS NULL - OR (TG_OP = 'DELETE' AND current_setting('sourceorigin.audit_prune', true) = 'on') THEN - RETURN CASE TG_OP WHEN 'DELETE' THEN OLD ELSE NEW END; - END IF; - RAISE EXCEPTION 'sealed event at chain position % cannot be changed', OLD.chain_position - USING ERRCODE = 'integrity_constraint_violation'; -END; -$$; - -CREATE TRIGGER domain_events_guard_sealed - BEFORE UPDATE OR DELETE ON domain_events - FOR EACH ROW EXECUTE FUNCTION guard_sealed_events(); - -CREATE FUNCTION refuse_audit_history_change() RETURNS TRIGGER LANGUAGE plpgsql -SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - RAISE EXCEPTION '% on % would change sealed audit history', TG_OP, TG_TABLE_NAME - USING ERRCODE = 'integrity_constraint_violation'; -END; -$$; - -CREATE TRIGGER audit_checkpoints_guard - BEFORE UPDATE OR DELETE ON audit_checkpoints - FOR EACH ROW EXECUTE FUNCTION refuse_audit_history_change(); - --- The anchor moves only forward, and only while pruning, so it cannot hide events --- left at or before it, and concurrent prunes cannot move it back. -CREATE FUNCTION guard_audit_anchor() RETURNS TRIGGER LANGUAGE plpgsql -SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - IF TG_OP <> 'DELETE' AND current_setting('sourceorigin.audit_prune', true) = 'on' THEN - IF TG_OP = 'INSERT' THEN - RETURN NEW; - END IF; - IF NEW.position > OLD.position THEN - RETURN NEW; - END IF; - END IF; - RAISE EXCEPTION 'the audit anchor only moves forward, by pruning' - USING ERRCODE = 'integrity_constraint_violation'; -END; -$$; - -CREATE TRIGGER audit_anchor_guard - BEFORE INSERT OR UPDATE OR DELETE ON audit_anchor - FOR EACH ROW EXECUTE FUNCTION guard_audit_anchor(); - -CREATE TRIGGER audit_anchor_guard_truncate - BEFORE TRUNCATE ON audit_anchor - FOR EACH STATEMENT EXECUTE FUNCTION refuse_audit_history_change(); - -CREATE TRIGGER domain_events_guard_truncate - BEFORE TRUNCATE ON domain_events - FOR EACH STATEMENT EXECUTE FUNCTION refuse_audit_history_change(); - -CREATE TRIGGER audit_checkpoints_guard_truncate - BEFORE TRUNCATE ON audit_checkpoints - FOR EACH STATEMENT EXECUTE FUNCTION refuse_audit_history_change(); diff --git a/crates/database/migrations/0025_drop_legacy_client_secret.sql b/crates/database/migrations/0025_drop_legacy_client_secret.sql deleted file mode 100644 index c249f1a65..000000000 --- a/crates/database/migrations/0025_drop_legacy_client_secret.sql +++ /dev/null @@ -1,4 +0,0 @@ --- Contracts what migration 0018 (#187) kept for the release before it, which no --- environment runs anymore: every deployed release stores client secrets only in --- oidc_client_secrets, and none reads or writes oidc_clients.client_secret_hash. -ALTER TABLE oidc_clients DROP COLUMN client_secret_hash; diff --git a/crates/database/migrations/0026_account_purge.sql b/crates/database/migrations/0026_account_purge.sql deleted file mode 100644 index 0d454e731..000000000 --- a/crates/database/migrations/0026_account_purge.sql +++ /dev/null @@ -1,89 +0,0 @@ --- An account purge leaves no personal data behind, and costs no more as --- everyone's history grows (#265). --- --- The previous release keeps working beside this one: it reads none of the new --- columns, and the trigger scrubs the clients it deletes too. - --- A purge that fails is retried with a backoff, so accounts that keep failing no --- longer hold back every other due account. next_attempt_at is NULL until the --- first failure: the purge is due at purge_after until then. last_error is the --- error's message chain, never a value from the account. -ALTER TABLE account_deletions - ADD COLUMN attempts INT NOT NULL DEFAULT 0, - ADD COLUMN last_error TEXT, - ADD COLUMN next_attempt_at TIMESTAMPTZ, - ADD CHECK ((attempts = 0) = (last_error IS NULL)), - ADD CHECK ((last_error IS NULL) = (next_attempt_at IS NULL)); --- The purge job reads due accounts in the order they became due. greatest() --- ignores a NULL next_attempt_at. -CREATE INDEX account_deletions_due_idx - ON account_deletions ((greatest(next_attempt_at, purge_after))); -DROP INDEX account_deletions_purge_idx; - --- A purge erases the personal data of the events the account acted in, found by --- the actor's user ID. The index is not partial: PostgreSQL keeps no statistics --- on a partial index's expression, and without them it estimates so many matches --- that it scans every event's personal data instead. -CREATE INDEX domain_events_actor_user_idx ON domain_events ((actor ->> 'user_id')); --- A purge deletes the email deliveries addressed to the account. -CREATE INDEX deliveries_email_recipient_idx ON deliveries (recipient) - WHERE channel = 'email'; --- A purge deletes, or deleting the account cascades or sets NULL in, every row --- of the account, revoked or released ones included, which the partial indexes --- on these columns leave out. The other foreign keys to users without an index --- are on short-lived state: ceremonies, codes and pending sign-ins, which --- cleanup keeps small. -CREATE INDEX active_verified_email_ownership_user_idx - ON active_verified_email_ownership (user_id); -CREATE INDEX sessions_user_idx ON sessions (user_id); -CREATE INDEX refresh_families_user_idx ON refresh_token_families (user_id); -CREATE INDEX passkey_credentials_user_idx ON passkey_credentials (user_id); -CREATE INDEX external_login_identities_user_idx ON external_login_identities (user_id); -CREATE INDEX handles_user_idx ON handles (user_id); --- Purging an owner erases its clients' related origins from the events about --- them, and deleting its clients deletes their consents. -CREATE INDEX domain_events_client_idx ON domain_events (client_id) - WHERE client_id IS NOT NULL; -CREATE INDEX oidc_consents_client_idx ON oidc_consents (client_id); - --- Personal data is erased, never rewritten. Purging an app's owner erases the --- app's related origins from other people's events by removing them from --- `details`, the only column the runtime role may update; any other update fails. -CREATE FUNCTION guard_personal_data_erasure() RETURNS TRIGGER -LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - IF NOT EXISTS ( - SELECT FROM jsonb_each(NEW.details) kept - WHERE OLD.details -> kept.key IS DISTINCT FROM kept.value - ) THEN - RETURN NEW; - END IF; - RAISE EXCEPTION 'personal data of event % can only be erased', OLD.event_id - USING ERRCODE = 'integrity_constraint_violation'; -END $$; -CREATE TRIGGER event_personal_data_guard_erasure - BEFORE UPDATE ON event_personal_data - FOR EACH ROW EXECUTE FUNCTION guard_personal_data_erasure(); - --- A deleted client keeps only its ID, settings that identify nobody, and its --- lifecycle dates: its name, redirect URIs and back-channel logout URI may name a --- person or their domain. Its name becomes empty rather than NULL, which the --- previous release could not read. -CREATE FUNCTION scrub_deleted_client() RETURNS TRIGGER -LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - NEW.display_name := ''; - NEW.backchannel_logout_uri := NULL; - DELETE FROM oidc_redirect_uris WHERE client_id = NEW.id; - RETURN NEW; -END $$; -CREATE TRIGGER oidc_clients_scrub_deleted - BEFORE UPDATE OF deleted_at ON oidc_clients - FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) - EXECUTE FUNCTION scrub_deleted_client(); - --- Clients deleted before this migration. -UPDATE oidc_clients SET display_name = '', backchannel_logout_uri = NULL -WHERE deleted_at IS NOT NULL; -DELETE FROM oidc_redirect_uris r USING oidc_clients c -WHERE r.client_id = c.id AND c.deleted_at IS NOT NULL; diff --git a/crates/database/migrations/0027_event_counts.sql b/crates/database/migrations/0027_event_counts.sql deleted file mode 100644 index 964572714..000000000 --- a/crates/database/migrations/0027_event_counts.sql +++ /dev/null @@ -1,4 +0,0 @@ --- The overviews count events of a kind over the last hour and week, across --- every account: the dashboard's failed and successful sign-ins and code --- exchanges, against what an hour usually brings. -CREATE INDEX domain_events_kind_time_idx ON domain_events (kind, occurred_at); diff --git a/crates/database/migrations/0028_authorization_request_interaction.sql b/crates/database/migrations/0028_authorization_request_interaction.sql deleted file mode 100644 index 52e409069..000000000 --- a/crates/database/migrations/0028_authorization_request_interaction.sql +++ /dev/null @@ -1,22 +0,0 @@ --- An authorization request's `prompt` becomes one value: `prompt=none` excludes --- `login` and `consent`, which three flags could not say. The old release reads --- and writes the flags, so its replicas fail authorizations until they are --- replaced, as after migration 0021; requests live for minutes, so keeping both --- shapes in sync for a release would buy little. -ALTER TABLE authorization_requests - ADD COLUMN interaction TEXT NOT NULL DEFAULT 'as_needed' - CHECK (interaction IN ('as_needed', 'login', 'consent', 'login_consent', 'none')); - -UPDATE authorization_requests SET interaction = CASE - WHEN prompt_none THEN 'none' - WHEN force_login AND force_consent THEN 'login_consent' - WHEN force_login THEN 'login' - WHEN force_consent THEN 'consent' - ELSE 'as_needed' -END; - -ALTER TABLE authorization_requests - ALTER COLUMN interaction DROP DEFAULT, - DROP COLUMN force_login, - DROP COLUMN force_consent, - DROP COLUMN prompt_none; diff --git a/crates/database/migrations/0029_reserved_handles.sql b/crates/database/migrations/0029_reserved_handles.sql deleted file mode 100644 index a82d5c44e..000000000 --- a/crates/database/migrations/0029_reserved_handles.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Handles administrators reserve, on top of the names the handle rules build in: --- signup and the settings refuse them and their look-alikes, as they do built-in --- ones, until an administrator gives one to an account or removes it from the --- list. The reason says who or what it is kept for. Accounts already holding one --- keep it, and `handle check` lists them. -CREATE TABLE reserved_handles ( - handle TEXT PRIMARY KEY - CHECK (length(handle) BETWEEN 3 AND 32 AND handle ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), - skeleton TEXT NOT NULL UNIQUE GENERATED ALWAYS AS (handle_skeleton(handle)) STORED, - reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 500), - reserved_at TIMESTAMPTZ NOT NULL DEFAULT now() -); diff --git a/crates/database/migrations/0030_profile_pictures.sql b/crates/database/migrations/0030_profile_pictures.sql deleted file mode 100644 index a773217f9..000000000 --- a/crates/database/migrations/0030_profile_pictures.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Each account's profile picture: the JPEG auth re-encoded from the upload, never --- the uploaded bytes. `id` names it in its URL and is new on every upload, so the --- image at a URL never changes and caches keep it for good; replacing or removing --- the picture stops that URL at once. --- --- The account's purge removes it through the cascade, whichever release purges: --- the previous release's purge does not know this table. -CREATE TABLE profile_pictures ( - user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - id UUID NOT NULL UNIQUE, - image BYTEA NOT NULL CHECK (octet_length(image) BETWEEN 1 AND 131072), - created_at TIMESTAMPTZ NOT NULL DEFAULT now() -); - --- JPEG does not compress further: keep images out of line without trying. -ALTER TABLE profile_pictures ALTER COLUMN image SET STORAGE EXTERNAL; diff --git a/crates/database/migrations/0031_pending_federation_picture.sql b/crates/database/migrations/0031_pending_federation_picture.sql deleted file mode 100644 index 312216b5e..000000000 --- a/crates/database/migrations/0031_pending_federation_picture.sql +++ /dev/null @@ -1,5 +0,0 @@ --- The profile picture URL a provider reported with its evidence, so a social --- signup can import it once the account exists. Nullable: the previous release --- inserts evidence without one, and its signups import nothing. -ALTER TABLE pending_federation - ADD COLUMN picture_url TEXT CHECK (char_length(picture_url) <= 2048); diff --git a/crates/database/migrations/0032_pending_email_authority.sql b/crates/database/migrations/0032_pending_email_authority.sql deleted file mode 100644 index 8126a2a1d..000000000 --- a/crates/database/migrations/0032_pending_email_authority.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Whether the provider of a pending sign-in is authoritative for its address, so --- the address is imported verified. Rows written before this read as not, which --- only asks their owner to verify the address. -ALTER TABLE pending_federation - ADD COLUMN email_authoritative BOOLEAN NOT NULL DEFAULT false, - ADD CHECK (email IS NOT NULL OR NOT email_authoritative); diff --git a/crates/database/migrations/0033_notifications.sql b/crates/database/migrations/0033_notifications.sql deleted file mode 100644 index 1b2ef9a00..000000000 --- a/crates/database/migrations/0033_notifications.sql +++ /dev/null @@ -1,20 +0,0 @@ --- What each account's owner is told about their account, in their settings --- inbox. A notification is written in the transaction of the event it comes --- from, if any, and holds no personal data: it renders from its payload alone, --- so it outlives its event's personal data and the event itself, which audit --- pruning may delete. `event_id` is no foreign key for that reason. Purging the --- account deletes its notifications with it. -CREATE TABLE notifications ( - id UUID PRIMARY KEY, - user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, - event_id UUID, - payload JSONB NOT NULL CHECK (jsonb_typeof(payload -> 'kind') = 'string'), - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - read_at TIMESTAMPTZ -); - --- The inbox, newest first. Notifications written in one transaction share --- `now()`, so pages continue after `(created_at, id)`. -CREATE INDEX notifications_inbox_idx ON notifications (user_id, created_at DESC, id DESC); --- The unread count every settings page shows. -CREATE INDEX notifications_unread_idx ON notifications (user_id) WHERE read_at IS NULL; diff --git a/crates/database/migrations/0034_notification_emails.sql b/crates/database/migrations/0034_notification_emails.sql deleted file mode 100644 index a9b65870e..000000000 --- a/crates/database/migrations/0034_notification_emails.sql +++ /dev/null @@ -1,12 +0,0 @@ --- The notices about an account's addresses and recoveries are now emails of its --- notifications (`{"type": "notification", …}`), and the four kinds of message --- that carried them before are gone, so a delivery of one would no longer decode. --- Those still waiting to be sent, or failed, are cancelled rather than --- translated: there are no real users yet, and a notice that late is stale. -UPDATE deliveries -SET status = 'cancelled', finished_at = now(), claim_token = NULL -WHERE channel = 'email' - AND status IN ('pending', 'failed') - AND payload ->> 'type' IN ( - 'primary_address_changed', 'address_removed', 'recovery_revoked', 'recovered' - ); diff --git a/crates/database/migrations/0035_history_writes.sql b/crates/database/migrations/0035_history_writes.sql deleted file mode 100644 index f0eb91f1c..000000000 --- a/crates/database/migrations/0035_history_writes.sql +++ /dev/null @@ -1,152 +0,0 @@ --- Auth's runtime role writes history only the way auth does (#250), so a --- compromised auth can neither forge history nor plant rows that freeze it. With --- the column grants of runtime_role.sql, it cannot set an event's transaction, --- time, sequence or chain columns when inserting it. These guards refuse the --- rest, for every role: an event auth could not read back, personal data --- attached to another transaction's event, a seal that skips a position, and a --- checkpoint for anything but a sealed event's hash, or dated in the future. A --- huge position, an unreadable event or a future checkpoint would otherwise stop --- sealing or signing until the schema owner repaired it. SQL cannot check a hash --- or a checkpoint's signature; the sealer and `audit verify` do, and a seal with --- a wrong one still stops signing until the owner repairs the chain. --- --- The previous release keeps working beside this one: it records personal data --- with its event, seals positions in order and signs the head it just sealed. --- --- Requests write a passkey, then an event, then its personal data. Changing each --- table locks it against writes, and adding the check also against reads of --- domain_events, for a moment, so take the locks up front in that order: locking --- personal data first would deadlock with a request that already inserted its --- event. The migration waits for those requests, within its lock limit. An --- account purge erases personal data before recording its event, so one running --- then can still deadlock with the migration, which fails and is run again. -LOCK TABLE passkey_credentials IN SHARE ROW EXCLUSIVE MODE; - --- An event the sealer could not read would fail every sealing pass, which loads --- up to 100 events at once. serde_json refuses numbers beyond a double's range --- and nesting past 128 levels, and a huge event would exhaust the sealer's memory --- or time: parsed, JSON can take about 100 times its text. So an event's payload --- stays under 8 KiB, its actor under 1 KiB and its text columns under 256 bytes, --- about 95 MB for a batch at worst. Real events are a few hundred bytes, the --- largest a recovery listing an account's passkeys, which the passkey limit below --- keeps around 4 KiB, so existing rows are not rechecked. Sealing an event --- updates it and checks it again, so one recorded before this migration must --- fit too; real ones do. -CREATE FUNCTION auth_reads_json(value JSONB, bytes INT) RETURNS BOOLEAN -LANGUAGE sql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$ - SELECT octet_length(value::text) <= bytes AND NOT ( - value @? '$.** ? (@.type() == "number" && (@ > 1e308 || @ < -1e308))' - OR value @? '$.**{64 to last}' - ) -$$; -ALTER TABLE domain_events ADD CONSTRAINT domain_events_readable CHECK ( - auth_reads_json(payload, 8192) AND auth_reads_json(actor, 1024) - AND octet_length(kind) <= 256 AND octet_length(client_id) <= 256 - AND octet_length(trace_id) <= 256 -) NOT VALID; -LOCK TABLE event_personal_data, audit_checkpoints IN SHARE ROW EXCLUSIVE MODE; - --- Personal data is recorded with its event, never attached to an older one: with --- the deletes retention needs, that would let it be rewritten. -CREATE FUNCTION guard_personal_data_insert() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - IF EXISTS ( - SELECT FROM domain_events WHERE id = NEW.event_id AND txid = pg_current_xact_id() - ) THEN - RETURN NEW; - END IF; - RAISE EXCEPTION 'personal data of event % can only be recorded with the event', NEW.event_id - USING ERRCODE = 'integrity_constraint_violation'; -END $$; -CREATE TRIGGER event_personal_data_guard_insert - BEFORE INSERT ON event_personal_data - FOR EACH ROW EXECUTE FUNCTION guard_personal_data_insert(); - --- Each sealed position follows a sealed one, or the anchor, or starts the chain, --- so no seal leaves a gap or jumps ahead. It runs once the statement has sealed --- its whole batch, whatever order the rows were updated in. A wrong hash is for --- verification to find: SQL cannot compute one. --- --- Sealing must read committed data, as the sealer does: an older snapshot could --- still show events a concurrent prune deleted, and seal behind the anchor. Read --- committed, the check sees every committed prune, and a prune still deleting the --- position makes the seal wait for it on the unique index first. -CREATE FUNCTION guard_seal_order() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - IF current_setting('transaction_isolation') <> 'read committed' THEN - RAISE EXCEPTION 'events are sealed only in read committed transactions' - USING ERRCODE = 'integrity_constraint_violation'; - END IF; - IF NEW.chain_position - 1 = coalesce((SELECT position FROM audit_anchor), 0) - OR EXISTS (SELECT FROM domain_events WHERE chain_position = NEW.chain_position - 1) - THEN - RETURN NULL; - END IF; - RAISE EXCEPTION 'event % cannot be sealed at position %: the position before is not sealed', - NEW.id, NEW.chain_position - USING ERRCODE = 'integrity_constraint_violation'; -END $$; -CREATE TRIGGER domain_events_guard_seal_order - AFTER UPDATE OF chain_position ON domain_events - FOR EACH ROW WHEN (OLD.chain_position IS NULL AND NEW.chain_position IS NOT NULL) - EXECUTE FUNCTION guard_seal_order(); - --- A checkpoint is of a sealed event's chain hash, and dated at a finite time --- not in the future: auth cannot read an infinite one back. A minute of leeway --- covers auth's clock running ahead of the database's. Its note, which auth reads --- and checks a signature line by line, stays under 1 KiB; auth's are about 300 --- bytes. -CREATE FUNCTION guard_new_checkpoint() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - IF isfinite(NEW.created_at) AND octet_length(NEW.note) <= 1024 - AND NEW.created_at <= clock_timestamp() + INTERVAL '1 minute' AND EXISTS ( - SELECT FROM domain_events WHERE chain_position = NEW.position AND chain_hash = NEW.head - ) THEN - RETURN NEW; - END IF; - RAISE EXCEPTION 'checkpoint at position % is not of the sealed chain as of now', - NEW.position - USING ERRCODE = 'integrity_constraint_violation'; -END $$; -CREATE TRIGGER audit_checkpoints_guard_insert - BEFORE INSERT ON audit_checkpoints - FOR EACH ROW EXECUTE FUNCTION guard_new_checkpoint(); - --- An account keeps at most 100 active passkeys, so the recovery event listing --- them stays well under the payload bound above. Nobody needs more. Concurrent --- registrations can pass it by a few, which the bound still fits. -CREATE FUNCTION limit_passkeys() RETURNS TRIGGER -LANGUAGE plpgsql AS $$ -BEGIN - IF ( - SELECT count(*) FROM passkey_credentials - WHERE user_id = NEW.user_id AND revoked_at IS NULL - ) < 100 THEN - RETURN NEW; - END IF; - RAISE EXCEPTION 'account % already has 100 active passkeys', NEW.user_id - USING ERRCODE = 'check_violation'; -END $$; -CREATE TRIGGER passkey_credentials_limit - BEFORE INSERT ON passkey_credentials - FOR EACH ROW EXECUTE FUNCTION limit_passkeys(); - --- The functions look tables up in the schema this migration runs in, with --- pg_temp last: public when deployed, a test's own schema in tests. -DO $$ -DECLARE - guard TEXT; -BEGIN - FOREACH guard IN ARRAY ARRAY[ - 'guard_personal_data_insert', 'guard_seal_order', 'guard_new_checkpoint', - 'limit_passkeys' - ] LOOP - EXECUTE format( - 'ALTER FUNCTION %I() SET search_path = pg_catalog, %I, pg_temp', - guard, current_schema() - ); - END LOOP; -END $$; diff --git a/crates/database/migrations/0036_chain_format.sql b/crates/database/migrations/0036_chain_format.sql deleted file mode 100644 index b15d4f063..000000000 --- a/crates/database/migrations/0036_chain_format.sql +++ /dev/null @@ -1,20 +0,0 @@ --- The sealer verifies what it builds on, and the chain can grow new fields (#251). --- --- Each sealed event records the format of the canonical event its hash covers, --- so a later format can add fields without breaking the hashes of events sealed --- before it. Format 1 is the original, untagged one; every event sealed so far --- is in it. The default keeps the previous release's seals in format 1, which is --- what it hashes. Only known formats are allowed, so a forged one is reported --- where it is rather than taken for a newer release's; the release that adds a --- format widens the check. -ALTER TABLE domain_events - ADD COLUMN chain_format SMALLINT NOT NULL DEFAULT 1 CHECK (chain_format IN (1, 2)); - --- Histories list events in the order they are sealed in, (txid, sequence), which --- verification checks against the chain, rather than by sequence alone, which the --- chain does not cover. --- --- PENDING CONTRACT: domain_events_subject_idx stays while a deployed release --- still lists an account's history by sequence; drop it once none does. -CREATE INDEX domain_events_subject_order_idx - ON domain_events (subject_user_id, txid DESC, sequence DESC); diff --git a/crates/database/migrations/0037_announcements.sql b/crates/database/migrations/0037_announcements.sql deleted file mode 100644 index 93c7f91eb..000000000 --- a/crates/database/migrations/0037_announcements.sql +++ /dev/null @@ -1,57 +0,0 @@ --- Announcements administrators send to accounts, such as a security incident or --- a change to the privacy policy: emailed to each recipient's primary verified --- address, and written to each recipient's inbox as a notification. --- --- An announcement is a draft until it is sent, and only a draft changes. Its --- text is written for everyone it goes to, so it is no one's personal data, --- except that an announcement to chosen accounts may concern them: a purge --- deletes it with its last recipient. -CREATE TABLE announcements ( - id UUID PRIMARY KEY, - subject TEXT NOT NULL CHECK (subject <> ''), - body TEXT NOT NULL CHECK (body <> ''), - -- Whether it goes to every account, rather than to the chosen ones. - everyone BOOLEAN NOT NULL, - -- Counts the draft's changes. Sending names the revision that was checked, - -- so a change made meanwhile is checked again before anything is sent. - revision BIGINT NOT NULL DEFAULT 1, - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), - sent_at TIMESTAMPTZ -); -CREATE INDEX announcements_recent_idx ON announcements (created_at DESC, id DESC); - --- What was sent stays as it was sent: the audit history names the announcement, --- not its text. -CREATE FUNCTION guard_sent_announcement() RETURNS TRIGGER -LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - RAISE EXCEPTION 'announcement % was sent, so it can no longer change', OLD.id - USING ERRCODE = 'integrity_constraint_violation'; -END $$; -CREATE TRIGGER announcements_sent_unchanged - BEFORE UPDATE ON announcements - FOR EACH ROW WHEN (OLD.sent_at IS NOT NULL) - EXECUTE FUNCTION guard_sent_announcement(); - --- The accounts an announcement goes to: the chosen ones from the draft on, or --- every account, added when it is sent. Accounts created later never get it. --- Deleting an account deletes its rows. -CREATE TABLE announcement_recipients ( - announcement_id UUID NOT NULL REFERENCES announcements(id) ON DELETE CASCADE, - user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, - PRIMARY KEY (announcement_id, user_id) -); --- A purge finds the announcements an account received, and the cascade its rows. -CREATE INDEX announcement_recipients_user_idx ON announcement_recipients (user_id); - --- The dashboard counts an announcement's emails by status while the queue keeps --- them: their payload is the announcement's ID. A purge deletes the account's. -CREATE INDEX deliveries_announcement_idx ON deliveries (payload) - WHERE channel = 'announcement'; -CREATE INDEX deliveries_announcement_recipient_idx ON deliveries (recipient) - WHERE channel = 'announcement'; - --- How many of an announcement's recipients read it, which its page shows. -CREATE INDEX notifications_announcement_idx ON notifications ((payload ->> 'announcement_id')) - WHERE payload ->> 'kind' = 'announcement'; diff --git a/crates/database/migrations/0038_alerts.sql b/crates/database/migrations/0038_alerts.sql deleted file mode 100644 index 8d781ba08..000000000 --- a/crates/database/migrations/0038_alerts.sql +++ /dev/null @@ -1,21 +0,0 @@ --- What needs an administrator's attention, such as a broken audit chain: a --- condition auth found, which concerns no account. An alert is current from when --- it is raised until its condition clears, and open until then too, unless an --- administrator acknowledges it first: auth then raises it again only once its --- condition clears or changes. At most one alert of each kind is current. Like --- an event's payload, it holds no personal data, and its events tell who --- acknowledged it. -CREATE TABLE alerts ( - id UUID PRIMARY KEY, - payload JSONB NOT NULL CHECK (jsonb_typeof(payload -> 'kind') = 'string'), - -- The payload's version, as an event's: a release reads one it does not - -- write as an alert it cannot show. - version SMALLINT NOT NULL, - raised_at TIMESTAMPTZ NOT NULL DEFAULT now(), - -- When auth last found its condition holding. - seen_at TIMESTAMPTZ NOT NULL DEFAULT now(), - acknowledged_at TIMESTAMPTZ, - cleared_at TIMESTAMPTZ -); - -CREATE UNIQUE INDEX alerts_current_idx ON alerts ((payload ->> 'kind')) WHERE cleared_at IS NULL; diff --git a/crates/database/migrations/0039_notification_preferences.sql b/crates/database/migrations/0039_notification_preferences.sql deleted file mode 100644 index 2a8025332..000000000 --- a/crates/database/migrations/0039_notification_preferences.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Whether each account receives a category of notifications by email. Only --- categories whose email the owner may turn off have rows, and no row means --- the category's default: everything about the account itself is always --- emailed. Deleting an account deletes its rows. -CREATE TABLE notification_preferences ( - user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, - category TEXT NOT NULL CHECK (category IN ('announcements')), - email BOOLEAN NOT NULL, - updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, category) -); - --- An essential announcement, such as a security incident or a change to the --- privacy policy or terms, is emailed to every recipient whatever their --- preference. Its sender chooses so on the draft. -ALTER TABLE announcements ADD COLUMN essential BOOLEAN NOT NULL DEFAULT false; - --- Whether `account` receives announcements that are not essential by email: --- unless its owner turned them off. -CREATE FUNCTION announcements_emailed(account UUID) RETURNS BOOLEAN -LANGUAGE sql STABLE SET search_path = pg_catalog, public, pg_temp AS $$ - SELECT NOT EXISTS ( - SELECT FROM notification_preferences p - WHERE p.user_id = account AND p.category = 'announcements' AND NOT p.email - ) -$$; diff --git a/crates/database/migrations/0040_alert_updates.sql b/crates/database/migrations/0040_alert_updates.sql deleted file mode 100644 index b585f06cc..000000000 --- a/crates/database/migrations/0040_alert_updates.sql +++ /dev/null @@ -1,21 +0,0 @@ --- What administrators post on an alert while they handle it: where its handling --- stands. The first acknowledges the alert, which then needs no attention while --- its condition holds as it says. The author is the administrator or operator, as --- an event's actor. Each update records an `alert_updated` event, `event_id`, --- whose reason holds its note: the note is personal data, deleted with the --- event's after 90 days or when its author's account is purged. No foreign key --- holds `event_id`, since pruning the audit chain deletes events, and the update --- outlives its event. An update is stamped when it is written, after its alert's --- row is locked, not when its transaction began: updates sort in the order they --- were posted even when their transactions overlap. -CREATE TABLE alert_updates ( - id UUID PRIMARY KEY, - alert_id UUID NOT NULL REFERENCES alerts(id) ON DELETE CASCADE, - status TEXT NOT NULL CHECK (status IN ('investigating', 'fixing', 'monitoring')), - event_id UUID NOT NULL UNIQUE, - author JSONB NOT NULL CHECK (author ->> 'type' IN ('admin', 'cli')), - posted_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() -); - --- An alert's updates, oldest first. -CREATE INDEX alert_updates_alert_idx ON alert_updates (alert_id, posted_at, id); diff --git a/crates/database/migrations/0041_dashboard_session_limits.sql b/crates/database/migrations/0041_dashboard_session_limits.sql deleted file mode 100644 index ca4930eed..000000000 --- a/crates/database/migrations/0041_dashboard_session_limits.sql +++ /dev/null @@ -1,14 +0,0 @@ --- A dashboard session ends after 30 minutes without a request, and 12 hours --- after its sign-in however busy, so an unattended browser or a stolen cookie --- stops working within a working day. Auth sets both on each sign-in, and --- refreshes `last_used_at` on each request. The defaults serve the previous --- release, which inserts neither, during a deploy. -ALTER TABLE dashboard_sessions - ADD COLUMN last_used_at TIMESTAMPTZ NOT NULL DEFAULT now(), - ADD COLUMN expires_at TIMESTAMPTZ NOT NULL DEFAULT now() + interval '12 hours'; - --- A session signed in more than 12 hours ago has ended already. -UPDATE dashboard_sessions SET expires_at = created_at + interval '12 hours'; - --- Cleanup deletes the sessions that ended. -CREATE INDEX dashboard_sessions_expires_idx ON dashboard_sessions (expires_at); diff --git a/crates/database/migrations/0042_retention.sql b/crates/database/migrations/0042_retention.sql deleted file mode 100644 index ba8894636..000000000 --- a/crates/database/migrations/0042_retention.sql +++ /dev/null @@ -1,30 +0,0 @@ --- Retention limits on what an account leaves behind (#266). Cleanup deletes --- revoked passkeys, unlinked identities and ended recoveries 90 days after they --- end, notifications a year after they arrive, and a purged account's handles a --- year after its purge, when anyone may claim them again. - --- A purged account's handles are released by its purge, whichever release runs --- it: deleting the account sets their `user_id` to NULL, which fires this. It --- also overwrites when an older handle was released, so every handle the account --- held is freed a year after the purge, not after its rename. -CREATE FUNCTION release_purged_handle() RETURNS trigger -LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$ -BEGIN - NEW.released_at := now(); - RETURN NEW; -END $$; -CREATE TRIGGER handles_release_purged - BEFORE UPDATE OF user_id ON handles - FOR EACH ROW WHEN (OLD.user_id IS NOT NULL AND NEW.user_id IS NULL) - EXECUTE FUNCTION release_purged_handle(); - --- Accounts purged before this keep their handles a year from now. -UPDATE handles SET released_at = now() WHERE user_id IS NULL; - --- Cleanup's scans, so they read only what may be due. -CREATE INDEX passkey_credentials_revoked_idx ON passkey_credentials (revoked_at) - WHERE revoked_at IS NOT NULL; -CREATE INDEX external_login_identities_revoked_idx ON external_login_identities (revoked_at) - WHERE revoked_at IS NOT NULL; -CREATE INDEX notifications_created_idx ON notifications (created_at); -CREATE INDEX handles_purged_idx ON handles (released_at) WHERE user_id IS NULL; diff --git a/crates/database/migrations/0043_known_devices.sql b/crates/database/migrations/0043_known_devices.sql deleted file mode 100644 index f94bd100d..000000000 --- a/crates/database/migrations/0043_known_devices.sql +++ /dev/null @@ -1,20 +0,0 @@ --- The browsers each account has signed in from, so a sign-in from any other --- one alerts its owner. A browser is known by the digest of its device cookie, --- a random secret it keeps for 400 days, apart from its session cookie, so --- signing out does not forget it. Maintenance deletes a device unused for 400 --- days, and deleting the account deletes its devices. -CREATE TABLE known_devices ( - user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, - device_digest BYTEA NOT NULL CHECK (octet_length(device_digest) = 32), - user_agent_family TEXT, - first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(), - last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, device_digest) -); - --- Maintenance finds the devices unused for 400 days. -CREATE INDEX known_devices_last_seen_idx ON known_devices (last_seen_at); - --- When the "sign me out everywhere" link of a notification's email was used. --- The link works once, within 7 days of the notification. -ALTER TABLE notifications ADD COLUMN signed_out_at TIMESTAMPTZ; diff --git a/crates/database/migrations/0044_drop_unused_delivery_machinery.sql b/crates/database/migrations/0044_drop_unused_delivery_machinery.sql deleted file mode 100644 index 4d9955be5..000000000 --- a/crates/database/migrations/0044_drop_unused_delivery_machinery.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Event consumers' cursors were never used outside tests: no release reads or --- writes event_consumers, so it goes now. -DROP TABLE event_consumers; - --- No channel ever ordered its deliveries, so auth no longer reads or writes --- deliveries.ordering_key, deliveries.ordinal or delivery_orderings. --- --- PENDING CONTRACT: they stay, because the previous release still names them --- when it inserts, claims and lists deliveries. Once no deployed release does, --- a new migration must DROP TABLE delivery_orderings, then drop both columns, --- which takes their UNIQUE and CHECK constraints with them. diff --git a/crates/database/migrations/0045_invitation_recipients.sql b/crates/database/migrations/0045_invitation_recipients.sql deleted file mode 100644 index 5ee5e96cd..000000000 --- a/crates/database/migrations/0045_invitation_recipients.sql +++ /dev/null @@ -1,7 +0,0 @@ --- An invitation may be mailed to the person it invites: it remembers their --- normalized address, which their account starts with, verified, when they sign --- up with it. Its link's token is derived from its ID, so the email sender --- rebuilds the link from the stored digest, as it does a recovery's. Cleanup --- deletes the address with its invitation, once it expires or a day after it --- is redeemed. -ALTER TABLE invitations ADD COLUMN email TEXT; diff --git a/crates/database/migrations/0046_first_handle_change.sql b/crates/database/migrations/0046_first_handle_change.sql deleted file mode 100644 index 3889ef177..000000000 --- a/crates/database/migrations/0046_first_handle_change.sql +++ /dev/null @@ -1,7 +0,0 @@ --- A new account may correct the handle it chose at signup at once: the rename --- cooldown counts only from a change. handle_changed_at is NULL until the --- handle first changes, and existing accounts that never changed theirs get it --- back, since migration 0021 copied created_at into it. -ALTER TABLE users ALTER COLUMN handle_changed_at DROP NOT NULL; -ALTER TABLE users ALTER COLUMN handle_changed_at DROP DEFAULT; -UPDATE users SET handle_changed_at = NULL WHERE handle_changed_at = created_at; diff --git a/crates/database/migrations/0047_refresh_token_successors.sql b/crates/database/migrations/0047_refresh_token_successors.sql deleted file mode 100644 index 7e323aa65..000000000 --- a/crates/database/migrations/0047_refresh_token_successors.sql +++ /dev/null @@ -1,6 +0,0 @@ --- A rotated refresh token names the token it replaced, so a public client that --- presents that token again moments later, from a second tab or as a retry, is --- answered with this successor instead of having its family revoked as a --- replay. A token has at most one successor. -ALTER TABLE refresh_tokens - ADD COLUMN predecessor_id UUID UNIQUE REFERENCES refresh_tokens(id) ON DELETE SET NULL; diff --git a/crates/database/migrations/0048_optional_pkce.sql b/crates/database/migrations/0048_optional_pkce.sql deleted file mode 100644 index e83b6e8ef..000000000 --- a/crates/database/migrations/0048_optional_pkce.sql +++ /dev/null @@ -1,5 +0,0 @@ --- A confidential client may leave PKCE out of an authorization request, as --- RFC 9700 allows: it authenticates at the token endpoint. pkce_challenge is --- NULL for such a request and the code it issues. -ALTER TABLE authorization_requests ALTER COLUMN pkce_challenge DROP NOT NULL; -ALTER TABLE authorization_codes ALTER COLUMN pkce_challenge DROP NOT NULL; diff --git a/crates/database/migrations/0049_optional_state.sql b/crates/database/migrations/0049_optional_state.sql deleted file mode 100644 index e290c5be9..000000000 --- a/crates/database/migrations/0049_optional_state.sql +++ /dev/null @@ -1,3 +0,0 @@ --- An authorization request's state is optional (RFC 6749 §4.1.1): client_state --- is NULL when the client sent none, so no empty state goes back to it. -ALTER TABLE authorization_requests ALTER COLUMN client_state DROP NOT NULL; diff --git a/crates/database/migrations/0050_contract_deliveries_and_history_index.sql b/crates/database/migrations/0050_contract_deliveries_and_history_index.sql deleted file mode 100644 index 19a2d338a..000000000 --- a/crates/database/migrations/0050_contract_deliveries_and_history_index.sql +++ /dev/null @@ -1,20 +0,0 @@ --- Contracts what earlier migrations kept for the release before them, which no --- environment runs anymore: staging and production both run releases that --- include the changes below. - --- Migration 0044 (#491) stopped ordering deliveries, but kept their ordering for --- the release before it, which still inserted, claimed and listed deliveries by --- it. Dropping the columns takes their UNIQUE and CHECK constraints with them. -DROP TABLE delivery_orderings; -ALTER TABLE deliveries DROP COLUMN ordering_key, DROP COLUMN ordinal; - --- Migration 0036 (#369) lists an account's history by (txid, sequence) through --- domain_events_subject_order_idx, but kept the index by sequence alone for the --- release before it, which still listed history that way. -DROP INDEX domain_events_subject_idx; - --- Migration 0041 (#439) defaulted a dashboard session's expiry for the release --- before it, which inserted none. Auth now sets it on every sign-in, so a --- session inserted without one is a bug, not a 12-hour session. last_used_at --- keeps its default, which every sign-in still relies on. -ALTER TABLE dashboard_sessions ALTER COLUMN expires_at DROP DEFAULT; diff --git a/crates/database/src/connection/mod.rs b/crates/database/src/connection/mod.rs index b1c1177bb..12df5aace 100644 --- a/crates/database/src/connection/mod.rs +++ b/crates/database/src/connection/mod.rs @@ -402,38 +402,6 @@ impl Database { pool } - /// Connects to `TEST_DATABASE_URL` in a new schema of its own, with the - /// migrations in `versions` applied, for tests of a migration: the test - /// database is already migrated. The schema is left behind; test databases - /// are disposable. - pub(crate) async fn scratch_schema(versions: impl std::ops::RangeBounds) -> PgConnection { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let mut connection = PgConnection::connect(&url).await.expect("connect"); - let schema = format!("scratch_{}", uuid::Uuid::now_v7().simple()); - // A schema name cannot be a bind parameter; this one is generated above. - sqlx::raw_sql(&format!( - "CREATE SCHEMA {schema}; SET search_path TO {schema}" - )) - .execute(&mut connection) - .await - .expect("schema"); - Self::apply_migrations(&mut connection, versions).await; - connection - } - - /// Applies the migrations in `versions` to `connection`'s schema, in order. - pub(crate) async fn apply_migrations( - connection: &mut PgConnection, - versions: impl std::ops::RangeBounds, - ) { - for migration in MIGRATOR.iter().filter(|m| versions.contains(&m.version)) { - sqlx::raw_sql(&migration.sql) - .execute(&mut *connection) - .await - .unwrap_or_else(|error| panic!("migration {}: {error}", migration.version)); - } - } - /// The server process of `connection`, to watch its lock waits with /// [`Self::wait_for_lock`]. pub(crate) async fn backend(connection: &mut PgConnection) -> i32 { diff --git a/crates/database/src/connection/tests.rs b/crates/database/src/connection/tests.rs index bd19f52f6..33a434ebc 100644 --- a/crates/database/src/connection/tests.rs +++ b/crates/database/src/connection/tests.rs @@ -1,7 +1,7 @@ //! Focused persistence and security contract tests. use super::{Database, DatabaseConfig, Limit, MIGRATOR, RuntimeRole, Scope}; -use crate::{DatabaseConnectionError, DatabaseError, EventContent, LockKey}; +use crate::{DatabaseConnectionError, DatabaseError, LockKey}; use sqlx::{PgConnection, Postgres, postgres::PgArguments, query::Query}; use std::time::Duration; use uuid::Uuid; @@ -189,9 +189,11 @@ async fn cleanup_keeps_redeemed_codes_while_their_session_is_live() { ), redeemed AS ( INSERT INTO authorization_codes ( id, secret_digest, client_id, user_id, session_id, redirect_uri, - pkce_challenge, scopes, audience, expires_at, consumed_at, authentication + pkce_challenge, scopes, audience, expires_at, consumed_at, authentication, + digest_key ) VALUES ($3, convert_to($3::text, 'UTF8'), $5, $1, $2, 'https://client.example', - 'challenge', '[]', 'test', now() - interval '2 days', now() - interval '2 days', '{}') + 'challenge', '[]', 'test', now() - interval '2 days', now() - interval '2 days', '{}', + 'test') ) INSERT INTO refresh_token_families ( id, user_id, client_id, session_id, authorization_code_id, audience, scopes, @@ -318,7 +320,7 @@ async fn runtime_role_has_only_row_privileges() { // Sealing locks unsealed events and sets their chain columns, nothing else. let mut seal = runtime.begin().await.expect("begin"); seal.audit() - .unsealed(1, EventContent::UNTAGGED) + .unsealed(1) .await .expect("lock unsealed events"); seal.rollback().await.expect("rollback"); diff --git a/crates/database/src/repositories/administrators.rs b/crates/database/src/repositories/administrators.rs index 027b83da1..eff67481a 100644 --- a/crates/database/src/repositories/administrators.rs +++ b/crates/database/src/repositories/administrators.rs @@ -133,8 +133,8 @@ impl AdministratorRepository<'_> { /// Their rights and accounts stay key-share locked until the transaction /// ends, so a purge of one waits for their notifications and emails to be /// written, then deletes them with the account. Locking the rights too - /// holds back a purge that deletes emails before the account, as the - /// previous release's does, until those emails are written. + /// holds back any purge that deletes emails before the account until those + /// emails are written. /// /// # Errors /// diff --git a/crates/database/src/repositories/audit/mod.rs b/crates/database/src/repositories/audit/mod.rs index fac1e6990..c7c151d19 100644 --- a/crates/database/src/repositories/audit/mod.rs +++ b/crates/database/src/repositories/audit/mod.rs @@ -51,19 +51,15 @@ pub struct EventContent { trace_id: Option, /// The payload as stored, with `"$erased"` where personal values were. payload: Value, - /// The canonical event's format, stored in `chain_format`. The first, - /// [`Self::UNTAGGED`], has no `format` field; every later one has it. - #[serde(skip_serializing_if = "EventContent::untagged")] + /// The canonical event's format, stored in `chain_format`, which every + /// format names. format: i16, } impl EventContent { - /// The canonical event's first format, which names no format. - pub const UNTAGGED: i16 = 1; - /// The newest format this release hashes: format 2, which only adds its - /// `format` to the untagged one. A later format that adds a field comes with - /// a release that knows it. - pub const NEWEST_FORMAT: i16 = 2; + /// The newest format this release hashes, and the one it seals in. A later + /// format that adds a field comes with a release that knows it. + pub const NEWEST_FORMAT: i16 = 1; /// The format of the canonical event the chain hashes for this event. #[must_use] @@ -71,15 +67,6 @@ impl EventContent { self.format } - /// Whether `format` is [`Self::UNTAGGED`], which serializes without it. - #[expect( - clippy::trivially_copy_pass_by_ref, - reason = "serde's skip_serializing_if passes a reference" - )] - const fn untagged(format: &i16) -> bool { - *format == Self::UNTAGGED - } - /// Writes `occurred_at` as RFC 3339 in UTC with exactly six fractional digits, /// e.g. `2026-10-13T12:00:00.000000Z`, so it never depends on serde defaults. fn timestamp(value: &DateTime, serializer: S) -> Result { @@ -219,7 +206,7 @@ impl From for Checkpoint { impl AuditRepository<'_> { /// Returns up to `limit` unsealed events in the order to seal them, to be - /// sealed in `format`: the safe order of `in_safe_order!`. No + /// sealed in [`EventContent::NEWEST_FORMAT`]: the safe order of `in_safe_order!`. No /// event can later appear before one returned here, so positions never need to be /// reassigned. The rows stay locked until the transaction ends, so /// none changes between being hashed and being sealed. @@ -227,11 +214,7 @@ impl AuditRepository<'_> { /// # Errors /// /// Returns [`DatabaseError`] if the query fails. - pub async fn unsealed( - &mut self, - limit: u32, - format: i16, - ) -> Result, DatabaseError> { + pub async fn unsealed(&mut self, limit: u32) -> Result, DatabaseError> { run!( self, fetch_all, @@ -245,7 +228,7 @@ impl AuditRepository<'_> { WHERE chain_position IS NULL"#, "LIMIT $1 FOR UPDATE", i64::from(limit), - format, + EventContent::NEWEST_FORMAT, ) ) } @@ -750,7 +733,7 @@ impl AuditRepository<'_> { r#"INSERT INTO domain_events ( id, kind, version, payload, actor, chain_position, chain_hash ) - SELECT $2, 'imported', 1, '{}', '{"type": "unrecorded"}', $1::bigint, chain_hash + SELECT $2, 'forged', 1, '{}', '{"type": "anonymous"}', $1::bigint, chain_hash FROM domain_events WHERE chain_position = $1::bigint + 1"#, position, Uuid::now_v7(), diff --git a/crates/database/src/repositories/audit/tests.rs b/crates/database/src/repositories/audit/tests.rs index b460dca6f..2cc775724 100644 --- a/crates/database/src/repositories/audit/tests.rs +++ b/crates/database/src/repositories/audit/tests.rs @@ -20,7 +20,7 @@ async fn attempt(connection: &mut PgConnection, sql: &str, id: Uuid) -> Result<( /// Inserts the unsealed event `$1`. const INSERT: &str = r#"INSERT INTO domain_events (id, kind, version, payload, actor) - VALUES ($1, 'imported', 1, '{}', '{"type": "unrecorded"}')"#; + VALUES ($1, 'forged', 1, '{}', '{"type": "anonymous"}')"#; /// Seals the event `$1` at `position`. fn seal(position: u8) -> String { diff --git a/crates/database/src/repositories/deletions/mod.rs b/crates/database/src/repositories/deletions/mod.rs index b129e4dbf..ec5624954 100644 --- a/crates/database/src/repositories/deletions/mod.rs +++ b/crates/database/src/repositories/deletions/mod.rs @@ -281,9 +281,9 @@ impl AccountDeletionRepository<'_> { /// their clients' logout tokens, and delete the clients it manages first. The events themselves stay: they hold only pseudonymous /// IDs. /// - /// The personal data goes last because of migration 0022's trigger, which - /// key-share locks every account an event names as it stores the event's - /// personal data. Only deleting the account conflicts with that lock; the + /// The personal data goes last because of the + /// `event_personal_data_skip_purged_accounts` trigger, which key-share locks + /// every account an event names as it stores the event's personal data. Only deleting the account conflicts with that lock; the /// callers' `FOR NO KEY UPDATE` does not. So the delete waits for every /// request that stored personal data while the account existed, and the next /// statement, with a fresh snapshot, erases it too; a request that stores diff --git a/crates/database/src/repositories/deletions/tests.rs b/crates/database/src/repositories/deletions/tests.rs index 64f6cc751..fd70ad6c9 100644 --- a/crates/database/src/repositories/deletions/tests.rs +++ b/crates/database/src/repositories/deletions/tests.rs @@ -108,8 +108,8 @@ async fn restore_tokens_expire_and_end_with_the_deletion() { "an account that is not scheduled gets no token" ); - // Leaving 'deleting' any other way, as the previous release's enable and - // disable do, ends the schedule too. + // Leaving 'deleting' any other way, through a plain enable or disable, ends + // the schedule too. let mut users = crate::UserRepository::from_pool(&pool); users .set_status(user, AccountStatus::Deleting) @@ -169,10 +169,10 @@ async fn purge_leaves_nothing_that_references_or_identifies_the_account() { VALUES (uuidv7(), '{user}', '{{\"kind\": \"account_enabled\"}}'); INSERT INTO authorization_requests ( id, secret_digest, client_id, redirect_uri, client_state, pkce_challenge, scopes, - audience, interaction, expires_at, hinted_user_id + audience, interaction, expires_at, hinted_user_id, digest_key ) VALUES ( uuidv7(), uuid_send('{user}'), '{client}', 'https://client.example/callback', 'state', - 'challenge', '[]', 'test', 'as_needed', now() + interval '5 minutes', '{user}' + 'challenge', '[]', 'test', 'as_needed', now() + interval '5 minutes', '{user}', 'test' ); INSERT INTO sessions (id, user_id, authentication_methods, authenticated_at, expires_at, last_seen_at) VALUES ('{session}', '{user}', '[\"passkey\"]', now(), now() + interval '1 day', now()); @@ -198,17 +198,17 @@ async fn purge_leaves_nothing_that_references_or_identifies_the_account() { VALUES (uuidv7(), '{user}', '{session}', 'enrollment', '\\x00', '{{}}', now() + interval '5 minutes'); INSERT INTO authorization_codes ( id, secret_digest, client_id, user_id, session_id, redirect_uri, pkce_challenge, - scopes, audience, expires_at, authentication + scopes, audience, expires_at, authentication, digest_key ) VALUES ( '{code}', uuid_send('{code}'), '{client}', '{user}', '{session}', 'https://client.example/callback', 'challenge', '[]', 'test', - now() + interval '1 minute', '{{}}' + now() + interval '1 minute', '{{}}', 'test' ); INSERT INTO refresh_token_families ( id, user_id, client_id, session_id, audience, scopes, authentication, authorization_code_id ) VALUES ('{family}', '{user}', '{client}', '{session}', 'test', '[]', '{{}}', '{code}'); - INSERT INTO refresh_tokens (id, family_id, secret_digest, expires_at) - VALUES (uuidv7(), '{family}', uuid_send('{family}'), now() + interval '1 day'); + INSERT INTO refresh_tokens (id, family_id, secret_digest, expires_at, digest_key) + VALUES (uuidv7(), '{family}', uuid_send('{family}'), now() + interval '1 day', 'test'); INSERT INTO announcements (id, subject, body, everyone, sent_at) VALUES ('{alone}', 'About you', 'Text', FALSE, now()), ('{shared}', 'About you both', 'Text', FALSE, now()), @@ -391,7 +391,7 @@ async fn purge_leaves_nothing_that_references_or_identifies_the_account() { /// A request that stores personal data about the account while it is being /// purged, such as a failed sign-in's IP address, leaves none behind. Here the -/// request holds migration 0022's key-share lock on the account until the purge +/// request holds the personal data trigger's key-share lock on the account until the purge /// waits for it, then commits: the purge must erase what it stored. #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] diff --git a/crates/database/src/repositories/deliveries/tests.rs b/crates/database/src/repositories/deliveries/tests.rs index 018afecc9..fbbc0c673 100644 --- a/crates/database/src/repositories/deliveries/tests.rs +++ b/crates/database/src/repositories/deliveries/tests.rs @@ -513,9 +513,10 @@ async fn revoking_a_session_queues_a_logout_token_for_each_client_to_tell() { VALUES($1,'Logout test','[]','[]',$2) RETURNING id ) INSERT INTO authorization_codes(id,secret_digest,client_id,user_id,session_id, - redirect_uri,pkce_challenge,scopes,audience,expires_at,authentication) + redirect_uri,pkce_challenge,scopes,audience,expires_at,authentication,digest_key) SELECT gen_random_uuid(),uuid_send(gen_random_uuid()),id,$3,$4, - 'https://app.example/callback','challenge','[]',id,now()+interval '1 minute','{}' + 'https://app.example/callback','challenge','[]',id,now()+interval '1 minute','{}', + 'test' FROM client", ) .bind(&client) diff --git a/crates/database/src/repositories/events/mod.rs b/crates/database/src/repositories/events/mod.rs index eedee4912..1ac80f832 100644 --- a/crates/database/src/repositories/events/mod.rs +++ b/crates/database/src/repositories/events/mod.rs @@ -592,7 +592,7 @@ impl EventRepository<'_> { kind, version, payload, - Json(&Actor::Unrecorded) as _, + Json(&Actor::Anonymous) as _, subject.as_uuid(), ) )?; @@ -600,6 +600,6 @@ impl EventRepository<'_> { } } -/// Database tests for recording, personal data and the migration. +/// Database tests for recording and personal data. #[cfg(test)] mod tests; diff --git a/crates/database/src/repositories/events/tests.rs b/crates/database/src/repositories/events/tests.rs index 61c21af32..412241c30 100644 --- a/crates/database/src/repositories/events/tests.rs +++ b/crates/database/src/repositories/events/tests.rs @@ -1,4 +1,4 @@ -//! Recording, personal data and the audit log import. +//! Recording and personal data. use super::*; use crate::{Database, DatabaseTransaction}; use sourceorigin_common::{ @@ -6,7 +6,7 @@ use sourceorigin_common::{ clients::RelatedOrigin, events::{RecordedOrigin, RevocationReason}, }; -use sqlx::{PgConnection, PgPool}; +use sqlx::PgPool; /// Inserts an active account to be the subject of recorded events. async fn insert_user(pool: &PgPool) -> UserId { @@ -302,75 +302,6 @@ async fn events_a_newer_release_wrote_read_as_unknown() { tx.rollback().await.expect("rollback"); } -/// Migration `0005` turns audit rows into imported events with their action, outcome -/// and metadata, and `0018` imports the rows written since, then drops the log. It -/// runs in a scratch schema, since the test database is migrated. -#[tokio::test] -#[ignore = "requires a disposable TEST_DATABASE_URL"] -async fn migration_imports_the_audit_log() { - let mut connection = Database::scratch_schema(..5).await; - let user = UserId::new(); - sqlx::query("INSERT INTO users(id,username,display_name) VALUES($1,'imported','Import test')") - .bind(user.as_uuid()) - .execute(&mut connection) - .await - .expect("user"); - let audit = async |connection: &mut PgConnection, action: &str, metadata: &str, age: i32| { - sqlx::query( - "INSERT INTO security_audit_log(id,user_id,action,outcome,request_metadata,created_at) - VALUES($1,$2,$3,'success',$4::jsonb,now() - make_interval(hours => $5))", - ) - .bind(EventId::new().as_uuid()) - .bind(user.as_uuid()) - .bind(action) - .bind(metadata) - .bind(age) - .execute(connection) - .await - .expect("audit row"); - }; - audit(&mut connection, "passkey.login", "{}", 3).await; - audit( - &mut connection, - "federation.link", - r#"{"provider":"github"}"#, - 2, - ) - .await; - Database::apply_migrations(&mut connection, 5..=5).await; - // The release before 0005 keeps writing to the log during that deploy. - audit(&mut connection, "passkey.login", "{}", 1).await; - // The rest bring the schema to the one this release reads. - Database::apply_migrations(&mut connection, 6..).await; - - let history = EventRepository::from_connection(&mut connection) - .history_for_user(user, 10) - .await - .expect("history"); - let imported: Vec<_> = history - .iter() - .map(|stored| match &stored.event { - RecordedEvent::Known(DomainEvent::Imported(audit)) => { - assert_eq!(stored.actor, Actor::Unrecorded); - (audit.action(), audit.outcome(), audit.metadata().clone()) - } - event => panic!("unexpected {event:?}"), - }) - .collect(); - assert_eq!( - imported, - [ - ("passkey.login", "success", serde_json::json!({})), - ( - "federation.link", - "success", - serde_json::json!({"provider": "github"}) - ), - ("passkey.login", "success", serde_json::json!({})), - ] - ); -} - /// An alert update's note is its event's reason, so it is read while the event's /// personal data is kept, and reads as none once that is erased. #[tokio::test] diff --git a/crates/database/src/repositories/handles/tests.rs b/crates/database/src/repositories/handles/tests.rs index ed2bf8aff..57e74c0ea 100644 --- a/crates/database/src/repositories/handles/tests.rs +++ b/crates/database/src/repositories/handles/tests.rs @@ -1,7 +1,5 @@ //! Renames, reclaims and their races, against the schema's keys. -use crate::{ - Database, DatabaseError, InsertUser, connection::MIGRATOR, repositories::UserRepository, -}; +use crate::{Database, DatabaseError, InsertUser, repositories::UserRepository}; use sourceorigin_common::{Handle, UserId}; /// The schema's `handle_skeleton` computes the Rust `Skeleton` of every handle, @@ -187,60 +185,3 @@ async fn locked_lookups_read_a_rename_they_waited_for() { let user = lookup.await.expect("lookup task"); assert_eq!((user.handle, user.profile_version), (renamed, 2)); } - -/// The handles migration refuses to run while a username breaks the handle rules -/// or looks like another, naming them all, and copies them once fixed. It runs in a -/// scratch schema, since the test database is migrated. -#[tokio::test] -#[ignore = "requires a disposable TEST_DATABASE_URL"] -async fn the_migration_refuses_usernames_that_are_not_handles() { - // Found by name, so renumbering it after another branch's migration needs no - // change here. - let handles = MIGRATOR - .iter() - .find(|migration| migration.description == "handles") - .expect("the handles migration"); - let mut connection = Database::scratch_schema(..handles.version).await; - for username in ["a_b", "sourceorigin", "s0urce0rigin", "fine"] { - sqlx::query("INSERT INTO users(id,username,display_name) VALUES($1,$2,'Migration test')") - .bind(UserId::new().as_uuid()) - .bind(username) - .execute(&mut connection) - .await - .expect("user"); - } - let migration = &handles.sql; - let refused = sqlx::raw_sql(migration) - .execute(&mut connection) - .await - .expect_err("invalid usernames"); - assert!( - refused - .to_string() - .contains("a_b, s0urce0rigin, sourceorigin"), - "{refused}" - ); - sqlx::raw_sql( - "UPDATE users SET username = 'a-b' WHERE username = 'a_b'; - UPDATE users SET username = 'renamed' WHERE username = 's0urce0rigin'", - ) - .execute(&mut connection) - .await - .expect("rename"); - sqlx::raw_sql(migration) - .execute(&mut connection) - .await - .expect("migration"); - let copied: Vec<(String, bool)> = sqlx::query_as( - "SELECT h.handle, u.handle_changed_at = u.created_at - FROM handles h JOIN users u ON u.id = h.user_id - WHERE h.released_at IS NULL ORDER BY h.handle", - ) - .fetch_all(&mut connection) - .await - .expect("handles"); - assert_eq!( - copied, - ["a-b", "fine", "renamed", "sourceorigin"].map(|handle| (handle.to_owned(), true)) - ); -} diff --git a/crates/database/src/repositories/maintenance/mod.rs b/crates/database/src/repositories/maintenance/mod.rs index 6ff9dcad2..edecc5d0a 100644 --- a/crates/database/src/repositories/maintenance/mod.rs +++ b/crates/database/src/repositories/maintenance/mod.rs @@ -22,9 +22,8 @@ sourceorigin_common::str_enum! { pub struct DigestUsage { /// The kind of record. pub secret: DigestedSecret, - /// The digest key's fingerprint; `None` for digests made before fingerprints - /// were recorded, under the key derived from the PEM signing key. - pub digest_key: Option, + /// The digest key's fingerprint. + pub digest_key: String, /// How many of them are stored. pub stored: u64, } @@ -49,7 +48,7 @@ impl MaintenanceRepository<'_> { sqlx::query_as!( DigestUsage, r#"SELECT - secret AS "secret!: DigestedSecret", digest_key, + secret AS "secret!: DigestedSecret", digest_key AS "digest_key!", count(*) AS "stored!: Unsigned" FROM ( SELECT 'authorization_request' AS secret, digest_key @@ -337,8 +336,9 @@ impl MaintenanceRepository<'_> { LIMIT $1 FOR UPDATE SKIP LOCKED )", - // A purged account's handles were released at its purge (migration - // 0042), and stay reserved a year, so nobody takes one to pass for it. + // A purged account's handles were released at its purge (the + // `handles_release_purged` trigger), and stay reserved a year, so + // nobody takes one to pass for it. "DELETE FROM handles WHERE ctid IN ( SELECT ctid diff --git a/crates/database/src/repositories/oidc/clients.rs b/crates/database/src/repositories/oidc/clients.rs index f857cd3ef..f974af599 100644 --- a/crates/database/src/repositories/oidc/clients.rs +++ b/crates/database/src/repositories/oidc/clients.rs @@ -23,7 +23,7 @@ use sqlx::types::Json; /// A registered client with its exact URI allowlists. A deleted client is still /// returned, disabled, with its `deleted_at`, but without its name, redirect URIs -/// or back-channel logout URI, which migration 0026's trigger erases. +/// or back-channel logout URI, which the `oidc_clients_scrub_deleted` trigger erases. #[derive(Clone, Debug, PartialEq, Eq, Serialize)] #[expect( clippy::struct_excessive_bools, diff --git a/crates/database/src/repositories/oidc/tests.rs b/crates/database/src/repositories/oidc/tests.rs index d9f05c597..258787b6f 100644 --- a/crates/database/src/repositories/oidc/tests.rs +++ b/crates/database/src/repositories/oidc/tests.rs @@ -1,6 +1,6 @@ //! Client registrations against a real database: secret rotation, the origins -//! public clients may call from, when pushed authorization requests can be claimed, -//! and which clients of live sessions the back-channel logout migration finds. +//! public clients may call from, and when pushed authorization requests can be +//! claimed. use crate::repositories::{EventRepository, OidcRepository, UserRepository}; use crate::{Database, DatabaseTransaction, InsertAuthorizationRequest, InsertUser, RecordedEvent}; use chrono::{DateTime, Duration, Utc}; @@ -267,66 +267,6 @@ async fn purging_an_owner_needs_its_live_clients_deleted() { } } -/// The back-channel logout migration finds the clients of live sessions in what is -/// left of their exchanges: redeemed codes and refresh families. Unredeemed codes -/// and sessions that ended are left out. -#[tokio::test] -#[ignore = "requires a disposable TEST_DATABASE_URL"] -async fn migration_finds_the_clients_of_live_sessions() { - let mut connection = Database::scratch_schema(..13).await; - let user = UserId::new(); - let (live, revoked, expired) = (SessionId::new(), SessionId::new(), SessionId::new()); - sqlx::raw_sql(&format!( - "INSERT INTO users (id, username, display_name) VALUES ('{user}', 'backfill', 'Backfill'); - INSERT INTO oidc_clients (id, display_name, allowed_scopes, allowed_audiences) - SELECT id, id, '[]'::jsonb, '[]'::jsonb - FROM unnest(array['coded', 'refreshed', 'unredeemed']) id; - INSERT INTO sessions ( - id, user_id, authentication_methods, authenticated_at, expires_at, - last_seen_at, revoked_at - ) VALUES - ('{live}', '{user}', '[]', now(), now() + interval '1 day', now(), NULL), - ('{revoked}', '{user}', '[]', now(), now() + interval '1 day', now(), now()), - ('{expired}', '{user}', '[]', now() - interval '2 days', now() - interval '1 day', - now(), NULL); - INSERT INTO authorization_codes ( - id, secret_digest, client_id, user_id, session_id, redirect_uri, - pkce_challenge, scopes, audience, expires_at, authentication, consumed_at - ) - SELECT gen_random_uuid(), uuid_send(gen_random_uuid()), client, '{user}', session, - 'https://app.example/callback', 'challenge', '[]'::jsonb, client, now(), - '{{}}'::jsonb, consumed - FROM (VALUES - ('coded', '{live}'::uuid, now()), - ('unredeemed', '{live}', NULL), - ('coded', '{revoked}', now()) - ) code(client, session, consumed); - INSERT INTO refresh_token_families ( - id, user_id, client_id, session_id, audience, scopes, authentication - ) - SELECT gen_random_uuid(), '{user}', 'refreshed', session, 'refreshed', '[]'::jsonb, - '{{}}'::jsonb - FROM unnest(array['{live}', '{expired}']::uuid[]) session;" - )) - .execute(&mut connection) - .await - .expect("sessions and their exchanges"); - - Database::apply_migrations(&mut connection, 13..=13).await; - let found: Vec<(uuid::Uuid, String)> = - sqlx::query_as("SELECT session_id, client_id FROM oidc_session_clients ORDER BY client_id") - .fetch_all(&mut connection) - .await - .expect("session clients"); - assert_eq!( - found, - [ - (live.as_uuid(), "coded".to_owned()), - (live.as_uuid(), "refreshed".to_owned()), - ] - ); -} - /// Purging an app's owner erases the app's related origins from events that name /// neither the owner nor its account: an operator's approval and another person's /// inline sign-in. That person's own personal data stays. diff --git a/crates/database/src/repositories/signing_keys/mod.rs b/crates/database/src/repositories/signing_keys/mod.rs index 33edbbc3d..c3eaddeeb 100644 --- a/crates/database/src/repositories/signing_keys/mod.rs +++ b/crates/database/src/repositories/signing_keys/mod.rs @@ -24,7 +24,7 @@ pub struct StoredSigningKey { pub public_jwk: Jwk, /// Its sealed PKCS#8 private key; `None` once retired. pub sealed_private_key: Option>, - /// When it was generated or imported. + /// When it was generated. pub created_at: DateTime, /// When it started signing. pub activated_at: Option>, diff --git a/crates/database/src/repositories/tokens/tests.rs b/crates/database/src/repositories/tokens/tests.rs index cab0f1a93..85df3600b 100644 --- a/crates/database/src/repositories/tokens/tests.rs +++ b/crates/database/src/repositories/tokens/tests.rs @@ -106,9 +106,9 @@ impl Grant { sqlx::query( "INSERT INTO authorization_codes ( id, secret_digest, client_id, user_id, session_id, redirect_uri, - pkce_challenge, scopes, audience, expires_at, authentication + pkce_challenge, scopes, audience, expires_at, authentication, digest_key ) VALUES ($1, $2, $3, $4, $5, $6, 'challenge', '[\"openid\"]', 'test', - now() + interval '1 minute', $7)", + now() + interval '1 minute', $7, 'test')", ) .bind(grant.code.as_uuid()) .bind(&grant.code_digest) diff --git a/crates/database/tests/recoveries.rs b/crates/database/tests/recoveries.rs index 5bbae2931..653d2369f 100644 --- a/crates/database/tests/recoveries.rs +++ b/crates/database/tests/recoveries.rs @@ -1,6 +1,6 @@ //! Persistence guarantees behind account recoveries: their links, their state, -//! and the database backstops that hold for every writer, a release older than -//! recovery included. +//! and the database backstops that hold for every writer, even one not granted +//! `account_recoveries`. #![expect( clippy::expect_used, reason = "a test, whose setup helpers fail it with a message rather than return errors" @@ -95,9 +95,9 @@ async fn account(db: &Database) -> UserId { user } -/// A role like the runtime role between the migration and provisioning: it may -/// use every table but `account_recoveries`, which the migration created after -/// its grants. Connected as that role, the database the triggers run under. +/// A role like the runtime role, but without `account_recoveries`: it may use +/// every other table. Connected as that role, the database the triggers run +/// under. struct Limited { /// Connected as the role. db: Database, @@ -188,7 +188,7 @@ async fn probation(db: &Database, user: UserId) -> (RecoveryId, PasskeyId) { } /// Inserts a session of `user`, signed in with `passkey` and confirmed at `now` -/// when `confirmed`, as any release writes one. +/// when `confirmed`, as any writer could. async fn session( db: &Database, user: UserId, @@ -343,8 +343,8 @@ async fn one_open_recovery_per_account() { .expect("once the first is cancelled"); } -/// A passkey of a recovery in probation never confirms a session, whichever -/// release writes it, even without access to `account_recoveries`; nor does a +/// A passkey of a recovery in probation never confirms a session, whoever +/// writes it, even without access to `account_recoveries`; nor does a /// confirmation that names no passkey. An older passkey still confirms, and so /// does any once the recovery settled or was undone. #[tokio::test] @@ -390,7 +390,7 @@ async fn a_probation_passkey_never_confirms_a_session() { } /// No account is made an administrator while a recovery of it can be undone, -/// whichever release grants it: neither while its link works, nor during its +/// whoever grants it: neither while its link works, nor during its /// probation. Once the link expired unused, or the recovery settled, it may be. #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] @@ -414,8 +414,8 @@ async fn no_grant_while_a_recovery_can_be_undone() { limited.drop(&owner).await; } -/// While a recovery can be undone, no passkey but its own is revoked, whichever -/// release revokes it, so nothing takes away the passkeys that can undo it. +/// While a recovery can be undone, no passkey but its own is revoked, whoever +/// revokes it, so nothing takes away the passkeys that can undo it. /// Once the link expired unused, or the recovery settled or was undone, any may /// be. #[tokio::test] diff --git a/crates/ui/src/admin/events.rs b/crates/ui/src/admin/events.rs index fa0d6c4f5..d308d880f 100644 --- a/crates/ui/src/admin/events.rs +++ b/crates/ui/src/admin/events.rs @@ -105,7 +105,7 @@ impl EventRow<'_> { Ok(Actor::Client { client_id }) => (format!("the app {client_id}"), false), Ok(Actor::System { job }) => (format!("the {} job", Self::job(job)), false), Ok(Actor::Anonymous) => ("someone not signed in".to_owned(), false), - Ok(Actor::Unrecorded) | Err(_) => ("nobody recorded".to_owned(), false), + Err(_) => ("nobody recorded".to_owned(), false), } } @@ -490,9 +490,6 @@ impl EventRow<'_> { DomainEvent::AlertCleared { alert_id, alert } => { Self::alert("Alert cleared", alert_id, &alert) } - DomainEvent::Imported(audit) => { - Description::new(format!("{} ({})", audit.action(), audit.outcome())) - } } } diff --git a/crates/ui/src/settings/timeline.rs b/crates/ui/src/settings/timeline.rs index 44fc000f0..9fa930291 100644 --- a/crates/ui/src/settings/timeline.rs +++ b/crates/ui/src/settings/timeline.rs @@ -223,14 +223,6 @@ impl HistoryRow<'_> { HistoryEntry::CompromiseReported { .. } => { "You reported activity that wasn’t you".to_owned() } - HistoryEntry::Legacy { action, outcome } => { - let failed = if outcome == "success" { - "" - } else { - " (failed)" - }; - format!("{}{failed}", Self::legacy(action)) - } } } @@ -274,24 +266,6 @@ impl HistoryRow<'_> { } } - /// A row the audit log recorded before typed history, by its logged action. - fn legacy(action: &str) -> &str { - match action { - "account.create" => "Account created", - "passkey.login" => "Signed in with a passkey", - "passkey.add" => "Passkey added", - "passkey.rename" => "Passkey renamed", - "passkey.remove" => "Passkey removed", - "settings.unlock" => "Settings unlocked", - "federation.login" => "Signed in with a social provider", - "federation.link" => "Social sign-in linked", - "federation.unlink" => "Social sign-in unlinked", - "refresh.replay" => "An app’s sign-in was reused and revoked", - "refresh.policy_rejected" => "An app’s access ended", - other => other, - } - } - /// Whether it is something to look at: a failure, a report, or an /// administrator's change. pub(crate) const fn worrying(&self) -> bool { @@ -332,9 +306,7 @@ impl HistoryRow<'_> { HistoryActor::Operator => "By a SourceOrigin operator", HistoryActor::Client => "By an app", HistoryActor::System => "Automatically by SourceOrigin", - HistoryActor::Account | HistoryActor::Anonymous | HistoryActor::Unrecorded => { - return None; - } + HistoryActor::Account | HistoryActor::Anonymous => return None, }; Some(match self.reason { Some(reason) => format!("{actor}: “{reason}”"), diff --git a/docs/dev/architecture/database.md b/docs/dev/architecture/database.md index dd662c192..8b1e7f294 100644 --- a/docs/dev/architecture/database.md +++ b/docs/dev/architecture/database.md @@ -137,9 +137,10 @@ Important invariants: from the events about them, the account itself, then the personal data of the events it is the subject or actor of, in the same transaction. Its handles stay in `handles` without an owner, so nobody claims them again. The personal data goes last: storing an event's personal data - key-share locks each account the event names (migration `0022`'s trigger), and - only deleting the account conflicts with that lock. The account lock's `FOR NO - KEY UPDATE` does not, despite what that migration's comment says. So the + key-share locks each account the event names (the + `event_personal_data_skip_purged_accounts` trigger), and only deleting the + account conflicts with that lock; the account lock's `FOR NO KEY UPDATE` does + not. So the delete waits for every request that stored personal data while the account existed, and the next statement erases it; a later one waits for the purge, finds the account gone and stores none. @@ -342,10 +343,9 @@ server. It still takes the advisory locks `try_exclusive` uses. Trigger functions run as the role that fires them, except a trigger that reads or writes a table its own migration creates: the runtime role is granted that table only after the migrations, while the previous release already fires the trigger. -That function runs as its owner (`SECURITY DEFINER`), like the one migration -`0013` uses to record redeemed codes in `oidc_session_clients`, or those -migration `0019` uses to hold account recoveries' rules for every release, and -only its owner may execute it. A role that could create temporary tables and +That function runs as its owner (`SECURITY DEFINER`), like the one that records +redeemed codes in `oidc_session_clients`, or those that hold account +recoveries' rules for every writer, and only its owner may execute it. A role that could create temporary tables and types could otherwise attach the function to a table of its own and have it run that type's cast as the owner. The runtime role no longer can, but a test still fails for any such function others may execute. @@ -367,9 +367,7 @@ back-channel logout tokens of the clients that received tokens from it (`oidc_session_clients`, which a trigger fills whenever any release redeems a code). The repository method underneath is private to the crate, so no revocation can skip the event. Refreshes are too frequent to be -events. `Imported` holds the rows of `security_audit_log`, the log events replaced, -verbatim; only migrations write it, and its fields are private, so it can only be -read back. `repositories/events/` stores events and the personal data split below. +events. `repositories/events/` stores events and the personal data split below. Variants hold only typed IDs, enums, scopes, timestamps and counts, so a secret, token, `WebAuthn` state or raw header cannot end up in one. Anything that identifies @@ -413,9 +411,8 @@ always reads it. content the audit chain covers; see [Audit chain](#audit-chain). - `event_personal_data`, one row per event, holds the client IP, the user agent family and every `Personal` payload value, keyed by its JSON pointer. The - family's browser is in `user_agent_family`, the one value releases before - migration `0010` read there, and its platform in `platform`; older rows have no - platform and read it as `other`. On write + family's browser is in `user_agent_family` and its platform in `platform`. On + write the repository moves each `Personal` value there and leaves `"$erased"` in the payload; on read it merges them back. Once the row is gone, they and the request origin read as `Personal::Erased`. Deleting it never breaks the event. @@ -518,8 +515,8 @@ unsealed, so recording never waits on the chain head. Auth's sealer job, under `insert_checkpoint`. The repository never hashes or signs: auth computes the hashes from `EventContent`, whose serialization is the canonical event, so a tampered row reads back and fails verification rather than failing to decode. `seal` also -stores the canonical event's format in `chain_format`, which `unsealed` takes -from the sealer, and `chain` returns each event's `(txid, sequence)` beside it, +stores the canonical event's format in `chain_format`, which `unsealed` sets to +`EventContent::NEWEST_FORMAT`, and `chain` returns each event's `(txid, sequence)` beside it, for verification to check against chain order. `newest_checkpoints` reads checkpoints newest first, for the sealer to find the newest that verifies. @@ -543,15 +540,15 @@ run as the schema owner, deletes sealed events: it sets `sourceorigin.audit_prun its own transaction, then moves the anchor (`audit_anchor`) to the checkpoint it pruned through. The anchor only moves forward, so of two concurrent prunes, the one that would move it back fails. Personal data is not covered, so retention -keeps deleting `event_personal_data` freely. Migration `0006`'s comment says -nothing deletes events; pruning does. `deliveries.event_id` has no foreign key, -so a delivery may name an event already pruned. +keeps deleting `event_personal_data` freely. `deliveries.event_id` has no +foreign key, so a delivery may name an event already pruned. Verification tests need history no other test shares: `Database::isolated` (behind `test-util`) migrates a schema of its own, and `audit().tamper` applies the -changes an attacker could make, with the triggers disabled. The guards migration -`0035` adds look tables up in the schema they were migrated into, so they guard -that schema's chain too. +changes an attacker could make, with the triggers disabled. The history guards +(`guard_personal_data_insert`, `guard_seal_order`, `guard_new_checkpoint`) look +tables up in the schema they were migrated into, so they guard that schema's +chain too; so does `limit_passkeys`, for its passkeys. ### Security history diff --git a/docs/dev/extending/migration.md b/docs/dev/extending/migration.md index fa6546117..b4a1afc6a 100644 --- a/docs/dev/extending/migration.md +++ b/docs/dev/extending/migration.md @@ -28,7 +28,7 @@ must keep that release working. ## 1. Number it Create `crates/database/migrations/_.sql`, numbered one after the -latest migration on `main`, such as `0035_recovery_codes.sql`. Numbers count up +latest migration on `main`, such as `0002_recovery_codes.sql`. Numbers count up from `0001` with no gap or repeat, which `migration_versions_are_unique_and_contiguous` checks. If another branch merges a migration first, rebase and renumber yours. @@ -59,8 +59,8 @@ release could violate, waits for a later release, once no deployed code uses the old shape. A migration may break the rule only when the previous release cannot be harmed, -and then says why in its own comments. `0034_notification_emails.sql` cancels -the deliveries an older kind of message left, since there are no real users yet: +and then says why in its own comments, as one cancelling the deliveries of a +kind of message that no longer exists might, since there are no real users yet: ```sql -- Those still waiting to be sent, or failed, are cancelled rather than @@ -130,11 +130,11 @@ skip, then `just db prepare-check`, which fails when a migration breaks a cached query or the cache holds a query the code no longer uses. A migration that changes existing rows gets a test of its own: it migrates a -schema up to the migration before it, writes rows in the old shape, applies the -migration and checks the result, as -`the_migration_refuses_usernames_that_are_not_handles` does in -`crates/database/src/repositories/handles/tests.rs`. It finds the migration by its -name, so renumbering needs no change. +scratch schema up to the migration before it, writes rows in the old shape, +applies the migration and checks the result. It finds the migration in +`MIGRATOR` by its name, so renumbering needs no change. The helpers for this, +`Database::scratch_schema` and `Database::apply_migrations`, went with the last +such test; bring them back from git history. To look at the migrated schema yourself: diff --git a/docs/dev/extending/notification.md b/docs/dev/extending/notification.md index 9d766b77d..b1de6714c 100644 --- a/docs/dev/extending/notification.md +++ b/docs/dev/extending/notification.md @@ -96,8 +96,8 @@ whose email the owner turns off in their inbox's **Email preferences**. Only announcements are wired today. A new category needs more than its variant, with its `label` and `description`, which settings and the dashboard show: -- a migration widening the `CHECK` on `notification_preferences.category` - (`0039_notification_preferences.sql`), or saving the preference fails; +- a migration widening the `CHECK` on `notification_preferences.category`, or + saving the preference fails; - a check in the channel that sends its email, when the email is queued and when it is sent, as the `announcements_emailed` SQL function does for the `announcement` channel: the `email` channel checks no preference; diff --git a/docs/dev/operations/signing-keys.md b/docs/dev/operations/signing-keys.md index c24bf54a6..75a564084 100644 --- a/docs/dev/operations/signing-keys.md +++ b/docs/dev/operations/signing-keys.md @@ -243,5 +243,4 @@ and per key, until cleanup deletes them. It names each key: - `current`: `AUTH_TOKEN_DIGEST_KEY`. - `accepted`: `AUTH_TOKEN_DIGEST_KEY_ACCEPTED`. -- `unrecorded`: made before digests recorded their key's fingerprint. - `unknown`: neither configured key. diff --git a/docs/dev/security/account-recovery.md b/docs/dev/security/account-recovery.md index d001b7f96..5aece280a 100644 --- a/docs/dev/security/account-recovery.md +++ b/docs/dev/security/account-recovery.md @@ -38,7 +38,8 @@ 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/mod.rs`), migration `0019_account_recoveries`, the CLI's +`crates/ui/src/recovery/mod.rs`), the account recoveries section of +`crates/database/migrations/0001_initial.sql`, 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; @@ -357,13 +358,11 @@ support unlinks (the owner can't during a probation); and the P3 edits. ## Database backstops The rules above live in Rust, which gives the typed answer and the right error. -Three triggers in migration `0019` hold the ones a way in depends on for every -writer, including a replica of the previous release during a deploy, a release -rolled back below this one (migrations aren't reverted), and any future code -path. Each runs as its owner (`SECURITY DEFINER`, `search_path` ending in -`pg_temp`, executable by its owner only), because the previous release fires it -before the runtime role is granted `account_recoveries`. Each test below runs -as a role with no grant on that table. +Three triggers hold the ones a way in depends on for every writer, including a +release rolled back below the current one (migrations aren't reverted), and any +future code path. Each runs as its owner (`SECURITY DEFINER`, `search_path` +ending in `pg_temp`, executable by its owner only), so it holds even for a role +with no grant on `account_recoveries`. Each test below runs as such a role. - **B1.** `sessions_no_probation_confirmation` clears a session's passkey confirmation when the passkey it names is a probation passkey, or when it diff --git a/docs/dev/security/audit-history.md b/docs/dev/security/audit-history.md index bac68fc95..fbf89abda 100644 --- a/docs/dev/security/audit-history.md +++ b/docs/dev/security/audit-history.md @@ -31,18 +31,16 @@ chain_hash = SHA-256(previous chain_hash || SHA-256(canonical event)) The first event chains from 32 zero bytes, or, after pruning, from the anchor. The canonical event is the RFC 8785 (JCS) form of the event's row: `position`, `id`, `kind`, `version`, `occurred_at` (RFC 3339 in UTC, with microseconds), -`actor`, `subject`, `client`, `session`, `trace_id` and `payload`, as stored. +`actor`, `subject`, `client`, `session`, `trace_id`, `payload`, as stored, and +`format`. Each sealed event records the format of its canonical event in `chain_format`, -so a later format can add a field without breaking the hashes of events sealed -before it. Format 1, the original, has no `format` field. Format 2 adds only -`"format": 2`, and every later format names itself the same way. Auth seals -format 2 and verifies both. A format is sealed only once the release before -verifies it, so a rolling deploy or a rollback by one release reads every -event. Once format 2 is sealed, roll back no further than #369, the first -release that reads it: an older one reports those events changed and stops -signing. Verification refuses a format it does not know, rather than report the -chain broken. +and the canonical event names it in a `format` field, so a later format can add +a field without breaking the hashes of events sealed before it. Auth seals and +verifies format 1, the only one so far. A new format is sealed only once the +release before verifies it, so a rolling deploy or a rollback by one release +reads every event. Verification refuses a format it does not know, rather than +report the chain broken. The sealer works in the order `(txid, sequence)`, and only on events whose transaction, and every older one, has finished. No event can