diff --git a/.config/nextest.toml b/.config/nextest.toml index 36dcf4eb7..f54cf5513 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -2,31 +2,3 @@ # fails with a report instead of stalling validation indefinitely. [profile.default] slow-timeout = { period = "60s", terminate-after = 5 } - -# The tests share one database, and with it every advisory lock, even in a schema -# of their own. Tests that hold one of those locks for most of their run wait for -# it under a timeout, the statement timeout or their own, which on a busy machine -# runs out for the last of several waiting ones. So each lock's tests run one at -# a time, as the lock would make them anyway. -[test-groups] -# The signing key lock, which the key change tests hold for their whole transaction. -signing-keys = { max-threads = 1 } -# The audit chain lock, which the audit tests take to seal, and the audit -# verification lock, which its verifier tests also take and expect to be free. -# They contend over the chain lock either way, so they share one group. -audit = { max-threads = 1 } - -[[profile.default.overrides]] -filter = ''' -(package(auth-service) & ( - test(/^keys::tests::/) - | test(/^admin::tests::keys::/) - | test(/::signing_keys_are_rotated_and_revoked_from_the_dashboard$/) -)) -| (package(sourceorigin-repository) & test(/^repositories::signing_keys::tests::/)) -''' -test-group = "signing-keys" - -[[profile.default.overrides]] -filter = 'package(auth-service) & test(/^audit::tests::/)' -test-group = "audit" diff --git a/AGENTS.md b/AGENTS.md index 71cd58ffa..9e154948f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,11 +51,11 @@ can recognise a case it doesn't name. it with other credentials or tokens found on the machine: they grant what the owner chose not to give you. - **Databases:** `just db test` and `just coverage` make a scratch cluster and - delete it. Never point `TEST_DATABASE_URL` at a database that matters: the - tests migrate it, leave accounts and schemas in it, and create and drop roles, - which belong to the whole cluster. `auth-service` commands, `just auth` - included, act on whatever database their `AUTH_DATABASE_*` variables name: - run them on your preview + delete it. Never point `TEST_DATABASE_URL` at a database, or a server, that + matters: the tests migrate it and leave accounts in it, and they create + databases and create and drop roles, which belong to the whole cluster. + `auth-service` commands, `just auth` included, act on whatever database their + `AUTH_DATABASE_*` variables name: run them on your preview (`piquelctl preview exec sourceorigin auth -- auth-service --operator …`). - **Processes:** stop only a process you started, by the PID you captured, or the one that owns your own port. Never kill by name or pattern (`pkill -f`, diff --git a/apps/auth-service/src/admin/tests/keys.rs b/apps/auth-service/src/admin/tests/keys.rs index 241f42a74..f17ac57fd 100644 --- a/apps/auth-service/src/admin/tests/keys.rs +++ b/apps/auth-service/src/admin/tests/keys.rs @@ -9,7 +9,9 @@ use crate::security::CONFIRMATION_MAX_AGE; #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] async fn signing_key_changes_check_their_administrator() { - let harness = Harness::new().await; + // Generating the key holds the signing key lock, which the replicas of other + // tests on the shared database wait for as they start. + let harness = Harness::isolated().await; let service = harness.service(); let keys = crate::KeyStore::new( harness.database.clone(), diff --git a/apps/auth-service/src/admin/tests/mod.rs b/apps/auth-service/src/admin/tests/mod.rs index 9053135c7..56cfbc4a6 100644 --- a/apps/auth-service/src/admin/tests/mod.rs +++ b/apps/auth-service/src/admin/tests/mod.rs @@ -59,11 +59,11 @@ impl Harness { } } - /// Connects to a schema of its own, for a scenario that must know every + /// Connects to a database of its own, for a scenario that must know every /// administrator, which the shared database's other tests keep adding, or /// every alert, or that holds a lock other tests' changes would queue behind. pub(crate) async fn isolated() -> Self { - let database = Database::isolated(Replicas::database_config(5)) + let database = Database::isolated(Database::test_config(5)) .await .expect("isolated database"); Self { database } diff --git a/apps/auth-service/src/admin/tests/mutations.rs b/apps/auth-service/src/admin/tests/mutations.rs index 8e48a0f5f..459315729 100644 --- a/apps/auth-service/src/admin/tests/mutations.rs +++ b/apps/auth-service/src/admin/tests/mutations.rs @@ -1,7 +1,7 @@ //! How a change waits on locks and rechecks its caller after waiting. //! //! Each scenario holds a lock while a mutation waits for it, and every mutation -//! first takes the administrators lock, so each runs in a schema of its own: no +//! first takes the administrators lock, so each runs in a database of its own: no //! other test's change queues behind the lock it holds, or holds one it waits for. use super::*; diff --git a/apps/auth-service/src/alerts/tests.rs b/apps/auth-service/src/alerts/tests.rs index a272a005a..c5a8c68f2 100644 --- a/apps/auth-service/src/alerts/tests.rs +++ b/apps/auth-service/src/alerts/tests.rs @@ -1,5 +1,5 @@ //! How raising, clearing and acknowledging change the current alert of a kind, -//! and what they record. Each test uses a schema of its own, since an alert +//! and what they record. Each test uses a database of its own, since an alert //! concerns the whole database. use super::*; use crate::{ diff --git a/apps/auth-service/src/audit/tests.rs b/apps/auth-service/src/audit/tests.rs index fe5a466e4..bc9eb9c35 100644 --- a/apps/auth-service/src/audit/tests.rs +++ b/apps/auth-service/src/audit/tests.rs @@ -1,11 +1,12 @@ //! Sealing order, verification of tampered history, and pruning. Each test uses a -//! schema of its own, since the chain covers every event of its database. +//! database of its own, since the chain covers every event of its database, and +//! its locks are the database's. use super::*; use crate::{ AdminError, AdminService, AuthConfig, alerts::Alerts, config::AuditConfig, - tests::{Replicas, operator, reason}, + tests::{operator, reason}, }; use chrono::{SubsecRound, TimeDelta}; use sourceorigin_common::alerts::{Alert, AlertKind}; @@ -21,8 +22,14 @@ use sourceorigin_repository::{ }; use std::{sync::Arc, time::Duration}; -/// A migrated schema of its own on `TEST_DATABASE_URL`, with a sealer that signs -/// a checkpoint on every pass with new events. +/// Longest a test waits for its events to be sealed. Sealing waits for every +/// older transaction on the cluster to end, even in another database, such as a +/// signing key test's, which generates keys in one transaction and on a loaded +/// machine lasts a minute or more. +const SEALED_WITHIN: Duration = Duration::from_mins(2); + +/// A migrated database of its own on `TEST_DATABASE_URL`'s server, with a sealer +/// that signs a checkpoint on every pass with new events. struct Fixture { /// The isolated database. database: Database, @@ -38,11 +45,11 @@ struct Fixture { } impl Fixture { - /// Creates the schema and a fresh audit key. + /// Creates the database and a fresh audit key. async fn new() -> Self { // Two connections: a test holds at most a transaction and a read at once, // and every fixture's pool is one more on the server the suite shares. - let database = Database::isolated(Replicas::database_config(2)) + let database = Database::isolated(Database::test_config(2)) .await .expect("isolated database"); let key = NoteKey::generate("auth.example/audit").expect("audit key"); @@ -62,8 +69,8 @@ impl Fixture { "https://auth.example".parse().expect("origin") } - /// The whole service over the fixture's schema and audit key, whose security - /// layer sets every response's caching. The schema is the fixture's own, so no + /// The whole service over the fixture's database and audit key, whose security + /// layer sets every response's caching. The database is the fixture's own, so no /// other test shares its rate budgets. async fn router(&self) -> axum::Router { let mut config = AuthConfig::test(&Self::origin()); @@ -116,7 +123,7 @@ impl Fixture { /// Seals, holding the sealer's `lock`, until every committed event is sealed. async fn seal_with(&self, lock: &mut ExclusiveConnection) { - tokio::time::timeout(Duration::from_secs(30), async { + tokio::time::timeout(SEALED_WITHIN, async { while self.unsealed().await > 0 { if self.sealer.seal(lock).await.expect("seal") == 0 { tokio::time::sleep(Duration::from_millis(20)).await; @@ -127,24 +134,14 @@ impl Fixture { .expect("every committed event is sealed"); } - /// Takes the sealer's lock. Advisory locks are per database, not per schema, so - /// the other tests' fixtures take turns with it. + /// Takes the sealer's lock, which is the fixture's own: advisory locks are per + /// database. async fn lock(&self) -> ExclusiveConnection { - tokio::time::timeout(Duration::from_secs(30), async { - loop { - if let Some(lock) = self - .database - .try_exclusive(LockKey::AuditChain) - .await - .expect("lock") - { - return lock; - } - tokio::time::sleep(Duration::from_millis(20)).await; - } - }) - .await - .expect("the sealer lock") + self.database + .try_exclusive(LockKey::AuditChain) + .await + .expect("lock") + .expect("the sealer lock is free") } /// Counts the events not sealed yet. @@ -233,8 +230,8 @@ impl Fixture { async fn events_are_sealed_in_safe_order_and_checkpointed() { let mut fixture = Fixture::new().await; let database = fixture.database.clone(); - // The open transaction holds back sealing in every schema of the cluster, so - // it stays open only while this test holds the lock other tests seal under. + // The open transaction holds back sealing in every database of the cluster, + // so other tests' fixtures wait for it as they seal. let mut lock = fixture.lock().await; let mut open = database.begin().await.expect("transaction"); fixture.record_in(&mut open).await; @@ -1056,7 +1053,7 @@ async fn sealing_goes_on_when_a_checkpoint_fails() { // Events are sealed only once every older transaction has ended, and other // tests' transactions can delay that, so passes that seal nothing don't count. let mut sealing = 0; - tokio::time::timeout(Duration::from_secs(30), async { + tokio::time::timeout(SEALED_WITHIN, async { while let unsealed @ 1.. = fixture.unsealed().await { let pass = fixture.sealer.pass(&mut lock, None).await; assert!(matches!(pass, Err(AuditError::Broken(_))), "{pass:?}"); @@ -1148,7 +1145,7 @@ async fn checkpoints_keep_their_interval_while_batches_stay_full() { } tx.commit().await.expect("commit"); let mut lock = fixture.lock().await; - tokio::time::timeout(Duration::from_secs(30), async { + tokio::time::timeout(SEALED_WITHIN, async { while fixture.unsealed().await > 0 { fixture.sealer.pass(&mut lock, None).await.expect("pass"); tokio::time::sleep(Duration::from_millis(20)).await; diff --git a/apps/auth-service/src/jobs/tests.rs b/apps/auth-service/src/jobs/tests.rs index 7b4501cc1..1c0c5855c 100644 --- a/apps/auth-service/src/jobs/tests.rs +++ b/apps/auth-service/src/jobs/tests.rs @@ -182,7 +182,7 @@ async fn runners_never_overlap_and_a_dropped_holder_hands_over() { } /// A purge run raises the alert of accounts that keep failing to be purged, and -/// a run with none clears it. The schema is its own, since the count is every +/// a run with none clears it. The database is its own, since the count is every /// account's. #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] diff --git a/apps/auth-service/src/keys/tests.rs b/apps/auth-service/src/keys/tests.rs index 53086719e..13eaddfe8 100644 --- a/apps/auth-service/src/keys/tests.rs +++ b/apps/auth-service/src/keys/tests.rs @@ -1,12 +1,13 @@ -//! Rotation and revocation on the shared test database. Each test works in -//! a transaction that holds the signing key lock and rolls back, so tests never -//! see each other's keys, and the replicas of other tests keep theirs. +//! Rotation and revocation. Each test works in a database of its own, in a +//! transaction that holds the signing key lock while it generates keys. On a +//! busy machine that takes longer than the replicas of other tests wait for the +//! lock as they start, and advisory locks are per database. use super::*; use crate::{ routes, service::ServiceApplication, - tests::{Replicas, key_encryption_key, key_encryption_keys}, + tests::{key_encryption_key, key_encryption_keys}, }; use axum::{ body::Body, @@ -24,21 +25,20 @@ use tower::ServiceExt; /// The issuer the test tokens name. const ISSUER: &str = "https://auth.example"; -/// A store over the test database, sealing with the tests' key-encryption key. +/// A store over a database of its own, sealing with the tests' key-encryption key. async fn store() -> (KeyStore, Database) { - let database = Replicas::database().await; + let database = Database::isolated(Database::test_config(5)) + .await + .expect("isolated database"); ( KeyStore::new(database.clone(), key_encryption_keys()), database, ) } -/// Deletes every key in `tx`, after taking the lock. -async fn clear(tx: &mut DatabaseTransaction<'_>) { +/// Takes the signing key lock in `tx`, as every change does. +async fn lock(tx: &mut DatabaseTransaction<'_>) { tx.signing_keys().lock().await.expect("lock"); - for key in tx.signing_keys().list().await.expect("list") { - tx.signing_keys().delete(&key.id).await.expect("delete"); - } } /// The keys in `tx` and their states, oldest first. @@ -177,7 +177,7 @@ async fn rotation_takes_each_step_once_on_schedule() { use SigningKeyChange::{Activated, Deleted, Generated, Retired, Retiring}; let (store, database) = store().await; let mut tx = database.begin().await.expect("transaction"); - clear(&mut tx).await; + lock(&mut tx).await; let start = Utc::now(); let states = advance(&store, &mut tx, start).await; let [(first, SigningKeyState::Active)] = &states[..] else { @@ -285,7 +285,7 @@ async fn rotation_takes_each_step_once_on_schedule() { async fn concurrent_ticks_take_each_step_once() { let (store, database) = store().await; let mut first = database.begin().await.expect("transaction"); - clear(&mut first).await; + lock(&mut first).await; let mut second = database.begin().await.expect("transaction"); let now = Utc::now(); let (ran_first, ran_second) = tokio::join!( @@ -312,7 +312,7 @@ async fn concurrent_ticks_take_each_step_once() { async fn revoking_a_key_removes_it_and_replaces_the_signer() { let (store, database) = store().await; let mut tx = database.begin().await.expect("transaction"); - clear(&mut tx).await; + lock(&mut tx).await; let mut change = Change::new(&mut tx, &store, Utc::now(), None); change.advance().await.expect("first key"); change.rotate(true).await.expect("a second key signs"); @@ -367,7 +367,7 @@ async fn revoking_a_key_removes_it_and_replaces_the_signer() { async fn another_key_encryption_key_neither_opens_nor_changes_the_keys() { let (store, database) = store().await; let mut tx = database.begin().await.expect("transaction"); - clear(&mut tx).await; + lock(&mut tx).await; assert!(store.tick_in(&mut tx, Utc::now()).await.expect("first key")); let other = KeyStore::new( @@ -403,7 +403,7 @@ async fn another_key_encryption_key_neither_opens_nor_changes_the_keys() { async fn rewrapping_seals_every_key_under_the_current_key_encryption_key() { let (old, database) = store().await; let mut tx = database.begin().await.expect("transaction"); - clear(&mut tx).await; + lock(&mut tx).await; let start = Utc::now(); assert!(old.tick_in(&mut tx, start).await.expect("first key")); let mut change = Change::new(&mut tx, &old, start, None); @@ -477,7 +477,7 @@ async fn rewrapping_seals_every_key_under_the_current_key_encryption_key() { async fn a_next_key_that_cannot_sign_is_never_promoted() { let (store, database) = store().await; let mut tx = database.begin().await.expect("transaction"); - clear(&mut tx).await; + lock(&mut tx).await; let start = Utc::now(); let due = start + PRE_PUBLICATION; assert!(store.tick_in(&mut tx, start).await.expect("first key")); @@ -547,7 +547,7 @@ async fn a_next_key_that_cannot_sign_is_never_promoted() { async fn keys_sealed_either_way_open() { let (store, database) = store().await; let mut tx = database.begin().await.expect("transaction"); - clear(&mut tx).await; + lock(&mut tx).await; let start = Utc::now(); assert!(store.tick_in(&mut tx, start).await.expect("first key")); let stored = tx.signing_keys().list().await.expect("list"); @@ -596,7 +596,7 @@ async fn keys_sealed_either_way_open() { async fn revoking_a_broken_active_key_recovers_the_key_set() { let (store, database) = store().await; let mut tx = database.begin().await.expect("transaction"); - clear(&mut tx).await; + lock(&mut tx).await; let key = Rs256Key::generate("broken").expect("key"); let public = key.public_key().jwk().clone(); let sealing = (Binding::Record, Some(vec![0; 64])); diff --git a/apps/auth-service/src/security/tests/sessions.rs b/apps/auth-service/src/security/tests/sessions.rs index 3d0164541..fc321d823 100644 --- a/apps/auth-service/src/security/tests/sessions.rs +++ b/apps/auth-service/src/security/tests/sessions.rs @@ -9,10 +9,14 @@ use sourceorigin_repository::InsertSession; #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] async fn optional_session_preserves_database_failure_instead_of_reporting_signed_out() { - // A pool of one connection, which the test then holds. - let database = Database::connect(Replicas::database_config(1)) - .await - .expect("database"); + // A pool of one connection, which the test then holds. The lookup waits the + // service's five seconds for it, not a fixture's longer wait, so it fails long + // before PostgreSQL ends the held transaction as idle. + let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); + let config = + sourceorigin_repository::DatabaseConfig::new(&url, 1, std::time::Duration::from_secs(5)) + .expect("database configuration"); + let database = Database::connect(config).await.expect("database"); // Exhaust only this test's private pool; the database and all other tests // remain usable. A well-formed session cookie must trigger a real lookup. let transaction = database.begin().await.expect("hold sole connection"); diff --git a/apps/auth-service/src/tests.rs b/apps/auth-service/src/tests.rs index 468116f56..570043158 100644 --- a/apps/auth-service/src/tests.rs +++ b/apps/auth-service/src/tests.rs @@ -36,9 +36,9 @@ use sourceorigin_common::{ }; use sourceorigin_crypto::{ClientSecret, KeyEncryptionKey, NoteKey, Secret}; use sourceorigin_repository::{ - Database, DatabaseConfig, DatabaseError, DatabaseTransaction, InsertAuthorizationCode, - InsertPasskey, InsertRefreshFamily, InsertRefreshToken, InsertUser, InsertVerifiedEmail, - PendingFederation, SessionAuthentication, SessionScope, + Database, DatabaseError, DatabaseTransaction, InsertAuthorizationCode, InsertPasskey, + InsertRefreshFamily, InsertRefreshToken, InsertUser, InsertVerifiedEmail, PendingFederation, + SessionAuthentication, SessionScope, }; use std::{ collections::BTreeMap, @@ -149,7 +149,7 @@ impl Replicas { } } - /// Builds both replicas from `config` over `database`, such as a schema of + /// Builds both replicas from `config` over `database`, such as a database of /// a fixture's own. pub(crate) async fn over(config: &AuthConfig, database: &Database) -> Self { let peer = Self::peer(); @@ -204,16 +204,6 @@ impl Replicas { pub(crate) async fn database() -> Database { Database::test().await } - - /// A pool of up to `connections` to the test database, such as a fixture - /// passes to [`Database::isolated`] for a schema of its own. - pub(crate) fn database_config(connections: u32) -> DatabaseConfig { - let url = sourceorigin_common::config::Variable::new("TEST_DATABASE_URL") - .required() - .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); - DatabaseConfig::new(&url, connections, std::time::Duration::from_secs(5)) - .expect("database configuration") - } } /// The request budget the test configuration allows, as production does. diff --git a/apps/auth-service/src/web/admin/tests/mod.rs b/apps/auth-service/src/web/admin/tests/mod.rs index 46c043790..cadb1484b 100644 --- a/apps/auth-service/src/web/admin/tests/mod.rs +++ b/apps/auth-service/src/web/admin/tests/mod.rs @@ -73,13 +73,13 @@ impl Harness { } } - /// Builds auth and its dashboard over a schema of their own, for a scenario + /// Builds auth and its dashboard over a database of their own, for a scenario /// no other may disturb, such as one on the current alerts, which a /// verification of the shared test database clears. async fn isolated() -> Self { let config = Self::with_dashboard(AuthConfig::test(&AUTH_ORIGIN.parse().expect("auth origin"))); - let database = Database::isolated(Replicas::database_config(5)) + let database = Database::isolated(Database::test_config(5)) .await .expect("isolated database"); Self { diff --git a/apps/auth-service/src/web/admin/tests/operations.rs b/apps/auth-service/src/web/admin/tests/operations.rs index b7c0cc039..99c01e907 100644 --- a/apps/auth-service/src/web/admin/tests/operations.rs +++ b/apps/auth-service/src/web/admin/tests/operations.rs @@ -173,7 +173,9 @@ async fn deliveries_are_cancelled_and_retried_from_the_dashboard() { #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] async fn signing_keys_are_rotated_and_revoked_from_the_dashboard() { - let harness = Harness::new().await; + // Generating a key holds the signing key lock, which the replicas of other + // tests on the shared database wait for as they start. + let harness = Harness::isolated().await; let admin = harness.admin().await; let dashboard = harness.confirmed(&admin, "/keys/rotate", Utc::now()).await; let post = async |path: &str| { diff --git a/crates/database/src/connection/mod.rs b/crates/database/src/connection/mod.rs index 12df5aace..22300eab4 100644 --- a/crates/database/src/connection/mod.rs +++ b/crates/database/src/connection/mod.rs @@ -358,26 +358,37 @@ impl Database { #[cfg(any(test, feature = "test-util"))] impl Database { - /// Connects to `config`'s database in a schema of its own, created and migrated - /// for this call, so a test can change history that the whole database shares, - /// like the audit chain, without disturbing other tests. The schema is left - /// behind; test databases are disposable. + /// Connects to a database of its own on `config`'s server, created and migrated + /// for this call, so a test can change history the whole database shares, like + /// the audit chain, or hold one of its advisory locks, like the signing key + /// lock, without disturbing other tests. The database is left behind; test + /// servers are disposable. /// /// # Errors /// - /// Returns [`DatabaseError`] if connecting, creating the schema or migrating fails. + /// Returns [`DatabaseError`] if connecting, creating the database or migrating + /// fails. pub async fn isolated(config: DatabaseConfig) -> Result { - let schema = format!("test_{}", uuid::Uuid::now_v7().simple()); - let setup = Self::connect(config.clone()) - .await - .map_err(|error| DatabaseError::Operation(Box::new(error)))?; - // A schema name cannot be a bind parameter; this one is generated above. - sqlx::raw_sql(&format!("CREATE SCHEMA {schema}")) + let name = format!("test_{}", uuid::Uuid::now_v7().simple()); + // Copying the template database may outlast the statement limit on a loaded + // disk, so this one setup connection has none. + let setup = Self::connect(DatabaseConfig { + options: config + .options + .clone() + .options([Limit::STATEMENT.at(Duration::ZERO).option()]), + max_connections: 1, + ..config.clone() + }) + .await + .map_err(|error| DatabaseError::Operation(Box::new(error)))?; + // A database name cannot be a bind parameter; this one is generated above. + sqlx::raw_sql(&format!("CREATE DATABASE {name}")) .execute(&setup.pool) .await?; setup.pool.close().await; let config = DatabaseConfig { - options: config.options.options([("search_path", schema.as_str())]), + options: config.options.database(&name), ..config }; let database = Self::connect(config) @@ -390,11 +401,16 @@ impl Database { #[cfg(test)] impl Database { - /// Connects to `TEST_DATABASE_URL` and applies the schema. In-crate database - /// tests get the raw pool so they can insert fixtures with plain SQL. + /// Connects to `TEST_DATABASE_URL`, waiting [`Self::TEST_ACQUIRE_TIMEOUT`] for + /// each connection, and applies the schema. In-crate database tests get the raw + /// pool so they can insert fixtures with plain SQL. pub(crate) async fn test_pool() -> PgPool { let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let pool = PgPool::connect(&url).await.expect("connect"); + let pool = PgPoolOptions::new() + .acquire_timeout(Self::TEST_ACQUIRE_TIMEOUT) + .connect(&url) + .await + .expect("connect"); Self { pool: pool.clone() } .run_migrations() .await diff --git a/crates/database/src/connection/tests.rs b/crates/database/src/connection/tests.rs index 4a6ef9c00..222b6357a 100644 --- a/crates/database/src/connection/tests.rs +++ b/crates/database/src/connection/tests.rs @@ -392,7 +392,7 @@ fn config_for(user: &str) -> DatabaseConfig { .expect("test URL"); url.set_username(user).expect("user"); url.set_password(None).expect("password"); - DatabaseConfig::new(url.as_str(), 1, Duration::from_secs(5)).expect("config") + DatabaseConfig::new(url.as_str(), 1, Database::TEST_ACQUIRE_TIMEOUT).expect("config") } /// Provisioning resets what an existing role holds beyond its grants: settings, @@ -533,9 +533,9 @@ async fn functions_running_as_their_owner_are_not_executable_by_others() { #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn statements_and_lock_waits_past_their_limits_fail() { Database::test_pool().await; - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let config = DatabaseConfig::new(&url, 2, Duration::from_secs(5)).expect("configuration"); - let database = Database::connect(config).await.expect("connect"); + let database = Database::connect(Database::test_config(2)) + .await + .expect("connect"); let settings: Vec = sqlx::query_scalar( "SELECT current_setting(name) FROM unnest(ARRAY[ 'statement_timeout', 'lock_timeout', 'idle_in_transaction_session_timeout', @@ -655,7 +655,7 @@ async fn assert_personal_data_only_erases(runtime: &Database) { /// A checkpoint `runtime` inserts must sign a sealed event's hash, and an event it /// inserts must be JSON auth can read back, or sealing would fail on it. /// `personal_data_is_recorded_only_with_its_event` covers attaching personal data -/// to an older event, which needs a committed event, so a schema of its own. +/// to an older event, which needs a committed event, so a database of its own. async fn assert_history_is_never_forged(runtime: &Database) { for payload in [ r#"{"n": 1e400}"#.to_owned(), diff --git a/crates/database/src/fixtures.rs b/crates/database/src/fixtures.rs index 233237e39..ae6558447 100644 --- a/crates/database/src/fixtures.rs +++ b/crates/database/src/fixtures.rs @@ -8,11 +8,38 @@ use sourceorigin_common::{ Handle, SessionId, UserId, events::{Browser, DomainEvent, Platform, UserAgentFamily}, }; -use std::net::IpAddr; +use std::{net::IpAddr, time::Duration}; impl Database { - /// Opens a pool of up to five connections to `TEST_DATABASE_URL`, with the - /// time limits every connection of the service has, and applies the schema. + /// Longest a test waits for a pooled connection, which also bounds connecting + /// for its migrations. The service waits five seconds, but a test only sets + /// itself up with it, and on a machine loaded many times over, connecting alone + /// can take longer. A test that truly hangs still fails, after nextest's slow + /// timeout at the latest. + pub const TEST_ACQUIRE_TIMEOUT: Duration = Duration::from_mins(1); + + /// A pool of up to `connections` to `TEST_DATABASE_URL`, with the time limits + /// every connection of the service has, waiting [`Self::TEST_ACQUIRE_TIMEOUT`] + /// for each, such as a fixture passes to [`Self::isolated`] for a database of + /// its own. + /// + /// # Panics + /// + /// Panics if `TEST_DATABASE_URL` is unset or invalid. + #[must_use] + #[expect( + clippy::expect_used, + reason = "test-only fixture; documented under `# Panics`" + )] + pub fn test_config(connections: u32) -> DatabaseConfig { + let url = std::env::var("TEST_DATABASE_URL") + .expect("TEST_DATABASE_URL must name a disposable PostgreSQL database"); + DatabaseConfig::new(&url, connections, Self::TEST_ACQUIRE_TIMEOUT) + .expect("database configuration") + } + + /// Opens a pool of up to five connections of [`Self::test_config`] and applies + /// the schema. /// /// # Panics /// @@ -23,10 +50,7 @@ impl Database { reason = "test-only fixture; documented under `# Panics`" )] pub async fn test() -> Self { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let config = DatabaseConfig::new(&url, 5, std::time::Duration::from_secs(5)) - .expect("database configuration"); - let database = Self::connect(config).await.expect("connect"); + let database = Self::connect(Self::test_config(5)).await.expect("connect"); database.run_migrations().await.expect("migrate"); database } diff --git a/crates/database/src/repositories/audit/tests.rs b/crates/database/src/repositories/audit/tests.rs index 2cc775724..be6e11c6e 100644 --- a/crates/database/src/repositories/audit/tests.rs +++ b/crates/database/src/repositories/audit/tests.rs @@ -1,7 +1,6 @@ //! The guard triggers on sealed history. -use crate::{Database, DatabaseConfig}; +use crate::Database; use sqlx::{Connection, PgConnection}; -use std::time::Duration; use uuid::Uuid; /// Runs `sql`, bound to `id`, in a savepoint, so a refusal leaves the surrounding @@ -53,17 +52,14 @@ async fn sealing_needs_committed_data() { /// sealed one is never updated; only a transaction that set `sourceorigin.audit_prune` /// deletes it or sets the anchor, which never moves back. A checkpoint is added /// only if it is of a sealed event's hash and dated at a finite time not in the -/// future, and is never changed. The chain starts in a schema of its own, and +/// future, and is never changed. The chain starts in a database of its own, and /// everything runs in one transaction that is rolled back. #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn sealed_history_is_guarded() { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let database = Database::isolated( - DatabaseConfig::new(&url, 1, Duration::from_secs(5)).expect("configuration"), - ) - .await - .expect("isolated database"); + let database = Database::isolated(Database::test_config(1)) + .await + .expect("isolated database"); let refused = Err("23000".to_owned()); let mut tx = database.pool.begin().await.expect("transaction"); let [id, later] = [(); 2].map(|()| Uuid::now_v7()); @@ -142,16 +138,13 @@ async fn sealed_history_is_guarded() { } /// Personal data is recorded only with its event, never attached to an event of -/// an earlier transaction. That event is committed, so in a schema of its own. +/// an earlier transaction. That event is committed, so in a database of its own. #[tokio::test] #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn personal_data_is_recorded_only_with_its_event() { - let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let database = Database::isolated( - DatabaseConfig::new(&url, 1, Duration::from_secs(5)).expect("configuration"), - ) - .await - .expect("isolated database"); + let database = Database::isolated(Database::test_config(1)) + .await + .expect("isolated database"); let mut connection = database.pool.acquire().await.expect("connection"); let id = Uuid::now_v7(); assert_eq!(attempt(&mut connection, INSERT, id).await, Ok(()), "event"); diff --git a/crates/database/src/repositories/deliveries/tests.rs b/crates/database/src/repositories/deliveries/tests.rs index b12fcfb93..61b07ac29 100644 --- a/crates/database/src/repositories/deliveries/tests.rs +++ b/crates/database/src/repositories/deliveries/tests.rs @@ -315,7 +315,10 @@ async fn operators_retry_and_cancel_deliveries() { let pool = Database::test_pool().await; clear::(&pool).await; let id = insert::(&pool).await; - let lease = Duration::from_millis(300); + // The test cancels, retries and looks again within the first attempt's lease, + // in a few queries that may each take a second on a loaded machine, then waits + // it out once. + let lease = Duration::from_secs(5); let next = async || claim::(&pool, lease).await; let repository = || DeliveryRepository::from_pool(&pool); diff --git a/docs/dev/architecture/database.md b/docs/dev/architecture/database.md index 7c46038b7..c3c388a60 100644 --- a/docs/dev/architecture/database.md +++ b/docs/dev/architecture/database.md @@ -61,7 +61,7 @@ Only `Database::provision` runs unchecked SQL outside the tests: DDL takes no bind parameters, so a checked query renders its script (`src/connection/runtime_role.sql`) with `format`, which quotes the values, and `raw_sql` runs it. The test helpers behind the `test-util` feature run DDL the -same way, to create a schema (`Database::isolated`) or to turn the audit tables' +same way, to create a database (`Database::isolated`) or to turn the audit tables' guards off and on (`AuditRepository::tamper`), with names they generate or write as literals. Test fixtures may use unchecked `sqlx::query`. @@ -552,11 +552,8 @@ 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 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. +`test-util`) creates and migrates a database of its own, and `audit().tamper` +applies the changes an attacker could make, with the triggers disabled. ### Security history diff --git a/docs/dev/testing.md b/docs/dev/testing.md index 630ab7c8e..86bfb5a63 100644 --- a/docs/dev/testing.md +++ b/docs/dev/testing.md @@ -73,12 +73,21 @@ which fails if the committed query cache doesn't match the migrated schema exactly. To use a database of your own instead, set `TEST_DATABASE_URL` to it. The tests -create accounts in it and leave it migrated, so name only a database you can -throw away, never one that holds real accounts. A TCP URL must include -`sslmode=disable` or `sslmode=verify-full`. +create accounts in it and leave it migrated, and create more databases on its +server, so name only a server you can throw away, never one that holds real +accounts, and connect as a role that may create databases. A TCP URL must +include `sslmode=disable` or `sslmode=verify-full`. + +The databases a run creates are named `test_` and a random suffix, and the +tests never drop them. Drop them when they pile up: + +```console +psql "$TEST_DATABASE_URL" -Atc "SELECT format('DROP DATABASE %I;', datname) FROM pg_database WHERE datname LIKE 'test\_%'" | psql "$TEST_DATABASE_URL" +``` A new database test starts from the fixtures in `crates/database/src/fixtures.rs`. -`Database::test()` connects with the limits every connection of the service has. +`Database::test()` connects with the limits every connection of the service has, +and `Database::test_config` configures a pool of your own with them. `insert_named` creates an account, `InsertSession::lasting` describes a session, `known_history` lists an account's events, and `test_channels!` declares channels whose deliveries a test inserts itself. @@ -86,17 +95,27 @@ Another crate's tests get them through the `test-util` feature. A test in `crates/database` that inserts rows with plain SQL connects through `Database::test_pool()` instead, and auth-service's tests use `Replicas`, `Browser`, and the `html`, `json` and `reply` readers in -`apps/auth-service/src/tests.rs`. A test that needs a migrated schema no other -test shares, such as the audit chain's verification tests, gets one from -`Database::isolated`. - -The tests share one database, so they share its advisory locks too, even in a -schema of their own. A test that holds a database-wide lock belongs in that -lock's test group in `.config/nextest.toml`: `signing-keys` for the signing key -lock, `audit` for the audit chain and verification locks. Each group runs its -tests one at a time. Otherwise they queue for the lock under a timeout, the -15-second statement timeout or the test's own, and on a busy machine the last -one fails. +`apps/auth-service/src/tests.rs`. A test that needs a migrated database no other +test shares gets one from `Database::isolated`. + +The other tests share one database, its rows and its advisory locks, and run +under the service's own time limits: 15 seconds a statement, 5 seconds a lock +wait and 30 seconds idle in a transaction. Give a test a database of its own +when it: + +- needs history or state the whole database shares, such as the audit chain's + tests, or every administrator or alert; +- holds a lock the other tests take, for longer than they wait under those + limits. The signing key tests do: they hold the signing key lock while they + generate keys, and every replica a test starts waits for that lock. On a busy + machine, a key takes seconds to generate. + +A test waits longer than the service does only for what it needs to get going, +never for what it asserts. Its pools wait up to a minute for a connection +(`Database::TEST_ACQUIRE_TIMEOUT`), and the audit tests up to two minutes for +their events to be sealed, which every older transaction on the server holds +back. nextest ends a test that runs five minutes as hung, as +`.config/nextest.toml` sets. ### SDK test vectors