From 7954eec0b47a000728182e268a9479679d8d3e17 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:03:43 +0100 Subject: [PATCH] test: session expiry and listener tests wait for their events instead of sleeping --- .../auth-service/src/admin/tests/mutations.rs | 2 ++ apps/auth-service/src/cli/serve/tests.rs | 21 +++++++++++++++---- .../src/security/tests/sessions.rs | 7 +++++-- ...4796c341343645db4e59c62422b9ee7c86f49.json | 14 +++++++++++++ crates/database/src/repositories/sessions.rs | 18 ++++++++++++++++ 5 files changed, 56 insertions(+), 6 deletions(-) create mode 100644 crates/database/.sqlx/query-0c5f9a0b365b185c3ba6bc66fde4796c341343645db4e59c62422b9ee7c86f49.json diff --git a/apps/auth-service/src/admin/tests/mutations.rs b/apps/auth-service/src/admin/tests/mutations.rs index b10dce728..62c31eb85 100644 --- a/apps/auth-service/src/admin/tests/mutations.rs +++ b/apps/auth-service/src/admin/tests/mutations.rs @@ -34,6 +34,8 @@ async fn mutations_recheck_the_confirmation_after_waiting() { "the mutation waits while its caller is still confirmed" ); let expired = auth_time + window + Duration::milliseconds(10) - Utc::now(); + // wall-clock: the confirmation ends by the system clock, which paused + // tokio time doesn't move. tokio::time::sleep(expired.to_std().unwrap_or_default()).await; logout.commit().await.expect("logout"); } diff --git a/apps/auth-service/src/cli/serve/tests.rs b/apps/auth-service/src/cli/serve/tests.rs index d31fdbf52..8b878f763 100644 --- a/apps/auth-service/src/cli/serve/tests.rs +++ b/apps/auth-service/src/cli/serve/tests.rs @@ -3,7 +3,10 @@ use super::*; use axum::routing::get; use std::net::SocketAddr; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + sync::mpsc, +}; /// A listener on a free local port, serving `router` until the returned sender is /// set, and the port's address. @@ -38,15 +41,25 @@ async fn a_connection_that_never_finishes_its_headers_is_closed() { /// then cuts off a request that never ends. #[tokio::test(start_paused = true)] async fn a_stop_cuts_off_requests_after_the_grace_period() { - let router = Router::new().route("/", get(std::future::pending::<()>)); + let (reached, mut arrivals) = mpsc::unbounded_channel(); + let handler = move || { + let reached = reached.clone(); + async move { + reached.send(()).expect("the test listens"); + std::future::pending::<()>().await; + } + }; + let router = Router::new().route("/", get(handler)); let (address, stop, mut server) = serving(router).await; let mut client = TcpStream::connect(address).await.expect("connect"); client .write_all(b"GET / HTTP/1.1\r\nHost: auth\r\n\r\n") .await .expect("request"); - // Let the request reach its handler before stopping. - tokio::task::yield_now().await; + arrivals + .recv() + .await + .expect("the request reaches its handler"); let started = Instant::now(); stop.send_replace(true); server diff --git a/apps/auth-service/src/security/tests/sessions.rs b/apps/auth-service/src/security/tests/sessions.rs index 4ac679ad2..01001449f 100644 --- a/apps/auth-service/src/security/tests/sessions.rs +++ b/apps/auth-service/src/security/tests/sessions.rs @@ -136,7 +136,7 @@ async fn session_lock_rechecks_expiry_after_waiting() { user_id, authentication_methods: vec![AuthenticationMethod::Passkey], authenticated_at: now, - expires_at: now + Duration::seconds(1), + expires_at: now + Duration::hours(1), user_agent_family: RequestContext::TEST.user_agent_family, ip: RequestContext::TEST.client_ip, passkey_confirmed_at: Some(now), @@ -151,6 +151,7 @@ async fn session_lock_rechecks_expiry_after_waiting() { .await .expect("account lock") .expect("active account"); + let id = session.id; let change = tokio::spawn({ let database = database.clone(); async move { @@ -158,7 +159,9 @@ async fn session_lock_rechecks_expiry_after_waiting() { Session::lock(&mut change, &session).await.map(drop) } }); - tokio::time::sleep(std::time::Duration::from_millis(1500)).await; + // The session expires while the change waits, after its transaction began. + holder.until_blocked(1).await; + database.sessions().expire(id).await.expect("expire"); holder.rollback().await.expect("release account"); assert!(matches!( change.await.expect("change task"), diff --git a/crates/database/.sqlx/query-0c5f9a0b365b185c3ba6bc66fde4796c341343645db4e59c62422b9ee7c86f49.json b/crates/database/.sqlx/query-0c5f9a0b365b185c3ba6bc66fde4796c341343645db4e59c62422b9ee7c86f49.json new file mode 100644 index 000000000..cfa145b3a --- /dev/null +++ b/crates/database/.sqlx/query-0c5f9a0b365b185c3ba6bc66fde4796c341343645db4e59c62422b9ee7c86f49.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE sessions SET expires_at = clock_timestamp() WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "0c5f9a0b365b185c3ba6bc66fde4796c341343645db4e59c62422b9ee7c86f49" +} diff --git a/crates/database/src/repositories/sessions.rs b/crates/database/src/repositories/sessions.rs index 7dcf9326e..031dd900e 100644 --- a/crates/database/src/repositories/sessions.rs +++ b/crates/database/src/repositories/sessions.rs @@ -329,6 +329,24 @@ impl SessionRepository<'_> { ) } + /// Makes session `id` expire now: a fixture for expiry. + /// + /// # Errors + /// + /// Returns [`DatabaseError`] if the update fails. + #[cfg(any(test, feature = "test-util"))] + pub async fn expire(&mut self, id: SessionId) -> Result<(), DatabaseError> { + run!( + self, + execute, + sqlx::query!( + "UPDATE sessions SET expires_at = clock_timestamp() WHERE id = $1", + id.as_uuid(), + ) + )?; + Ok(()) + } + /// Revokes the active `scope` sessions of `user_id`, with the refresh token /// families issued from every `scope` session, and returns the IDs of the /// sessions it revoked. Sessions and families of other accounts are never