Jump to…
snowinitial commitqoxwzsukwmkx1mo
Matt W1//! OIDC relying party against Ory Hydra (spec §6).
Matt W2//!
Matt W3//! Authorization code flow with PKCE. The PKCE verifier, nonce, and post-login
Matt W4//! redirect are held server-side in `auth_flows` and keyed by an opaque state
Matt W5//! parameter, so nothing sensitive round-trips through the browser.
Matt W6//!
Matt W7//! Users are keyed on the `sub` claim, never on email — "emails change and are
Matt W8//! reassigned" (spec §6). On this deployment `sub` is the Kratos identity UUID,
Matt W9//! minted by the Account Experience consent handler at sso.dogfood.sh.
Matt W10
Matt W11use anyhow::{anyhow, Context, Result};
Matt W12use chrono::{Duration, Utc};
Matt W13use openidconnect::core::{CoreAuthenticationFlow, CoreClient, CoreProviderMetadata};
Matt W14use openidconnect::reqwest;
Matt W15use openidconnect::{
Matt W16 AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, OAuth2TokenResponse,
Matt W17 PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, Scope, TokenResponse,
Matt W18};
Matt W19use sqlx::PgPool;
Matt W20
Matt W21/// Claims Dogfood needs from a completed login.
Matt W22#[derive(Debug, Clone)]
Matt W23pub struct Identity {
Matt W24 /// The OIDC `sub`. The stable key for `users.subject`.
Matt W25 pub subject: String,
Matt W26 pub email: Option<String>,
Matt W27 pub name: Option<String>,
Matt W28 pub preferred_username: Option<String>,
Matt W29 /// The raw ID token JWT, kept only to send as `id_token_hint` on RP-
Matt W30 /// Initiated Logout. `None` when the identity was reconstructed from the
Matt W31 /// pending-handle cookie rather than a fresh token exchange.
Matt W32 pub id_token: Option<String>,
Matt W33}
Matt W34
Matt W35impl Identity {
Matt W36 /// Derive a candidate handle.
Matt W37 ///
Matt W38 /// Returns `None` when nothing clean can be derived, in which case the user
Matt W39 /// is prompted to choose one (spec §6). Deliberately conservative: a bad
Matt W40 /// automatic handle is worse than asking.
Matt W41 pub fn suggested_handle(&self) -> Option<String> {
Matt W42 let raw = self
Matt W43 .preferred_username
Matt W44 .as_deref()
Matt W45 .or_else(|| self.email.as_deref().and_then(|e| e.split('@').next()))?;
Matt W46
Matt W47 let cleaned: String = raw
Matt W48 .to_lowercase()
Matt W49 .chars()
Matt W50 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
Matt W51 .collect();
Matt W52
Matt W53 // Collapse runs of hyphens and trim them from both ends, then apply the
Matt W54 // same rules the database CHECK enforces.
Matt W55 let mut out = String::with_capacity(cleaned.len());
Matt W56 let mut last_hyphen = false;
Matt W57 for c in cleaned.chars() {
Matt W58 if c == '-' {
Matt W59 if !last_hyphen && !out.is_empty() {
Matt W60 out.push('-');
Matt W61 }
Matt W62 last_hyphen = true;
Matt W63 } else {
Matt W64 out.push(c);
Matt W65 last_hyphen = false;
Matt W66 }
Matt W67 }
Matt W68 let out = out.trim_end_matches('-').to_string();
Matt W69
Matt W70 let valid = !out.is_empty()
Matt W71 && out.len() <= 39
Matt W72 && out.starts_with(|c: char| c.is_ascii_lowercase() || c.is_ascii_digit());
Matt W73
Matt W74 valid.then_some(out)
Matt W75 }
Matt W76}
Matt W77
Matt W78/// A configured relying party.
Matt W79pub struct Oidc {
Matt W80 client: CoreClient<
Matt W81 openidconnect::EndpointSet,
Matt W82 openidconnect::EndpointNotSet,
Matt W83 openidconnect::EndpointNotSet,
Matt W84 openidconnect::EndpointNotSet,
Matt W85 openidconnect::EndpointMaybeSet,
Matt W86 openidconnect::EndpointMaybeSet,
Matt W87 >,
Matt W88 http: reqwest::Client,
Matt W89 scopes: Vec<String>,
Matt W90 end_session_endpoint: Option<String>,
Matt W91}
Matt W92
Matt W93impl Oidc {
Matt W94 /// Discover provider metadata and build the client.
Matt W95 ///
Matt W96 /// Called once at startup; a failure here is fatal, because an instance that
Matt W97 /// cannot authenticate anyone is not usefully running.
Matt W98 pub async fn discover(
Matt W99 issuer: &str,
Matt W100 client_id: &str,
Matt W101 client_secret: &str,
Matt W102 redirect_url: &str,
Matt W103 scopes: &str,
Matt W104 ) -> Result<Self> {
Matt W105 let http = reqwest::ClientBuilder::new()
Matt W106 // SSRF hardening: the discovery document and JWKS are the only
Matt W107 // outbound requests this process makes, and neither should ever
Matt W108 // redirect.
Matt W109 .redirect(reqwest::redirect::Policy::none())
Matt W110 .timeout(std::time::Duration::from_secs(15))
Matt W111 .build()
Matt W112 .context("building OIDC http client")?;
Matt W113
Matt W114 let issuer_url = IssuerUrl::new(issuer.to_string())
Matt W115 .with_context(|| format!("invalid OIDC_ISSUER: {issuer}"))?;
Matt W116
Matt W117 let metadata = CoreProviderMetadata::discover_async(issuer_url.clone(), &http)
Matt W118 .await
Matt W119 .with_context(|| format!("OIDC discovery failed against {issuer}"))?;
Matt W120
Matt W121 // `end_session_endpoint` is an RP-Initiated Logout field, not part of
Matt W122 // core OIDC discovery, so `openidconnect` puts it behind a typed
Matt W123 // additional-metadata parameter. Re-reading the document for one
Matt W124 // optional string is simpler than threading that type through, and it
Matt W125 // costs one request at startup. Absence is not an error — single logout
Matt W126 // is then unavailable and we fall back to clearing our own session.
Matt W127 let end_session_endpoint = fetch_end_session_endpoint(&http, &issuer_url).await;
Matt W128
Matt W129 let client = CoreClient::from_provider_metadata(
Matt W130 metadata,
Matt W131 ClientId::new(client_id.to_string()),
Matt W132 Some(ClientSecret::new(client_secret.to_string())),
Matt W133 )
Matt W134 .set_redirect_uri(
Matt W135 RedirectUrl::new(redirect_url.to_string())
Matt W136 .with_context(|| format!("invalid OIDC_REDIRECT_URL: {redirect_url}"))?,
Matt W137 );
Matt W138
Matt W139 Ok(Oidc {
Matt W140 client,
Matt W141 http,
Matt W142 scopes: scopes.split_whitespace().map(str::to_string).collect(),
Matt W143 end_session_endpoint,
Matt W144 })
Matt W145 }
Matt W146
Matt W147 /// Build a client from provider metadata supplied directly, with no
Matt W148 /// discovery request.
Matt W149 ///
Matt W150 /// Exists so tests can construct an `AppState` without a live identity
Matt W151 /// provider. It is `#[doc(hidden)]` and takes the metadata JSON rather than
Matt W152 /// an issuer URL, so it cannot be mistaken for a supported way to configure
Matt W153 /// a real instance — production always discovers.
Matt W154 #[doc(hidden)]
Matt W155 pub fn from_metadata_json(
Matt W156 metadata_json: &str,
Matt W157 client_id: &str,
Matt W158 client_secret: &str,
Matt W159 redirect_url: &str,
Matt W160 scopes: &str,
Matt W161 ) -> Result<Self> {
Matt W162 let metadata: CoreProviderMetadata =
Matt W163 serde_json::from_str(metadata_json).context("parsing provider metadata")?;
Matt W164
Matt W165 let client = CoreClient::from_provider_metadata(
Matt W166 metadata,
Matt W167 ClientId::new(client_id.to_string()),
Matt W168 Some(ClientSecret::new(client_secret.to_string())),
Matt W169 )
Matt W170 .set_redirect_uri(RedirectUrl::new(redirect_url.to_string()).context("redirect url")?);
Matt W171
Matt W172 Ok(Oidc {
Matt W173 client,
Matt W174 http: reqwest::Client::new(),
Matt W175 scopes: scopes.split_whitespace().map(str::to_string).collect(),
Matt W176 end_session_endpoint: None,
Matt W177 })
Matt W178 }
Matt W179
Matt W180 pub fn end_session_endpoint(&self) -> Option<&str> {
Matt W181 self.end_session_endpoint.as_deref()
Matt W182 }
Matt W183
Matt W184 /// Begin a login: persist the flow and return the URL to redirect to.
Matt W185 ///
Matt W186 /// `redirect_after` is where to send the user once login completes. It must
Matt W187 /// already have been validated as a local path by the caller — an open
Matt W188 /// redirect here would be handed to every user who clicks a login link.
Matt W189 pub async fn begin(&self, db: &PgPool, redirect_after: Option<&str>) -> Result<String> {
Matt W190 let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
Matt W191
Matt W192 let (auth_url, csrf_state, nonce) = {
Matt W193 let mut req = self.client.authorize_url(
Matt W194 CoreAuthenticationFlow::AuthorizationCode,
Matt W195 CsrfToken::new_random,
Matt W196 Nonce::new_random,
Matt W197 );
Matt W198 // `authorize_url` already includes `openid`; adding it again
Matt W199 // produces a duplicated scope in the request.
Matt W200 for s in self.scopes.iter().filter(|s| s.as_str() != "openid") {
Matt W201 req = req.add_scope(Scope::new(s.clone()));
Matt W202 }
Matt W203 req.set_pkce_challenge(pkce_challenge).url()
Matt W204 };
Matt W205
Matt W206 sqlx::query(
Matt W207 "INSERT INTO auth_flows (state, pkce_verifier, nonce, redirect_after, expires_at)
Matt W208 VALUES ($1, $2, $3, $4, $5)",
Matt W209 )
Matt W210 .bind(csrf_state.secret())
Matt W211 .bind(pkce_verifier.secret())
Matt W212 .bind(nonce.secret())
Matt W213 .bind(redirect_after)
Matt W214 // Ten minutes is generous for a login round-trip and short enough that
Matt W215 // abandoned flows do not accumulate.
Matt W216 .bind(Utc::now() + Duration::minutes(10))
Matt W217 .execute(db)
Matt W218 .await
Matt W219 .context("persisting auth flow")?;
Matt W220
Matt W221 Ok(auth_url.to_string())
Matt W222 }
Matt W223
Matt W224 /// Complete a login. Consumes the stored flow, exchanges the code, and
Matt W225 /// verifies the ID token.
Matt W226 ///
Matt W227 /// Returns the identity and the validated post-login redirect path.
Matt W228 pub async fn complete(
Matt W229 &self,
Matt W230 db: &PgPool,
Matt W231 state: &str,
Matt W232 code: &str,
Matt W233 ) -> Result<(Identity, Option<String>)> {
Matt W234 // Single-use: DELETE … RETURNING means a replayed callback finds nothing
Matt W235 // and is rejected, rather than being processed twice.
Matt W236 let row: Option<(String, String, Option<String>, chrono::DateTime<Utc>)> = sqlx::query_as(
Matt W237 "DELETE FROM auth_flows WHERE state = $1
Matt W238 RETURNING pkce_verifier, nonce, redirect_after, expires_at",
Matt W239 )
Matt W240 .bind(state)
Matt W241 .fetch_optional(db)
Matt W242 .await
Matt W243 .context("loading auth flow")?;
Matt W244
Matt W245 let (verifier, nonce, redirect_after, expires_at) =
Matt W246 row.ok_or_else(|| anyhow!("unknown or already-used login state"))?;
Matt W247
Matt W248 if expires_at < Utc::now() {
Matt W249 return Err(anyhow!("login took too long; please try again"));
Matt W250 }
Matt W251
Matt W252 let token_response = self
Matt W253 .client
Matt W254 .exchange_code(AuthorizationCode::new(code.to_string()))
Matt W255 .map_err(|e| anyhow!("configuring code exchange: {e}"))?
Matt W256 .set_pkce_verifier(PkceCodeVerifier::new(verifier))
Matt W257 .request_async(&self.http)
Matt W258 .await
Matt W259 .context("exchanging authorization code")?;
Matt W260
Matt W261 let id_token = token_response
Matt W262 .id_token()
Matt W263 .ok_or_else(|| anyhow!("provider returned no ID token"))?;
Matt W264
Matt W265 // Verifies signature, issuer, audience, expiry, and the nonce binding.
Matt W266 let claims = id_token
Matt W267 .claims(&self.client.id_token_verifier(), &Nonce::new(nonce))
Matt W268 .context("verifying ID token")?;
Matt W269
Matt W270 // Belt and braces: the access token hash binding, when the provider
Matt W271 // supplies it.
Matt W272 if let Some(expected) = claims.access_token_hash() {
Matt W273 let actual = openidconnect::AccessTokenHash::from_token(
Matt W274 token_response.access_token(),
Matt W275 id_token.signing_alg().map_err(|e| anyhow!("{e}"))?,
Matt W276 id_token.signing_key(&self.client.id_token_verifier()).map_err(|e| anyhow!("{e}"))?,
Matt W277 )
Matt W278 .map_err(|e| anyhow!("computing access token hash: {e}"))?;
Matt W279 if &actual != expected {
Matt W280 return Err(anyhow!("access token hash mismatch"));
Matt W281 }
Matt W282 }
Matt W283
Matt W284 let identity = Identity {
Matt W285 subject: claims.subject().to_string(),
Matt W286 email: claims.email().map(|e| e.to_string()),
Matt W287 name: claims
Matt W288 .name()
Matt W289 .and_then(|n| n.get(None))
Matt W290 .map(|n| n.to_string()),
Matt W291 preferred_username: claims.preferred_username().map(|u| u.to_string()),
Matt W292 id_token: Some(id_token.to_string()),
Matt W293 };
Matt W294
Matt W295 Ok((identity, redirect_after))
Matt W296 }
Matt W297}
Matt W298
Matt W299/// Read `end_session_endpoint` out of the discovery document.
Matt W300///
Matt W301/// Best-effort: any failure logs and yields `None` rather than aborting
Matt W302/// startup, since the endpoint is optional and only affects single logout.
Matt W303async fn fetch_end_session_endpoint(
Matt W304 http: &reqwest::Client,
Matt W305 issuer: &IssuerUrl,
Matt W306) -> Option<String> {
Matt W307 let url = format!(
Matt W308 "{}/.well-known/openid-configuration",
Matt W309 issuer.as_str().trim_end_matches('/')
Matt W310 );
Matt W311 // `.text()` rather than `.json()`: the reqwest re-exported by
Matt W312 // `openidconnect` is built without the `json` feature.
Matt W313 let body = match http.get(&url).send().await {
Matt W314 Ok(r) => match r.text().await {
Matt W315 Ok(b) => b,
Matt W316 Err(e) => {
Matt W317 tracing::warn!("reading discovery document failed: {e}");
Matt W318 return None;
Matt W319 }
Matt W320 },
Matt W321 Err(e) => {
Matt W322 tracing::warn!("re-reading discovery document failed: {e}");
Matt W323 return None;
Matt W324 }
Matt W325 };
Matt W326 let doc: serde_json::Value = match serde_json::from_str(&body) {
Matt W327 Ok(v) => v,
Matt W328 Err(e) => {
Matt W329 tracing::warn!("discovery document was not JSON: {e}");
Matt W330 return None;
Matt W331 }
Matt W332 };
Matt W333
Matt W334 let endpoint = doc
Matt W335 .get("end_session_endpoint")
Matt W336 .and_then(|v| v.as_str())
Matt W337 .map(str::to_string);
Matt W338
Matt W339 match &endpoint {
Matt W340 Some(e) => tracing::info!("single logout available at {e}"),
Matt W341 None => tracing::info!("provider advertises no end_session_endpoint; single logout disabled"),
Matt W342 }
Matt W343 endpoint
Matt W344}
Matt W345
Matt W346/// Remove expired login flows. Run periodically from the worker.
Matt W347pub async fn sweep_expired_flows(db: &PgPool) -> Result<u64> {
Matt W348 let r = sqlx::query("DELETE FROM auth_flows WHERE expires_at < now()")
Matt W349 .execute(db)
Matt W350 .await?;
Matt W351 Ok(r.rows_affected())
Matt W352}
Matt W353
Matt W354/// Validate a post-login redirect target.
Matt W355///
Matt W356/// Only site-local absolute paths are allowed. Anything else — an absolute URL,
Matt W357/// a protocol-relative `//evil.example`, or a backslash variant some browsers
Matt W358/// normalise to `//` — is discarded rather than corrected.
Matt W359pub fn safe_redirect(candidate: &str) -> Option<String> {
Matt W360 if !candidate.starts_with('/') {
Matt W361 return None;
Matt W362 }
Matt W363 // `//host` and `/\host` are both treated as scheme-relative by some
Matt W364 // browsers, which would make this an open redirect.
Matt W365 let rest = &candidate.as_bytes()[1..];
Matt W366 if matches!(rest.first(), Some(b'/') | Some(b'\\')) {
Matt W367 return None;
Matt W368 }
Matt W369 if candidate.contains(['\r', '\n', '\0']) {
Matt W370 return None;
Matt W371 }
Matt W372 Some(candidate.to_string())
Matt W373}
Matt W374
Matt W375#[cfg(test)]
Matt W376mod tests {
Matt W377 use super::*;
Matt W378
Matt W379 fn ident(user: Option<&str>, email: Option<&str>) -> Identity {
Matt W380 Identity {
Matt W381 subject: "sub".into(),
Matt W382 email: email.map(str::to_string),
Matt W383 name: None,
Matt W384 preferred_username: user.map(str::to_string),
Matt W385 id_token: None,
Matt W386 }
Matt W387 }
Matt W388
Matt W389 #[test]
Matt W390 fn handle_prefers_preferred_username() {
Matt W391 assert_eq!(
Matt W392 ident(Some("alice"), Some("bob@example.com")).suggested_handle(),
Matt W393 Some("alice".into())
Matt W394 );
Matt W395 }
Matt W396
Matt W397 #[test]
Matt W398 fn handle_falls_back_to_email_local_part() {
Matt W399 assert_eq!(
Matt W400 ident(None, Some("bob@example.com")).suggested_handle(),
Matt W401 Some("bob".into())
Matt W402 );
Matt W403 }
Matt W404
Matt W405 #[test]
Matt W406 fn handle_is_normalised_to_the_database_constraint() {
Matt W407 // Must satisfy: ^[a-z0-9][a-z0-9-]{0,38}$
Matt W408 assert_eq!(
Matt W409 ident(None, Some("Bob.Smith+tag@example.com")).suggested_handle(),
Matt W410 Some("bob-smith-tag".into())
Matt W411 );
Matt W412 assert_eq!(
Matt W413 ident(Some("Foo__Bar"), None).suggested_handle(),
Matt W414 Some("foo-bar".into()),
Matt W415 "runs of invalid characters collapse to a single hyphen"
Matt W416 );
Matt W417 }
Matt W418
Matt W419 #[test]
Matt W420 fn handle_is_none_when_nothing_clean_can_be_derived() {
Matt W421 assert_eq!(ident(None, None).suggested_handle(), None);
Matt W422 assert_eq!(ident(Some("___"), None).suggested_handle(), None);
Matt W423 // Must not start with a hyphen or be empty after cleaning.
Matt W424 assert_eq!(ident(Some("-"), None).suggested_handle(), None);
Matt W425 }
Matt W426
Matt W427 #[test]
Matt W428 fn suggested_handles_always_satisfy_the_db_constraint() {
Matt W429 let re = regex_lite();
Matt W430 for raw in [
Matt W431 "alice", "Bob.Smith+tag@x.com", "UPPER", "a", "9lives", "x--y",
Matt W432 "trailing-", "-leading", "with space", "üñí", "a".repeat(80).as_str(),
Matt W433 ] {
Matt W434 if let Some(h) = ident(Some(raw), None).suggested_handle() {
Matt W435 assert!(re(&h), "derived handle {h:?} from {raw:?} violates the constraint");
Matt W436 }
Matt W437 }
Matt W438 }
Matt W439
Matt W440 /// Mirror of the SQL CHECK, so the test does not need a regex crate.
Matt W441 fn regex_lite() -> impl Fn(&str) -> bool {
Matt W442 |h: &str| {
Matt W443 !h.is_empty()
Matt W444 && h.len() <= 39
Matt W445 && h.chars().next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
Matt W446 && h.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
Matt W447 }
Matt W448 }
Matt W449
Matt W450 // ─── open redirect (spec §9) ─────────────────────────────────────────────
Matt W451
Matt W452 #[test]
Matt W453 fn safe_redirect_accepts_local_paths() {
Matt W454 assert_eq!(safe_redirect("/dogfood/repo"), Some("/dogfood/repo".into()));
Matt W455 assert_eq!(safe_redirect("/"), Some("/".into()));
Matt W456 }
Matt W457
Matt W458 #[test]
Matt W459 fn safe_redirect_rejects_off_site_targets() {
Matt W460 for bad in [
Matt W461 "https://evil.example",
Matt W462 "//evil.example",
Matt W463 "/\\evil.example",
Matt W464 "http://evil.example",
Matt W465 "evil.example",
Matt W466 "",
Matt W467 "/path\r\nSet-Cookie: x=y",
Matt W468 "/path\0",
Matt W469 ] {
Matt W470 assert_eq!(safe_redirect(bad), None, "must reject redirect target {bad:?}");
Matt W471 }
Matt W472 }
Matt W473}

473 lines · Rust