From 7872b80395207de0036cab90335a810d62007616 Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:09:13 +0200 Subject: [PATCH 1/4] feat(auth): add federated identity foundation --- apps/auth-service/src/federation.rs | 48 +++++++++++++++++++ apps/auth-service/src/lib.rs | 2 + .../database/migrations/0005_federation.sql | 12 +++++ 3 files changed, 62 insertions(+) create mode 100644 apps/auth-service/src/federation.rs create mode 100644 crates/database/migrations/0005_federation.sql diff --git a/apps/auth-service/src/federation.rs b/apps/auth-service/src/federation.rs new file mode 100644 index 000000000..48c035b77 --- /dev/null +++ b/apps/auth-service/src/federation.rs @@ -0,0 +1,48 @@ +//! Approved-provider identity-linking invariants. + +use piquel_auth_protocol::UserId; + +/// Provider claims after issuer/signature/nonce verification by the adapter. +pub(super) struct VerifiedProviderIdentity { + pub issuer: String, + pub subject: String, + pub verified_email: String, +} +/// Linking is permitted only for a stable issuer/subject and an asserted verified email. +pub(super) fn validate_identity( + identity: &VerifiedProviderIdentity, + approved_issuer: &str, +) -> Result<(), ()> { + if identity.issuer != approved_issuer + || identity.subject.is_empty() + || identity.subject.len() > 255 + || identity.verified_email.is_empty() + { + return Err(()); + } + Ok(()) +} +/// A durable mapping always uses issuer/subject rather than email. +pub(super) struct IdentityLink { + pub user_id: UserId, + pub issuer: String, + pub subject: String, +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn provider_identity_cannot_be_email_only() { + assert!( + validate_identity( + &VerifiedProviderIdentity { + issuer: "https://issuer".into(), + subject: String::new(), + verified_email: "a@example.com".into() + }, + "https://issuer" + ) + .is_err() + ); + } +} diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 610ec3493..05b944828 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -16,6 +16,8 @@ mod email; #[allow(dead_code)] mod event_log; #[allow(dead_code)] +mod federation; +#[allow(dead_code)] mod oidc; pub use oidc::{Es256KeyProvider, OidcApplication}; #[allow(dead_code)] diff --git a/crates/database/migrations/0005_federation.sql b/crates/database/migrations/0005_federation.sql new file mode 100644 index 000000000..b02f2691a --- /dev/null +++ b/crates/database/migrations/0005_federation.sql @@ -0,0 +1,12 @@ +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, + issuer TEXT NOT NULL, + subject TEXT NOT NULL, + linked_email TEXT NOT NULL, + linked_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; From 12dd31590590491944472c819296c4217d83b52b Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 14:14:24 +0200 Subject: [PATCH 2/4] feat(auth): approve github and google federation --- apps/auth-service/src/federation.rs | 42 +++++++++++++++++++ .../database/migrations/0005_federation.sql | 2 +- docs/security/federation-providers.md | 13 ++++++ 3 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 docs/security/federation-providers.md diff --git a/apps/auth-service/src/federation.rs b/apps/auth-service/src/federation.rs index 48c035b77..2dc0dc12f 100644 --- a/apps/auth-service/src/federation.rs +++ b/apps/auth-service/src/federation.rs @@ -1,6 +1,42 @@ //! Approved-provider identity-linking invariants. use piquel_auth_protocol::UserId; +use piquel_configuration::SecretReference; + +/// The only approved social identity providers in the first iteration. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Provider { + /// GitHub's OAuth identity API with verified-email lookup. + GitHub, + /// Google's `OpenID` Connect identity API. + Google, +} + +impl Provider { + /// Stable provider label stored in the database. + pub(super) const fn name(self) -> &'static str { + match self { + Self::GitHub => "github", + Self::Google => "google", + } + } + + /// Expected issuer used as the durable external identity namespace. + pub(super) const fn issuer(self) -> &'static str { + match self { + Self::GitHub => "https://github.com", + Self::Google => "https://accounts.google.com", + } + } +} + +/// Provider-specific configuration, with client secrets held only by references. +#[derive(Clone, Debug)] +pub(super) struct ProviderConfiguration { + pub provider: Provider, + pub client_id: String, + pub client_secret: SecretReference, +} /// Provider claims after issuer/signature/nonce verification by the adapter. pub(super) struct VerifiedProviderIdentity { @@ -45,4 +81,10 @@ mod tests { .is_err() ); } + + #[test] + fn provider_set_is_explicit_and_stable() { + assert_eq!(Provider::GitHub.name(), "github"); + assert_eq!(Provider::Google.issuer(), "https://accounts.google.com"); + } } diff --git a/crates/database/migrations/0005_federation.sql b/crates/database/migrations/0005_federation.sql index b02f2691a..f167add4f 100644 --- a/crates/database/migrations/0005_federation.sql +++ b/crates/database/migrations/0005_federation.sql @@ -1,7 +1,7 @@ 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, + provider_name TEXT NOT NULL CHECK (provider_name IN ('github', 'google')), issuer TEXT NOT NULL, subject TEXT NOT NULL, linked_email TEXT NOT NULL, 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. From 1ba987e40778f5be7a523b0e75703f228eacc52b Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 15:46:15 +0200 Subject: [PATCH 3/4] fix(auth): implement GitHub and Google federation --- Cargo.lock | 39 + Cargo.toml | 1 + apps/auth-service/Cargo.toml | 2 + apps/auth-service/src/federation.rs | 680 ++++++++++++++++-- apps/auth-service/src/lib.rs | 23 +- apps/auth-service/src/main.rs | 19 +- .../database/migrations/0005_federation.sql | 14 + crates/database/src/models.rs | 34 + crates/database/src/repositories.rs | 98 ++- crates/database/tests/identity.rs | 65 +- 10 files changed, 913 insertions(+), 62 deletions(-) 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 5a6e31392..98097f5c4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,6 +34,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 f2a4d3493..09638fdff 100644 --- a/apps/auth-service/Cargo.toml +++ b/apps/auth-service/Cargo.toml @@ -13,6 +13,7 @@ axum.workspace = true base64.workspace = true chrono.workspace = true hmac.workspace = true +jsonwebtoken.workspace = true openssl.workspace = true p256.workspace = true piquel-auth-protocol = { path = "../../crates/auth-protocol" } @@ -23,6 +24,7 @@ serde.workspace = true serde_json.workspace = true sha2.workspace = true rand.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 index 2dc0dc12f..d513874e8 100644 --- a/apps/auth-service/src/federation.rs +++ b/apps/auth-service/src/federation.rs @@ -1,90 +1,668 @@ -//! Approved-provider identity-linking invariants. +//! Explicit GitHub OAuth and Google OIDC login adapters. -use piquel_auth_protocol::UserId; +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; +use sha2::{Digest, Sha256}; +use std::{collections::HashMap, fmt::Write, sync::Arc, time::Duration as StdDuration}; +use thiserror::Error; +use url::Url; -/// The only approved social identity providers in the first iteration. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Provider { - /// GitHub's OAuth identity API with verified-email lookup. +enum Provider { GitHub, - /// Google's `OpenID` Connect identity API. Google, } - impl Provider { - /// Stable provider label stored in the database. - pub(super) const fn name(self) -> &'static str { + 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", } } - - /// Expected issuer used as the durable external identity namespace. - pub(super) const fn issuer(self) -> &'static str { + 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", + } + } } -/// Provider-specific configuration, with client secrets held only by references. +/// Secret-reference configuration for one approved provider. #[derive(Clone, Debug)] -pub(super) struct ProviderConfiguration { - pub provider: Provider, +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)) + .with_state(app) +} + +async fn start( + State(app): State, + Path(provider): Path, +) -> 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())); + 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, + 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 mut destination = app.base_url.clone(); + destination.set_path("/"); + destination.set_query(None); + 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) +} + +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, + } +} -/// Provider claims after issuer/signature/nonce verification by the adapter. -pub(super) struct VerifiedProviderIdentity { - pub issuer: String, - pub subject: String, - pub verified_email: String, -} -/// Linking is permitted only for a stable issuer/subject and an asserted verified email. -pub(super) fn validate_identity( - identity: &VerifiedProviderIdentity, - approved_issuer: &str, -) -> Result<(), ()> { - if identity.issuer != approved_issuer +#[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 - || identity.verified_email.is_empty() { - return Err(()); + 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 users = tx + .emails() + .find_users_by_verified_email(email.as_str()) + .await + .map_err(|_| ApiError)?; + let user_id = if users.is_empty() { + 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 + } else if users.len() == 1 && users[0].status == AccountStatus::Active { + users[0].id + } else { + return Err(ApiError); + }; + 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), } - Ok(()) + 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) } -/// A durable mapping always uses issuer/subject rather than email. -pub(super) struct IdentityLink { - pub user_id: UserId, - pub issuer: String, - pub subject: String, + +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 provider_identity_cannot_be_email_only() { - assert!( - validate_identity( - &VerifiedProviderIdentity { - issuer: "https://issuer".into(), - subject: String::new(), - verified_email: "a@example.com".into() - }, - "https://issuer" - ) - .is_err() - ); + 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 provider_set_is_explicit_and_stable() { - assert_eq!(Provider::GitHub.name(), "github"); - assert_eq!(Provider::Google.issuer(), "https://accounts.google.com"); + 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 05b944828..56d0bb07f 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -17,6 +17,7 @@ mod email; mod event_log; #[allow(dead_code)] mod federation; +pub use federation::{FederationApplication, ProviderConfiguration}; #[allow(dead_code)] mod oidc; pub use oidc::{Es256KeyProvider, OidcApplication}; @@ -45,6 +46,10 @@ pub struct AuthConfig { pub development_mode: bool, /// Stable identifier published with the active signing key. 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 +89,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 +145,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 +154,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 +182,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 +206,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 81fac8895..d533388fa 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}; @@ -47,6 +48,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( @@ -55,6 +71,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 index f167add4f..98620ddc6 100644 --- a/crates/database/migrations/0005_federation.sql +++ b/crates/database/migrations/0005_federation.sql @@ -6,7 +6,21 @@ CREATE TABLE external_login_identities ( 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, + 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 502329514..92673e696 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -228,3 +228,37 @@ pub enum RefreshRotationError { Replay { user_id: UserId }, 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 expires_at: DateTime, +} +#[derive(Clone, Debug)] +pub struct ConsumedFederationTransaction { + pub nonce: String, + pub pkce_verifier: 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, +} diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index ed505ff90..c0305a192 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, InsertRefreshFamily, InsertRefreshToken, InsertSession, - InsertUser, InsertVerifiedEmail, RefreshRotationError, RotatedRefreshToken, - StoredAuthorizationRequest, StoredEmail, StoredOidcClient, StoredPasskey, StoredSession, - StoredUser, UpdateUserProfile, + ConsumedCeremony, ConsumedFederationTransaction, DatabaseError, InsertAuthorizationCode, + InsertAuthorizationRequest, InsertCeremony, InsertExternalIdentity, + InsertFederationTransaction, InsertPasskey, InsertRefreshFamily, InsertRefreshToken, + InsertSession, InsertUser, InsertVerifiedEmail, RefreshRotationError, 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(crate::error::map_error)?; + rows.iter().map(stored_user).collect() + } } impl SessionRepository<'_> { @@ -604,6 +613,85 @@ 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,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7)").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.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").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)?, + }) + } + 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(crate::error::map_error)?; + 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 4ed55c91f..c9088521c 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -4,8 +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, InsertRefreshFamily, InsertRefreshToken, InsertSession, - InsertUser, InsertVerifiedEmail, RefreshRotationError, UpdateUserProfile, + InsertCeremony, InsertExternalIdentity, InsertFederationTransaction, InsertPasskey, + InsertRefreshFamily, InsertRefreshToken, InsertSession, InsertUser, InsertVerifiedEmail, + RefreshRotationError, UpdateUserProfile, }; use std::{env, time::Duration}; @@ -226,6 +227,66 @@ 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), + 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() From f7ba061757c8cbe222bbb5e16cfe1c314bbd0c0d Mon Sep 17 00:00:00 2001 From: piquel Date: Tue, 14 Jul 2026 16:55:15 +0200 Subject: [PATCH 4/4] fix(auth): preserve social login continuations and active ownership --- apps/auth-service/src/federation.rs | 86 ++++++++++++++++--- .../database/migrations/0005_federation.sql | 1 + crates/database/src/models.rs | 2 + crates/database/src/repositories.rs | 7 +- crates/database/tests/identity.rs | 1 + 5 files changed, 84 insertions(+), 13 deletions(-) diff --git a/apps/auth-service/src/federation.rs b/apps/auth-service/src/federation.rs index d513874e8..7a5bdc60b 100644 --- a/apps/auth-service/src/federation.rs +++ b/apps/auth-service/src/federation.rs @@ -18,7 +18,7 @@ use piquel_repository::{ InsertFederationTransaction, InsertSession, InsertUser, InsertVerifiedEmail, }; use rand::{RngCore, rngs::OsRng}; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{collections::HashMap, fmt::Write, sync::Arc, time::Duration as StdDuration}; use thiserror::Error; @@ -147,12 +147,19 @@ 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)?; @@ -161,6 +168,7 @@ async fn start( 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 { @@ -170,6 +178,7 @@ async fn start( 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 @@ -245,9 +254,10 @@ async fn callback( .await?; let user_id = link_identity(&app.database, provider, &identity).await?; let cookie = create_session(&app.database, user_id).await?; - let mut destination = app.base_url.clone(); - destination.set_path("/"); - destination.set_query(None); + 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, @@ -262,6 +272,57 @@ async fn callback( 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, @@ -496,12 +557,19 @@ async fn link_identity( } let email = normalize(&identity.email).map_err(|()| ApiError)?; let mut tx = database.begin().await.map_err(|_| ApiError)?; - let users = tx + let owner = tx .emails() - .find_users_by_verified_email(email.as_str()) + .find_active_verified(email.as_str()) .await .map_err(|_| ApiError)?; - let user_id = if users.is_empty() { + 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); @@ -524,10 +592,6 @@ async fn link_identity( .await .map_err(|_| ApiError)?; id - } else if users.len() == 1 && users[0].status == AccountStatus::Active { - users[0].id - } else { - return Err(ApiError); }; match tx .federation() diff --git a/crates/database/migrations/0005_federation.sql b/crates/database/migrations/0005_federation.sql index 98620ddc6..12b489886 100644 --- a/crates/database/migrations/0005_federation.sql +++ b/crates/database/migrations/0005_federation.sql @@ -19,6 +19,7 @@ CREATE TABLE federation_transactions ( 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() diff --git a/crates/database/src/models.rs b/crates/database/src/models.rs index 92673e696..73e31443b 100644 --- a/crates/database/src/models.rs +++ b/crates/database/src/models.rs @@ -237,12 +237,14 @@ pub struct InsertFederationTransaction { 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 { diff --git a/crates/database/src/repositories.rs b/crates/database/src/repositories.rs index c0305a192..8b8db22b0 100644 --- a/crates/database/src/repositories.rs +++ b/crates/database/src/repositories.rs @@ -619,7 +619,7 @@ impl FederationRepository<'_> { &mut self, input: &InsertFederationTransaction, ) -> Result<(), DatabaseError> { - execute!(self,sqlx::query("INSERT INTO federation_transactions(id,provider_name,state_digest,browser_digest,nonce,pkce_verifier,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7)").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.expires_at))?; + 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( @@ -628,7 +628,7 @@ impl FederationRepository<'_> { 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").bind(provider).bind(state_digest).bind(browser_digest))?.ok_or(DatabaseError::NotFound)?; + 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") @@ -636,6 +636,9 @@ impl FederationRepository<'_> { 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( diff --git a/crates/database/tests/identity.rs b/crates/database/tests/identity.rs index c9088521c..908600905 100644 --- a/crates/database/tests/identity.rs +++ b/crates/database/tests/identity.rs @@ -238,6 +238,7 @@ async fn identity_transactions_and_concurrency_hold() { browser_digest: browser.clone(), nonce: "nonce".into(), pkce_verifier: "v".repeat(43), + return_to: "/".into(), expires_at: Utc::now() + ChronoDuration::minutes(5), }) .await