diff --git a/Cargo.lock b/Cargo.lock index 138fa06c9..f374320cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -129,6 +129,7 @@ dependencies = [ "base64 0.22.1", "chrono", "hmac", + "jsonwebtoken", "openssl", "p256", "piquel-auth-protocol", @@ -136,6 +137,7 @@ dependencies = [ "piquel-repository", "piquel-telemetry", "rand 0.8.7", + "reqwest", "serde", "serde_json", "sha2", @@ -1131,6 +1133,21 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -1455,6 +1472,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -2132,6 +2159,18 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror 2.0.18", + "time", +] + [[package]] name = "slab" version = "0.4.12" diff --git a/Cargo.toml b/Cargo.toml index 4b033658c..2f8fbf05c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "serd http = "1.3" hmac = "0.12" http-body-util = "0.1" +jsonwebtoken = "9.3" openssl = { version = "0.10", features = ["vendored"] } p256 = { version = "0.13", features = ["ecdsa", "pem", "pkcs8"] } rand = "0.8" diff --git a/apps/auth-service/Cargo.toml b/apps/auth-service/Cargo.toml index f2dd434a7..0765a4259 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -18,12 +18,14 @@ axum.workspace = true base64.workspace = true chrono.workspace = true hmac.workspace = true +jsonwebtoken.workspace = true openssl.workspace = true p256.workspace = true rand.workspace = true serde.workspace = true serde_json.workspace = true sha2.workspace = true +reqwest.workspace = true thiserror.workspace = true tokio.workspace = true tracing.workspace = true diff --git a/apps/auth-service/src/federation.rs b/apps/auth-service/src/federation.rs new file mode 100644 index 000000000..7a5bdc60b --- /dev/null +++ b/apps/auth-service/src/federation.rs @@ -0,0 +1,732 @@ +//! Explicit GitHub OAuth and Google OIDC login adapters. + +use crate::email::normalize; +use axum::{ + Json, Router, + extract::{Path, Query, State}, + http::{HeaderMap, HeaderValue, StatusCode, header}, + response::{IntoResponse, Redirect, Response}, + routing::get, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::{Duration, Utc}; +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; +use piquel_auth_protocol::{AccountStatus, AuthenticationMethod, SessionId, TokenId, UserId}; +use piquel_configuration::SecretReference; +use piquel_repository::{ + AppendAuditEvent, AppendInternalEvent, Database, DatabaseError, InsertExternalIdentity, + InsertFederationTransaction, InsertSession, InsertUser, InsertVerifiedEmail, +}; +use rand::{RngCore, rngs::OsRng}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{collections::HashMap, fmt::Write, sync::Arc, time::Duration as StdDuration}; +use thiserror::Error; +use url::Url; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Provider { + GitHub, + Google, +} +impl Provider { + fn parse(value: &str) -> Option { + match value { + "github" => Some(Self::GitHub), + "google" => Some(Self::Google), + _ => None, + } + } + const fn name(self) -> &'static str { + match self { + Self::GitHub => "github", + Self::Google => "google", + } + } + const fn issuer(self) -> &'static str { + match self { + Self::GitHub => "https://github.com", + Self::Google => "https://accounts.google.com", + } + } + const fn authorization_endpoint(self) -> &'static str { + match self { + Self::GitHub => "https://github.com/login/oauth/authorize", + Self::Google => "https://accounts.google.com/o/oauth2/v2/auth", + } + } + const fn token_endpoint(self) -> &'static str { + match self { + Self::GitHub => "https://github.com/login/oauth/access_token", + Self::Google => "https://oauth2.googleapis.com/token", + } + } +} + +/// Secret-reference configuration for one approved provider. +#[derive(Clone, Debug)] +pub struct ProviderConfiguration { + /// Public provider OAuth client identifier. + pub client_id: String, + /// Reference to the provider secret; never the secret value. + pub client_secret: SecretReference, +} +/// Runnable two-provider federation state. +#[derive(Clone)] +pub struct FederationApplication { + database: Database, + base_url: Url, + providers: Arc>, + client: reqwest::Client, +} +impl FederationApplication { + /// Constructs the exact GitHub and Google provider set. + /// + /// # Errors + /// + /// Returns an error unless the callback base is HTTPS and both client IDs are present. + pub fn new( + database: Database, + base_url: &Url, + github: ProviderConfiguration, + google: ProviderConfiguration, + ) -> Result { + if base_url.scheme() != "https" + || github.client_id.is_empty() + || google.client_id.is_empty() + { + return Err(FederationConfigurationError); + } + Ok(Self { + database, + base_url: base_url.clone(), + providers: Arc::new(HashMap::from([("github", github), ("google", google)])), + client: reqwest::Client::new(), + }) + } + /// Constructs loopback-only HTTP callbacks for explicit development. + /// + /// # Errors + /// + /// Returns an error unless the base URL is loopback-only and both client IDs are present. + pub fn new_development( + database: Database, + base_url: &Url, + github: ProviderConfiguration, + google: ProviderConfiguration, + ) -> Result { + let loopback = base_url.host_str().is_some_and(|host| { + host == "localhost" + || host + .parse::() + .is_ok_and(|ip| ip.is_loopback()) + }); + if !loopback { + return Err(FederationConfigurationError); + } + let app = Self { + database, + base_url: base_url.clone(), + providers: Arc::new(HashMap::from([("github", github), ("google", google)])), + client: reqwest::Client::new(), + }; + if app + .providers + .values() + .any(|provider| provider.client_id.is_empty()) + { + return Err(FederationConfigurationError); + } + Ok(app) + } +} +#[derive(Debug, Error)] +#[error("invalid federation configuration")] +pub struct FederationConfigurationError; +pub(super) fn routes(app: FederationApplication) -> Router { + Router::new() + .route("/login/{provider}", get(start)) + .route("/login/{provider}/callback", get(callback)) + .route("/account/social-identities", get(list_identities)) + .with_state(app) +} + +#[derive(Default, Deserialize)] +struct StartQuery { + return_to: Option, +} + +async fn start( + State(app): State, + Path(provider): Path, + Query(query): Query, +) -> Result { + let provider = Provider::parse(&provider).ok_or(ApiError)?; + let config = app.providers.get(provider.name()).ok_or(ApiError)?; + let state = random(); + let nonce = random(); + let verifier = random(); + let browser = random(); + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + let return_to = validate_return_to(query.return_to.as_deref())?; + app.database + .federation() + .insert_transaction(&InsertFederationTransaction { + id: TokenId::new(), + provider: provider.name().into(), + state_digest: Sha256::digest(state.as_bytes()).to_vec(), + browser_digest: Sha256::digest(browser.as_bytes()).to_vec(), + nonce: nonce.clone(), + pkce_verifier: verifier, + return_to, + expires_at: Utc::now() + Duration::minutes(10), + }) + .await + .map_err(|_| ApiError)?; + let callback = format!( + "{}/login/{}/callback", + app.base_url.as_str().trim_end_matches('/'), + provider.name() + ); + let mut url = Url::parse(provider.authorization_endpoint()).map_err(|_| ApiError)?; + let scope = match provider { + Provider::GitHub => "read:user user:email", + Provider::Google => "openid email profile", + }; + url.query_pairs_mut() + .append_pair("client_id", &config.client_id) + .append_pair("redirect_uri", &callback) + .append_pair("response_type", "code") + .append_pair("scope", scope) + .append_pair("state", &state) + .append_pair("code_challenge", &challenge) + .append_pair("code_challenge_method", "S256"); + if provider == Provider::Google { + url.query_pairs_mut().append_pair("nonce", &nonce); + } + let mut response = Redirect::to(url.as_str()).into_response(); + response.headers_mut().insert(header::SET_COOKIE,HeaderValue::from_str(&format!("__Host-piquel_federation={browser}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=600")).map_err(|_|ApiError)?); + Ok(response) +} + +#[derive(Deserialize)] +struct CallbackQuery { + code: Option, + state: Option, + error: Option, +} +async fn callback( + State(app): State, + Path(provider): Path, + headers: HeaderMap, + Query(query): Query, +) -> Result { + if query.error.is_some() { + return Err(ApiError); + } + let provider = Provider::parse(&provider).ok_or(ApiError)?; + let code = query + .code + .filter(|value| !value.is_empty() && value.len() <= 2048) + .ok_or(ApiError)?; + let state = query + .state + .filter(|value| value.len() <= 256) + .ok_or(ApiError)?; + let browser = cookie(&headers, "__Host-piquel_federation").ok_or(ApiError)?; + let transaction = app + .database + .federation() + .consume_transaction( + provider.name(), + &Sha256::digest(state.as_bytes()), + &Sha256::digest(browser.as_bytes()), + ) + .await + .map_err(|_| ApiError)?; + let identity = exchange( + &app, + provider, + &code, + &transaction.pkce_verifier, + &transaction.nonce, + ) + .await?; + let user_id = link_identity(&app.database, provider, &identity).await?; + let cookie = create_session(&app.database, user_id).await?; + let destination = app + .base_url + .join(&transaction.return_to) + .map_err(|_| ApiError)?; + let mut response = Redirect::to(destination.as_str()).into_response(); + response.headers_mut().append( + header::SET_COOKIE, + HeaderValue::from_str(&cookie).map_err(|_| ApiError)?, + ); + response.headers_mut().append( + header::SET_COOKIE, + HeaderValue::from_static( + "__Host-piquel_federation=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0", + ), + ); + Ok(response) +} + +fn validate_return_to(value: Option<&str>) -> Result { + let value = value.unwrap_or("/"); + if value.len() > 512 + || !value.starts_with('/') + || value.starts_with("//") + || value.contains('#') + { + return Err(ApiError); + } + Ok(value.to_owned()) +} + +#[derive(Serialize)] +struct SocialIdentityView { + provider: String, + linked_email: String, +} + +async fn list_identities( + State(app): State, + headers: HeaderMap, +) -> Result>, ApiError> { + let raw = cookie(&headers, "__Host-piquel_session").ok_or(ApiError)?; + let secret = URL_SAFE_NO_PAD.decode(raw).map_err(|_| ApiError)?; + if secret.len() != 32 { + return Err(ApiError); + } + let session = app + .database + .sessions() + .find_active_by_browser_secret(&Sha256::digest(secret)) + .await + .map_err(|_| ApiError)? + .ok_or(ApiError)?; + let identities = app + .database + .federation() + .list_active(session.user_id) + .await + .map_err(|_| ApiError)?; + Ok(Json( + identities + .into_iter() + .map(|identity| SocialIdentityView { + provider: identity.provider, + linked_email: identity.linked_email, + }) + .collect(), + )) +} + +struct VerifiedIdentity { + issuer: &'static str, + subject: String, + email: String, + display_name: String, +} +async fn exchange( + app: &FederationApplication, + provider: Provider, + code: &str, + verifier: &str, + nonce: &str, +) -> Result { + let config = app.providers.get(provider.name()).ok_or(ApiError)?; + let secret = config.client_secret.resolve().map_err(|_| ApiError)?; + let secret = std::str::from_utf8(secret.expose_secret()).map_err(|_| ApiError)?; + let callback = format!( + "{}/login/{}/callback", + app.base_url.as_str().trim_end_matches('/'), + provider.name() + ); + let response = app + .client + .post(provider.token_endpoint()) + .timeout(StdDuration::from_secs(5)) + .header(header::ACCEPT, "application/json") + .form(&[ + ("client_id", config.client_id.as_str()), + ("client_secret", secret), + ("code", code), + ("redirect_uri", &callback), + ("code_verifier", verifier), + ("grant_type", "authorization_code"), + ]) + .send() + .await + .map_err(|_| ApiError)?; + if !response.status().is_success() { + return Err(ApiError); + } + match provider { + Provider::GitHub => github_identity(app, response).await, + Provider::Google => google_identity(app, response, &config.client_id, nonce).await, + } +} + +#[derive(Deserialize)] +struct GithubToken { + access_token: String, +} +#[derive(Deserialize)] +struct GithubUser { + id: u64, + name: Option, + login: String, +} +#[derive(Deserialize)] +struct GithubEmail { + email: String, + verified: bool, + primary: bool, +} +async fn github_identity( + app: &FederationApplication, + response: reqwest::Response, +) -> Result { + let token: GithubToken = response.json().await.map_err(|_| ApiError)?; + if token.access_token.is_empty() { + return Err(ApiError); + } + let auth = format!("Bearer {}", token.access_token); + let user: GithubUser = app + .client + .get("https://api.github.com/user") + .timeout(StdDuration::from_secs(5)) + .header(header::AUTHORIZATION, &auth) + .header(header::USER_AGENT, "piquel-auth") + .send() + .await + .map_err(|_| ApiError)? + .error_for_status() + .map_err(|_| ApiError)? + .json() + .await + .map_err(|_| ApiError)?; + let emails: Vec = app + .client + .get("https://api.github.com/user/emails") + .timeout(StdDuration::from_secs(5)) + .header(header::AUTHORIZATION, auth) + .header(header::USER_AGENT, "piquel-auth") + .send() + .await + .map_err(|_| ApiError)? + .error_for_status() + .map_err(|_| ApiError)? + .json() + .await + .map_err(|_| ApiError)?; + let email = emails + .iter() + .find(|email| email.verified && email.primary) + .or_else(|| emails.iter().find(|email| email.verified)) + .ok_or(ApiError)? + .email + .clone(); + Ok(VerifiedIdentity { + issuer: Provider::GitHub.issuer(), + subject: user.id.to_string(), + email, + display_name: user.name.unwrap_or(user.login), + }) +} + +#[derive(Deserialize)] +struct GoogleToken { + id_token: String, +} +#[derive(Deserialize)] +struct GoogleClaims { + iss: String, + sub: String, + aud: String, + exp: i64, + nonce: String, + email: String, + email_verified: bool, + name: Option, +} +#[derive(Deserialize)] +struct GoogleJwks { + keys: Vec, +} +#[derive(Deserialize)] +struct GoogleJwk { + kid: String, + kty: String, + alg: String, + n: String, + e: String, +} +async fn google_identity( + app: &FederationApplication, + response: reqwest::Response, + client_id: &str, + nonce: &str, +) -> Result { + let token: GoogleToken = response.json().await.map_err(|_| ApiError)?; + if token.id_token.len() > 8192 { + return Err(ApiError); + } + let header = decode_header(&token.id_token).map_err(|_| ApiError)?; + if header.alg != Algorithm::RS256 { + return Err(ApiError); + } + let kid = header.kid.ok_or(ApiError)?; + let jwks: GoogleJwks = app + .client + .get("https://www.googleapis.com/oauth2/v3/certs") + .timeout(StdDuration::from_secs(3)) + .send() + .await + .map_err(|_| ApiError)? + .error_for_status() + .map_err(|_| ApiError)? + .json() + .await + .map_err(|_| ApiError)?; + let jwk = jwks + .keys + .into_iter() + .find(|key| key.kid == kid && key.kty == "RSA" && key.alg == "RS256") + .ok_or(ApiError)?; + let key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(|_| ApiError)?; + let mut validation = Validation::new(Algorithm::RS256); + validation.set_audience(&[client_id]); + validation.set_issuer(&[Provider::Google.issuer()]); + validation.leeway = 30; + let claims = decode::(&token.id_token, &key, &validation) + .map_err(|_| ApiError)? + .claims; + if claims.iss != Provider::Google.issuer() + || claims.aud != client_id + || claims.nonce != nonce + || !claims.email_verified + || claims.sub.is_empty() + || claims.exp <= Utc::now().timestamp() + { + return Err(ApiError); + } + Ok(VerifiedIdentity { + issuer: Provider::Google.issuer(), + subject: claims.sub, + email: claims.email, + display_name: claims.name.unwrap_or_else(|| "Google user".into()), + }) +} + +#[allow(clippy::too_many_lines)] +async fn link_identity( + database: &Database, + provider: Provider, + identity: &VerifiedIdentity, +) -> Result { + if identity.issuer != provider.issuer() + || identity.subject.is_empty() + || identity.subject.len() > 255 + { + return Err(ApiError); + } + if let Some(existing) = database + .federation() + .find_active(identity.issuer, &identity.subject) + .await + .map_err(|_| ApiError)? + { + let user = database + .users() + .find_by_id(existing.user_id) + .await + .map_err(|_| ApiError)? + .ok_or(ApiError)?; + if user.status != AccountStatus::Active { + return Err(ApiError); + } + database + .federation() + .record_login(existing.id) + .await + .map_err(|_| ApiError)?; + return Ok(user.id); + } + let email = normalize(&identity.email).map_err(|()| ApiError)?; + let mut tx = database.begin().await.map_err(|_| ApiError)?; + let owner = tx + .emails() + .find_active_verified(email.as_str()) + .await + .map_err(|_| ApiError)?; + let user_id = if let Some(owner) = owner { + tx.users() + .find_active_by_id_for_update(owner.user_id) + .await + .map_err(|_| ApiError)? + .map(|user| user.id) + .ok_or(ApiError)? + } else { + let id = UserId::new(); + let suffix = &hex_digest(identity.subject.as_bytes())[..12]; + let username = format!("{}_{}", provider.name(), suffix); + tx.users() + .insert(&InsertUser { + id, + username, + display_name: identity.display_name.chars().take(80).collect(), + }) + .await + .map_err(|_| ApiError)?; + tx.emails() + .insert_verified(&InsertVerifiedEmail { + id: TokenId::new(), + user_id: id, + normalized_email: email.as_str().into(), + is_primary: true, + verified_at: Utc::now(), + }) + .await + .map_err(|_| ApiError)?; + id + }; + match tx + .federation() + .insert_identity(&InsertExternalIdentity { + id: TokenId::new(), + user_id, + provider: provider.name().into(), + issuer: identity.issuer.into(), + subject: identity.subject.clone(), + linked_email: email.as_str().into(), + }) + .await + { + Ok(_) => {} + Err(DatabaseError::Conflict) => { + tx.rollback().await.map_err(|_| ApiError)?; + return database + .federation() + .find_active(identity.issuer, &identity.subject) + .await + .map_err(|_| ApiError)? + .map(|mapping| mapping.user_id) + .ok_or(ApiError); + } + Err(_) => return Err(ApiError), + } + tx.audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: Some(user_id), + action: "federation.link".into(), + outcome: "success".into(), + request_metadata: serde_json::json!({"provider":provider.name()}), + }) + .await + .map_err(|_| ApiError)?; + tx.internal_events() + .append(&AppendInternalEvent { + id: TokenId::new(), + aggregate_type: "user".into(), + aggregate_id: user_id, + event_type: "federation.linked".into(), + schema_version: 1, + payload: serde_json::json!({"provider":provider.name()}), + }) + .await + .map_err(|_| ApiError)?; + tx.commit().await.map_err(|_| ApiError)?; + Ok(user_id) +} + +async fn create_session(database: &Database, user_id: UserId) -> Result { + let mut tx = database.begin().await.map_err(|_| ApiError)?; + let id = SessionId::new(); + let now = Utc::now(); + let mut secret = [0_u8; 32]; + OsRng.fill_bytes(&mut secret); + tx.sessions() + .insert(&InsertSession { + id, + user_id, + authentication_methods: vec![AuthenticationMethod::Federation], + authenticated_at: now, + expires_at: now + Duration::days(30), + user_agent_family: None, + }) + .await + .map_err(|_| ApiError)?; + tx.sessions() + .insert_browser_secret(id, &Sha256::digest(secret)) + .await + .map_err(|_| ApiError)?; + tx.audit_events() + .append(&AppendAuditEvent { + id: TokenId::new(), + user_id: Some(user_id), + action: "federation.login".into(), + outcome: "success".into(), + request_metadata: serde_json::json!({}), + }) + .await + .map_err(|_| ApiError)?; + tx.commit().await.map_err(|_| ApiError)?; + Ok(format!( + "__Host-piquel_session={}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=2592000", + URL_SAFE_NO_PAD.encode(secret) + )) +} +fn random() -> String { + let mut bytes = [0_u8; 32]; + OsRng.fill_bytes(&mut bytes); + URL_SAFE_NO_PAD.encode(bytes) +} +fn cookie(headers: &HeaderMap, name: &str) -> Option { + headers + .get(header::COOKIE)? + .to_str() + .ok()? + .split(';') + .map(str::trim) + .find_map(|part| part.strip_prefix(&format!("{name}=")).map(str::to_owned)) +} +fn hex_digest(value: &[u8]) -> String { + Sha256::digest(value) + .iter() + .fold(String::with_capacity(64), |mut output, byte| { + write!(output, "{byte:02x}").expect("writing to String cannot fail"); + output + }) +} +#[derive(Debug, Error)] +#[error("social authentication failed")] +struct ApiError; +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error":"social_authentication_failed"})), + ) + .into_response() + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn providers_are_explicit() { + assert_eq!(Provider::parse("github"), Some(Provider::GitHub)); + assert_eq!(Provider::parse("google"), Some(Provider::Google)); + assert_eq!(Provider::parse("other"), None); + } + #[test] + fn callback_secrets_are_bounded() { + assert_eq!(random().len(), 43); + assert!(normalize("Ada+work@Example.COM").is_ok()); + } +} diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index e735692b8..bbd1fe101 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -16,6 +16,9 @@ mod email; #[allow(dead_code)] mod event_log; #[allow(dead_code)] +mod federation; +pub use federation::{FederationApplication, ProviderConfiguration}; +#[allow(dead_code)] mod oidc; pub use oidc::OidcApplication; #[allow(dead_code)] @@ -45,6 +48,10 @@ pub struct AuthConfig { pub development_mode: bool, /// Stable identifier embedded in signed-token headers. pub signing_key_id: String, + /// GitHub OAuth client configuration. + pub github: ProviderConfiguration, + /// Google OIDC client configuration. + pub google: ProviderConfiguration, } impl AuthConfig { /// Loads the minimum service configuration from the environment. @@ -84,6 +91,14 @@ impl AuthConfig { webauthn_rp_id: required("AUTH_WEBAUTHN_RP_ID")?, development_mode: development, signing_key_id: required("AUTH_SIGNING_KEY_ID")?, + github: ProviderConfiguration { + client_id: required("AUTH_GITHUB_CLIENT_ID")?, + client_secret: SecretReference::parse(&required("AUTH_GITHUB_CLIENT_SECRET")?)?, + }, + google: ProviderConfiguration { + client_id: required("AUTH_GOOGLE_CLIENT_ID")?, + client_secret: SecretReference::parse(&required("AUTH_GOOGLE_CLIENT_SECRET")?)?, + }, }) } } @@ -132,6 +147,7 @@ pub fn router( readiness: Arc, passkeys: Option, oidc: Option, + federation: Option, ) -> Router { let health = Router::new() .route("/health/live", get(|| async { StatusCode::NO_CONTENT })) @@ -140,7 +156,10 @@ pub fn router( let router = passkeys.map_or(health.clone(), |passkeys| { health.merge(passkey::routes(passkeys)) }); - oidc.map_or(router.clone(), |oidc| router.merge(oidc::routes(oidc))) + let router = oidc.map_or(router.clone(), |oidc| router.merge(oidc::routes(oidc))); + federation.map_or(router.clone(), |federation| { + router.merge(federation::routes(federation)) + }) } async fn ready(State(state): State) -> impl IntoResponse { @@ -165,7 +184,7 @@ mod tests { #[tokio::test] async fn liveness_has_no_dependencies_and_readiness_fails_closed() { - let app = router(Arc::new(FixedReadiness(false)), None, None); + let app = router(Arc::new(FixedReadiness(false)), None, None, None); let live = app .clone() .oneshot( @@ -189,7 +208,7 @@ mod tests { #[tokio::test] async fn readiness_succeeds_with_test_substitutes() { - let response = router(Arc::new(FixedReadiness(true)), None, None) + let response = router(Arc::new(FixedReadiness(true)), None, 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 345f5bbd1..4ed6e4081 100644 --- a/apps/auth-service/src/main.rs +++ b/apps/auth-service/src/main.rs @@ -1,7 +1,8 @@ #![allow(missing_docs)] use auth_service::{ - AuthConfig, Es256KeyProvider, OidcApplication, PasskeyApplication, ProductionReadiness, router, + AuthConfig, Es256KeyProvider, FederationApplication, OidcApplication, PasskeyApplication, + ProductionReadiness, router, }; use piquel_repository::Database; use std::{net::SocketAddr, sync::Arc}; @@ -48,6 +49,21 @@ async fn main() -> anyhow::Result<()> { ) } .map_err(|()| anyhow::anyhow!("invalid OIDC configuration"))?; + let federation = if config.development_mode { + FederationApplication::new_development( + database.clone(), + config.public_base_url.as_url(), + config.github, + config.google, + ) + } else { + FederationApplication::new( + database.clone(), + config.public_base_url.as_url(), + config.github, + config.google, + ) + }?; let listener = tokio::net::TcpListener::bind(listener_address).await?; tracing::info!(%listener_address, "auth service listening"); axum::serve( @@ -56,6 +72,7 @@ async fn main() -> anyhow::Result<()> { Arc::new(ProductionReadiness::new(database, config.key_provider)), Some(passkeys), Some(oidc), + Some(federation), ), ) .with_graceful_shutdown(shutdown_signal()) diff --git a/crates/database/migrations/0005_federation.sql b/crates/database/migrations/0005_federation.sql new file mode 100644 index 000000000..12b489886 --- /dev/null +++ b/crates/database/migrations/0005_federation.sql @@ -0,0 +1,27 @@ +CREATE TABLE external_login_identities ( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + provider_name TEXT NOT NULL CHECK (provider_name IN ('github', 'google')), + issuer TEXT NOT NULL, + subject TEXT NOT NULL, + linked_email TEXT NOT NULL, + linked_at TIMESTAMPTZ NOT NULL DEFAULT now(), + last_login_at TIMESTAMPTZ NOT NULL DEFAULT now(), + revoked_at TIMESTAMPTZ, + UNIQUE (issuer, subject) +); +CREATE INDEX external_login_identities_user_idx ON external_login_identities (user_id) WHERE revoked_at IS NULL; + +CREATE TABLE federation_transactions ( + id UUID PRIMARY KEY, + provider_name TEXT NOT NULL CHECK (provider_name IN ('github', 'google')), + state_digest BYTEA NOT NULL UNIQUE, + browser_digest BYTEA NOT NULL, + nonce TEXT NOT NULL, + pkce_verifier TEXT NOT NULL, + return_to TEXT NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX federation_transactions_expiry_idx ON federation_transactions(expires_at) WHERE consumed_at IS NULL; diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs index d6f64d7b0..1ccf74e82 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -228,6 +228,42 @@ pub enum RefreshRotationError { Policy { user_id: UserId }, } +#[derive(Clone, Debug)] +pub struct InsertFederationTransaction { + pub id: TokenId, + pub provider: String, + pub state_digest: Vec, + pub browser_digest: Vec, + pub nonce: String, + pub pkce_verifier: String, + pub return_to: String, + pub expires_at: DateTime, +} +#[derive(Clone, Debug)] +pub struct ConsumedFederationTransaction { + pub nonce: String, + pub pkce_verifier: String, + pub return_to: String, +} +#[derive(Clone, Debug)] +pub struct InsertExternalIdentity { + pub id: TokenId, + pub user_id: UserId, + pub provider: String, + pub issuer: String, + pub subject: String, + pub linked_email: String, +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredExternalIdentity { + pub id: TokenId, + pub user_id: UserId, + pub provider: String, + pub issuer: String, + pub subject: String, + pub linked_email: String, +} + #[derive(Clone, Debug)] pub struct InsertPurposeAuthorization { pub id: TokenId, diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index f46192164..7b0b725ac 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -2,11 +2,12 @@ use crate::{ AppendAuditEvent, AppendInternalEvent, BootstrapOidcClient, ConsumedAuthorizationCode, - ConsumedCeremony, DatabaseError, InsertAuthorizationCode, InsertAuthorizationRequest, - InsertCeremony, InsertPasskey, InsertPurposeAuthorization, InsertRefreshFamily, + ConsumedCeremony, ConsumedFederationTransaction, DatabaseError, InsertAuthorizationCode, + InsertAuthorizationRequest, InsertCeremony, InsertExternalIdentity, + InsertFederationTransaction, InsertPasskey, InsertPurposeAuthorization, InsertRefreshFamily, InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, RefreshRotationError, - RotatedRefreshToken, StoredAuthorizationRequest, StoredEmail, StoredOidcClient, StoredPasskey, - StoredSession, StoredUser, UpdateUserProfile, + RotatedRefreshToken, StoredAuthorizationRequest, StoredEmail, StoredExternalIdentity, + StoredOidcClient, StoredPasskey, StoredSession, StoredUser, UpdateUserProfile, }; use piquel_auth_protocol::{AccountStatus, SessionId, TokenId, UserId}; use sqlx::{PgConnection, PgPool, Row}; @@ -226,6 +227,14 @@ impl EmailRepository<'_> { }) .transpose() } + + pub async fn find_users_by_verified_email( + &mut self, + normalized: &str, + ) -> Result, DatabaseError> { + let rows=match &mut self.executor{RepositoryExecutor::Pool(pool)=>sqlx::query("SELECT DISTINCT u.id,u.username,u.display_name,u.profile_version,u.status,u.created_at,u.updated_at FROM user_emails e JOIN users u ON u.id=e.user_id WHERE e.normalized_email=$1 AND e.verified_at IS NOT NULL ORDER BY u.id").bind(normalized).fetch_all(*pool).await,RepositoryExecutor::Connection(connection)=>sqlx::query("SELECT DISTINCT u.id,u.username,u.display_name,u.profile_version,u.status,u.created_at,u.updated_at FROM user_emails e JOIN users u ON u.id=e.user_id WHERE e.normalized_email=$1 AND e.verified_at IS NOT NULL ORDER BY u.id").bind(normalized).fetch_all(&mut **connection).await}.map_err(Into::::into)?; + rows.iter().map(stored_user).collect() + } } impl SessionRepository<'_> { @@ -604,6 +613,88 @@ impl TokenRepository<'_> { 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()) } } + +impl FederationRepository<'_> { + pub async fn insert_transaction( + &mut self, + input: &InsertFederationTransaction, + ) -> Result<(), DatabaseError> { + execute!(self,sqlx::query("INSERT INTO federation_transactions(id,provider_name,state_digest,browser_digest,nonce,pkce_verifier,return_to,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8)").bind(input.id.as_uuid()).bind(&input.provider).bind(&input.state_digest).bind(&input.browser_digest).bind(&input.nonce).bind(&input.pkce_verifier).bind(&input.return_to).bind(input.expires_at))?; + Ok(()) + } + pub async fn consume_transaction( + &mut self, + provider: &str, + state_digest: &[u8], + browser_digest: &[u8], + ) -> Result { + let row=fetch_optional!(self,sqlx::query("UPDATE federation_transactions SET consumed_at=now() WHERE provider_name=$1 AND state_digest=$2 AND browser_digest=$3 AND consumed_at IS NULL AND expires_at>now() RETURNING nonce,pkce_verifier,return_to").bind(provider).bind(state_digest).bind(browser_digest))?.ok_or(DatabaseError::NotFound)?; + Ok(ConsumedFederationTransaction { + nonce: row + .try_get("nonce") + .map_err(|_| DatabaseError::InvalidStoredData)?, + pkce_verifier: row + .try_get("pkce_verifier") + .map_err(|_| DatabaseError::InvalidStoredData)?, + return_to: row + .try_get("return_to") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) + } + pub async fn find_active( + &mut self, + issuer: &str, + subject: &str, + ) -> Result, DatabaseError> { + fetch_optional!(self,sqlx::query("SELECT id,user_id,provider_name,issuer,subject,linked_email FROM external_login_identities WHERE issuer=$1 AND subject=$2 AND revoked_at IS NULL").bind(issuer).bind(subject))?.map(|row|stored_external_identity(&row)).transpose() + } + pub async fn insert_identity( + &mut self, + input: &InsertExternalIdentity, + ) -> Result { + let row=fetch_one!(self,sqlx::query("INSERT INTO external_login_identities(id,user_id,provider_name,issuer,subject,linked_email) VALUES($1,$2,$3,$4,$5,$6) RETURNING id,user_id,provider_name,issuer,subject,linked_email").bind(input.id.as_uuid()).bind(input.user_id.as_uuid()).bind(&input.provider).bind(&input.issuer).bind(&input.subject).bind(&input.linked_email))?; + stored_external_identity(&row) + } + pub async fn record_login(&mut self, id: TokenId) -> Result<(), DatabaseError> { + execute!(self,sqlx::query("UPDATE external_login_identities SET last_login_at=now() WHERE id=$1 AND revoked_at IS NULL").bind(id.as_uuid()))?; + Ok(()) + } + pub async fn list_active( + &mut self, + user_id: UserId, + ) -> Result, DatabaseError> { + let rows=match &mut self.executor{RepositoryExecutor::Pool(pool)=>sqlx::query("SELECT id,user_id,provider_name,issuer,subject,linked_email FROM external_login_identities WHERE user_id=$1 AND revoked_at IS NULL ORDER BY linked_at").bind(user_id.as_uuid()).fetch_all(*pool).await,RepositoryExecutor::Connection(connection)=>sqlx::query("SELECT id,user_id,provider_name,issuer,subject,linked_email FROM external_login_identities WHERE user_id=$1 AND revoked_at IS NULL ORDER BY linked_at").bind(user_id.as_uuid()).fetch_all(&mut **connection).await}.map_err(Into::::into)?; + rows.iter().map(stored_external_identity).collect() + } +} +fn stored_external_identity( + row: &sqlx::postgres::PgRow, +) -> Result { + Ok(StoredExternalIdentity { + id: TokenId::from_uuid( + row.try_get("id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + user_id: UserId::from_uuid( + row.try_get("user_id") + .map_err(|_| DatabaseError::InvalidStoredData)?, + ) + .map_err(|_| DatabaseError::InvalidStoredData)?, + provider: row + .try_get("provider_name") + .map_err(|_| DatabaseError::InvalidStoredData)?, + issuer: row + .try_get("issuer") + .map_err(|_| DatabaseError::InvalidStoredData)?, + subject: row + .try_get("subject") + .map_err(|_| DatabaseError::InvalidStoredData)?, + linked_email: row + .try_get("linked_email") + .map_err(|_| DatabaseError::InvalidStoredData)?, + }) +} 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 61dee5067..57b7c1057 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -4,9 +4,9 @@ use chrono::{Duration as ChronoDuration, Utc}; use piquel_auth_protocol::{AccountStatus, AuthenticationMethod, SessionId, TokenId, UserId}; use piquel_repository::{ AppendInternalEvent, BootstrapOidcClient, Database, DatabaseConfig, DatabaseError, - InsertCeremony, InsertPasskey, InsertPurposeAuthorization, InsertRefreshFamily, - InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, RefreshRotationError, - UpdateUserProfile, + InsertCeremony, InsertExternalIdentity, InsertFederationTransaction, InsertPasskey, + InsertPurposeAuthorization, InsertRefreshFamily, InsertRefreshToken, InsertSession, InsertUser, + InsertVerifiedEmail, RefreshRotationError, UpdateUserProfile, }; use std::{env, time::Duration}; @@ -268,6 +268,67 @@ async fn identity_transactions_and_concurrency_hold() { || matches!(right, Err(RefreshRotationError::Replay { .. })) ); + let federation_state = vec![11_u8; 32]; + let browser = vec![12_u8; 32]; + database + .federation() + .insert_transaction(&InsertFederationTransaction { + id: TokenId::new(), + provider: "github".into(), + state_digest: federation_state.clone(), + browser_digest: browser.clone(), + nonce: "nonce".into(), + pkce_verifier: "v".repeat(43), + return_to: "/".into(), + expires_at: Utc::now() + ChronoDuration::minutes(5), + }) + .await + .expect("federation transaction"); + let one = database.clone(); + let two = database.clone(); + let (left, right) = tokio::join!( + async move { + one.federation() + .consume_transaction("github", &federation_state, &browser) + .await + }, + async move { + two.federation() + .consume_transaction("github", &[11_u8; 32], &[12_u8; 32]) + .await + }, + ); + assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); + + let issuer = "https://github.com"; + let subject = format!("subject-{first}"); + database + .federation() + .insert_identity(&InsertExternalIdentity { + id: TokenId::new(), + user_id: first, + provider: "github".into(), + issuer: issuer.into(), + subject: subject.clone(), + linked_email: "first@example.com".into(), + }) + .await + .expect("first identity"); + assert!(matches!( + database + .federation() + .insert_identity(&InsertExternalIdentity { + id: TokenId::new(), + user_id: second, + provider: "github".into(), + issuer: issuer.into(), + subject, + linked_email: "second@example.com".into(), + }) + .await, + Err(DatabaseError::Conflict) + )); + let credential_id = vec![7_u8; 32]; database .passkeys() diff --git a/docs/security/federation-providers.md b/docs/security/federation-providers.md new file mode 100644 index 000000000..de8951dad --- /dev/null +++ b/docs/security/federation-providers.md @@ -0,0 +1,13 @@ +# Approved social identity providers + +The first iteration permits exactly two providers: GitHub and Google. Their +durable external identities are `(https://github.com, subject)` and +`(https://accounts.google.com, subject)` respectively; an email is never a +durable provider key. + +Automatic linking requires a provider-asserted, usable verified email. GitHub +adapters must obtain that assertion from the authenticated email endpoint and +must not treat an unverified profile email as verified. Google adapters must +validate the ID token issuer, signature, audience, nonce, expiry, and its +`email_verified` claim. Both providers use state, nonce, and PKCE; client +secrets remain secret references and are never logged or stored in PostgreSQL.