| 1 | //! OIDC relying party against Ory Hydra (spec §6). |
| 2 | //! |
| 3 | //! Authorization code flow with PKCE. The PKCE verifier, nonce, and post-login |
| 4 | //! redirect are held server-side in `auth_flows` and keyed by an opaque state |
| 5 | //! parameter, so nothing sensitive round-trips through the browser. |
| 6 | //! |
| 7 | //! Users are keyed on the `sub` claim, never on email — "emails change and are |
| 8 | //! reassigned" (spec §6). On this deployment `sub` is the Kratos identity UUID, |
| 9 | //! minted by the Account Experience consent handler at sso.dogfood.sh. |
| 10 | |
| 11 | use anyhow::{anyhow, Context, Result}; |
| 12 | use chrono::{Duration, Utc}; |
| 13 | use openidconnect::core::{CoreAuthenticationFlow, CoreClient, CoreProviderMetadata}; |
| 14 | use openidconnect::reqwest; |
| 15 | use openidconnect::{ |
| 16 | AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, OAuth2TokenResponse, |
| 17 | PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, Scope, TokenResponse, |
| 18 | }; |
| 19 | use sqlx::PgPool; |
| 20 | |
| 21 | /// Claims Dogfood needs from a completed login. |
| 22 | #[derive(Debug, Clone)] |
| 23 | pub struct Identity { |
| 24 | /// The OIDC `sub`. The stable key for `users.subject`. |
| 25 | pub subject: String, |
| 26 | pub email: Option<String>, |
| 27 | pub name: Option<String>, |
| 28 | pub preferred_username: Option<String>, |
| 29 | /// The raw ID token JWT, kept only to send as `id_token_hint` on RP- |
| 30 | /// Initiated Logout. `None` when the identity was reconstructed from the |
| 31 | /// pending-handle cookie rather than a fresh token exchange. |
| 32 | pub id_token: Option<String>, |
| 33 | } |
| 34 | |
| 35 | impl Identity { |
| 36 | /// Derive a candidate handle. |
| 37 | /// |
| 38 | /// Returns `None` when nothing clean can be derived, in which case the user |
| 39 | /// is prompted to choose one (spec §6). Deliberately conservative: a bad |
| 40 | /// automatic handle is worse than asking. |
| 41 | pub fn suggested_handle(&self) -> Option<String> { |
| 42 | let raw = self |
| 43 | .preferred_username |
| 44 | .as_deref() |
| 45 | .or_else(|| self.email.as_deref().and_then(|e| e.split('@').next()))?; |
| 46 | |
| 47 | let cleaned: String = raw |
| 48 | .to_lowercase() |
| 49 | .chars() |
| 50 | .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) |
| 51 | .collect(); |
| 52 | |
| 53 | // Collapse runs of hyphens and trim them from both ends, then apply the |
| 54 | // same rules the database CHECK enforces. |
| 55 | let mut out = String::with_capacity(cleaned.len()); |
| 56 | let mut last_hyphen = false; |
| 57 | for c in cleaned.chars() { |
| 58 | if c == '-' { |
| 59 | if !last_hyphen && !out.is_empty() { |
| 60 | out.push('-'); |
| 61 | } |
| 62 | last_hyphen = true; |
| 63 | } else { |
| 64 | out.push(c); |
| 65 | last_hyphen = false; |
| 66 | } |
| 67 | } |
| 68 | let out = out.trim_end_matches('-').to_string(); |
| 69 | |
| 70 | let valid = !out.is_empty() |
| 71 | && out.len() <= 39 |
| 72 | && out.starts_with(|c: char| c.is_ascii_lowercase() || c.is_ascii_digit()); |
| 73 | |
| 74 | valid.then_some(out) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /// A configured relying party. |
| 79 | pub struct Oidc { |
| 80 | client: CoreClient< |
| 81 | openidconnect::EndpointSet, |
| 82 | openidconnect::EndpointNotSet, |
| 83 | openidconnect::EndpointNotSet, |
| 84 | openidconnect::EndpointNotSet, |
| 85 | openidconnect::EndpointMaybeSet, |
| 86 | openidconnect::EndpointMaybeSet, |
| 87 | >, |
| 88 | http: reqwest::Client, |
| 89 | scopes: Vec<String>, |
| 90 | end_session_endpoint: Option<String>, |
| 91 | } |
| 92 | |
| 93 | impl Oidc { |
| 94 | /// Discover provider metadata and build the client. |
| 95 | /// |
| 96 | /// Called once at startup; a failure here is fatal, because an instance that |
| 97 | /// cannot authenticate anyone is not usefully running. |
| 98 | pub async fn discover( |
| 99 | issuer: &str, |
| 100 | client_id: &str, |
| 101 | client_secret: &str, |
| 102 | redirect_url: &str, |
| 103 | scopes: &str, |
| 104 | ) -> Result<Self> { |
| 105 | let http = reqwest::ClientBuilder::new() |
| 106 | // SSRF hardening: the discovery document and JWKS are the only |
| 107 | // outbound requests this process makes, and neither should ever |
| 108 | // redirect. |
| 109 | .redirect(reqwest::redirect::Policy::none()) |
| 110 | .timeout(std::time::Duration::from_secs(15)) |
| 111 | .build() |
| 112 | .context("building OIDC http client")?; |
| 113 | |
| 114 | let issuer_url = IssuerUrl::new(issuer.to_string()) |
| 115 | .with_context(|| format!("invalid OIDC_ISSUER: {issuer}"))?; |
| 116 | |
| 117 | let metadata = CoreProviderMetadata::discover_async(issuer_url.clone(), &http) |
| 118 | .await |
| 119 | .with_context(|| format!("OIDC discovery failed against {issuer}"))?; |
| 120 | |
| 121 | // `end_session_endpoint` is an RP-Initiated Logout field, not part of |
| 122 | // core OIDC discovery, so `openidconnect` puts it behind a typed |
| 123 | // additional-metadata parameter. Re-reading the document for one |
| 124 | // optional string is simpler than threading that type through, and it |
| 125 | // costs one request at startup. Absence is not an error — single logout |
| 126 | // is then unavailable and we fall back to clearing our own session. |
| 127 | let end_session_endpoint = fetch_end_session_endpoint(&http, &issuer_url).await; |
| 128 | |
| 129 | let client = CoreClient::from_provider_metadata( |
| 130 | metadata, |
| 131 | ClientId::new(client_id.to_string()), |
| 132 | Some(ClientSecret::new(client_secret.to_string())), |
| 133 | ) |
| 134 | .set_redirect_uri( |
| 135 | RedirectUrl::new(redirect_url.to_string()) |
| 136 | .with_context(|| format!("invalid OIDC_REDIRECT_URL: {redirect_url}"))?, |
| 137 | ); |
| 138 | |
| 139 | Ok(Oidc { |
| 140 | client, |
| 141 | http, |
| 142 | scopes: scopes.split_whitespace().map(str::to_string).collect(), |
| 143 | end_session_endpoint, |
| 144 | }) |
| 145 | } |
| 146 | |
| 147 | /// Build a client from provider metadata supplied directly, with no |
| 148 | /// discovery request. |
| 149 | /// |
| 150 | /// Exists so tests can construct an `AppState` without a live identity |
| 151 | /// provider. It is `#[doc(hidden)]` and takes the metadata JSON rather than |
| 152 | /// an issuer URL, so it cannot be mistaken for a supported way to configure |
| 153 | /// a real instance — production always discovers. |
| 154 | #[doc(hidden)] |
| 155 | pub fn from_metadata_json( |
| 156 | metadata_json: &str, |
| 157 | client_id: &str, |
| 158 | client_secret: &str, |
| 159 | redirect_url: &str, |
| 160 | scopes: &str, |
| 161 | ) -> Result<Self> { |
| 162 | let metadata: CoreProviderMetadata = |
| 163 | serde_json::from_str(metadata_json).context("parsing provider metadata")?; |
| 164 | |
| 165 | let client = CoreClient::from_provider_metadata( |
| 166 | metadata, |
| 167 | ClientId::new(client_id.to_string()), |
| 168 | Some(ClientSecret::new(client_secret.to_string())), |
| 169 | ) |
| 170 | .set_redirect_uri(RedirectUrl::new(redirect_url.to_string()).context("redirect url")?); |
| 171 | |
| 172 | Ok(Oidc { |
| 173 | client, |
| 174 | http: reqwest::Client::new(), |
| 175 | scopes: scopes.split_whitespace().map(str::to_string).collect(), |
| 176 | end_session_endpoint: None, |
| 177 | }) |
| 178 | } |
| 179 | |
| 180 | pub fn end_session_endpoint(&self) -> Option<&str> { |
| 181 | self.end_session_endpoint.as_deref() |
| 182 | } |
| 183 | |
| 184 | /// Begin a login: persist the flow and return the URL to redirect to. |
| 185 | /// |
| 186 | /// `redirect_after` is where to send the user once login completes. It must |
| 187 | /// already have been validated as a local path by the caller — an open |
| 188 | /// redirect here would be handed to every user who clicks a login link. |
| 189 | pub async fn begin(&self, db: &PgPool, redirect_after: Option<&str>) -> Result<String> { |
| 190 | let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256(); |
| 191 | |
| 192 | let (auth_url, csrf_state, nonce) = { |
| 193 | let mut req = self.client.authorize_url( |
| 194 | CoreAuthenticationFlow::AuthorizationCode, |
| 195 | CsrfToken::new_random, |
| 196 | Nonce::new_random, |
| 197 | ); |
| 198 | // `authorize_url` already includes `openid`; adding it again |
| 199 | // produces a duplicated scope in the request. |
| 200 | for s in self.scopes.iter().filter(|s| s.as_str() != "openid") { |
| 201 | req = req.add_scope(Scope::new(s.clone())); |
| 202 | } |
| 203 | req.set_pkce_challenge(pkce_challenge).url() |
| 204 | }; |
| 205 | |
| 206 | sqlx::query( |
| 207 | "INSERT INTO auth_flows (state, pkce_verifier, nonce, redirect_after, expires_at) |
| 208 | VALUES ($1, $2, $3, $4, $5)", |
| 209 | ) |
| 210 | .bind(csrf_state.secret()) |
| 211 | .bind(pkce_verifier.secret()) |
| 212 | .bind(nonce.secret()) |
| 213 | .bind(redirect_after) |
| 214 | // Ten minutes is generous for a login round-trip and short enough that |
| 215 | // abandoned flows do not accumulate. |
| 216 | .bind(Utc::now() + Duration::minutes(10)) |
| 217 | .execute(db) |
| 218 | .await |
| 219 | .context("persisting auth flow")?; |
| 220 | |
| 221 | Ok(auth_url.to_string()) |
| 222 | } |
| 223 | |
| 224 | /// Complete a login. Consumes the stored flow, exchanges the code, and |
| 225 | /// verifies the ID token. |
| 226 | /// |
| 227 | /// Returns the identity and the validated post-login redirect path. |
| 228 | pub async fn complete( |
| 229 | &self, |
| 230 | db: &PgPool, |
| 231 | state: &str, |
| 232 | code: &str, |
| 233 | ) -> Result<(Identity, Option<String>)> { |
| 234 | // Single-use: DELETE … RETURNING means a replayed callback finds nothing |
| 235 | // and is rejected, rather than being processed twice. |
| 236 | let row: Option<(String, String, Option<String>, chrono::DateTime<Utc>)> = sqlx::query_as( |
| 237 | "DELETE FROM auth_flows WHERE state = $1 |
| 238 | RETURNING pkce_verifier, nonce, redirect_after, expires_at", |
| 239 | ) |
| 240 | .bind(state) |
| 241 | .fetch_optional(db) |
| 242 | .await |
| 243 | .context("loading auth flow")?; |
| 244 | |
| 245 | let (verifier, nonce, redirect_after, expires_at) = |
| 246 | row.ok_or_else(|| anyhow!("unknown or already-used login state"))?; |
| 247 | |
| 248 | if expires_at < Utc::now() { |
| 249 | return Err(anyhow!("login took too long; please try again")); |
| 250 | } |
| 251 | |
| 252 | let token_response = self |
| 253 | .client |
| 254 | .exchange_code(AuthorizationCode::new(code.to_string())) |
| 255 | .map_err(|e| anyhow!("configuring code exchange: {e}"))? |
| 256 | .set_pkce_verifier(PkceCodeVerifier::new(verifier)) |
| 257 | .request_async(&self.http) |
| 258 | .await |
| 259 | .context("exchanging authorization code")?; |
| 260 | |
| 261 | let id_token = token_response |
| 262 | .id_token() |
| 263 | .ok_or_else(|| anyhow!("provider returned no ID token"))?; |
| 264 | |
| 265 | // Verifies signature, issuer, audience, expiry, and the nonce binding. |
| 266 | let claims = id_token |
| 267 | .claims(&self.client.id_token_verifier(), &Nonce::new(nonce)) |
| 268 | .context("verifying ID token")?; |
| 269 | |
| 270 | // Belt and braces: the access token hash binding, when the provider |
| 271 | // supplies it. |
| 272 | if let Some(expected) = claims.access_token_hash() { |
| 273 | let actual = openidconnect::AccessTokenHash::from_token( |
| 274 | token_response.access_token(), |
| 275 | id_token.signing_alg().map_err(|e| anyhow!("{e}"))?, |
| 276 | id_token.signing_key(&self.client.id_token_verifier()).map_err(|e| anyhow!("{e}"))?, |
| 277 | ) |
| 278 | .map_err(|e| anyhow!("computing access token hash: {e}"))?; |
| 279 | if &actual != expected { |
| 280 | return Err(anyhow!("access token hash mismatch")); |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | let identity = Identity { |
| 285 | subject: claims.subject().to_string(), |
| 286 | email: claims.email().map(|e| e.to_string()), |
| 287 | name: claims |
| 288 | .name() |
| 289 | .and_then(|n| n.get(None)) |
| 290 | .map(|n| n.to_string()), |
| 291 | preferred_username: claims.preferred_username().map(|u| u.to_string()), |
| 292 | id_token: Some(id_token.to_string()), |
| 293 | }; |
| 294 | |
| 295 | Ok((identity, redirect_after)) |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | /// Read `end_session_endpoint` out of the discovery document. |
| 300 | /// |
| 301 | /// Best-effort: any failure logs and yields `None` rather than aborting |
| 302 | /// startup, since the endpoint is optional and only affects single logout. |
| 303 | async fn fetch_end_session_endpoint( |
| 304 | http: &reqwest::Client, |
| 305 | issuer: &IssuerUrl, |
| 306 | ) -> Option<String> { |
| 307 | let url = format!( |
| 308 | "{}/.well-known/openid-configuration", |
| 309 | issuer.as_str().trim_end_matches('/') |
| 310 | ); |
| 311 | // `.text()` rather than `.json()`: the reqwest re-exported by |
| 312 | // `openidconnect` is built without the `json` feature. |
| 313 | let body = match http.get(&url).send().await { |
| 314 | Ok(r) => match r.text().await { |
| 315 | Ok(b) => b, |
| 316 | Err(e) => { |
| 317 | tracing::warn!("reading discovery document failed: {e}"); |
| 318 | return None; |
| 319 | } |
| 320 | }, |
| 321 | Err(e) => { |
| 322 | tracing::warn!("re-reading discovery document failed: {e}"); |
| 323 | return None; |
| 324 | } |
| 325 | }; |
| 326 | let doc: serde_json::Value = match serde_json::from_str(&body) { |
| 327 | Ok(v) => v, |
| 328 | Err(e) => { |
| 329 | tracing::warn!("discovery document was not JSON: {e}"); |
| 330 | return None; |
| 331 | } |
| 332 | }; |
| 333 | |
| 334 | let endpoint = doc |
| 335 | .get("end_session_endpoint") |
| 336 | .and_then(|v| v.as_str()) |
| 337 | .map(str::to_string); |
| 338 | |
| 339 | match &endpoint { |
| 340 | Some(e) => tracing::info!("single logout available at {e}"), |
| 341 | None => tracing::info!("provider advertises no end_session_endpoint; single logout disabled"), |
| 342 | } |
| 343 | endpoint |
| 344 | } |
| 345 | |
| 346 | /// Remove expired login flows. Run periodically from the worker. |
| 347 | pub async fn sweep_expired_flows(db: &PgPool) -> Result<u64> { |
| 348 | let r = sqlx::query("DELETE FROM auth_flows WHERE expires_at < now()") |
| 349 | .execute(db) |
| 350 | .await?; |
| 351 | Ok(r.rows_affected()) |
| 352 | } |
| 353 | |
| 354 | /// Validate a post-login redirect target. |
| 355 | /// |
| 356 | /// Only site-local absolute paths are allowed. Anything else — an absolute URL, |
| 357 | /// a protocol-relative `//evil.example`, or a backslash variant some browsers |
| 358 | /// normalise to `//` — is discarded rather than corrected. |
| 359 | pub fn safe_redirect(candidate: &str) -> Option<String> { |
| 360 | if !candidate.starts_with('/') { |
| 361 | return None; |
| 362 | } |
| 363 | // `//host` and `/\host` are both treated as scheme-relative by some |
| 364 | // browsers, which would make this an open redirect. |
| 365 | let rest = &candidate.as_bytes()[1..]; |
| 366 | if matches!(rest.first(), Some(b'/') | Some(b'\\')) { |
| 367 | return None; |
| 368 | } |
| 369 | if candidate.contains(['\r', '\n', '\0']) { |
| 370 | return None; |
| 371 | } |
| 372 | Some(candidate.to_string()) |
| 373 | } |
| 374 | |
| 375 | #[cfg(test)] |
| 376 | mod tests { |
| 377 | use super::*; |
| 378 | |
| 379 | fn ident(user: Option<&str>, email: Option<&str>) -> Identity { |
| 380 | Identity { |
| 381 | subject: "sub".into(), |
| 382 | email: email.map(str::to_string), |
| 383 | name: None, |
| 384 | preferred_username: user.map(str::to_string), |
| 385 | id_token: None, |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | #[test] |
| 390 | fn handle_prefers_preferred_username() { |
| 391 | assert_eq!( |
| 392 | ident(Some("alice"), Some("bob@example.com")).suggested_handle(), |
| 393 | Some("alice".into()) |
| 394 | ); |
| 395 | } |
| 396 | |
| 397 | #[test] |
| 398 | fn handle_falls_back_to_email_local_part() { |
| 399 | assert_eq!( |
| 400 | ident(None, Some("bob@example.com")).suggested_handle(), |
| 401 | Some("bob".into()) |
| 402 | ); |
| 403 | } |
| 404 | |
| 405 | #[test] |
| 406 | fn handle_is_normalised_to_the_database_constraint() { |
| 407 | // Must satisfy: ^[a-z0-9][a-z0-9-]{0,38}$ |
| 408 | assert_eq!( |
| 409 | ident(None, Some("Bob.Smith+tag@example.com")).suggested_handle(), |
| 410 | Some("bob-smith-tag".into()) |
| 411 | ); |
| 412 | assert_eq!( |
| 413 | ident(Some("Foo__Bar"), None).suggested_handle(), |
| 414 | Some("foo-bar".into()), |
| 415 | "runs of invalid characters collapse to a single hyphen" |
| 416 | ); |
| 417 | } |
| 418 | |
| 419 | #[test] |
| 420 | fn handle_is_none_when_nothing_clean_can_be_derived() { |
| 421 | assert_eq!(ident(None, None).suggested_handle(), None); |
| 422 | assert_eq!(ident(Some("___"), None).suggested_handle(), None); |
| 423 | // Must not start with a hyphen or be empty after cleaning. |
| 424 | assert_eq!(ident(Some("-"), None).suggested_handle(), None); |
| 425 | } |
| 426 | |
| 427 | #[test] |
| 428 | fn suggested_handles_always_satisfy_the_db_constraint() { |
| 429 | let re = regex_lite(); |
| 430 | for raw in [ |
| 431 | "alice", "Bob.Smith+tag@x.com", "UPPER", "a", "9lives", "x--y", |
| 432 | "trailing-", "-leading", "with space", "üñí", "a".repeat(80).as_str(), |
| 433 | ] { |
| 434 | if let Some(h) = ident(Some(raw), None).suggested_handle() { |
| 435 | assert!(re(&h), "derived handle {h:?} from {raw:?} violates the constraint"); |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | /// Mirror of the SQL CHECK, so the test does not need a regex crate. |
| 441 | fn regex_lite() -> impl Fn(&str) -> bool { |
| 442 | |h: &str| { |
| 443 | !h.is_empty() |
| 444 | && h.len() <= 39 |
| 445 | && h.chars().next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) |
| 446 | && h.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | // ─── open redirect (spec §9) ───────────────────────────────────────────── |
| 451 | |
| 452 | #[test] |
| 453 | fn safe_redirect_accepts_local_paths() { |
| 454 | assert_eq!(safe_redirect("/dogfood/repo"), Some("/dogfood/repo".into())); |
| 455 | assert_eq!(safe_redirect("/"), Some("/".into())); |
| 456 | } |
| 457 | |
| 458 | #[test] |
| 459 | fn safe_redirect_rejects_off_site_targets() { |
| 460 | for bad in [ |
| 461 | "https://evil.example", |
| 462 | "//evil.example", |
| 463 | "/\\evil.example", |
| 464 | "http://evil.example", |
| 465 | "evil.example", |
| 466 | "", |
| 467 | "/path\r\nSet-Cookie: x=y", |
| 468 | "/path\0", |
| 469 | ] { |
| 470 | assert_eq!(safe_redirect(bad), None, "must reject redirect target {bad:?}"); |
| 471 | } |
| 472 | } |
| 473 | } |
473 lines · Rust