//! The OpenID Connect client of `in`, a relying party of `im` (docs/contracts.md section 2). //! //! It does four things and nothing more. It finds `im`'s endpoints (discovery, cached, with the //! standard paths as a fallback). It keeps `im`'s signing keys (JWKS, cached for ten minutes, refetched at //! most once a minute when a token names an unknown key). It verifies the three kinds of token `in` //! receives: ID tokens, logout tokens and access tokens. And it makes the calls `in` sends to `im`: the //! code exchange and the client-credentials token that the directory and the photos need. //! //! The verification rules are pure functions over a [`KeySet`], so they are tested without a network. //! Only EdDSA is accepted. The algorithm is checked on the raw header before any library parses it, so //! `none` and every other algorithm are refused with the same answer. use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use base64::prelude::{BASE64_STANDARD, BASE64_URL_SAFE_NO_PAD, Engine as _}; use in_core::config::Oidc; use in_core::error::{Error as CoreError, Result as CoreResult}; use in_core::token::constant_time_eq; use jsonwebtoken::errors::ErrorKind; use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode}; use serde::Deserialize; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; use tokio::sync::Mutex; /// Seconds of clock skew allowed on `exp`. The contracts do not name a value; `in` uses 60 s. pub const CLOCK_LEEWAY_SECS: i64 = 60; /// Seconds an `iat` may lie in the future. Contracts section 2.3 says five minutes. pub const MAX_FUTURE_IAT_SECS: i64 = 300; /// How long a fetched key set is used before it is fetched again (contracts section 2.2). pub const JWKS_MAX_AGE: Duration = Duration::from_secs(10 * 60); /// The shortest gap between two key fetches. A fetch for an unknown `kid`, and a retry after a failed /// fetch, both wait this long. It is the one-minute refetch limit of contracts section 2.2, and it /// protects `im` from a flood of tokens that name keys that do not exist. pub const JWKS_REFRESH_GAP: Duration = Duration::from_secs(60); /// How long a failed discovery is not retried. Until it succeeds the standard paths are used. const DISCOVERY_RETRY_GAP: Duration = Duration::from_secs(60); /// Time limit of every call to `im`, except the directory stream. pub const HTTP_TIMEOUT: Duration = Duration::from_secs(10); /// Longest silence on the directory stream before the connection is given up. The server sends a /// keep-alive every 30 seconds (contracts section 3.2), so three of them missed means it is dead. const STREAM_READ_TIMEOUT: Duration = Duration::from_secs(90); /// The largest JSON answer read from `im`: discovery, the key set and token answers are far smaller. const MAX_DOCUMENT_BYTES: usize = 1024 * 1024; /// A service token is refreshed this long before its stated end (contracts section 2.6). const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); /// The event name that marks a logout token (OIDC Back-Channel Logout 1.0). pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; /// The family key of `im`. Client-credentials tokens that `in` asks for carry it as `aud`. pub const IM_KEY: &str = "im"; /// The scope that reads the people directory and photos at `im`. pub const DIRECTORY_SCOPE: &str = "directory.read"; /// The family key of `in` itself. Client-credentials tokens that call `in` carry it as `aud`. pub const FAMILY_KEY: &str = "in"; /// The scope that lets a family service store and read its own objects in `in` (contracts.md 5). pub const FILES_SERVICE_SCOPE: &str = "files.service"; /// Why a token was refused. Every variant is a refusal; none of them says more than the cause. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum TokenError { /// The token is not three base64url segments with a JSON header and claims. #[error("the token is malformed")] Malformed, /// The header names an algorithm other than EdDSA, or none at all. #[error("the token is not signed with EdDSA")] Algorithm, /// The header has no `kid`, so the key cannot be chosen. #[error("the token has no key id")] NoKeyId, /// The `kid` is not in the published key set. The caller may refetch the keys once. #[error("the token names an unknown key")] UnknownKey, /// The signature does not verify with the named key. #[error("the signature does not verify")] Signature, /// `exp` is in the past, beyond the leeway. #[error("the token has expired")] Expired, /// A claim is missing, has the wrong type, or has the wrong value. #[error("the claim {0} is missing or wrong")] Claim(&'static str), /// The nonce does not equal the one this sign-in sent. #[error("the nonce does not match")] Nonce, } /// Why a call to `im` failed. #[derive(Debug, thiserror::Error)] pub enum OidcError { /// A token did not verify. #[error(transparent)] Token(#[from] TokenError), /// `im` could not be reached, or answered something that is not what the contracts describe. #[error("the identity provider is unavailable: {0}")] Unavailable(String), /// `im` answered with a refusal, such as a rejected code or a wrong client secret. #[error("the identity provider refused the request")] Refused, } /// The claims of an ID token that `in` uses. Each field is checked by [`verify_id_token`]. #[derive(Debug, Clone, PartialEq, Eq)] pub struct IdClaims { /// The person's stable id (a ULID). pub sub: String, /// The `im` browser session the sign-in belongs to. Back-channel logout names it. pub sid: String, /// The person's email address. pub email: String, /// The display name. The email address when the claim is empty. pub name: String, /// Whether the person administers the family instance. pub admin: bool, /// `en` or `tr`. Anything else from `im` is read as `en`. pub locale: String, /// IANA time zone name. pub zoneinfo: String, /// Photo version; bumps when the photo changes. pub picture_version: i64, /// When the token was issued, in Unix seconds. `check_iat` has already made sure it is present. pub iat: i64, } /// The claims of a back-channel logout token that `in` uses. #[derive(Debug, Clone, PartialEq, Eq)] pub struct LogoutClaims { /// Unique id of the token. A replayed id is refused for ten minutes. pub jti: String, /// The `im` session that ended, when the token names one. pub sid: Option, /// The person, when the token names one. A token with only `sub` ends every session of the person. pub sub: Option, } /// The endpoints of `im` that `in` calls. Discovery provides them; the standard paths replace them /// when discovery cannot be fetched. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Endpoints { /// The sign-in page, `/authorize`. pub authorization: String, /// The token endpoint, `/token`. pub token: String, /// The signing keys, `/jwks.json`. pub jwks: String, /// The end-session page, `/logout`. pub end_session: String, } /// The fields of the discovery document that `in` reads. #[derive(Debug, Deserialize)] struct DiscoveryDocument { issuer: String, authorization_endpoint: String, token_endpoint: String, jwks_uri: String, end_session_endpoint: Option, } /// One key of the published JWKS, as far as `in` reads it. #[derive(Debug, Deserialize)] pub struct Jwk { #[serde(default)] kty: String, #[serde(default)] crv: String, #[serde(default)] x: String, #[serde(default)] kid: String, #[serde(default)] alg: String, #[serde(default, rename = "use")] usage: String, } /// The JWKS document. #[derive(Debug, Deserialize)] pub struct Jwks { keys: Vec, } /// The usable Ed25519 keys of `im`, by `kid`. pub struct KeySet { keys: Vec<(String, DecodingKey)>, } impl KeySet { /// Keeps the keys that `in` can use: Ed25519 (`OKP`) signing keys whose algorithm, when named, is /// EdDSA. Anything else in the document is skipped, not an error. pub fn from_jwks(jwks: &Jwks) -> KeySet { let keys = jwks .keys .iter() .filter(|key| key.kty == "OKP" && key.crv == "Ed25519") .filter(|key| key.alg.is_empty() || key.alg == "EdDSA") .filter(|key| key.usage.is_empty() || key.usage == "sig") .filter(|key| !key.kid.is_empty()) .filter_map(|key| { DecodingKey::from_ed_components(&key.x) .ok() .map(|decoding| (key.kid.clone(), decoding)) }) .collect(); KeySet { keys } } /// The key with this `kid`, if it is published. fn get(&self, kid: &str) -> Option<&DecodingKey> { self.keys .iter() .find(|(known, _)| known == kid) .map(|(_, key)| key) } } /// The current time in whole seconds since the Unix epoch. pub fn now_secs() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) } /// Reads a non-empty string claim. fn text_claim<'a>( claims: &'a Map, name: &'static str, ) -> Result<&'a str, TokenError> { claims .get(name) .and_then(Value::as_str) .filter(|value| !value.trim().is_empty()) .ok_or(TokenError::Claim(name)) } /// Reads an optional non-empty string claim. A present but empty value counts as absent. fn optional_text_claim<'a>(claims: &'a Map, name: &str) -> Option<&'a str> { claims .get(name) .and_then(Value::as_str) .filter(|value| !value.trim().is_empty()) } /// Whether `aud` names `expected`. A string must equal it; an array must hold exactly that one value. /// Contracts require an exact `client_id` for ID tokens, 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, } } /// Refuses an `iat` that is missing or more than [`MAX_FUTURE_IAT_SECS`] ahead of `now`. fn check_iat(claims: &Map, now: i64) -> Result<(), TokenError> { let iat = claims .get("iat") .and_then(Value::as_i64) .ok_or(TokenError::Claim("iat"))?; if iat > now + MAX_FUTURE_IAT_SECS { return Err(TokenError::Claim("iat")); } Ok(()) } /// Reads the protected header of `token` and refuses what `in` can never verify: the token must have /// three segments, the header must name EdDSA, and it must carry a `kid`. Returns the `kid`. /// /// The algorithm is read from the raw header, so `none` and any other algorithm are refused before a /// library sees the token. Callers run this before any key is fetched, so a token that cannot verify /// costs no network call. pub fn check_header(token: &str) -> Result { let segments: Vec<&str> = token.split('.').collect(); if segments.len() != 3 { return Err(TokenError::Malformed); } let header_bytes = BASE64_URL_SAFE_NO_PAD .decode(segments[0]) .map_err(|_| TokenError::Malformed)?; let header: Value = serde_json::from_slice(&header_bytes).map_err(|_| TokenError::Malformed)?; if header.get("alg").and_then(Value::as_str) != Some("EdDSA") { return Err(TokenError::Algorithm); } header .get("kid") .and_then(Value::as_str) .filter(|kid| !kid.is_empty()) .map(str::to_owned) .ok_or(TokenError::NoKeyId) } /// Checks the algorithm, the key id, the signature, the issuer, the expiry and the not-before time, and /// returns the claims. Audience, nonce and the rest are the job of the callers, which know what they /// expect. pub fn verify_signed( keys: &KeySet, token: &str, issuer: &str, ) -> Result, TokenError> { let kid = check_header(token)?; let key = keys.get(&kid).ok_or(TokenError::UnknownKey)?; let mut validation = Validation::new(Algorithm::EdDSA); validation.leeway = u64::try_from(CLOCK_LEEWAY_SECS).unwrap_or(0); validation.validate_exp = true; // A token whose `nbf` lies beyond the leeway is not valid yet. A token without `nbf` is unaffected. validation.validate_nbf = true; // Audience is checked by the callers, because the rule differs by token kind. validation.validate_aud = false; validation.set_issuer(&[issuer]); // `sub` is not required here: a back-channel token may carry only `sid`, and each caller checks // the subject it needs. validation.set_required_spec_claims(&["exp", "iss", "iat"]); let data = decode::>(token, key, &validation).map_err(|error| { match error.kind() { ErrorKind::ExpiredSignature => TokenError::Expired, ErrorKind::InvalidSignature => TokenError::Signature, ErrorKind::InvalidIssuer => TokenError::Claim("iss"), ErrorKind::InvalidAlgorithm => TokenError::Algorithm, ErrorKind::ImmatureSignature => TokenError::Claim("nbf"), ErrorKind::MissingRequiredClaim(_) => TokenError::Claim("required claim"), _ => TokenError::Malformed, } })?; Ok(data.claims) } /// Verifies an ID token from the code exchange: signature, issuer, `aud` equal to `client_id`, `exp`, /// `iat`, and the `nonce` this sign-in sent. Returns the claims `in` keeps about the person. pub fn verify_id_token( keys: &KeySet, token: &str, issuer: &str, client_id: &str, nonce: &str, ) -> Result { let claims = verify_signed(keys, token, issuer)?; if !audience_is(claims.get("aud"), client_id) { return Err(TokenError::Claim("aud")); } check_iat(&claims, now_secs())?; let sent = text_claim(&claims, "nonce")?; if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { return Err(TokenError::Nonce); } let sub = text_claim(&claims, "sub")?.to_owned(); let sid = text_claim(&claims, "sid")?.to_owned(); let email = text_claim(&claims, "email")?.to_owned(); let name = optional_text_claim(&claims, "name") .unwrap_or(&email) .to_owned(); let locale = match optional_text_claim(&claims, "locale") { Some("tr") => "tr".to_owned(), _ => "en".to_owned(), }; Ok(IdClaims { sub, sid, email, name, admin: claims .get("admin") .and_then(Value::as_bool) .unwrap_or(false), locale, zoneinfo: optional_text_claim(&claims, "zoneinfo") .unwrap_or("UTC") .to_owned(), iat: claims .get("iat") .and_then(Value::as_i64) .unwrap_or_default(), picture_version: claims .get("picture_version") .and_then(Value::as_i64) .unwrap_or(0) .max(0), }) } /// Verifies a back-channel logout token (contracts section 2.5): signature, issuer, `aud` equal to /// `client_id`, `iat`, `exp`, the logout event, a `jti`, a `sid` or `sub`, and no `nonce`. pub fn verify_logout_token( keys: &KeySet, token: &str, issuer: &str, client_id: &str, ) -> Result { let claims = verify_signed(keys, token, issuer)?; if !audience_is(claims.get("aud"), client_id) { return Err(TokenError::Claim("aud")); } check_iat(&claims, now_secs())?; if claims.contains_key("nonce") { return Err(TokenError::Claim("nonce")); } let has_event = claims .get("events") .and_then(Value::as_object) .and_then(|events| events.get(LOGOUT_EVENT)) .is_some_and(Value::is_object); if !has_event { return Err(TokenError::Claim("events")); } let jti = text_claim(&claims, "jti")?.to_owned(); let sid = optional_text_claim(&claims, "sid").map(str::to_owned); let sub = optional_text_claim(&claims, "sub").map(str::to_owned); if sid.is_none() && sub.is_none() { return Err(TokenError::Claim("sub")); } Ok(LogoutClaims { jti, sid, sub }) } /// The claims of a client-credentials access token that a machine API needs (contracts.md 2.6). #[derive(Debug, Clone, PartialEq, Eq)] pub struct MachineClaims { /// The token subject, `client:` for a client-credentials token. Only the prefix is checked. pub subject: String, /// The scopes the token grants, from the space-separated `scope` claim. Empty when there is none. pub scopes: Vec, /// The caller's family key from `svc`. Callers treat it as their identity. `None` when absent. pub svc: Option, } /// Verifies an access token addressed to `audience` (for `in`, [`FAMILY_KEY`]): signature, `iss`, `exp` /// (with leeway), `iat` (at most five minutes ahead), and `aud` equal to `audience` exactly. It does not /// judge the scopes or the `svc` claim; the caller decides what they must contain, because the refusal /// differs (a missing `svc` is a bad token, a missing scope is a forbidden call). pub fn verify_machine_token( keys: &KeySet, token: &str, issuer: &str, audience: &str, ) -> Result { let claims = verify_signed(keys, token, issuer)?; if !audience_is(claims.get("aud"), audience) { return Err(TokenError::Claim("aud")); } check_iat(&claims, now_secs())?; let subject = text_claim(&claims, "sub")?.to_owned(); let scopes = optional_text_claim(&claims, "scope") .map(|scope| { scope .split(' ') .filter(|s| !s.is_empty()) .map(str::to_owned) .collect() }) .unwrap_or_default(); let svc = optional_text_claim(&claims, "svc").map(str::to_owned); Ok(MachineClaims { subject, scopes, svc, }) } #[cfg(test)] impl OidcClient { /// A client whose key set is `keys` and whose endpoints are the standard paths under `issuer`. The cache /// is filled directly, so no request is made. Production always fetches; only tests use this. pub(crate) fn with_keys_for_tests(issuer: &str, client_id: &str, keys: KeySet) -> Self { let config = Oidc { issuer: issuer.to_owned(), client_id: client_id.to_owned(), client_secret_file: std::path::PathBuf::new(), }; let mut client = Self::new(&config, "https://in.test", "test-secret".to_owned()).expect("client"); let endpoints = client.standard_endpoints(); let cache = client.cache.get_mut(); cache.endpoints = Some(Arc::new(endpoints)); cache.keys = Some((Instant::now(), Arc::new(keys))); client } } /// Ed25519 keys and signed tokens for the tests of this crate. Test-only; production keys come from `im`. #[cfg(test)] pub(crate) mod test_support { use super::*; use ed25519_dalek::SigningKey; use ed25519_dalek::pkcs8::EncodePrivateKey; use jsonwebtoken::{EncodingKey, Header, encode}; use serde_json::json; /// The issuer the test tokens name. pub(crate) const ISSUER: &str = "https://im.example.test"; /// The client id `in` uses in the tests. pub(crate) const CLIENT: &str = "in"; /// The key id of the test key. pub(crate) const KID: &str = "k1"; /// A fresh Ed25519 key: the signing half as PKCS#8 DER, and the key set that publishes it. pub(crate) fn test_key() -> (Vec, KeySet) { let mut seed = [0u8; 32]; rand::fill(&mut seed); let signing = SigningKey::from_bytes(&seed); let der = signing.to_pkcs8_der().expect("pkcs8").as_bytes().to_vec(); let x = BASE64_URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()); let jwks: Jwks = serde_json::from_value(json!({ "keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": KID, "use": "sig", "alg": "EdDSA"}] })) .expect("jwks"); (der, KeySet::from_jwks(&jwks)) } /// Signs `claims` with `der` under [`KID`]. pub(crate) fn sign(der: &[u8], claims: &Value) -> String { let mut header = Header::new(Algorithm::EdDSA); header.kid = Some(KID.to_owned()); encode(&header, claims, &EncodingKey::from_ed_der(der)).expect("sign") } } /// The PKCE code challenge of `verifier`: base64url of its SHA-256, without padding (RFC 7636). pub fn pkce_challenge(verifier: &str) -> String { BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) } /// Reads a response body of at most `limit` bytes. Returns `None` when the body is larger, and stops /// reading as soon as it is, so a server that lies about its length cannot make `in` hold more than /// `limit` bytes. pub async fn read_limited( mut response: reqwest::Response, limit: usize, ) -> Result>, reqwest::Error> { if response .content_length() .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX)) { return Ok(None); } let mut body = Vec::new(); while let Some(chunk) = response.chunk().await? { if body.len() + chunk.len() > limit { return Ok(None); } body.extend_from_slice(&chunk); } Ok(Some(body)) } /// Reads the body of a JSON answer from `im`, at most [`MAX_DOCUMENT_BYTES`]. A larger body is unavailable, /// and a read error is reported without the URL. async fn read_document(response: reqwest::Response) -> Result, OidcError> { read_limited(response, MAX_DOCUMENT_BYTES) .await .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))? .ok_or_else(|| { OidcError::Unavailable(format!( "an answer is larger than {MAX_DOCUMENT_BYTES} bytes" )) }) } /// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1): /// unreserved characters pass, everything else becomes `%XX`. pub fn percent_encode(value: &str) -> String { let mut out = String::with_capacity(value.len()); for byte in value.bytes() { if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { out.push(char::from(byte)); } else { out.push_str(&format!("%{byte:02X}")); } } out } /// The body of a successful token response. Only the fields `in` reads are named. #[derive(Debug, Deserialize)] struct TokenResponse { #[serde(default)] id_token: Option, #[serde(default)] access_token: Option, #[serde(default)] expires_in: Option, } /// Cached state of the client. Every field is behind one lock. No method holds it across a network /// call, and no method holds it while it takes it again. #[derive(Default)] struct Cache { /// The endpoints from discovery, once fetched. endpoints: Option>, /// When the last discovery failed. Until [`DISCOVERY_RETRY_GAP`] has passed, the standard paths /// are used without asking again. discovery_failed_at: Option, /// The key set and when it was fetched. keys: Option<(Instant, Arc)>, /// When the keys were last fetched for an unknown `kid`, or a fetch failed. Limits those fetches. keys_refresh_at: Option, /// The client-credentials token for `im`, and the instant it stops being used. service: Option<(String, Instant)>, } /// What the cache answers for the key set, without the network. `None` means a fetch is due. /// /// A fresh set is used as it is unless a refetch is forced. Any set, fresh or stale, is also used while /// the last fetch attempt is younger than [`JWKS_REFRESH_GAP`]. That rate-limits forced refetches for /// unknown key ids and retries after a failed refetch alike. With no set at all, a recent failure is an /// answer of its own, so requests do not each wait for `im` again. fn keys_from_cache(cache: &Cache, force: bool) -> Option, OidcError>> { let recently_tried = cache .keys_refresh_at .is_some_and(|at| at.elapsed() < JWKS_REFRESH_GAP); match &cache.keys { Some((at, keys)) if at.elapsed() < JWKS_MAX_AGE && !force => Some(Ok(Arc::clone(keys))), Some((_, keys)) if recently_tried => Some(Ok(Arc::clone(keys))), None if recently_tried => Some(Err(OidcError::Unavailable( "the signing keys are not available yet".to_owned(), ))), _ => None, } } /// The OpenID Connect client. One per process, shared through the app state. pub struct OidcClient { issuer: String, client_id: String, client_secret: String, redirect_uri: String, http: reqwest::Client, stream_http: reqwest::Client, cache: Mutex, /// Held while the key set is fetched. One fetch runs at a time, and the requests that wait for it /// read the result from the cache. It is never held while `cache` is held. refresh: Mutex<()>, } impl OidcClient { /// Builds the client from the `[oidc]` table, the public base URL and the client secret read from /// its file. No request is made here. pub fn new(config: &Oidc, base_url: &str, client_secret: String) -> CoreResult { let http = reqwest::Client::builder() .timeout(HTTP_TIMEOUT) .connect_timeout(HTTP_TIMEOUT) .redirect(reqwest::redirect::Policy::none()) .build() .map_err(|e| CoreError::Config(format!("cannot build the HTTP client: {e}")))?; // The directory stream lasts for minutes, so it gets no total time limit, only a read limit. let stream_http = reqwest::Client::builder() .connect_timeout(HTTP_TIMEOUT) .read_timeout(STREAM_READ_TIMEOUT) .redirect(reqwest::redirect::Policy::none()) .build() .map_err(|e| CoreError::Config(format!("cannot build the stream client: {e}")))?; Ok(Self { issuer: config.issuer.clone(), client_id: config.client_id.clone(), client_secret, redirect_uri: format!("{base_url}/auth/callback"), http, stream_http, cache: Mutex::new(Cache::default()), refresh: Mutex::new(()), }) } /// The issuer URL of `im`, which is also the origin of its API. pub fn issuer(&self) -> &str { &self.issuer } /// The HTTP client for calls to `im` with a time limit. pub fn http(&self) -> &reqwest::Client { &self.http } /// The HTTP client for the directory stream, which has no total time limit. pub fn stream_http(&self) -> &reqwest::Client { &self.stream_http } /// The endpoints of `im`. Fetched from discovery once; when discovery fails, the standard paths /// under the issuer are used and discovery is retried after [`DISCOVERY_RETRY_GAP`]. pub async fn endpoints(&self) -> Arc { { let cache = self.cache.lock().await; if let Some(endpoints) = &cache.endpoints { return Arc::clone(endpoints); } if cache .discovery_failed_at .is_some_and(|at| at.elapsed() < DISCOVERY_RETRY_GAP) { return Arc::new(self.standard_endpoints()); } } // The lock is not held during the request. Two requests may race to fetch; both get the same // document, so that is harmless. match self.fetch_discovery().await { Ok(endpoints) => { let endpoints = Arc::new(endpoints); let mut cache = self.cache.lock().await; cache.endpoints = Some(Arc::clone(&endpoints)); cache.discovery_failed_at = None; endpoints } Err(error) => { tracing::warn!(error = %error, "oidc: discovery failed, using the standard paths"); self.cache.lock().await.discovery_failed_at = Some(Instant::now()); Arc::new(self.standard_endpoints()) } } } /// The paths of contracts section 2.1, under the issuer. fn standard_endpoints(&self) -> Endpoints { Endpoints { authorization: format!("{}/authorize", self.issuer), token: format!("{}/token", self.issuer), jwks: format!("{}/jwks.json", self.issuer), end_session: format!("{}/logout", self.issuer), } } /// Fetches and checks the discovery document. Its `issuer` must equal the configured one exactly. async fn fetch_discovery(&self) -> Result { let url = format!("{}/.well-known/openid-configuration", self.issuer); let document: DiscoveryDocument = self.get_json(&url).await?; if document.issuer != self.issuer { return Err(OidcError::Unavailable( "discovery names another issuer".to_owned(), )); } let end_session = document .end_session_endpoint .unwrap_or_else(|| format!("{}/logout", self.issuer)); Ok(Endpoints { authorization: document.authorization_endpoint, token: document.token_endpoint, jwks: document.jwks_uri, end_session, }) } /// GETs a JSON document. A non-2xx answer is unavailable: the caller cannot do anything with it. async fn get_json(&self, url: &str) -> Result { let response = self .http .get(url) .send() .await .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?; if !response.status().is_success() { return Err(OidcError::Unavailable(format!( "{url} answered {}", response.status() ))); } let bytes = read_document(response).await?; serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) } /// The key set in use. The cache answers when it can (see [`keys_from_cache`]). Otherwise one request /// at a time fetches it, with no lock held during the network call. A failed refetch keeps the old /// set, because a stale key still verifies tokens that were signed with it. async fn load_keys(&self, force: bool) -> Result, OidcError> { let decided = keys_from_cache(&*self.cache.lock().await, force); if let Some(answer) = decided { return answer; } let _single_flight = self.refresh.lock().await; // A request that waited for the fetch above finds its answer here. let decided = keys_from_cache(&*self.cache.lock().await, force); if let Some(answer) = decided { return answer; } let endpoints = self.endpoints().await; // Only a forced refetch 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 force { self.cache.lock().await.keys_refresh_at = Some(Instant::now()); } let fetched = self.get_json::(&endpoints.jwks).await; let mut cache = self.cache.lock().await; if fetched.is_err() { cache.keys_refresh_at = Some(Instant::now()); } match fetched { Ok(jwks) => { let keys = Arc::new(KeySet::from_jwks(&jwks)); cache.keys = Some((Instant::now(), Arc::clone(&keys))); Ok(keys) } Err(error) => match &cache.keys { Some((_, keys)) => { tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys"); Ok(Arc::clone(keys)) } None => Err(error), }, } } /// Verifies a client-credentials access token addressed to `audience`, with the cached key set. See /// [`verify_machine_token`]. pub async fn verify_machine_token( &self, token: &str, audience: &str, ) -> Result { self.verify_with(token, |keys| { verify_machine_token(keys, token, &self.issuer, audience) }) .await } /// Runs `check` against the key set. The header is checked first, so a token that cannot verify /// fetches nothing. An unknown key id triggers one rate-limited refetch. async fn verify_with( &self, token: &str, check: impl Fn(&KeySet) -> Result, ) -> Result { check_header(token)?; let keys = self.load_keys(false).await?; match check(&keys) { Err(TokenError::UnknownKey) => { let keys = self.load_keys(true).await?; Ok(check(&keys)?) } outcome => Ok(outcome?), } } /// Verifies an ID token of this sign-in. See [`verify_id_token`]. pub async fn verify_id_token(&self, token: &str, nonce: &str) -> Result { self.verify_with(token, |keys| { verify_id_token(keys, token, &self.issuer, &self.client_id, nonce) }) .await } /// Verifies a back-channel logout token. See [`verify_logout_token`]. pub async fn verify_logout_token(&self, token: &str) -> Result { self.verify_with(token, |keys| { verify_logout_token(keys, token, &self.issuer, &self.client_id) }) .await } /// The URL that sends the browser to `im` to sign in (contracts section 2.3, step 1). pub async fn authorize_url( &self, state: &str, nonce: &str, challenge: &str, ) -> Result { let endpoints = self.endpoints().await; let mut url = reqwest::Url::parse(&endpoints.authorization) .map_err(|e| OidcError::Unavailable(format!("bad 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", "openid profile email") .append_pair("state", state) .append_pair("nonce", nonce) .append_pair("code_challenge", challenge) .append_pair("code_challenge_method", "S256"); Ok(url.to_string()) } /// The URL that ends the `im` session (RP-initiated logout, contracts section 2.5). pub async fn end_session_url( &self, id_token_hint: &str, post_logout_redirect: &str, state: &str, ) -> Result { let endpoints = self.endpoints().await; let mut url = reqwest::Url::parse(&endpoints.end_session) .map_err(|e| OidcError::Unavailable(format!("bad end-session endpoint: {e}")))?; url.query_pairs_mut() .append_pair("id_token_hint", id_token_hint) .append_pair("post_logout_redirect_uri", post_logout_redirect) .append_pair("state", state); Ok(url.to_string()) } /// Exchanges the authorization code for the ID token (contracts section 2.3, step 3). The access /// and refresh tokens are not kept: this family does not use them. pub async fn exchange_code(&self, code: &str, verifier: &str) -> Result { let endpoints = self.endpoints().await; let response = self .token_request( &endpoints.token, &[ ("grant_type", "authorization_code"), ("code", code), ("redirect_uri", &self.redirect_uri), ("code_verifier", verifier), ], ) .await?; response .id_token .ok_or(OidcError::Token(TokenError::Claim("id_token"))) } /// A client-credentials token for the directory at `im` (contracts section 2.6). Cached until /// [`SERVICE_TOKEN_MARGIN`] before its stated lifetime ends. pub async fn service_token(&self) -> Result { { let cache = self.cache.lock().await; if let Some((token, until)) = &cache.service && Instant::now() < *until { return Ok(token.clone()); } } let endpoints = self.endpoints().await; let response = self .token_request( &endpoints.token, &[ ("grant_type", "client_credentials"), ("scope", DIRECTORY_SCOPE), ("audience", IM_KEY), ], ) .await?; let token = response .access_token .ok_or(OidcError::Token(TokenError::Claim("access_token")))?; let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); self.cache.lock().await.service = Some((token.clone(), until)); Ok(token) } /// Posts a form to a token endpoint with client_secret_basic authentication (RFC 6749 section /// 2.3.1). A 4xx answer is a refusal; anything else that is not a success is unavailable. async fn token_request( &self, url: &str, form: &[(&str, &str)], ) -> Result { let credentials = format!( "{}:{}", percent_encode(&self.client_id), percent_encode(&self.client_secret) ); let response = self .http .post(url) .header( reqwest::header::AUTHORIZATION, format!("Basic {}", BASE64_STANDARD.encode(credentials)), ) .header(reqwest::header::ACCEPT, "application/json") .form(form) .send() .await .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?; let status = response.status(); if status.is_client_error() { tracing::warn!(status = %status, "oidc: the token endpoint refused the request"); return Err(OidcError::Refused); } if !status.is_success() { return Err(OidcError::Unavailable(format!( "token endpoint answered {status}" ))); } let bytes = read_document(response).await?; serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) } } #[cfg(test)] mod tests { use super::test_support::{CLIENT, ISSUER, sign, test_key}; use super::*; use serde_json::json; const NONCE: &str = "nonce-value"; fn id_claims(now: i64) -> Value { json!({ "iss": ISSUER, "sub": "01JTESTSUB", "aud": CLIENT, "exp": now + 300, "iat": now, "nonce": NONCE, "sid": "im-session-1", "email": "ann@example.test", "name": "Ann", }) } #[test] fn a_valid_id_token_is_accepted() { let (der, keys) = test_key(); let token = sign(&der, &id_claims(now_secs())); let claims = verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).expect("valid"); assert_eq!(claims.sub, "01JTESTSUB"); assert_eq!(claims.sid, "im-session-1"); assert_eq!(claims.locale, "en"); } #[test] fn an_unsigned_alg_none_token_is_refused() { let (_der, keys) = test_key(); let header = BASE64_URL_SAFE_NO_PAD.encode(br#"{"alg":"none","kid":"k1","typ":"JWT"}"#); let payload = BASE64_URL_SAFE_NO_PAD.encode(id_claims(now_secs()).to_string()); let token = format!("{header}.{payload}."); assert_eq!( verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), Some(TokenError::Algorithm) ); } #[test] fn a_token_for_another_audience_is_refused() { let (der, keys) = test_key(); let mut claims = id_claims(now_secs()); claims["aud"] = json!("iz"); let token = sign(&der, &claims); assert_eq!( verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), Some(TokenError::Claim("aud")) ); } #[test] fn an_expired_token_is_refused_beyond_the_leeway() { let (der, keys) = test_key(); let now = now_secs(); let mut claims = id_claims(now); claims["exp"] = json!(now - 3 * CLOCK_LEEWAY_SECS); let token = sign(&der, &claims); assert_eq!( verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), Some(TokenError::Expired) ); } #[test] fn a_wrong_nonce_is_refused() { let (der, keys) = test_key(); let token = sign(&der, &id_claims(now_secs())); assert_eq!( verify_id_token(&keys, &token, ISSUER, CLIENT, "another-nonce").err(), Some(TokenError::Nonce) ); } #[test] fn the_pkce_challenge_matches_the_rfc_7636_vector() { assert_eq!( pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" ); } }