From 16bb112c1769bb4833e7e996e50a57d34f8bc4d7 Mon Sep 17 00:00:00 2001 From: piquel Date: Fri, 6 Nov 2026 23:22:40 +0100 Subject: [PATCH 1/2] test(database): merge overlapping tests and share their fixtures - One table-driven transport test replaces five URL validation tests. - The purged handle tests in deletions and handles become one test that goes from purge through release to reuse. - Migration tests share Database::scratch_schema and apply_migrations; the audit import now migrates to the current schema. - Lock-wait tests share Database::backend and wait_for_lock. - Account deletion tails in the events and deliveries tests go, since the purge test covers them, and so does a timestamp round-trip. --- crates/database/src/connection/mod.rs | 61 +++++ crates/database/src/connection/tests.rs | 221 +++++++----------- .../src/repositories/deletions/tests.rs | 94 ++------ .../src/repositories/deliveries/tests.rs | 17 +- .../database/src/repositories/events/tests.rs | 57 +---- .../src/repositories/handles/tests.rs | 71 +++--- .../database/src/repositories/oidc/tests.rs | 44 +--- .../database/src/repositories/tokens/tests.rs | 46 +--- crates/database/tests/security.rs | 8 +- 9 files changed, 213 insertions(+), 406 deletions(-) diff --git a/crates/database/src/connection/mod.rs b/crates/database/src/connection/mod.rs index a0fb3af20..4830da9ec 100644 --- a/crates/database/src/connection/mod.rs +++ b/crates/database/src/connection/mod.rs @@ -397,6 +397,67 @@ impl Database { .expect("migrate"); 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 { + sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(connection) + .await + .expect("backend pid") + } + + /// Waits until the server process `backend` is blocked on a lock. + pub(crate) async fn wait_for_lock(pool: &PgPool, backend: i32) { + tokio::time::timeout(Duration::from_secs(10), async { + while !sqlx::query_scalar::<_, bool>( + "SELECT EXISTS ( + SELECT FROM pg_stat_activity WHERE pid = $1 AND wait_event_type = 'Lock' + )", + ) + .bind(backend) + .fetch_one(pool) + .await + .expect("wait state") + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the transaction waits for a lock"); + } } /// Focused tests for this module and its security contracts. diff --git a/crates/database/src/connection/tests.rs b/crates/database/src/connection/tests.rs index 4ba371f2c..636f9c192 100644 --- a/crates/database/src/connection/tests.rs +++ b/crates/database/src/connection/tests.rs @@ -1,116 +1,95 @@ //! Focused persistence and security contract tests. use super::{Database, DatabaseConfig, Limit, MIGRATOR, RuntimeRole, Scope}; -use crate::DatabaseError; -use sqlx::postgres::PgSslMode; +use crate::{DatabaseConnectionError, DatabaseError}; use std::time::Duration; -/// TCP requires verified TLS unless plaintext is explicitly selected. -#[test] -fn production_requires_verified_tls() { - assert!( - DatabaseConfig::new("postgres://db.example/piquel", 1, Duration::from_secs(1)).is_err() - ); - assert!( - DatabaseConfig::new( - "postgres://db.example/piquel?sslmode=verify-full", - 1, - Duration::from_secs(1) - ) - .is_ok() - ); - assert!( - DatabaseConfig::new( - "postgres://db.example/piquel?ssl-mode=verify-full", - 1, - Duration::from_secs(1) - ) - .is_ok() - ); - for mode in ["prefer", "require", "verify-ca"] { - assert!( - DatabaseConfig::new( - &format!("postgres://db.example/piquel?sslmode={mode}"), - 1, - Duration::from_secs(1) - ) - .is_err(), - "accepted unverified TLS mode {mode}" - ); - } -} -/// Explicit plaintext is accepted without silently enabling opportunistic TLS. -#[test] -fn plaintext_tcp_requires_explicit_opt_in() { - let config = DatabaseConfig::new( - "postgres://postgres:5432/piquel?sslmode=disable", - 1, - Duration::from_secs(1), - ) - .expect("explicit plaintext is allowed"); - assert!(matches!(config.options.get_ssl_mode(), PgSslMode::Disable)); -} -/// Unix sockets require an absolute path and cannot replace remote TCP hosts. -#[test] -fn unix_sockets_are_explicit_and_cannot_override_tcp_hosts() { - let config = DatabaseConfig::new( - "postgres://piquel:password@localhost/piquel?host=/run/postgresql&sslmode=disable", - 1, - Duration::from_secs(1), - ) - .expect("local socket does not require TLS"); - assert_eq!( - config.options.get_socket().map(std::path::PathBuf::as_path), - Some(std::path::Path::new("/run/postgresql")) - ); - for url in [ - "postgres://db.example/piquel?host=/run/postgresql", - "postgres://localhost/piquel?host=relative/path", - "postgres://localhost/piquel?host=/run/postgresql&host=db.example", - "postgres://localhost/piquel?host=db.example&host=/run/postgresql", - "postgres://localhost/piquel?host=/run/postgresql&hostaddr=192.0.2.1", - ] { - assert!(DatabaseConfig::new(url, 1, Duration::from_secs(1)).is_err()); - } -} -/// Repeated transport settings and host overrides are rejected before `SQLx` parses them. + +/// TCP needs verified TLS or an explicit `sslmode=disable`, loopback included; a +/// Unix socket needs an absolute path under `localhost`. Repeated transport +/// settings and address overrides are refused before `SQLx` parses them. #[test] -fn production_rejects_ambiguous_tls_modes_and_host_overrides() { - for url in [ - "postgres://db.example/piquel?sslmode=verify-full&sslmode=disable", - "postgres://db.example/piquel?sslmode=disable&sslmode=verify-full", - "postgres://db.example/piquel?sslmode=verify-full&ssl-mode=disable", - "postgres://db.example/piquel?sslmode=verify-full&ssl-mode=verify-full", - "postgres://db.example/piquel?sslmode=verify-full&host=elsewhere.example", - "postgres://db.example/piquel?sslmode=verify-full&hostaddr=127.0.0.1", +fn transport_is_verified_tls_a_local_socket_or_explicit_plaintext() { + use DatabaseConnectionError::{AmbiguousTransport, InsecureTransport, InvalidSocket}; + for (url, expected) in [ + ("postgres://db.example/piquel?sslmode=verify-full", None), + ("postgres://db.example/piquel?ssl-mode=verify-full", None), + ("postgres://db.example/piquel?sslmode=disable", None), + ("postgres://[::1]/piquel?sslmode=disable", None), + ("postgres://localhost/piquel?host=/run/postgresql", None), + ("postgres://db.example/piquel", Some(InsecureTransport)), + ("postgres://localhost/piquel", Some(InsecureTransport)), + ("postgres://127.0.0.1/piquel", Some(InsecureTransport)), + ( + "postgres://db.example/piquel?sslmode=prefer", + Some(InsecureTransport), + ), + ( + "postgres://db.example/piquel?sslmode=require", + Some(InsecureTransport), + ), + ( + "postgres://db.example/piquel?sslmode=verify-ca", + Some(InsecureTransport), + ), + ( + "postgres://db.example/piquel?host=/run/postgresql", + Some(InvalidSocket), + ), + ( + "postgres://localhost/piquel?host=relative/path", + Some(InvalidSocket), + ), + ( + "postgres://db.example/piquel?sslmode=verify-full&host=elsewhere.example", + Some(InvalidSocket), + ), + ( + "postgres://db.example/piquel?sslmode=verify-full&sslmode=disable", + Some(AmbiguousTransport), + ), + ( + "postgres://db.example/piquel?sslmode=disable&ssl-mode=verify-full", + Some(AmbiguousTransport), + ), + ( + "postgres://db.example/piquel?sslmode=verify-full&hostaddr=127.0.0.1", + Some(AmbiguousTransport), + ), + ( + "postgres://localhost/piquel?host=/run/postgresql&host=db.example", + Some(AmbiguousTransport), + ), ] { - assert!( - DatabaseConfig::new(url, 1, Duration::from_secs(1)).is_err(), - "accepted ambiguous database URL: {url}" + let result = DatabaseConfig::new(url, 1, Duration::from_secs(1)); + assert_eq!( + result.err().map(|error| error.to_string()), + expected.map(|error| error.to_string()), + "{url}" ); } } -/// Loopback TCP also needs an explicit plaintext opt-in. +/// Startup failures name the scheme or pool bound at fault, keep the parser's +/// error as their source and never print credentials. #[test] -fn loopback_requires_explicit_transport() { - for host in ["localhost", "[::1]", "127.0.0.1"] { - assert!( - DatabaseConfig::new( - &format!("postgres://{host}/test"), - 1, - Duration::from_secs(1) - ) - .is_err() - ); - assert!( - DatabaseConfig::new( - &format!("postgres://{host}/test?sslmode=disable"), - 1, - Duration::from_secs(1) - ) - .is_ok() - ); +fn configuration_errors_name_the_setting_without_credentials() { + let timeout = Duration::from_secs(1); + let verified = "postgres://db.example/test?sslmode=verify-full"; + assert!(matches!( + DatabaseConfig::new("https://db.example/test", 1, timeout), + Err(DatabaseConnectionError::Scheme) + )); + for (max_connections, timeout) in [(0, timeout), (1, Duration::ZERO)] { + assert!(matches!( + DatabaseConfig::new(verified, max_connections, timeout), + Err(DatabaseConnectionError::ZeroPoolBound) + )); } + let error = DatabaseConfig::new("not a URL", 1, timeout).expect_err("absolute URL"); + assert!(std::error::Error::source(&error).is_some()); + let error = DatabaseConfig::new("postgres://user:secret@db.example/test", 1, timeout) + .expect_err("verified transport"); + assert!(!error.to_string().contains("secret")); } /// Cleanup skips rows a live request has locked instead of waiting on them. @@ -225,46 +204,6 @@ async fn cleanup_keeps_redeemed_codes_while_their_session_is_live() { assert_eq!(link().await, None, "an ended session releases its code"); } -/// Startup failures identify the invalid transport or pool setting without printing credentials. -#[test] -fn configuration_errors_name_the_constraint_and_preserve_parsers() { - use crate::DatabaseConnectionError; - let timeout = Duration::from_secs(1); - assert!(matches!( - DatabaseConfig::new("https://db.example/test", 1, timeout), - Err(DatabaseConnectionError::Scheme) - )); - assert!(matches!( - DatabaseConfig::new("postgres://db.example/test?sslmode=verify-full", 0, timeout), - Err(DatabaseConnectionError::ZeroPoolBound) - )); - assert!(matches!( - DatabaseConfig::new( - "postgres://db.example/test?sslmode=verify-full", - 1, - Duration::ZERO - ), - Err(DatabaseConnectionError::ZeroPoolBound) - )); - assert!(matches!( - DatabaseConfig::new( - "postgres://db.example/test?sslmode=verify-full&ssl-mode=disable", - 1, - timeout - ), - Err(DatabaseConnectionError::AmbiguousTransport) - )); - assert!(matches!( - DatabaseConfig::new("postgres://db.example/test", 1, timeout), - Err(DatabaseConnectionError::InsecureTransport) - )); - let error = DatabaseConfig::new("not a URL", 1, timeout).expect_err("absolute URL"); - assert!(std::error::Error::source(&error).is_some()); - let error = DatabaseConfig::new("postgres://user:secret@db.example/test", 1, timeout) - .expect_err("verified transport"); - assert!(!error.to_string().contains("secret")); -} - /// Migration versions count up from 1 with no gaps or repeats. Two branches /// that each add the next migration under different names fail here once the /// second is rebased, instead of failing every database test at runtime. diff --git a/crates/database/src/repositories/deletions/tests.rs b/crates/database/src/repositories/deletions/tests.rs index 6f8e3f727..53e8b0474 100644 --- a/crates/database/src/repositories/deletions/tests.rs +++ b/crates/database/src/repositories/deletions/tests.rs @@ -3,57 +3,20 @@ use super::*; use crate::{Database, DatabaseTransaction, EventRepository, InsertUser, RestoreToken}; use chrono::Duration; use piquel_common::{ - AccountStatus, Handle, PasskeyId, Personal, Provider, SessionId, TokenId, + AccountStatus, PasskeyId, Personal, Provider, SessionId, TokenId, events::{Actor, Browser, DomainEvent, EventContext, Platform, RequestOrigin, UserAgentFamily}, }; use piquel_common::{AuthenticationMethod, events::SignInFailure}; use sqlx::{Acquire, PgPool}; -use std::{net::IpAddr, time::Duration as StdDuration}; +use std::net::IpAddr; /// Inserts an active account whose handle is `prefix` and part of its ID. -async fn insert_user(pool: &PgPool, prefix: &str) -> (UserId, Handle) { - let user = InsertUser::named(prefix); +async fn insert_user(pool: &PgPool, prefix: &str) -> UserId { crate::UserRepository::from_pool(pool) - .insert(&user) + .insert(&InsertUser::named(prefix)) .await - .expect("user"); - (user.id, user.handle) -} - -/// Purges `user` in its own committed transaction. -async fn purge(pool: &PgPool, user: UserId) -> bool { - let mut tx = DatabaseTransaction::new(pool.begin().await.expect("transaction")); - let purged = tx.deletions().purge(user).await.expect("purge"); - tx.commit().await.expect("commit"); - purged -} - -/// A purged account's handles stay without an owner, so no account claims them -/// again until an operator releases them. -#[tokio::test] -#[ignore = "requires a disposable TEST_DATABASE_URL"] -async fn a_purged_accounts_handle_stays_taken() { - let pool = Database::test_pool().await; - let (user, handle) = insert_user(&pool, "retired").await; - assert!(purge(&pool, user).await); - assert!(!purge(&pool, user).await, "the account is gone"); - - let holder = crate::HandleRepository::from_pool(&pool) - .holder(&handle) - .await - .expect("lookup") - .expect("the handle stays"); - assert_eq!(holder.user_id, None); - let reuse = crate::UserRepository::from_pool(&pool) - .insert(&InsertUser { - handle, - ..InsertUser::named("again") - }) - .await; - assert!( - matches!(reuse, Err(DatabaseError::Conflict(_))), - "{reuse:?}" - ); + .expect("user") + .id } /// A restore token is found while unexpired and its passkey active, and a newer @@ -62,7 +25,7 @@ async fn a_purged_accounts_handle_stays_taken() { #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn restore_tokens_expire_and_end_with_the_deletion() { let pool = Database::test_pool().await; - let (user, _) = insert_user(&pool, "restore").await; + let user = insert_user(&pool, "restore").await; let mut deletions = AccountDeletionRepository::from_pool(&pool); let purge_after = Utc::now() + Duration::days(30); let scheduled = deletions @@ -174,8 +137,8 @@ async fn restore_tokens_expire_and_end_with_the_deletion() { )] async fn purge_leaves_nothing_that_references_or_identifies_the_account() { let pool = Database::test_pool().await; - let (user, handle) = insert_user(&pool, "purged").await; - let (bystander, _) = insert_user(&pool, "bystander").await; + let user = insert_user(&pool, "purged").await; + let bystander = insert_user(&pool, "bystander").await; let client = format!("purge-{user}"); let (session, code, family) = (SessionId::new(), TokenId::new(), TokenId::new()); // Test-generated IDs only, so formatting them into the SQL is safe. @@ -282,7 +245,9 @@ async fn purge_leaves_nothing_that_references_or_identifies_the_account() { .expect("schedule"); tx.commit().await.expect("commit"); - assert!(purge(&pool, user).await); + let mut tx = DatabaseTransaction::new(pool.begin().await.expect("transaction")); + assert!(tx.deletions().purge(user).await.expect("purge")); + tx.commit().await.expect("commit"); // Every column with a foreign key to users(id), and how many rows hold the account. // Only this schema's: audit tests migrate schemas of their own beside it. @@ -386,13 +351,6 @@ async fn purge_leaves_nothing_that_references_or_identifies_the_account() { .await .expect("deliveries"); assert_eq!(channels, ["backchannel_logout"]); - - let holder = crate::HandleRepository::from_pool(&pool) - .holder(&handle) - .await - .expect("lookup") - .expect("the handle stays"); - assert_eq!(holder.user_id, None, "without an owner"); } /// A request that stores personal data about the account while it is being @@ -403,7 +361,7 @@ async fn purge_leaves_nothing_that_references_or_identifies_the_account() { #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn personal_data_stored_during_a_purge_is_erased() { let pool = Database::test_pool().await; - let (user, _) = insert_user(&pool, "racing").await; + let user = insert_user(&pool, "racing").await; let failed = EventContext { actor: Actor::Anonymous, origin: RequestOrigin { @@ -426,10 +384,7 @@ async fn personal_data_stored_during_a_purge_is_erased() { .expect("failed sign-in"); let mut connection = pool.acquire().await.expect("connection"); - let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") - .fetch_one(&mut *connection) - .await - .expect("pid"); + let backend = Database::backend(&mut connection).await; let purging = tokio::spawn(async move { let mut tx = DatabaseTransaction::new(connection.begin().await.expect("transaction")); let purged = tx.deletions().purge(user).await.expect("purge"); @@ -437,22 +392,7 @@ async fn personal_data_stored_during_a_purge_is_erased() { purged }); // Only deleting the account waits for the request's lock. - let blocked = async { - while !sqlx::query_scalar::<_, bool>( - "SELECT coalesce(bool_or(wait_event_type = 'Lock'), FALSE) - FROM pg_stat_activity WHERE pid = $1", - ) - .bind(pid) - .fetch_one(&pool) - .await - .expect("activity") - { - tokio::time::sleep(StdDuration::from_millis(10)).await; - } - }; - tokio::time::timeout(StdDuration::from_secs(10), blocked) - .await - .expect("the purge waits for the request"); + Database::wait_for_lock(&pool, backend).await; request.commit().await.expect("commit"); assert!(purging.await.expect("purge task")); @@ -471,8 +411,8 @@ async fn personal_data_stored_during_a_purge_is_erased() { #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn failed_purges_back_off_behind_other_accounts() { let pool = Database::test_pool().await; - let (failing, _) = insert_user(&pool, "failing").await; - let (other, _) = insert_user(&pool, "other").await; + let failing = insert_user(&pool, "failing").await; + let other = insert_user(&pool, "other").await; let mut deletions = AccountDeletionRepository::from_pool(&pool); // Other tests' accounts may be due too, so only these two are compared. let order = async |deletions: &mut AccountDeletionRepository<'_>| { diff --git a/crates/database/src/repositories/deliveries/tests.rs b/crates/database/src/repositories/deliveries/tests.rs index 1c8092d2e..2269641b3 100644 --- a/crates/database/src/repositories/deliveries/tests.rs +++ b/crates/database/src/repositories/deliveries/tests.rs @@ -7,7 +7,7 @@ use crate::{ UserRepository, }; use piquel_common::{ - Personal, SessionId, + SessionId, events::{Actor, EventContext, RequestOrigin, RevocationReason}, }; use sqlx::PgPool; @@ -144,10 +144,10 @@ fn failed() -> DeliveryOutcome { } /// An event's deliveries commit with it, copying the facts they need, and a -/// rolled-back event has none. Deleting the account afterwards leaves them as they were. +/// rolled-back event has none. #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] -async fn deliveries_commit_with_their_event_and_outlive_the_account() { +async fn deliveries_commit_with_their_event() { let pool = Database::test_pool().await; let account = InsertUser::named("delivery"); let (user, username) = (account.id, account.handle.to_string()); @@ -195,23 +195,14 @@ async fn deliveries_commit_with_their_event_and_outlive_the_account() { .expect("history") .try_into() .expect("one event"); - let created = stored().await; assert_eq!( - created, + stored().await, [( event.id.as_uuid(), Value::from(username.clone()), "pending".into() )] ); - assert_eq!(event.origin, Personal::Value(RequestOrigin::default())); - - sqlx::query("DELETE FROM users WHERE id = $1") - .bind(user.as_uuid()) - .execute(&pool) - .await - .expect("purge the account"); - assert_eq!(stored().await, created, "the purge changes nothing"); } /// However many workers claim at once, each delivery goes to exactly one. diff --git a/crates/database/src/repositories/events/tests.rs b/crates/database/src/repositories/events/tests.rs index 77500e160..83f0965c0 100644 --- a/crates/database/src/repositories/events/tests.rs +++ b/crates/database/src/repositories/events/tests.rs @@ -6,7 +6,7 @@ use piquel_common::{ clients::RelatedOrigin, events::{RecordedOrigin, RevocationReason}, }; -use sqlx::{Connection, PgConnection, PgPool}; +use sqlx::{PgConnection, PgPool}; use std::time::Duration; /// Inserts an active account to be the subject of recorded events. @@ -49,8 +49,7 @@ async fn record(pool: &PgPool, user: UserId, event: DomainEvent) { /// Events commit and roll back with their transaction. Personal values, the /// request origin and the reason stay out of the event row, read back while kept, -/// and read as erased once their row is deleted. Deleting the account leaves its -/// history. +/// and read as erased once their row is deleted. #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn personal_data_is_stored_apart_and_erases() { @@ -121,13 +120,6 @@ async fn personal_data_is_stored_apart_and_erases() { ); assert_eq!(erased.origin, Personal::Erased); assert_eq!(erased.reason, None); - - sqlx::query("DELETE FROM users WHERE id = $1") - .bind(user.as_uuid()) - .execute(&pool) - .await - .expect("events never block deleting their account"); - assert_eq!(history().await.len(), 1, "history outlives the account"); } /// Reads `user`'s events from `consumer`'s cursor until `count` arrived, @@ -365,27 +357,8 @@ async fn events_a_newer_release_wrote_read_as_unknown() { #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn migration_imports_the_audit_log() { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let mut connection = PgConnection::connect(&url).await.expect("connect"); + let mut connection = Database::scratch_schema(..5).await; let user = UserId::new(); - let schema = format!("import_{}", user.as_uuid().simple()); - sqlx::raw_sql(&format!( - "CREATE SCHEMA {schema}; SET search_path TO {schema}" - )) - .execute(&mut connection) - .await - .expect("schema"); - for migration in [ - include_str!("../../../migrations/0001_initial.sql"), - include_str!("../../../migrations/0002_refresh_family_authorization_code.sql"), - include_str!("../../../migrations/0003_session_passkey_confirmation.sql"), - include_str!("../../../migrations/0004_authentication_claims.sql"), - ] { - sqlx::raw_sql(migration) - .execute(&mut connection) - .await - .expect("earlier migration"); - } sqlx::query("INSERT INTO users(id,username,display_name) VALUES($1,'imported','Import test')") .bind(user.as_uuid()) .execute(&mut connection) @@ -413,27 +386,11 @@ async fn migration_imports_the_audit_log() { 2, ) .await; - sqlx::raw_sql(include_str!("../../../migrations/0005_domain_events.sql")) - .execute(&mut connection) - .await - .expect("migration"); + 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. - for migration in [ - include_str!("../../../migrations/0006_deliveries.sql"), - include_str!("../../../migrations/0007_administrators.sql"), - include_str!("../../../migrations/0008_oidc_client_registry.sql"), - include_str!("../../../migrations/0009_pushed_authorization_requests.sql"), - include_str!("../../../migrations/0010_session_devices.sql"), - include_str!("../../../migrations/0015_event_reasons.sql"), - include_str!("../../../migrations/0018_contract_audit_log_and_legacy_secrets.sql"), - ] { - sqlx::raw_sql(migration) - .execute(&mut connection) - .await - .expect("later migration"); - } + Database::apply_migrations(&mut connection, 6..).await; let history = EventRepository::from_connection(&mut connection) .history_for_user(user, 10) @@ -461,8 +418,4 @@ async fn migration_imports_the_audit_log() { ("passkey.login", "success", serde_json::json!({})), ] ); - sqlx::raw_sql(&format!("DROP SCHEMA {schema} CASCADE")) - .execute(&mut connection) - .await - .expect("drop schema"); } diff --git a/crates/database/src/repositories/handles/tests.rs b/crates/database/src/repositories/handles/tests.rs index 13a509ebe..f009743af 100644 --- a/crates/database/src/repositories/handles/tests.rs +++ b/crates/database/src/repositories/handles/tests.rs @@ -3,7 +3,6 @@ use crate::{ Database, DatabaseError, InsertUser, connection::MIGRATOR, repositories::UserRepository, }; use piquel_common::{Handle, UserId}; -use sqlx::{Connection, PgConnection}; /// The schema's `handle_skeleton` is the Rust type's skeleton, which the generated /// `skeleton` column, and so look-alike uniqueness, relies on. @@ -71,13 +70,15 @@ async fn concurrent_renames_to_one_handle_let_one_win() { assert_eq!(won[0], winner.id == accounts[0].id); } -/// An account's current handle is never deleted, but once the account is purged, -/// its last handle can be, so anyone may claim it. +/// An account's current handle is never deleted. Once the account is purged its +/// handles stay without an owner, so no account claims them, until an operator +/// releases them. #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] -async fn a_purged_accounts_handle_can_be_released() { - let pool = Database::test_pool().await; - let database = Database { pool: pool.clone() }; +async fn a_purged_accounts_handle_stays_taken_until_released() { + let database = Database { + pool: Database::test_pool().await, + }; let account = InsertUser::named("purged"); database.users().insert(&account).await.expect("user"); let release = async || { @@ -87,16 +88,34 @@ async fn a_purged_accounts_handle_can_be_released() { .await .expect("delete") }; + let reuse = async || { + database + .users() + .insert(&InsertUser { + handle: account.handle.clone(), + ..InsertUser::named("again") + }) + .await + }; assert!(release().await.is_none(), "a current handle stays"); - sqlx::query("DELETE FROM users WHERE id = $1") - .bind(account.id.as_uuid()) - .execute(&pool) - .await - .expect("purge"); + let purge = async || { + let mut tx = database.begin().await.expect("transaction"); + let purged = tx.deletions().purge(account.id).await.expect("purge"); + tx.commit().await.expect("commit"); + purged + }; + assert!(purge().await); + assert!(!purge().await, "the account is gone"); + let refused = reuse().await; + assert!( + matches!(refused, Err(DatabaseError::Conflict(_))), + "{refused:?}" + ); assert!( release().await.is_some(), "a purged account's handle is freed" ); + reuse().await.expect("a released handle is free"); } /// Two accounts asking for each other's handles are both refused, without a @@ -168,31 +187,13 @@ async fn locked_lookups_read_a_rename_they_waited_for() { #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn the_migration_refuses_usernames_that_are_not_handles() { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let mut connection = PgConnection::connect(&url).await.expect("connect"); - let schema = format!("handles_{}", UserId::new().as_uuid().simple()); - sqlx::raw_sql(&format!( - "CREATE SCHEMA {schema}; SET search_path TO {schema}" - )) - .execute(&mut connection) - .await - .expect("schema"); // Found by name, so renumbering it after another branch's migration needs no // change here. - let version = MIGRATOR + let handles = MIGRATOR .iter() .find(|migration| migration.description == "handles") - .expect("the handles migration") - .version; - let (earlier, handles): (Vec<_>, Vec<_>) = MIGRATOR - .iter() - .partition(|migration| migration.version < version); - for migration in earlier { - sqlx::raw_sql(&migration.sql) - .execute(&mut connection) - .await - .expect("earlier migration"); - } + .expect("the handles migration"); + let mut connection = Database::scratch_schema(..handles.version).await; for username in ["a_b", "piquel", "pique1", "fine"] { sqlx::query("INSERT INTO users(id,username,display_name) VALUES($1,$2,'Migration test')") .bind(UserId::new().as_uuid()) @@ -201,7 +202,7 @@ async fn the_migration_refuses_usernames_that_are_not_handles() { .await .expect("user"); } - let migration = &handles[0].sql; + let migration = &handles.sql; let refused = sqlx::raw_sql(migration) .execute(&mut connection) .await @@ -233,8 +234,4 @@ async fn the_migration_refuses_usernames_that_are_not_handles() { copied, ["a-b", "fine", "piquel", "renamed"].map(|handle| (handle.to_owned(), true)) ); - sqlx::raw_sql(&format!("DROP SCHEMA {schema} CASCADE")) - .execute(&mut connection) - .await - .expect("drop schema"); } diff --git a/crates/database/src/repositories/oidc/tests.rs b/crates/database/src/repositories/oidc/tests.rs index 7a7cbafe7..a0a7727ee 100644 --- a/crates/database/src/repositories/oidc/tests.rs +++ b/crates/database/src/repositories/oidc/tests.rs @@ -2,10 +2,7 @@ //! public clients may call from, when pushed authorization requests can be claimed, //! and which clients of live sessions the back-channel logout migration finds. use crate::repositories::{EventRepository, OidcRepository, UserRepository}; -use crate::{ - Database, DatabaseTransaction, InsertAuthorizationRequest, InsertUser, RecordedEvent, - connection::MIGRATOR, -}; +use crate::{Database, DatabaseTransaction, InsertAuthorizationRequest, InsertUser, RecordedEvent}; use chrono::{DateTime, Duration, Utc}; use piquel_common::{ AuthenticationMethod, ClientId, Personal, SessionId, TokenId, UserId, @@ -16,8 +13,8 @@ use piquel_common::{ events::{Actor, DomainEvent, EventContext, InlineSignIn, RecordedOrigin, RequestOrigin}, protocol::oauth::{Interaction, Scope}, }; -use sqlx::{Connection, PgConnection, PgPool}; -use std::{net::IpAddr, ops::RangeBounds}; +use sqlx::PgPool; +use std::net::IpAddr; /// A registration of `kind` named after a fresh ID, redirecting to `origin`. fn registration(kind: ClientKind, origin: &str) -> ClientRegistration { @@ -270,35 +267,13 @@ async fn purging_an_owner_needs_its_live_clients_deleted() { } } -/// A connection to a new scratch schema with the migrations in `versions` applied, -/// and the schema's name, for tests of a migration: the test database is already -/// migrated. -async fn scratch_schema(versions: impl RangeBounds) -> (PgConnection, String) { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let mut connection = PgConnection::connect(&url).await.expect("connect"); - let schema = format!("migration_{}", UserId::new().as_uuid().simple()); - sqlx::raw_sql(&format!( - "CREATE SCHEMA {schema}; SET search_path TO {schema}" - )) - .execute(&mut connection) - .await - .expect("schema"); - for migration in MIGRATOR.iter().filter(|m| versions.contains(&m.version)) { - sqlx::raw_sql(&migration.sql) - .execute(&mut connection) - .await - .expect("earlier migration"); - } - (connection, schema) -} - /// 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, schema) = scratch_schema(..13).await; + 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!( @@ -337,12 +312,7 @@ async fn migration_finds_the_clients_of_live_sessions() { .await .expect("sessions and their exchanges"); - sqlx::raw_sql(include_str!( - "../../../migrations/0013_backchannel_logout.sql" - )) - .execute(&mut connection) - .await - .expect("migration"); + 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) @@ -355,10 +325,6 @@ async fn migration_finds_the_clients_of_live_sessions() { (live.as_uuid(), "refreshed".to_owned()), ] ); - sqlx::raw_sql(&format!("DROP SCHEMA {schema} CASCADE")) - .execute(&mut connection) - .await - .expect("drop schema"); } /// Purging an app's owner erases the app's related origins from events that name diff --git a/crates/database/src/repositories/tokens/tests.rs b/crates/database/src/repositories/tokens/tests.rs index a47f3109e..2b40b0c53 100644 --- a/crates/database/src/repositories/tokens/tests.rs +++ b/crates/database/src/repositories/tokens/tests.rs @@ -50,14 +50,6 @@ fn authentication() -> SessionAuthentication { } } -/// Returns the server process of a connection, to observe its lock waits. -async fn backend(connection: &mut PgConnection) -> i32 { - sqlx::query_scalar("SELECT pg_backend_pid()") - .fetch_one(connection) - .await - .expect("backend pid") -} - /// Counts the rows the connection's server process wrote. The count includes /// earlier transactions' rows not flushed to the statistics yet, so only its /// change within a transaction shows what that transaction wrote. @@ -71,32 +63,6 @@ async fn written(connection: &mut PgConnection) -> i64 { .expect("rows written") } -/// Waits until the server process `backend` is blocked on a lock. -async fn wait_for_lock(pool: &PgPool, backend: i32) { - tokio::time::timeout(Wait::from_secs(2), async { - loop { - let waiting: bool = sqlx::query_scalar( - "SELECT EXISTS ( - SELECT 1 - FROM pg_stat_activity - WHERE pid = $1 - AND wait_event_type = 'Lock' - )", - ) - .bind(backend) - .fetch_one(pool) - .await - .expect("wait state"); - if waiting { - break; - } - tokio::time::sleep(Wait::from_millis(10)).await; - } - }) - .await - .expect("the transaction waits for a lock"); -} - /// A committed account, browser session and unredeemed authorization code. struct Grant { /// Account the code was issued to. @@ -239,7 +205,7 @@ async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { .await .expect("lock session"); let mut rotation = pool.begin().await.expect("rotation transaction"); - let rotation_backend = backend(&mut rotation).await; + let rotation_backend = Database::backend(&mut rotation).await; let rotation_task = tokio::spawn(async move { let result = TokenRepository::from_connection(&mut rotation) .redeem_refresh( @@ -252,7 +218,7 @@ async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { rotation.rollback().await.expect("rollback rotation"); result }); - wait_for_lock(&pool, rotation_backend).await; + Database::wait_for_lock(&pool, rotation_backend).await; tokio::time::timeout( Wait::from_secs(2), SessionRepository::from_connection(&mut logout) @@ -443,7 +409,7 @@ async fn code_replay_waits_for_first_redemption_and_revokes_its_family() { .expect("remove redirect URI"); } let mut replay = DatabaseTransaction::new(pool.begin().await.expect("replay")); - let replay_backend = backend(&mut replay.inner).await; + let replay_backend = Database::backend(&mut replay.inner).await; let (code, code_digest, replay_client) = (grant.code, grant.code_digest.clone(), client.clone()); let replay_task = tokio::spawn(async move { @@ -454,7 +420,7 @@ async fn code_replay_waits_for_first_redemption_and_revokes_its_family() { replay.commit().await.expect("commit replay"); result }); - wait_for_lock(&pool, replay_backend).await; + Database::wait_for_lock(&pool, replay_backend).await; first.commit().await.expect("commit first redemption"); let result = replay_task.await.expect("replay task"); assert!( @@ -597,7 +563,7 @@ async fn logout_revokes_a_family_committed_while_it_waited() { ) .await; let mut logout = pool.begin().await.expect("logout transaction"); - let logout_backend = backend(&mut logout).await; + let logout_backend = Database::backend(&mut logout).await; let (user, session) = (grant.user, grant.session); let logout_task = tokio::spawn(async move { let revoked = SessionRepository::from_connection(&mut logout) @@ -607,7 +573,7 @@ async fn logout_revokes_a_family_committed_while_it_waited() { logout.commit().await.expect("commit logout"); revoked }); - wait_for_lock(&pool, logout_backend).await; + Database::wait_for_lock(&pool, logout_backend).await; exchange.commit().await.expect("commit exchange"); assert_eq!(logout_task.await.expect("logout task"), [session]); let revoked: bool = sqlx::query_scalar( diff --git a/crates/database/tests/security.rs b/crates/database/tests/security.rs index 0d90bd7b0..e86d79943 100644 --- a/crates/database/tests/security.rs +++ b/crates/database/tests/security.rs @@ -96,18 +96,12 @@ async fn invitation_redemption_and_confirmation_lifecycle() { confirmed_at(session).await.is_none(), "social sign-in has no confirmation" ); - let at = Utc::now() - Duration::seconds(30); for id in [session, other] { db.sessions() - .confirm_passkey(id, PasskeyId::new(), at) + .confirm_passkey(id, PasskeyId::new(), Utc::now()) .await .expect("confirm"); } - let stored = confirmed_at(session).await.expect("confirmation"); - assert!( - (stored - at).abs() < Duration::milliseconds(1), - "stored as given" - ); let context = EventContext { actor: Actor::User { user_id: user, From 1794deeb889d723b4154b0b3a9481c9ce86d8ac3 Mon Sep 17 00:00:00 2001 From: piquel Date: Fri, 6 Nov 2026 23:29:08 +0100 Subject: [PATCH 2/2] test(database): keep the transport and purged-handle lookups the merge dropped --- crates/database/src/connection/tests.rs | 16 ++++++++++++++++ .../database/src/repositories/handles/tests.rs | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/crates/database/src/connection/tests.rs b/crates/database/src/connection/tests.rs index 636f9c192..6b0fe9a0d 100644 --- a/crates/database/src/connection/tests.rs +++ b/crates/database/src/connection/tests.rs @@ -67,6 +67,22 @@ fn transport_is_verified_tls_a_local_socket_or_explicit_plaintext() { "{url}" ); } + // Accepting a URL is not enough: the transport it asked for is the one used. + let options = |url| { + DatabaseConfig::new(url, 1, Duration::from_secs(1)) + .expect("accepted") + .options + }; + assert!(matches!( + options("postgres://db.example/piquel?sslmode=disable").get_ssl_mode(), + sqlx::postgres::PgSslMode::Disable + )); + assert_eq!( + options("postgres://localhost/piquel?host=/run/postgresql") + .get_socket() + .map(std::path::PathBuf::as_path), + Some(std::path::Path::new("/run/postgresql")) + ); } /// Startup failures name the scheme or pool bound at fault, keep the parser's diff --git a/crates/database/src/repositories/handles/tests.rs b/crates/database/src/repositories/handles/tests.rs index f009743af..cfdfa4d00 100644 --- a/crates/database/src/repositories/handles/tests.rs +++ b/crates/database/src/repositories/handles/tests.rs @@ -106,6 +106,13 @@ async fn a_purged_accounts_handle_stays_taken_until_released() { }; assert!(purge().await); assert!(!purge().await, "the account is gone"); + let holder = database + .handles() + .holder(&account.handle) + .await + .expect("lookup") + .expect("the handle stays"); + assert_eq!(holder.user_id, None, "without an owner"); let refused = reuse().await; assert!( matches!(refused, Err(DatabaseError::Conflict(_))),