forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

oidc.rs1070 lines, 41.0 KiBHistoryRawDownload
1//! The OpenID Connect client of `in`, a relying party of `im` (docs/contracts.md section 2).
2//!
3//! It does four things and nothing more. It finds `im`'s endpoints (discovery, cached, with the
4//! standard paths as a fallback). It keeps `im`'s signing keys (JWKS, cached for ten minutes, refetched at
5//! most once a minute when a token names an unknown key). It verifies the three kinds of token `in`
6//! receives: ID tokens, logout tokens and access tokens. And it makes the calls `in` sends to `im`: the
7//! code exchange and the client-credentials token that the directory and the photos need.
8//!
9//! The verification rules are pure functions over a [`KeySet`], so they are tested without a network.
10//! Only EdDSA is accepted. The algorithm is checked on the raw header before any library parses it, so
11//! `none` and every other algorithm are refused with the same answer.
12
13use std::sync::Arc;
14use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
15
16use base64::prelude::{BASE64_STANDARD, BASE64_URL_SAFE_NO_PAD, Engine as _};
17use in_core::config::Oidc;
18use in_core::error::{Error as CoreError, Result as CoreResult};
19use in_core::token::constant_time_eq;
20use jsonwebtoken::errors::ErrorKind;
21use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
22use serde::Deserialize;
23use serde_json::{Map, Value};
24use sha2::{Digest, Sha256};
25use tokio::sync::Mutex;
26
27/// Seconds of clock skew allowed on `exp`. The contracts do not name a value; `in` uses 60 s.
28pub const CLOCK_LEEWAY_SECS: i64 = 60;
29
30/// Seconds an `iat` may lie in the future. Contracts section 2.3 says five minutes.
31pub const MAX_FUTURE_IAT_SECS: i64 = 300;
32
33/// How long a fetched key set is used before it is fetched again (contracts section 2.2).
34pub const JWKS_MAX_AGE: Duration = Duration::from_secs(10 * 60);
35
36/// The shortest gap between two key fetches. A fetch for an unknown `kid`, and a retry after a failed
37/// fetch, both wait this long. It is the one-minute refetch limit of contracts section 2.2, and it
38/// protects `im` from a flood of tokens that name keys that do not exist.
39pub const JWKS_REFRESH_GAP: Duration = Duration::from_secs(60);
40
41/// How long a failed discovery is not retried. Until it succeeds the standard paths are used.
42const DISCOVERY_RETRY_GAP: Duration = Duration::from_secs(60);
43
44/// Time limit of every call to `im`, except the directory stream.
45pub const HTTP_TIMEOUT: Duration = Duration::from_secs(10);
46
47/// Longest silence on the directory stream before the connection is given up. The server sends a
48/// keep-alive every 30 seconds (contracts section 3.2), so three of them missed means it is dead.
49const STREAM_READ_TIMEOUT: Duration = Duration::from_secs(90);
50
51/// The largest JSON answer read from `im`: discovery, the key set and token answers are far smaller.
52const MAX_DOCUMENT_BYTES: usize = 1024 * 1024;
53
54/// A service token is refreshed this long before its stated end (contracts section 2.6).
55const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60);
56
57/// The event name that marks a logout token (OIDC Back-Channel Logout 1.0).
58pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout";
59
60/// The family key of `im`. Client-credentials tokens that `in` asks for carry it as `aud`.
61pub const IM_KEY: &str = "im";
62
63/// The scope that reads the people directory and photos at `im`.
64pub const DIRECTORY_SCOPE: &str = "directory.read";
65
66/// The family key of `in` itself. Client-credentials tokens that call `in` carry it as `aud`.
67pub const FAMILY_KEY: &str = "in";
68
69/// The scope that lets a family service store and read its own objects in `in` (contracts.md 5).
70pub const FILES_SERVICE_SCOPE: &str = "files.service";
71
72/// Why a token was refused. Every variant is a refusal; none of them says more than the cause.
73#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
74pub enum TokenError {
75 /// The token is not three base64url segments with a JSON header and claims.
76 #[error("the token is malformed")]
77 Malformed,
78 /// The header names an algorithm other than EdDSA, or none at all.
79 #[error("the token is not signed with EdDSA")]
80 Algorithm,
81 /// The header has no `kid`, so the key cannot be chosen.
82 #[error("the token has no key id")]
83 NoKeyId,
84 /// The `kid` is not in the published key set. The caller may refetch the keys once.
85 #[error("the token names an unknown key")]
86 UnknownKey,
87 /// The signature does not verify with the named key.
88 #[error("the signature does not verify")]
89 Signature,
90 /// `exp` is in the past, beyond the leeway.
91 #[error("the token has expired")]
92 Expired,
93 /// A claim is missing, has the wrong type, or has the wrong value.
94 #[error("the claim {0} is missing or wrong")]
95 Claim(&'static str),
96 /// The nonce does not equal the one this sign-in sent.
97 #[error("the nonce does not match")]
98 Nonce,
99}
100
101/// Why a call to `im` failed.
102#[derive(Debug, thiserror::Error)]
103pub enum OidcError {
104 /// A token did not verify.
105 #[error(transparent)]
106 Token(#[from] TokenError),
107 /// `im` could not be reached, or answered something that is not what the contracts describe.
108 #[error("the identity provider is unavailable: {0}")]
109 Unavailable(String),
110 /// `im` answered with a refusal, such as a rejected code or a wrong client secret.
111 #[error("the identity provider refused the request")]
112 Refused,
113}
114
115/// The claims of an ID token that `in` uses. Each field is checked by [`verify_id_token`].
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct IdClaims {
118 /// The person's stable id (a ULID).
119 pub sub: String,
120 /// The `im` browser session the sign-in belongs to. Back-channel logout names it.
121 pub sid: String,
122 /// The person's email address.
123 pub email: String,
124 /// The display name. The email address when the claim is empty.
125 pub name: String,
126 /// Whether the person administers the family instance.
127 pub admin: bool,
128 /// `en` or `tr`. Anything else from `im` is read as `en`.
129 pub locale: String,
130 /// IANA time zone name.
131 pub zoneinfo: String,
132 /// Photo version; bumps when the photo changes.
133 pub picture_version: i64,
134 /// When the token was issued, in Unix seconds. `check_iat` has already made sure it is present.
135 pub iat: i64,
136}
137
138/// The claims of a back-channel logout token that `in` uses.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct LogoutClaims {
141 /// Unique id of the token. A replayed id is refused for ten minutes.
142 pub jti: String,
143 /// The `im` session that ended, when the token names one.
144 pub sid: Option<String>,
145 /// The person, when the token names one. A token with only `sub` ends every session of the person.
146 pub sub: Option<String>,
147}
148
149/// The endpoints of `im` that `in` calls. Discovery provides them; the standard paths replace them
150/// when discovery cannot be fetched.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct Endpoints {
153 /// The sign-in page, `/authorize`.
154 pub authorization: String,
155 /// The token endpoint, `/token`.
156 pub token: String,
157 /// The signing keys, `/jwks.json`.
158 pub jwks: String,
159 /// The end-session page, `/logout`.
160 pub end_session: String,
161}
162
163/// The fields of the discovery document that `in` reads.
164#[derive(Debug, Deserialize)]
165struct DiscoveryDocument {
166 issuer: String,
167 authorization_endpoint: String,
168 token_endpoint: String,
169 jwks_uri: String,
170 end_session_endpoint: Option<String>,
171}
172
173/// One key of the published JWKS, as far as `in` reads it.
174#[derive(Debug, Deserialize)]
175pub struct Jwk {
176 #[serde(default)]
177 kty: String,
178 #[serde(default)]
179 crv: String,
180 #[serde(default)]
181 x: String,
182 #[serde(default)]
183 kid: String,
184 #[serde(default)]
185 alg: String,
186 #[serde(default, rename = "use")]
187 usage: String,
188}
189
190/// The JWKS document.
191#[derive(Debug, Deserialize)]
192pub struct Jwks {
193 keys: Vec<Jwk>,
194}
195
196/// The usable Ed25519 keys of `im`, by `kid`.
197pub struct KeySet {
198 keys: Vec<(String, DecodingKey)>,
199}
200
201impl KeySet {
202 /// Keeps the keys that `in` can use: Ed25519 (`OKP`) signing keys whose algorithm, when named, is
203 /// EdDSA. Anything else in the document is skipped, not an error.
204 pub fn from_jwks(jwks: &Jwks) -> KeySet {
205 let keys = jwks
206 .keys
207 .iter()
208 .filter(|key| key.kty == "OKP" && key.crv == "Ed25519")
209 .filter(|key| key.alg.is_empty() || key.alg == "EdDSA")
210 .filter(|key| key.usage.is_empty() || key.usage == "sig")
211 .filter(|key| !key.kid.is_empty())
212 .filter_map(|key| {
213 DecodingKey::from_ed_components(&key.x)
214 .ok()
215 .map(|decoding| (key.kid.clone(), decoding))
216 })
217 .collect();
218 KeySet { keys }
219 }
220
221 /// The key with this `kid`, if it is published.
222 fn get(&self, kid: &str) -> Option<&DecodingKey> {
223 self.keys
224 .iter()
225 .find(|(known, _)| known == kid)
226 .map(|(_, key)| key)
227 }
228}
229
230/// The current time in whole seconds since the Unix epoch.
231pub fn now_secs() -> i64 {
232 SystemTime::now()
233 .duration_since(UNIX_EPOCH)
234 .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
235}
236
237/// Reads a non-empty string claim.
238fn text_claim<'a>(
239 claims: &'a Map<String, Value>,
240 name: &'static str,
241) -> Result<&'a str, TokenError> {
242 claims
243 .get(name)
244 .and_then(Value::as_str)
245 .filter(|value| !value.trim().is_empty())
246 .ok_or(TokenError::Claim(name))
247}
248
249/// Reads an optional non-empty string claim. A present but empty value counts as absent.
250fn optional_text_claim<'a>(claims: &'a Map<String, Value>, name: &str) -> Option<&'a str> {
251 claims
252 .get(name)
253 .and_then(Value::as_str)
254 .filter(|value| !value.trim().is_empty())
255}
256
257/// Whether `aud` names `expected`. A string must equal it; an array must hold exactly that one value.
258/// Contracts require an exact `client_id` for ID tokens, so a longer audience list is refused.
259fn audience_is(aud: Option<&Value>, expected: &str) -> bool {
260 match aud {
261 Some(Value::String(single)) => single == expected,
262 Some(Value::Array(items)) => {
263 items.len() == 1 && items.first().and_then(Value::as_str) == Some(expected)
264 }
265 _ => false,
266 }
267}
268
269/// Refuses an `iat` that is missing or more than [`MAX_FUTURE_IAT_SECS`] ahead of `now`.
270fn check_iat(claims: &Map<String, Value>, now: i64) -> Result<(), TokenError> {
271 let iat = claims
272 .get("iat")
273 .and_then(Value::as_i64)
274 .ok_or(TokenError::Claim("iat"))?;
275 if iat > now + MAX_FUTURE_IAT_SECS {
276 return Err(TokenError::Claim("iat"));
277 }
278 Ok(())
279}
280
281/// Reads the protected header of `token` and refuses what `in` can never verify: the token must have
282/// three segments, the header must name EdDSA, and it must carry a `kid`. Returns the `kid`.
283///
284/// The algorithm is read from the raw header, so `none` and any other algorithm are refused before a
285/// library sees the token. Callers run this before any key is fetched, so a token that cannot verify
286/// costs no network call.
287pub fn check_header(token: &str) -> Result<String, TokenError> {
288 let segments: Vec<&str> = token.split('.').collect();
289 if segments.len() != 3 {
290 return Err(TokenError::Malformed);
291 }
292 let header_bytes = BASE64_URL_SAFE_NO_PAD
293 .decode(segments[0])
294 .map_err(|_| TokenError::Malformed)?;
295 let header: Value = serde_json::from_slice(&header_bytes).map_err(|_| TokenError::Malformed)?;
296 if header.get("alg").and_then(Value::as_str) != Some("EdDSA") {
297 return Err(TokenError::Algorithm);
298 }
299 header
300 .get("kid")
301 .and_then(Value::as_str)
302 .filter(|kid| !kid.is_empty())
303 .map(str::to_owned)
304 .ok_or(TokenError::NoKeyId)
305}
306
307/// Checks the algorithm, the key id, the signature, the issuer, the expiry and the not-before time, and
308/// returns the claims. Audience, nonce and the rest are the job of the callers, which know what they
309/// expect.
310pub fn verify_signed(
311 keys: &KeySet,
312 token: &str,
313 issuer: &str,
314) -> Result<Map<String, Value>, TokenError> {
315 let kid = check_header(token)?;
316 let key = keys.get(&kid).ok_or(TokenError::UnknownKey)?;
317
318 let mut validation = Validation::new(Algorithm::EdDSA);
319 validation.leeway = u64::try_from(CLOCK_LEEWAY_SECS).unwrap_or(0);
320 validation.validate_exp = true;
321 // A token whose `nbf` lies beyond the leeway is not valid yet. A token without `nbf` is unaffected.
322 validation.validate_nbf = true;
323 // Audience is checked by the callers, because the rule differs by token kind.
324 validation.validate_aud = false;
325 validation.set_issuer(&[issuer]);
326 // `sub` is not required here: a back-channel token may carry only `sid`, and each caller checks
327 // the subject it needs.
328 validation.set_required_spec_claims(&["exp", "iss", "iat"]);
329 let data =
330 decode::<Map<String, Value>>(token, key, &validation).map_err(|error| {
331 match error.kind() {
332 ErrorKind::ExpiredSignature => TokenError::Expired,
333 ErrorKind::InvalidSignature => TokenError::Signature,
334 ErrorKind::InvalidIssuer => TokenError::Claim("iss"),
335 ErrorKind::InvalidAlgorithm => TokenError::Algorithm,
336 ErrorKind::ImmatureSignature => TokenError::Claim("nbf"),
337 ErrorKind::MissingRequiredClaim(_) => TokenError::Claim("required claim"),
338 _ => TokenError::Malformed,
339 }
340 })?;
341 Ok(data.claims)
342}
343
344/// Verifies an ID token from the code exchange: signature, issuer, `aud` equal to `client_id`, `exp`,
345/// `iat`, and the `nonce` this sign-in sent. Returns the claims `in` keeps about the person.
346pub fn verify_id_token(
347 keys: &KeySet,
348 token: &str,
349 issuer: &str,
350 client_id: &str,
351 nonce: &str,
352) -> Result<IdClaims, TokenError> {
353 let claims = verify_signed(keys, token, issuer)?;
354 if !audience_is(claims.get("aud"), client_id) {
355 return Err(TokenError::Claim("aud"));
356 }
357 check_iat(&claims, now_secs())?;
358 let sent = text_claim(&claims, "nonce")?;
359 if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) {
360 return Err(TokenError::Nonce);
361 }
362 let sub = text_claim(&claims, "sub")?.to_owned();
363 let sid = text_claim(&claims, "sid")?.to_owned();
364 let email = text_claim(&claims, "email")?.to_owned();
365 let name = optional_text_claim(&claims, "name")
366 .unwrap_or(&email)
367 .to_owned();
368 let locale = match optional_text_claim(&claims, "locale") {
369 Some("tr") => "tr".to_owned(),
370 _ => "en".to_owned(),
371 };
372 Ok(IdClaims {
373 sub,
374 sid,
375 email,
376 name,
377 admin: claims
378 .get("admin")
379 .and_then(Value::as_bool)
380 .unwrap_or(false),
381 locale,
382 zoneinfo: optional_text_claim(&claims, "zoneinfo")
383 .unwrap_or("UTC")
384 .to_owned(),
385 iat: claims
386 .get("iat")
387 .and_then(Value::as_i64)
388 .unwrap_or_default(),
389 picture_version: claims
390 .get("picture_version")
391 .and_then(Value::as_i64)
392 .unwrap_or(0)
393 .max(0),
394 })
395}
396
397/// Verifies a back-channel logout token (contracts section 2.5): signature, issuer, `aud` equal to
398/// `client_id`, `iat`, `exp`, the logout event, a `jti`, a `sid` or `sub`, and no `nonce`.
399pub fn verify_logout_token(
400 keys: &KeySet,
401 token: &str,
402 issuer: &str,
403 client_id: &str,
404) -> Result<LogoutClaims, TokenError> {
405 let claims = verify_signed(keys, token, issuer)?;
406 if !audience_is(claims.get("aud"), client_id) {
407 return Err(TokenError::Claim("aud"));
408 }
409 check_iat(&claims, now_secs())?;
410 if claims.contains_key("nonce") {
411 return Err(TokenError::Claim("nonce"));
412 }
413 let has_event = claims
414 .get("events")
415 .and_then(Value::as_object)
416 .and_then(|events| events.get(LOGOUT_EVENT))
417 .is_some_and(Value::is_object);
418 if !has_event {
419 return Err(TokenError::Claim("events"));
420 }
421 let jti = text_claim(&claims, "jti")?.to_owned();
422 let sid = optional_text_claim(&claims, "sid").map(str::to_owned);
423 let sub = optional_text_claim(&claims, "sub").map(str::to_owned);
424 if sid.is_none() && sub.is_none() {
425 return Err(TokenError::Claim("sub"));
426 }
427 Ok(LogoutClaims { jti, sid, sub })
428}
429
430/// The claims of a client-credentials access token that a machine API needs (contracts.md 2.6).
431#[derive(Debug, Clone, PartialEq, Eq)]
432pub struct MachineClaims {
433 /// The token subject, `client:<client_id>` for a client-credentials token. Only the prefix is checked.
434 pub subject: String,
435 /// The scopes the token grants, from the space-separated `scope` claim. Empty when there is none.
436 pub scopes: Vec<String>,
437 /// The caller's family key from `svc`. Callers treat it as their identity. `None` when absent.
438 pub svc: Option<String>,
439}
440
441/// Verifies an access token addressed to `audience` (for `in`, [`FAMILY_KEY`]): signature, `iss`, `exp`
442/// (with leeway), `iat` (at most five minutes ahead), and `aud` equal to `audience` exactly. It does not
443/// judge the scopes or the `svc` claim; the caller decides what they must contain, because the refusal
444/// differs (a missing `svc` is a bad token, a missing scope is a forbidden call).
445pub fn verify_machine_token(
446 keys: &KeySet,
447 token: &str,
448 issuer: &str,
449 audience: &str,
450) -> Result<MachineClaims, TokenError> {
451 let claims = verify_signed(keys, token, issuer)?;
452 if !audience_is(claims.get("aud"), audience) {
453 return Err(TokenError::Claim("aud"));
454 }
455 check_iat(&claims, now_secs())?;
456 let subject = text_claim(&claims, "sub")?.to_owned();
457 let scopes = optional_text_claim(&claims, "scope")
458 .map(|scope| {
459 scope
460 .split(' ')
461 .filter(|s| !s.is_empty())
462 .map(str::to_owned)
463 .collect()
464 })
465 .unwrap_or_default();
466 let svc = optional_text_claim(&claims, "svc").map(str::to_owned);
467 Ok(MachineClaims {
468 subject,
469 scopes,
470 svc,
471 })
472}
473
474#[cfg(test)]
475impl OidcClient {
476 /// A client whose key set is `keys` and whose endpoints are the standard paths under `issuer`. The cache
477 /// is filled directly, so no request is made. Production always fetches; only tests use this.
478 pub(crate) fn with_keys_for_tests(issuer: &str, client_id: &str, keys: KeySet) -> Self {
479 let config = Oidc {
480 issuer: issuer.to_owned(),
481 client_id: client_id.to_owned(),
482 client_secret_file: std::path::PathBuf::new(),
483 };
484 let mut client =
485 Self::new(&config, "https://in.test", "test-secret".to_owned()).expect("client");
486 let endpoints = client.standard_endpoints();
487 let cache = client.cache.get_mut();
488 cache.endpoints = Some(Arc::new(endpoints));
489 cache.keys = Some((Instant::now(), Arc::new(keys)));
490 client
491 }
492}
493
494/// Ed25519 keys and signed tokens for the tests of this crate. Test-only; production keys come from `im`.
495#[cfg(test)]
496pub(crate) mod test_support {
497 use super::*;
498 use ed25519_dalek::SigningKey;
499 use ed25519_dalek::pkcs8::EncodePrivateKey;
500 use jsonwebtoken::{EncodingKey, Header, encode};
501 use serde_json::json;
502
503 /// The issuer the test tokens name.
504 pub(crate) const ISSUER: &str = "https://im.example.test";
505 /// The client id `in` uses in the tests.
506 pub(crate) const CLIENT: &str = "in";
507 /// The key id of the test key.
508 pub(crate) const KID: &str = "k1";
509
510 /// A fresh Ed25519 key: the signing half as PKCS#8 DER, and the key set that publishes it.
511 pub(crate) fn test_key() -> (Vec<u8>, KeySet) {
512 let mut seed = [0u8; 32];
513 rand::fill(&mut seed);
514 let signing = SigningKey::from_bytes(&seed);
515 let der = signing.to_pkcs8_der().expect("pkcs8").as_bytes().to_vec();
516 let x = BASE64_URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes());
517 let jwks: Jwks = serde_json::from_value(json!({
518 "keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": KID, "use": "sig", "alg": "EdDSA"}]
519 }))
520 .expect("jwks");
521 (der, KeySet::from_jwks(&jwks))
522 }
523
524 /// Signs `claims` with `der` under [`KID`].
525 pub(crate) fn sign(der: &[u8], claims: &Value) -> String {
526 let mut header = Header::new(Algorithm::EdDSA);
527 header.kid = Some(KID.to_owned());
528 encode(&header, claims, &EncodingKey::from_ed_der(der)).expect("sign")
529 }
530}
531
532/// The PKCE code challenge of `verifier`: base64url of its SHA-256, without padding (RFC 7636).
533pub fn pkce_challenge(verifier: &str) -> String {
534 BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
535}
536
537/// Reads a response body of at most `limit` bytes. Returns `None` when the body is larger, and stops
538/// reading as soon as it is, so a server that lies about its length cannot make `in` hold more than
539/// `limit` bytes.
540pub async fn read_limited(
541 mut response: reqwest::Response,
542 limit: usize,
543) -> Result<Option<Vec<u8>>, reqwest::Error> {
544 if response
545 .content_length()
546 .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX))
547 {
548 return Ok(None);
549 }
550 let mut body = Vec::new();
551 while let Some(chunk) = response.chunk().await? {
552 if body.len() + chunk.len() > limit {
553 return Ok(None);
554 }
555 body.extend_from_slice(&chunk);
556 }
557 Ok(Some(body))
558}
559
560/// Reads the body of a JSON answer from `im`, at most [`MAX_DOCUMENT_BYTES`]. A larger body is unavailable,
561/// and a read error is reported without the URL.
562async fn read_document(response: reqwest::Response) -> Result<Vec<u8>, OidcError> {
563 read_limited(response, MAX_DOCUMENT_BYTES)
564 .await
565 .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?
566 .ok_or_else(|| {
567 OidcError::Unavailable(format!(
568 "an answer is larger than {MAX_DOCUMENT_BYTES} bytes"
569 ))
570 })
571}
572
573/// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1):
574/// unreserved characters pass, everything else becomes `%XX`.
575pub fn percent_encode(value: &str) -> String {
576 let mut out = String::with_capacity(value.len());
577 for byte in value.bytes() {
578 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
579 out.push(char::from(byte));
580 } else {
581 out.push_str(&format!("%{byte:02X}"));
582 }
583 }
584 out
585}
586
587/// The body of a successful token response. Only the fields `in` reads are named.
588#[derive(Debug, Deserialize)]
589struct TokenResponse {
590 #[serde(default)]
591 id_token: Option<String>,
592 #[serde(default)]
593 access_token: Option<String>,
594 #[serde(default)]
595 expires_in: Option<u64>,
596}
597
598/// Cached state of the client. Every field is behind one lock. No method holds it across a network
599/// call, and no method holds it while it takes it again.
600#[derive(Default)]
601struct Cache {
602 /// The endpoints from discovery, once fetched.
603 endpoints: Option<Arc<Endpoints>>,
604 /// When the last discovery failed. Until [`DISCOVERY_RETRY_GAP`] has passed, the standard paths
605 /// are used without asking again.
606 discovery_failed_at: Option<Instant>,
607 /// The key set and when it was fetched.
608 keys: Option<(Instant, Arc<KeySet>)>,
609 /// When the keys were last fetched for an unknown `kid`, or a fetch failed. Limits those fetches.
610 keys_refresh_at: Option<Instant>,
611 /// The client-credentials token for `im`, and the instant it stops being used.
612 service: Option<(String, Instant)>,
613}
614
615/// What the cache answers for the key set, without the network. `None` means a fetch is due.
616///
617/// A fresh set is used as it is unless a refetch is forced. Any set, fresh or stale, is also used while
618/// the last fetch attempt is younger than [`JWKS_REFRESH_GAP`]. That rate-limits forced refetches for
619/// unknown key ids and retries after a failed refetch alike. With no set at all, a recent failure is an
620/// answer of its own, so requests do not each wait for `im` again.
621fn keys_from_cache(cache: &Cache, force: bool) -> Option<Result<Arc<KeySet>, OidcError>> {
622 let recently_tried = cache
623 .keys_refresh_at
624 .is_some_and(|at| at.elapsed() < JWKS_REFRESH_GAP);
625 match &cache.keys {
626 Some((at, keys)) if at.elapsed() < JWKS_MAX_AGE && !force => Some(Ok(Arc::clone(keys))),
627 Some((_, keys)) if recently_tried => Some(Ok(Arc::clone(keys))),
628 None if recently_tried => Some(Err(OidcError::Unavailable(
629 "the signing keys are not available yet".to_owned(),
630 ))),
631 _ => None,
632 }
633}
634
635/// The OpenID Connect client. One per process, shared through the app state.
636pub struct OidcClient {
637 issuer: String,
638 client_id: String,
639 client_secret: String,
640 redirect_uri: String,
641 http: reqwest::Client,
642 stream_http: reqwest::Client,
643 cache: Mutex<Cache>,
644 /// Held while the key set is fetched. One fetch runs at a time, and the requests that wait for it
645 /// read the result from the cache. It is never held while `cache` is held.
646 refresh: Mutex<()>,
647}
648
649impl OidcClient {
650 /// Builds the client from the `[oidc]` table, the public base URL and the client secret read from
651 /// its file. No request is made here.
652 pub fn new(config: &Oidc, base_url: &str, client_secret: String) -> CoreResult<Self> {
653 let http = reqwest::Client::builder()
654 .timeout(HTTP_TIMEOUT)
655 .connect_timeout(HTTP_TIMEOUT)
656 .redirect(reqwest::redirect::Policy::none())
657 .build()
658 .map_err(|e| CoreError::Config(format!("cannot build the HTTP client: {e}")))?;
659 // The directory stream lasts for minutes, so it gets no total time limit, only a read limit.
660 let stream_http = reqwest::Client::builder()
661 .connect_timeout(HTTP_TIMEOUT)
662 .read_timeout(STREAM_READ_TIMEOUT)
663 .redirect(reqwest::redirect::Policy::none())
664 .build()
665 .map_err(|e| CoreError::Config(format!("cannot build the stream client: {e}")))?;
666 Ok(Self {
667 issuer: config.issuer.clone(),
668 client_id: config.client_id.clone(),
669 client_secret,
670 redirect_uri: format!("{base_url}/auth/callback"),
671 http,
672 stream_http,
673 cache: Mutex::new(Cache::default()),
674 refresh: Mutex::new(()),
675 })
676 }
677
678 /// The issuer URL of `im`, which is also the origin of its API.
679 pub fn issuer(&self) -> &str {
680 &self.issuer
681 }
682
683 /// The HTTP client for calls to `im` with a time limit.
684 pub fn http(&self) -> &reqwest::Client {
685 &self.http
686 }
687
688 /// The HTTP client for the directory stream, which has no total time limit.
689 pub fn stream_http(&self) -> &reqwest::Client {
690 &self.stream_http
691 }
692
693 /// The endpoints of `im`. Fetched from discovery once; when discovery fails, the standard paths
694 /// under the issuer are used and discovery is retried after [`DISCOVERY_RETRY_GAP`].
695 pub async fn endpoints(&self) -> Arc<Endpoints> {
696 {
697 let cache = self.cache.lock().await;
698 if let Some(endpoints) = &cache.endpoints {
699 return Arc::clone(endpoints);
700 }
701 if cache
702 .discovery_failed_at
703 .is_some_and(|at| at.elapsed() < DISCOVERY_RETRY_GAP)
704 {
705 return Arc::new(self.standard_endpoints());
706 }
707 }
708 // The lock is not held during the request. Two requests may race to fetch; both get the same
709 // document, so that is harmless.
710 match self.fetch_discovery().await {
711 Ok(endpoints) => {
712 let endpoints = Arc::new(endpoints);
713 let mut cache = self.cache.lock().await;
714 cache.endpoints = Some(Arc::clone(&endpoints));
715 cache.discovery_failed_at = None;
716 endpoints
717 }
718 Err(error) => {
719 tracing::warn!(error = %error, "oidc: discovery failed, using the standard paths");
720 self.cache.lock().await.discovery_failed_at = Some(Instant::now());
721 Arc::new(self.standard_endpoints())
722 }
723 }
724 }
725
726 /// The paths of contracts section 2.1, under the issuer.
727 fn standard_endpoints(&self) -> Endpoints {
728 Endpoints {
729 authorization: format!("{}/authorize", self.issuer),
730 token: format!("{}/token", self.issuer),
731 jwks: format!("{}/jwks.json", self.issuer),
732 end_session: format!("{}/logout", self.issuer),
733 }
734 }
735
736 /// Fetches and checks the discovery document. Its `issuer` must equal the configured one exactly.
737 async fn fetch_discovery(&self) -> Result<Endpoints, OidcError> {
738 let url = format!("{}/.well-known/openid-configuration", self.issuer);
739 let document: DiscoveryDocument = self.get_json(&url).await?;
740 if document.issuer != self.issuer {
741 return Err(OidcError::Unavailable(
742 "discovery names another issuer".to_owned(),
743 ));
744 }
745 let end_session = document
746 .end_session_endpoint
747 .unwrap_or_else(|| format!("{}/logout", self.issuer));
748 Ok(Endpoints {
749 authorization: document.authorization_endpoint,
750 token: document.token_endpoint,
751 jwks: document.jwks_uri,
752 end_session,
753 })
754 }
755
756 /// GETs a JSON document. A non-2xx answer is unavailable: the caller cannot do anything with it.
757 async fn get_json<T: serde::de::DeserializeOwned>(&self, url: &str) -> Result<T, OidcError> {
758 let response = self
759 .http
760 .get(url)
761 .send()
762 .await
763 .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?;
764 if !response.status().is_success() {
765 return Err(OidcError::Unavailable(format!(
766 "{url} answered {}",
767 response.status()
768 )));
769 }
770 let bytes = read_document(response).await?;
771 serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string()))
772 }
773
774 /// The key set in use. The cache answers when it can (see [`keys_from_cache`]). Otherwise one request
775 /// at a time fetches it, with no lock held during the network call. A failed refetch keeps the old
776 /// set, because a stale key still verifies tokens that were signed with it.
777 async fn load_keys(&self, force: bool) -> Result<Arc<KeySet>, OidcError> {
778 let decided = keys_from_cache(&*self.cache.lock().await, force);
779 if let Some(answer) = decided {
780 return answer;
781 }
782 let _single_flight = self.refresh.lock().await;
783 // A request that waited for the fetch above finds its answer here.
784 let decided = keys_from_cache(&*self.cache.lock().await, force);
785 if let Some(answer) = decided {
786 return answer;
787 }
788 let endpoints = self.endpoints().await;
789 // Only a forced refetch or a failure starts the gap. A scheduled fetch does not, so the first token
790 // signed by a newly rotated key is verified at once.
791 if force {
792 self.cache.lock().await.keys_refresh_at = Some(Instant::now());
793 }
794 let fetched = self.get_json::<Jwks>(&endpoints.jwks).await;
795 let mut cache = self.cache.lock().await;
796 if fetched.is_err() {
797 cache.keys_refresh_at = Some(Instant::now());
798 }
799 match fetched {
800 Ok(jwks) => {
801 let keys = Arc::new(KeySet::from_jwks(&jwks));
802 cache.keys = Some((Instant::now(), Arc::clone(&keys)));
803 Ok(keys)
804 }
805 Err(error) => match &cache.keys {
806 Some((_, keys)) => {
807 tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys");
808 Ok(Arc::clone(keys))
809 }
810 None => Err(error),
811 },
812 }
813 }
814
815 /// Verifies a client-credentials access token addressed to `audience`, with the cached key set. See
816 /// [`verify_machine_token`].
817 pub async fn verify_machine_token(
818 &self,
819 token: &str,
820 audience: &str,
821 ) -> Result<MachineClaims, OidcError> {
822 self.verify_with(token, |keys| {
823 verify_machine_token(keys, token, &self.issuer, audience)
824 })
825 .await
826 }
827
828 /// Runs `check` against the key set. The header is checked first, so a token that cannot verify
829 /// fetches nothing. An unknown key id triggers one rate-limited refetch.
830 async fn verify_with<T>(
831 &self,
832 token: &str,
833 check: impl Fn(&KeySet) -> Result<T, TokenError>,
834 ) -> Result<T, OidcError> {
835 check_header(token)?;
836 let keys = self.load_keys(false).await?;
837 match check(&keys) {
838 Err(TokenError::UnknownKey) => {
839 let keys = self.load_keys(true).await?;
840 Ok(check(&keys)?)
841 }
842 outcome => Ok(outcome?),
843 }
844 }
845
846 /// Verifies an ID token of this sign-in. See [`verify_id_token`].
847 pub async fn verify_id_token(&self, token: &str, nonce: &str) -> Result<IdClaims, OidcError> {
848 self.verify_with(token, |keys| {
849 verify_id_token(keys, token, &self.issuer, &self.client_id, nonce)
850 })
851 .await
852 }
853
854 /// Verifies a back-channel logout token. See [`verify_logout_token`].
855 pub async fn verify_logout_token(&self, token: &str) -> Result<LogoutClaims, OidcError> {
856 self.verify_with(token, |keys| {
857 verify_logout_token(keys, token, &self.issuer, &self.client_id)
858 })
859 .await
860 }
861
862 /// The URL that sends the browser to `im` to sign in (contracts section 2.3, step 1).
863 pub async fn authorize_url(
864 &self,
865 state: &str,
866 nonce: &str,
867 challenge: &str,
868 ) -> Result<String, OidcError> {
869 let endpoints = self.endpoints().await;
870 let mut url = reqwest::Url::parse(&endpoints.authorization)
871 .map_err(|e| OidcError::Unavailable(format!("bad authorization endpoint: {e}")))?;
872 url.query_pairs_mut()
873 .append_pair("response_type", "code")
874 .append_pair("client_id", &self.client_id)
875 .append_pair("redirect_uri", &self.redirect_uri)
876 .append_pair("scope", "openid profile email")
877 .append_pair("state", state)
878 .append_pair("nonce", nonce)
879 .append_pair("code_challenge", challenge)
880 .append_pair("code_challenge_method", "S256");
881 Ok(url.to_string())
882 }
883
884 /// The URL that ends the `im` session (RP-initiated logout, contracts section 2.5).
885 pub async fn end_session_url(
886 &self,
887 id_token_hint: &str,
888 post_logout_redirect: &str,
889 state: &str,
890 ) -> Result<String, OidcError> {
891 let endpoints = self.endpoints().await;
892 let mut url = reqwest::Url::parse(&endpoints.end_session)
893 .map_err(|e| OidcError::Unavailable(format!("bad end-session endpoint: {e}")))?;
894 url.query_pairs_mut()
895 .append_pair("id_token_hint", id_token_hint)
896 .append_pair("post_logout_redirect_uri", post_logout_redirect)
897 .append_pair("state", state);
898 Ok(url.to_string())
899 }
900
901 /// Exchanges the authorization code for the ID token (contracts section 2.3, step 3). The access
902 /// and refresh tokens are not kept: this family does not use them.
903 pub async fn exchange_code(&self, code: &str, verifier: &str) -> Result<String, OidcError> {
904 let endpoints = self.endpoints().await;
905 let response = self
906 .token_request(
907 &endpoints.token,
908 &[
909 ("grant_type", "authorization_code"),
910 ("code", code),
911 ("redirect_uri", &self.redirect_uri),
912 ("code_verifier", verifier),
913 ],
914 )
915 .await?;
916 response
917 .id_token
918 .ok_or(OidcError::Token(TokenError::Claim("id_token")))
919 }
920
921 /// A client-credentials token for the directory at `im` (contracts section 2.6). Cached until
922 /// [`SERVICE_TOKEN_MARGIN`] before its stated lifetime ends.
923 pub async fn service_token(&self) -> Result<String, OidcError> {
924 {
925 let cache = self.cache.lock().await;
926 if let Some((token, until)) = &cache.service
927 && Instant::now() < *until
928 {
929 return Ok(token.clone());
930 }
931 }
932 let endpoints = self.endpoints().await;
933 let response = self
934 .token_request(
935 &endpoints.token,
936 &[
937 ("grant_type", "client_credentials"),
938 ("scope", DIRECTORY_SCOPE),
939 ("audience", IM_KEY),
940 ],
941 )
942 .await?;
943 let token = response
944 .access_token
945 .ok_or(OidcError::Token(TokenError::Claim("access_token")))?;
946 let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0));
947 let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN);
948 self.cache.lock().await.service = Some((token.clone(), until));
949 Ok(token)
950 }
951
952 /// Posts a form to a token endpoint with client_secret_basic authentication (RFC 6749 section
953 /// 2.3.1). A 4xx answer is a refusal; anything else that is not a success is unavailable.
954 async fn token_request(
955 &self,
956 url: &str,
957 form: &[(&str, &str)],
958 ) -> Result<TokenResponse, OidcError> {
959 let credentials = format!(
960 "{}:{}",
961 percent_encode(&self.client_id),
962 percent_encode(&self.client_secret)
963 );
964 let response = self
965 .http
966 .post(url)
967 .header(
968 reqwest::header::AUTHORIZATION,
969 format!("Basic {}", BASE64_STANDARD.encode(credentials)),
970 )
971 .header(reqwest::header::ACCEPT, "application/json")
972 .form(form)
973 .send()
974 .await
975 .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?;
976 let status = response.status();
977 if status.is_client_error() {
978 tracing::warn!(status = %status, "oidc: the token endpoint refused the request");
979 return Err(OidcError::Refused);
980 }
981 if !status.is_success() {
982 return Err(OidcError::Unavailable(format!(
983 "token endpoint answered {status}"
984 )));
985 }
986 let bytes = read_document(response).await?;
987 serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string()))
988 }
989}
990
991#[cfg(test)]
992mod tests {
993 use super::test_support::{CLIENT, ISSUER, sign, test_key};
994 use super::*;
995 use serde_json::json;
996
997 const NONCE: &str = "nonce-value";
998
999 fn id_claims(now: i64) -> Value {
1000 json!({
1001 "iss": ISSUER, "sub": "01JTESTSUB", "aud": CLIENT, "exp": now + 300, "iat": now,
1002 "nonce": NONCE, "sid": "im-session-1", "email": "ann@example.test", "name": "Ann",
1003 })
1004 }
1005
1006 #[test]
1007 fn a_valid_id_token_is_accepted() {
1008 let (der, keys) = test_key();
1009 let token = sign(&der, &id_claims(now_secs()));
1010 let claims = verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).expect("valid");
1011 assert_eq!(claims.sub, "01JTESTSUB");
1012 assert_eq!(claims.sid, "im-session-1");
1013 assert_eq!(claims.locale, "en");
1014 }
1015
1016 #[test]
1017 fn an_unsigned_alg_none_token_is_refused() {
1018 let (_der, keys) = test_key();
1019 let header = BASE64_URL_SAFE_NO_PAD.encode(br#"{"alg":"none","kid":"k1","typ":"JWT"}"#);
1020 let payload = BASE64_URL_SAFE_NO_PAD.encode(id_claims(now_secs()).to_string());
1021 let token = format!("{header}.{payload}.");
1022 assert_eq!(
1023 verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(),
1024 Some(TokenError::Algorithm)
1025 );
1026 }
1027
1028 #[test]
1029 fn a_token_for_another_audience_is_refused() {
1030 let (der, keys) = test_key();
1031 let mut claims = id_claims(now_secs());
1032 claims["aud"] = json!("iz");
1033 let token = sign(&der, &claims);
1034 assert_eq!(
1035 verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(),
1036 Some(TokenError::Claim("aud"))
1037 );
1038 }
1039
1040 #[test]
1041 fn an_expired_token_is_refused_beyond_the_leeway() {
1042 let (der, keys) = test_key();
1043 let now = now_secs();
1044 let mut claims = id_claims(now);
1045 claims["exp"] = json!(now - 3 * CLOCK_LEEWAY_SECS);
1046 let token = sign(&der, &claims);
1047 assert_eq!(
1048 verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(),
1049 Some(TokenError::Expired)
1050 );
1051 }
1052
1053 #[test]
1054 fn a_wrong_nonce_is_refused() {
1055 let (der, keys) = test_key();
1056 let token = sign(&der, &id_claims(now_secs()));
1057 assert_eq!(
1058 verify_id_token(&keys, &token, ISSUER, CLIENT, "another-nonce").err(),
1059 Some(TokenError::Nonce)
1060 );
1061 }
1062
1063 #[test]
1064 fn the_pkce_challenge_matches_the_rfc_7636_vector() {
1065 assert_eq!(
1066 pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
1067 "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
1068 );
1069 }
1070}