Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 0 additions & 28 deletions .config/nextest.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
10 changes: 5 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <branch> auth -- auth-service --operator <you> …`).
- **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`,
Expand Down
4 changes: 3 additions & 1 deletion apps/auth-service/src/admin/tests/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/admin/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/admin/tests/mutations.rs
Original file line number Diff line number Diff line change
@@ -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::*;
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/alerts/tests.rs
Original file line number Diff line number Diff line change
@@ -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::{
Expand Down
57 changes: 27 additions & 30 deletions apps/auth-service/src/audit/tests.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand All @@ -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,
Expand All @@ -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");
Expand All @@ -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());
Expand Down Expand Up @@ -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;
Expand All @@ -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.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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:?}");
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/jobs/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
38 changes: 19 additions & 19 deletions apps/auth-service/src/keys/tests.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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!(
Expand All @@ -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");
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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"));
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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]));
Expand Down
12 changes: 8 additions & 4 deletions apps/auth-service/src/security/tests/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Loading