//! The OpenID Connect relying party for `im` (docs/contracts.md section 2), and the client //! credentials token that iz uses to read the people directory (section 2.6). //! //! It finds `im`'s endpoints through discovery and keeps them for an hour. It keeps `im`'s signing //! keys (JWKS) for ten minutes, and refetches them at most once a minute when a token names a key that //! is not known. It exchanges authorization codes, and it verifies ID tokens and logout tokens. //! //! It decides nothing about who may sign in: that is `pages/sign_in.rs` and the store. It keeps no //! session state: that is `iz_core::store::sessions`. //! //! Verification accepts EdDSA only. The shape, the algorithm and the `kid` are checked before any key //! set is fetched, so `none` and every other algorithm are refused without a call to `im`. The checks //! are: the signature, `iss` equal to the configured issuer, `aud` equal to the client id, `exp` and //! `nbf` with 60 seconds of leeway, `iat` not more than five minutes ahead, and the claims each token //! kind needs. The pure functions below take the key set and the clock as arguments, so the tests can //! run without a network. use std::collections::HashMap; use std::fmt; use std::path::Path; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; use futures_util::StreamExt; use iz_core::config::OidcConfig; use iz_core::token::constant_time_eq; use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; use serde::Deserialize; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; use tokio::sync::Mutex; /// The scope that reads the people directory and its photos at `im`. pub const DIRECTORY_SCOPE: &str = "directory.read"; /// The audience of every directory call: the family key of `im`. pub const IM_AUDIENCE: &str = "im"; /// The scopes asked for at sign-in. `openid` is required; `profile` and `email` carry the claims iz uses. pub const SIGN_IN_SCOPE: &str = "openid profile email"; /// The event name a back-channel logout token must carry (OIDC Back-Channel Logout 1.0). pub const BACKCHANNEL_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; /// Longest wait for one call to `im`, in seconds. Reason: a slow identity provider must not hold a /// request, and the directory worker retries with backoff anyway. pub const IM_TIMEOUT: Duration = Duration::from_secs(10); /// Clock skew tolerated on `exp`, in seconds. Reason: the task policy for every token check. pub const LEEWAY_SECS: u64 = 60; /// How far ahead of the local clock an `iat` may be, in seconds. Reason: contracts.md 2.3, five minutes. pub const MAX_IAT_AHEAD_SECS: u64 = 300; /// Largest discovery, JWKS or token response read from `im`, in bytes. Reason: those documents are /// a few kilobytes; a larger answer is not what `im` sends. pub const MAX_RESPONSE_BYTES: usize = 256 * 1024; /// How long discovery is cached, before it is fetched again. const DISCOVERY_TTL: Duration = Duration::from_secs(3600); /// How long the JWKS is cached, before it is fetched again (contracts.md 2.2). const KEYS_TTL: Duration = Duration::from_secs(600); /// The shortest gap between two JWKS fetch attempts (contracts.md 2.2). It bounds the refetch for unknown /// key ids, and the retries after a failed fetch, so an unreachable `im` is not asked once per request. const UNKNOWN_KEY_REFETCH: Duration = Duration::from_secs(60); /// A service token is replaced this long before it expires (contracts.md 2.6). const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); /// Every failure of a call to `im` or of a token check. #[derive(Debug, thiserror::Error)] pub enum ImError { /// The token is signed with a key id that is not in the key set. The caller may refetch the /// keys once and check again. #[error("the token names a key that is not published")] UnknownKey, /// The token failed a check. The text names the check; it is for logs only. #[error("the token was rejected: {0}")] Rejected(String), /// `im` could not be reached, or it did not answer in time. #[error("the account service cannot be reached: {0}")] Unavailable(String), /// `im` answered, but not in a form iz accepts. #[error("the account service answered in an unexpected way: {0}")] BadResponse(String), } /// The result of a call to `im` or of a token check. pub type ImResult = std::result::Result; /// The part of the discovery document that iz uses (contracts.md 2.1). #[derive(Debug, Deserialize)] pub struct Discovery { /// Must equal the configured issuer exactly. pub issuer: String, /// Where the browser is sent to sign in. pub authorization_endpoint: String, /// Where codes and client credentials are exchanged for tokens. pub token_endpoint: String, /// Where the signing keys are published. pub jwks_uri: String, /// Where the browser is sent to end its `im` session. #[serde(default)] pub end_session_endpoint: Option, } /// The answer of the token endpoint. The refresh token is not read: iz discards it (contracts.md 2.4). #[derive(Deserialize)] pub struct TokenResponse { /// The ID token, for an authorization-code exchange. #[serde(default)] pub id_token: Option, /// The access token, for a client-credentials grant. #[serde(default)] pub access_token: Option, /// The lifetime of the access token, in seconds. #[serde(default)] pub expires_in: Option, } // Hand-written so that a debug print never shows the ID token or the access token. impl fmt::Debug for TokenResponse { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TokenResponse") .field("id_token", &self.id_token.as_ref().map(|_| "")) .field( "access_token", &self.access_token.as_ref().map(|_| ""), ) .field("expires_in", &self.expires_in) .finish() } } /// The claims of an ID token that iz uses. `sid` is the `im` browser session. #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] pub struct IdClaims { /// The user's id (a ULID, stable forever). pub sub: String, /// The `im` browser session id, kept with the local session for back-channel logout. #[serde(default)] pub sid: Option, /// The address. `im` only stores confirmed addresses. #[serde(default)] pub email: Option, /// The display name. #[serde(default)] pub name: Option, /// Whether `im` marks the user as an instance administrator. #[serde(default)] pub admin: bool, /// The language the user chose in `im`, `en` or `tr`. #[serde(default)] pub locale: Option, /// The user's IANA time zone, for example `Europe/Istanbul`. #[serde(default)] pub zoneinfo: Option, /// Bumps when the photo changes. Used as the avatar cache key. #[serde(default)] pub picture_version: i64, /// When `im` issued the token, in Unix seconds. Orders a sign-in against directory changes. #[serde(default)] pub iat: i64, } /// The claims of a back-channel logout token that iz uses. #[derive(Debug, Clone, PartialEq, Eq)] pub struct LogoutClaims { /// The token id, refused when it is seen again. pub jti: String, /// The `im` browser session that ended, when the token names one. pub sid: Option, /// The user whose sessions end, when the token names one. pub sub: Option, } #[derive(Deserialize)] struct JwksDocument { keys: Vec, } #[derive(Deserialize)] struct Jwk { kty: String, #[serde(default)] crv: Option, #[serde(default)] x: Option, #[serde(default)] kid: Option, #[serde(default)] alg: Option, } /// The verification keys of `im`, by key id. Only Ed25519 keys are kept; others are skipped. #[derive(Default)] pub struct KeySet { keys: HashMap, } impl KeySet { /// Reads a JWKS document. Keys that are not Ed25519 or have no `kid` are skipped, not fatal. pub fn from_jwks(bytes: &[u8]) -> ImResult { let document: JwksDocument = serde_json::from_slice(bytes) .map_err(|e| ImError::BadResponse(format!("the key set is not JSON: {e}")))?; let mut keys = HashMap::new(); for jwk in document.keys { let (Some(kid), Some(x)) = (jwk.kid.as_deref(), jwk.x.as_deref()) else { continue; }; let is_ed25519 = jwk.kty == "OKP" && jwk.crv.as_deref() == Some("Ed25519"); if !is_ed25519 || jwk.alg.as_deref().is_some_and(|alg| alg != "EdDSA") { continue; } match DecodingKey::from_ed_components(x) { Ok(key) => { keys.insert(kid.to_owned(), key); } Err(e) => tracing::warn!(kid, error = %e, "skipping an unreadable signing key"), } } Ok(KeySet { keys }) } fn get(&self, kid: &str) -> Option<&DecodingKey> { self.keys.get(kid) } } /// The client of `im`: discovery, keys, token calls and token checks. One per process. pub struct OidcClient { issuer: String, client_id: String, client_secret: String, redirect_uri: String, post_logout_uri: String, /// Short calls: discovery, keys, tokens, photos. The timeout applies to the whole call. http: reqwest::Client, /// Long-lived event stream. Only the connect is bounded here; the reader has its own idle limit. stream_http: reqwest::Client, discovery: Mutex)>>, keys: Mutex, /// Held across a JWKS fetch, so one fetch runs at a time. It is never held together with `keys`, /// which is only locked for reads and writes of the cache. refresh: Mutex<()>, /// Client-credentials tokens by `(audience, scope)`. Each target has its own entry. service: Mutex>, } #[derive(Default)] struct KeyCache { /// The last key set fetched, and when it was fetched. current: Option<(Instant, Arc)>, /// When the keys were last fetched for an unknown key, or a fetch failed. Limits those fetches. last_fetch: Option, } impl OidcClient { /// Builds the client. `base_url` is the public origin of iz, from which the callback and the /// post-logout URIs are derived; `im` has these registered for the client. pub fn new( config: &OidcConfig, base_url: &str, client_secret: String, ) -> iz_core::Result { // Redirects are never followed: a token call that is redirected would send the client // secret to another host. let http = reqwest::Client::builder() .timeout(IM_TIMEOUT) .connect_timeout(IM_TIMEOUT) .redirect(reqwest::redirect::Policy::none()) .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) .build() .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?; let stream_http = reqwest::Client::builder() .connect_timeout(IM_TIMEOUT) .redirect(reqwest::redirect::Policy::none()) .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) .build() .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?; Ok(OidcClient { issuer: config.issuer.clone(), client_id: config.client_id.clone(), client_secret, redirect_uri: format!("{base_url}/auth/callback"), post_logout_uri: format!("{base_url}/"), http, stream_http, discovery: Mutex::new(None), keys: Mutex::new(KeyCache::default()), refresh: Mutex::new(()), service: Mutex::new(HashMap::new()), }) } /// The configured issuer, exactly as it is compared with `iss`. pub fn issuer(&self) -> &str { &self.issuer } /// The short-call HTTP client. pub fn http(&self) -> &reqwest::Client { &self.http } /// The event-stream HTTP client. pub fn stream_http(&self) -> &reqwest::Client { &self.stream_http } /// The discovery document, fetched once and kept for an hour. pub async fn discovery(&self) -> ImResult> { let mut slot = self.discovery.lock().await; if let Some((at, doc)) = slot.as_ref() && at.elapsed() < DISCOVERY_TTL { return Ok(doc.clone()); } let url = format!("{}/.well-known/openid-configuration", self.issuer); let response = self.http.get(url).send().await.map_err(unavailable)?; if !response.status().is_success() { return Err(ImError::Unavailable(format!( "discovery answered {}", response.status().as_u16() ))); } let body = read_limited(response, MAX_RESPONSE_BYTES).await?; let doc: Discovery = serde_json::from_slice(&body) .map_err(|e| ImError::BadResponse(format!("discovery: {e}")))?; if doc.issuer != self.issuer { return Err(ImError::BadResponse( "discovery names another issuer".into(), )); } let doc = Arc::new(doc); *slot = Some((Instant::now(), doc.clone())); Ok(doc) } /// The key set to check a token against. A fresh cached set is used as it is. An expired one is /// fetched again, and when that fails the cached set is kept and used (contracts.md 2.2). With /// `refetch_unknown` set, a token names a key that is not in the set, so it is fetched again once /// [`UNKNOWN_KEY_REFETCH`] has passed since the last attempt. async fn key_set(&self, refetch_unknown: bool) -> ImResult> { if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? { return Ok(keys); } // One fetch at a time. The cache lock is not held here, so a slow `im` stalls only the callers // that need a fetch, never a caller that a cached set can answer. A caller that waited may find // the set refreshed by the one before it. let _single_flight = self.refresh.lock().await; if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? { return Ok(keys); } // Only a refetch for an unknown key or a failure starts the gap. A scheduled fetch does not, so the // first token signed by a newly rotated key is verified at once. if refetch_unknown { self.keys.lock().await.last_fetch = Some(Instant::now()); } let fetched = self.fetch_keys().await; let mut cache = self.keys.lock().await; if fetched.is_err() { cache.last_fetch = Some(Instant::now()); } match fetched { Ok(keys) => { cache.current = Some((Instant::now(), keys.clone())); Ok(keys) } Err(error) => match &cache.current { Some((_, keys)) => { tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys"); Ok(keys.clone()) } None => Err(error), }, } } /// The cached key set, when no fetch is due: it is fresh, or a fetch was attempted less than /// [`UNKNOWN_KEY_REFETCH`] ago (see `last_fetch`). `None` when a fetch is due. With no cached set and a fetch attempted /// that recently, the answer is an error at once, without a network call. async fn keys_without_fetch(&self, refetch_unknown: bool) -> ImResult>> { let cache = self.keys.lock().await; let attempted_recently = cache .last_fetch .is_some_and(|at| at.elapsed() < UNKNOWN_KEY_REFETCH); match &cache.current { Some((at, keys)) => { let fresh = at.elapsed() < KEYS_TTL && !refetch_unknown; Ok((fresh || attempted_recently).then(|| keys.clone())) } None if attempted_recently => Err(ImError::Unavailable( "the key set has not been fetched yet".into(), )), None => Ok(None), } } /// Fetches the key set from `im`'s JWKS endpoint. Called only under `refresh`. async fn fetch_keys(&self) -> ImResult> { let discovery = self.discovery().await?; let response = self .http .get(&discovery.jwks_uri) .send() .await .map_err(unavailable)?; if !response.status().is_success() { return Err(ImError::Unavailable(format!( "the key set answered {}", response.status().as_u16() ))); } let body = read_limited(response, MAX_RESPONSE_BYTES).await?; Ok(Arc::new(KeySet::from_jwks(&body)?)) } /// Runs a check against the cached keys. A token that names an unknown key gets one more try /// against a fresh key set, which the rate bound may refuse. async fn with_keys(&self, check: impl Fn(&KeySet) -> ImResult) -> ImResult { let keys = self.key_set(false).await?; match check(&keys) { Err(ImError::UnknownKey) => { let keys = self.key_set(true).await?; match check(&keys) { Err(ImError::UnknownKey) => { Err(ImError::Rejected("the signing key is not published".into())) } other => other, } } other => other, } } /// The authorization URL for a sign-in, with PKCE (S256) and the state and nonce of this flight. pub async fn authorize_url( &self, state: &str, nonce: &str, challenge: &str, ) -> ImResult { let discovery = self.discovery().await?; let mut url = reqwest::Url::parse(&discovery.authorization_endpoint) .map_err(|e| ImError::BadResponse(format!("authorization endpoint: {e}")))?; url.query_pairs_mut() .append_pair("response_type", "code") .append_pair("client_id", &self.client_id) .append_pair("redirect_uri", &self.redirect_uri) .append_pair("scope", SIGN_IN_SCOPE) .append_pair("state", state) .append_pair("nonce", nonce) .append_pair("code_challenge", challenge) .append_pair("code_challenge_method", "S256"); Ok(url.into()) } /// The end-session URL of RP-initiated logout (contracts.md 2.5). `id_token_hint` is omitted when /// the session has no stored ID token. pub async fn end_session_url( &self, id_token_hint: Option<&str>, state: &str, ) -> ImResult { let discovery = self.discovery().await?; let endpoint = discovery .end_session_endpoint .as_deref() .ok_or_else(|| ImError::BadResponse("no end_session_endpoint".into()))?; let mut url = reqwest::Url::parse(endpoint) .map_err(|e| ImError::BadResponse(format!("end_session endpoint: {e}")))?; { let mut query = url.query_pairs_mut(); if let Some(hint) = id_token_hint { query.append_pair("id_token_hint", hint); } query .append_pair("post_logout_redirect_uri", &self.post_logout_uri) .append_pair("state", state); } Ok(url.into()) } /// Exchanges an authorization code for tokens (contracts.md 2.3, step 3). pub async fn exchange_code(&self, code: &str, verifier: &str) -> ImResult { let discovery = self.discovery().await?; let form = [ ("grant_type", "authorization_code"), ("code", code), ("redirect_uri", self.redirect_uri.as_str()), ("code_verifier", verifier), ]; self.post_token(&discovery.token_endpoint, &form).await } /// The client-credentials token for the directory at `im` (`aud = im`, `directory.read`). pub async fn service_token(&self) -> ImResult { self.client_token(IM_AUDIENCE, DIRECTORY_SCOPE).await } /// A client-credentials token for `scope` at the family service `audience`, cached until 60 seconds /// before it expires (contracts.md 2.6). Each `(audience, scope)` pair has its own cache entry, so the /// token for `in` never replaces the one for `im`. pub async fn client_token(&self, audience: &str, scope: &str) -> ImResult { let key = (audience.to_owned(), scope.to_owned()); let mut slots = self.service.lock().await; if let Some((until, token)) = slots.get(&key) && Instant::now() < *until { return Ok(token.clone()); } let discovery = self.discovery().await?; let form = [ ("grant_type", "client_credentials"), ("scope", scope), ("audience", audience), ]; let response = self.post_token(&discovery.token_endpoint, &form).await?; let token = response .access_token .filter(|token| !token.is_empty()) .ok_or_else(|| ImError::BadResponse("the token answer has no access token".into()))?; let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); slots.insert(key, (until, token.clone())); Ok(token) } /// Posts a form to the token endpoint with `client_secret_basic` and no redirect following. async fn post_token(&self, url: &str, form: &[(&str, &str)]) -> ImResult { let response = self .http .post(url) .basic_auth(&self.client_id, Some(&self.client_secret)) .form(form) .send() .await .map_err(unavailable)?; let status = response.status(); let body = read_limited(response, MAX_RESPONSE_BYTES).await?; if !status.is_success() { // The body of an error answer is not logged: it can echo request values. return Err(ImError::Rejected(format!( "the token endpoint answered {}", status.as_u16() ))); } serde_json::from_slice(&body) .map_err(|e| ImError::BadResponse(format!("the token answer: {e}"))) } /// Verifies an ID token against the current keys, and the nonce of the flight. pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult { check_shape(token)?; let now = unix_now(); self.with_keys(|keys| { verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now) }) .await } /// Verifies a back-channel logout token against the current keys. pub async fn verify_logout_token(&self, token: &str) -> ImResult { check_shape(token)?; let now = unix_now(); self.with_keys(|keys| verify_logout_token(keys, &self.issuer, &self.client_id, token, now)) .await } } /// The PKCE code challenge of a verifier: base64url of the SHA-256 of the verifier (RFC 7636, S256). pub fn pkce_challenge(verifier: &str) -> String { BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) } /// The current time as seconds since the Unix epoch. Zero if the clock is before it. pub fn unix_now() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(0, |d| d.as_secs()) } /// Verifies an ID token (contracts.md 2.3, step 4). `nonce` must equal the nonce of this flight. pub fn verify_id_token( keys: &KeySet, issuer: &str, client_id: &str, token: &str, nonce: &str, now: u64, ) -> ImResult { let claims = verify_signature(keys, issuer, client_id, token)?; check_iat(&claims, now)?; let sent = str_claim(&claims, "nonce") .ok_or_else(|| ImError::Rejected("the nonce claim is missing".into()))?; if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { return Err(ImError::Rejected( "the nonce does not match this sign-in".into(), )); } let id: IdClaims = serde_json::from_value(Value::Object(claims)) .map_err(|e| ImError::Rejected(format!("the claims are malformed: {e}")))?; if id.sub.is_empty() || id.sub.len() > 64 { return Err(ImError::Rejected("the subject is not a member id".into())); } Ok(id) } /// Verifies a back-channel logout token (OIDC Back-Channel Logout 1.0, contracts.md 2.5). It must /// carry the back-channel event, must not carry a nonce, must carry a `jti`, and must name a `sid` or /// a `sub`. pub fn verify_logout_token( keys: &KeySet, issuer: &str, client_id: &str, token: &str, now: u64, ) -> ImResult { let claims = verify_signature(keys, issuer, client_id, token)?; check_iat(&claims, now)?; if claims.contains_key("nonce") { return Err(ImError::Rejected( "a logout token must not carry a nonce".into(), )); } let events = claims .get("events") .and_then(Value::as_object) .ok_or_else(|| ImError::Rejected("the events claim is missing".into()))?; if !events.contains_key(BACKCHANNEL_EVENT) { return Err(ImError::Rejected( "the event is not back-channel logout".into(), )); } let jti = str_claim(&claims, "jti") .ok_or_else(|| ImError::Rejected("the jti claim is missing".into()))?; let sid = str_claim(&claims, "sid"); let sub = str_claim(&claims, "sub"); if sid.is_none() && sub.is_none() { return Err(ImError::Rejected( "the token names neither sid nor sub".into(), )); } Ok(LogoutClaims { jti, sid, sub }) } /// Refuses a token that cannot verify before any key set is fetched: three segments, a header that /// names EdDSA, and a `kid`. A hostile token therefore costs no call to `im`. fn check_shape(token: &str) -> ImResult<()> { if token.split('.').count() != 3 { return Err(ImError::Rejected( "the token does not have three segments".into(), )); } let header = decode_header(token) .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?; if header.alg != Algorithm::EdDSA { return Err(ImError::Rejected(format!( "the algorithm {:?} is not accepted", header.alg ))); } if header.kid.is_none() { return Err(ImError::Rejected("the header has no kid".into())); } Ok(()) } /// Checks the header, finds the key, and verifies the signature and the registered claims. Returns /// the claims as a map, for the token-specific checks. fn verify_signature( keys: &KeySet, issuer: &str, client_id: &str, token: &str, ) -> ImResult> { // The algorithm is read from the header and refused unless it is EdDSA, before any key is used. let header = decode_header(token) .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?; if header.alg != Algorithm::EdDSA { return Err(ImError::Rejected(format!( "the algorithm {:?} is not accepted", header.alg ))); } let kid = header .kid .as_deref() .ok_or_else(|| ImError::Rejected("the header has no kid".into()))?; let key = keys.get(kid).ok_or(ImError::UnknownKey)?; let mut validation = Validation::new(Algorithm::EdDSA); validation.leeway = LEEWAY_SECS; validation.validate_nbf = true; validation.set_issuer(&[issuer]); validation.set_audience(&[client_id]); validation.set_required_spec_claims(&["exp", "iss", "aud"]); let data = decode::>(token, key, &validation) .map_err(|e| ImError::Rejected(e.to_string()))?; // `set_audience` accepts any member of an array, so the exact rule is applied here. if !audience_is(data.claims.get("aud"), client_id) { return Err(ImError::Rejected( "the aud claim is not the client id".into(), )); } Ok(data.claims) } /// Whether `aud` names `expected`. A string must equal it; an array must hold exactly that one value. /// Contracts require an exact `client_id`, so a longer audience list is refused. fn audience_is(aud: Option<&Value>, expected: &str) -> bool { match aud { Some(Value::String(single)) => single == expected, Some(Value::Array(items)) => { items.len() == 1 && items.first().and_then(Value::as_str) == Some(expected) } _ => false, } } /// `iat` must be present and not more than [`MAX_IAT_AHEAD_SECS`] ahead of `now`. fn check_iat(claims: &Map, now: u64) -> ImResult<()> { let iat = claims .get("iat") .and_then(Value::as_u64) .ok_or_else(|| ImError::Rejected("the iat claim is missing".into()))?; if iat > now.saturating_add(MAX_IAT_AHEAD_SECS) { return Err(ImError::Rejected("the iat claim is in the future".into())); } Ok(()) } /// A string claim that is present and not empty. fn str_claim(claims: &Map, name: &str) -> Option { claims .get(name) .and_then(Value::as_str) .filter(|s| !s.is_empty()) .map(str::to_owned) } fn unavailable(error: reqwest::Error) -> ImError { ImError::Unavailable(error.without_url().to_string()) } /// Reads a response body, refusing one larger than `limit` bytes. The check runs while the body is /// read, so a server that lies about its length cannot make iz hold more than `limit`. pub async fn read_limited(response: reqwest::Response, limit: usize) -> ImResult> { let too_large = || ImError::BadResponse("the answer is too large".into()); if response .content_length() .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX)) { return Err(too_large()); } let mut body = Vec::new(); let mut chunks = response.bytes_stream(); while let Some(chunk) = chunks.next().await { let chunk = chunk.map_err(unavailable)?; if body.len() + chunk.len() > limit { return Err(too_large()); } body.extend_from_slice(&chunk); } Ok(body) } /// Reads the client secret from `path`. The file must not be readable by group or others, the same /// rule as the instance key. The value is trimmed and must not be empty. pub fn read_client_secret(path: &Path) -> iz_core::Result { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mode = std::fs::metadata(path)?.permissions().mode(); if mode & 0o077 != 0 { return Err(iz_core::Error::Config(format!( "client secret {} is group or world accessible (mode {:o}); expected 0600", path.display(), mode & 0o777 ))); } } let text = std::fs::read_to_string(path)?; let secret = text.trim().to_owned(); if secret.is_empty() { return Err(iz_core::Error::Config(format!( "client secret {} is empty", path.display() ))); } Ok(secret) } #[cfg(test)] pub(crate) mod test_support { //! Ed25519 keys and signed tokens for the tests. The keys are generated for each test, so no key //! material lives in the repository. use aws_lc_rs::rand::SystemRandom; use aws_lc_rs::signature::{Ed25519KeyPair, KeyPair}; use jsonwebtoken::{EncodingKey, Header, encode}; use serde_json::{Value, json}; use super::KeySet; /// The issuer used by the tests. pub const ISSUER: &str = "https://im.example.com"; /// The client id used by the tests. pub const CLIENT_ID: &str = "iz"; /// A signing key with the key set that verifies it, under the key id `k1`. pub struct Signer { pub keys: KeySet, encoding: EncodingKey, } impl Signer { pub fn generate() -> Signer { let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).expect("keygen"); let pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).expect("pkcs8"); let x = base64::Engine::encode( &base64::prelude::BASE64_URL_SAFE_NO_PAD, pair.public_key().as_ref(), ); let jwks = json!({"keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": "k1", "use": "sig", "alg": "EdDSA"}]}); Signer { keys: KeySet::from_jwks(jwks.to_string().as_bytes()).expect("jwks"), encoding: EncodingKey::from_ed_der(pkcs8.as_ref()), } } /// Signs `claims` as an EdDSA token with kid `k1`. pub fn sign(&self, claims: &Value) -> String { self.sign_with_kid("k1", claims) } /// Signs `claims` as an EdDSA token with the given kid. pub fn sign_with_kid(&self, kid: &str, claims: &Value) -> String { let mut header = Header::new(jsonwebtoken::Algorithm::EdDSA); header.kid = Some(kid.into()); encode(&header, claims, &self.encoding).expect("sign") } } /// Claims of an ID token that passes every check at time `now`, with `nonce`. pub fn id_claims(now: u64, nonce: &str) -> Value { json!({ "iss": ISSUER, "aud": CLIENT_ID, "sub": "01JMEMBER0000000000000000A", "exp": now + 600, "iat": now, "auth_time": now, "nonce": nonce, "sid": "sid-1", "email": "ada@example.com", "email_verified": true, "name": "Ada", "admin": false, "locale": "en", "zoneinfo": "Europe/Istanbul", "picture_version": 1 }) } /// Claims of a back-channel logout token that passes every check at time `now`. pub fn logout_claims(now: u64, jti: &str) -> Value { json!({ "iss": ISSUER, "aud": CLIENT_ID, "iat": now, "exp": now + 120, "jti": jti, "sid": "sid-1", "sub": "01JMEMBER0000000000000000A", "events": {"http://schemas.openid.net/event/backchannel-logout": {}} }) } } #[cfg(test)] mod tests { use super::test_support::{CLIENT_ID, ISSUER, Signer, id_claims, logout_claims}; use super::*; use serde_json::json; const NOW: u64 = 1_800_000_000; fn unsigned(header: &str, payload: &Value) -> String { let h = BASE64_URL_SAFE_NO_PAD.encode(header); let p = BASE64_URL_SAFE_NO_PAD.encode(payload.to_string()); format!("{h}.{p}.") } #[test] fn pkce_challenge_matches_the_rfc_7636_example() { assert_eq!( pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" ); } #[test] fn a_well_formed_id_token_is_accepted() { let signer = Signer::generate(); let token = signer.sign(&id_claims(NOW, "n-1")); let id = verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW).unwrap(); assert_eq!(id.sub, "01JMEMBER0000000000000000A"); assert_eq!(id.sid.as_deref(), Some("sid-1")); assert_eq!(id.picture_version, 1); } #[test] fn an_unsigned_alg_none_token_is_refused() { let signer = Signer::generate(); let token = unsigned(r#"{"alg":"none","kid":"k1"}"#, &id_claims(NOW, "n-1")); assert!(matches!( verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), Err(ImError::Rejected(_)) )); } #[test] fn a_token_for_another_audience_is_refused() { let signer = Signer::generate(); let mut claims = id_claims(NOW, "n-1"); claims["aud"] = json!("in"); let token = signer.sign(&claims); assert!(matches!( verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), Err(ImError::Rejected(_)) )); } #[test] fn an_expired_token_is_refused_but_leeway_is_allowed() { // `exp` is checked against the system clock, so this test uses the real current time. let now = unix_now(); let signer = Signer::generate(); let mut claims = id_claims(now, "n-1"); claims["exp"] = json!(now - 3600); let token = signer.sign(&claims); assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_err()); let mut claims = id_claims(now, "n-1"); claims["exp"] = json!(now - 30); let token = signer.sign(&claims); assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_ok()); } #[test] fn a_wrong_nonce_is_refused() { let signer = Signer::generate(); let token = signer.sign(&id_claims(NOW, "n-1")); assert!(matches!( verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-2", NOW), Err(ImError::Rejected(_)) )); } #[test] fn an_unknown_key_id_asks_for_a_refetch() { let signer = Signer::generate(); let token = signer.sign_with_kid("k2", &id_claims(NOW, "n-1")); assert!(matches!( verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), Err(ImError::UnknownKey) )); } #[test] fn a_logout_token_needs_the_event_and_no_nonce() { let signer = Signer::generate(); let good = signer.sign(&logout_claims(NOW, "j-1")); let claims = verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &good, NOW).unwrap(); assert_eq!(claims.jti, "j-1"); assert_eq!(claims.sid.as_deref(), Some("sid-1")); let mut with_nonce = logout_claims(NOW, "j-2"); with_nonce["nonce"] = json!("n"); let token = signer.sign(&with_nonce); assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err()); let mut no_event = logout_claims(NOW, "j-3"); no_event["events"] = json!({}); let token = signer.sign(&no_event); assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err()); } #[test] fn the_key_set_keeps_only_ed25519_keys_with_a_kid() { let set = KeySet::from_jwks( br#"{"keys":[{"kty":"RSA","kid":"r1","n":"x","e":"AQAB"},{"kty":"OKP","crv":"Ed25519","kid":"no-x"}]}"#, ) .unwrap(); assert!(set.keys.is_empty()); } }