forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

oidc.rs975 lines, 38.2 KiBHistoryRawDownload
1//! The OpenID Connect relying party for `im` (docs/contracts.md section 2), and the client
2//! credentials token that iz uses to read the people directory (section 2.6).
3//!
4//! It finds `im`'s endpoints through discovery and keeps them for an hour. It keeps `im`'s signing
5//! keys (JWKS) for ten minutes, and refetches them at most once a minute when a token names a key that
6//! is not known. It exchanges authorization codes, and it verifies ID tokens and logout tokens.
7//!
8//! It decides nothing about who may sign in: that is `pages/sign_in.rs` and the store. It keeps no
9//! session state: that is `iz_core::store::sessions`.
10//!
11//! Verification accepts EdDSA only. The shape, the algorithm and the `kid` are checked before any key
12//! set is fetched, so `none` and every other algorithm are refused without a call to `im`. The checks
13//! are: the signature, `iss` equal to the configured issuer, `aud` equal to the client id, `exp` and
14//! `nbf` with 60 seconds of leeway, `iat` not more than five minutes ahead, and the claims each token
15//! kind needs. The pure functions below take the key set and the clock as arguments, so the tests can
16//! run without a network.
17
18use std::collections::HashMap;
19use std::fmt;
20use std::path::Path;
21use std::sync::Arc;
22use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
23
24use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
25use futures_util::StreamExt;
26use iz_core::config::OidcConfig;
27use iz_core::token::constant_time_eq;
28use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
29use serde::Deserialize;
30use serde_json::{Map, Value};
31use sha2::{Digest, Sha256};
32use tokio::sync::Mutex;
33
34/// The scope that reads the people directory and its photos at `im`.
35pub const DIRECTORY_SCOPE: &str = "directory.read";
36/// The audience of every directory call: the family key of `im`.
37pub const IM_AUDIENCE: &str = "im";
38/// The scopes asked for at sign-in. `openid` is required; `profile` and `email` carry the claims iz uses.
39pub const SIGN_IN_SCOPE: &str = "openid profile email";
40/// The event name a back-channel logout token must carry (OIDC Back-Channel Logout 1.0).
41pub const BACKCHANNEL_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout";
42
43/// Longest wait for one call to `im`, in seconds. Reason: a slow identity provider must not hold a
44/// request, and the directory worker retries with backoff anyway.
45pub const IM_TIMEOUT: Duration = Duration::from_secs(10);
46/// Clock skew tolerated on `exp`, in seconds. Reason: the task policy for every token check.
47pub const LEEWAY_SECS: u64 = 60;
48/// How far ahead of the local clock an `iat` may be, in seconds. Reason: contracts.md 2.3, five minutes.
49pub const MAX_IAT_AHEAD_SECS: u64 = 300;
50/// Largest discovery, JWKS or token response read from `im`, in bytes. Reason: those documents are
51/// a few kilobytes; a larger answer is not what `im` sends.
52pub const MAX_RESPONSE_BYTES: usize = 256 * 1024;
53/// How long discovery is cached, before it is fetched again.
54const DISCOVERY_TTL: Duration = Duration::from_secs(3600);
55/// How long the JWKS is cached, before it is fetched again (contracts.md 2.2).
56const KEYS_TTL: Duration = Duration::from_secs(600);
57/// The shortest gap between two JWKS fetch attempts (contracts.md 2.2). It bounds the refetch for unknown
58/// key ids, and the retries after a failed fetch, so an unreachable `im` is not asked once per request.
59const UNKNOWN_KEY_REFETCH: Duration = Duration::from_secs(60);
60/// A service token is replaced this long before it expires (contracts.md 2.6).
61const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60);
62
63/// Every failure of a call to `im` or of a token check.
64#[derive(Debug, thiserror::Error)]
65pub enum ImError {
66 /// The token is signed with a key id that is not in the key set. The caller may refetch the
67 /// keys once and check again.
68 #[error("the token names a key that is not published")]
69 UnknownKey,
70 /// The token failed a check. The text names the check; it is for logs only.
71 #[error("the token was rejected: {0}")]
72 Rejected(String),
73 /// `im` could not be reached, or it did not answer in time.
74 #[error("the account service cannot be reached: {0}")]
75 Unavailable(String),
76 /// `im` answered, but not in a form iz accepts.
77 #[error("the account service answered in an unexpected way: {0}")]
78 BadResponse(String),
79}
80
81/// The result of a call to `im` or of a token check.
82pub type ImResult<T> = std::result::Result<T, ImError>;
83
84/// The part of the discovery document that iz uses (contracts.md 2.1).
85#[derive(Debug, Deserialize)]
86pub struct Discovery {
87 /// Must equal the configured issuer exactly.
88 pub issuer: String,
89 /// Where the browser is sent to sign in.
90 pub authorization_endpoint: String,
91 /// Where codes and client credentials are exchanged for tokens.
92 pub token_endpoint: String,
93 /// Where the signing keys are published.
94 pub jwks_uri: String,
95 /// Where the browser is sent to end its `im` session.
96 #[serde(default)]
97 pub end_session_endpoint: Option<String>,
98}
99
100/// The answer of the token endpoint. The refresh token is not read: iz discards it (contracts.md 2.4).
101#[derive(Deserialize)]
102pub struct TokenResponse {
103 /// The ID token, for an authorization-code exchange.
104 #[serde(default)]
105 pub id_token: Option<String>,
106 /// The access token, for a client-credentials grant.
107 #[serde(default)]
108 pub access_token: Option<String>,
109 /// The lifetime of the access token, in seconds.
110 #[serde(default)]
111 pub expires_in: Option<u64>,
112}
113
114// Hand-written so that a debug print never shows the ID token or the access token.
115impl fmt::Debug for TokenResponse {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.debug_struct("TokenResponse")
118 .field("id_token", &self.id_token.as_ref().map(|_| "<redacted>"))
119 .field(
120 "access_token",
121 &self.access_token.as_ref().map(|_| "<redacted>"),
122 )
123 .field("expires_in", &self.expires_in)
124 .finish()
125 }
126}
127
128/// The claims of an ID token that iz uses. `sid` is the `im` browser session.
129#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
130pub struct IdClaims {
131 /// The user's id (a ULID, stable forever).
132 pub sub: String,
133 /// The `im` browser session id, kept with the local session for back-channel logout.
134 #[serde(default)]
135 pub sid: Option<String>,
136 /// The address. `im` only stores confirmed addresses.
137 #[serde(default)]
138 pub email: Option<String>,
139 /// The display name.
140 #[serde(default)]
141 pub name: Option<String>,
142 /// Whether `im` marks the user as an instance administrator.
143 #[serde(default)]
144 pub admin: bool,
145 /// The language the user chose in `im`, `en` or `tr`.
146 #[serde(default)]
147 pub locale: Option<String>,
148 /// The user's IANA time zone, for example `Europe/Istanbul`.
149 #[serde(default)]
150 pub zoneinfo: Option<String>,
151 /// Bumps when the photo changes. Used as the avatar cache key.
152 #[serde(default)]
153 pub picture_version: i64,
154 /// When `im` issued the token, in Unix seconds. Orders a sign-in against directory changes.
155 #[serde(default)]
156 pub iat: i64,
157}
158
159/// The claims of a back-channel logout token that iz uses.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct LogoutClaims {
162 /// The token id, refused when it is seen again.
163 pub jti: String,
164 /// The `im` browser session that ended, when the token names one.
165 pub sid: Option<String>,
166 /// The user whose sessions end, when the token names one.
167 pub sub: Option<String>,
168}
169
170#[derive(Deserialize)]
171struct JwksDocument {
172 keys: Vec<Jwk>,
173}
174
175#[derive(Deserialize)]
176struct Jwk {
177 kty: String,
178 #[serde(default)]
179 crv: Option<String>,
180 #[serde(default)]
181 x: Option<String>,
182 #[serde(default)]
183 kid: Option<String>,
184 #[serde(default)]
185 alg: Option<String>,
186}
187
188/// The verification keys of `im`, by key id. Only Ed25519 keys are kept; others are skipped.
189#[derive(Default)]
190pub struct KeySet {
191 keys: HashMap<String, DecodingKey>,
192}
193
194impl KeySet {
195 /// Reads a JWKS document. Keys that are not Ed25519 or have no `kid` are skipped, not fatal.
196 pub fn from_jwks(bytes: &[u8]) -> ImResult<KeySet> {
197 let document: JwksDocument = serde_json::from_slice(bytes)
198 .map_err(|e| ImError::BadResponse(format!("the key set is not JSON: {e}")))?;
199 let mut keys = HashMap::new();
200 for jwk in document.keys {
201 let (Some(kid), Some(x)) = (jwk.kid.as_deref(), jwk.x.as_deref()) else {
202 continue;
203 };
204 let is_ed25519 = jwk.kty == "OKP" && jwk.crv.as_deref() == Some("Ed25519");
205 if !is_ed25519 || jwk.alg.as_deref().is_some_and(|alg| alg != "EdDSA") {
206 continue;
207 }
208 match DecodingKey::from_ed_components(x) {
209 Ok(key) => {
210 keys.insert(kid.to_owned(), key);
211 }
212 Err(e) => tracing::warn!(kid, error = %e, "skipping an unreadable signing key"),
213 }
214 }
215 Ok(KeySet { keys })
216 }
217
218 fn get(&self, kid: &str) -> Option<&DecodingKey> {
219 self.keys.get(kid)
220 }
221}
222
223/// The client of `im`: discovery, keys, token calls and token checks. One per process.
224pub struct OidcClient {
225 issuer: String,
226 client_id: String,
227 client_secret: String,
228 redirect_uri: String,
229 post_logout_uri: String,
230 /// Short calls: discovery, keys, tokens, photos. The timeout applies to the whole call.
231 http: reqwest::Client,
232 /// Long-lived event stream. Only the connect is bounded here; the reader has its own idle limit.
233 stream_http: reqwest::Client,
234 discovery: Mutex<Option<(Instant, Arc<Discovery>)>>,
235 keys: Mutex<KeyCache>,
236 /// Held across a JWKS fetch, so one fetch runs at a time. It is never held together with `keys`,
237 /// which is only locked for reads and writes of the cache.
238 refresh: Mutex<()>,
239 /// Client-credentials tokens by `(audience, scope)`. Each target has its own entry.
240 service: Mutex<HashMap<(String, String), (Instant, String)>>,
241}
242
243#[derive(Default)]
244struct KeyCache {
245 /// The last key set fetched, and when it was fetched.
246 current: Option<(Instant, Arc<KeySet>)>,
247 /// When the keys were last fetched for an unknown key, or a fetch failed. Limits those fetches.
248 last_fetch: Option<Instant>,
249}
250
251impl OidcClient {
252 /// Builds the client. `base_url` is the public origin of iz, from which the callback and the
253 /// post-logout URIs are derived; `im` has these registered for the client.
254 pub fn new(
255 config: &OidcConfig,
256 base_url: &str,
257 client_secret: String,
258 ) -> iz_core::Result<Self> {
259 // Redirects are never followed: a token call that is redirected would send the client
260 // secret to another host.
261 let http = reqwest::Client::builder()
262 .timeout(IM_TIMEOUT)
263 .connect_timeout(IM_TIMEOUT)
264 .redirect(reqwest::redirect::Policy::none())
265 .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION")))
266 .build()
267 .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?;
268 let stream_http = reqwest::Client::builder()
269 .connect_timeout(IM_TIMEOUT)
270 .redirect(reqwest::redirect::Policy::none())
271 .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION")))
272 .build()
273 .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?;
274 Ok(OidcClient {
275 issuer: config.issuer.clone(),
276 client_id: config.client_id.clone(),
277 client_secret,
278 redirect_uri: format!("{base_url}/auth/callback"),
279 post_logout_uri: format!("{base_url}/"),
280 http,
281 stream_http,
282 discovery: Mutex::new(None),
283 keys: Mutex::new(KeyCache::default()),
284 refresh: Mutex::new(()),
285 service: Mutex::new(HashMap::new()),
286 })
287 }
288
289 /// The configured issuer, exactly as it is compared with `iss`.
290 pub fn issuer(&self) -> &str {
291 &self.issuer
292 }
293
294 /// The short-call HTTP client.
295 pub fn http(&self) -> &reqwest::Client {
296 &self.http
297 }
298
299 /// The event-stream HTTP client.
300 pub fn stream_http(&self) -> &reqwest::Client {
301 &self.stream_http
302 }
303
304 /// The discovery document, fetched once and kept for an hour.
305 pub async fn discovery(&self) -> ImResult<Arc<Discovery>> {
306 let mut slot = self.discovery.lock().await;
307 if let Some((at, doc)) = slot.as_ref()
308 && at.elapsed() < DISCOVERY_TTL
309 {
310 return Ok(doc.clone());
311 }
312 let url = format!("{}/.well-known/openid-configuration", self.issuer);
313 let response = self.http.get(url).send().await.map_err(unavailable)?;
314 if !response.status().is_success() {
315 return Err(ImError::Unavailable(format!(
316 "discovery answered {}",
317 response.status().as_u16()
318 )));
319 }
320 let body = read_limited(response, MAX_RESPONSE_BYTES).await?;
321 let doc: Discovery = serde_json::from_slice(&body)
322 .map_err(|e| ImError::BadResponse(format!("discovery: {e}")))?;
323 if doc.issuer != self.issuer {
324 return Err(ImError::BadResponse(
325 "discovery names another issuer".into(),
326 ));
327 }
328 let doc = Arc::new(doc);
329 *slot = Some((Instant::now(), doc.clone()));
330 Ok(doc)
331 }
332
333 /// The key set to check a token against. A fresh cached set is used as it is. An expired one is
334 /// fetched again, and when that fails the cached set is kept and used (contracts.md 2.2). With
335 /// `refetch_unknown` set, a token names a key that is not in the set, so it is fetched again once
336 /// [`UNKNOWN_KEY_REFETCH`] has passed since the last attempt.
337 async fn key_set(&self, refetch_unknown: bool) -> ImResult<Arc<KeySet>> {
338 if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? {
339 return Ok(keys);
340 }
341 // One fetch at a time. The cache lock is not held here, so a slow `im` stalls only the callers
342 // that need a fetch, never a caller that a cached set can answer. A caller that waited may find
343 // the set refreshed by the one before it.
344 let _single_flight = self.refresh.lock().await;
345 if let Some(keys) = self.keys_without_fetch(refetch_unknown).await? {
346 return Ok(keys);
347 }
348 // Only a refetch for an unknown key or a failure starts the gap. A scheduled fetch does not, so the
349 // first token signed by a newly rotated key is verified at once.
350 if refetch_unknown {
351 self.keys.lock().await.last_fetch = Some(Instant::now());
352 }
353 let fetched = self.fetch_keys().await;
354 let mut cache = self.keys.lock().await;
355 if fetched.is_err() {
356 cache.last_fetch = Some(Instant::now());
357 }
358 match fetched {
359 Ok(keys) => {
360 cache.current = Some((Instant::now(), keys.clone()));
361 Ok(keys)
362 }
363 Err(error) => match &cache.current {
364 Some((_, keys)) => {
365 tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys");
366 Ok(keys.clone())
367 }
368 None => Err(error),
369 },
370 }
371 }
372
373 /// The cached key set, when no fetch is due: it is fresh, or a fetch was attempted less than
374 /// [`UNKNOWN_KEY_REFETCH`] ago (see `last_fetch`). `None` when a fetch is due. With no cached set and a fetch attempted
375 /// that recently, the answer is an error at once, without a network call.
376 async fn keys_without_fetch(&self, refetch_unknown: bool) -> ImResult<Option<Arc<KeySet>>> {
377 let cache = self.keys.lock().await;
378 let attempted_recently = cache
379 .last_fetch
380 .is_some_and(|at| at.elapsed() < UNKNOWN_KEY_REFETCH);
381 match &cache.current {
382 Some((at, keys)) => {
383 let fresh = at.elapsed() < KEYS_TTL && !refetch_unknown;
384 Ok((fresh || attempted_recently).then(|| keys.clone()))
385 }
386 None if attempted_recently => Err(ImError::Unavailable(
387 "the key set has not been fetched yet".into(),
388 )),
389 None => Ok(None),
390 }
391 }
392
393 /// Fetches the key set from `im`'s JWKS endpoint. Called only under `refresh`.
394 async fn fetch_keys(&self) -> ImResult<Arc<KeySet>> {
395 let discovery = self.discovery().await?;
396 let response = self
397 .http
398 .get(&discovery.jwks_uri)
399 .send()
400 .await
401 .map_err(unavailable)?;
402 if !response.status().is_success() {
403 return Err(ImError::Unavailable(format!(
404 "the key set answered {}",
405 response.status().as_u16()
406 )));
407 }
408 let body = read_limited(response, MAX_RESPONSE_BYTES).await?;
409 Ok(Arc::new(KeySet::from_jwks(&body)?))
410 }
411
412 /// Runs a check against the cached keys. A token that names an unknown key gets one more try
413 /// against a fresh key set, which the rate bound may refuse.
414 async fn with_keys<T>(&self, check: impl Fn(&KeySet) -> ImResult<T>) -> ImResult<T> {
415 let keys = self.key_set(false).await?;
416 match check(&keys) {
417 Err(ImError::UnknownKey) => {
418 let keys = self.key_set(true).await?;
419 match check(&keys) {
420 Err(ImError::UnknownKey) => {
421 Err(ImError::Rejected("the signing key is not published".into()))
422 }
423 other => other,
424 }
425 }
426 other => other,
427 }
428 }
429
430 /// The authorization URL for a sign-in, with PKCE (S256) and the state and nonce of this flight.
431 pub async fn authorize_url(
432 &self,
433 state: &str,
434 nonce: &str,
435 challenge: &str,
436 ) -> ImResult<String> {
437 let discovery = self.discovery().await?;
438 let mut url = reqwest::Url::parse(&discovery.authorization_endpoint)
439 .map_err(|e| ImError::BadResponse(format!("authorization endpoint: {e}")))?;
440 url.query_pairs_mut()
441 .append_pair("response_type", "code")
442 .append_pair("client_id", &self.client_id)
443 .append_pair("redirect_uri", &self.redirect_uri)
444 .append_pair("scope", SIGN_IN_SCOPE)
445 .append_pair("state", state)
446 .append_pair("nonce", nonce)
447 .append_pair("code_challenge", challenge)
448 .append_pair("code_challenge_method", "S256");
449 Ok(url.into())
450 }
451
452 /// The end-session URL of RP-initiated logout (contracts.md 2.5). `id_token_hint` is omitted when
453 /// the session has no stored ID token.
454 pub async fn end_session_url(
455 &self,
456 id_token_hint: Option<&str>,
457 state: &str,
458 ) -> ImResult<String> {
459 let discovery = self.discovery().await?;
460 let endpoint = discovery
461 .end_session_endpoint
462 .as_deref()
463 .ok_or_else(|| ImError::BadResponse("no end_session_endpoint".into()))?;
464 let mut url = reqwest::Url::parse(endpoint)
465 .map_err(|e| ImError::BadResponse(format!("end_session endpoint: {e}")))?;
466 {
467 let mut query = url.query_pairs_mut();
468 if let Some(hint) = id_token_hint {
469 query.append_pair("id_token_hint", hint);
470 }
471 query
472 .append_pair("post_logout_redirect_uri", &self.post_logout_uri)
473 .append_pair("state", state);
474 }
475 Ok(url.into())
476 }
477
478 /// Exchanges an authorization code for tokens (contracts.md 2.3, step 3).
479 pub async fn exchange_code(&self, code: &str, verifier: &str) -> ImResult<TokenResponse> {
480 let discovery = self.discovery().await?;
481 let form = [
482 ("grant_type", "authorization_code"),
483 ("code", code),
484 ("redirect_uri", self.redirect_uri.as_str()),
485 ("code_verifier", verifier),
486 ];
487 self.post_token(&discovery.token_endpoint, &form).await
488 }
489
490 /// The client-credentials token for the directory at `im` (`aud = im`, `directory.read`).
491 pub async fn service_token(&self) -> ImResult<String> {
492 self.client_token(IM_AUDIENCE, DIRECTORY_SCOPE).await
493 }
494
495 /// A client-credentials token for `scope` at the family service `audience`, cached until 60 seconds
496 /// before it expires (contracts.md 2.6). Each `(audience, scope)` pair has its own cache entry, so the
497 /// token for `in` never replaces the one for `im`.
498 pub async fn client_token(&self, audience: &str, scope: &str) -> ImResult<String> {
499 let key = (audience.to_owned(), scope.to_owned());
500 let mut slots = self.service.lock().await;
501 if let Some((until, token)) = slots.get(&key)
502 && Instant::now() < *until
503 {
504 return Ok(token.clone());
505 }
506 let discovery = self.discovery().await?;
507 let form = [
508 ("grant_type", "client_credentials"),
509 ("scope", scope),
510 ("audience", audience),
511 ];
512 let response = self.post_token(&discovery.token_endpoint, &form).await?;
513 let token = response
514 .access_token
515 .filter(|token| !token.is_empty())
516 .ok_or_else(|| ImError::BadResponse("the token answer has no access token".into()))?;
517 let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0));
518 let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN);
519 slots.insert(key, (until, token.clone()));
520 Ok(token)
521 }
522
523 /// Posts a form to the token endpoint with `client_secret_basic` and no redirect following.
524 async fn post_token(&self, url: &str, form: &[(&str, &str)]) -> ImResult<TokenResponse> {
525 let response = self
526 .http
527 .post(url)
528 .basic_auth(&self.client_id, Some(&self.client_secret))
529 .form(form)
530 .send()
531 .await
532 .map_err(unavailable)?;
533 let status = response.status();
534 let body = read_limited(response, MAX_RESPONSE_BYTES).await?;
535 if !status.is_success() {
536 // The body of an error answer is not logged: it can echo request values.
537 return Err(ImError::Rejected(format!(
538 "the token endpoint answered {}",
539 status.as_u16()
540 )));
541 }
542 serde_json::from_slice(&body)
543 .map_err(|e| ImError::BadResponse(format!("the token answer: {e}")))
544 }
545
546 /// Verifies an ID token against the current keys, and the nonce of the flight.
547 pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult<IdClaims> {
548 check_shape(token)?;
549 let now = unix_now();
550 self.with_keys(|keys| {
551 verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now)
552 })
553 .await
554 }
555
556 /// Verifies a back-channel logout token against the current keys.
557 pub async fn verify_logout_token(&self, token: &str) -> ImResult<LogoutClaims> {
558 check_shape(token)?;
559 let now = unix_now();
560 self.with_keys(|keys| verify_logout_token(keys, &self.issuer, &self.client_id, token, now))
561 .await
562 }
563}
564
565/// The PKCE code challenge of a verifier: base64url of the SHA-256 of the verifier (RFC 7636, S256).
566pub fn pkce_challenge(verifier: &str) -> String {
567 BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
568}
569
570/// The current time as seconds since the Unix epoch. Zero if the clock is before it.
571pub fn unix_now() -> u64 {
572 SystemTime::now()
573 .duration_since(UNIX_EPOCH)
574 .map_or(0, |d| d.as_secs())
575}
576
577/// Verifies an ID token (contracts.md 2.3, step 4). `nonce` must equal the nonce of this flight.
578pub fn verify_id_token(
579 keys: &KeySet,
580 issuer: &str,
581 client_id: &str,
582 token: &str,
583 nonce: &str,
584 now: u64,
585) -> ImResult<IdClaims> {
586 let claims = verify_signature(keys, issuer, client_id, token)?;
587 check_iat(&claims, now)?;
588 let sent = str_claim(&claims, "nonce")
589 .ok_or_else(|| ImError::Rejected("the nonce claim is missing".into()))?;
590 if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) {
591 return Err(ImError::Rejected(
592 "the nonce does not match this sign-in".into(),
593 ));
594 }
595 let id: IdClaims = serde_json::from_value(Value::Object(claims))
596 .map_err(|e| ImError::Rejected(format!("the claims are malformed: {e}")))?;
597 if id.sub.is_empty() || id.sub.len() > 64 {
598 return Err(ImError::Rejected("the subject is not a member id".into()));
599 }
600 Ok(id)
601}
602
603/// Verifies a back-channel logout token (OIDC Back-Channel Logout 1.0, contracts.md 2.5). It must
604/// carry the back-channel event, must not carry a nonce, must carry a `jti`, and must name a `sid` or
605/// a `sub`.
606pub fn verify_logout_token(
607 keys: &KeySet,
608 issuer: &str,
609 client_id: &str,
610 token: &str,
611 now: u64,
612) -> ImResult<LogoutClaims> {
613 let claims = verify_signature(keys, issuer, client_id, token)?;
614 check_iat(&claims, now)?;
615 if claims.contains_key("nonce") {
616 return Err(ImError::Rejected(
617 "a logout token must not carry a nonce".into(),
618 ));
619 }
620 let events = claims
621 .get("events")
622 .and_then(Value::as_object)
623 .ok_or_else(|| ImError::Rejected("the events claim is missing".into()))?;
624 if !events.contains_key(BACKCHANNEL_EVENT) {
625 return Err(ImError::Rejected(
626 "the event is not back-channel logout".into(),
627 ));
628 }
629 let jti = str_claim(&claims, "jti")
630 .ok_or_else(|| ImError::Rejected("the jti claim is missing".into()))?;
631 let sid = str_claim(&claims, "sid");
632 let sub = str_claim(&claims, "sub");
633 if sid.is_none() && sub.is_none() {
634 return Err(ImError::Rejected(
635 "the token names neither sid nor sub".into(),
636 ));
637 }
638 Ok(LogoutClaims { jti, sid, sub })
639}
640
641/// Refuses a token that cannot verify before any key set is fetched: three segments, a header that
642/// names EdDSA, and a `kid`. A hostile token therefore costs no call to `im`.
643fn check_shape(token: &str) -> ImResult<()> {
644 if token.split('.').count() != 3 {
645 return Err(ImError::Rejected(
646 "the token does not have three segments".into(),
647 ));
648 }
649 let header = decode_header(token)
650 .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?;
651 if header.alg != Algorithm::EdDSA {
652 return Err(ImError::Rejected(format!(
653 "the algorithm {:?} is not accepted",
654 header.alg
655 )));
656 }
657 if header.kid.is_none() {
658 return Err(ImError::Rejected("the header has no kid".into()));
659 }
660 Ok(())
661}
662
663/// Checks the header, finds the key, and verifies the signature and the registered claims. Returns
664/// the claims as a map, for the token-specific checks.
665fn verify_signature(
666 keys: &KeySet,
667 issuer: &str,
668 client_id: &str,
669 token: &str,
670) -> ImResult<Map<String, Value>> {
671 // The algorithm is read from the header and refused unless it is EdDSA, before any key is used.
672 let header = decode_header(token)
673 .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?;
674 if header.alg != Algorithm::EdDSA {
675 return Err(ImError::Rejected(format!(
676 "the algorithm {:?} is not accepted",
677 header.alg
678 )));
679 }
680 let kid = header
681 .kid
682 .as_deref()
683 .ok_or_else(|| ImError::Rejected("the header has no kid".into()))?;
684 let key = keys.get(kid).ok_or(ImError::UnknownKey)?;
685 let mut validation = Validation::new(Algorithm::EdDSA);
686 validation.leeway = LEEWAY_SECS;
687 validation.validate_nbf = true;
688 validation.set_issuer(&[issuer]);
689 validation.set_audience(&[client_id]);
690 validation.set_required_spec_claims(&["exp", "iss", "aud"]);
691 let data = decode::<Map<String, Value>>(token, key, &validation)
692 .map_err(|e| ImError::Rejected(e.to_string()))?;
693 // `set_audience` accepts any member of an array, so the exact rule is applied here.
694 if !audience_is(data.claims.get("aud"), client_id) {
695 return Err(ImError::Rejected(
696 "the aud claim is not the client id".into(),
697 ));
698 }
699 Ok(data.claims)
700}
701
702/// Whether `aud` names `expected`. A string must equal it; an array must hold exactly that one value.
703/// Contracts require an exact `client_id`, so a longer audience list is refused.
704fn audience_is(aud: Option<&Value>, expected: &str) -> bool {
705 match aud {
706 Some(Value::String(single)) => single == expected,
707 Some(Value::Array(items)) => {
708 items.len() == 1 && items.first().and_then(Value::as_str) == Some(expected)
709 }
710 _ => false,
711 }
712}
713
714/// `iat` must be present and not more than [`MAX_IAT_AHEAD_SECS`] ahead of `now`.
715fn check_iat(claims: &Map<String, Value>, now: u64) -> ImResult<()> {
716 let iat = claims
717 .get("iat")
718 .and_then(Value::as_u64)
719 .ok_or_else(|| ImError::Rejected("the iat claim is missing".into()))?;
720 if iat > now.saturating_add(MAX_IAT_AHEAD_SECS) {
721 return Err(ImError::Rejected("the iat claim is in the future".into()));
722 }
723 Ok(())
724}
725
726/// A string claim that is present and not empty.
727fn str_claim(claims: &Map<String, Value>, name: &str) -> Option<String> {
728 claims
729 .get(name)
730 .and_then(Value::as_str)
731 .filter(|s| !s.is_empty())
732 .map(str::to_owned)
733}
734
735fn unavailable(error: reqwest::Error) -> ImError {
736 ImError::Unavailable(error.without_url().to_string())
737}
738
739/// Reads a response body, refusing one larger than `limit` bytes. The check runs while the body is
740/// read, so a server that lies about its length cannot make iz hold more than `limit`.
741pub async fn read_limited(response: reqwest::Response, limit: usize) -> ImResult<Vec<u8>> {
742 let too_large = || ImError::BadResponse("the answer is too large".into());
743 if response
744 .content_length()
745 .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX))
746 {
747 return Err(too_large());
748 }
749 let mut body = Vec::new();
750 let mut chunks = response.bytes_stream();
751 while let Some(chunk) = chunks.next().await {
752 let chunk = chunk.map_err(unavailable)?;
753 if body.len() + chunk.len() > limit {
754 return Err(too_large());
755 }
756 body.extend_from_slice(&chunk);
757 }
758 Ok(body)
759}
760
761/// Reads the client secret from `path`. The file must not be readable by group or others, the same
762/// rule as the instance key. The value is trimmed and must not be empty.
763pub fn read_client_secret(path: &Path) -> iz_core::Result<String> {
764 #[cfg(unix)]
765 {
766 use std::os::unix::fs::PermissionsExt;
767 let mode = std::fs::metadata(path)?.permissions().mode();
768 if mode & 0o077 != 0 {
769 return Err(iz_core::Error::Config(format!(
770 "client secret {} is group or world accessible (mode {:o}); expected 0600",
771 path.display(),
772 mode & 0o777
773 )));
774 }
775 }
776 let text = std::fs::read_to_string(path)?;
777 let secret = text.trim().to_owned();
778 if secret.is_empty() {
779 return Err(iz_core::Error::Config(format!(
780 "client secret {} is empty",
781 path.display()
782 )));
783 }
784 Ok(secret)
785}
786
787#[cfg(test)]
788pub(crate) mod test_support {
789 //! Ed25519 keys and signed tokens for the tests. The keys are generated for each test, so no key
790 //! material lives in the repository.
791
792 use aws_lc_rs::rand::SystemRandom;
793 use aws_lc_rs::signature::{Ed25519KeyPair, KeyPair};
794 use jsonwebtoken::{EncodingKey, Header, encode};
795 use serde_json::{Value, json};
796
797 use super::KeySet;
798
799 /// The issuer used by the tests.
800 pub const ISSUER: &str = "https://im.example.com";
801 /// The client id used by the tests.
802 pub const CLIENT_ID: &str = "iz";
803
804 /// A signing key with the key set that verifies it, under the key id `k1`.
805 pub struct Signer {
806 pub keys: KeySet,
807 encoding: EncodingKey,
808 }
809
810 impl Signer {
811 pub fn generate() -> Signer {
812 let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).expect("keygen");
813 let pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).expect("pkcs8");
814 let x = base64::Engine::encode(
815 &base64::prelude::BASE64_URL_SAFE_NO_PAD,
816 pair.public_key().as_ref(),
817 );
818 let jwks = json!({"keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": "k1", "use": "sig", "alg": "EdDSA"}]});
819 Signer {
820 keys: KeySet::from_jwks(jwks.to_string().as_bytes()).expect("jwks"),
821 encoding: EncodingKey::from_ed_der(pkcs8.as_ref()),
822 }
823 }
824
825 /// Signs `claims` as an EdDSA token with kid `k1`.
826 pub fn sign(&self, claims: &Value) -> String {
827 self.sign_with_kid("k1", claims)
828 }
829
830 /// Signs `claims` as an EdDSA token with the given kid.
831 pub fn sign_with_kid(&self, kid: &str, claims: &Value) -> String {
832 let mut header = Header::new(jsonwebtoken::Algorithm::EdDSA);
833 header.kid = Some(kid.into());
834 encode(&header, claims, &self.encoding).expect("sign")
835 }
836 }
837
838 /// Claims of an ID token that passes every check at time `now`, with `nonce`.
839 pub fn id_claims(now: u64, nonce: &str) -> Value {
840 json!({
841 "iss": ISSUER, "aud": CLIENT_ID, "sub": "01JMEMBER0000000000000000A",
842 "exp": now + 600, "iat": now, "auth_time": now, "nonce": nonce,
843 "sid": "sid-1", "email": "ada@example.com", "email_verified": true,
844 "name": "Ada", "admin": false, "locale": "en", "zoneinfo": "Europe/Istanbul",
845 "picture_version": 1
846 })
847 }
848
849 /// Claims of a back-channel logout token that passes every check at time `now`.
850 pub fn logout_claims(now: u64, jti: &str) -> Value {
851 json!({
852 "iss": ISSUER, "aud": CLIENT_ID, "iat": now, "exp": now + 120, "jti": jti,
853 "sid": "sid-1", "sub": "01JMEMBER0000000000000000A",
854 "events": {"http://schemas.openid.net/event/backchannel-logout": {}}
855 })
856 }
857}
858
859#[cfg(test)]
860mod tests {
861 use super::test_support::{CLIENT_ID, ISSUER, Signer, id_claims, logout_claims};
862 use super::*;
863 use serde_json::json;
864
865 const NOW: u64 = 1_800_000_000;
866
867 fn unsigned(header: &str, payload: &Value) -> String {
868 let h = BASE64_URL_SAFE_NO_PAD.encode(header);
869 let p = BASE64_URL_SAFE_NO_PAD.encode(payload.to_string());
870 format!("{h}.{p}.")
871 }
872
873 #[test]
874 fn pkce_challenge_matches_the_rfc_7636_example() {
875 assert_eq!(
876 pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
877 "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
878 );
879 }
880
881 #[test]
882 fn a_well_formed_id_token_is_accepted() {
883 let signer = Signer::generate();
884 let token = signer.sign(&id_claims(NOW, "n-1"));
885 let id = verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW).unwrap();
886 assert_eq!(id.sub, "01JMEMBER0000000000000000A");
887 assert_eq!(id.sid.as_deref(), Some("sid-1"));
888 assert_eq!(id.picture_version, 1);
889 }
890
891 #[test]
892 fn an_unsigned_alg_none_token_is_refused() {
893 let signer = Signer::generate();
894 let token = unsigned(r#"{"alg":"none","kid":"k1"}"#, &id_claims(NOW, "n-1"));
895 assert!(matches!(
896 verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW),
897 Err(ImError::Rejected(_))
898 ));
899 }
900
901 #[test]
902 fn a_token_for_another_audience_is_refused() {
903 let signer = Signer::generate();
904 let mut claims = id_claims(NOW, "n-1");
905 claims["aud"] = json!("in");
906 let token = signer.sign(&claims);
907 assert!(matches!(
908 verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW),
909 Err(ImError::Rejected(_))
910 ));
911 }
912
913 #[test]
914 fn an_expired_token_is_refused_but_leeway_is_allowed() {
915 // `exp` is checked against the system clock, so this test uses the real current time.
916 let now = unix_now();
917 let signer = Signer::generate();
918 let mut claims = id_claims(now, "n-1");
919 claims["exp"] = json!(now - 3600);
920 let token = signer.sign(&claims);
921 assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_err());
922 let mut claims = id_claims(now, "n-1");
923 claims["exp"] = json!(now - 30);
924 let token = signer.sign(&claims);
925 assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_ok());
926 }
927
928 #[test]
929 fn a_wrong_nonce_is_refused() {
930 let signer = Signer::generate();
931 let token = signer.sign(&id_claims(NOW, "n-1"));
932 assert!(matches!(
933 verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-2", NOW),
934 Err(ImError::Rejected(_))
935 ));
936 }
937
938 #[test]
939 fn an_unknown_key_id_asks_for_a_refetch() {
940 let signer = Signer::generate();
941 let token = signer.sign_with_kid("k2", &id_claims(NOW, "n-1"));
942 assert!(matches!(
943 verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW),
944 Err(ImError::UnknownKey)
945 ));
946 }
947
948 #[test]
949 fn a_logout_token_needs_the_event_and_no_nonce() {
950 let signer = Signer::generate();
951 let good = signer.sign(&logout_claims(NOW, "j-1"));
952 let claims = verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &good, NOW).unwrap();
953 assert_eq!(claims.jti, "j-1");
954 assert_eq!(claims.sid.as_deref(), Some("sid-1"));
955
956 let mut with_nonce = logout_claims(NOW, "j-2");
957 with_nonce["nonce"] = json!("n");
958 let token = signer.sign(&with_nonce);
959 assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err());
960
961 let mut no_event = logout_claims(NOW, "j-3");
962 no_event["events"] = json!({});
963 let token = signer.sign(&no_event);
964 assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err());
965 }
966
967 #[test]
968 fn the_key_set_keeps_only_ed25519_keys_with_a_kid() {
969 let set = KeySet::from_jwks(
970 br#"{"keys":[{"kty":"RSA","kid":"r1","n":"x","e":"AQAB"},{"kty":"OKP","crv":"Ed25519","kid":"no-x"}]}"#,
971 )
972 .unwrap();
973 assert!(set.keys.is_empty());
974 }
975}