From 63dd3a4e530095fcf66c50e08db573ab3920553a Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:16:48 +0200 Subject: [PATCH 1/6] docs(auth): add operational security runbooks --- docs/operations/auth-incidents.md | 14 ++++++++++++++ docs/operations/auth-key-rotation.md | 11 +++++++++++ docs/operations/auth-release.md | 12 ++++++++++++ docs/security/auth-data-retention.md | 13 +++++++++++++ justfile | 13 +++++++++++++ 5 files changed, 63 insertions(+) create mode 100644 docs/operations/auth-incidents.md create mode 100644 docs/operations/auth-key-rotation.md create mode 100644 docs/operations/auth-release.md create mode 100644 docs/security/auth-data-retention.md diff --git a/docs/operations/auth-incidents.md b/docs/operations/auth-incidents.md new file mode 100644 index 000000000..47664b041 --- /dev/null +++ b/docs/operations/auth-incidents.md @@ -0,0 +1,14 @@ +# Auth incident response + +For refresh-token replay, revoke the affected family in one transaction, retain +the sanitized audit record, and return only a generic invalid-grant response. +Existing access JWTs may remain valid for their accepted five-minute tail. + +For an auth outage, fail closed for new authentication and token issuance; +resource servers may continue to validate unexpired access JWTs locally. Do not +copy raw tokens, authorization codes, WebAuthn challenges, or provider callback +parameters into tickets, dashboards, or logs. + +After restoring a backup, validate user IDs, verified-email ownership, active +sessions, refresh-family revocation, and internal-event aggregate sequences +before accepting production traffic. diff --git a/docs/operations/auth-key-rotation.md b/docs/operations/auth-key-rotation.md new file mode 100644 index 000000000..5f0e349c0 --- /dev/null +++ b/docs/operations/auth-key-rotation.md @@ -0,0 +1,11 @@ +# Auth signing and service-key rotation + +Create a new asymmetric signing key in the approved key provider with a stable +`kid`. Publish its public JWK while retaining the old public key, begin issuing +with the new key, and retain the old JWK for longer than the maximum token life +(five minutes for access and service tokens). Remove the old JWK only after that +overlap has elapsed and no token class depending on it remains valid. + +Service public keys follow the same overlap rule: register the new `kid`, permit +both keys during transition, move the service signer, then revoke the old key. +Runtime services cannot self-register or rotate their own keys. diff --git a/docs/operations/auth-release.md b/docs/operations/auth-release.md new file mode 100644 index 000000000..8e65c2e6e --- /dev/null +++ b/docs/operations/auth-release.md @@ -0,0 +1,12 @@ +# Auth release and migration order + +1. Run `just check`, `just test`, `pnpm check:web`, and `pnpm test:web`. +2. Back up PostgreSQL and verify the restore procedure before a schema release. +3. Run `just migrate "$DATABASE_URL"` once with the migration role. +4. Deploy auth-service replicas with readiness checks enabled; replicas never run + migrations at startup. +5. Deploy auth-web only after the public auth endpoints it references are live. + +Liveness is process-only. Readiness fails closed when PostgreSQL or a required +key provider is unavailable. During a graceful shutdown, remove the replica +from intake first and allow only bounded in-flight requests to complete. diff --git a/docs/security/auth-data-retention.md b/docs/security/auth-data-retention.md new file mode 100644 index 000000000..b8350385a --- /dev/null +++ b/docs/security/auth-data-retention.md @@ -0,0 +1,13 @@ +# Auth redaction and retained data + +Security audit events retain action, outcome, timestamp, and minimized request +metadata. They never contain passwords, tokens, authorization codes, PKCE +verifiers, WebAuthn challenges, provider access/refresh tokens, or client +secrets. Metrics use bounded outcome and endpoint labels only; they do not use +emails, raw user IDs, headers, or unbounded provider data. + +Accepted first-iteration risks are the maximum five-minute access-token tail +after revocation and trusted verified-email assertions from the explicitly +approved GitHub and Google providers. Redis, if introduced, is disposable +coordination only and must never be an authority for identity, session, +revocation, audit, or event state. diff --git a/justfile b/justfile index 7f455646b..ff2588777 100644 --- a/justfile +++ b/justfile @@ -10,6 +10,19 @@ test: test-database: cargo test -p piquel-repository --test identity -- --ignored --test-threads=1 +check-web: + pnpm check:web + +test-web: + pnpm test:web + +ci: + cargo fmt --all --check + cargo clippy --workspace --all-targets --all-features -- -D warnings + cargo test --workspace + pnpm check:web + pnpm test:web + migrate: cargo run -p piquel-repository --bin migrate From b79209306db9fc2557fd76d1b94b58b456848f49 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:03:27 +0200 Subject: [PATCH 2/6] fix(auth): enforce operational hardening controls --- Cargo.lock | 4 + Cargo.toml | 2 +- apps/auth-service/Cargo.toml | 1 + apps/auth-service/src/hardening.rs | 125 +++++++++++++++++++++++++++++ apps/auth-service/src/lib.rs | 25 +++--- apps/auth-service/src/main.rs | 41 +++++++--- docs/operations/auth-release.md | 3 +- 7 files changed, 180 insertions(+), 21 deletions(-) create mode 100644 apps/auth-service/src/hardening.rs diff --git a/Cargo.lock b/Cargo.lock index da2bb63b9..5c270509a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -148,6 +148,7 @@ dependencies = [ "tokio-stream", "tonic", "tower 0.5.3", + "tower-http", "tracing", "unicode-normalization", "url", @@ -3116,10 +3117,13 @@ dependencies = [ "futures-util", "http", "http-body", + "http-body-util", "pin-project-lite", + "tokio", "tower 0.5.3", "tower-layer", "tower-service", + "tracing", "url", ] diff --git a/Cargo.toml b/Cargo.toml index a0dc9a4e1..7fbf2bec9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,7 @@ tonic-build = "0.12" tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time", "sync"] } tokio-stream = { version = "0.1", features = ["net"] } tower = { version = "0.5", features = ["util"] } -tower-http = { version = "0.6", features = ["trace"] } +tower-http = { version = "0.6", features = ["trace", "limit", "timeout", "set-header", "catch-panic"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } url = { version = "2.5", features = ["serde"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index 5d98e0f88..c81ac9abd 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -29,6 +29,7 @@ reqwest.workspace = true thiserror.workspace = true tokio.workspace = true tonic.workspace = true +tower-http.workspace = true tracing.workspace = true unicode-normalization.workspace = true url.workspace = true diff --git a/apps/auth-service/src/hardening.rs b/apps/auth-service/src/hardening.rs new file mode 100644 index 000000000..bfd2aaacc --- /dev/null +++ b/apps/auth-service/src/hardening.rs @@ -0,0 +1,125 @@ +//! Bounded public HTTP controls with sanitized, low-cardinality telemetry. + +use axum::{ + Router, + extract::{ConnectInfo, Request, State}, + http::{HeaderValue, StatusCode, header}, + middleware::{self, Next}, + response::{IntoResponse, Response}, +}; +use std::{ + collections::HashMap, + net::{IpAddr, SocketAddr}, + sync::Arc, + time::{Duration, Instant}, +}; +use tokio::sync::Mutex; +use tower_http::{ + catch_panic::CatchPanicLayer, limit::RequestBodyLimitLayer, set_header::SetResponseHeaderLayer, + timeout::TimeoutLayer, +}; + +#[derive(Clone, Default)] +struct Limiter(Arc>>); +struct Window { + started: Instant, + count: u32, +} +pub(super) fn apply(router: Router) -> Router { + let limiter = Limiter::default(); + router + .layer(SetResponseHeaderLayer::if_not_present( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + )) + .layer(SetResponseHeaderLayer::if_not_present( + header::CACHE_CONTROL, + HeaderValue::from_static("no-store"), + )) + .layer(SetResponseHeaderLayer::if_not_present( + header::STRICT_TRANSPORT_SECURITY, + HeaderValue::from_static("max-age=31536000; includeSubDomains"), + )) + .layer(CatchPanicLayer::new()) + .layer(TimeoutLayer::with_status_code( + StatusCode::REQUEST_TIMEOUT, + Duration::from_secs(10), + )) + .layer(RequestBodyLimitLayer::new(64 * 1024)) + .layer(middleware::from_fn_with_state(limiter, enforce)) +} +async fn enforce(State(limiter): State, request: Request, next: Next) -> Response { + let (class, limit) = classify(request.uri().path()); + let address = match request + .extensions() + .get::>() + .map(|value| value.0.ip()) + { + Some(address) => address, + None if class == "public" => IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), + None => { + return ( + StatusCode::SERVICE_UNAVAILABLE, + "request source unavailable", + ) + .into_response(); + } + }; + let now = Instant::now(); + let mut windows = limiter.0.lock().await; + if windows.len() > 10_000 { + windows.retain(|_, window| now.duration_since(window.started) < Duration::from_mins(1)); + } + let window = windows.entry((address, class)).or_insert(Window { + started: now, + count: 0, + }); + if now.duration_since(window.started) >= Duration::from_mins(1) { + *window = Window { + started: now, + count: 0, + }; + } + if window.count >= limit { + tracing::warn!( + endpoint_class = class, + outcome = "rate_limited", + "authentication request rejected" + ); + return (StatusCode::TOO_MANY_REQUESTS, "too many requests").into_response(); + } + window.count += 1; + drop(windows); + let response = next.run(request).await; + tracing::info!( + endpoint_class = class, + status = response.status().as_u16(), + "authentication request completed" + ); + response +} +fn classify(path: &str) -> (&'static str, u32) { + if path.starts_with("/webauthn/") { + ("webauthn", 30) + } else if path.starts_with("/login/") { + ("federation", 30) + } else if path == "/oauth/token" || path == "/oauth/revoke" { + ("token", 60) + } else if path == "/oauth/authorize" { + ("authorization", 60) + } else if path.starts_with("/account/") { + ("account", 60) + } else { + ("public", 300) + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn sensitive_routes_have_specific_bounds() { + assert_eq!(classify("/oauth/token"), ("token", 60)); + assert_eq!(classify("/login/google/callback"), ("federation", 30)); + assert_eq!(classify("/webauthn/authenticate/start"), ("webauthn", 30)); + } +} diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 0dd5599fe..d711ec57c 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -24,6 +24,7 @@ pub use oidc::{Es256KeyProvider, KeyProvider, OidcApplication}; #[allow(dead_code)] mod passkey; pub use passkey::PasskeyApplication; +mod hardening; mod service_rpc; #[allow(dead_code)] mod session; @@ -122,15 +123,15 @@ pub trait Readiness: Send + Sync { /// Production readiness checks `PostgreSQL` and resolves the configured key. pub struct ProductionReadiness { database: Database, - key_provider: SecretReference, + secret_providers: Vec, } impl ProductionReadiness { /// Builds the production readiness dependency set. #[must_use] - pub const fn new(database: Database, key_provider: SecretReference) -> Self { + pub fn new(database: Database, secret_providers: Vec) -> Self { Self { database, - key_provider, + secret_providers, } } } @@ -138,11 +139,14 @@ impl ProductionReadiness { impl Readiness for ProductionReadiness { async fn check(&self) -> Result<(), ()> { self.database.health_check().await.map_err(|_| ())?; - tokio::time::timeout(Duration::from_secs(2), async { - self.key_provider.resolve().map(|_| ()).map_err(|_| ()) - }) - .await - .map_err(|_| ())? + for provider in &self.secret_providers { + tokio::time::timeout(Duration::from_secs(2), async { + provider.resolve().map(|_| ()).map_err(|_| ()) + }) + .await + .map_err(|_| ())??; + } + Ok(()) } } @@ -166,9 +170,10 @@ pub fn router( health.merge(passkey::routes(passkeys)) }); let router = oidc.map_or(router.clone(), |oidc| router.merge(oidc::routes(oidc))); - federation.map_or(router.clone(), |federation| { + let router = federation.map_or(router.clone(), |federation| { router.merge(federation::routes(federation)) - }) + }); + hardening::apply(router) } async fn ready(State(state): State) -> impl IntoResponse { diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index a56edcd5b..342b1b7f9 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -12,6 +12,14 @@ use std::{net::SocketAddr, sync::Arc, time::Duration}; async fn main() -> anyhow::Result<()> { piquel_telemetry::init("auth_service=info"); let config = AuthConfig::from_environment()?; + let readiness_secrets = vec![ + config.key_provider.clone(), + config.github.client_secret.clone(), + config.google.client_secret.clone(), + config.rpc_tls_certificate.clone(), + config.rpc_tls_private_key.clone(), + config.rpc_client_ca.clone(), + ]; let listener_address: SocketAddr = config.public_listener; let database = Database::connect(config.database).await?; let key_secret = config.key_provider.resolve()?; @@ -79,15 +87,22 @@ async fn main() -> anyhow::Result<()> { let rpc_client_ca = config.rpc_client_ca.resolve()?; let listener = tokio::net::TcpListener::bind(listener_address).await?; tracing::info!(%listener_address, "auth service listening"); + let (shutdown_sender, shutdown_receiver) = tokio::sync::watch::channel(false); + tokio::spawn(async move { + shutdown_signal().await; + let _ = shutdown_sender.send(true); + }); let public = axum::serve( listener, router( - Arc::new(ProductionReadiness::new(database, config.key_provider)), + Arc::new(ProductionReadiness::new(database, readiness_secrets)), Some(passkeys), Some(oidc), Some(federation), - ), - ); + ) + .into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(wait_for_shutdown(shutdown_receiver.clone())); let tls = tonic::transport::ServerTlsConfig::new() .identity(tonic::transport::Identity::from_pem( rpc_certificate.expose_secret(), @@ -108,15 +123,23 @@ async fn main() -> anyhow::Result<()> { .max_decoding_message_size(16 * 1024), ) .add_service(rpc.auth_server().max_decoding_message_size(1024 * 1024)) - .serve(config.internal_listener); - tokio::select! { - result = public => result?, - result = private => result?, - () = shutdown_signal() => {}, - } + .serve_with_shutdown( + config.internal_listener, + wait_for_shutdown(shutdown_receiver), + ); + tokio::try_join!(async { public.await.map_err(anyhow::Error::from) }, async { + private.await.map_err(anyhow::Error::from) + })?; Ok(()) } async fn shutdown_signal() { let _ = tokio::signal::ctrl_c().await; } +async fn wait_for_shutdown(mut receiver: tokio::sync::watch::Receiver) { + while !*receiver.borrow() { + if receiver.changed().await.is_err() { + break; + } + } +} diff --git a/docs/operations/auth-release.md b/docs/operations/auth-release.md index 8e65c2e6e..cc8d5ff22 100644 --- a/docs/operations/auth-release.md +++ b/docs/operations/auth-release.md @@ -2,7 +2,8 @@ 1. Run `just check`, `just test`, `pnpm check:web`, and `pnpm test:web`. 2. Back up PostgreSQL and verify the restore procedure before a schema release. -3. Run `just migrate "$DATABASE_URL"` once with the migration role. +3. Export `AUTH_DATABASE_URL` only in the migration process environment and run + `just migrate` once with the migration role; never pass credentials in argv. 4. Deploy auth-service replicas with readiness checks enabled; replicas never run migrations at startup. 5. Deploy auth-web only after the public auth endpoints it references are live. From c3f4985965c51ac0d58e1f649fbd563304d951ae Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:05:26 +0200 Subject: [PATCH 3/6] fix(auth): drain on orchestrator termination --- apps/auth-service/src/main.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index 342b1b7f9..8134576a8 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -134,6 +134,14 @@ async fn main() -> anyhow::Result<()> { } async fn shutdown_signal() { + #[cfg(unix)] + { + let mut terminate = + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .expect("install SIGTERM handler"); + tokio::select! { _ = tokio::signal::ctrl_c()=>{}, _ = terminate.recv()=>{} } + } + #[cfg(not(unix))] let _ = tokio::signal::ctrl_c().await; } async fn wait_for_shutdown(mut receiver: tokio::sync::watch::Receiver) { From 0f3050354a8531632827d048184a127003ee161c Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 17:25:27 +0200 Subject: [PATCH 4/6] fix(auth): close second-review operational gaps --- .github/workflows/ci.yml | 65 +++++ .gitignore | 2 + Cargo.lock | 231 +++++++----------- Cargo.toml | 8 +- apps/auth-service/Cargo.toml | 1 + apps/auth-service/src/hardening.rs | 175 ++++++++++--- apps/auth-service/src/lib.rs | 81 ++++-- apps/auth-service/src/main.rs | 84 +++++-- apps/auth-service/tests/http_flow.rs | 154 ++++++++++++ apps/auth-web/package.json | 4 +- apps/auth-web/playwright.config.ts | 20 ++ apps/auth-web/src/hooks.server.ts | 1 - apps/auth-web/svelte.config.js | 23 +- apps/auth-web/tests/auth-flow.spec.ts | 139 +++++++++++ apps/auth-web/vite.config.ts | 7 +- crates/database/src/connection.rs | 28 +++ crates/database/tests/identity.rs | 196 ++++++++++++++- crates/service-auth/Cargo.toml | 4 +- crates/service-auth/build.rs | 6 +- .../0001-auth-edge-and-service-identity.md | 54 ++++ docs/operations/auth-key-rotation.md | 27 +- docs/operations/auth-release.md | 22 +- docs/security/auth-data-retention.md | 15 ++ infra/traefik/auth-dynamic.yml | 39 +++ infra/traefik/auth-static.yml | 33 +++ justfile | 8 + package.json | 3 +- pnpm-lock.yaml | 38 +++ 28 files changed, 1230 insertions(+), 238 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 apps/auth-service/tests/http_flow.rs create mode 100644 apps/auth-web/playwright.config.ts create mode 100644 apps/auth-web/tests/auth-flow.spec.ts create mode 100644 docs/decisions/0001-auth-edge-and-service-identity.md create mode 100644 infra/traefik/auth-dynamic.yml create mode 100644 infra/traefik/auth-static.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..48ab7d29e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + verify: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: piquel_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d piquel_test" + --health-interval 5s + --health-timeout 5s + --health-retries 12 + env: + TEST_DATABASE_URL: postgres://postgres:postgres@127.0.0.1:5432/piquel_test + steps: + - uses: actions/checkout@v6 + - uses: dtolnay/rust-toolchain@stable + with: + toolchain: '1.97' + components: rustfmt, clippy + - uses: pnpm/action-setup@v6 + with: + version: 11.9.0 + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm --filter @piquel/auth-web exec playwright install --with-deps chromium + - run: cargo fmt --all --check + - run: cargo clippy --workspace --all-targets --all-features -- -D warnings + - run: cargo test --workspace + - run: cargo test -p piquel-repository --test identity -- --ignored --test-threads=1 + - run: cargo test -p auth-service --test http_flow -- --ignored --test-threads=1 + - run: pnpm check:web + - run: pnpm test:web + - run: pnpm test:browser + - uses: EmbarkStudios/cargo-deny-action@v2 + with: + command: check advisories + - run: pnpm audit --audit-level=high + - name: Validate Traefik auth topology + run: | + docker run -d --name auth-traefik-config \ + -v "$PWD/infra/traefik:/etc/traefik:ro" \ + traefik:v3.6 --configFile=/etc/traefik/auth-static.yml + trap 'docker logs auth-traefik-config; docker rm -f auth-traefik-config' EXIT + sleep 3 + test "$(docker inspect -f '{{.State.Running}}' auth-traefik-config)" = true + test "$(docker inspect -f '{{.State.ExitCode}}' auth-traefik-config)" = 0 diff --git a/.gitignore b/.gitignore index 6e8f31f38..9b69c1d9b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ target node_modules .svelte-kit apps/auth-web/build +apps/auth-web/playwright-report +apps/auth-web/test-results # These are backup files generated by rustfmt **/*.rs.bk diff --git a/Cargo.lock b/Cargo.lock index 5c270509a..9c934cfda 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -125,10 +125,11 @@ version = "0.1.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "chrono", "hmac", + "ipnet", "jsonwebtoken", "openssl", "p256", @@ -147,7 +148,7 @@ dependencies = [ "tokio", "tokio-stream", "tonic", - "tower 0.5.3", + "tower", "tower-http", "tracing", "unicode-normalization", @@ -162,40 +163,13 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" -[[package]] -name = "axum" -version = "0.7.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" -dependencies = [ - "async-trait", - "axum-core 0.4.5", - "bytes", - "futures-util", - "http", - "http-body", - "http-body-util", - "itoa", - "matchit 0.7.3", - "memchr", - "mime", - "percent-encoding", - "pin-project-lite", - "rustversion", - "serde", - "sync_wrapper", - "tower 0.5.3", - "tower-layer", - "tower-service", -] - [[package]] name = "axum" version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ - "axum-core 0.5.6", + "axum-core", "bytes", "form_urlencoded", "futures-util", @@ -205,7 +179,7 @@ dependencies = [ "hyper", "hyper-util", "itoa", - "matchit 0.8.4", + "matchit", "memchr", "mime", "percent-encoding", @@ -216,32 +190,12 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tower 0.5.3", + "tower", "tower-layer", "tower-service", "tracing", ] -[[package]] -name = "axum-core" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" -dependencies = [ - "async-trait", - "bytes", - "futures-util", - "http", - "http-body", - "http-body-util", - "mime", - "pin-project-lite", - "rustversion", - "sync_wrapper", - "tower-layer", - "tower-service", -] - [[package]] name = "axum-core" version = "0.5.6" @@ -874,7 +828,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.14.0", + "indexmap", "slab", "tokio", "tokio-util", @@ -892,12 +846,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - [[package]] name = "hashbrown" version = "0.15.5" @@ -1076,7 +1024,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.5", + "socket2", "tokio", "tower-service", "tracing", @@ -1209,16 +1157,6 @@ dependencies = [ "icu_properties", ] -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", -] - [[package]] name = "indexmap" version = "2.14.0" @@ -1361,12 +1299,6 @@ dependencies = [ "regex-automata", ] -[[package]] -name = "matchit" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" - [[package]] name = "matchit" version = "0.8.4" @@ -1645,12 +1577,13 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "petgraph" -version = "0.7.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" dependencies = [ "fixedbitset", - "indexmap 2.14.0", + "hashbrown 0.15.5", + "indexmap", ] [[package]] @@ -1770,13 +1703,13 @@ dependencies = [ "p256", "piquel-auth-protocol", "prost", - "prost-build", "protoc-bin-vendored", "serde", "serde_json", "thiserror 2.0.18", "tonic", - "tonic-build", + "tonic-prost", + "tonic-prost-build", ] [[package]] @@ -1874,9 +1807,9 @@ dependencies = [ [[package]] name = "prost" -version = "0.13.5" +version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" dependencies = [ "bytes", "prost-derive", @@ -1884,19 +1817,20 @@ dependencies = [ [[package]] name = "prost-build" -version = "0.13.5" +version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf" +checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042" dependencies = [ "heck", "itertools", "log", "multimap", - "once_cell", "petgraph", "prettyplease", "prost", "prost-types", + "pulldown-cmark", + "pulldown-cmark-to-cmark", "regex", "syn", "tempfile", @@ -1904,9 +1838,9 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.13.5" +version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", "itertools", @@ -1917,9 +1851,9 @@ dependencies = [ [[package]] name = "prost-types" -version = "0.13.5" +version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16" +checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a" dependencies = [ "prost", ] @@ -1988,6 +1922,26 @@ version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" +[[package]] +name = "pulldown-cmark" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +dependencies = [ + "bitflags 2.13.0", + "memchr", + "unicase", +] + +[[package]] +name = "pulldown-cmark-to-cmark" +version = "22.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50793def1b900256624a709439404384204a5dc3a6ec580281bfaac35e882e90" +dependencies = [ + "pulldown-cmark", +] + [[package]] name = "quinn" version = "0.11.11" @@ -2001,7 +1955,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2 0.6.5", + "socket2", "thiserror 2.0.18", "tokio", "tracing", @@ -2039,7 +1993,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.6.5", + "socket2", "tracing", "windows-sys 0.61.2", ] @@ -2225,7 +2179,7 @@ dependencies = [ "sync_wrapper", "tokio", "tokio-rustls", - "tower 0.5.3", + "tower", "tower-http", "tower-service", "url", @@ -2322,15 +2276,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "rustls-pemfile" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "rustls-pki-types" version = "1.15.0" @@ -2554,16 +2499,6 @@ dependencies = [ "serde", ] -[[package]] -name = "socket2" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - [[package]] name = "socket2" version = "0.6.5" @@ -2625,7 +2560,7 @@ dependencies = [ "futures-util", "hashbrown 0.15.5", "hashlink", - "indexmap 2.14.0", + "indexmap", "log", "memchr", "once_cell", @@ -2973,7 +2908,7 @@ dependencies = [ "mio", "pin-project-lite", "signal-hook-registry", - "socket2 0.6.5", + "socket2", "tokio-macros", "windows-sys 0.61.2", ] @@ -3026,13 +2961,12 @@ dependencies = [ [[package]] name = "tonic" -version = "0.12.3" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877c5b330756d856ffcc4553ab34a5684481ade925ecc54bcd1bf02b1d0d4d52" +checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" dependencies = [ - "async-stream", "async-trait", - "axum 0.7.9", + "axum", "base64 0.22.1", "bytes", "h2", @@ -3044,13 +2978,12 @@ dependencies = [ "hyper-util", "percent-encoding", "pin-project", - "prost", - "rustls-pemfile", - "socket2 0.5.10", + "socket2", + "sync_wrapper", "tokio", "tokio-rustls", "tokio-stream", - "tower 0.4.13", + "tower", "tower-layer", "tower-service", "tracing", @@ -3058,36 +2991,41 @@ dependencies = [ [[package]] name = "tonic-build" -version = "0.12.3" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9557ce109ea773b399c9b9e5dca39294110b74f1f342cb347a80d1fce8c26a11" +checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" dependencies = [ "prettyplease", "proc-macro2", - "prost-build", - "prost-types", "quote", "syn", ] [[package]] -name = "tower" -version = "0.4.13" +name = "tonic-prost" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" dependencies = [ - "futures-core", - "futures-util", - "indexmap 1.9.3", - "pin-project", - "pin-project-lite", - "rand 0.8.7", - "slab", - "tokio", - "tokio-util", - "tower-layer", - "tower-service", - "tracing", + "bytes", + "prost", + "tonic", +] + +[[package]] +name = "tonic-prost-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27" +dependencies = [ + "prettyplease", + "proc-macro2", + "prost-build", + "prost-types", + "quote", + "syn", + "tempfile", + "tonic-build", ] [[package]] @@ -3098,9 +3036,12 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", + "indexmap", "pin-project-lite", + "slab", "sync_wrapper", "tokio", + "tokio-util", "tower-layer", "tower-service", "tracing", @@ -3120,7 +3061,7 @@ dependencies = [ "http-body-util", "pin-project-lite", "tokio", - "tower 0.5.3", + "tower", "tower-layer", "tower-service", "tracing", @@ -3213,6 +3154,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + [[package]] name = "unicode-bidi" version = "0.3.18" diff --git a/Cargo.toml b/Cargo.toml index 7fbf2bec9..130d5e692 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,11 +35,12 @@ base64 = "0.22" chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } http = "1.3" hmac = "0.12" +ipnet = "2.11" http-body-util = "0.1" jsonwebtoken = "9.3" openssl = { version = "0.10", features = ["vendored"] } p256 = { version = "0.13", features = ["ecdsa", "pem", "pkcs8"] } -prost = "0.13" +prost = "0.14" rand = "0.8" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } serde = { version = "1.0", features = ["derive"] } @@ -47,8 +48,9 @@ serde_json = "1.0" sha2 = "0.10" sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "chrono", "uuid", "json", "migrate", "macros"] } thiserror = "2.0" -tonic = { version = "0.12", features = ["tls"] } -tonic-build = "0.12" +tonic = { version = "0.14", features = ["tls-ring"] } +tonic-prost = "0.14" +tonic-prost-build = "0.14" tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time", "sync"] } tokio-stream = { version = "0.1", features = ["net"] } tower = { version = "0.5", features = ["util"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index c81ac9abd..41bbc0360 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -13,6 +13,7 @@ axum.workspace = true base64.workspace = true chrono.workspace = true hmac.workspace = true +ipnet.workspace = true jsonwebtoken.workspace = true openssl.workspace = true p256.workspace = true diff --git a/apps/auth-service/src/hardening.rs b/apps/auth-service/src/hardening.rs index bfd2aaacc..f42d6cb75 100644 --- a/apps/auth-service/src/hardening.rs +++ b/apps/auth-service/src/hardening.rs @@ -1,4 +1,4 @@ -//! Bounded public HTTP controls with sanitized, low-cardinality telemetry. +//! Bounded public HTTP controls with an explicit trusted-proxy boundary. use axum::{ Router, @@ -7,8 +7,9 @@ use axum::{ middleware::{self, Next}, response::{IntoResponse, Response}, }; +use ipnet::IpNet; use std::{ - collections::HashMap, + collections::{HashMap, VecDeque}, net::{IpAddr, SocketAddr}, sync::Arc, time::{Duration, Instant}, @@ -19,14 +20,35 @@ use tower_http::{ timeout::TimeoutLayer, }; -#[derive(Clone, Default)] -struct Limiter(Arc>>); +const MAX_WINDOWS: usize = 10_000; +const EVICTIONS_PER_REQUEST: usize = 64; + +#[derive(Clone)] +pub(crate) enum IngressPolicy { + Direct, + TrustedProxies(Arc<[IpNet]>), +} + +#[derive(Clone)] +struct Limiter { + ingress: IngressPolicy, + state: Arc>, +} +#[derive(Default)] +struct LimiterState { + windows: HashMap<(IpAddr, &'static str), Window>, + order: VecDeque<(Instant, (IpAddr, &'static str))>, +} struct Window { started: Instant, count: u32, } -pub(super) fn apply(router: Router) -> Router { - let limiter = Limiter::default(); + +pub(super) fn apply(router: Router, ingress: IngressPolicy) -> Router { + let limiter = Limiter { + ingress, + state: Arc::default(), + }; router .layer(SetResponseHeaderLayer::if_not_present( header::X_CONTENT_TYPE_OPTIONS, @@ -48,38 +70,43 @@ pub(super) fn apply(router: Router) -> Router { .layer(RequestBodyLimitLayer::new(64 * 1024)) .layer(middleware::from_fn_with_state(limiter, enforce)) } + async fn enforce(State(limiter): State, request: Request, next: Next) -> Response { let (class, limit) = classify(request.uri().path()); - let address = match request - .extensions() - .get::>() - .map(|value| value.0.ip()) - { - Some(address) => address, - None if class == "public" => IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), - None => { - return ( - StatusCode::SERVICE_UNAVAILABLE, - "request source unavailable", - ) - .into_response(); - } + let Some(address) = client_address(&request, &limiter.ingress) else { + tracing::warn!( + endpoint_class = class, + outcome = "untrusted_proxy", + "request rejected" + ); + return (StatusCode::BAD_REQUEST, "invalid forwarding boundary").into_response(); }; let now = Instant::now(); - let mut windows = limiter.0.lock().await; - if windows.len() > 10_000 { - windows.retain(|_, window| now.duration_since(window.started) < Duration::from_mins(1)); + let key = (address, class); + let mut state = limiter.state.lock().await; + evict_expired(&mut state, now); + if !state.windows.contains_key(&key) && state.windows.len() >= MAX_WINDOWS { + return ( + StatusCode::SERVICE_UNAVAILABLE, + "rate limiter capacity reached", + ) + .into_response(); } - let window = windows.entry((address, class)).or_insert(Window { - started: now, - count: 0, - }); - if now.duration_since(window.started) >= Duration::from_mins(1) { - *window = Window { - started: now, - count: 0, - }; + let reset = state + .windows + .get(&key) + .is_none_or(|window| now.duration_since(window.started) >= Duration::from_mins(1)); + if reset { + state.windows.insert( + key, + Window { + started: now, + count: 0, + }, + ); + state.order.push_back((now, key)); } + let window = state.windows.get_mut(&key).expect("window was inserted"); if window.count >= limit { tracing::warn!( endpoint_class = class, @@ -89,7 +116,7 @@ async fn enforce(State(limiter): State, request: Request, next: Next) - return (StatusCode::TOO_MANY_REQUESTS, "too many requests").into_response(); } window.count += 1; - drop(windows); + drop(state); let response = next.run(request).await; tracing::info!( endpoint_class = class, @@ -98,6 +125,47 @@ async fn enforce(State(limiter): State, request: Request, next: Next) - ); response } + +fn evict_expired(state: &mut LimiterState, now: Instant) { + for _ in 0..EVICTIONS_PER_REQUEST { + let Some((started, key)) = state.order.front().copied() else { + break; + }; + if now.duration_since(started) < Duration::from_mins(1) { + break; + } + state.order.pop_front(); + if state + .windows + .get(&key) + .is_some_and(|window| window.started == started) + { + state.windows.remove(&key); + } + } +} + +fn client_address(request: &Request, ingress: &IngressPolicy) -> Option { + let peer = request + .extensions() + .get::>()? + .0 + .ip(); + match ingress { + IngressPolicy::Direct => Some(peer), + IngressPolicy::TrustedProxies(proxies) => { + if !proxies.iter().any(|network| network.contains(&peer)) { + return None; + } + let forwarded = request.headers().get("x-forwarded-for")?.to_str().ok()?; + if forwarded.len() > 512 { + return None; + } + forwarded.split(',').next()?.trim().parse().ok() + } + } +} + fn classify(path: &str) -> (&'static str, u32) { if path.starts_with("/webauthn/") { ("webauthn", 30) @@ -105,7 +173,7 @@ fn classify(path: &str) -> (&'static str, u32) { ("federation", 30) } else if path == "/oauth/token" || path == "/oauth/revoke" { ("token", 60) - } else if path == "/oauth/authorize" { + } else if path.starts_with("/oauth/authorize") { ("authorization", 60) } else if path.starts_with("/account/") { ("account", 60) @@ -113,6 +181,7 @@ fn classify(path: &str) -> (&'static str, u32) { ("public", 300) } } + #[cfg(test)] mod tests { use super::*; @@ -122,4 +191,42 @@ mod tests { assert_eq!(classify("/login/google/callback"), ("federation", 30)); assert_eq!(classify("/webauthn/authenticate/start"), ("webauthn", 30)); } + + #[test] + fn eviction_work_is_bounded() { + let now = Instant::now(); + let mut state = LimiterState::default(); + for offset in 0..100 { + let key = (IpAddr::from([10, 0, 0, offset]), "public"); + let started = now + .checked_sub(Duration::from_mins(2)) + .expect("test instant supports two-minute subtraction"); + state.windows.insert(key, Window { started, count: 1 }); + state.order.push_back((started, key)); + } + evict_expired(&mut state, now); + assert_eq!(state.windows.len(), 100 - EVICTIONS_PER_REQUEST); + } + + #[test] + fn forwarded_address_is_accepted_only_from_traefik_network() { + let mut request = Request::builder() + .header("x-forwarded-for", "203.0.113.7, 172.18.0.2") + .body(axum::body::Body::empty()) + .expect("request"); + request.extensions_mut().insert(ConnectInfo( + "172.18.0.2:443".parse::().expect("peer"), + )); + let trusted = IngressPolicy::TrustedProxies( + vec!["172.18.0.0/16".parse::().expect("network")].into(), + ); + assert_eq!( + client_address(&request, &trusted), + Some("203.0.113.7".parse().expect("client IP")) + ); + let untrusted = IngressPolicy::TrustedProxies( + vec!["10.0.0.0/8".parse::().expect("network")].into(), + ); + assert_eq!(client_address(&request, &untrusted), None); + } } diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index d711ec57c..f863fd78b 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -3,9 +3,10 @@ use async_trait::async_trait; use axum::{Router, extract::State, http::StatusCode, response::IntoResponse, routing::get}; +use ipnet::IpNet; use piquel_configuration::{ConfigurationError, PublicUrl, SecretReference, socket_addr}; use piquel_repository::{Database, DatabaseConfig}; -use std::{env, net::SocketAddr, sync::Arc, time::Duration}; +use std::{env, net::SocketAddr, str::FromStr, sync::Arc, time::Duration}; #[allow(dead_code)] mod account; @@ -37,6 +38,8 @@ pub struct AuthConfig { pub public_base_url: PublicUrl, /// Public HTTP listener address. pub public_listener: SocketAddr, + /// Internal-only HTTP health listener, never routed by Traefik. + pub health_listener: SocketAddr, /// Reserved private RPC listener address; no RPC is exposed yet. pub internal_listener: SocketAddr, /// Database connection settings. @@ -59,6 +62,8 @@ pub struct AuthConfig { pub rpc_tls_private_key: SecretReference, /// Client CA used to require private-RPC client certificates. pub rpc_client_ca: SecretReference, + /// Docker networks from which Traefik forwarding headers are accepted. + pub trusted_proxy_cidrs: Arc<[IpNet]>, } impl AuthConfig { /// Loads the minimum service configuration from the environment. @@ -83,12 +88,35 @@ impl AuthConfig { .map_err(|_| ConfigurationError::Invalid { name: "AUTH_DATABASE_URL", })?; + let trusted_proxy_cidrs: Arc<[IpNet]> = if development { + Arc::default() + } else { + let values = required("AUTH_TRUSTED_PROXY_CIDRS")?; + let parsed: Vec<_> = values + .split(',') + .map(str::trim) + .map(IpNet::from_str) + .collect::>() + .map_err(|_| ConfigurationError::Invalid { + name: "AUTH_TRUSTED_PROXY_CIDRS", + })?; + if parsed.is_empty() { + return Err(ConfigurationError::Invalid { + name: "AUTH_TRUSTED_PROXY_CIDRS", + }); + } + parsed.into() + }; Ok(Self { public_base_url, public_listener: socket_addr( "AUTH_PUBLIC_LISTENER", &required("AUTH_PUBLIC_LISTENER")?, )?, + health_listener: socket_addr( + "AUTH_HEALTH_LISTENER", + &required("AUTH_HEALTH_LISTENER")?, + )?, internal_listener: socket_addr( "AUTH_INTERNAL_LISTENER", &required("AUTH_INTERNAL_LISTENER")?, @@ -109,6 +137,7 @@ impl AuthConfig { rpc_tls_certificate: SecretReference::parse(&required("AUTH_RPC_TLS_CERTIFICATE")?)?, rpc_tls_private_key: SecretReference::parse(&required("AUTH_RPC_TLS_PRIVATE_KEY")?)?, rpc_client_ca: SecretReference::parse(&required("AUTH_RPC_CLIENT_CA")?)?, + trusted_proxy_cidrs, }) } } @@ -124,6 +153,7 @@ pub trait Readiness: Send + Sync { pub struct ProductionReadiness { database: Database, secret_providers: Vec, + secret_check: Arc, } impl ProductionReadiness { /// Builds the production readiness dependency set. @@ -132,6 +162,7 @@ impl ProductionReadiness { Self { database, secret_providers, + secret_check: Arc::new(tokio::sync::Semaphore::new(1)), } } } @@ -140,10 +171,23 @@ impl Readiness for ProductionReadiness { async fn check(&self) -> Result<(), ()> { self.database.health_check().await.map_err(|_| ())?; for provider in &self.secret_providers { - tokio::time::timeout(Duration::from_secs(2), async { - provider.resolve().map(|_| ()).map_err(|_| ()) - }) + let provider = provider.clone(); + let permit = tokio::time::timeout( + Duration::from_secs(2), + self.secret_check.clone().acquire_owned(), + ) .await + .map_err(|_| ())? + .map_err(|_| ())?; + tokio::time::timeout( + Duration::from_secs(2), + tokio::task::spawn_blocking(move || { + let _permit = permit; + provider.resolve().map(|_| ()).map_err(|_| ()) + }), + ) + .await + .map_err(|_| ())? .map_err(|_| ())??; } Ok(()) @@ -155,25 +199,30 @@ struct AppState { readiness: Arc, } -/// Builds the public health-only router. Liveness has no dependencies; readiness fails closed. +/// Builds the public protocol/API router behind the trusted ingress boundary. pub fn router( - readiness: Arc, passkeys: Option, oidc: Option, federation: Option, + trusted_proxy_cidrs: Option>, ) -> Router { - let health = Router::new() - .route("/health/live", get(|| async { StatusCode::NO_CONTENT })) - .route("/health/ready", get(ready)) - .with_state(AppState { readiness }); - let router = passkeys.map_or(health.clone(), |passkeys| { - health.merge(passkey::routes(passkeys)) - }); + let router = passkeys.map_or_else(Router::new, passkey::routes); let router = oidc.map_or(router.clone(), |oidc| router.merge(oidc::routes(oidc))); let router = federation.map_or(router.clone(), |federation| { router.merge(federation::routes(federation)) }); - hardening::apply(router) + let ingress = trusted_proxy_cidrs.map_or(hardening::IngressPolicy::Direct, |cidrs| { + hardening::IngressPolicy::TrustedProxies(cidrs) + }); + hardening::apply(router, ingress) +} + +/// Builds the internal, unthrottled health router. +pub fn health_router(readiness: Arc) -> Router { + Router::new() + .route("/health/live", get(|| async { StatusCode::NO_CONTENT })) + .route("/health/ready", get(ready)) + .with_state(AppState { readiness }) } async fn ready(State(state): State) -> impl IntoResponse { @@ -198,7 +247,7 @@ mod tests { #[tokio::test] async fn liveness_has_no_dependencies_and_readiness_fails_closed() { - let app = router(Arc::new(FixedReadiness(false)), None, None, None); + let app = health_router(Arc::new(FixedReadiness(false))); let live = app .clone() .oneshot( @@ -222,7 +271,7 @@ mod tests { #[tokio::test] async fn readiness_succeeds_with_test_substitutes() { - let response = router(Arc::new(FixedReadiness(true)), None, None, None) + let response = health_router(Arc::new(FixedReadiness(true))) .oneshot( axum::http::Request::get("/health/ready") .body(axum::body::Body::empty()) diff --git a/apps/auth-service/src/main.rs b/apps/auth-service/src/main.rs index 8134576a8..737104859 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -2,8 +2,9 @@ use auth_service::{ AuthConfig, Es256KeyProvider, FederationApplication, OidcApplication, PasskeyApplication, - ProductionReadiness, ServiceRpcApplication, router, + ProductionReadiness, ServiceRpcApplication, health_router, router, }; +use piquel_configuration::{SecretBytes, SecretReference}; use piquel_repository::Database; use std::{net::SocketAddr, sync::Arc, time::Duration}; @@ -22,7 +23,7 @@ async fn main() -> anyhow::Result<()> { ]; let listener_address: SocketAddr = config.public_listener; let database = Database::connect(config.database).await?; - let key_secret = config.key_provider.resolve()?; + let key_secret = resolve_secret(config.key_provider.clone()).await?; let keys = if config.development_mode { Arc::new(Es256KeyProvider::generate_for_development( config.signing_key_id.clone(), @@ -82,25 +83,35 @@ async fn main() -> anyhow::Result<()> { .to_owned(), keys, ); - let rpc_certificate = config.rpc_tls_certificate.resolve()?; - let rpc_private_key = config.rpc_tls_private_key.resolve()?; - let rpc_client_ca = config.rpc_client_ca.resolve()?; + let rpc_certificate = resolve_secret(config.rpc_tls_certificate.clone()).await?; + let rpc_private_key = resolve_secret(config.rpc_tls_private_key.clone()).await?; + let rpc_client_ca = resolve_secret(config.rpc_client_ca.clone()).await?; let listener = tokio::net::TcpListener::bind(listener_address).await?; + let health_listener = tokio::net::TcpListener::bind(config.health_listener).await?; tracing::info!(%listener_address, "auth service listening"); let (shutdown_sender, shutdown_receiver) = tokio::sync::watch::channel(false); tokio::spawn(async move { shutdown_signal().await; let _ = shutdown_sender.send(true); }); + tokio::spawn(maintenance_loop( + database.clone(), + shutdown_receiver.clone(), + )); + let readiness = Arc::new(ProductionReadiness::new( + database.clone(), + readiness_secrets, + )); + let ingress = (!config.development_mode).then_some(config.trusted_proxy_cidrs.clone()); let public = axum::serve( listener, - router( - Arc::new(ProductionReadiness::new(database, readiness_secrets)), - Some(passkeys), - Some(oidc), - Some(federation), - ) - .into_make_service_with_connect_info::(), + router(Some(passkeys), Some(oidc), Some(federation), ingress) + .into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(wait_for_shutdown(shutdown_receiver.clone())); + let health = axum::serve( + health_listener, + health_router(readiness).into_make_service(), ) .with_graceful_shutdown(wait_for_shutdown(shutdown_receiver.clone())); let tls = tonic::transport::ServerTlsConfig::new() @@ -125,14 +136,38 @@ async fn main() -> anyhow::Result<()> { .add_service(rpc.auth_server().max_decoding_message_size(1024 * 1024)) .serve_with_shutdown( config.internal_listener, - wait_for_shutdown(shutdown_receiver), + wait_for_shutdown(shutdown_receiver.clone()), ); - tokio::try_join!(async { public.await.map_err(anyhow::Error::from) }, async { - private.await.map_err(anyhow::Error::from) - })?; + let servers = async { + tokio::try_join!( + async { public.await.map_err(anyhow::Error::from) }, + async { health.await.map_err(anyhow::Error::from) }, + async { private.await.map_err(anyhow::Error::from) } + ) + }; + tokio::pin!(servers); + tokio::select! { + result = &mut servers => { result?; } + () = wait_for_shutdown(shutdown_receiver) => { + tokio::time::timeout(Duration::from_secs(15), &mut servers) + .await + .map_err(|_| anyhow::anyhow!("listener drain exceeded 15 seconds"))??; + } + } Ok(()) } +async fn resolve_secret(reference: SecretReference) -> anyhow::Result { + tokio::time::timeout( + Duration::from_secs(2), + tokio::task::spawn_blocking(move || reference.resolve()), + ) + .await + .map_err(|_| anyhow::anyhow!("secret provider deadline exceeded"))? + .map_err(|_| anyhow::anyhow!("secret provider task failed"))? + .map_err(anyhow::Error::from) +} + async fn shutdown_signal() { #[cfg(unix)] { @@ -151,3 +186,20 @@ async fn wait_for_shutdown(mut receiver: tokio::sync::watch::Receiver) { } } } + +async fn maintenance_loop(database: Database, mut shutdown: tokio::sync::watch::Receiver) { + let mut interval = tokio::time::interval(Duration::from_mins(15)); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tokio::select! { + _ = interval.tick() => if let Ok(deleted) = database.purge_expired_auth_state(500).await { + tracing::info!(deleted, "expired authentication state purged"); + } else { + tracing::warn!("authentication state purge failed"); + }, + changed = shutdown.changed() => { + if changed.is_err() || *shutdown.borrow() { break; } + } + } + } +} diff --git a/apps/auth-service/tests/http_flow.rs b/apps/auth-service/tests/http_flow.rs new file mode 100644 index 000000000..c71771de1 --- /dev/null +++ b/apps/auth-service/tests/http_flow.rs @@ -0,0 +1,154 @@ +#![allow(missing_docs)] + +use auth_service::{ + Es256KeyProvider, FederationApplication, OidcApplication, ProviderConfiguration, router, +}; +use axum::{ + body::Body, + extract::ConnectInfo, + http::{Request, StatusCode, header}, +}; +use piquel_auth_protocol::TokenId; +use piquel_configuration::SecretReference; +use piquel_repository::{BootstrapOidcClient, Database, DatabaseConfig}; +use serde_json::Value; +use std::{env, net::SocketAddr, sync::Arc, time::Duration}; +use tower::ServiceExt; +use url::Url; + +async fn database() -> Database { + let url = env::var("TEST_DATABASE_URL") + .expect("TEST_DATABASE_URL must name an isolated PostgreSQL database"); + Database::connect( + DatabaseConfig::new_development(url, 5, Duration::from_secs(5)) + .expect("test database configuration"), + ) + .await + .expect("connect test database") +} + +fn request(uri: &str) -> Request { + let mut request = Request::get(uri).body(Body::empty()).expect("request"); + request.extensions_mut().insert(ConnectInfo( + "127.0.0.1:4242".parse::().expect("peer"), + )); + request +} + +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL after migrations"] +#[allow(clippy::too_many_lines)] +async fn public_protocol_routes_execute_across_http_and_postgres() { + let database = database().await; + let client_id = format!("browser-test-{}", TokenId::new()); + database + .oidc() + .bootstrap_client(&BootstrapOidcClient { + id: client_id.clone(), + display_name: "Browser test client".into(), + redirect_uris: vec!["https://client.example/callback".into()], + post_logout_uris: vec!["https://client.example/logout".into()], + allowed_scopes: vec!["openid".into(), "profile".into()], + allowed_audiences: vec!["client-api".into()], + allow_refresh: true, + }) + .await + .expect("bootstrap client"); + + let issuer = Url::parse("http://127.0.0.1:4180").expect("issuer"); + let keys = Arc::new(Es256KeyProvider::generate_for_development("http-flow")); + let oidc = OidcApplication::new_development(database.clone(), &issuer, &[7; 32], keys) + .expect("OIDC application"); + let provider = || ProviderConfiguration { + client_id: "test-provider-client".into(), + client_secret: SecretReference::parse("env://AUTH_TEST_PROVIDER_SECRET") + .expect("provider secret reference"), + }; + let federation = + FederationApplication::new_development(database, &issuer, provider(), provider()) + .expect("federation application"); + let app = router(None, Some(oidc), Some(federation), None); + + let discovery = app + .clone() + .oneshot(request("/.well-known/openid-configuration")) + .await + .expect("discovery response"); + assert_eq!(discovery.status(), StatusCode::OK); + let discovery: Value = serde_json::from_slice( + &axum::body::to_bytes(discovery.into_body(), 64 * 1024) + .await + .expect("discovery body"), + ) + .expect("discovery JSON"); + assert_eq!(discovery["issuer"], issuer.as_str().trim_end_matches('/')); + assert_eq!(discovery["code_challenge_methods_supported"][0], "S256"); + + let query = url::form_urlencoded::Serializer::new(String::new()) + .append_pair("response_type", "code") + .append_pair("client_id", &client_id) + .append_pair("redirect_uri", "https://client.example/callback") + .append_pair("scope", "openid profile") + .append_pair("state", "client-state") + .append_pair("nonce", "client-nonce") + .append_pair( + "code_challenge", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + ) + .append_pair("code_challenge_method", "S256") + .append_pair("audience", "client-api") + .finish(); + let authorization = app + .clone() + .oneshot(request(&format!("/oauth/authorize?{query}"))) + .await + .expect("authorization response"); + assert_eq!(authorization.status(), StatusCode::SEE_OTHER); + let continuation = authorization + .headers() + .get(header::LOCATION) + .and_then(|value| value.to_str().ok()) + .expect("continuation location"); + assert!(continuation.starts_with("http://127.0.0.1:4180/login?transaction=par_v1_")); + + let attacker_query = query.replace( + "https%3A%2F%2Fclient.example%2Fcallback", + "https%3A%2F%2Fattacker.example%2Fcallback", + ); + let invalid_redirect = app + .clone() + .oneshot(request(&format!("/oauth/authorize?{attacker_query}"))) + .await + .expect("invalid redirect response"); + assert_eq!(invalid_redirect.status(), StatusCode::BAD_REQUEST); + assert!(invalid_redirect.headers().get(header::LOCATION).is_none()); + + for provider in ["github", "google"] { + let response = app + .clone() + .oneshot(request(&format!( + "/login/{provider}?return_to=%2Fauthorize%3Ftransaction%3Dcontinuation" + ))) + .await + .expect("provider response"); + assert_eq!(response.status(), StatusCode::SEE_OTHER); + let location = response + .headers() + .get(header::LOCATION) + .and_then(|value| value.to_str().ok()) + .expect("provider location"); + assert!(location.contains("code_challenge_method=S256")); + if provider == "google" { + assert!(location.starts_with("https://accounts.google.com/")); + assert!(location.contains("nonce=")); + } else { + assert!(location.starts_with("https://github.com/")); + } + let cookie = response + .headers() + .get(header::SET_COOKIE) + .and_then(|value| value.to_str().ok()) + .expect("provider cookie"); + assert!(cookie.contains("Secure; HttpOnly; SameSite=Lax")); + } +} diff --git a/apps/auth-web/package.json b/apps/auth-web/package.json index 3b350c8bf..59857965b 100644 --- a/apps/auth-web/package.json +++ b/apps/auth-web/package.json @@ -7,9 +7,11 @@ "dev": "vite dev", "build": "vite build", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", - "test": "vitest run" + "test": "vitest run", + "test:browser": "playwright test" }, "devDependencies": { + "@playwright/test": "^1.55.0", "@sveltejs/adapter-node": "^5.0.0", "@sveltejs/kit": "^2.0.0", "@sveltejs/vite-plugin-svelte": "^6.0.0", diff --git a/apps/auth-web/playwright.config.ts b/apps/auth-web/playwright.config.ts new file mode 100644 index 000000000..a60337a8b --- /dev/null +++ b/apps/auth-web/playwright.config.ts @@ -0,0 +1,20 @@ +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests', + fullyParallel: true, + forbidOnly: Boolean(process.env.CI), + retries: process.env.CI ? 2 : 0, + reporter: process.env.CI ? 'github' : 'list', + use: { + baseURL: 'http://127.0.0.1:4173', + trace: 'on-first-retry' + }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], + webServer: { + command: 'pnpm build && HOST=127.0.0.1 PORT=4173 node build', + url: 'http://127.0.0.1:4173/', + reuseExistingServer: !process.env.CI, + timeout: 120_000 + } +}); diff --git a/apps/auth-web/src/hooks.server.ts b/apps/auth-web/src/hooks.server.ts index 743995add..b412395f6 100644 --- a/apps/auth-web/src/hooks.server.ts +++ b/apps/auth-web/src/hooks.server.ts @@ -2,7 +2,6 @@ import type { Handle } from '@sveltejs/kit'; export const handle: Handle = async ({ event, resolve }) => { const response = await resolve(event); - response.headers.set('Content-Security-Policy', "default-src 'self'; connect-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'; object-src 'none'"); response.headers.set('Referrer-Policy', 'no-referrer'); response.headers.set('X-Content-Type-Options', 'nosniff'); response.headers.set('Permissions-Policy', 'publickey-credentials-get=(self), publickey-credentials-create=(self), camera=(), microphone=(), geolocation=()'); diff --git a/apps/auth-web/svelte.config.js b/apps/auth-web/svelte.config.js index 3417aa54f..f85d402ea 100644 --- a/apps/auth-web/svelte.config.js +++ b/apps/auth-web/svelte.config.js @@ -1,3 +1,24 @@ import adapter from '@sveltejs/adapter-node'; -export default { kit: { adapter: adapter() } }; +/** @type {import('@sveltejs/kit').Config} */ +const config = { + kit: { + adapter: adapter(), + csp: { + mode: 'auto', + directives: { + 'default-src': ['self'], + 'script-src': ['self'], + 'connect-src': ['self'], + 'img-src': ['self', 'data:'], + 'style-src': ['self', 'unsafe-inline'], + 'base-uri': ['none'], + 'frame-ancestors': ['none'], + 'form-action': ['self'], + 'object-src': ['none'] + } + } + } +}; + +export default config; diff --git a/apps/auth-web/tests/auth-flow.spec.ts b/apps/auth-web/tests/auth-flow.spec.ts new file mode 100644 index 000000000..f8384b72a --- /dev/null +++ b/apps/auth-web/tests/auth-flow.spec.ts @@ -0,0 +1,139 @@ +import { expect, test, type Page } from '@playwright/test'; + +const credentialScript = () => { + const bytes = (values: number[]) => new Uint8Array(values).buffer; + Object.defineProperty(window, 'PublicKeyCredential', { + configurable: true, + value: class PublicKeyCredential {} + }); + Object.defineProperty(navigator, 'credentials', { + configurable: true, + value: { + get: async () => ({ + id: 'credential-id', + rawId: bytes([1, 2, 3]), + type: 'public-key', + response: { + authenticatorData: bytes([4, 5]), + clientDataJSON: bytes([6, 7]), + signature: bytes([8, 9]), + userHandle: bytes([10]) + }, + getClientExtensionResults: () => ({}) + }), + create: async () => ({ + id: 'new-credential-id', + rawId: bytes([11, 12]), + type: 'public-key', + response: { + attestationObject: bytes([13, 14]), + clientDataJSON: bytes([15, 16]) + }, + getClientExtensionResults: () => ({}) + }) + } + }); +}; + +async function mockSecurity(page: Page) { + await page.route('**/account/passkeys', (route) => route.fulfill({ + json: [{ id: 'passkey-1', friendly_name: 'Laptop' }] + })); + await page.route('**/account/social-identities', (route) => route.fulfill({ + json: [{ provider: 'github', linked_email: 'person@example.test' }] + })); +} + +test('passkey login resumes an authorization transaction', async ({ page }) => { + await page.addInitScript(credentialScript); + await mockSecurity(page); + let startBody = ''; + let finishBody = ''; + await page.route('**/webauthn/authenticate/start', async (route) => { + startBody = route.request().postData() ?? ''; + await route.fulfill({ json: { + ceremony_id: 'ceremony-1', + public_key: { + challenge: 'AQID', + allowCredentials: [{ type: 'public-key', id: 'BAUG' }] + } + } }); + }); + await page.route('**/webauthn/authenticate/finish', async (route) => { + finishBody = route.request().postData() ?? ''; + await route.fulfill({ status: 204 }); + }); + + await page.goto('/login?transaction=authorization-1'); + await page.getByLabel('Username').fill('piquel_user'); + await page.getByRole('button', { name: 'Sign in with a passkey' }).click(); + + await expect(page).toHaveURL('/authorize?transaction=authorization-1'); + expect(JSON.parse(startBody)).toEqual({ username: 'piquel_user' }); + expect(JSON.parse(finishBody).ceremony_id).toBe('ceremony-1'); +}); + +test('social login preserves the same server-side continuation', async ({ page }) => { + await page.goto('/login?transaction=authorization-2'); + await expect(page.getByRole('link', { name: 'Sign in with GitHub' })).toHaveAttribute( + 'href', + '/login/github?return_to=%2Fauthorize%3Ftransaction%3Dauthorization-2' + ); + await expect(page.getByRole('link', { name: 'Sign in with Google' })).toHaveAttribute( + 'href', + '/login/google?return_to=%2Fauthorize%3Ftransaction%3Dauthorization-2' + ); +}); + +test('authorization renders server-owned grants and posts cancellation', async ({ page }) => { + await page.route('**/oauth/authorize/transaction/authorization-3', (route) => route.fulfill({ + json: { client_name: 'Piquel Photos', scopes: ['openid', 'profile'], audience: 'photos-api' } + })); + let decision = ''; + await page.route('**/oauth/authorize/decision', async (route) => { + decision = route.request().postData() ?? ''; + await route.fulfill({ status: 303, headers: { location: '/login' } }); + }); + + await page.goto('/authorize?transaction=authorization-3'); + await expect(page.getByRole('heading', { name: 'Continue to Piquel Photos' })).toBeVisible(); + await expect(page.getByText('photos-api')).toBeVisible(); + await page.getByRole('button', { name: 'Cancel' }).click(); + + await expect(page).toHaveURL('/login'); + expect(new URLSearchParams(decision).get('transaction')).toBe('authorization-3'); + expect(new URLSearchParams(decision).get('decision')).toBe('deny'); +}); + +test('security page enrolls a passkey and performs CSRF-protected logout', async ({ page }) => { + await page.addInitScript(credentialScript); + await mockSecurity(page); + await page.route('**/account/passkeys/enroll/start', (route) => route.fulfill({ json: { + ceremony_id: 'enrollment-1', + public_key: { + challenge: 'AQID', + user: { id: 'BAUG', name: 'piquel_user', displayName: 'Piquel User' } + } + } })); + let enrollment = ''; + await page.route('**/account/passkeys/enroll/finish', async (route) => { + enrollment = route.request().postData() ?? ''; + await route.fulfill({ status: 204 }); + }); + let logoutCsrf = ''; + await page.route('**/session/logout', async (route) => { + logoutCsrf = route.request().headers()['x-piquel-csrf'] ?? ''; + await route.fulfill({ status: 204 }); + }); + page.on('dialog', (dialog) => dialog.accept('Security key')); + + await page.goto('/security'); + await expect(page.getByText('Sign in with GitHub')).toBeVisible(); + await page.getByRole('button', { name: 'Add a passkey' }).click(); + await expect.poll(() => enrollment).not.toBe(''); + expect(JSON.parse(enrollment).friendly_name).toBe('Security key'); + + await page.getByRole('button', { name: 'Sign out' }).click(); + await expect(page).toHaveURL('/login'); + expect(logoutCsrf).toBe('1'); +}); diff --git a/apps/auth-web/vite.config.ts b/apps/auth-web/vite.config.ts index 63a65fd85..3eff654e3 100644 --- a/apps/auth-web/vite.config.ts +++ b/apps/auth-web/vite.config.ts @@ -1,3 +1,6 @@ import { sveltekit } from '@sveltejs/kit/vite'; -import { defineConfig } from 'vite'; -export default defineConfig({ plugins: [sveltekit()] }); +import { defineConfig } from 'vitest/config'; +export default defineConfig({ + plugins: [sveltekit()], + test: { include: ['src/**/*.test.ts'] } +}); diff --git a/crates/database/src/connection.rs b/crates/database/src/connection.rs index 6156bf4d4..2ea9bd4c8 100644 --- a/crates/database/src/connection.rs +++ b/crates/database/src/connection.rs @@ -127,6 +127,34 @@ impl Database { .await .map_err(|_| DatabaseError::Internal) } + /// Purges a bounded batch of expired ephemeral authentication state. + pub async fn purge_expired_auth_state(&self, batch_size: u32) -> Result { + let limit = i64::from(batch_size.clamp(1, 1_000)); + let mut transaction = self.pool.begin().await.map_err(crate::error::map_error)?; + let mut deleted = 0; + for statement in [ + "DELETE FROM federation_transactions WHERE ctid IN (SELECT ctid FROM federation_transactions WHERE expires_at UserRepository<'_> { UserRepository::from_pool(&self.pool) } diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index 908600905..6124d4707 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -4,9 +4,9 @@ use chrono::{Duration as ChronoDuration, Utc}; use piquel_auth_protocol::{AccountStatus, AuthenticationMethod, SessionId, TokenId, UserId}; use piquel_repository::{ AppendInternalEvent, BootstrapOidcClient, Database, DatabaseConfig, DatabaseError, - InsertCeremony, InsertExternalIdentity, InsertFederationTransaction, InsertPasskey, - InsertRefreshFamily, InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, - RefreshRotationError, UpdateUserProfile, + InsertAuthorizationRequest, InsertCeremony, InsertExternalIdentity, + InsertFederationTransaction, InsertPasskey, InsertRefreshFamily, InsertRefreshToken, + InsertSession, InsertUser, InsertVerifiedEmail, RefreshRotationError, UpdateUserProfile, }; use std::{env, time::Duration}; @@ -192,6 +192,41 @@ async fn identity_transactions_and_concurrency_hold() { .await .expect("refresh family"); setup.commit().await.expect("OIDC setup commit"); + let authorization_id = TokenId::new(); + let authorization_digest = vec![31_u8; 32]; + database + .oidc() + .insert_authorization_request(&InsertAuthorizationRequest { + id: authorization_id, + secret_digest: authorization_digest.clone(), + client_id: "test-client".into(), + redirect_uri: "https://client.example/callback".into(), + client_state: "client-state".into(), + nonce: Some("nonce".into()), + pkce_challenge: "challenge".into(), + scopes: vec!["openid".into()], + audience: "test-api".into(), + force_login: false, + max_age: None, + expires_at: Utc::now() + ChronoDuration::minutes(5), + }) + .await + .expect("authorization request"); + let one = database.clone(); + let two = database.clone(); + let (left, right) = tokio::join!( + async move { + one.oidc() + .consume_authorization_request(authorization_id, &authorization_digest) + .await + }, + async move { + two.oidc() + .consume_authorization_request(authorization_id, &[31_u8; 32]) + .await + } + ); + assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); let rotate = |database: Database, replacement: TokenId, digest: Vec| async move { let mut tx = database.begin().await.expect("rotation transaction"); match tx.tokens().consume_for_rotation(refresh_id, &digest).await { @@ -227,6 +262,46 @@ async fn identity_transactions_and_concurrency_hold() { || matches!(right, Err(RefreshRotationError::Replay { .. })) ); + let last_factor_user = insert_user(&database, "factors").await; + let factor_one = TokenId::new(); + let factor_two = TokenId::new(); + for (id, credential) in [(factor_one, 41_u8), (factor_two, 42_u8)] { + database + .passkeys() + .insert(&InsertPasskey { + id, + credential_id: vec![credential; 32], + user_id: last_factor_user, + credential: serde_json::json!({"fixture":credential}), + friendly_name: "Factor".into(), + }) + .await + .expect("factor"); + } + let remove = |database: Database, id: TokenId| async move { + let mut tx = database.begin().await.expect("factor transaction"); + let removed = tx + .passkeys() + .revoke_if_not_last(id, last_factor_user) + .await + .expect("factor removal"); + tx.commit().await.expect("factor commit"); + removed + }; + let (left, right) = tokio::join!( + remove(database.clone(), factor_one), + remove(database.clone(), factor_two) + ); + assert_eq!(usize::from(left) + usize::from(right), 1); + assert_eq!( + database + .passkeys() + .list_active(last_factor_user, 20) + .await + .expect("remaining factors") + .len(), + 1 + ); let federation_state = vec![11_u8; 32]; let browser = vec![12_u8; 32]; database @@ -259,6 +334,121 @@ async fn identity_transactions_and_concurrency_hold() { ); assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); + let disable_race_user = insert_user(&database, "disable_race").await; + let disable_race_session = SessionId::new(); + let insert_database = database.clone(); + let disable_database = database.clone(); + let (inserted, disabled) = tokio::join!( + async move { + insert_database + .sessions() + .insert(&InsertSession { + id: disable_race_session, + user_id: disable_race_user, + authentication_methods: vec![AuthenticationMethod::Passkey], + authenticated_at: Utc::now(), + expires_at: Utc::now() + ChronoDuration::hours(1), + user_agent_family: None, + }) + .await + }, + async move { + disable_database + .users() + .set_status(disable_race_user, AccountStatus::Disabled) + .await + } + ); + assert!(disabled.expect("disable race status")); + assert!(inserted.is_ok() || matches!(inserted, Err(DatabaseError::NotFound))); + assert!( + database + .sessions() + .find_active_by_id(disable_race_session) + .await + .expect("active session lookup") + .is_none() + ); + + let policy_user = insert_user(&database, "policy").await; + let policy_session = SessionId::new(); + database + .sessions() + .insert(&InsertSession { + id: policy_session, + user_id: policy_user, + authentication_methods: vec![AuthenticationMethod::Passkey], + authenticated_at: Utc::now(), + expires_at: Utc::now() + ChronoDuration::hours(1), + user_agent_family: None, + }) + .await + .expect("policy session"); + database + .oidc() + .bootstrap_client(&BootstrapOidcClient { + id: "policy-client".into(), + display_name: "Policy client".into(), + redirect_uris: vec!["https://policy.example/callback".into()], + post_logout_uris: vec!["https://policy.example/logout".into()], + allowed_scopes: vec!["openid".into()], + allowed_audiences: vec!["policy-api".into()], + allow_refresh: true, + }) + .await + .expect("policy client"); + let policy_family = TokenId::new(); + let policy_token = TokenId::new(); + let policy_digest = vec![51_u8; 32]; + database + .tokens() + .insert_family( + &InsertRefreshFamily { + id: policy_family, + user_id: policy_user, + client_id: "policy-client".into(), + session_id: policy_session, + audience: "policy-api".into(), + scopes: vec!["openid".into()], + }, + &InsertRefreshToken { + id: policy_token, + family_id: policy_family, + secret_digest: policy_digest.clone(), + expires_at: Utc::now() + ChronoDuration::days(1), + }, + ) + .await + .expect("policy family"); + database + .oidc() + .bootstrap_client(&BootstrapOidcClient { + id: "policy-client".into(), + display_name: "Policy client".into(), + redirect_uris: vec!["https://policy.example/callback".into()], + post_logout_uris: vec!["https://policy.example/logout".into()], + allowed_scopes: vec!["openid".into()], + allowed_audiences: vec!["policy-api".into()], + allow_refresh: false, + }) + .await + .expect("reduce policy"); + let mut tx = database.begin().await.expect("policy transaction"); + assert!(matches!( + tx.tokens() + .consume_for_rotation(policy_token, &policy_digest) + .await, + Err(RefreshRotationError::Policy { user_id }) if user_id == policy_user + )); + tx.commit().await.expect("persist policy revocation"); + assert!(matches!( + database + .tokens() + .consume_for_rotation(policy_token, &policy_digest) + .await, + Err(RefreshRotationError::Invalid) + )); + let issuer = "https://github.com"; let subject = format!("subject-{first}"); database diff --git a/crates/service-auth/Cargo.toml b/crates/service-auth/Cargo.toml index f22569f66..6dd43a8d0 100644 --- a/crates/service-auth/Cargo.toml +++ b/crates/service-auth/Cargo.toml @@ -17,11 +17,11 @@ serde.workspace = true serde_json.workspace = true thiserror.workspace = true tonic.workspace = true +tonic-prost.workspace = true [build-dependencies] -prost-build = "0.13" protoc-bin-vendored = "3" -tonic-build.workspace = true +tonic-prost-build.workspace = true [lints] workspace = true diff --git a/crates/service-auth/build.rs b/crates/service-auth/build.rs index 84450c71c..e25ad0cb0 100644 --- a/crates/service-auth/build.rs +++ b/crates/service-auth/build.rs @@ -1,12 +1,12 @@ #![allow(missing_docs)] fn main() { let protoc = protoc_bin_vendored::protoc_bin_path().expect("vendored protoc"); - let mut prost = prost_build::Config::new(); + let mut prost = tonic_prost_build::Config::new(); prost.protoc_executable(protoc); - tonic_build::configure() + tonic_prost_build::configure() .build_server(true) .build_client(true) - .compile_protos_with_config( + .compile_with_config( prost, &["../../proto/piquel/auth/v1/auth.proto"], &["../../proto"], diff --git a/docs/decisions/0001-auth-edge-and-service-identity.md b/docs/decisions/0001-auth-edge-and-service-identity.md new file mode 100644 index 000000000..1740f4128 --- /dev/null +++ b/docs/decisions/0001-auth-edge-and-service-identity.md @@ -0,0 +1,54 @@ +# ADR 0001: Auth edge and service identity + +Status: accepted for the first version + +## Context + +The SvelteKit application and the protocol authority must share +`https://auth.piquel.fr` so WebAuthn, cookies, OAuth redirects, and CSRF checks +have one exact origin. The Rust public listener intentionally serves plaintext +HTTP and therefore needs an enforced TLS and forwarding boundary. Private RPC +also needs a certificate identity that can be compared with the signed client +assertion. + +## Decision + +Traefik terminates public TLS and routes a single origin by path. The checked-in +static and dynamic configurations are `infra/traefik/auth-static.yml` and +`infra/traefik/auth-dynamic.yml`. + +- Protocol and account API paths go to `auth-service:8080`. +- All remaining paths, including `/login`, `/authorize`, `/security`, and + SvelteKit assets, go to `auth-web:3000`. +- Neither backend publishes its application port on the Docker host. Traefik + and the two applications share a dedicated `piquel-auth-edge` network. +- Traefik discards untrusted inbound forwarding headers (`insecure: false`). If + a separately reviewed upstream load balancer is later introduced, only its + exact CIDRs may be added to Traefik's `forwardedHeaders.trustedIPs`. Auth-service + independently accepts `X-Forwarded-For` only when the TCP peer belongs to + `AUTH_TRUSTED_PROXY_CIDRS`, which is the exact Docker edge-network CIDR. +- `AUTH_HEALTH_LISTENER` is reachable only by container health checks and the + orchestrator. It is not a Traefik route and is not rate limited. +- `AUTH_INTERNAL_LISTENER` is reachable only on the private service network and + requires mTLS. A service certificate has exactly one identity URI SAN of the + form `spiffe://piquel.fr/service/`. That service ID must equal the + assertion subject before a service token is issued. + +The public issuer and WebAuthn relying-party origin are both exactly +`https://auth.piquel.fr`. No application trusts `X-Forwarded-Host` or +`X-Forwarded-Proto` to change configured security policy. + +## Route ownership + +Auth-service owns `/.well-known/*`, `/oauth/*`, `/oidc/*`, `/webauthn/*`, +`/account/*`, `/session/*`, `/login/github*`, and `/login/google*`. Auth-web +owns every other public path. The protocol router has higher Traefik priority, +so `/login/github` and `/login/google` cannot fall through to SvelteKit. + +## Consequences + +Changing either route set is an architecture change: update the Traefik +configuration, this ADR, and browser contract tests together. A deployment +must not bypass Traefik to reach the public authority. Horizontal replicas use +per-process rate-limit budgets in this first version; PostgreSQL remains the +authority for all replay and revocation state. diff --git a/docs/operations/auth-key-rotation.md b/docs/operations/auth-key-rotation.md index 5f0e349c0..75d6859b0 100644 --- a/docs/operations/auth-key-rotation.md +++ b/docs/operations/auth-key-rotation.md @@ -1,11 +1,20 @@ -# Auth signing and service-key rotation +# Auth key rotation: explicitly deferred -Create a new asymmetric signing key in the approved key provider with a stable -`kid`. Publish its public JWK while retaining the old public key, begin issuing -with the new key, and retain the old JWK for longer than the maximum token life -(five minutes for access and service tokens). Remove the old JWK only after that -overlap has elapsed and no token class depending on it remains valid. +Routine signing-key and service-public-key rotation is **not implemented in the +first version**. The authority currently loads one signing key and publishes +one JWK. Its opaque authorization-code and refresh-token digests also depend on +that key material. Replacing it immediately removes verification for existing +JWTs and invalidates outstanding opaque credentials. Operators must not treat +the current implementation as an overlap-capable rotation mechanism. -Service public keys follow the same overlap rule: register the new `kid`, permit -both keys during transition, move the service signer, then revoke the old key. -Runtime services cannot self-register or rotate their own keys. +Until the follow-up key-lifecycle plan lands, replacement is an emergency-only +operation with an accepted global reauthentication impact. The operator must +revoke active sessions and refresh families, replace the key and `kid`, deploy +the authority, and verify its single published JWK before reopening traffic. + +The deferred implementation must introduce an independently managed stable +opaque-token digest key and an active-plus-retired signing-key ring. It must +prove new issuance, old-key verification during overlap, removal only after the +last affected token expires, and refresh continuity. Service public-key overlap +and revocation require the same explicit implementation and tests; runtime +services must never self-register keys. diff --git a/docs/operations/auth-release.md b/docs/operations/auth-release.md index cc8d5ff22..581ae3d26 100644 --- a/docs/operations/auth-release.md +++ b/docs/operations/auth-release.md @@ -1,13 +1,27 @@ # Auth release and migration order -1. Run `just check`, `just test`, `pnpm check:web`, and `pnpm test:web`. +1. Run `just ci` with `TEST_DATABASE_URL` pointing to an isolated disposable + PostgreSQL database. This includes the database concurrency suite and browser + tests. 2. Back up PostgreSQL and verify the restore procedure before a schema release. 3. Export `AUTH_DATABASE_URL` only in the migration process environment and run `just migrate` once with the migration role; never pass credentials in argv. -4. Deploy auth-service replicas with readiness checks enabled; replicas never run - migrations at startup. -5. Deploy auth-web only after the public auth endpoints it references are live. +4. Create a dedicated `piquel-auth-edge` Docker network. Attach only Traefik, + auth-service, and auth-web. Do not publish either application port on the + host. +5. Deploy auth-service with `AUTH_PUBLIC_LISTENER=0.0.0.0:8080`, + `AUTH_HEALTH_LISTENER=0.0.0.0:8081`, and + `AUTH_TRUSTED_PROXY_CIDRS=`. Health checks use port + 8081 directly; replicas never run migrations at startup. +6. Deploy auth-web on port 3000, load `infra/traefik/auth-static.yml` and + `infra/traefik/auth-dynamic.yml`, provision the `auth.piquel.fr` certificate, + and verify the route ownership documented in ADR 0001 before accepting + public traffic. +7. Keep the mTLS gRPC listener on a distinct private Docker network. Each client + certificate must have the exact SPIFFE URI SAN documented in ADR 0001. Liveness is process-only. Readiness fails closed when PostgreSQL or a required key provider is unavailable. During a graceful shutdown, remove the replica from intake first and allow only bounded in-flight requests to complete. +Signing and service-key rotation remains explicitly deferred; see +`docs/operations/auth-key-rotation.md` before replacing any production key. diff --git a/docs/security/auth-data-retention.md b/docs/security/auth-data-retention.md index b8350385a..7e48d2036 100644 --- a/docs/security/auth-data-retention.md +++ b/docs/security/auth-data-retention.md @@ -11,3 +11,18 @@ after revocation and trusted verified-email assertions from the explicitly approved GitHub and Google providers. Redis, if introduced, is disposable coordination only and must never be an authority for identity, session, revocation, audit, or event state. + +Auth-service owns a bounded cleanup job. Every 15 minutes it removes at most +500 rows per ephemeral table in a transaction, then returns to serving traffic. +Expired or consumed WebAuthn ceremonies, federation transactions, +authorization continuations, and authorization codes are retained for at most +one additional day. Revoked or expired browser-session secrets and refresh +tokens are retained for at most one additional day. Empty refresh families are +eligible after revocation plus one day or creation plus 31 days; sessions are +removed only after their dependent codes and refresh families are gone. Audit +events and the transactional event log are not deleted by this job. + +The cleanup interval and batch size are availability controls, not compliance +retention promises. Operators must alert on repeated cleanup failure and +database growth; any future deletion of audit or event records needs a separate +approved retention policy. diff --git a/infra/traefik/auth-dynamic.yml b/infra/traefik/auth-dynamic.yml new file mode 100644 index 000000000..8443516b6 --- /dev/null +++ b/infra/traefik/auth-dynamic.yml @@ -0,0 +1,39 @@ +http: + routers: + auth-protocol: + entryPoints: [websecure] + rule: >- + Host(`auth.piquel.fr`) && + (PathPrefix(`/.well-known/`) || PathPrefix(`/oauth/`) || + PathPrefix(`/oidc/`) || PathPrefix(`/webauthn/`) || + PathPrefix(`/account/`) || PathPrefix(`/session/`) || + PathPrefix(`/login/github`) || PathPrefix(`/login/google`)) + priority: 200 + service: auth-service + middlewares: [auth-security-headers] + tls: {} + auth-web: + entryPoints: [websecure] + rule: Host(`auth.piquel.fr`) + priority: 100 + service: auth-web + middlewares: [auth-security-headers] + tls: {} + services: + auth-service: + loadBalancer: + passHostHeader: true + servers: + - url: http://auth-service:8080 + auth-web: + loadBalancer: + passHostHeader: true + servers: + - url: http://auth-web:3000 + middlewares: + auth-security-headers: + headers: + stsSeconds: 31536000 + stsIncludeSubdomains: true + contentTypeNosniff: true + referrerPolicy: no-referrer diff --git a/infra/traefik/auth-static.yml b/infra/traefik/auth-static.yml new file mode 100644 index 000000000..601823e47 --- /dev/null +++ b/infra/traefik/auth-static.yml @@ -0,0 +1,33 @@ +entryPoints: + traefik: + address: :8082 + web: + address: :80 + http: + redirections: + entryPoint: + to: websecure + scheme: https + permanent: true + websecure: + address: :443 + forwardedHeaders: + insecure: false + http: + encodeQuerySemicolons: true + transport: + respondingTimeouts: + readTimeout: 15s + writeTimeout: 15s + idleTimeout: 60s + +providers: + file: + filename: /etc/traefik/auth-dynamic.yml + watch: true + +api: + dashboard: false + +ping: + entryPoint: traefik diff --git a/justfile b/justfile index ff2588777..7e8208c67 100644 --- a/justfile +++ b/justfile @@ -9,6 +9,7 @@ test: test-database: cargo test -p piquel-repository --test identity -- --ignored --test-threads=1 + cargo test -p auth-service --test http_flow -- --ignored --test-threads=1 check-web: pnpm check:web @@ -16,12 +17,19 @@ check-web: test-web: pnpm test:web +test-browser: + pnpm test:browser + ci: cargo fmt --all --check cargo clippy --workspace --all-targets --all-features -- -D warnings cargo test --workspace + cargo test -p piquel-repository --test identity -- --ignored --test-threads=1 pnpm check:web pnpm test:web + pnpm test:browser + cargo deny check advisories + pnpm audit --audit-level=high migrate: cargo run -p piquel-repository --bin migrate diff --git a/package.json b/package.json index ae8e049ef..2a27b5bc7 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "packageManager": "pnpm@11.9.0", "scripts": { "check:web": "pnpm --filter @piquel/auth-web check", - "test:web": "pnpm --filter @piquel/auth-web test" + "test:web": "pnpm --filter @piquel/auth-web test", + "test:browser": "pnpm --filter @piquel/auth-web test:browser" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1742b6915..0d9f896c2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10,6 +10,9 @@ importers: apps/auth-web: devDependencies: + '@playwright/test': + specifier: ^1.55.0 + version: 1.61.1 '@sveltejs/adapter-node': specifier: ^5.0.0 version: 5.5.7(@sveltejs/kit@2.69.2(@sveltejs/vite-plugin-svelte@6.2.4(svelte@5.56.4)(vite@7.3.6))(svelte@5.56.4)(typescript@5.9.3)(vite@7.3.6)) @@ -209,6 +212,11 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@playwright/test@1.61.1': + resolution: {integrity: sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==} + engines: {node: '>=18'} + hasBin: true + '@polka/url@1.0.0-next.29': resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} @@ -596,6 +604,11 @@ packages: picomatch: optional: true + fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -674,6 +687,16 @@ packages: resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} engines: {node: '>=12'} + playwright-core@1.61.1: + resolution: {integrity: sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==} + engines: {node: '>=18'} + hasBin: true + + playwright@1.61.1: + resolution: {integrity: sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==} + engines: {node: '>=18'} + hasBin: true + postcss@8.5.19: resolution: {integrity: sha512-Mz8SaolMd8nB+G13WkORcxQKHZ/NE4xXevtkJHVuG+guo9/wYKlIMTKAqGdEmYOXR2ijPjTYNHssizdaVSUNdQ==} engines: {node: ^10 || ^12 || >=14} @@ -954,6 +977,10 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@playwright/test@1.61.1': + dependencies: + playwright: 1.61.1 + '@polka/url@1.0.0-next.29': {} '@rollup/plugin-commonjs@29.0.3(rollup@4.62.2)': @@ -1276,6 +1303,9 @@ snapshots: optionalDependencies: picomatch: 4.0.5 + fsevents@2.3.2: + optional: true + fsevents@2.3.3: optional: true @@ -1331,6 +1361,14 @@ snapshots: picomatch@4.0.5: {} + playwright-core@1.61.1: {} + + playwright@1.61.1: + dependencies: + playwright-core: 1.61.1 + optionalDependencies: + fsevents: 2.3.2 + postcss@8.5.19: dependencies: nanoid: 3.3.16 From e35a312f51fc7b7b1546c3b7a0c12dede12df8ec Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 17:33:55 +0200 Subject: [PATCH 5/6] test(auth): gate the private RPC composition --- .github/workflows/ci.yml | 1 + justfile | 3 +++ 2 files changed, 4 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48ab7d29e..6031e8c0a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,6 +47,7 @@ jobs: - run: cargo test --workspace - run: cargo test -p piquel-repository --test identity -- --ignored --test-threads=1 - run: cargo test -p auth-service --test http_flow -- --ignored --test-threads=1 + - run: cargo test -p auth-service --test rpc_flow -- --ignored --test-threads=1 - run: pnpm check:web - run: pnpm test:web - run: pnpm test:browser diff --git a/justfile b/justfile index 7e8208c67..cfb1b4b9d 100644 --- a/justfile +++ b/justfile @@ -10,6 +10,7 @@ test: test-database: cargo test -p piquel-repository --test identity -- --ignored --test-threads=1 cargo test -p auth-service --test http_flow -- --ignored --test-threads=1 + cargo test -p auth-service --test rpc_flow -- --ignored --test-threads=1 check-web: pnpm check:web @@ -25,6 +26,8 @@ ci: cargo clippy --workspace --all-targets --all-features -- -D warnings cargo test --workspace cargo test -p piquel-repository --test identity -- --ignored --test-threads=1 + cargo test -p auth-service --test http_flow -- --ignored --test-threads=1 + cargo test -p auth-service --test rpc_flow -- --ignored --test-threads=1 pnpm check:web pnpm test:web pnpm test:browser From 365d160ca9dd0b1a7e4780544b950886520b9ec9 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 17:35:44 +0200 Subject: [PATCH 6/6] test(auth): exercise the Traefik path boundary --- .github/workflows/ci.yml | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6031e8c0a..a836f191c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,12 +55,39 @@ jobs: with: command: check advisories - run: pnpm audit --audit-level=high - - name: Validate Traefik auth topology + - name: Exercise Traefik auth topology run: | - docker run -d --name auth-traefik-config \ + cleanup() { + docker logs auth-traefik-edge || true + docker rm -f auth-traefik-edge auth-service auth-web || true + docker network rm piquel-auth-edge || true + } + trap cleanup EXIT + docker network create piquel-auth-edge + docker run -d --name auth-service --hostname auth-service \ + --network piquel-auth-edge traefik/whoami:v1.11 --port 8080 + docker run -d --name auth-web --hostname auth-web \ + --network piquel-auth-edge traefik/whoami:v1.11 --port 3000 + docker run -d --name auth-traefik-edge --network piquel-auth-edge \ + -p 127.0.0.1:18443:443 \ -v "$PWD/infra/traefik:/etc/traefik:ro" \ traefik:v3.6 --configFile=/etc/traefik/auth-static.yml - trap 'docker logs auth-traefik-config; docker rm -f auth-traefik-config' EXIT sleep 3 - test "$(docker inspect -f '{{.State.Running}}' auth-traefik-config)" = true - test "$(docker inspect -f '{{.State.ExitCode}}' auth-traefik-config)" = 0 + test "$(docker inspect -f '{{.State.Running}}' auth-traefik-edge)" = true + protocol="$(curl --fail --silent --show-error --insecure \ + -H 'Host: auth.piquel.fr' -H 'X-Forwarded-For: 198.51.100.9' \ + https://127.0.0.1:18443/oauth/token)" + printf '%s' "$protocol" | grep --quiet 'Hostname: auth-service' + if printf '%s' "$protocol" | grep --quiet '198.51.100.9'; then exit 1; fi + curl --fail --silent --show-error --insecure -H 'Host: auth.piquel.fr' \ + https://127.0.0.1:18443/.well-known/openid-configuration \ + | grep --quiet 'Hostname: auth-service' + curl --fail --silent --show-error --insecure -H 'Host: auth.piquel.fr' \ + https://127.0.0.1:18443/login/github \ + | grep --quiet 'Hostname: auth-service' + curl --fail --silent --show-error --insecure -H 'Host: auth.piquel.fr' \ + https://127.0.0.1:18443/login \ + | grep --quiet 'Hostname: auth-web' + curl --fail --silent --show-error --insecure -H 'Host: auth.piquel.fr' \ + https://127.0.0.1:18443/_app/test.js \ + | grep --quiet 'Hostname: auth-web'