Skip to content
Open
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
8 changes: 4 additions & 4 deletions apps/auth-service/src/account/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
security::{BrowserCookie, CONFIRMATION_MAX_AGE},
tests::{
AUTH_ORIGIN, Browser, Replicas, change, pending_sign_in, registration, sign_out,
until_blocked, unusable_passkey, verified_address,
unusable_passkey, verified_address,
},
};
use axum::{
Expand Down Expand Up @@ -505,7 +505,7 @@ async fn changes_check_the_administrator_again_after_waiting() {
let (result, ()) = tokio::join!(
fixture.rename(operator(revoked, Utc::now()), user, passkeys[0]),
async {
until_blocked(&mut revocation, 1).await;
revocation.until_blocked(1).await;
revocation.commit().await.expect("commit");
}
);
Expand All @@ -528,7 +528,7 @@ async fn changes_check_the_administrator_again_after_waiting() {
let (result, ()) = tokio::join!(
fixture.rename(fixture.operator(Duration::zero()), user, passkeys[0]),
async {
until_blocked(&mut grant, 1).await;
grant.until_blocked(1).await;
grant.commit().await.expect("commit");
}
);
Expand Down Expand Up @@ -650,7 +650,7 @@ async fn a_confirmation_while_waiting_does_not_count() {
.expect("account lock");
let path = passkey::ITEM.replace("{id}", &PasskeyId::new().to_string());
let ((status, body), ()) = tokio::join!(social.call(&routes, Method::DELETE, &path), async {
until_blocked(&mut confirmation, 1).await;
confirmation.until_blocked(1).await;
confirmation
.sessions()
.confirm_passkey(social.session_id, PasskeyId::new(), Utc::now())
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/admin/tests/administrators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ async fn the_last_active_administrator_stays() {
service.disable_user(&cli, a.user_id, reason("Away")),
service.revoke_administrator(&cli, b.user_id, reason("Asked by email")),
async {
until_blocked(&mut held, 2).await;
held.until_blocked(2).await;
held.commit().await.expect("commit");
}
);
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/admin/tests/invitations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ async fn invitation_revocation_waits_for_signup() {
let (result, ()) = tokio::join!(
service.revoke_invitation(&operator, invitation.id, reason("Asked by email")),
async {
until_blocked(&mut signup, 1).await;
signup.until_blocked(1).await;
// The signup revokes the browser's session without a deadlock.
admin.sign_out(&mut signup).await;
signup.commit().await.expect("signup");
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/admin/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use super::*;
use crate::security::RequestContext;
use crate::tests::{Browser, Replicas, until_blocked};
use crate::tests::{Browser, Replicas};
use chrono::{Duration, Utc};
use sourceorigin_common::{
AccountStatus, AuthenticationMethod, Handle, Personal, SessionId, TokenId, UserId,
Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/admin/tests/mutations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async fn mutations_recheck_the_confirmation_after_waiting() {
let (result, ()) = tokio::join!(
service.disable_user(&operator, user.user_id, reason),
async {
until_blocked(&mut logout, 1).await;
logout.until_blocked(1).await;
assert!(
operator.confirmation_left() > Duration::zero(),
"the mutation waits while its caller is still confirmed"
Expand Down Expand Up @@ -73,7 +73,7 @@ async fn waiting_mutations_hold_no_caller_locks() {
let (result, ()) = tokio::join!(
service.disable_user(&operator, user.user_id, reason),
async {
until_blocked(&mut switch, 1).await;
switch.until_blocked(1).await;
// The switch revokes the caller's session without a deadlock.
admin.sign_out(&mut switch).await;
switch.commit().await.expect("commit");
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
Expand Up @@ -157,7 +157,7 @@ async fn concurrent_raises_leave_one_alert() {
let database = database.clone();
async move { found(&database, Some(broken(5))).await }
});
crate::tests::until_blocked(&mut first, 1).await;
first.until_blocked(1).await;
first.commit().await.expect("commit");
second.await.expect("second raise");
let raised = recorded(&database).await;
Expand Down
8 changes: 4 additions & 4 deletions apps/auth-service/src/clients/tests/deletion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ async fn deletion_and_refresh_rotation_never_deadlock() {
.await
.expect("hold the first family");
let deletion = granting.delete();
until_blocked(&mut holder, 1).await;
holder.until_blocked(1).await;
holder
.tokens()
.redeem_refresh(
Expand Down Expand Up @@ -225,7 +225,7 @@ async fn deletion_skips_families_granted_while_it_waits() {
.await
.expect("hold the family");
let deletion = granting.delete();
until_blocked(&mut holder, 1).await;
holder.until_blocked(1).await;
let (token, digest) = granting.grant(fresh).await;
let mut rotation = granting.database.begin().await.expect("transaction");
rotation
Expand Down Expand Up @@ -274,7 +274,7 @@ async fn deletion_and_logout_never_deadlock() {
.await
.expect("hold the lowest family");
let deletion = granting.delete();
until_blocked(&mut holder, 1).await;
holder.until_blocked(1).await;
let logout = tokio::spawn({
let database = granting.database.clone();
let (user, session) = (granting.user.user_id, granting.user.session_id);
Expand All @@ -284,7 +284,7 @@ async fn deletion_and_logout_never_deadlock() {
tx.commit().await
}
});
until_blocked(&mut holder, 2).await;
holder.until_blocked(2).await;
holder.commit().await.expect("commit");
deletion.await.expect("task").expect("deletion");
logout.await.expect("task").expect("logout");
Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/clients/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use super::*;
use crate::{
account::{AccountError, AccountService, Owner},
security::Session,
tests::{Browser, Replicas, change, register, registration, replace, until_blocked},
tests::{Browser, Replicas, change, register, registration, replace},
};
use sourceorigin_common::{AuthenticationMethod, UserId, clients::RedirectUris};
use sourceorigin_repository::Database;
Expand Down Expand Up @@ -82,7 +82,7 @@ impl Account {
.expect("lock")
.expect("account");
let (result, ()) = tokio::join!(change(&client), async {
until_blocked(&mut holder, 1).await;
holder.until_blocked(1).await;
let session = holder.sessions().find_by_id(stale.session_id).await;
let session = session.expect("lookup").expect("session");
let passkey = AuthenticationMethod::Passkey.into();
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/oidc/tests/app_removal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ async fn an_exchange_waits_for_a_removal_and_finds_its_code_expired() {
let response = exchanging.exchange(&code, Flow::verifier(), None).await;
(response.status(), json(response).await)
});
until_blocked(&mut removal, 1).await;
removal.until_blocked(1).await;
removal
.oidc()
.expire_codes(flow.user_id, &flow.client.id)
Expand Down
6 changes: 3 additions & 3 deletions apps/auth-service/src/oidc/tests/authorization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ async fn a_failed_redemption_uses_the_code_up_for_one_waiting() {
tokio::spawn(async move { flow.exchange(&code, verifier, None).await.status() })
};
let failed = exchange("wrong");
until_blocked(&mut holder, 1).await;
holder.until_blocked(1).await;
let valid = exchange(Flow::verifier());
until_blocked(&mut holder, 2).await;
holder.until_blocked(2).await;
holder.commit().await.expect("commit");

assert_eq!(failed.await.expect("failed"), StatusCode::BAD_REQUEST);
Expand Down Expand Up @@ -257,7 +257,7 @@ async fn a_consent_whose_session_ended_while_waiting_is_not_saved() {
.await;
response.status()
});
until_blocked(&mut holder, 1).await;
holder.until_blocked(1).await;
let context = RequestContext::TEST.actor(Actor::Anonymous);
holder
.revoke_sessions(
Expand Down
3 changes: 1 addition & 2 deletions apps/auth-service/src/oidc/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use super::*;
use crate::config::TokenDigestKey;
use crate::security::RequestContext;
use crate::tests::{
AUTH_ORIGIN, Browser, Replicas, TlsListener, html, json, location, parameter, until_blocked,
verified_address,
AUTH_ORIGIN, Browser, Replicas, TlsListener, html, json, location, parameter, verified_address,
};
use crate::{AuthConfig, federation::FederationApplication, web::WebApplication};
use axum::{
Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/oidc/tests/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ async fn suspending_an_app_during_an_exchange_issues_nothing() {
let exchanging = flow.clone();
let exchange =
tokio::spawn(async move { exchanging.exchange(&code, Flow::verifier(), None).await });
until_blocked(&mut suspension, 1).await;
suspension.until_blocked(1).await;
suspension.commit().await.expect("commit");

let response = exchange.await.expect("exchange");
Expand Down Expand Up @@ -124,7 +124,7 @@ async fn consent_waits_for_an_owners_change_to_the_app() {
.await
.status()
});
until_blocked(&mut change, 1).await;
change.until_blocked(1).await;
change
.oidc()
.lock_client(&flow.client.id)
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/oidc/tests/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ async fn a_refresh_that_waits_for_an_undo_or_disablement_issues_nothing() {
.expect("user");
let refreshing = flow.clone();
let refresh = tokio::spawn(async move { refreshing.refresh(&token).await });
until_blocked(&mut holder, 1).await;
holder.until_blocked(1).await;
if disable {
holder
.users()
Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/passkey/tests/related_pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use super::*;
use crate::{
ClientRegistry,
tests::{change, operator, reason, register, until_blocked},
tests::{change, operator, reason, register},
};
use sourceorigin_common::{ClientId, clients::RelatedOrigin};

Expand Down Expand Up @@ -484,7 +484,7 @@ async fn removing_an_origin_during_a_sign_in_refuses_it() {
json!({"ceremony_id":started["ceremony_id"],"credential":assertion}),
);
let (finished, ()) = tokio::join!(finish, async {
until_blocked(&mut removal, 1).await;
removal.until_blocked(1).await;
removal.commit().await.expect("commit");
});
assert_eq!(finished.status(), StatusCode::BAD_REQUEST);
Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/recovery/tests/undo.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Undoing a recovery: who may, what it takes back, and what the pages read of it.

use super::*;
use crate::{passkey::VerifiedRecoveryUndo, tests::until_blocked};
use crate::passkey::VerifiedRecoveryUndo;
use sourceorigin_common::events::SignInFailure;

/// Undoing a recovery in probation, with a passkey from before it and no
Expand Down Expand Up @@ -94,7 +94,7 @@ async fn an_undo_and_a_client_deletion_never_deadlock() {
let admin = scenario.admin();
async move { admin.undo_recovery(&cli(), user, recovery_reason()).await }
});
until_blocked(&mut holder, 1).await;
holder.until_blocked(1).await;
holder
.oidc()
.delete_client(&client)
Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/security/tests/sessions.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Session lookup, passkey confirmation age and session locking against logout.

use super::*;
use crate::tests::{Browser, Replicas, until_blocked};
use crate::tests::{Browser, Replicas};
use sourceorigin_crypto::Secret;
use sourceorigin_repository::InsertSession;

Expand Down Expand Up @@ -111,7 +111,7 @@ async fn confirmed_changes_serialize_with_logout() {
}
});
// The logout waits for the change.
until_blocked(&mut change, 1).await;
change.until_blocked(1).await;
change.commit().await.expect("commit change");
assert_eq!(logout.await.expect("logout task").expect("logout"), [id]);
let mut change = database.begin().await.expect("change transaction");
Expand Down
11 changes: 0 additions & 11 deletions apps/auth-service/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -740,17 +740,6 @@ pub(crate) async fn sign_out(
.await
}

/// Waits until `waiters` other transactions wait for a lock `holder` holds.
pub(crate) async fn until_blocked(holder: &mut DatabaseTransaction<'_>, waiters: i64) {
tokio::time::timeout(std::time::Duration::from_secs(10), async {
while holder.blocked_transactions().await.expect("lock waits") < waiters {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("the operation waits for the holder's lock");
}

/// Issues the refresh grant `family` to `client` from `user_id`'s session
/// `session_id`, as a code exchange would, and returns its first refresh token's
/// ID and digest.
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/web/admin/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
security::{BrowserCookie, RequestContext},
tests::{
AUTH_ORIGIN, Browser, OWN_PAGE, Replicas, cookie, html, location, operator, parameter,
policy, reason, redirect, until_blocked,
policy, reason, redirect,
},
};
use axum::{
Expand Down
4 changes: 2 additions & 2 deletions apps/auth-service/src/web/admin/tests/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ async fn a_sign_in_racing_a_revocation_never_outlives_it() {
let (revoked, ()) = tokio::join!(
service.revoke_administrator(&cli, admin.user_id, reason()),
async {
until_blocked(&mut redeeming, 1).await;
redeeming.until_blocked(1).await;
let expires_at = Utc::now() + chrono::Duration::hours(1);
(redeeming.dashboard())
.insert_session(b"in flight", admin.session_id, Utc::now(), expires_at)
Expand Down Expand Up @@ -178,7 +178,7 @@ async fn a_sign_in_racing_a_revocation_never_outlives_it() {
sign_in.hand_off(&owner, &query, proof()),
dashboard.visit(&harness.dashboard, code_url.as_str()),
async {
until_blocked(&mut revoking, 2).await;
revoking.until_blocked(2).await;
revoking.commit().await.expect("commit");
}
);
Expand Down
2 changes: 2 additions & 0 deletions crates/database/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,8 @@ impl Database {
.await
.expect("wait state")
{
// wall-clock: PostgreSQL shows lock waits only in its catalog views,
// and signals nothing when one starts.
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
Expand Down
36 changes: 32 additions & 4 deletions crates/database/src/fixtures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
//! sessions, delivery channels and an account's event history. This crate's
//! tests use them, and so do other crates' tests, behind the `test-util` feature.

use crate::{Database, DatabaseConfig, EventRepository, InsertSession, InsertUser, UserRepository};
use crate::{
Database, DatabaseConfig, DatabaseTransaction, EventRepository, InsertSession, InsertUser,
UserRepository,
};
use chrono::{TimeDelta, Utc};
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
Expand All @@ -24,8 +27,8 @@ impl Database {
)]
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 config =
DatabaseConfig::new(&url, 5, Duration::from_secs(5)).expect("database configuration");
let database = Self::connect(config).await.expect("connect");
database.run_migrations().await.expect("migrate");
database
Expand Down Expand Up @@ -117,6 +120,31 @@ impl EventRepository<'_> {
}
}

impl DatabaseTransaction<'_> {
/// Waits until `waiters` other transactions wait for a lock this one holds,
/// directly or queued behind another waiter, so a test orders concurrent work
/// on what the database is doing.
///
/// # Panics
///
/// Panics if a query fails, or fewer transactions wait within ten seconds.
#[expect(
clippy::expect_used,
reason = "test-only fixture; documented under `# Panics`"
)]
pub async fn until_blocked(&mut self, waiters: i64) {
tokio::time::timeout(Duration::from_secs(10), async {
while self.blocked_transactions().await.expect("lock waits") < waiters {
// wall-clock: PostgreSQL shows lock waits only in its catalog views,
// and signals nothing when one starts.
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the other transactions wait for the holder's lock");
}
}

/// Declares channels whose deliveries tests insert themselves, so no event causes
/// one. Each entry reads `/// Doc comment` then
/// `Name = "stored_name": Recipient => Payload;`. Tests run at once on one
Expand Down
Loading