diff --git a/Cargo.lock b/Cargo.lock index d75a472eb..a49dda2a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -128,6 +128,7 @@ dependencies = [ "axum", "base64 0.22.1", "chrono", + "hmac", "openssl", "p256", "piquel-auth-protocol", diff --git a/Cargo.toml b/Cargo.toml index ecc1cb404..bfa20d010 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,12 +37,14 @@ axum = "0.8" base64 = "0.22" chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } http = "1.3" +hmac = "0.12" +http-body-util = "0.1" openssl = { version = "0.10", features = ["vendored"] } p256 = { version = "0.13", features = ["ecdsa", "pem", "pkcs8"] } +rand = "0.8" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sha2 = "0.10" -rand = "0.8" 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"] } diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index b63bf7130..f2dd434a7 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -17,13 +17,14 @@ async-trait.workspace = true axum.workspace = true base64.workspace = true chrono.workspace = true +hmac.workspace = true openssl.workspace = true p256.workspace = true rand.workspace = true serde.workspace = true serde_json.workspace = true -thiserror.workspace = true sha2.workspace = true +thiserror.workspace = true tokio.workspace = true tracing.workspace = true unicode-normalization.workspace = true diff --git a/apps/auth-service/src/account.rs b/apps/auth-service/src/account.rs index c4ad55b8c..d4fa87e3e 100644 --- a/apps/auth-service/src/account.rs +++ b/apps/auth-service/src/account.rs @@ -127,6 +127,7 @@ pub(super) async fn disable(database: &Database, user_id: UserId) -> Result, passkeys: Option) -> Router { +pub fn router( + readiness: Arc, + passkeys: Option, + oidc: Option, +) -> Router { let health = Router::new() .route("/health/live", get(|| async { StatusCode::NO_CONTENT })) .route("/health/ready", get(ready)) .with_state(AppState { readiness }); - if let Some(passkeys) = passkeys { + let router = passkeys.map_or(health.clone(), |passkeys| { health.merge(passkey::routes(passkeys)) - } else { - health - } + }); + oidc.map_or(router.clone(), |oidc| router.merge(oidc::routes(oidc))) } async fn ready(State(state): State) -> impl IntoResponse { @@ -155,7 +165,7 @@ mod tests { #[tokio::test] async fn liveness_has_no_dependencies_and_readiness_fails_closed() { - let app = router(Arc::new(FixedReadiness(false)), None); + let app = router(Arc::new(FixedReadiness(false)), None, None); let live = app .clone() .oneshot( @@ -179,7 +189,7 @@ mod tests { #[tokio::test] async fn readiness_succeeds_with_test_substitutes() { - let response = router(Arc::new(FixedReadiness(true)), None) + let response = router(Arc::new(FixedReadiness(true)), None, None) .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 bb5950aac..345f5bbd1 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -1,6 +1,8 @@ #![allow(missing_docs)] -use auth_service::{AuthConfig, Es256KeyProvider, PasskeyApplication, ProductionReadiness, router}; +use auth_service::{ + AuthConfig, Es256KeyProvider, OidcApplication, PasskeyApplication, ProductionReadiness, router, +}; use piquel_repository::Database; use std::{net::SocketAddr, sync::Arc}; @@ -11,16 +13,41 @@ 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 pem = std::str::from_utf8(key_secret.expose_secret()) - .map_err(|_| anyhow::anyhow!("signing key provider returned invalid data"))?; - let purpose_keys = Es256KeyProvider::from_pkcs8_pem(config.signing_key_id.clone(), pem) - .map_err(|()| anyhow::anyhow!("signing key provider returned an invalid ES256 key"))?; + let keys = if config.development_mode { + Arc::new(Es256KeyProvider::generate_for_development( + config.signing_key_id.clone(), + )) + } else { + let pem = std::str::from_utf8(key_secret.expose_secret()) + .map_err(|_| anyhow::anyhow!("signing key provider returned invalid data"))?; + Arc::new( + Es256KeyProvider::from_pkcs8_pem(config.signing_key_id.clone(), pem).map_err(|()| { + anyhow::anyhow!("signing key provider returned an invalid ES256 key") + })?, + ) + }; let passkeys = PasskeyApplication::new( database.clone(), &config.webauthn_rp_id, config.public_base_url.as_url(), - Arc::new(purpose_keys), + Arc::clone(&keys), )?; + let oidc = if config.development_mode { + OidcApplication::new_development( + database.clone(), + config.public_base_url.as_url(), + key_secret.expose_secret(), + keys, + ) + } else { + OidcApplication::new( + database.clone(), + config.public_base_url.as_url(), + key_secret.expose_secret(), + keys, + ) + } + .map_err(|()| anyhow::anyhow!("invalid OIDC configuration"))?; let listener = tokio::net::TcpListener::bind(listener_address).await?; tracing::info!(%listener_address, "auth service listening"); axum::serve( @@ -28,6 +55,7 @@ async fn main() -> anyhow::Result<()> { router( Arc::new(ProductionReadiness::new(database, config.key_provider)), Some(passkeys), + Some(oidc), ), ) .with_graceful_shutdown(shutdown_signal()) diff --git a/apps/auth-service/src/oidc.rs b/apps/auth-service/src/oidc.rs new file mode 100644 index 000000000..bda89e089 --- /dev/null +++ b/apps/auth-service/src/oidc.rs @@ -0,0 +1,928 @@ +//! Authorization Code + PKCE, ES256 tokens, and rotating opaque refresh tokens. + +use crate::Es256KeyProvider; +use axum::{ + Form, Json, Router, + extract::{Path, Query, State}, + http::{HeaderMap, StatusCode, header}, + response::{IntoResponse, Redirect, Response}, + routing::{get, post}, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::{Duration, Utc}; +use hmac::{Hmac, Mac}; +use piquel_auth_protocol::{SessionId, TokenId, UserId}; +use piquel_repository::{ + AppendAuditEvent, Database, InsertAuthorizationCode, InsertAuthorizationRequest, + InsertRefreshFamily, InsertRefreshToken, RefreshRotationError, StoredAuthorizationRequest, + StoredSession, +}; +use rand::{RngCore, rngs::OsRng}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{collections::BTreeSet, str::FromStr, sync::Arc}; +use thiserror::Error; +use url::Url; + +type HmacSha256 = Hmac; +const OPAQUE_SECRET_BYTES: usize = 32; +const ACCESS_TOKEN_SECONDS: i64 = 300; + +/// Supplies a stable active ES256 key and its public JWK. +pub trait KeyProvider: Send + Sync { + fn sign(&self, token_type: &str, claims: &Value) -> Result; + fn jwks(&self) -> Value; + fn verify_access(&self, token: &str, issuer: &str) -> Result; +} + +impl KeyProvider for Es256KeyProvider { + fn sign(&self, token_type: &str, claims: &Value) -> Result { + Es256KeyProvider::sign(self, token_type, claims) + } + + fn jwks(&self) -> Value { + self.public_jwks() + } + + fn verify_access(&self, token: &str, issuer: &str) -> Result { + let claims: Value = self.verify("at+jwt", token)?; + let now = Utc::now().timestamp(); + if claims.get("iss") != Some(&json!(issuer)) + || claims + .get("exp") + .and_then(Value::as_i64) + .is_none_or(|exp| exp <= now) + || claims + .get("iat") + .and_then(Value::as_i64) + .is_none_or(|iat| iat > now + 30) + { + return Err(()); + } + Ok(claims) + } +} + +/// Runnable OIDC application state. +#[derive(Clone)] +pub struct OidcApplication { + database: Database, + issuer: String, + refresh_key: Arc<[u8; 32]>, + keys: Arc, +} + +impl OidcApplication { + /// Constructs an OIDC endpoint set with an exact HTTPS issuer. + /// + /// # Errors + /// + /// Returns an error for an insecure issuer or insufficient key material. + #[allow(clippy::result_unit_err)] + pub fn new( + database: Database, + issuer: &Url, + secret: &[u8], + keys: Arc, + ) -> Result { + if issuer.scheme() != "https" + || issuer.query().is_some() + || issuer.fragment().is_some() + || secret.len() < 32 + { + return Err(()); + } + Self::build(database, issuer, secret, keys) + } + + /// Constructs an HTTP issuer only for an explicit loopback development configuration. + /// + /// # Errors + /// + /// Returns an error unless the issuer is loopback-only and key material is sufficient. + #[allow(clippy::result_unit_err)] + pub fn new_development( + database: Database, + issuer: &Url, + secret: &[u8], + keys: Arc, + ) -> Result { + let loopback = issuer.host_str().is_some_and(|host| { + host == "localhost" + || host + .parse::() + .is_ok_and(|ip| ip.is_loopback()) + }); + if !loopback + || !matches!(issuer.scheme(), "http" | "https") + || issuer.query().is_some() + || issuer.fragment().is_some() + || secret.len() < 32 + { + return Err(()); + } + Self::build(database, issuer, secret, keys) + } + + fn build( + database: Database, + issuer: &Url, + secret: &[u8], + keys: Arc, + ) -> Result { + let mut mac = HmacSha256::new_from_slice(secret).map_err(|_| ())?; + mac.update(b"piquel-refresh-token-digest-v1"); + let refresh_key = mac.finalize().into_bytes().into(); + Ok(Self { + database, + issuer: issuer.as_str().trim_end_matches('/').into(), + refresh_key: Arc::new(refresh_key), + keys, + }) + } +} + +pub(super) fn routes(application: OidcApplication) -> Router { + Router::new() + .route("/.well-known/openid-configuration", get(discovery)) + .route("/.well-known/jwks.json", get(jwks)) + .route("/oauth/authorize", get(authorize)) + .route( + "/oauth/authorize/transaction/{transaction}", + get(authorization_transaction), + ) + .route("/oauth/authorize/decision", post(authorization_decision)) + .route("/oauth/token", post(token)) + .route("/oauth/revoke", post(revoke)) + .route("/oidc/userinfo", get(userinfo)) + .route("/oidc/logout", post(logout)) + .with_state(application) +} + +async fn discovery(State(app): State) -> Json { + let base = &app.issuer; + Json(json!({ + "issuer":base, "authorization_endpoint":format!("{base}/oauth/authorize"), + "token_endpoint":format!("{base}/oauth/token"), "revocation_endpoint":format!("{base}/oauth/revoke"), + "userinfo_endpoint":format!("{base}/oidc/userinfo"), "jwks_uri":format!("{base}/.well-known/jwks.json"), + "end_session_endpoint":format!("{base}/oidc/logout"), "response_types_supported":["code"], + "grant_types_supported":["authorization_code","refresh_token"], "code_challenge_methods_supported":["S256"], + "token_endpoint_auth_methods_supported":["none"], "id_token_signing_alg_values_supported":["ES256"], + "scopes_supported":["openid","profile","email","offline_access"] + })) +} +async fn jwks(State(app): State) -> Json { + Json(app.keys.jwks()) +} + +#[derive(Deserialize)] +struct AuthorizeQuery { + response_type: String, + client_id: String, + redirect_uri: String, + scope: String, + state: String, + nonce: Option, + code_challenge: String, + code_challenge_method: String, + audience: String, + prompt: Option, + max_age: Option, +} + +async fn authorize( + State(app): State, + headers: HeaderMap, + Query(q): Query, +) -> Result { + let client = app + .database + .oidc() + .find_client(&q.client_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(ApiError::request)?; + if !client.enabled || !client.redirect_uris.contains(&q.redirect_uri) { + return Err(ApiError::request()); + } + let redirect = Url::parse(&q.redirect_uri).map_err(|_| ApiError::request())?; + let fail = |error: &str| redirect_error(&redirect, error, &q.state); + let challenge_valid = URL_SAFE_NO_PAD + .decode(&q.code_challenge) + .is_ok_and(|value| value.len() == 32); + if q.response_type != "code" + || q.state.is_empty() + || q.state.len() > 512 + || q.code_challenge_method != "S256" + || !challenge_valid + { + return Err(fail("invalid_request")); + } + let scopes = parse_scopes(&q.scope).ok_or_else(|| fail("invalid_scope"))?; + if !scopes + .iter() + .all(|scope| client.allowed_scopes.contains(scope)) + { + return Err(fail("invalid_scope")); + } + if !client.allowed_audiences.contains(&q.audience) { + return Err(fail("invalid_target")); + } + if scopes.contains("openid") && q.nonce.as_deref().is_none_or(str::is_empty) { + return Err(fail("invalid_request")); + } + if q.prompt + .as_deref() + .is_some_and(|value| !matches!(value, "none" | "login")) + { + return Err(fail("invalid_request")); + } + let session = browser_session(&app.database, &headers).await; + let requires_login = q.prompt.as_deref() == Some("login") + || session.is_none() + || q.max_age.is_some_and(|age| { + age < 0 + || session.as_ref().is_none_or(|session| { + Utc::now() + .signed_duration_since(session.authenticated_at) + .num_seconds() + > age + }) + }); + if q.prompt.as_deref() == Some("none") && requires_login { + return Err(fail("login_required")); + } + let (transaction, id, secret) = new_opaque("par_v1"); + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + app.database + .oidc() + .insert_authorization_request(&InsertAuthorizationRequest { + id, + secret_digest: digest.to_vec(), + client_id: q.client_id, + redirect_uri: q.redirect_uri, + client_state: q.state, + pkce_challenge: q.code_challenge, + nonce: q.nonce, + scopes: scopes.into_iter().collect(), + audience: q.audience, + force_login: q.prompt.as_deref() == Some("login"), + max_age: q.max_age, + expires_at: Utc::now() + Duration::minutes(10), + }) + .await + .map_err(|_| ApiError::server())?; + let page = if requires_login { "login" } else { "authorize" }; + Ok(Redirect::to(&format!( + "{}/{page}?transaction={transaction}", + app.issuer + ))) +} + +#[derive(Serialize)] +struct AuthorizationTransactionView { + client_name: String, + scopes: Vec, + audience: String, +} + +async fn authorization_transaction( + State(app): State, + headers: HeaderMap, + Path(transaction): Path, +) -> Result, ApiError> { + let session = browser_session(&app.database, &headers) + .await + .ok_or_else(ApiError::unauthorized)?; + let request = find_authorization_request(&app, &transaction).await?; + require_authorization_session(&request, &session)?; + Ok(Json(AuthorizationTransactionView { + client_name: request.client_display_name, + scopes: request.scopes, + audience: request.audience, + })) +} + +#[derive(Deserialize)] +struct AuthorizationDecision { + transaction: String, + decision: String, +} + +async fn authorization_decision( + State(app): State, + headers: HeaderMap, + Form(input): Form, +) -> Result { + require_same_origin(&app, &headers)?; + let session = browser_session(&app.database, &headers) + .await + .ok_or_else(ApiError::unauthorized)?; + let (id, secret) = parse_opaque("par_v1", &input.transaction)?; + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + let mut transaction = app.database.begin().await.map_err(|_| ApiError::server())?; + let request = transaction + .oidc() + .consume_authorization_request(id, &digest) + .await + .map_err(|_| ApiError::request())?; + require_authorization_session(&request, &session)?; + let mut redirect = Url::parse(&request.redirect_uri).map_err(|_| ApiError::server())?; + match input.decision.as_str() { + "deny" => { + redirect + .query_pairs_mut() + .append_pair("error", "access_denied") + .append_pair("state", &request.client_state); + } + "approve" => { + let user = transaction + .users() + .find_active_by_id_for_update(session.user_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(ApiError::unauthorized)?; + if user.id != session.user_id { + return Err(ApiError::unauthorized()); + } + let (code, code_id, code_secret) = new_opaque("pac_v1"); + let code_digest = keyed_digest(app.refresh_key.as_ref(), &code_secret)?; + transaction + .oidc() + .insert_code(&InsertAuthorizationCode { + id: code_id, + secret_digest: code_digest.to_vec(), + client_id: request.client_id, + user_id: session.user_id, + session_id: session.id, + redirect_uri: request.redirect_uri, + pkce_challenge: request.pkce_challenge, + nonce: request.nonce, + scopes: request.scopes, + audience: request.audience, + expires_at: Utc::now() + Duration::minutes(2), + }) + .await + .map_err(|_| ApiError::server())?; + redirect + .query_pairs_mut() + .append_pair("code", &code) + .append_pair("state", &request.client_state); + } + _ => return Err(ApiError::request()), + } + transaction.commit().await.map_err(|_| ApiError::server())?; + Ok(Redirect::to(redirect.as_str())) +} + +async fn find_authorization_request( + app: &OidcApplication, + value: &str, +) -> Result { + let (id, secret) = parse_opaque("par_v1", value)?; + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + app.database + .oidc() + .find_authorization_request(id, &digest) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(ApiError::request) +} + +fn require_authorization_session( + request: &StoredAuthorizationRequest, + session: &StoredSession, +) -> Result<(), ApiError> { + let newer_than_request = session.authenticated_at >= request.created_at; + let within_max_age = request.max_age.is_none_or(|age| { + age >= 0 + && Utc::now() + .signed_duration_since(session.authenticated_at) + .num_seconds() + <= age + }); + (!request.force_login || newer_than_request) + .then_some(()) + .filter(|()| within_max_age) + .ok_or_else(ApiError::unauthorized) +} + +#[derive(Deserialize)] +struct TokenForm { + grant_type: String, + client_id: String, + code: Option, + redirect_uri: Option, + code_verifier: Option, + refresh_token: Option, +} +#[derive(Serialize)] +struct TokenResponse { + access_token: String, + token_type: &'static str, + expires_in: i64, + scope: String, + #[serde(skip_serializing_if = "Option::is_none")] + id_token: Option, + #[serde(skip_serializing_if = "Option::is_none")] + refresh_token: Option, +} + +async fn token( + State(app): State, + Form(form): Form, +) -> Result, ApiError> { + match form.grant_type.as_str() { + "authorization_code" => exchange_code(&app, form).await.map(Json), + "refresh_token" => rotate_refresh(&app, form).await.map(Json), + _ => Err(ApiError::oauth("unsupported_grant_type")), + } +} + +async fn exchange_code(app: &OidcApplication, form: TokenForm) -> Result { + let (id, secret) = parse_opaque( + "pac_v1", + form.code + .as_deref() + .ok_or_else(|| ApiError::oauth("invalid_grant"))?, + )?; + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + let mut tx = app.database.begin().await.map_err(|_| ApiError::server())?; + let code = tx + .oidc() + .consume_code(id, &digest) + .await + .map_err(|_| ApiError::oauth("invalid_grant"))?; + if code.client_id != form.client_id + || form.redirect_uri.as_deref() != Some(&code.redirect_uri) + || validate_pkce_s256( + form.code_verifier.as_deref().unwrap_or_default(), + &code.pkce_challenge, + ) + .is_err() + { + return Err(ApiError::oauth("invalid_grant")); + } + let user = tx + .users() + .find_active_by_id_for_update(code.user_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let session = tx + .sessions() + .find_by_id(code.session_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let client = tx + .oidc() + .find_client(&form.client_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(|| ApiError::oauth("invalid_client"))?; + let tokens = issue_tokens( + app, + &client.id, + &code.audience, + &code.scopes, + code.nonce.as_deref(), + &user, + &session, + )?; + let refresh = + if client.allow_refresh && code.scopes.iter().any(|scope| scope == "offline_access") { + Some( + create_refresh( + &mut tx, + app, + code.user_id, + code.session_id, + client.id, + code.audience, + code.scopes, + ) + .await?, + ) + } else { + None + }; + tx.commit().await.map_err(|_| ApiError::server())?; + Ok(TokenResponse { + refresh_token: refresh, + ..tokens + }) +} + +async fn rotate_refresh(app: &OidcApplication, form: TokenForm) -> Result { + let (id, secret) = parse_opaque( + "prt_v1", + form.refresh_token + .as_deref() + .ok_or_else(|| ApiError::oauth("invalid_grant"))?, + )?; + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + let mut tx = app.database.begin().await.map_err(|_| ApiError::server())?; + let rotated = match tx.tokens().consume_for_rotation(id, &digest).await { + Ok(value) => value, + Err(RefreshRotationError::Replay { user_id }) => { + tx.audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: Some(user_id), + action: "refresh.replay".into(), + outcome: "rejected".into(), + request_metadata: json!({}), + }) + .await + .map_err(|_| ApiError::server())?; + tx.commit().await.map_err(|_| ApiError::server())?; + tracing::warn!( + event = "auth.refresh_replay", + "refresh token replay rejected" + ); + return Err(ApiError::oauth("invalid_grant")); + } + Err(RefreshRotationError::Policy { user_id }) => { + tx.audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: Some(user_id), + action: "refresh.policy_rejected".into(), + outcome: "rejected".into(), + request_metadata: json!({}), + }) + .await + .map_err(|_| ApiError::server())?; + tx.commit().await.map_err(|_| ApiError::server())?; + return Err(ApiError::oauth("invalid_grant")); + } + Err(RefreshRotationError::Invalid) => return Err(ApiError::oauth("invalid_grant")), + }; + if rotated.client_id != form.client_id { + return Err(ApiError::oauth("invalid_grant")); + } + let user = tx + .users() + .find_by_id(rotated.user_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let session = tx + .sessions() + .find_by_id(rotated.session_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let (raw, new_id, new_secret) = new_opaque("prt_v1"); + let new_digest = keyed_digest(app.refresh_key.as_ref(), &new_secret)?; + tx.tokens() + .insert_token(&InsertRefreshToken { + id: new_id, + family_id: rotated.family_id, + secret_digest: new_digest.to_vec(), + expires_at: Utc::now() + Duration::days(30), + }) + .await + .map_err(|_| ApiError::server())?; + let mut tokens = issue_tokens( + app, + &rotated.client_id, + &rotated.audience, + &rotated.scopes, + None, + &user, + &session, + )?; + tokens.refresh_token = Some(raw); + tx.commit().await.map_err(|_| ApiError::server())?; + Ok(tokens) +} + +async fn create_refresh( + tx: &mut piquel_repository::DatabaseTransaction<'_>, + app: &OidcApplication, + user_id: UserId, + session_id: SessionId, + client_id: String, + audience: String, + scopes: Vec, +) -> Result { + let family_id = TokenId::new(); + let (raw, id, secret) = new_opaque("prt_v1"); + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + tx.tokens() + .insert_family( + &InsertRefreshFamily { + id: family_id, + user_id, + client_id, + session_id, + audience, + scopes, + }, + &InsertRefreshToken { + id, + family_id, + secret_digest: digest.to_vec(), + expires_at: Utc::now() + Duration::days(30), + }, + ) + .await + .map_err(|_| ApiError::server())?; + Ok(raw) +} + +fn issue_tokens( + app: &OidcApplication, + client: &str, + audience: &str, + scopes: &[String], + nonce: Option<&str>, + user: &piquel_repository::StoredUser, + session: &StoredSession, +) -> Result { + let now = Utc::now().timestamp(); + let amr = &session.authentication_methods; + let access=app.keys.sign("at+jwt",&json!({"iss":app.issuer,"sub":user.id,"aud":audience,"client_id":client,"sid":session.id,"jti":TokenId::new(),"profile_version":user.profile_version,"preferred_username":user.username,"name":user.display_name,"amr":amr,"auth_time":session.authenticated_at.timestamp(),"scope":scopes.join(" "),"iat":now,"exp":now+ACCESS_TOKEN_SECONDS})).map_err(|()|ApiError::server())?; + let id_token = if scopes.iter().any(|s| s == "openid") { + Some(app.keys.sign("JWT",&json!({"iss":app.issuer,"sub":user.id,"aud":client,"sid":session.id,"nonce":nonce,"profile_version":user.profile_version,"preferred_username":user.username,"name":user.display_name,"auth_time":session.authenticated_at.timestamp(),"amr":amr,"iat":now,"exp":now+ACCESS_TOKEN_SECONDS})).map_err(|()|ApiError::server())?) + } else { + None + }; + Ok(TokenResponse { + access_token: access, + token_type: "Bearer", + expires_in: ACCESS_TOKEN_SECONDS, + scope: scopes.join(" "), + id_token, + refresh_token: None, + }) +} + +#[derive(Deserialize)] +struct RevokeForm { + token: String, +} +async fn revoke( + State(app): State, + Form(form): Form, +) -> Result { + if let Ok((id, secret)) = parse_opaque("prt_v1", &form.token) { + let digest = keyed_digest(app.refresh_key.as_ref(), &secret)?; + let mut tx = app.database.begin().await.map_err(|_| ApiError::server())?; + tx.tokens() + .revoke_family_for_token(id, &digest) + .await + .map_err(|_| ApiError::server())?; + tx.commit().await.map_err(|_| ApiError::server())?; + } + Ok(StatusCode::OK) +} + +async fn userinfo( + State(app): State, + headers: HeaderMap, +) -> Result, ApiError> { + let token = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .ok_or_else(ApiError::unauthorized)?; + let claims = app + .keys + .verify_access(token, &app.issuer) + .map_err(|()| ApiError::unauthorized())?; + let scopes: BTreeSet<_> = claims + .get("scope") + .and_then(Value::as_str) + .unwrap_or_default() + .split_ascii_whitespace() + .collect(); + if !scopes.contains("openid") { + return Err(ApiError::unauthorized()); + } + let mut response = json!({"sub":claims.get("sub")}); + if scopes.contains("profile") { + response["preferred_username"] = claims + .get("preferred_username") + .cloned() + .unwrap_or(Value::Null); + response["name"] = claims.get("name").cloned().unwrap_or(Value::Null); + response["profile_version"] = claims + .get("profile_version") + .cloned() + .unwrap_or(Value::Null); + } + Ok(Json(response)) +} + +#[derive(Deserialize)] +struct LogoutQuery { + client_id: Option, + post_logout_redirect_uri: Option, + state: Option, +} +async fn logout( + State(app): State, + headers: HeaderMap, + Form(q): Form, +) -> Result { + require_same_origin(&app, &headers)?; + if let Some(session) = browser_session(&app.database, &headers).await { + app.database + .sessions() + .revoke(session.id) + .await + .map_err(|_| ApiError::server())?; + } + if let (Some(client_id), Some(uri)) = (q.client_id, q.post_logout_redirect_uri) { + let client = app + .database + .oidc() + .find_client(&client_id) + .await + .map_err(|_| ApiError::server())? + .ok_or_else(ApiError::request)?; + if !client.post_logout_uris.contains(&uri) { + return Err(ApiError::request()); + } + let mut url = Url::parse(&uri).map_err(|_| ApiError::request())?; + if let Some(state) = q.state { + url.query_pairs_mut().append_pair("state", &state); + } + return Ok(Redirect::to(url.as_str()).into_response()); + } + Ok(StatusCode::NO_CONTENT.into_response()) +} + +fn require_same_origin(app: &OidcApplication, headers: &HeaderMap) -> Result<(), ApiError> { + let origin_matches = headers + .get(header::ORIGIN) + .and_then(|value| value.to_str().ok()) + .is_some_and(|origin| origin == app.issuer); + let csrf_header = headers + .get("x-piquel-csrf") + .and_then(|value| value.to_str().ok()) + == Some("1"); + (origin_matches && csrf_header) + .then_some(()) + .ok_or_else(ApiError::request) +} + +async fn browser_session(database: &Database, headers: &HeaderMap) -> Option { + let raw = headers + .get(header::COOKIE)? + .to_str() + .ok()? + .split(';') + .map(str::trim) + .find_map(|part| part.strip_prefix("__Host-piquel_session="))?; + let secret = URL_SAFE_NO_PAD.decode(raw).ok()?; + if secret.len() != OPAQUE_SECRET_BYTES { + return None; + } + let digest = Sha256::digest(secret); + database + .sessions() + .find_active_by_browser_secret(&digest) + .await + .ok() + .flatten() +} + +fn parse_scopes(value: &str) -> Option> { + let scopes: BTreeSet<_> = value.split_ascii_whitespace().map(str::to_owned).collect(); + (!scopes.is_empty() && scopes.len() <= 16).then_some(scopes) +} +fn new_opaque(prefix: &str) -> (String, TokenId, [u8; OPAQUE_SECRET_BYTES]) { + let id = TokenId::new(); + let mut secret = [0; OPAQUE_SECRET_BYTES]; + OsRng.fill_bytes(&mut secret); + ( + format!("{prefix}_{id}.{}", URL_SAFE_NO_PAD.encode(secret)), + id, + secret, + ) +} +fn parse_opaque( + prefix: &str, + value: &str, +) -> Result<(TokenId, [u8; OPAQUE_SECRET_BYTES]), ApiError> { + if value.len() > 160 { + return Err(ApiError::oauth("invalid_grant")); + } + let rest = value + .strip_prefix(&format!("{prefix}_")) + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let (id, secret) = rest + .split_once('.') + .ok_or_else(|| ApiError::oauth("invalid_grant"))?; + let id = TokenId::from_str(id).map_err(|_| ApiError::oauth("invalid_grant"))?; + let decoded = URL_SAFE_NO_PAD + .decode(secret) + .map_err(|_| ApiError::oauth("invalid_grant"))?; + let secret: [u8; OPAQUE_SECRET_BYTES] = decoded + .try_into() + .map_err(|_| ApiError::oauth("invalid_grant"))?; + Ok((id, secret)) +} +fn keyed_digest(key: &[u8], secret: &[u8]) -> Result<[u8; 32], ApiError> { + let mut mac = HmacSha256::new_from_slice(key).map_err(|_| ApiError::server())?; + mac.update(secret); + Ok(mac.finalize().into_bytes().into()) +} +fn validate_pkce_s256(verifier: &str, challenge: &str) -> Result<(), ()> { + if !(43..=128).contains(&verifier.len()) + || !verifier + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')) + { + return Err(()); + } + (URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) == challenge) + .then_some(()) + .ok_or(()) +} +fn redirect_error(base: &Url, error: &str, state: &str) -> ApiError { + let mut url = base.clone(); + url.query_pairs_mut() + .append_pair("error", error) + .append_pair("state", state); + ApiError( + StatusCode::FOUND, + json!({"error":error}), + Some(url.to_string()), + ) +} + +#[derive(Debug, Error)] +#[error("OIDC request failed")] +struct ApiError(StatusCode, Value, Option); +impl ApiError { + fn request() -> Self { + Self( + StatusCode::BAD_REQUEST, + json!({"error":"invalid_request"}), + None, + ) + } + fn oauth(code: &str) -> Self { + Self(StatusCode::BAD_REQUEST, json!({"error":code}), None) + } + fn unauthorized() -> Self { + Self( + StatusCode::UNAUTHORIZED, + json!({"error":"invalid_token"}), + None, + ) + } + fn server() -> Self { + Self( + StatusCode::INTERNAL_SERVER_ERROR, + json!({"error":"server_error"}), + None, + ) + } +} +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + if let Some(location) = self.2 { + return Redirect::to(&location).into_response(); + } + (self.0, Json(self.1)).into_response() + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn exact_redirect_and_pkce_and_refresh_bounds() { + let registered = ["https://a.example/cb".to_owned()]; + assert!(!registered.contains(&"https://a.example/cb.evil".to_owned())); + assert!(validate_pkce_s256("short", "x").is_err()); + let huge = format!("prt_v1_{}.{:0200}", TokenId::new(), "x"); + assert!(parse_opaque("prt_v1", &huge).is_err()); + } + #[test] + fn jwt_types_are_cryptographically_distinct() { + let keys = Es256KeyProvider::generate_for_development("test"); + let now = Utc::now().timestamp(); + let id = keys + .sign( + "JWT", + &json!({"iss":"https://issuer","exp":now+60,"iat":now}), + ) + .expect("sign"); + assert!(keys.verify_access(&id, "https://issuer").is_err()); + let access = keys + .sign( + "at+jwt", + &json!({"iss":"https://issuer","exp":now+60,"iat":now}), + ) + .expect("sign"); + assert!(keys.verify_access(&access, "https://issuer").is_ok()); + } +} diff --git a/apps/auth-service/src/signing.rs b/apps/auth-service/src/signing.rs index fda48d206..499549141 100644 --- a/apps/auth-service/src/signing.rs +++ b/apps/auth-service/src/signing.rs @@ -8,7 +8,6 @@ use p256::{ }, pkcs8::DecodePrivateKey, }; -#[cfg(test)] use rand::rngs::OsRng; use serde::{Serialize, de::DeserializeOwned}; use serde_json::json; @@ -37,16 +36,21 @@ impl Es256KeyProvider { }) } - /// Generates an ephemeral key for tests only. - #[cfg(test)] + /// Generates an ephemeral key for explicit development and tests only. #[must_use] - pub(crate) fn generate_for_tests(kid: impl Into) -> Self { + pub fn generate_for_development(kid: impl Into) -> Self { Self { kid: kid.into(), signing: SigningKey::random(&mut OsRng), } } + #[cfg(test)] + #[must_use] + pub(crate) fn generate_for_tests(kid: impl Into) -> Self { + Self::generate_for_development(kid) + } + pub(crate) fn sign(&self, token_type: &str, claims: &T) -> Result { let header = URL_SAFE_NO_PAD.encode( serde_json::to_vec(&json!({ @@ -101,6 +105,15 @@ impl Es256KeyProvider { serde_json::from_slice(&URL_SAFE_NO_PAD.decode(claims_part).map_err(|_| ())?) .map_err(|_| ()) } + + pub(crate) fn public_jwks(&self) -> serde_json::Value { + let point = self.signing.verifying_key().to_encoded_point(false); + json!({"keys":[{ + "kty":"EC", "crv":"P-256", "use":"sig", "alg":"ES256", "kid":self.kid, + "x":URL_SAFE_NO_PAD.encode(point.x().expect("uncompressed point")), + "y":URL_SAFE_NO_PAD.encode(point.y().expect("uncompressed point")) + }]}) + } } #[cfg(test)] diff --git a/crates/database/migrations/0004_oidc_tokens.sql b/crates/database/migrations/0004_oidc_tokens.sql new file mode 100644 index 000000000..1f118b16c --- /dev/null +++ b/crates/database/migrations/0004_oidc_tokens.sql @@ -0,0 +1,71 @@ +CREATE TABLE oidc_clients ( + id TEXT PRIMARY KEY, + display_name TEXT NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + token_endpoint_auth_method TEXT NOT NULL DEFAULT 'none' CHECK (token_endpoint_auth_method IN ('none')), + allowed_scopes JSONB NOT NULL, + allowed_audiences JSONB NOT NULL, + allow_refresh BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE TABLE oidc_redirect_uris ( + client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE, + uri TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('authorization', 'post_logout')), + PRIMARY KEY (client_id, uri, kind) +); + +CREATE TABLE authorization_codes ( + id UUID PRIMARY KEY, + secret_digest BYTEA NOT NULL UNIQUE, + client_id TEXT NOT NULL REFERENCES oidc_clients(id), + user_id UUID NOT NULL REFERENCES users(id), + session_id UUID NOT NULL REFERENCES sessions(id), + redirect_uri TEXT NOT NULL, + pkce_challenge TEXT NOT NULL, + nonce TEXT, + scopes JSONB NOT NULL, + audience TEXT NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX authorization_codes_active_idx ON authorization_codes (expires_at) WHERE consumed_at IS NULL; + +CREATE TABLE authorization_requests ( + id UUID PRIMARY KEY, + secret_digest BYTEA NOT NULL UNIQUE, + client_id TEXT NOT NULL REFERENCES oidc_clients(id), + redirect_uri TEXT NOT NULL, + client_state TEXT NOT NULL, + nonce TEXT, + pkce_challenge TEXT NOT NULL, + scopes JSONB NOT NULL, + audience TEXT NOT NULL, + force_login BOOLEAN NOT NULL, + max_age BIGINT, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX authorization_requests_active_idx ON authorization_requests (expires_at) WHERE consumed_at IS NULL; + +CREATE TABLE refresh_token_families ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id), + client_id TEXT NOT NULL REFERENCES oidc_clients(id), + session_id UUID NOT NULL REFERENCES sessions(id), + audience TEXT NOT NULL, + scopes JSONB NOT NULL, + revoked_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE TABLE refresh_tokens ( + id UUID PRIMARY KEY, + family_id UUID NOT NULL REFERENCES refresh_token_families(id) ON DELETE CASCADE, + secret_digest BYTEA NOT NULL UNIQUE, + expires_at TIMESTAMPTZ NOT NULL, + issued_at TIMESTAMPTZ NOT NULL DEFAULT now(), + consumed_at TIMESTAMPTZ +); +CREATE INDEX refresh_tokens_family_idx ON refresh_tokens (family_id); diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs index c1645f99e..d6f64d7b0 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -111,6 +111,123 @@ pub struct ConsumedCeremony { pub session_id: Option, pub state: Value, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredOidcClient { + pub id: String, + pub display_name: String, + pub enabled: bool, + pub redirect_uris: Vec, + pub post_logout_uris: Vec, + pub allowed_scopes: Vec, + pub allowed_audiences: Vec, + pub allow_refresh: bool, +} + +#[derive(Clone, Debug)] +pub struct InsertAuthorizationRequest { + pub id: TokenId, + pub secret_digest: Vec, + pub client_id: String, + pub redirect_uri: String, + pub client_state: String, + pub nonce: Option, + pub pkce_challenge: String, + pub scopes: Vec, + pub audience: String, + pub force_login: bool, + pub max_age: Option, + pub expires_at: DateTime, +} + +#[derive(Clone, Debug)] +pub struct StoredAuthorizationRequest { + pub id: TokenId, + pub client_id: String, + pub client_display_name: String, + pub redirect_uri: String, + pub client_state: String, + pub nonce: Option, + pub pkce_challenge: String, + pub scopes: Vec, + pub audience: String, + pub force_login: bool, + pub max_age: Option, + pub created_at: DateTime, +} + +#[derive(Clone, Debug)] +pub struct BootstrapOidcClient { + pub id: String, + pub display_name: String, + pub redirect_uris: Vec, + pub post_logout_uris: Vec, + pub allowed_scopes: Vec, + pub allowed_audiences: Vec, + pub allow_refresh: bool, +} + +#[derive(Clone, Debug)] +pub struct InsertAuthorizationCode { + pub id: TokenId, + pub secret_digest: Vec, + pub client_id: String, + pub user_id: UserId, + pub session_id: SessionId, + pub redirect_uri: String, + pub pkce_challenge: String, + pub nonce: Option, + pub scopes: Vec, + pub audience: String, + pub expires_at: DateTime, +} + +#[derive(Clone, Debug)] +pub struct ConsumedAuthorizationCode { + pub client_id: String, + pub user_id: UserId, + pub session_id: SessionId, + pub redirect_uri: String, + pub pkce_challenge: String, + pub nonce: Option, + pub scopes: Vec, + pub audience: String, +} + +#[derive(Clone, Debug)] +pub struct InsertRefreshFamily { + pub id: TokenId, + pub user_id: UserId, + pub client_id: String, + pub session_id: SessionId, + pub audience: String, + pub scopes: Vec, +} + +#[derive(Clone, Debug)] +pub struct InsertRefreshToken { + pub id: TokenId, + pub family_id: TokenId, + pub secret_digest: Vec, + pub expires_at: DateTime, +} + +#[derive(Clone, Debug)] +pub struct RotatedRefreshToken { + pub family_id: TokenId, + pub user_id: UserId, + pub client_id: String, + pub session_id: SessionId, + pub audience: String, + pub scopes: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RefreshRotationError { + Invalid, + Replay { user_id: UserId }, + Policy { user_id: UserId }, +} + #[derive(Clone, Debug)] pub struct InsertPurposeAuthorization { pub id: TokenId, diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index 4b1e9679a..f46192164 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -1,9 +1,12 @@ //! Domain repository handles backed by a private pool or transaction connection. use crate::{ - AppendAuditEvent, AppendInternalEvent, ConsumedCeremony, DatabaseError, InsertCeremony, - InsertPasskey, InsertPurposeAuthorization, InsertSession, InsertUser, InsertVerifiedEmail, - StoredEmail, StoredPasskey, StoredSession, StoredUser, UpdateUserProfile, + AppendAuditEvent, AppendInternalEvent, BootstrapOidcClient, ConsumedAuthorizationCode, + ConsumedCeremony, DatabaseError, InsertAuthorizationCode, InsertAuthorizationRequest, + InsertCeremony, InsertPasskey, InsertPurposeAuthorization, InsertRefreshFamily, + InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, RefreshRotationError, + RotatedRefreshToken, StoredAuthorizationRequest, StoredEmail, StoredOidcClient, StoredPasskey, + StoredSession, StoredUser, UpdateUserProfile, }; use piquel_auth_protocol::{AccountStatus, SessionId, TokenId, UserId}; use sqlx::{PgConnection, PgPool, Row}; @@ -122,6 +125,12 @@ impl UserRepository<'_> { pub async fn find_by_id(&mut self, id: UserId) -> Result, DatabaseError> { fetch_optional!(self, sqlx::query("SELECT id, username, display_name, profile_version, status, created_at, updated_at FROM users WHERE id = $1").bind(id.as_uuid()))?.map(|row| stored_user(&row)).transpose() } + pub async fn find_active_by_id_for_update( + &mut self, + id: UserId, + ) -> Result, DatabaseError> { + fetch_optional!(self, sqlx::query("SELECT id, username, display_name, profile_version, status, created_at, updated_at FROM users WHERE id = $1 AND status='active' FOR UPDATE").bind(id.as_uuid()))?.map(|row| stored_user(&row)).transpose() + } pub async fn find_active_by_username( &mut self, username: &str, @@ -264,6 +273,337 @@ impl SessionRepository<'_> { .rows_affected()) } } + +impl OidcRepository<'_> { + /// Idempotently provisions a statically reviewed public client and exact URI allowlists. + pub async fn bootstrap_client( + &mut self, + input: &BootstrapOidcClient, + ) -> Result<(), DatabaseError> { + validate_bootstrap_client(input)?; + let scopes = + serde_json::to_value(&input.allowed_scopes).map_err(|_| DatabaseError::Internal)?; + let audiences = + serde_json::to_value(&input.allowed_audiences).map_err(|_| DatabaseError::Internal)?; + execute!(self, sqlx::query("WITH upsert AS (INSERT INTO oidc_clients(id,display_name,allowed_scopes,allowed_audiences,allow_refresh) VALUES($1,$2,$3,$4,$5) ON CONFLICT(id) DO UPDATE SET display_name=EXCLUDED.display_name,allowed_scopes=EXCLUDED.allowed_scopes,allowed_audiences=EXCLUDED.allowed_audiences,allow_refresh=EXCLUDED.allow_refresh RETURNING id), desired(uri,kind) AS (SELECT unnest($6::text[]),'authorization' UNION ALL SELECT unnest($7::text[]),'post_logout'), inserted AS (INSERT INTO oidc_redirect_uris(client_id,uri,kind) SELECT $1,d.uri,d.kind FROM desired d,upsert ON CONFLICT DO NOTHING RETURNING uri), removed AS (DELETE FROM oidc_redirect_uris r WHERE r.client_id=$1 AND NOT EXISTS (SELECT 1 FROM desired d WHERE d.uri=r.uri AND d.kind=r.kind) RETURNING uri) SELECT id FROM upsert") + .bind(&input.id).bind(&input.display_name).bind(scopes).bind(audiences).bind(input.allow_refresh).bind(&input.redirect_uris).bind(&input.post_logout_uris))?; + Ok(()) + } + + pub async fn find_client( + &mut self, + id: &str, + ) -> Result, DatabaseError> { + let row = fetch_optional!(self, sqlx::query("SELECT c.id,c.display_name,c.enabled,c.allowed_scopes,c.allowed_audiences,c.allow_refresh,COALESCE(jsonb_agg(r.uri) FILTER (WHERE r.kind='authorization'),'[]'::jsonb) AS redirect_uris,COALESCE(jsonb_agg(r.uri) FILTER (WHERE r.kind='post_logout'),'[]'::jsonb) AS post_logout_uris FROM oidc_clients c LEFT JOIN oidc_redirect_uris r ON r.client_id=c.id WHERE c.id=$1 GROUP BY c.id").bind(id))?; + row.map(|row| { + let strings = |column| -> Result, DatabaseError> { + serde_json::from_value( + row.try_get(column) + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData) + }; + Ok(StoredOidcClient { + id: row + .try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + display_name: row + .try_get("display_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + enabled: row + .try_get("enabled") + .map_err(|_| DatabaseError::InvalidStoredData)?, + redirect_uris: strings("redirect_uris")?, + post_logout_uris: strings("post_logout_uris")?, + allowed_scopes: strings("allowed_scopes")?, + allowed_audiences: strings("allowed_audiences")?, + allow_refresh: row + .try_get("allow_refresh") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + }) + .transpose() + } + + pub async fn insert_code( + &mut self, + input: &InsertAuthorizationCode, + ) -> Result<(), DatabaseError> { + let scopes = serde_json::to_value(&input.scopes).map_err(|_| DatabaseError::Internal)?; + execute!(self, sqlx::query("INSERT INTO authorization_codes(id,secret_digest,client_id,user_id,session_id,redirect_uri,pkce_challenge,nonce,scopes,audience,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)") + .bind(input.id.as_uuid()).bind(&input.secret_digest).bind(&input.client_id) + .bind(input.user_id.as_uuid()).bind(input.session_id.as_uuid()).bind(&input.redirect_uri) + .bind(&input.pkce_challenge).bind(&input.nonce).bind(scopes).bind(&input.audience).bind(input.expires_at))?; + Ok(()) + } + + pub async fn insert_authorization_request( + &mut self, + input: &InsertAuthorizationRequest, + ) -> Result<(), DatabaseError> { + let scopes = serde_json::to_value(&input.scopes).map_err(|_| DatabaseError::Internal)?; + execute!(self, sqlx::query("INSERT INTO authorization_requests(id,secret_digest,client_id,redirect_uri,client_state,nonce,pkce_challenge,scopes,audience,force_login,max_age,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)") + .bind(input.id.as_uuid()).bind(&input.secret_digest).bind(&input.client_id) + .bind(&input.redirect_uri).bind(&input.client_state).bind(&input.nonce) + .bind(&input.pkce_challenge).bind(scopes).bind(&input.audience) + .bind(input.force_login).bind(input.max_age).bind(input.expires_at))?; + Ok(()) + } + + pub async fn find_authorization_request( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result, DatabaseError> { + fetch_optional!(self, sqlx::query("SELECT r.id,r.client_id,c.display_name AS client_display_name,r.redirect_uri,r.client_state,r.nonce,r.pkce_challenge,r.scopes,r.audience,r.force_login,r.max_age,r.created_at FROM authorization_requests r JOIN oidc_clients c ON c.id=r.client_id WHERE r.id=$1 AND r.secret_digest=$2 AND r.consumed_at IS NULL AND r.expires_at>now() AND c.enabled").bind(id.as_uuid()).bind(digest))?.map(|row| stored_authorization_request(&row)).transpose() + } + + pub async fn consume_authorization_request( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result { + let row = fetch_optional!(self, sqlx::query("UPDATE authorization_requests r SET consumed_at=now() FROM oidc_clients c WHERE r.id=$1 AND r.secret_digest=$2 AND r.consumed_at IS NULL AND r.expires_at>now() AND c.id=r.client_id AND c.enabled RETURNING r.id,r.client_id,c.display_name AS client_display_name,r.redirect_uri,r.client_state,r.nonce,r.pkce_challenge,r.scopes,r.audience,r.force_login,r.max_age,r.created_at").bind(id.as_uuid()).bind(digest))?.ok_or(DatabaseError::NotFound)?; + stored_authorization_request(&row) + } + + pub async fn consume_code( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result { + let row = fetch_optional!(self, sqlx::query("UPDATE authorization_codes c SET consumed_at=now() FROM oidc_clients cl,sessions s,users u WHERE c.id=$1 AND c.secret_digest=$2 AND c.consumed_at IS NULL AND c.expires_at>now() AND cl.id=c.client_id AND cl.enabled AND s.id=c.session_id AND s.revoked_at IS NULL AND s.expires_at>now() AND u.id=c.user_id AND u.status='active' RETURNING c.client_id,c.user_id,c.session_id,c.redirect_uri,c.pkce_challenge,c.nonce,c.scopes,c.audience").bind(id.as_uuid()).bind(digest))?.ok_or(DatabaseError::NotFound)?; + Ok(ConsumedAuthorizationCode { + client_id: row + .try_get("client_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + user_id: UserId::from_uuid( + row.try_get("user_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + session_id: SessionId::from_uuid( + row.try_get("session_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + redirect_uri: row + .try_get("redirect_uri") + .map_err(|_| DatabaseError::InvalidStoredData)?, + pkce_challenge: row + .try_get("pkce_challenge") + .map_err(|_| DatabaseError::InvalidStoredData)?, + nonce: row + .try_get("nonce") + .map_err(|_| DatabaseError::InvalidStoredData)?, + scopes: serde_json::from_value( + row.try_get("scopes") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + audience: row + .try_get("audience") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + } +} + +fn validate_bootstrap_client(input: &BootstrapOidcClient) -> Result<(), DatabaseError> { + let identifier = |value: &str| { + (1..=64).contains(&value.len()) + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + }; + let redirect = |value: &str| { + url::Url::parse(value).is_ok_and(|url| { + url.scheme() == "https" + && url.host_str().is_some() + && url.username().is_empty() + && url.password().is_none() + && url.fragment().is_none() + }) + }; + let valid = identifier(&input.id) + && !input.display_name.trim().is_empty() + && input.display_name.chars().count() <= 80 + && !input.redirect_uris.is_empty() + && input.redirect_uris.len() <= 16 + && input.post_logout_uris.len() <= 16 + && input.redirect_uris.iter().all(|uri| redirect(uri)) + && input.post_logout_uris.iter().all(|uri| redirect(uri)) + && !input.allowed_scopes.is_empty() + && input.allowed_scopes.len() <= 32 + && input.allowed_scopes.iter().all(|scope| identifier(scope)) + && !input.allowed_audiences.is_empty() + && input.allowed_audiences.len() <= 16 + && input + .allowed_audiences + .iter() + .all(|audience| identifier(audience)); + valid.then_some(()).ok_or(DatabaseError::Conflict) +} + +fn stored_authorization_request( + row: &sqlx::postgres::PgRow, +) -> Result { + Ok(StoredAuthorizationRequest { + id: TokenId::from_uuid( + row.try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + client_id: row + .try_get("client_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + client_display_name: row + .try_get("client_display_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + redirect_uri: row + .try_get("redirect_uri") + .map_err(|_| DatabaseError::InvalidStoredData)?, + client_state: row + .try_get("client_state") + .map_err(|_| DatabaseError::InvalidStoredData)?, + nonce: row + .try_get("nonce") + .map_err(|_| DatabaseError::InvalidStoredData)?, + pkce_challenge: row + .try_get("pkce_challenge") + .map_err(|_| DatabaseError::InvalidStoredData)?, + scopes: serde_json::from_value( + row.try_get("scopes") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + audience: row + .try_get("audience") + .map_err(|_| DatabaseError::InvalidStoredData)?, + force_login: row + .try_get("force_login") + .map_err(|_| DatabaseError::InvalidStoredData)?, + max_age: row + .try_get("max_age") + .map_err(|_| DatabaseError::InvalidStoredData)?, + created_at: row + .try_get("created_at") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) +} + +impl TokenRepository<'_> { + pub async fn insert_family( + &mut self, + family: &InsertRefreshFamily, + token: &InsertRefreshToken, + ) -> Result<(), DatabaseError> { + let scopes = serde_json::to_value(&family.scopes).map_err(|_| DatabaseError::Internal)?; + execute!(self, sqlx::query("INSERT INTO refresh_token_families(id,user_id,client_id,session_id,audience,scopes) VALUES($1,$2,$3,$4,$5,$6)") + .bind(family.id.as_uuid()).bind(family.user_id.as_uuid()).bind(&family.client_id) + .bind(family.session_id.as_uuid()).bind(&family.audience).bind(scopes))?; + self.insert_token(token).await + } + + pub async fn insert_token(&mut self, token: &InsertRefreshToken) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("INSERT INTO refresh_tokens(id,family_id,secret_digest,expires_at) VALUES($1,$2,$3,$4)") + .bind(token.id.as_uuid()).bind(token.family_id.as_uuid()).bind(&token.secret_digest).bind(token.expires_at))?; + Ok(()) + } + + pub async fn consume_for_rotation( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result { + let row = fetch_optional!(self, sqlx::query("SELECT t.family_id,t.consumed_at,f.user_id,f.client_id,f.session_id,f.audience,f.scopes,c.allow_refresh,c.allowed_scopes,c.allowed_audiences FROM refresh_tokens t JOIN refresh_token_families f ON f.id=t.family_id JOIN oidc_clients c ON c.id=f.client_id JOIN sessions s ON s.id=f.session_id JOIN users u ON u.id=f.user_id WHERE t.id=$1 AND t.secret_digest=$2 AND t.expires_at>now() AND f.revoked_at IS NULL AND c.enabled AND s.revoked_at IS NULL AND s.expires_at>now() AND u.status='active' FOR UPDATE OF t,f,c,s,u").bind(id.as_uuid()).bind(digest)).map_err(|_| RefreshRotationError::Invalid)?.ok_or(RefreshRotationError::Invalid)?; + let family_uuid: uuid::Uuid = row + .try_get("family_id") + .map_err(|_| RefreshRotationError::Invalid)?; + let user_id = UserId::from_uuid( + row.try_get("user_id") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?; + if row + .try_get::>, _>("consumed_at") + .map_err(|_| RefreshRotationError::Invalid)? + .is_some() + { + execute!(self, sqlx::query("UPDATE refresh_token_families SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL").bind(family_uuid)).map_err(|_| RefreshRotationError::Invalid)?; + return Err(RefreshRotationError::Replay { user_id }); + } + let family_scopes: Vec = serde_json::from_value( + row.try_get("scopes") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?; + let allowed_scopes: Vec = serde_json::from_value( + row.try_get("allowed_scopes") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?; + let allowed_audiences: Vec = serde_json::from_value( + row.try_get("allowed_audiences") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?; + let audience: String = row + .try_get("audience") + .map_err(|_| RefreshRotationError::Invalid)?; + let policy_valid = row + .try_get::("allow_refresh") + .map_err(|_| RefreshRotationError::Invalid)? + && allowed_audiences.contains(&audience) + && family_scopes + .iter() + .all(|scope| allowed_scopes.contains(scope)); + if !policy_valid { + execute!(self, sqlx::query("UPDATE refresh_token_families SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL").bind(family_uuid)).map_err(|_| RefreshRotationError::Invalid)?; + return Err(RefreshRotationError::Policy { user_id }); + } + if execute!( + self, + sqlx::query( + "UPDATE refresh_tokens SET consumed_at=now() WHERE id=$1 AND consumed_at IS NULL" + ) + .bind(id.as_uuid()) + ) + .map_err(|_| RefreshRotationError::Invalid)? + .rows_affected() + != 1 + { + return Err(RefreshRotationError::Invalid); + } + Ok(RotatedRefreshToken { + family_id: TokenId::from_uuid(family_uuid) + .map_err(|_| RefreshRotationError::Invalid)?, + user_id, + client_id: row + .try_get("client_id") + .map_err(|_| RefreshRotationError::Invalid)?, + session_id: SessionId::from_uuid( + row.try_get("session_id") + .map_err(|_| RefreshRotationError::Invalid)?, + ) + .map_err(|_| RefreshRotationError::Invalid)?, + audience, + scopes: family_scopes, + }) + } + + pub async fn revoke_family_for_token( + &mut self, + id: TokenId, + digest: &[u8], + ) -> Result<(), DatabaseError> { + execute!(self, sqlx::query("UPDATE refresh_token_families f SET revoked_at=COALESCE(revoked_at,now()) FROM refresh_tokens t WHERE t.id=$1 AND t.secret_digest=$2 AND t.family_id=f.id").bind(id.as_uuid()).bind(digest))?; + Ok(()) + } + + pub async fn revoke_all_for_user(&mut self, user_id: UserId) -> Result { + Ok(execute!(self, sqlx::query("UPDATE refresh_token_families SET revoked_at=now() WHERE user_id=$1 AND revoked_at IS NULL").bind(user_id.as_uuid()))?.rows_affected()) + } +} fn stored_session(row: &sqlx::postgres::PgRow) -> Result { let methods: serde_json::Value = row .try_get("authentication_methods") diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index c5e4a76d7..61dee5067 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -3,8 +3,10 @@ use chrono::{Duration as ChronoDuration, Utc}; use piquel_auth_protocol::{AccountStatus, AuthenticationMethod, SessionId, TokenId, UserId}; use piquel_repository::{ - AppendInternalEvent, Database, DatabaseConfig, DatabaseError, InsertCeremony, InsertPasskey, - InsertPurposeAuthorization, InsertSession, InsertUser, InsertVerifiedEmail, UpdateUserProfile, + AppendInternalEvent, BootstrapOidcClient, Database, DatabaseConfig, DatabaseError, + InsertCeremony, InsertPasskey, InsertPurposeAuthorization, InsertRefreshFamily, + InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, RefreshRotationError, + UpdateUserProfile, }; use std::{env, time::Duration}; @@ -180,6 +182,92 @@ async fn identity_transactions_and_concurrency_hold() { ); assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); + let refresh_session = SessionId::new(); + database + .sessions() + .insert(&InsertSession { + id: refresh_session, + user_id: first, + authentication_methods: vec![AuthenticationMethod::Passkey], + authenticated_at: Utc::now(), + expires_at: Utc::now() + ChronoDuration::hours(1), + user_agent_family: None, + }) + .await + .expect("refresh session"); + let mut setup = database.begin().await.expect("OIDC setup"); + setup + .oidc() + .bootstrap_client(&BootstrapOidcClient { + id: "test-client".into(), + display_name: "Test".into(), + redirect_uris: vec!["https://client.example/callback".into()], + post_logout_uris: vec!["https://client.example/logout".into()], + allowed_scopes: vec!["openid".into(), "offline_access".into()], + allowed_audiences: vec!["test-api".into()], + allow_refresh: true, + }) + .await + .expect("client"); + let family_id = TokenId::new(); + let refresh_id = TokenId::new(); + let digest = vec![9_u8; 32]; + setup + .tokens() + .insert_family( + &InsertRefreshFamily { + id: family_id, + user_id: first, + client_id: "test-client".into(), + session_id: refresh_session, + audience: "test-api".into(), + scopes: vec!["openid".into()], + }, + &InsertRefreshToken { + id: refresh_id, + family_id, + secret_digest: digest.clone(), + expires_at: Utc::now() + ChronoDuration::days(1), + }, + ) + .await + .expect("refresh family"); + setup.commit().await.expect("OIDC setup commit"); + 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 { + Ok(token) => { + tx.tokens() + .insert_token(&InsertRefreshToken { + id: replacement, + family_id: token.family_id, + secret_digest: vec![replacement.as_uuid().as_bytes()[0]; 32], + expires_at: Utc::now() + ChronoDuration::days(1), + }) + .await + .expect("replacement"); + tx.commit().await.expect("rotation commit"); + Ok(replacement) + } + Err(error @ RefreshRotationError::Replay { .. }) => { + tx.commit().await.expect("persist replay revocation"); + Err(error) + } + Err(error) => Err(error), + } + }; + let replacement_one = TokenId::new(); + let replacement_two = TokenId::new(); + let (left, right) = tokio::join!( + rotate(database.clone(), replacement_one, digest.clone()), + rotate(database.clone(), replacement_two, digest), + ); + assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); + assert!( + matches!(left, Err(RefreshRotationError::Replay { .. })) + || matches!(right, Err(RefreshRotationError::Replay { .. })) + ); + let credential_id = vec![7_u8; 32]; database .passkeys()