Skip to content

Commit f435f19

Browse files
PiquelChipsclaude
andcommitted
feat(auth): run auth as several replicas
Auth keeps its state in PostgreSQL, but nothing checked that two instances agree, and every deploy already overlaps two replicas. - AuthConfig::router no longer writes to the database. Startup provisions OIDC clients separately with AuthConfig::provision_clients, so tests can build two routers on one database as replicas. - Database tests build two replicas and check that a passkey sign-in and a logout span them, that they share one rate-limit budget, and that a refresh token rotated on both at once rotates exactly once. - On shutdown, expired-state cleanup finishes its current batch instead of being aborted. - The auth_replicas manifest variable sets the replica count (default 1). - infra/README.md documents what replicas share; database-crate.md makes migrations expand, then contract. Refs #33. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9af9abe commit f435f19

12 files changed

Lines changed: 322 additions & 35 deletions

File tree

‎apps/auth-service/src/assets.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,9 @@ impl From<AssetError> for ApiError {
3737
pub(crate) struct EmbeddedAssets(&'static [(&'static str, &'static [u8])]);
3838
impl EmbeddedAssets {
3939
/// Takes the embedded frontend, rejecting executables compiled before it was built.
40+
/// Tests accept an empty frontend: they build routers but never request a page.
4041
pub(crate) fn new() -> Result<Self, StartupError> {
41-
if FILES.is_empty() {
42+
if FILES.is_empty() && !cfg!(test) {
4243
Err(StartupError::MissingAssets)
4344
} else {
4445
Ok(Self(FILES))

‎apps/auth-service/src/lib.rs‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ mod routes;
1717
mod security;
1818
/// Built-in public configuration, liveness and readiness.
1919
mod service;
20+
/// Fixtures shared by the applications' tests.
21+
#[cfg(test)]
22+
mod tests;
2023

2124
pub use config::{AuthConfig, PUBLIC_BASE_URL};
2225
use federation::FederationApplication;
@@ -56,24 +59,17 @@ pub enum StartupError {
5659

5760
impl AuthConfig {
5861
/// Builds uniformly constructed applications under shared browser-origin protection.
62+
/// It changes nothing in the database, so tests build several to act as replicas.
5963
///
6064
/// # Errors
61-
/// Fails when the frontend is not embedded, an application cannot initialize, or
62-
/// client provisioning fails.
63-
pub async fn router(&self, database: Database) -> Result<Router, StartupError> {
64-
// Finish fallible application initialization before changing client registrations.
65+
/// Fails when the frontend is not embedded or an application cannot initialize.
66+
pub fn router(&self, database: Database) -> Result<Router, StartupError> {
6567
let assets = EmbeddedAssets::new()?;
6668
let application = Router::new()
6769
.merge(ServiceApplication::new(database.clone(), self).routes())
6870
.merge(PasskeyApplication::new(database.clone(), &self.passkey)?.routes())
6971
.merge(FederationApplication::new(database.clone(), &self.federation)?.routes())
7072
.merge(OidcApplication::new(database.clone(), &self.oidc)?.routes());
71-
let mut tx = database.begin().await?;
72-
tx.oidc().disable_all_clients().await?;
73-
for client in &self.oidc.clients {
74-
tx.oidc().bootstrap_client(client).await?;
75-
}
76-
tx.commit().await?;
7773
let policy = security::HttpSecurity::new(self, database);
7874
Ok(application
7975
.fallback(move |uri: Uri| async move { assets.serve(uri.path()) })
@@ -83,4 +79,19 @@ impl AuthConfig {
8379
security::HttpSecurity::protect,
8480
)))
8581
}
82+
83+
/// Replaces every client registration with the clients file, atomically. Every
84+
/// replica runs this at startup, after [`Self::router`] has initialized.
85+
///
86+
/// # Errors
87+
/// Fails when the database rejects the registrations.
88+
pub async fn provision_clients(&self, database: &Database) -> Result<(), StartupError> {
89+
let mut tx = database.begin().await?;
90+
tx.oidc().disable_all_clients().await?;
91+
for client in &self.oidc.clients {
92+
tx.oidc().bootstrap_client(client).await?;
93+
}
94+
tx.commit().await?;
95+
Ok(())
96+
}
8697
}

‎apps/auth-service/src/main.rs‎

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use piquel_common::{ConfigurationError, ErrorChain, Origin};
66
use piquel_crypto::{CryptoError, Secret};
77
use piquel_repository::{Database, DatabaseConnectionError, DatabaseError};
88
use thiserror::Error;
9+
use tokio::sync::oneshot;
910

1011
use std::{net::SocketAddr, process::ExitCode, str::FromStr, time::Duration as StdDuration};
1112

@@ -47,6 +48,9 @@ enum CliError {
4748
/// The service listener could not be bound or served.
4849
#[error("authentication HTTP listener failed")]
4950
Listener(#[from] std::io::Error),
51+
/// Expired-state cleanup panicked.
52+
#[error("expired authentication state cleanup panicked")]
53+
Cleanup(#[from] tokio::task::JoinError),
5054
}
5155

5256
/// Piquel authentication service. Runs `serve` when no command is given.
@@ -152,10 +156,16 @@ impl DatabaseCommand {
152156
/// Every five minutes, drains expired auth state in bounded batches until a
153157
/// pass finds nothing or a one-minute budget runs out. Short pauses between
154158
/// batches keep cleanup from monopolizing the database under heavy churn.
155-
async fn purge_expired_state(database: Database) {
159+
/// Returns once `stop` resolves, which its sender's drop triggers, after
160+
/// finishing the batch in progress.
161+
async fn purge_expired_state(database: Database, mut stop: oneshot::Receiver<()>) {
156162
let mut interval = tokio::time::interval(CLEANUP_INTERVAL);
157163
loop {
158-
interval.tick().await;
164+
tokio::select! {
165+
biased;
166+
_ = &mut stop => return,
167+
_ = interval.tick() => {}
168+
}
159169
let deadline = tokio::time::Instant::now() + CLEANUP_BUDGET;
160170
loop {
161171
match database.purge_expired_auth_state(CLEANUP_BATCH_SIZE).await {
@@ -164,7 +174,11 @@ impl DatabaseCommand {
164174
tracing::warn!("expired authentication state cleanup is falling behind");
165175
break;
166176
}
167-
Ok(_) => tokio::time::sleep(CLEANUP_PAUSE).await,
177+
Ok(_) => tokio::select! {
178+
biased;
179+
_ = &mut stop => return,
180+
() = tokio::time::sleep(CLEANUP_PAUSE) => {}
181+
},
168182
Err(error) => {
169183
tracing::error!(?error, "expired authentication state cleanup failed");
170184
break;
@@ -174,21 +188,30 @@ impl DatabaseCommand {
174188
}
175189
}
176190

177-
/// Builds the configured service, starts cleanup and serves until a shutdown signal.
191+
/// Builds the configured service, provisions clients, starts cleanup and serves
192+
/// until a shutdown signal. Cleanup then finishes its current batch while
193+
/// in-flight requests drain.
178194
async fn serve(database: Database) -> Result<(), CliError> {
179195
let config = AuthConfig::from_environment()?;
180196
let listener = tokio::net::TcpListener::bind(config.public_listener).await?;
181-
let router = config.router(database.clone()).await?;
182-
let cleanup = tokio::spawn(Self::purge_expired_state(database));
197+
let router = config.router(database.clone())?;
198+
config.provision_clients(&database).await?;
199+
let (stop, stopped) = oneshot::channel();
200+
let cleanup = tokio::spawn(Self::purge_expired_state(database, stopped));
183201
tracing::info!(address=%config.public_listener,"authentication service listening");
184202
let result = axum::serve(
185203
listener,
186204
router.into_make_service_with_connect_info::<SocketAddr>(),
187205
)
188-
.with_graceful_shutdown(Self::shutdown_signal())
206+
.with_graceful_shutdown(async move {
207+
Self::shutdown_signal().await;
208+
drop(stop);
209+
})
189210
.await;
190-
cleanup.abort();
191-
Ok(result?)
211+
// A listener failure drops `stop` with the shutdown future, so cleanup ends too.
212+
let cleanup = cleanup.await;
213+
result?;
214+
Ok(cleanup?)
192215
}
193216
}
194217

‎apps/auth-service/src/oidc/tests.rs‎

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Focused parsing checks and database-backed OAuth/OIDC scenarios.
22
33
use super::*;
4+
use crate::tests::{AUTH_ORIGIN, Replicas};
45
use axum::{
56
body::{Body, to_bytes},
67
http::{Method, Request, StatusCode},
@@ -15,9 +16,12 @@ use tower::ServiceExt;
1516
use url::Url;
1617

1718
/// Database-backed OIDC scenario with a provisioned client and authenticated browser.
19+
#[derive(Clone)]
1820
struct Flow {
1921
/// Application under test, sharing the scenario database.
2022
app: OidcApplication,
23+
/// Where requests go: the OIDC routes, or a replica of the whole service.
24+
router: axum::Router,
2125
/// Client identifier bound into the token claims.
2226
client: BootstrapOidcClient,
2327
/// Authenticated browser cookie pair sent by the scenario.
@@ -109,7 +113,7 @@ impl Flow {
109113
let app = OidcApplication::new(
110114
db,
111115
&OidcConfig {
112-
origin: "https://auth.example.com"
116+
origin: AUTH_ORIGIN
113117
.parse::<piquel_common::Origin>()
114118
.expect("issuer"),
115119
keys: Arc::new(Rs256Key::generate("oidc-tests").expect("RSA signing key")),
@@ -120,13 +124,21 @@ impl Flow {
120124
)
121125
.expect("OIDC application");
122126
Self {
127+
router: app.clone().routes(),
123128
app,
124129
client,
125130
cookie,
126131
user_id,
127132
basic,
128133
}
129134
}
135+
/// The same scenario, sending its requests to `router`, such as one of [`Replicas`].
136+
fn on(&self, router: &axum::Router) -> Self {
137+
Self {
138+
router: router.clone(),
139+
..self.clone()
140+
}
141+
}
130142
/// Dispatches an encoded protocol request through the OIDC routes.
131143
async fn request(
132144
&self,
@@ -139,7 +151,7 @@ impl Flow {
139151
.method(method)
140152
.uri(uri)
141153
.header(header::COOKIE, &self.cookie)
142-
.header(header::ORIGIN, "https://auth.example.com")
154+
.header(header::ORIGIN, AUTH_ORIGIN)
143155
.header("x-piquel-csrf", "1");
144156
if let Some(basic) = basic {
145157
builder = builder.header(header::AUTHORIZATION, basic);
@@ -151,9 +163,8 @@ impl Flow {
151163
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
152164
.body(Body::from(body))
153165
.expect("build test HTTP request");
154-
self.app
166+
self.router
155167
.clone()
156-
.routes()
157168
.oneshot(request)
158169
.await
159170
.expect("dispatch OIDC HTTP request")
@@ -170,7 +181,7 @@ impl Flow {
170181
prompt: Option<&str>,
171182
extra: &[(&str, &str)],
172183
) -> Response {
173-
let mut url = Url::parse("https://auth.example.com/oauth/authorize")
184+
let mut url = Url::parse(&format!("{AUTH_ORIGIN}/oauth/authorize"))
174185
.expect("parse authorization endpoint URL");
175186
url.query_pairs_mut().extend_pairs([
176187
("response_type", ResponseType::Code.as_str()),
@@ -613,6 +624,42 @@ async fn code_replay_revokes_its_refresh_family() {
613624
);
614625
}
615626

627+
/// The same refresh token, rotated on two replicas at once, rotates exactly once. The
628+
/// other attempt is a replay, which revokes the family.
629+
#[tokio::test]
630+
#[ignore = "requires TEST_DATABASE_URL"]
631+
async fn concurrent_refresh_across_replicas_rotates_once() {
632+
let flow = Flow::new(true, true).await;
633+
let replicas = Replicas::new().await;
634+
let (a, b) = (flow.on(&replicas.a), flow.on(&replicas.b));
635+
let code = a.code(REFRESH_SCOPES).await;
636+
let response = b
637+
.exchange(&code, Flow::verifier(), b.basic.as_deref())
638+
.await;
639+
assert_eq!(response.status(), StatusCode::OK);
640+
let token = Flow::json(response).await["refresh_token"]
641+
.as_str()
642+
.expect("token response contains a refresh token")
643+
.to_owned();
644+
let (first, second) = tokio::join!(a.refresh(&token), b.refresh(&token));
645+
let (rotated, replayed) = if first.status() == StatusCode::OK {
646+
(first, second)
647+
} else {
648+
(second, first)
649+
};
650+
assert_eq!(rotated.status(), StatusCode::OK);
651+
assert_eq!(replayed.status(), StatusCode::BAD_REQUEST);
652+
let rotated = Flow::json(rotated).await["refresh_token"]
653+
.as_str()
654+
.expect("refresh response contains the rotated token")
655+
.to_owned();
656+
assert_eq!(
657+
a.refresh(&rotated).await.status(),
658+
StatusCode::BAD_REQUEST,
659+
"the replay revoked the family"
660+
);
661+
}
662+
616663
/// Checks that policy reductions reject new requests and invalidate outstanding grants,
617664
/// and that unsafe logout redirects are refused.
618665
#[tokio::test]

‎apps/auth-service/src/passkey/tests.rs‎

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Focused name validation and database-backed `WebAuthn` ceremony invariants.
22
33
use super::*;
4+
use crate::tests::{AUTH_ORIGIN, Replicas};
45
use axum::{
56
body::{Body, to_bytes},
67
http::{Method, Request},
@@ -118,6 +119,8 @@ fn typed_ceremonies_preserve_persistence_and_check_the_expected_payload() {
118119
struct Fixture {
119120
/// Routes and persistence under test.
120121
app: PasskeyApplication,
122+
/// Where requests go: the passkey routes, or a replica of the whole service.
123+
router: axum::Router,
121124
/// Software credential capable of user verification and monotonic counters.
122125
authenticator: WebauthnAuthenticator<SoftPasskey>,
123126
/// HTTPS origin passed to the authenticator.
@@ -141,7 +144,7 @@ impl Fixture {
141144
.await
142145
.expect("database");
143146
database.run_migrations().await.expect("migrations");
144-
let origin = Url::parse("https://auth.piquel.fr/").expect("origin");
147+
let origin = Url::parse(AUTH_ORIGIN).expect("origin");
145148
let app = PasskeyApplication::new(
146149
database,
147150
&PasskeyConfig {
@@ -193,6 +196,7 @@ impl Fixture {
193196
.expect("stored key");
194197
tx.commit().await.expect("commit");
195198
Self {
199+
router: app.clone().routes(),
196200
app,
197201
authenticator,
198202
origin,
@@ -201,15 +205,21 @@ impl Fixture {
201205
username,
202206
}
203207
}
204-
/// Sends a JSON request through the passkey routes with the supplied cookies.
208+
/// Sends the next requests to `router`, such as one of [`Replicas`].
209+
fn on(&mut self, router: &axum::Router) -> &mut Self {
210+
self.router = router.clone();
211+
self
212+
}
213+
/// Sends a JSON request from the auth origin with the supplied cookies.
205214
async fn request(&self, path: &str, method: Method, cookies: &str, body: Value) -> Response {
206-
self.app
215+
self.router
207216
.clone()
208-
.routes()
209217
.oneshot(
210218
Request::builder()
211219
.method(method)
212220
.uri(path)
221+
.header(header::ORIGIN, AUTH_ORIGIN)
222+
.header("x-piquel-csrf", "1")
213223
.header(header::CONTENT_TYPE, "application/json")
214224
.header(header::COOKIE, cookies)
215225
.body(Body::from(body.to_string()))
@@ -838,3 +848,37 @@ async fn passkey_sign_in_confirms_the_browsers_session() {
838848
);
839849
assert!(authentication.auth_time > before.authenticated_at);
840850
}
851+
852+
/// A sign-in started on one replica finishes on the other, and logging out on one
853+
/// ends the session on both.
854+
#[tokio::test]
855+
#[ignore = "requires TEST_DATABASE_URL"]
856+
async fn sign_in_and_logout_span_replicas() {
857+
let mut fixture = Fixture::new().await;
858+
let replicas = Replicas::new().await;
859+
let username = json!({"username":fixture.username});
860+
let (started, browser) = fixture
861+
.on(&replicas.a)
862+
.start("/webauthn/authenticate/start", "", username)
863+
.await;
864+
let assertion = fixture.assertion(&started);
865+
let finished = fixture
866+
.on(&replicas.b)
867+
.request(
868+
"/webauthn/authenticate/finish",
869+
Method::POST,
870+
&browser,
871+
json!({"ceremony_id":started["ceremony_id"],"credential":assertion}),
872+
)
873+
.await;
874+
assert_eq!(finished.status(), StatusCode::NO_CONTENT);
875+
let session = Fixture::cookie(&finished);
876+
fixture.on(&replicas.a);
877+
let read = fixture.request("/session", Method::GET, &session, json!({}));
878+
assert_eq!(read.await.status(), StatusCode::OK);
879+
let logout = fixture.request("/session/logout", Method::POST, &session, json!({}));
880+
assert!(logout.await.status().is_success());
881+
fixture.on(&replicas.b);
882+
let read = fixture.request("/session", Method::GET, &session, json!({}));
883+
assert_eq!(read.await.status(), StatusCode::UNAUTHORIZED);
884+
}

0 commit comments

Comments
 (0)