From 4226640e146fc32957e709a080275c5d38de3164 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:08:43 +0200 Subject: [PATCH 1/4] feat(auth): add downstream validation facade --- Cargo.lock | 17 ++++ Cargo.toml | 2 + crates/auth-middleware/Cargo.toml | 15 ++++ crates/auth-middleware/src/lib.rs | 130 ++++++++++++++++++++++++++++++ crates/auth-sdk/Cargo.toml | 14 ++++ crates/auth-sdk/src/lib.rs | 5 ++ 6 files changed, 183 insertions(+) create mode 100644 crates/auth-middleware/Cargo.toml create mode 100644 crates/auth-middleware/src/lib.rs create mode 100644 crates/auth-sdk/Cargo.toml create mode 100644 crates/auth-sdk/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index a49dda2a1..c6fddea4b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1408,6 +1408,15 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piquel-auth-middleware" +version = "0.1.0" +dependencies = [ + "piquel-auth-protocol", + "thiserror", + "url", +] + [[package]] name = "piquel-auth-protocol" version = "0.1.0" @@ -1417,6 +1426,14 @@ dependencies = [ "uuid", ] +[[package]] +name = "piquel-auth-sdk" +version = "0.1.0" +dependencies = [ + "piquel-auth-middleware", + "piquel-auth-protocol", +] + [[package]] name = "piquel-configuration" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index bcf266ec8..83bdfa7a5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,8 @@ resolver = "3" members = [ "apps/auth-service", "crates/auth-protocol", + "crates/auth-middleware", + "crates/auth-sdk", "crates/configuration", "crates/database", "crates/telemetry", diff --git a/crates/auth-middleware/Cargo.toml b/crates/auth-middleware/Cargo.toml new file mode 100644 index 000000000..eddb01f11 --- /dev/null +++ b/crates/auth-middleware/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "piquel-auth-middleware" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +piquel-auth-protocol = { path = "../auth-protocol" } +thiserror.workspace = true +url.workspace = true + +[lints] +workspace = true diff --git a/crates/auth-middleware/src/lib.rs b/crates/auth-middleware/src/lib.rs new file mode 100644 index 000000000..6541b3eb2 --- /dev/null +++ b/crates/auth-middleware/src/lib.rs @@ -0,0 +1,130 @@ +//! Resource-server validation configuration with no insecure construction path. + +use piquel_auth_protocol::{Audience, UserId}; +use thiserror::Error; +use url::Url; + +/// A verified user identity, never a raw JWT. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AuthenticatedUser { + /// Immutable global account ID. + pub user_id: UserId, + /// Exact validated audience. + pub audience: Audience, +} +/// Validation construction failure. +#[derive(Debug, Error)] +pub enum ConfigurationError { + #[error("issuer must be an absolute HTTPS URL")] + /// The issuer or JWKS URL is not a trusted HTTPS URL. + InvalidIssuer, + #[error("an asymmetric algorithm must be selected")] + /// The requested signing algorithm is not explicitly allowed. + InvalidAlgorithm, +} +/// A production validator requires issuer, exact audience, trusted JWKS URL, and algorithm. +#[derive(Clone, Debug)] +pub struct AuthMiddleware { + issuer: Url, + audience: Audience, + jwks_url: Url, + algorithm: String, +} +impl AuthMiddleware { + /// Returns the configured exact resource audience. + #[must_use] + pub fn expected_audience(&self) -> &Audience { + &self.audience + } + + /// Returns the trusted issuer URL. + #[must_use] + pub fn issuer(&self) -> &Url { + &self.issuer + } + + /// Returns the trusted JWKS URL. + #[must_use] + pub fn jwks_url(&self) -> &Url { + &self.jwks_url + } + + /// Returns the explicitly allowed asymmetric algorithm. + #[must_use] + pub fn algorithm(&self) -> &str { + &self.algorithm + } + + /// Builds a validator without any signature, expiry, or audience bypass. + /// + /// # Errors + /// Returns an error for non-HTTPS issuers/JWKS URLs or non-asymmetric algorithms. + pub fn new( + issuer: Url, + audience: Audience, + jwks_url: Url, + algorithm: String, + ) -> Result { + if issuer.scheme() != "https" || jwks_url.scheme() != "https" { + return Err(ConfigurationError::InvalidIssuer); + } + if !matches!(algorithm.as_str(), "ES256" | "RS256") { + return Err(ConfigurationError::InvalidAlgorithm); + } + Ok(Self { + issuer, + audience, + jwks_url, + algorithm, + }) + } + /// Parses exactly one well-formed bearer credential before cryptographic validation. + /// + /// # Errors + /// + /// Returns a sanitized error when the header is malformed. + pub fn bearer_header(value: &str) -> Result<&str, AuthenticationError> { + let Some(token) = value.strip_prefix("Bearer ") else { + return Err(AuthenticationError::MalformedBearer); + }; + if token.is_empty() || token.contains(char::is_whitespace) { + return Err(AuthenticationError::MalformedBearer); + } + Ok(token) + } +} +/// A sanitized 401-class authentication failure. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum AuthenticationError { + #[error("authentication failed")] + /// The authorization header is malformed. + MalformedBearer, + #[error("authentication failed")] + /// Cryptographic or claims validation failed. + InvalidToken, +} +#[cfg(test)] +mod tests { + use super::*; + use std::str::FromStr; + #[test] + fn bearer_requires_one_value() { + assert_eq!( + AuthMiddleware::bearer_header("Bearer token").expect("one token"), + "token" + ); + assert!(AuthMiddleware::bearer_header("Bearer one two").is_err()); + } + #[test] + fn no_insecure_constructor() { + assert!( + AuthMiddleware::new( + Url::parse("http://issuer").expect("url"), + Audience::from_str("api").expect("audience"), + Url::parse("https://issuer/jwks").expect("url"), + "none".into() + ) + .is_err() + ); + } +} diff --git a/crates/auth-sdk/Cargo.toml b/crates/auth-sdk/Cargo.toml new file mode 100644 index 000000000..03f0d1d85 --- /dev/null +++ b/crates/auth-sdk/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "piquel-auth-sdk" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +piquel-auth-middleware = { path = "../auth-middleware" } +piquel-auth-protocol = { path = "../auth-protocol" } + +[lints] +workspace = true diff --git a/crates/auth-sdk/src/lib.rs b/crates/auth-sdk/src/lib.rs new file mode 100644 index 000000000..5a499404e --- /dev/null +++ b/crates/auth-sdk/src/lib.rs @@ -0,0 +1,5 @@ +//! Intended downstream facade for Piquel authentication integration. +pub use piquel_auth_middleware::{ + AuthMiddleware, AuthenticatedUser, AuthenticationError, ConfigurationError, +}; +pub use piquel_auth_protocol::{AccessTokenClaims, Audience, ClientId, UserId}; From bc9e19b17b015017ff8fa207fce3c43a85ff6003 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 15:40:09 +0200 Subject: [PATCH 2/4] fix(auth): enforce local JWT validation in SDK --- Cargo.lock | 293 ++++++++++++++- Cargo.toml | 3 +- crates/auth-middleware/Cargo.toml | 8 + crates/auth-middleware/src/lib.rs | 600 ++++++++++++++++++++++++++---- crates/auth-sdk/Cargo.toml | 8 + crates/auth-sdk/src/lib.rs | 333 ++++++++++++++++- 6 files changed, 1174 insertions(+), 71 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c6fddea4b..76a79ef80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -300,6 +300,23 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -342,6 +359,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + [[package]] name = "crc" version = "3.4.0" @@ -721,8 +747,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -744,8 +772,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -898,6 +929,23 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots 1.0.8", ] [[package]] @@ -906,13 +954,21 @@ version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ + "base64 0.22.1", "bytes", + "futures-channel", + "futures-util", "http", "http-body", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2", "tokio", "tower-service", + "tracing", ] [[package]] @@ -1052,6 +1108,12 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + [[package]] name = "itoa" version = "1.0.18" @@ -1133,6 +1195,12 @@ version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "matchers" version = "0.2.0" @@ -1412,8 +1480,16 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" name = "piquel-auth-middleware" version = "0.1.0" dependencies = [ + "async-trait", + "base64 0.22.1", + "chrono", + "p256", "piquel-auth-protocol", - "thiserror", + "reqwest", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", "url", ] @@ -1430,8 +1506,16 @@ dependencies = [ name = "piquel-auth-sdk" version = "0.1.0" dependencies = [ + "base64 0.22.1", "piquel-auth-middleware", "piquel-auth-protocol", + "rand 0.8.7", + "reqwest", + "serde", + "serde_json", + "sha2", + "thiserror 2.0.18", + "url", ] [[package]] @@ -1542,6 +1626,62 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.46" @@ -1584,6 +1724,17 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -1622,6 +1773,21 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1657,6 +1823,44 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots 1.0.8", +] + [[package]] name = "rfc6979" version = "0.4.0" @@ -1701,6 +1905,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rusticata-macros" version = "4.1.0" @@ -1730,6 +1940,7 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" dependencies = [ + "web-time", "zeroize", ] @@ -1869,7 +2080,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -1880,7 +2091,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -2200,6 +2411,9 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] [[package]] name = "synstructure" @@ -2343,6 +2557,16 @@ dependencies = [ "syn", ] +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-stream" version = "0.1.18" @@ -2384,6 +2608,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.0", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + [[package]] name = "tower-layer" version = "0.3.3" @@ -2458,6 +2700,12 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.1" @@ -2546,6 +2794,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2580,6 +2837,16 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.126" @@ -2612,6 +2879,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-sys" +version = "0.3.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webauthn-attestation-ca" version = "0.5.5" diff --git a/Cargo.toml b/Cargo.toml index 83bdfa7a5..5a6e31392 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,12 +37,13 @@ http-body-util = "0.1" openssl = { version = "0.10", features = ["vendored"] } p256 = { version = "0.13", features = ["ecdsa", "pem", "pkcs8"] } rand = "0.8" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } serde = { version = "1.0", features = ["derive"] } 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" -tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time"] } +tokio = { version = "1.48", features = ["macros", "rt-multi-thread", "signal", "net", "time", "sync"] } tower = { version = "0.5", features = ["util"] } tower-http = { version = "0.6", features = ["trace"] } tracing = "0.1" diff --git a/crates/auth-middleware/Cargo.toml b/crates/auth-middleware/Cargo.toml index eddb01f11..8a74d02bb 100644 --- a/crates/auth-middleware/Cargo.toml +++ b/crates/auth-middleware/Cargo.toml @@ -7,8 +7,16 @@ repository.workspace = true rust-version.workspace = true [dependencies] +async-trait.workspace = true +base64.workspace = true +chrono.workspace = true +p256.workspace = true piquel-auth-protocol = { path = "../auth-protocol" } +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true thiserror.workspace = true +tokio.workspace = true url.workspace = true [lints] diff --git a/crates/auth-middleware/src/lib.rs b/crates/auth-middleware/src/lib.rs index 6541b3eb2..b8ab28f1d 100644 --- a/crates/auth-middleware/src/lib.rs +++ b/crates/auth-middleware/src/lib.rs @@ -1,116 +1,501 @@ -//! Resource-server validation configuration with no insecure construction path. +//! Fail-closed local validation for Piquel ES256 access tokens. +#![allow(missing_docs)] -use piquel_auth_protocol::{Audience, UserId}; +use async_trait::async_trait; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::Utc; +use p256::{ + EncodedPoint, + ecdsa::{Signature, VerifyingKey, signature::Verifier}, +}; +use piquel_auth_protocol::{Audience, ClientId, SessionId, TokenId, UserId}; +use serde::Deserialize; +use serde_json::Value; +use std::{ + collections::{BTreeSet, HashMap}, + str::FromStr, + sync::Arc, + time::{Duration, Instant}, +}; use thiserror::Error; +use tokio::sync::Mutex; use url::Url; +const MAX_TOKEN_BYTES: usize = 8192; +const MAX_JWKS_BYTES: usize = 256 * 1024; +const CACHE_TTL: Duration = Duration::from_mins(5); +const RETIRED_KEY_OVERLAP: Duration = Duration::from_mins(10); +const UNKNOWN_KID_BACKOFF: Duration = Duration::from_secs(30); + /// A verified user identity, never a raw JWT. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AuthenticatedUser { - /// Immutable global account ID. pub user_id: UserId, - /// Exact validated audience. + pub session_id: SessionId, + pub token_id: TokenId, + pub client_id: ClientId, pub audience: Audience, + pub scopes: BTreeSet, + pub profile_version: u64, } -/// Validation construction failure. + #[derive(Debug, Error)] pub enum ConfigurationError { - #[error("issuer must be an absolute HTTPS URL")] - /// The issuer or JWKS URL is not a trusted HTTPS URL. + #[error("issuer and JWKS URL must be exact HTTPS URLs")] InvalidIssuer, - #[error("an asymmetric algorithm must be selected")] - /// The requested signing algorithm is not explicitly allowed. + #[error("only ES256 is supported")] InvalidAlgorithm, } -/// A production validator requires issuer, exact audience, trusted JWKS URL, and algorithm. -#[derive(Clone, Debug)] + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum AuthenticationError { + #[error("authentication failed")] + MalformedBearer, + #[error("authentication failed")] + InvalidToken, + #[error("authentication temporarily unavailable")] + KeySetUnavailable, + #[error("required scope is absent")] + MissingScope, +} + +/// Fetch boundary used by the bounded JWKS cache. +#[async_trait] +pub trait JwksFetcher: Send + Sync { + async fn fetch(&self, url: &Url) -> Result, AuthenticationError>; +} + +struct HttpJwksFetcher(reqwest::Client); +#[async_trait] +impl JwksFetcher for HttpJwksFetcher { + async fn fetch(&self, url: &Url) -> Result, AuthenticationError> { + let response = self + .0 + .get(url.clone()) + .timeout(Duration::from_secs(3)) + .send() + .await + .map_err(|_| AuthenticationError::KeySetUnavailable)?; + if !response.status().is_success() + || response + .content_length() + .is_some_and(|length| length > MAX_JWKS_BYTES as u64) + { + return Err(AuthenticationError::KeySetUnavailable); + } + let bytes = response + .bytes() + .await + .map_err(|_| AuthenticationError::KeySetUnavailable)?; + if bytes.len() > MAX_JWKS_BYTES { + return Err(AuthenticationError::KeySetUnavailable); + } + Ok(bytes.to_vec()) + } +} + +#[derive(Clone)] pub struct AuthMiddleware { - issuer: Url, + inner: Arc, +} +struct Validator { + issuer: String, audience: Audience, jwks_url: Url, - algorithm: String, + fetcher: Arc, + cache: Mutex, +} +struct KeyCache { + keys: HashMap, + fetched_at: Option, + last_unknown_refresh: Option, +} +struct CachedKey { + key: VerifyingKey, + last_present: Instant, } -impl AuthMiddleware { - /// Returns the configured exact resource audience. - #[must_use] - pub fn expected_audience(&self) -> &Audience { - &self.audience - } - - /// Returns the trusted issuer URL. - #[must_use] - pub fn issuer(&self) -> &Url { - &self.issuer - } - /// Returns the trusted JWKS URL. - #[must_use] - pub fn jwks_url(&self) -> &Url { - &self.jwks_url - } +#[derive(Deserialize)] +struct Jwks { + keys: Vec, +} +#[derive(Deserialize)] +struct Jwk { + kty: String, + crv: String, + #[serde(rename = "use")] + use_: Option, + alg: Option, + kid: String, + x: String, + y: String, +} +#[derive(Deserialize)] +struct Header { + alg: String, + typ: String, + kid: String, +} - /// Returns the explicitly allowed asymmetric algorithm. - #[must_use] - pub fn algorithm(&self) -> &str { - &self.algorithm +impl AuthMiddleware { + /// Builds a validator with a bounded HTTPS JWKS fetcher. + /// + /// # Errors + /// + /// Returns an error unless issuer and JWKS are HTTPS and ES256 is explicitly selected. + pub fn new( + issuer: &Url, + audience: Audience, + jwks_url: &Url, + algorithm: &str, + ) -> Result { + Self::with_fetcher( + issuer, + audience, + jwks_url, + algorithm, + Arc::new(HttpJwksFetcher(reqwest::Client::new())), + ) } - /// Builds a validator without any signature, expiry, or audience bypass. + /// Builds a validator with a caller-supplied fetch boundary, primarily for controlled infrastructure and tests. /// /// # Errors - /// Returns an error for non-HTTPS issuers/JWKS URLs or non-asymmetric algorithms. - pub fn new( - issuer: Url, + /// + /// Returns an error unless issuer and JWKS are HTTPS and ES256 is explicitly selected. + pub fn with_fetcher( + issuer: &Url, audience: Audience, - jwks_url: Url, - algorithm: String, + jwks_url: &Url, + algorithm: &str, + fetcher: Arc, ) -> Result { - if issuer.scheme() != "https" || jwks_url.scheme() != "https" { + if issuer.scheme() != "https" + || jwks_url.scheme() != "https" + || issuer.fragment().is_some() + || issuer.query().is_some() + || jwks_url.fragment().is_some() + { return Err(ConfigurationError::InvalidIssuer); } - if !matches!(algorithm.as_str(), "ES256" | "RS256") { + if algorithm != "ES256" { return Err(ConfigurationError::InvalidAlgorithm); } Ok(Self { - issuer, - audience, - jwks_url, - algorithm, + inner: Arc::new(Validator { + issuer: issuer.as_str().trim_end_matches('/').to_owned(), + audience, + jwks_url: jwks_url.clone(), + fetcher, + cache: Mutex::new(KeyCache { + keys: HashMap::new(), + fetched_at: None, + last_unknown_refresh: None, + }), + }), }) } - /// Parses exactly one well-formed bearer credential before cryptographic validation. + + #[must_use] + pub fn expected_audience(&self) -> &Audience { + &self.inner.audience + } + #[must_use] + pub fn issuer(&self) -> &str { + &self.inner.issuer + } + #[must_use] + pub fn jwks_url(&self) -> &Url { + &self.inner.jwks_url + } + #[must_use] + pub const fn algorithm(&self) -> &'static str { + "ES256" + } + + /// Parses exactly one well-formed Bearer credential. /// /// # Errors /// - /// Returns a sanitized error when the header is malformed. + /// Returns a sanitized error unless the value contains one Bearer token. pub fn bearer_header(value: &str) -> Result<&str, AuthenticationError> { - let Some(token) = value.strip_prefix("Bearer ") else { - return Err(AuthenticationError::MalformedBearer); - }; + let token = value + .strip_prefix("Bearer ") + .ok_or(AuthenticationError::MalformedBearer)?; if token.is_empty() || token.contains(char::is_whitespace) { return Err(AuthenticationError::MalformedBearer); } Ok(token) } + + /// Rejects zero or multiple Authorization header values before validating the token. + /// + /// # Errors + /// + /// Returns a sanitized authentication or key-availability error. + pub async fn authenticate_headers<'a>( + &self, + values: impl IntoIterator, + ) -> Result { + let mut values = values.into_iter(); + let value = values.next().ok_or(AuthenticationError::MalformedBearer)?; + if values.next().is_some() { + return Err(AuthenticationError::MalformedBearer); + } + self.authenticate(Self::bearer_header(value)?).await + } + + /// Validates signature, token type, fixed algorithm, key identifier, issuer, audience, time, and typed claims. + /// + /// # Errors + /// + /// Returns a sanitized authentication or key-availability error. + pub async fn authenticate( + &self, + token: &str, + ) -> Result { + if token.len() > MAX_TOKEN_BYTES { + return Err(AuthenticationError::InvalidToken); + } + let mut parts = token.split('.'); + let header_part = parts.next().ok_or(AuthenticationError::InvalidToken)?; + let claims_part = parts.next().ok_or(AuthenticationError::InvalidToken)?; + let signature_part = parts.next().ok_or(AuthenticationError::InvalidToken)?; + if parts.next().is_some() { + return Err(AuthenticationError::InvalidToken); + } + let header: Header = decode_json(header_part)?; + if header.alg != "ES256" + || header.typ != "at+jwt" + || header.kid.is_empty() + || header.kid.len() > 128 + { + return Err(AuthenticationError::InvalidToken); + } + let key = self.key(&header.kid).await?; + let signature_bytes = URL_SAFE_NO_PAD + .decode(signature_part) + .map_err(|_| AuthenticationError::InvalidToken)?; + let signature = Signature::from_slice(&signature_bytes) + .map_err(|_| AuthenticationError::InvalidToken)?; + key.verify( + format!("{header_part}.{claims_part}").as_bytes(), + &signature, + ) + .map_err(|_| AuthenticationError::InvalidToken)?; + let claims: Value = decode_json(claims_part)?; + self.validate_claims(&claims) + } + + /// Applies an optional coarse scope gate after authentication. + /// + /// # Errors + /// + /// Returns `MissingScope` when the verified token lacks the requested scope. + pub fn require_scope(user: &AuthenticatedUser, scope: &str) -> Result<(), AuthenticationError> { + if user.scopes.contains(scope) { + Ok(()) + } else { + Err(AuthenticationError::MissingScope) + } + } + + async fn key(&self, kid: &str) -> Result { + let now = Instant::now(); + let mut cache = self.inner.cache.lock().await; + if cache + .fetched_at + .is_none_or(|at| now.duration_since(at) >= CACHE_TTL) + { + self.refresh_locked(&mut cache, now).await?; + } + if let Some(key) = cache.keys.get(kid) { + return Ok(key.key); + } + if cache + .last_unknown_refresh + .is_none_or(|at| now.duration_since(at) >= UNKNOWN_KID_BACKOFF) + { + cache.last_unknown_refresh = Some(now); + self.refresh_locked(&mut cache, now).await?; + } + cache + .keys + .get(kid) + .map(|key| key.key) + .ok_or(AuthenticationError::InvalidToken) + } + async fn refresh_locked( + &self, + cache: &mut KeyCache, + now: Instant, + ) -> Result<(), AuthenticationError> { + let bytes = self.inner.fetcher.fetch(&self.inner.jwks_url).await?; + let jwks: Jwks = + serde_json::from_slice(&bytes).map_err(|_| AuthenticationError::KeySetUnavailable)?; + if jwks.keys.is_empty() || jwks.keys.len() > 32 { + return Err(AuthenticationError::KeySetUnavailable); + } + let mut present = BTreeSet::new(); + for jwk in jwks.keys { + if jwk.kty != "EC" + || jwk.crv != "P-256" + || jwk.alg.as_deref() != Some("ES256") + || jwk.use_.as_deref().is_some_and(|use_| use_ != "sig") + || jwk.kid.is_empty() + { + continue; + } + let x = URL_SAFE_NO_PAD + .decode(jwk.x) + .map_err(|_| AuthenticationError::KeySetUnavailable)?; + let y = URL_SAFE_NO_PAD + .decode(jwk.y) + .map_err(|_| AuthenticationError::KeySetUnavailable)?; + if x.len() != 32 || y.len() != 32 { + return Err(AuthenticationError::KeySetUnavailable); + } + let point = EncodedPoint::from_affine_coordinates( + x.as_slice().into(), + y.as_slice().into(), + false, + ); + let key = VerifyingKey::from_encoded_point(&point) + .map_err(|_| AuthenticationError::KeySetUnavailable)?; + present.insert(jwk.kid.clone()); + cache.keys.insert( + jwk.kid, + CachedKey { + key, + last_present: now, + }, + ); + } + if present.is_empty() { + return Err(AuthenticationError::KeySetUnavailable); + } + cache.keys.retain(|kid, key| { + present.contains(kid) || now.duration_since(key.last_present) < RETIRED_KEY_OVERLAP + }); + cache.fetched_at = Some(now); + Ok(()) + } + fn validate_claims(&self, claims: &Value) -> Result { + let string = |name| { + claims + .get(name) + .and_then(Value::as_str) + .ok_or(AuthenticationError::InvalidToken) + }; + let integer = |name| { + claims + .get(name) + .and_then(Value::as_i64) + .ok_or(AuthenticationError::InvalidToken) + }; + let now = Utc::now().timestamp(); + let exp = integer("exp")?; + let iat = integer("iat")?; + if exp <= now + || exp > iat + 300 + || iat > now + 30 + || claims + .get("nbf") + .and_then(Value::as_i64) + .is_some_and(|nbf| nbf > now + 30) + || string("iss")? != self.inner.issuer + || string("aud")? != self.inner.audience.as_str() + { + return Err(AuthenticationError::InvalidToken); + } + let scopes = string("scope")? + .split_ascii_whitespace() + .map(str::to_owned) + .collect(); + let profile_version = claims + .get("profile_version") + .and_then(Value::as_u64) + .ok_or(AuthenticationError::InvalidToken)?; + Ok(AuthenticatedUser { + user_id: UserId::from_str(string("sub")?) + .map_err(|_| AuthenticationError::InvalidToken)?, + session_id: SessionId::from_str(string("sid")?) + .map_err(|_| AuthenticationError::InvalidToken)?, + token_id: TokenId::from_str(string("jti")?) + .map_err(|_| AuthenticationError::InvalidToken)?, + client_id: ClientId::from_str(string("client_id")?) + .map_err(|_| AuthenticationError::InvalidToken)?, + audience: self.inner.audience.clone(), + scopes, + profile_version, + }) + } } -/// A sanitized 401-class authentication failure. -#[derive(Debug, Error, PartialEq, Eq)] -pub enum AuthenticationError { - #[error("authentication failed")] - /// The authorization header is malformed. - MalformedBearer, - #[error("authentication failed")] - /// Cryptographic or claims validation failed. - InvalidToken, + +fn decode_json Deserialize<'de>>(part: &str) -> Result { + let bytes = URL_SAFE_NO_PAD + .decode(part) + .map_err(|_| AuthenticationError::InvalidToken)?; + if bytes.len() > MAX_TOKEN_BYTES { + return Err(AuthenticationError::InvalidToken); + } + serde_json::from_slice(&bytes).map_err(|_| AuthenticationError::InvalidToken) } + #[cfg(test)] mod tests { use super::*; - use std::str::FromStr; + use p256::ecdsa::{SigningKey, signature::Signer}; + use serde_json::json; + use std::sync::{ + Mutex as StdMutex, + atomic::{AtomicUsize, Ordering}, + }; + + struct MockFetcher { + body: StdMutex>, + calls: AtomicUsize, + fail: bool, + } + #[async_trait] + impl JwksFetcher for MockFetcher { + async fn fetch(&self, _: &Url) -> Result, AuthenticationError> { + self.calls.fetch_add(1, Ordering::SeqCst); + if self.fail { + Err(AuthenticationError::KeySetUnavailable) + } else { + Ok(self.body.lock().expect("body").clone()) + } + } + } + fn jwks(kid: &str, key: &SigningKey) -> Vec { + let point = key.verifying_key().to_encoded_point(false); + serde_json::to_vec(&json!({"keys":[{"kty":"EC","crv":"P-256","use":"sig","alg":"ES256","kid":kid,"x":URL_SAFE_NO_PAD.encode(point.x().expect("x")),"y":URL_SAFE_NO_PAD.encode(point.y().expect("y"))}]})).expect("JWKS") + } + fn token(kid: &str, typ: &str, key: &SigningKey, aud: &str) -> String { + let now = Utc::now().timestamp(); + let header = URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&json!({"alg":"ES256","typ":typ,"kid":kid})).expect("header"), + ); + let claims=URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({"iss":"https://issuer.example","sub":UserId::new(),"aud":aud,"sid":SessionId::new(),"jti":TokenId::new(),"client_id":"web-client","scope":"openid profile","profile_version":1,"iat":now,"exp":now+300})).expect("claims")); + let input = format!("{header}.{claims}"); + let signature: Signature = key.sign(input.as_bytes()); + format!("{input}.{}", URL_SAFE_NO_PAD.encode(signature.to_bytes())) + } + fn validator(fetcher: Arc) -> AuthMiddleware { + AuthMiddleware::with_fetcher( + &Url::parse("https://issuer.example").expect("issuer"), + Audience::from_str("product-api").expect("audience"), + &Url::parse("https://issuer.example/.well-known/jwks.json").expect("JWKS URL"), + "ES256", + fetcher, + ) + .expect("validator") + } #[test] fn bearer_requires_one_value() { assert_eq!( - AuthMiddleware::bearer_header("Bearer token").expect("one token"), + AuthMiddleware::bearer_header("Bearer token").expect("token"), "token" ); assert!(AuthMiddleware::bearer_header("Bearer one two").is_err()); @@ -119,12 +504,97 @@ mod tests { fn no_insecure_constructor() { assert!( AuthMiddleware::new( - Url::parse("http://issuer").expect("url"), + &Url::parse("http://issuer").expect("url"), Audience::from_str("api").expect("audience"), - Url::parse("https://issuer/jwks").expect("url"), - "none".into() + &Url::parse("https://issuer/jwks").expect("url"), + "none" ) .is_err() ); } + + #[tokio::test] + async fn verifies_real_es256_and_rejects_wrong_token_contract() { + let key = SigningKey::from_bytes((&[7_u8; 32]).into()).expect("key"); + let fetcher = Arc::new(MockFetcher { + body: StdMutex::new(jwks("active", &key)), + calls: AtomicUsize::new(0), + fail: false, + }); + let middleware = validator(fetcher); + assert!( + middleware + .authenticate(&token("active", "at+jwt", &key, "product-api")) + .await + .is_ok() + ); + assert_eq!( + middleware + .authenticate(&token("active", "JWT", &key, "product-api")) + .await, + Err(AuthenticationError::InvalidToken) + ); + assert_eq!( + middleware + .authenticate(&token("active", "at+jwt", &key, "other-api")) + .await, + Err(AuthenticationError::InvalidToken) + ); + } + + #[tokio::test] + async fn refreshes_once_for_unknown_kid_and_keeps_rotation_overlap() { + let old = SigningKey::from_bytes((&[3_u8; 32]).into()).expect("old"); + let new = SigningKey::from_bytes((&[4_u8; 32]).into()).expect("new"); + let fetcher = Arc::new(MockFetcher { + body: StdMutex::new(jwks("old", &old)), + calls: AtomicUsize::new(0), + fail: false, + }); + let middleware = validator(fetcher.clone()); + let old_token = token("old", "at+jwt", &old, "product-api"); + middleware + .authenticate(&old_token) + .await + .expect("old accepted"); + *fetcher.body.lock().expect("body") = jwks("new", &new); + middleware + .authenticate(&token("new", "at+jwt", &new, "product-api")) + .await + .expect("new accepted after refresh"); + middleware + .authenticate(&old_token) + .await + .expect("old retained during overlap"); + assert_eq!(fetcher.calls.load(Ordering::SeqCst), 2); + assert!( + middleware + .authenticate(&token("unknown", "at+jwt", &new, "product-api")) + .await + .is_err() + ); + assert!( + middleware + .authenticate(&token("another", "at+jwt", &new, "product-api")) + .await + .is_err() + ); + assert_eq!(fetcher.calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn fails_closed_when_jwks_is_unavailable() { + let fetcher = Arc::new(MockFetcher { + body: StdMutex::new(vec![]), + calls: AtomicUsize::new(0), + fail: true, + }); + let key = SigningKey::from_bytes((&[9_u8; 32]).into()).expect("key"); + assert_eq!( + validator(fetcher) + .authenticate(&token("kid", "at+jwt", &key, "product-api")) + .await, + Err(AuthenticationError::KeySetUnavailable) + ); + } } diff --git a/crates/auth-sdk/Cargo.toml b/crates/auth-sdk/Cargo.toml index 03f0d1d85..7efb7996a 100644 --- a/crates/auth-sdk/Cargo.toml +++ b/crates/auth-sdk/Cargo.toml @@ -7,8 +7,16 @@ repository.workspace = true rust-version.workspace = true [dependencies] +base64.workspace = true piquel-auth-middleware = { path = "../auth-middleware" } piquel-auth-protocol = { path = "../auth-protocol" } +rand.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +thiserror.workspace = true +url.workspace = true [lints] workspace = true diff --git a/crates/auth-sdk/src/lib.rs b/crates/auth-sdk/src/lib.rs index 5a499404e..e9742df96 100644 --- a/crates/auth-sdk/src/lib.rs +++ b/crates/auth-sdk/src/lib.rs @@ -1,5 +1,334 @@ -//! Intended downstream facade for Piquel authentication integration. +//! Downstream facade for local token validation and server-side OIDC flows. +#![allow(missing_docs)] + pub use piquel_auth_middleware::{ - AuthMiddleware, AuthenticatedUser, AuthenticationError, ConfigurationError, + AuthMiddleware, AuthenticatedUser, AuthenticationError, ConfigurationError, JwksFetcher, }; pub use piquel_auth_protocol::{AccessTokenClaims, Audience, ClientId, UserId}; + +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use rand::{RngCore, rngs::OsRng}; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use std::{fmt, time::Duration}; +use thiserror::Error; +use url::Url; + +#[derive(Clone, Debug, Deserialize)] +pub struct DiscoveryDocument { + pub issuer: String, + pub authorization_endpoint: Url, + pub token_endpoint: Url, + pub revocation_endpoint: Url, + pub jwks_uri: Url, + pub end_session_endpoint: Url, + pub code_challenge_methods_supported: Vec, +} + +#[derive(Debug, Error)] +pub enum OidcClientError { + #[error("OIDC configuration is invalid")] + InvalidConfiguration, + #[error("OIDC request failed")] + Request, + #[error("authorization callback is invalid")] + InvalidCallback, +} + +#[derive(Clone)] +pub struct OidcClient { + client: reqwest::Client, + client_id: ClientId, + redirect_uri: Url, + discovery: DiscoveryDocument, +} + +impl OidcClient { + /// Fetches and validates discovery from the exact issuer. + /// + /// # Errors + /// + /// Fails closed on non-HTTPS configuration, network errors, oversized responses, issuer mismatch, or missing S256 support. + pub async fn discover( + issuer: Url, + client_id: ClientId, + redirect_uri: Url, + ) -> Result { + if issuer.scheme() != "https" + || redirect_uri.scheme() != "https" + || issuer.query().is_some() + || issuer.fragment().is_some() + { + return Err(OidcClientError::InvalidConfiguration); + } + let client = reqwest::Client::new(); + let url = Url::parse(&format!( + "{}/.well-known/openid-configuration", + issuer.as_str().trim_end_matches('/') + )) + .map_err(|_| OidcClientError::InvalidConfiguration)?; + let response = client + .get(url) + .timeout(Duration::from_secs(3)) + .send() + .await + .map_err(|_| OidcClientError::Request)?; + if !response.status().is_success() + || response + .content_length() + .is_some_and(|length| length > 128 * 1024) + { + return Err(OidcClientError::Request); + } + let bytes = response + .bytes() + .await + .map_err(|_| OidcClientError::Request)?; + if bytes.len() > 128 * 1024 { + return Err(OidcClientError::Request); + } + let discovery: DiscoveryDocument = + serde_json::from_slice(&bytes).map_err(|_| OidcClientError::InvalidConfiguration)?; + if discovery.issuer.trim_end_matches('/') != issuer.as_str().trim_end_matches('/') + || !discovery + .code_challenge_methods_supported + .iter() + .any(|method| method == "S256") + || [ + &discovery.authorization_endpoint, + &discovery.token_endpoint, + &discovery.revocation_endpoint, + &discovery.jwks_uri, + &discovery.end_session_endpoint, + ] + .iter() + .any(|url| url.scheme() != "https") + { + return Err(OidcClientError::InvalidConfiguration); + } + Ok(Self { + client, + client_id, + redirect_uri, + discovery, + }) + } + + /// Builds an authorization URL and server-side callback context with random state, nonce, and S256 verifier. + /// + /// # Errors + /// + /// Returns an error if the trusted authorization URL cannot be constructed. + pub fn authorization_url( + &self, + scopes: &[&str], + audience: &Audience, + ) -> Result<(Url, CallbackContext), OidcClientError> { + let state = random_b64(32); + let nonce = random_b64(32); + let verifier = random_b64(32); + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + let mut url = self.discovery.authorization_endpoint.clone(); + url.query_pairs_mut() + .append_pair("response_type", "code") + .append_pair("client_id", self.client_id.as_str()) + .append_pair("redirect_uri", self.redirect_uri.as_str()) + .append_pair("scope", &scopes.join(" ")) + .append_pair("audience", audience.as_str()) + .append_pair("state", &state) + .append_pair("nonce", &nonce) + .append_pair("code_challenge", &challenge) + .append_pair("code_challenge_method", "S256"); + Ok(( + url, + CallbackContext { + state, + nonce, + verifier, + }, + )) + } + + /// Validates callback state and exchanges the one-time code from the server side. + /// + /// # Errors + /// + /// Returns an error on state mismatch, OAuth error, malformed callback, or failed token exchange. + pub async fn exchange_callback( + &self, + callback: &Url, + context: CallbackContext, + ) -> Result { + let mut state = None; + let mut code = None; + let mut error = false; + for (key, value) in callback.query_pairs() { + match key.as_ref() { + "state" => state = Some(value.into_owned()), + "code" => code = Some(value.into_owned()), + "error" => error = true, + _ => {} + } + } + if error || state.as_deref() != Some(&context.state) { + return Err(OidcClientError::InvalidCallback); + } + let code = code.ok_or(OidcClientError::InvalidCallback)?; + let response = self + .client + .post(self.discovery.token_endpoint.clone()) + .timeout(Duration::from_secs(5)) + .form(&[ + ("grant_type", "authorization_code"), + ("client_id", self.client_id.as_str()), + ("code", &code), + ("redirect_uri", self.redirect_uri.as_str()), + ("code_verifier", &context.verifier), + ]) + .send() + .await + .map_err(|_| OidcClientError::Request)?; + parse_token_response(response).await + } + + /// Rotates a refresh token. Callers must persist only the returned replacement. + /// + /// # Errors + /// + /// Returns an error on network or invalid-grant responses. + pub async fn refresh(&self, refresh_token: &str) -> Result { + let response = self + .client + .post(self.discovery.token_endpoint.clone()) + .timeout(Duration::from_secs(5)) + .form(&[ + ("grant_type", "refresh_token"), + ("client_id", self.client_id.as_str()), + ("refresh_token", refresh_token), + ]) + .send() + .await + .map_err(|_| OidcClientError::Request)?; + parse_token_response(response).await + } + + /// Builds an exact post-logout redirect request. + #[must_use] + pub fn logout_url(&self, post_logout_redirect_uri: &Url, state: &str) -> Url { + let mut url = self.discovery.end_session_endpoint.clone(); + url.query_pairs_mut() + .append_pair("client_id", self.client_id.as_str()) + .append_pair( + "post_logout_redirect_uri", + post_logout_redirect_uri.as_str(), + ) + .append_pair("state", state); + url + } + + #[must_use] + pub fn discovery(&self) -> &DiscoveryDocument { + &self.discovery + } +} + +/// Secrets retained only in a server-side login transaction. +pub struct CallbackContext { + state: String, + nonce: String, + verifier: String, +} +impl CallbackContext { + #[must_use] + pub fn nonce(&self) -> &str { + &self.nonce + } +} +impl fmt::Debug for CallbackContext { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("CallbackContext(REDACTED)") + } +} + +#[derive(Deserialize)] +struct RawTokenSet { + access_token: String, + token_type: String, + expires_in: i64, + scope: String, + id_token: Option, + refresh_token: Option, +} +pub struct TokenSet { + raw: RawTokenSet, +} +impl TokenSet { + #[must_use] + pub fn access_token(&self) -> &str { + &self.raw.access_token + } + #[must_use] + pub fn id_token(&self) -> Option<&str> { + self.raw.id_token.as_deref() + } + #[must_use] + pub fn refresh_token(&self) -> Option<&str> { + self.raw.refresh_token.as_deref() + } + #[must_use] + pub fn expires_in(&self) -> i64 { + self.raw.expires_in + } + #[must_use] + pub fn scopes(&self) -> &str { + &self.raw.scope + } +} +impl fmt::Debug for TokenSet { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TokenSet") + .field("token_type", &self.raw.token_type) + .field("expires_in", &self.raw.expires_in) + .field("scope", &self.raw.scope) + .field("tokens", &"REDACTED") + .finish() + } +} + +async fn parse_token_response(response: reqwest::Response) -> Result { + if !response.status().is_success() { + return Err(OidcClientError::Request); + } + let raw: RawTokenSet = response + .json() + .await + .map_err(|_| OidcClientError::Request)?; + if raw.token_type != "Bearer" + || raw.access_token.is_empty() + || raw.expires_in <= 0 + || raw.expires_in > 300 + { + return Err(OidcClientError::Request); + } + Ok(TokenSet { raw }) +} +fn random_b64(size: usize) -> String { + let mut bytes = vec![0; size]; + OsRng.fill_bytes(&mut bytes); + URL_SAFE_NO_PAD.encode(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn secrets_are_redacted() { + let context = CallbackContext { + state: "state".into(), + nonce: "nonce".into(), + verifier: "secret".into(), + }; + assert_eq!(format!("{context:?}"), "CallbackContext(REDACTED)"); + } +} From e4f79a76c418e6f35210d3624158094dcdfa8cc4 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:04:20 +0200 Subject: [PATCH 3/4] fix(auth): make verified principals opaque --- crates/auth-middleware/src/lib.rs | 46 +++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/auth-middleware/src/lib.rs b/crates/auth-middleware/src/lib.rs index b8ab28f1d..de4d76b37 100644 --- a/crates/auth-middleware/src/lib.rs +++ b/crates/auth-middleware/src/lib.rs @@ -30,13 +30,43 @@ const UNKNOWN_KID_BACKOFF: Duration = Duration::from_secs(30); /// A verified user identity, never a raw JWT. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AuthenticatedUser { - pub user_id: UserId, - pub session_id: SessionId, - pub token_id: TokenId, - pub client_id: ClientId, - pub audience: Audience, - pub scopes: BTreeSet, - pub profile_version: u64, + user_id: UserId, + session_id: SessionId, + token_id: TokenId, + client_id: ClientId, + audience: Audience, + scopes: BTreeSet, + profile_version: u64, +} +impl AuthenticatedUser { + #[must_use] + pub const fn user_id(&self) -> UserId { + self.user_id + } + #[must_use] + pub const fn session_id(&self) -> SessionId { + self.session_id + } + #[must_use] + pub const fn token_id(&self) -> TokenId { + self.token_id + } + #[must_use] + pub fn client_id(&self) -> &ClientId { + &self.client_id + } + #[must_use] + pub fn audience(&self) -> &Audience { + &self.audience + } + #[must_use] + pub fn scopes(&self) -> &BTreeSet { + &self.scopes + } + #[must_use] + pub const fn profile_version(&self) -> u64 { + self.profile_version + } } #[derive(Debug, Error)] @@ -293,7 +323,7 @@ impl AuthMiddleware { /// /// Returns `MissingScope` when the verified token lacks the requested scope. pub fn require_scope(user: &AuthenticatedUser, scope: &str) -> Result<(), AuthenticationError> { - if user.scopes.contains(scope) { + if user.scopes().contains(scope) { Ok(()) } else { Err(AuthenticationError::MissingScope) From f797924de16b784a8f28d2c1765f1421680e613e Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:53:35 +0200 Subject: [PATCH 4/4] fix(auth): verify OIDC identity tokens in the SDK --- Cargo.lock | 2 + crates/auth-sdk/Cargo.toml | 2 + crates/auth-sdk/src/lib.rs | 306 ++++++++++++++++++++++++++++++++++++- 3 files changed, 307 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 76a79ef80..138fa06c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1507,6 +1507,8 @@ name = "piquel-auth-sdk" version = "0.1.0" dependencies = [ "base64 0.22.1", + "chrono", + "p256", "piquel-auth-middleware", "piquel-auth-protocol", "rand 0.8.7", diff --git a/crates/auth-sdk/Cargo.toml b/crates/auth-sdk/Cargo.toml index 7efb7996a..bd2feaaa4 100644 --- a/crates/auth-sdk/Cargo.toml +++ b/crates/auth-sdk/Cargo.toml @@ -8,6 +8,8 @@ rust-version.workspace = true [dependencies] base64.workspace = true +chrono.workspace = true +p256.workspace = true piquel-auth-middleware = { path = "../auth-middleware" } piquel-auth-protocol = { path = "../auth-protocol" } rand.workspace = true diff --git a/crates/auth-sdk/src/lib.rs b/crates/auth-sdk/src/lib.rs index e9742df96..1801561d3 100644 --- a/crates/auth-sdk/src/lib.rs +++ b/crates/auth-sdk/src/lib.rs @@ -7,8 +7,15 @@ pub use piquel_auth_middleware::{ pub use piquel_auth_protocol::{AccessTokenClaims, Audience, ClientId, UserId}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::Utc; +use p256::{ + EncodedPoint, + ecdsa::{Signature, VerifyingKey, signature::Verifier}, +}; +use piquel_auth_protocol::SessionId; use rand::{RngCore, rngs::OsRng}; use serde::Deserialize; +use serde_json::Value; use sha2::{Digest, Sha256}; use std::{fmt, time::Duration}; use thiserror::Error; @@ -158,7 +165,7 @@ impl OidcClient { &self, callback: &Url, context: CallbackContext, - ) -> Result { + ) -> Result { let mut state = None; let mut code = None; let mut error = false; @@ -188,7 +195,21 @@ impl OidcClient { .send() .await .map_err(|_| OidcClientError::Request)?; - parse_token_response(response).await + let tokens = parse_token_response(response).await?; + let id_token = tokens + .raw + .id_token + .as_deref() + .ok_or(OidcClientError::InvalidCallback)?; + let jwks = self.fetch_jwks().await?; + let identity = validate_id_token( + id_token, + &jwks, + self.discovery.issuer.trim_end_matches('/'), + self.client_id.as_str(), + &context.nonce, + )?; + Ok(AuthenticatedTokenSet { tokens, identity }) } /// Rotates a refresh token. Callers must persist only the returned replacement. @@ -230,6 +251,30 @@ impl OidcClient { pub fn discovery(&self) -> &DiscoveryDocument { &self.discovery } + + async fn fetch_jwks(&self) -> Result, OidcClientError> { + let response = self + .client + .get(self.discovery.jwks_uri.clone()) + .timeout(Duration::from_secs(3)) + .send() + .await + .map_err(|_| OidcClientError::Request)?; + if !response.status().is_success() + || response + .content_length() + .is_some_and(|length| length > 256 * 1024) + { + return Err(OidcClientError::Request); + } + let bytes = response + .bytes() + .await + .map_err(|_| OidcClientError::Request)?; + (bytes.len() <= 256 * 1024) + .then(|| bytes.to_vec()) + .ok_or(OidcClientError::Request) + } } /// Secrets retained only in a server-side login transaction. @@ -268,7 +313,7 @@ impl TokenSet { &self.raw.access_token } #[must_use] - pub fn id_token(&self) -> Option<&str> { + pub fn raw_id_token(&self) -> Option<&str> { self.raw.id_token.as_deref() } #[must_use] @@ -284,6 +329,43 @@ impl TokenSet { &self.raw.scope } } + +/// Token response whose ID token has been cryptographically and semantically verified. +pub struct AuthenticatedTokenSet { + tokens: TokenSet, + identity: VerifiedIdentity, +} +impl AuthenticatedTokenSet { + #[must_use] + pub const fn identity(&self) -> &VerifiedIdentity { + &self.identity + } + #[must_use] + pub const fn tokens(&self) -> &TokenSet { + &self.tokens + } + #[must_use] + pub fn into_tokens(self) -> TokenSet { + self.tokens + } +} + +/// Identity claims obtained only after ID-token verification. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VerifiedIdentity { + user_id: UserId, + session_id: SessionId, +} +impl VerifiedIdentity { + #[must_use] + pub const fn user_id(&self) -> UserId { + self.user_id + } + #[must_use] + pub const fn session_id(&self) -> SessionId { + self.session_id + } +} impl fmt::Debug for TokenSet { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter @@ -313,6 +395,137 @@ async fn parse_token_response(response: reqwest::Response) -> Result, +} +#[derive(Deserialize)] +struct Jwk { + kty: String, + crv: String, + #[serde(rename = "use")] + use_: Option, + alg: String, + kid: String, + x: String, + y: String, +} + +fn validate_id_token( + token: &str, + jwks: &[u8], + issuer: &str, + client_id: &str, + nonce: &str, +) -> Result { + if token.len() > 8192 || nonce.is_empty() { + return Err(OidcClientError::InvalidCallback); + } + let mut parts = token.split('.'); + let header_part = parts.next().ok_or(OidcClientError::InvalidCallback)?; + let claims_part = parts.next().ok_or(OidcClientError::InvalidCallback)?; + let signature_part = parts.next().ok_or(OidcClientError::InvalidCallback)?; + if parts.next().is_some() { + return Err(OidcClientError::InvalidCallback); + } + let header: IdTokenHeader = decode_part(header_part)?; + if header.alg != "ES256" + || header.typ != "JWT" + || header.kid.is_empty() + || header.kid.len() > 128 + { + return Err(OidcClientError::InvalidCallback); + } + let jwks: Jwks = serde_json::from_slice(jwks).map_err(|_| OidcClientError::InvalidCallback)?; + if jwks.keys.is_empty() || jwks.keys.len() > 32 { + return Err(OidcClientError::InvalidCallback); + } + let jwk = jwks + .keys + .into_iter() + .find(|key| key.kid == header.kid) + .ok_or(OidcClientError::InvalidCallback)?; + if jwk.kty != "EC" + || jwk.crv != "P-256" + || jwk.alg != "ES256" + || jwk.use_.as_deref().is_some_and(|use_| use_ != "sig") + { + return Err(OidcClientError::InvalidCallback); + } + let x = URL_SAFE_NO_PAD + .decode(jwk.x) + .map_err(|_| OidcClientError::InvalidCallback)?; + let y = URL_SAFE_NO_PAD + .decode(jwk.y) + .map_err(|_| OidcClientError::InvalidCallback)?; + if x.len() != 32 || y.len() != 32 { + return Err(OidcClientError::InvalidCallback); + } + let point = + EncodedPoint::from_affine_coordinates(x.as_slice().into(), y.as_slice().into(), false); + let key = + VerifyingKey::from_encoded_point(&point).map_err(|_| OidcClientError::InvalidCallback)?; + let signature = URL_SAFE_NO_PAD + .decode(signature_part) + .ok() + .and_then(|bytes| Signature::from_slice(&bytes).ok()) + .ok_or(OidcClientError::InvalidCallback)?; + key.verify( + format!("{header_part}.{claims_part}").as_bytes(), + &signature, + ) + .map_err(|_| OidcClientError::InvalidCallback)?; + let claims: Value = decode_part(claims_part)?; + let string = |name| { + claims + .get(name) + .and_then(Value::as_str) + .ok_or(OidcClientError::InvalidCallback) + }; + let integer = |name| { + claims + .get(name) + .and_then(Value::as_i64) + .ok_or(OidcClientError::InvalidCallback) + }; + let now = Utc::now().timestamp(); + let issued_at = integer("iat")?; + if string("iss")?.trim_end_matches('/') != issuer + || string("aud")? != client_id + || string("nonce")? != nonce + || integer("exp")? <= now + || claims + .get("nbf") + .and_then(Value::as_i64) + .is_some_and(|nbf| nbf > now + 30) + || issued_at > now + 30 + || issued_at < now - 600 + { + return Err(OidcClientError::InvalidCallback); + } + Ok(VerifiedIdentity { + user_id: string("sub")? + .parse() + .map_err(|_| OidcClientError::InvalidCallback)?, + session_id: string("sid")? + .parse() + .map_err(|_| OidcClientError::InvalidCallback)?, + }) +} + +fn decode_part Deserialize<'de>>(value: &str) -> Result { + let bytes = URL_SAFE_NO_PAD + .decode(value) + .map_err(|_| OidcClientError::InvalidCallback)?; + serde_json::from_slice(&bytes).map_err(|_| OidcClientError::InvalidCallback) +} fn random_b64(size: usize) -> String { let mut bytes = vec![0; size]; OsRng.fill_bytes(&mut bytes); @@ -322,6 +535,9 @@ fn random_b64(size: usize) -> String { #[cfg(test)] mod tests { use super::*; + use p256::ecdsa::{Signature, SigningKey, signature::Signer}; + use rand::rngs::OsRng; + use serde_json::json; #[test] fn secrets_are_redacted() { let context = CallbackContext { @@ -331,4 +547,88 @@ mod tests { }; assert_eq!(format!("{context:?}"), "CallbackContext(REDACTED)"); } + + fn id_fixture(claims: &Value, algorithm: &str) -> (String, Vec) { + let key = SigningKey::random(&mut OsRng); + let header = URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&json!({"alg":algorithm,"typ":"JWT","kid":"test"})).expect("header"), + ); + let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).expect("claims")); + let input = format!("{header}.{payload}"); + let signature: Signature = key.sign(input.as_bytes()); + let point = key.verifying_key().to_encoded_point(false); + let jwks = serde_json::to_vec(&json!({"keys":[{ + "kty":"EC","crv":"P-256","use":"sig","alg":"ES256","kid":"test", + "x":URL_SAFE_NO_PAD.encode(point.x().expect("x")), + "y":URL_SAFE_NO_PAD.encode(point.y().expect("y")) + }]})) + .expect("JWKS"); + ( + format!("{input}.{}", URL_SAFE_NO_PAD.encode(signature.to_bytes())), + jwks, + ) + } + + #[test] + fn id_token_requires_signature_issuer_audience_nonce_and_algorithm() { + let now = Utc::now().timestamp(); + let user_id = UserId::new(); + let session_id = SessionId::new(); + let claims = json!({ + "iss":"https://auth.example","aud":"client","nonce":"nonce", + "sub":user_id,"sid":session_id,"iat":now,"exp":now+300 + }); + let (valid, jwks) = id_fixture(&claims, "ES256"); + assert_eq!( + validate_id_token(&valid, &jwks, "https://auth.example", "client", "nonce") + .expect("valid ID token") + .user_id(), + user_id + ); + assert!(validate_id_token(&valid, &jwks, "https://other", "client", "nonce").is_err()); + assert!( + validate_id_token( + &valid, + &jwks, + "https://auth.example", + "other-client", + "nonce" + ) + .is_err() + ); + assert!( + validate_id_token( + &valid, + &jwks, + "https://auth.example", + "client", + "other-nonce" + ) + .is_err() + ); + let (wrong_algorithm, _) = id_fixture(&claims, "RS256"); + assert!( + validate_id_token( + &wrong_algorithm, + &jwks, + "https://auth.example", + "client", + "nonce" + ) + .is_err() + ); + let mut bad_signature = valid.into_bytes(); + let last = bad_signature.last_mut().expect("token byte"); + *last = if *last == b'A' { b'B' } else { b'A' }; + assert!( + validate_id_token( + std::str::from_utf8(&bad_signature).expect("token"), + &jwks, + "https://auth.example", + "client", + "nonce" + ) + .is_err() + ); + } }