From 033dbf6bb0b31464ef3136343500fda45bb70067 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 13:35:42 +0100 Subject: [PATCH 1/2] fix(database): transaction-scoped locks refuse to run outside a transaction A repository bound to the pool or to an ExclusiveConnection took pg_advisory_xact_lock and FOR UPDATE locks that ended with their statement. The executor now tells a transaction from an exclusive connection, and one guarded helper takes every transaction-scoped advisory lock, refusing with DatabaseError::OutsideTransaction anywhere else. --- apps/auth-service/src/oidc/error.rs | 3 +- apps/auth-service/src/passkey/mod.rs | 3 +- apps/auth-service/src/security/mod.rs | 3 +- crates/database/src/error/mod.rs | 5 + crates/database/src/exclusive/mod.rs | 4 + crates/database/src/repositories/alerts.rs | 9 +- .../database/src/repositories/emails/tests.rs | 2 +- crates/database/src/repositories/mod.rs | 101 ++++++++++++++---- .../database/src/repositories/oidc/clients.rs | 13 +-- .../src/repositories/signing_keys/mod.rs | 38 ++----- crates/database/src/repositories/tests.rs | 41 ++++++- .../database/src/repositories/tokens/mod.rs | 7 +- .../database/src/repositories/tokens/tests.rs | 38 +++---- .../database/src/repositories/users/tests.rs | 8 +- 14 files changed, 169 insertions(+), 106 deletions(-) diff --git a/apps/auth-service/src/oidc/error.rs b/apps/auth-service/src/oidc/error.rs index 294e13e78..43e1322cb 100644 --- a/apps/auth-service/src/oidc/error.rs +++ b/apps/auth-service/src/oidc/error.rs @@ -221,7 +221,8 @@ impl OAuthError { | DatabaseError::Cancelled(_) | DatabaseError::LockUnavailable(_) | DatabaseError::InvalidStoredData { .. } - | DatabaseError::Operation(_) => Self::Database(error), + | DatabaseError::Operation(_) + | DatabaseError::OutsideTransaction => Self::Database(error), } } diff --git a/apps/auth-service/src/passkey/mod.rs b/apps/auth-service/src/passkey/mod.rs index 89c189f42..e26a85396 100644 --- a/apps/auth-service/src/passkey/mod.rs +++ b/apps/auth-service/src/passkey/mod.rs @@ -214,7 +214,8 @@ impl PasskeyApplication { | DatabaseError::Cancelled(_) | DatabaseError::LockUnavailable(_) | DatabaseError::InvalidStoredData { .. } - | DatabaseError::Operation(_) => error.into(), + | DatabaseError::Operation(_) + | DatabaseError::OutsideTransaction => error.into(), })?; tx.record( context, diff --git a/apps/auth-service/src/security/mod.rs b/apps/auth-service/src/security/mod.rs index e4ac18774..338bc7af4 100644 --- a/apps/auth-service/src/security/mod.rs +++ b/apps/auth-service/src/security/mod.rs @@ -178,7 +178,8 @@ impl From for ApiError { | DatabaseError::Cancelled(_) | DatabaseError::LockUnavailable(_) | DatabaseError::InvalidStoredData { .. } - | DatabaseError::Operation(_)) => Self::internal(error), + | DatabaseError::Operation(_) + | DatabaseError::OutsideTransaction) => Self::internal(error), } } } diff --git a/crates/database/src/error/mod.rs b/crates/database/src/error/mod.rs index 408628de1..c46be209d 100644 --- a/crates/database/src/error/mod.rs +++ b/crates/database/src/error/mod.rs @@ -51,6 +51,11 @@ pub enum DatabaseError { /// Any other driver, query, migration or event serialization failure. #[error("database operation failed")] Operation(#[source] Source), + /// An operation whose locks must last until its transaction ends, such as a + /// transaction-scoped advisory lock, ran outside a transaction, where they would + /// end with their statement. It is refused before any query runs. + #[error("the operation's locks need a transaction, and none is open")] + OutsideTransaction, } /// Why a stored value did not decode, without the value: a decoder's message can diff --git a/crates/database/src/exclusive/mod.rs b/crates/database/src/exclusive/mod.rs index 31da764ed..fc2e450c6 100644 --- a/crates/database/src/exclusive/mod.rs +++ b/crates/database/src/exclusive/mod.rs @@ -48,6 +48,10 @@ pub enum LockKey { /// expects its key free; no release takes it. #[cfg(any(test, feature = "test-util"))] TransactionTest = -4, + /// The test that transaction-scoped locks refuse an exclusive connection; + /// no release takes it. + #[cfg(any(test, feature = "test-util"))] + GuardTest = -5, } impl LockKey { diff --git a/crates/database/src/repositories/alerts.rs b/crates/database/src/repositories/alerts.rs index de02cf97c..e6dd4ab0d 100644 --- a/crates/database/src/repositories/alerts.rs +++ b/crates/database/src/repositories/alerts.rs @@ -104,13 +104,10 @@ impl AlertRepository<'_> { /// /// # Errors /// - /// Returns [`DatabaseError`] if a query fails or its payload does not decode. + /// Returns [`DatabaseError::OutsideTransaction`] outside a transaction, or + /// another [`DatabaseError`] if a query fails or its payload does not decode. pub async fn current(&mut self, kind: AlertKind) -> Result, DatabaseError> { - run!( - self, - execute, - sqlx::query!("SELECT pg_advisory_xact_lock($1)", LockKey::Alerts.id()) - )?; + self.executor.lock(LockKey::Alerts).await?; run!( self, fetch_optional, diff --git a/crates/database/src/repositories/emails/tests.rs b/crates/database/src/repositories/emails/tests.rs index abba66de3..7c3d424fb 100644 --- a/crates/database/src/repositories/emails/tests.rs +++ b/crates/database/src/repositories/emails/tests.rs @@ -13,7 +13,7 @@ use sourceorigin_common::{EmailId, UserId}; async fn verified_email_updates_preserve_and_release_ownership() { let pool = Database::test_pool().await; let mut tx = pool.begin().await.expect("transaction"); - let mut accounts = UserRepository::from_connection(&mut tx); + let mut accounts = UserRepository::from_transaction(&mut tx); let users = [ accounts.insert_named("email").await, accounts.insert_named("email").await, diff --git a/crates/database/src/repositories/mod.rs b/crates/database/src/repositories/mod.rs index 0ec2f19cc..8847d9a92 100644 --- a/crates/database/src/repositories/mod.rs +++ b/crates/database/src/repositories/mod.rs @@ -6,7 +6,7 @@ //! that checked queries decode into. Each submodule owns one repository together with the //! records it accepts and returns. -use crate::{Database, DatabaseTransaction, ExclusiveConnection}; +use crate::{Database, DatabaseError, DatabaseTransaction, ExclusiveConnection, LockKey}; use serde::de::DeserializeOwned; use serde_json::Value; use sourceorigin_common::events::DomainEvent; @@ -17,13 +17,17 @@ use sqlx::{ types::Json, }; -/// Where a repository runs its queries: directly on the pool, or on the -/// connection of an open transaction. +/// Where a repository runs its queries: directly on the pool, on the connection of +/// an open transaction, or on an [`ExclusiveConnection`]. Only a transaction keeps +/// locks past the statement that takes them, so [`Self::lock`] tells them apart. pub(crate) enum RepositoryExecutor<'a> { /// Each operation borrows a connection from the shared pool. Pool(&'a PgPool), /// Every operation participates in one caller-owned transaction. - Connection(&'a mut PgConnection), + Transaction(&'a mut PgConnection), + /// Every operation runs on a locked [`ExclusiveConnection`], each statement in + /// a transaction of its own. + Exclusive(&'a mut PgConnection), } /// Declares each repository handle and its accessor on [`Database`], @@ -48,8 +52,13 @@ macro_rules! repositories { } /// Binds this handle to a transaction connection for atomic operations. - pub(crate) fn from_connection(connection: &'a mut PgConnection) -> Self { - Self { executor: RepositoryExecutor::Connection(connection) } + pub(crate) fn from_transaction(connection: &'a mut PgConnection) -> Self { + Self { executor: RepositoryExecutor::Transaction(connection) } + } + + /// Binds this handle to a locked [`ExclusiveConnection`]'s connection. + pub(crate) fn from_exclusive(connection: &'a mut PgConnection) -> Self { + Self { executor: RepositoryExecutor::Exclusive(connection) } } } )* @@ -69,7 +78,7 @@ macro_rules! repositories { $( #[doc = concat!("Returns a [`", stringify!($name), "`] bound to this transaction.")] pub fn $accessor(&mut self) -> $name<'_> { - $name::from_connection(&mut self.inner) + $name::from_transaction(&mut self.inner) } )* } @@ -80,7 +89,7 @@ macro_rules! repositories { "Returns a [`", stringify!($name), "`] bound to the locked connection." )] pub fn $accessor(&mut self) -> $name<'_> { - $name::from_connection(&mut self.connection) + $name::from_exclusive(&mut self.connection) } )* } @@ -212,25 +221,17 @@ impl KindProbe { /// whether it changed exactly one row, and `required` returns `()`, or /// [`DatabaseError::NotFound`](crate::DatabaseError::NotFound) if it changed none. A macro /// rather than a method because `&PgPool` and `&mut PgConnection` are different -/// executor types. +/// executor types. `run!(@on executor, ...)` runs on a [`RepositoryExecutor`] itself. macro_rules! run { - ($self:expr, changed_one, $query:expr) => { - run!($self, execute, $query).map(|done| done.rows_affected() == 1) - }; - ($self:expr, required, $query:expr) => { - run!($self, execute, $query).and_then(|done| match done.rows_affected() { - 0 => Err(crate::DatabaseError::NotFound), - _ => Ok(()), - }) - }; - ($self:expr, $method:ident, $query:expr) => {{ + (@on $executor:expr, $method:ident, $query:expr) => {{ let query = $query; let span = RepositoryExecutor::span(sqlx::Execute::sql(&query)); let result = tracing::Instrument::instrument( async { - match &mut $self.executor { + match &mut $executor { RepositoryExecutor::Pool(pool) => query.$method(*pool).await, - RepositoryExecutor::Connection(connection) => { + RepositoryExecutor::Transaction(connection) + | RepositoryExecutor::Exclusive(connection) => { query.$method(&mut **connection).await } } @@ -241,6 +242,18 @@ macro_rules! run { .map_err(Into::::into); RepositoryExecutor::finish(&span, result) }}; + ($self:expr, changed_one, $query:expr) => { + run!($self, execute, $query).map(|done| done.rows_affected() == 1) + }; + ($self:expr, required, $query:expr) => { + run!($self, execute, $query).and_then(|done| match done.rows_affected() { + 0 => Err(crate::DatabaseError::NotFound), + _ => Ok(()), + }) + }; + ($self:expr, $method:ident, $query:expr) => { + run!(@on $self.executor, $method, $query) + }; } /// A checked `sqlx::query_as!` returning `$record`s, with their `$columns` @@ -286,6 +299,50 @@ macro_rules! in_safe_order { } impl RepositoryExecutor<'_> { + /// Waits for `key`'s transaction-scoped advisory lock, held until the + /// transaction ends. + /// + /// # Errors + /// + /// Returns [`DatabaseError::OutsideTransaction`] outside a transaction, where + /// the lock would end with its statement, or another [`DatabaseError`] if the + /// query fails. + async fn lock(&mut self, key: LockKey) -> Result<(), DatabaseError> { + self.require_transaction()?; + run!(@on *self, execute, sqlx::query!("SELECT pg_advisory_xact_lock($1)", key.id()))?; + Ok(()) + } + + /// Takes the lock of [`Self::lock`] if no other transaction holds it, and + /// returns whether it did. + /// + /// # Errors + /// + /// As [`Self::lock`]. + async fn try_lock(&mut self, key: LockKey) -> Result { + self.require_transaction()?; + run!( + @on *self, + fetch_one, + sqlx::query_scalar!(r#"SELECT pg_try_advisory_xact_lock($1) AS "locked!""#, key.id()) + ) + } + + /// Refuses work whose locks must last until its transaction ends, such as a + /// transaction-scoped advisory lock or `FOR UPDATE`, outside a transaction, + /// where they would end with the statement that takes them. + /// + /// # Errors + /// + /// Returns [`DatabaseError::OutsideTransaction`] on the pool or an + /// [`ExclusiveConnection`]. + fn require_transaction(&self) -> Result<(), DatabaseError> { + match self { + Self::Transaction(_) => Ok(()), + Self::Pool(_) | Self::Exclusive(_) => Err(DatabaseError::OutsideTransaction), + } + } + /// A client span for one query, recording its parameterized `sql` as /// `db.query.text`, never its bind values. A query outside any trace, such as an /// idle delivery worker's poll, gets none: each would be a trace of its own. @@ -459,7 +516,7 @@ pub(crate) mod security; pub(crate) mod sessions; /// Signing keys, their lifecycle and its lock. pub(crate) mod signing_keys; -/// Focused tests for the column types shared by every repository. +/// Focused tests for the column types and the lock guard shared by every repository. #[cfg(test)] mod tests; /// Refresh-token grants, their redemption and replay revocation. diff --git a/crates/database/src/repositories/oidc/clients.rs b/crates/database/src/repositories/oidc/clients.rs index 129fb4ec5..2216d65fe 100644 --- a/crates/database/src/repositories/oidc/clients.rs +++ b/crates/database/src/repositories/oidc/clients.rs @@ -777,17 +777,10 @@ impl OidcRepository<'_> { /// /// # Errors /// - /// Returns [`DatabaseError`] if the query fails. + /// Returns [`DatabaseError::OutsideTransaction`] outside a transaction, or + /// another [`DatabaseError`] if the query fails. pub async fn lock_related_origins(&mut self) -> Result<(), DatabaseError> { - run!( - self, - execute, - sqlx::query!( - "SELECT pg_advisory_xact_lock($1)", - LockKey::RelatedOrigins.id() - ) - )?; - Ok(()) + self.executor.lock(LockKey::RelatedOrigins).await } /// Every approved related origin, by origin. diff --git a/crates/database/src/repositories/signing_keys/mod.rs b/crates/database/src/repositories/signing_keys/mod.rs index 9c83859f5..b2dc5744f 100644 --- a/crates/database/src/repositories/signing_keys/mod.rs +++ b/crates/database/src/repositories/signing_keys/mod.rs @@ -74,23 +74,16 @@ impl SigningKeyRepository<'_> { /// /// # Errors /// - /// Returns [`DatabaseError`] if the query fails, or this repository is not - /// bound to a transaction, where the lock would end at once. + /// Returns [`DatabaseError::OutsideTransaction`] if this repository is not + /// bound to a transaction, where the lock would end at once, or another + /// [`DatabaseError`] if a query fails. pub async fn lock(&mut self) -> Result<(), DatabaseError> { - Self::require_transaction(&self.executor)?; run!( self, fetch_one, Limit::LOCK.at(Duration::ZERO).set(Scope::Transaction) )?; - run!( - self, - execute, - sqlx::query!( - "SELECT pg_advisory_xact_lock($1)", - LockKey::SigningKeys.id() - ) - )?; + self.executor.lock(LockKey::SigningKeys).await?; run!(self, fetch_one, Limit::LOCK.set(Scope::Transaction))?; Ok(()) } @@ -99,28 +92,9 @@ impl SigningKeyRepository<'_> { /// /// # Errors /// - /// Returns [`DatabaseError`] if the query fails, or this repository is not - /// bound to a transaction. + /// As [`Self::lock`]. pub async fn try_lock(&mut self) -> Result { - Self::require_transaction(&self.executor)?; - run!( - self, - fetch_one, - sqlx::query_scalar!( - r#"SELECT pg_try_advisory_xact_lock($1) AS "locked!""#, - LockKey::SigningKeys.id() - ) - ) - } - - /// Refuses to take a transaction-level lock outside a transaction. - fn require_transaction(executor: &RepositoryExecutor<'_>) -> Result<(), DatabaseError> { - match executor { - RepositoryExecutor::Pool(_) => Err(DatabaseError::Operation( - "the signing key lock requires a transaction".into(), - )), - RepositoryExecutor::Connection(_) => Ok(()), - } + self.executor.try_lock(LockKey::SigningKeys).await } /// Lists every key, oldest first. diff --git a/crates/database/src/repositories/tests.rs b/crates/database/src/repositories/tests.rs index d36b873ca..e1492aa09 100644 --- a/crates/database/src/repositories/tests.rs +++ b/crates/database/src/repositories/tests.rs @@ -1,7 +1,8 @@ -//! Stored values that their Rust types reject surface as invalid data. +//! Stored values that their Rust types reject surface as invalid data, and +//! transaction-scoped locks refuse to run outside a transaction. use crate::{ - Database, DatabaseError, - repositories::{SessionRepository, UserRepository}, + Database, DatabaseError, LockKey, + repositories::{RepositoryExecutor, SessionRepository, UserRepository}, }; use sourceorigin_common::{Handle, SessionId, UserId}; @@ -53,3 +54,37 @@ async fn undecodable_columns_are_invalid_stored_data() { Err(DatabaseError::InvalidStoredData { .. }) )); } + +/// A transaction-scoped advisory lock taken on the pool or an exclusive connection +/// would end with its statement, so both refuse it before running any query; a +/// transaction takes it. +#[tokio::test] +#[ignore = "requires a disposable TEST_DATABASE_URL"] +async fn transaction_scoped_locks_need_a_transaction() { + let database = Database::test().await; + let key = LockKey::GuardTest; + assert!(matches!( + RepositoryExecutor::Pool(&database.pool).lock(key).await, + Err(DatabaseError::OutsideTransaction) + )); + + let mut tx = database.begin().await.expect("transaction"); + let locked = RepositoryExecutor::Transaction(&mut tx.inner) + .try_lock(key) + .await; + assert!(matches!(locked, Ok(true)), "{locked:?}"); + tx.rollback().await.expect("rollback"); + + let mut exclusive = database + .try_exclusive(key) + .await + .expect("lock") + .expect("a free lock"); + assert!(matches!( + RepositoryExecutor::Exclusive(&mut exclusive.connection) + .try_lock(key) + .await, + Err(DatabaseError::OutsideTransaction) + )); + exclusive.release().await.expect("release"); +} diff --git a/crates/database/src/repositories/tokens/mod.rs b/crates/database/src/repositories/tokens/mod.rs index 6f1c6aaa3..0090da2e1 100644 --- a/crates/database/src/repositories/tokens/mod.rs +++ b/crates/database/src/repositories/tokens/mod.rs @@ -249,12 +249,7 @@ impl TokenRepository<'_> { // All state locks must outlive the redemption, token issuance and commit, // even when nothing is written: they make the refresh wait for a logout, // disablement or recovery undo, then fail on what it committed. - if matches!(self.executor, RepositoryExecutor::Pool(_)) { - return Err(DatabaseError::Operation( - "refresh redemption requires a transaction".into(), - ) - .into()); - } + self.executor.require_transaction()?; // Look up immutable ownership without locks, then acquire locks explicitly. // Account mutations take user -> session -> family; logout takes session -> // family. A joined FOR UPDATE does not guarantee that ordering. diff --git a/crates/database/src/repositories/tokens/tests.rs b/crates/database/src/repositories/tokens/tests.rs index c65bb2d71..b03635d52 100644 --- a/crates/database/src/repositories/tokens/tests.rs +++ b/crates/database/src/repositories/tokens/tests.rs @@ -84,12 +84,12 @@ impl Grant { /// Commits a fresh account, session and code issued to `client`. async fn new(pool: &PgPool, client: &ClientId) -> Self { let mut tx = pool.begin().await.expect("transaction"); - let user = UserRepository::from_connection(&mut tx) + let user = UserRepository::from_transaction(&mut tx) .insert_named("lock") .await; let grant = Self { user, - session: SessionRepository::from_connection(&mut tx) + session: SessionRepository::from_transaction(&mut tx) .insert(&InsertSession::lasting(user, Duration::hours(1))) .await .expect("session") @@ -171,7 +171,7 @@ async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { .family(&mut TokenRepository::from_pool(&pool), &client) .await; let mut first_tx = pool.begin().await.expect("first transaction"); - TokenRepository::from_connection(&mut first_tx) + TokenRepository::from_transaction(&mut first_tx) .redeem_refresh( first, std::slice::from_ref(&digest_first), @@ -183,7 +183,7 @@ async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { let mut second_tx = pool.begin().await.expect("second transaction"); tokio::time::timeout( Wait::from_secs(2), - TokenRepository::from_connection(&mut second_tx).redeem_refresh( + TokenRepository::from_transaction(&mut second_tx).redeem_refresh( second, std::slice::from_ref(&digest_second), client.as_str(), @@ -205,7 +205,7 @@ async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { let mut rotation = pool.begin().await.expect("rotation transaction"); let rotation_backend = Database::backend(&mut rotation).await; let rotation_task = tokio::spawn(async move { - let result = TokenRepository::from_connection(&mut rotation) + let result = TokenRepository::from_transaction(&mut rotation) .redeem_refresh( first, std::slice::from_ref(&digest_first), @@ -219,7 +219,7 @@ async fn independent_refreshes_share_client_and_logout_does_not_deadlock() { Database::wait_for_lock(&pool, rotation_backend).await; tokio::time::timeout( Wait::from_secs(2), - SessionRepository::from_connection(&mut logout) + SessionRepository::from_transaction(&mut logout) .revoke(grant.user, SessionScope::One(grant.session)), ) .await @@ -259,7 +259,7 @@ async fn replay_revokes_family_despite_invalid_scopes() { .expect("consumed token with invalid scopes"); } let mut tx = pool.begin().await.expect("transaction"); - let result = TokenRepository::from_connection(&mut tx) + let result = TokenRepository::from_transaction(&mut tx) .redeem_refresh( token, std::slice::from_ref(&digest), @@ -343,7 +343,7 @@ async fn a_kept_token_writes_nothing_and_holds_its_locks_until_commit() { for _ in 0..2 { let mut tx = pool.begin().await.expect("transaction"); let before = written(&mut tx).await; - let redeemed = TokenRepository::from_connection(&mut tx) + let redeemed = TokenRepository::from_transaction(&mut tx) .redeem_refresh( token, std::slice::from_ref(&digest), @@ -365,7 +365,7 @@ async fn a_kept_token_writes_nothing_and_holds_its_locks_until_commit() { // The count does see a write: rotating consumes the token. let mut tx = pool.begin().await.expect("transaction"); let before = written(&mut tx).await; - TokenRepository::from_connection(&mut tx) + TokenRepository::from_transaction(&mut tx) .redeem_refresh( token, std::slice::from_ref(&digest), @@ -392,7 +392,7 @@ async fn a_concurrent_redemption_answers_with_the_same_successor() { .family(&mut TokenRepository::from_pool(&pool), &client) .await; let mut first_tx = pool.begin().await.expect("first redemption"); - let redeemed = TokenRepository::from_connection(&mut first_tx) + let redeemed = TokenRepository::from_transaction(&mut first_tx) .redeem_refresh( first, std::slice::from_ref(&first_digest), @@ -406,7 +406,7 @@ async fn a_concurrent_redemption_answers_with_the_same_successor() { let (retry_digest, retry_client) = (first_digest.clone(), client.clone()); let retry_task = tokio::spawn(async move { let before = written(&mut retry).await; - let result = TokenRepository::from_connection(&mut retry) + let result = TokenRepository::from_transaction(&mut retry) .redeem_refresh( first, std::slice::from_ref(&retry_digest), @@ -421,7 +421,7 @@ async fn a_concurrent_redemption_answers_with_the_same_successor() { Database::wait_for_lock(&pool, retry_backend).await; let second = TokenId::new(); let second_digest = second.as_uuid().as_bytes().repeat(2); - TokenRepository::from_connection(&mut first_tx) + TokenRepository::from_transaction(&mut first_tx) .insert_token(&InsertRefreshToken { id: second, family_id: redeemed.family_id, @@ -445,7 +445,7 @@ async fn a_concurrent_redemption_answers_with_the_same_successor() { assert_eq!(wrote, 0, "the retry writes nothing"); let mut tx = pool.begin().await.expect("transaction"); - let mut tokens = TokenRepository::from_connection(&mut tx); + let mut tokens = TokenRepository::from_transaction(&mut tx); let rotated = tokens .redeem_refresh( second, @@ -470,7 +470,7 @@ async fn a_concurrent_redemption_answers_with_the_same_successor() { .expect("its successor"); tx.commit().await.expect("commit rotation"); let mut tx = pool.begin().await.expect("transaction"); - let result = TokenRepository::from_connection(&mut tx) + let result = TokenRepository::from_transaction(&mut tx) .redeem_refresh( first, std::slice::from_ref(&first_digest), @@ -533,7 +533,7 @@ async fn code_replay_waits_for_first_redemption_and_revokes_its_family() { "redeemable {redeemable}: {result:?}" ); let mut rotation = pool.begin().await.expect("rotation transaction"); - let result = TokenRepository::from_connection(&mut rotation) + let result = TokenRepository::from_transaction(&mut rotation) .redeem_refresh( token, std::slice::from_ref(&digest), @@ -578,7 +578,7 @@ async fn code_replay_by_another_client_revokes_nothing() { "{result:?}" ); let mut rotation = pool.begin().await.expect("rotation transaction"); - TokenRepository::from_connection(&mut rotation) + TokenRepository::from_transaction(&mut rotation) .redeem_refresh( token, std::slice::from_ref(&digest), @@ -656,14 +656,14 @@ async fn logout_revokes_a_family_committed_while_it_waited() { let client = client(&pool).await; let grant = Grant::new(&pool, &client).await; let mut exchange = pool.begin().await.expect("exchange transaction"); - SessionRepository::from_connection(&mut exchange) + SessionRepository::from_transaction(&mut exchange) .find_active_by_id_for_update(grant.session) .await .expect("lock") .expect("active session"); grant .family( - &mut TokenRepository::from_connection(&mut exchange), + &mut TokenRepository::from_transaction(&mut exchange), &client, ) .await; @@ -671,7 +671,7 @@ async fn logout_revokes_a_family_committed_while_it_waited() { 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) + let revoked = SessionRepository::from_transaction(&mut logout) .revoke(user, SessionScope::One(session)) .await .expect("logout"); diff --git a/crates/database/src/repositories/users/tests.rs b/crates/database/src/repositories/users/tests.rs index 570ac4388..e66098d5f 100644 --- a/crates/database/src/repositories/users/tests.rs +++ b/crates/database/src/repositories/users/tests.rs @@ -31,7 +31,7 @@ async fn account_locks_allow_foreign_key_checks() { let pool = Database::test_pool().await; let user = UserRepository::from_pool(&pool).insert_named("lock").await; let mut account = pool.begin().await.expect("account transaction"); - UserRepository::from_connection(&mut account) + UserRepository::from_transaction(&mut account) .find_active_by_id_for_update(user) .await .expect("account lock") @@ -59,7 +59,7 @@ async fn account_locks_do_not_wait_on_foreign_key_checks() { let mut account = pool.begin().await.expect("account transaction"); tokio::time::timeout( Duration::from_secs(2), - SessionRepository::from_connection(&mut account) + SessionRepository::from_transaction(&mut account) .insert(&InsertSession::lasting(user, chrono::Duration::days(1))), ) .await @@ -96,7 +96,7 @@ async fn locked_session_lookup_waits_for_concurrent_logout() { .id; let mut logout = pool.begin().await.expect("logout transaction"); assert_eq!( - SessionRepository::from_connection(&mut logout) + SessionRepository::from_transaction(&mut logout) .revoke(user, SessionScope::One(session)) .await .expect("revoke"), @@ -105,7 +105,7 @@ async fn locked_session_lookup_waits_for_concurrent_logout() { let mut exchange = pool.begin().await.expect("exchange transaction"); let backend = Database::backend(&mut exchange).await; let exchange = tokio::spawn(async move { - SessionRepository::from_connection(&mut exchange) + SessionRepository::from_transaction(&mut exchange) .find_active_by_id_for_update(session) .await .expect("lookup") From ff5d1559809e6d574a1585509282b69ff535572e Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 15:00:11 +0100 Subject: [PATCH 2/2] fix(database): the signing key lock refuses before its first statement Review follow-up: SigningKeyRepository::lock checks for a transaction before it sets the lock wait, from_transaction takes a sqlx Transaction so only one binds as a transaction, and the guard's test goes through the public accessors, so it also proves an ExclusiveConnection's handles refuse. --- crates/database/src/repositories/mod.rs | 8 ++++---- .../src/repositories/signing_keys/mod.rs | 1 + .../src/repositories/signing_keys/tests.rs | 5 ++++- crates/database/src/repositories/tests.rs | 16 +++++----------- 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/crates/database/src/repositories/mod.rs b/crates/database/src/repositories/mod.rs index 8847d9a92..342821de8 100644 --- a/crates/database/src/repositories/mod.rs +++ b/crates/database/src/repositories/mod.rs @@ -11,7 +11,7 @@ use serde::de::DeserializeOwned; use serde_json::Value; use sourceorigin_common::events::DomainEvent; use sqlx::{ - Decode, PgConnection, PgPool, Postgres, Type, + Decode, PgConnection, PgPool, Postgres, Transaction, Type, error::BoxDynError, postgres::{PgTypeInfo, PgValueRef}, types::Json, @@ -51,9 +51,9 @@ macro_rules! repositories { Self { executor: RepositoryExecutor::Pool(pool) } } - /// Binds this handle to a transaction connection for atomic operations. - pub(crate) fn from_transaction(connection: &'a mut PgConnection) -> Self { - Self { executor: RepositoryExecutor::Transaction(connection) } + /// Binds this handle to a transaction for atomic operations. + pub(crate) fn from_transaction(transaction: &'a mut Transaction<'_, Postgres>) -> Self { + Self { executor: RepositoryExecutor::Transaction(&mut **transaction) } } /// Binds this handle to a locked [`ExclusiveConnection`]'s connection. diff --git a/crates/database/src/repositories/signing_keys/mod.rs b/crates/database/src/repositories/signing_keys/mod.rs index b2dc5744f..dcfeeca34 100644 --- a/crates/database/src/repositories/signing_keys/mod.rs +++ b/crates/database/src/repositories/signing_keys/mod.rs @@ -78,6 +78,7 @@ impl SigningKeyRepository<'_> { /// bound to a transaction, where the lock would end at once, or another /// [`DatabaseError`] if a query fails. pub async fn lock(&mut self) -> Result<(), DatabaseError> { + self.executor.require_transaction()?; run!( self, fetch_one, diff --git a/crates/database/src/repositories/signing_keys/tests.rs b/crates/database/src/repositories/signing_keys/tests.rs index 5208c6e0b..ac590fe15 100644 --- a/crates/database/src/repositories/signing_keys/tests.rs +++ b/crates/database/src/repositories/signing_keys/tests.rs @@ -38,7 +38,10 @@ async fn the_lock_excludes_and_one_key_per_type_signs() { assert!(!other.signing_keys().try_lock().await.expect("try lock")); other.rollback().await.expect("rollback"); assert!( - database.signing_keys().lock().await.is_err(), + matches!( + database.signing_keys().lock().await, + Err(DatabaseError::OutsideTransaction) + ), "the pool has no transaction" ); diff --git a/crates/database/src/repositories/tests.rs b/crates/database/src/repositories/tests.rs index e1492aa09..e3c9d5556 100644 --- a/crates/database/src/repositories/tests.rs +++ b/crates/database/src/repositories/tests.rs @@ -2,7 +2,7 @@ //! transaction-scoped locks refuse to run outside a transaction. use crate::{ Database, DatabaseError, LockKey, - repositories::{RepositoryExecutor, SessionRepository, UserRepository}, + repositories::{SessionRepository, UserRepository}, }; use sourceorigin_common::{Handle, SessionId, UserId}; @@ -62,28 +62,22 @@ async fn undecodable_columns_are_invalid_stored_data() { #[ignore = "requires a disposable TEST_DATABASE_URL"] async fn transaction_scoped_locks_need_a_transaction() { let database = Database::test().await; - let key = LockKey::GuardTest; assert!(matches!( - RepositoryExecutor::Pool(&database.pool).lock(key).await, + database.oidc().lock_related_origins().await, Err(DatabaseError::OutsideTransaction) )); let mut tx = database.begin().await.expect("transaction"); - let locked = RepositoryExecutor::Transaction(&mut tx.inner) - .try_lock(key) - .await; - assert!(matches!(locked, Ok(true)), "{locked:?}"); + tx.oidc().lock_related_origins().await.expect("lock"); tx.rollback().await.expect("rollback"); let mut exclusive = database - .try_exclusive(key) + .try_exclusive(LockKey::GuardTest) .await .expect("lock") .expect("a free lock"); assert!(matches!( - RepositoryExecutor::Exclusive(&mut exclusive.connection) - .try_lock(key) - .await, + exclusive.oidc().lock_related_origins().await, Err(DatabaseError::OutsideTransaction) )); exclusive.release().await.expect("release");