Skip to main content

beyondigital_auth_sdk/
jwt.rs

1//! JWT verification via JWKS with TTL cache + bounded kid-miss refresh.
2//! Mirrors `src/crypto/jwt.rs` (RS256, exp/iat/type, kid header), the
3//! `ValidationPolicy` surface from [`crate::policy`], and the RFC 9068 §2.1
4//! `at+jwt` JOSE typ check auth_service mints on every access token (WP-03b).
5//!
6//! [`MultiIssuerVerifier`] (R-21.2) is the engine: an explicit issuer
7//! allow-list is checked against the token's `iss` BEFORE any JWKS fetch,
8//! every listed issuer has its own JWKS cache, the verification algorithm
9//! comes from the key (never the token header), and a kid miss triggers one
10//! refresh that is rate-limited per issuer, so a flood of unknown kids (or of
11//! tokens from unlisted issuers) cannot drive unbounded fetches. [`Verifier`]
12//! is the single-issuer wrapper over it and keeps the original API.
13use std::collections::HashMap;
14use std::future::Future;
15use std::pin::Pin;
16use std::sync::atomic::{AtomicU64, Ordering};
17use std::sync::Arc;
18use std::sync::Mutex as StdMutex;
19use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
20
21use base64::Engine as _;
22use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
23use serde::{Deserialize, Serialize};
24use serde_json::{Map, Value};
25use tokio::sync::{Mutex, RwLock};
26
27use crate::error::AuthError;
28use crate::logout::{
29    check_logout_claims, is_logout_typ, LogoutFailure, LogoutToken,
30    DEFAULT_LOGOUT_TOKEN_MAX_AGE_SECONDS,
31};
32use crate::policy::{validate_claims, validate_typ_header, ValidationPolicy};
33
34/// Default minimum interval between JWKS fetch attempts, kept per issuer.
35/// Bounds the kid-miss refetch path so a forged `kid` cannot drive a fetch
36/// loop — mirrors jose's `cooldownDuration` contract. `Duration::ZERO`
37/// disables it (tests, and verifiers pinned to a static JWKS).
38pub const DEFAULT_MIN_FETCH_INTERVAL: Duration = Duration::from_secs(10);
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct Claims {
42    pub sub: String,
43    pub iss: Option<String>,
44    pub aud: Option<serde_json::Value>,
45    pub exp: i64,
46    pub iat: i64,
47    #[serde(rename = "type")]
48    pub typ: String,
49    pub jti: Option<String>,
50    pub client_id: Option<String>,
51    pub session_id: Option<String>,
52    pub central_user_id: Option<String>,
53    pub auth_user_id: Option<String>,
54    pub scopes: Option<Vec<String>>,
55    pub scope: Option<String>,
56    pub app: Option<String>,
57    pub email: Option<String>,
58    pub token_version: Option<i64>,
59    pub permissions_version: Option<i64>,
60    pub is_system_admin: Option<bool>,
61    pub identity_class: Option<String>,
62}
63
64/// Verified identity from an access token.
65///
66/// `id` is the token's `sub` — a **pairwise sector subject** for clients on
67/// the RFC 9068 profile (WP-03b), not the account's global `users.id`. Never
68/// use it to correlate identities across clients; `auth_user_id` (present
69/// only under the `legacy_global_id` compat adapter) is the legacy global
70/// shape, and `central_identity_id()` keeps answering it for compat.
71#[derive(Debug, Clone)]
72pub struct CurrentUser {
73    pub id: String,
74    /// The verified token's issuer: the allow-listed issuer that signed it.
75    pub issuer: Option<String>,
76    pub email: String,
77    pub scopes: Vec<String>,
78    pub firm_id: Option<String>,
79    pub auth_user_id: Option<String>,
80    pub session_id: Option<String>,
81    pub app: Option<String>,
82    pub token_version: i64,
83    pub permissions_version: i64,
84    pub is_system_admin: bool,
85    pub identity_class: Option<String>,
86}
87
88impl CurrentUser {
89    pub fn central_identity_id(&self) -> &str {
90        self.auth_user_id.as_deref().unwrap_or(&self.id)
91    }
92    pub fn has_scope(&self, scope: &str) -> bool {
93        let requires_admin = scope == "admin:*" || scope.starts_with("admin:");
94        if requires_admin && !self.is_system_admin {
95            return false;
96        }
97        if (self.scopes.contains(&"admin:*".to_string()) && self.is_system_admin)
98            || self.scopes.contains(&scope.to_string())
99        {
100            return true;
101        }
102        if let Some((ns, _)) = scope.split_once(':') {
103            return self.scopes.contains(&format!("{ns}:*"));
104        }
105        false
106    }
107    pub fn is_admin(&self) -> bool {
108        self.scopes.contains(&"admin:*".to_string()) && self.is_system_admin
109    }
110}
111
112fn claims_to_user(map: Map<String, Value>) -> Result<CurrentUser, AuthError> {
113    let c: Claims = serde_json::from_value(Value::Object(map))
114        .map_err(|e| AuthError::jwt(e.to_string(), "invalid"))?;
115    if c.sub.is_empty() {
116        return Err(AuthError::jwt("Missing sub", "invalid"));
117    }
118    let scopes = c.scopes.clone().unwrap_or_else(|| {
119        c.scope
120            .as_deref()
121            .unwrap_or("")
122            .split_whitespace()
123            .map(String::from)
124            .collect()
125    });
126    let is_system_admin =
127        c.is_system_admin.unwrap_or(false) || c.identity_class.as_deref() == Some("system_admin");
128    Ok(CurrentUser {
129        id: c.sub.clone(),
130        issuer: c.iss.clone().filter(|iss| !iss.is_empty()),
131        email: c.email.clone().unwrap_or_default(),
132        scopes,
133        firm_id: None,
134        auth_user_id: c.central_user_id.clone().or(c.auth_user_id.clone()),
135        session_id: c.session_id.clone(),
136        app: c.app.clone(),
137        token_version: c.token_version.unwrap_or(0),
138        permissions_version: c.permissions_version.unwrap_or(0),
139        is_system_admin,
140        identity_class: c.identity_class.clone(),
141    })
142}
143
144fn normalize_issuer(url: &str) -> String {
145    url.trim_end_matches('/').to_string()
146}
147
148/// One allow-listed issuer. `jwks_uri` overrides the default
149/// `<issuer>/.well-known/jwks.json` (set it from discovery).
150#[derive(Debug, Clone)]
151pub struct IssuerConfig {
152    pub issuer_url: String,
153    pub jwks_uri: Option<String>,
154}
155
156impl IssuerConfig {
157    pub fn new(issuer_url: impl Into<String>) -> Self {
158        Self {
159            issuer_url: issuer_url.into(),
160            jwks_uri: None,
161        }
162    }
163    pub fn with_jwks_uri(mut self, uri: impl Into<String>) -> Self {
164        self.jwks_uri = Some(uri.into());
165        self
166    }
167}
168
169impl From<&str> for IssuerConfig {
170    fn from(issuer_url: &str) -> Self {
171        Self::new(issuer_url)
172    }
173}
174impl From<String> for IssuerConfig {
175    fn from(issuer_url: String) -> Self {
176        Self::new(issuer_url)
177    }
178}
179
180#[derive(Debug, Clone, Deserialize)]
181struct Jwks {
182    keys: Vec<Jwk>,
183}
184/// A JWKS entry. Only RSA keys are used, but every field is optional so a
185/// key of another type in the same set (EC, OKP) cannot make the whole
186/// document unparsable.
187#[derive(Debug, Clone, Deserialize)]
188struct Jwk {
189    kty: String,
190    #[serde(rename = "use")]
191    use_: Option<String>,
192    alg: Option<String>,
193    kid: Option<String>,
194    n: Option<String>,
195    e: Option<String>,
196}
197
198/// The algorithm a JWK dictates, or `None` when this SDK will not verify with
199/// it. Taken from the key (`kty`, and `alg` when the key declares one), never
200/// from a token header. auth_service signs RS256.
201fn key_algorithm(k: &Jwk) -> Option<Algorithm> {
202    if k.kty != "RSA" || k.use_.as_deref().is_some_and(|usage| usage != "sig") {
203        return None;
204    }
205    match k.alg.as_deref() {
206        None | Some("RS256") => Some(Algorithm::RS256),
207        Some(_) => None,
208    }
209}
210
211/// The JOSE name of an algorithm the verifier can hold a key for.
212fn algorithm_name(alg: Algorithm) -> &'static str {
213    match alg {
214        Algorithm::RS256 => "RS256",
215        _ => "unsupported",
216    }
217}
218
219/// A verification key together with the algorithm the KEY dictates.
220#[derive(Clone)]
221struct VerificationKey {
222    key: DecodingKey,
223    alg: Algorithm,
224}
225
226struct Cached {
227    fetched_at: Instant,
228    keys: HashMap<String, VerificationKey>,
229}
230
231/// Per-issuer JWKS state: its own cache, fetch-attempt clock and a lock that
232/// makes concurrent refreshes share one fetch.
233struct IssuerState {
234    issuer: String,
235    jwks_uri: Option<String>,
236    cache: RwLock<Option<Cached>>,
237    /// Time of the last fetch *attempt* (success or failure): the bound on
238    /// forced refreshes lives here so a failing JWKS can't be hammered either.
239    last_attempt: StdMutex<Option<Instant>>,
240    /// Serialises refreshes; waiters re-check `generation` once they hold it.
241    fetch_lock: Mutex<()>,
242    /// Bumped after every successful cache refresh.
243    generation: AtomicU64,
244}
245
246impl IssuerState {
247    fn new(issuer: String, jwks_uri: Option<String>) -> Self {
248        Self {
249            issuer,
250            jwks_uri,
251            cache: RwLock::new(None),
252            last_attempt: StdMutex::new(None),
253            fetch_lock: Mutex::new(()),
254            generation: AtomicU64::new(0),
255        }
256    }
257
258    fn jwks_uri_resolved(&self) -> String {
259        self.jwks_uri
260            .clone()
261            .unwrap_or_else(|| format!("{}/.well-known/jwks.json", self.issuer))
262    }
263}
264
265/// Kid-aware JWKS verifier over an explicit issuer allow-list. The production
266/// surface: `verify` enforces the RFC 9068 `at+jwt` profile, the issuer
267/// allow-list and the configured audience; `verify_claims` takes an explicit
268/// [`ValidationPolicy`] matching auth_service's `decode_with_policy` semantics
269/// exactly.
270pub struct MultiIssuerVerifier {
271    /// Allow-listed issuers by normalised URL.
272    issuers: HashMap<String, IssuerState>,
273    /// Configuration order of `issuers`.
274    order: Vec<String>,
275    /// Accepted audiences. Never empty after construction; a blank pin makes
276    /// `verify` fail closed (see [`MultiIssuerVerifier::new`]).
277    audience: Vec<String>,
278    ttl: Duration,
279    min_fetch_interval: Duration,
280    /// Tolerated clock difference when judging `exp` (and, for logout tokens, `nbf` and `iat`). Zero by default.
281    clock_skew: Duration,
282    /// RFC 9068 typ enforcement on `verify()`/`verify_with()`. Default on.
283    require_at_jwt: bool,
284    http: reqwest::Client,
285}
286
287impl MultiIssuerVerifier {
288    /// Pin the audience this resource server accepts, then list the trusted
289    /// issuers with [`with_issuer`](Self::with_issuer). Both pins are required
290    /// (WP-09c): a verifier with no audience pin would accept any token an
291    /// issuer ever signed, for any resource. The constructor is infallible, so
292    /// a blank audience or an empty allow-list makes `verify` fail closed with
293    /// a `jwt` error before any network call.
294    pub fn new(audience: impl Into<String>) -> Self {
295        let audience = audience.into();
296        Self {
297            issuers: HashMap::new(),
298            order: Vec::new(),
299            audience: if audience.trim().is_empty() {
300                Vec::new()
301            } else {
302                vec![audience]
303            },
304            ttl: Duration::from_secs(300),
305            min_fetch_interval: DEFAULT_MIN_FETCH_INTERVAL,
306            clock_skew: Duration::ZERO,
307            require_at_jwt: true,
308            http: reqwest::Client::builder()
309                .timeout(Duration::from_secs(10))
310                .build()
311                .unwrap_or_else(|_| reqwest::Client::new()),
312        }
313    }
314    /// Add an issuer to the allow-list (a URL or an [`IssuerConfig`]). Blank
315    /// URLs are ignored; trailing slashes are normalised; a repeated issuer
316    /// keeps its first JWKS URI unless it had none.
317    pub fn with_issuer(mut self, issuer: impl Into<IssuerConfig>) -> Self {
318        let IssuerConfig {
319            issuer_url,
320            jwks_uri,
321        } = issuer.into();
322        let issuer = normalize_issuer(&issuer_url);
323        if issuer.trim().is_empty() {
324            return self;
325        }
326        match self.issuers.get_mut(&issuer) {
327            Some(existing) => {
328                if existing.jwks_uri.is_none() {
329                    existing.jwks_uri = jwks_uri;
330                }
331            }
332            None => {
333                self.order.push(issuer.clone());
334                self.issuers
335                    .insert(issuer.clone(), IssuerState::new(issuer, jwks_uri));
336            }
337        }
338        self
339    }
340    /// Accept one more audience in addition to the one given to `new`. Blank
341    /// values are ignored.
342    pub fn with_audience(mut self, aud: impl Into<String>) -> Self {
343        let a = aud.into();
344        if !a.trim().is_empty() && !self.audience.contains(&a) {
345            self.audience.push(a);
346        }
347        self
348    }
349    /// Accept several more audiences. Blank values are ignored.
350    pub fn with_audiences(mut self, auds: Vec<String>) -> Self {
351        for aud in auds {
352            self = self.with_audience(aud);
353        }
354        self
355    }
356    pub fn with_ttl(mut self, ttl: Duration) -> Self {
357        self.ttl = ttl;
358        self
359    }
360    /// Minimum interval between JWKS fetches per issuer (the kid-miss DoS
361    /// bound). `Duration::ZERO` disables it — for tests and static-JWKS
362    /// fixtures.
363    pub fn with_min_fetch_interval(mut self, interval: Duration) -> Self {
364        self.min_fetch_interval = interval;
365        self
366    }
367    /// Compat window: accept access tokens without the `at+jwt` JOSE typ
368    /// (pre-WP-03b mints). Off by default — production consumers should
369    /// require the profile marker.
370    pub fn allow_legacy_typ(mut self) -> Self {
371        self.require_at_jwt = false;
372        self
373    }
374    /// Tolerate this much clock difference when judging expiry (and, for logout tokens, `nbf` and `iat`). Zero (strict)
375    /// by default; a few seconds is typical when clocks drift. Access-token expiry is judged in whole seconds, so a
376    /// sub-second skew rounds up to the next second there; logout tokens compare it exactly.
377    pub fn with_clock_skew(mut self, skew: Duration) -> Self {
378        self.clock_skew = skew;
379        self
380    }
381
382    /// The normalised issuer allow-list, in configuration order.
383    pub fn issuers(&self) -> Vec<String> {
384        self.order.clone()
385    }
386
387    async fn fetch_jwks(&self, state: &IssuerState) -> Result<Jwks, AuthError> {
388        let uri = state.jwks_uri_resolved();
389        let resp = self
390            .http
391            .get(&uri)
392            .send()
393            .await
394            .map_err(|e| AuthError::Network(e.to_string()))?;
395        if !resp.status().is_success() {
396            return Err(AuthError::Network(format!(
397                "JWKS fetch failed: {}",
398                resp.status()
399            )));
400        }
401        resp.json::<Jwks>()
402            .await
403            .map_err(|e| AuthError::Network(e.to_string()))
404    }
405
406    /// Whether a JWKS fetch may run now for this issuer: always the first
407    /// time; afterwards at most once per `min_fetch_interval`. This is the
408    /// "bounded refresh" — one refetch on a kid miss, never a per-request loop.
409    fn fetch_allowed(&self, state: &IssuerState) -> bool {
410        if self.min_fetch_interval.is_zero() {
411            return true;
412        }
413        match *state.last_attempt.lock().expect("last_attempt lock") {
414            None => true,
415            Some(at) => at.elapsed() >= self.min_fetch_interval,
416        }
417    }
418
419    /// Refresh one issuer's cache. `seen` is the generation observed before
420    /// the caller's cache lookup: if another caller refreshed since, that
421    /// refresh is reused instead of fetching again. Returns whether the cache
422    /// is newer than the caller's view; `false` means the bound denied a fetch.
423    async fn refresh(&self, state: &IssuerState, seen: u64) -> Result<bool, AuthError> {
424        let _flight = state.fetch_lock.lock().await;
425        if state.generation.load(Ordering::Acquire) != seen {
426            return Ok(true);
427        }
428        if !self.fetch_allowed(state) {
429            return Ok(false);
430        }
431        // Every attempt stamps `last_attempt`, so `fetch_allowed` bounds both
432        // success-driven and failure-driven refetches.
433        *state.last_attempt.lock().expect("last_attempt lock") = Some(Instant::now());
434        let jwks = self.fetch_jwks(state).await?;
435        let mut keys = HashMap::new();
436        for k in &jwks.keys {
437            let (Some(kid), Some(n), Some(e), Some(alg)) = (
438                k.kid.as_deref(),
439                k.n.as_deref(),
440                k.e.as_deref(),
441                key_algorithm(k),
442            ) else {
443                continue;
444            };
445            if kid.is_empty() {
446                continue;
447            }
448            if let Ok(pem) = crate::jwk::jwk_to_pem(n, e) {
449                if let Ok(key) = DecodingKey::from_rsa_pem(pem.as_bytes()) {
450                    keys.insert(kid.to_string(), VerificationKey { key, alg });
451                }
452            }
453        }
454        *state.cache.write().await = Some(Cached {
455            fetched_at: Instant::now(),
456            keys,
457        });
458        state.generation.fetch_add(1, Ordering::Release);
459        Ok(true)
460    }
461
462    async fn cache_stale(&self, state: &IssuerState) -> bool {
463        match &*state.cache.read().await {
464            None => true,
465            Some(c) => c.fetched_at.elapsed() > self.ttl,
466        }
467    }
468
469    /// `Ok(key)` on a hit; `Err(true)` when the cache has keys but not this
470    /// kid, `Err(false)` when it has none.
471    async fn lookup(&self, state: &IssuerState, kid: &str) -> Result<VerificationKey, bool> {
472        let g = state.cache.read().await;
473        let Some(c) = &*g else { return Err(false) };
474        let hit = if !kid.is_empty() {
475            c.keys.get(kid)
476        } else if c.keys.len() == 1 {
477            // Tolerate a missing kid on a single-key JWKS (pre-kid mints).
478            c.keys.values().next()
479        } else {
480            None
481        };
482        hit.cloned().ok_or(!c.keys.is_empty())
483    }
484
485    /// Verification key for `kid` from this issuer's JWKS: cached key, else
486    /// exactly one bounded refresh, then fail `kid_mismatch`.
487    async fn key_for_kid(
488        &self,
489        state: &IssuerState,
490        kid: &str,
491    ) -> Result<VerificationKey, AuthError> {
492        let seen = state.generation.load(Ordering::Acquire);
493        // `refreshed`: this call already ran (or reused) a refresh, so a miss
494        // now is definitive; refetching again would double the cost of one miss.
495        let mut refreshed = false;
496        if self.cache_stale(state).await {
497            // A denied fetch (recent attempt) serves the stale/empty cache.
498            refreshed = self.refresh(state, seen).await?;
499        }
500        let mut miss = match self.lookup(state, kid).await {
501            Ok(key) => return Ok(key),
502            Err(has_keys) => has_keys,
503        };
504        if !refreshed {
505            if !self.refresh(state, seen).await? {
506                return Err(AuthError::jwt(
507                    format!("Unknown kid: {kid} (JWKS refresh bounded)"),
508                    "kid_mismatch",
509                ));
510            }
511            miss = match self.lookup(state, kid).await {
512                Ok(key) => return Ok(key),
513                Err(has_keys) => has_keys,
514            };
515        }
516        Err(if !miss {
517            AuthError::jwt("No RSA signing key in JWKS", "missing_key")
518        } else if kid.is_empty() {
519            AuthError::jwt("missing kid in a multi-key JWKS", "kid_mismatch")
520        } else {
521            AuthError::jwt(format!("Unknown kid: {kid}"), "kid_mismatch")
522        })
523    }
524
525    fn decode_claims(
526        &self,
527        token: &str,
528        key: &VerificationKey,
529    ) -> Result<Map<String, Value>, AuthError> {
530        // The key's algorithm, not the token header's: a header naming any
531        // other algorithm is refused.
532        let mut validation = Validation::new(key.alg);
533        validation.validate_aud = false; // iss/aud run through ValidationPolicy
534        validation.validate_exp = true;
535        validation.required_spec_claims.insert("exp".to_string());
536        validation.leeway = leeway_seconds(self.clock_skew);
537        decode::<Map<String, Value>>(token, &key.key, &validation)
538            .map(|d| d.claims)
539            .map_err(|e| {
540                let msg = e.to_string();
541                if msg.contains("ExpiredSignature") || msg.to_lowercase().contains("expired") {
542                    AuthError::jwt(msg, "expired")
543                } else if msg.contains("InvalidIssuer") {
544                    AuthError::jwt(msg, "issuer_mismatch")
545                } else {
546                    AuthError::jwt(msg, "invalid")
547                }
548            })
549    }
550
551    /// Pick the issuer state for a token BEFORE any network call. `iss` is
552    /// read from the still-unverified payload purely to route and to refuse;
553    /// it is trusted only after the signature verifies against that issuer's
554    /// keys.
555    fn route(&self, token: &str, policy: &ValidationPolicy) -> Result<&IssuerState, AuthError> {
556        let payload = token
557            .split('.')
558            .nth(1)
559            .ok_or_else(|| AuthError::jwt("Invalid token payload", "invalid"))?;
560        let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
561            .decode(payload.trim_end_matches('='))
562            .map_err(|e| AuthError::jwt(format!("Invalid token payload: {e}"), "invalid"))?;
563        let unverified: Value = serde_json::from_slice(&bytes)
564            .map_err(|e| AuthError::jwt(format!("Invalid token payload: {e}"), "invalid"))?;
565        match unverified.get("iss") {
566            None | Some(Value::Null) => {
567                // No iss to route on. With exactly one configured issuer the
568                // token can only be that issuer's; the policy decides after the
569                // signature check (an issuer-pinned policy still rejects it).
570                // With several, refuse.
571                if self.order.len() == 1 {
572                    return Ok(&self.issuers[&self.order[0]]);
573                }
574                Err(AuthError::jwt(
575                    "token has no iss claim to select an allow-listed issuer",
576                    "issuer_mismatch",
577                ))
578            }
579            Some(iss) => {
580                let state = iss.as_str().and_then(|iss| self.issuers.get(iss));
581                match state {
582                    Some(state)
583                        if policy.trusted_issuers.is_empty()
584                            || policy.trusted_issuers.contains(&state.issuer) =>
585                    {
586                        Ok(state)
587                    }
588                    _ => Err(AuthError::jwt(
589                        format!("untrusted issuer {iss}"),
590                        "issuer_mismatch",
591                    )),
592                }
593            }
594        }
595    }
596
597    /// Verify `token` against `policy`: JOSE typ check (when the policy's
598    /// purpose carries `at+jwt`), issuer allow-list (before any fetch),
599    /// kid-pinned signature with the key's own algorithm + expiry, then the
600    /// claim contract (`type`, required claims, iss/aud allow-lists). Returns
601    /// the raw claim map — the right return for non-user purposes (refresh,
602    /// id_token, internal_assertion).
603    pub async fn verify_claims(
604        &self,
605        token: &str,
606        policy: &ValidationPolicy,
607    ) -> Result<Map<String, Value>, AuthError> {
608        let header = jsonwebtoken::decode_header(token)
609            .map_err(|e| AuthError::jwt(e.to_string(), "invalid"))?;
610        validate_typ_header(header.typ.as_deref(), policy)?;
611        if self.order.is_empty() {
612            return Err(AuthError::jwt(
613                "verifier issuer allow-list is empty: list the exact issuers this resource server trusts",
614                "issuer_mismatch",
615            ));
616        }
617        let state = self.route(token, policy)?;
618        let kid = header.kid.clone().unwrap_or_default();
619        let key = self.key_for_kid(state, &kid).await?;
620        let claims = self.decode_claims(token, &key)?;
621        validate_claims(&claims, policy)?;
622        Ok(claims)
623    }
624
625    /// Verify an OpenID Connect Back-Channel Logout token (the `logout_token` the service POSTs to a client's
626    /// `backchannel_logout_uri`) and say which session or subject to end.
627    ///
628    /// In order: the JOSE `typ` is `logout+jwt` (so an access token or an ID token can never pass as one); `iss` is on
629    /// the issuer allow-list (before any JWKS request); the signature verifies under the key the issuer publishes for
630    /// the token's `kid`, with the algorithm the key dictates, and the token has not expired; `aud` names this client;
631    /// `iat`, `exp` and `jti` are present and `iat` is recent; `events` has the back-channel logout member as an
632    /// object; there is no `nonce`; and `sub`, `sid` or both are present. Anything else is
633    /// [`AuthError::LogoutToken`] with a [`LogoutFailure`] reason and a fixed message that never carries the token.
634    ///
635    /// The `consume_jti` hook of [`LogoutTokenOptions`] is optional replay protection, called once after every other
636    /// check passed. The service re-sends a delivery with the same `jti` until it gets a 2xx, so record the `jti` only
637    /// once you have ended the session, or a retry after your own failure will be refused as a replay.
638    ///
639    /// Answer 200 (or 204) to the service only after this returns and you have ended the session; answer 400 for
640    /// [`AuthError::LogoutToken`]. A failure fetching the JWKS is [`AuthError::Network`]: answer 5xx so the service
641    /// retries.
642    pub async fn verify_logout_token(
643        &self,
644        token: &str,
645        options: &LogoutTokenOptions,
646    ) -> Result<LogoutToken, AuthError> {
647        if options.client_ids.is_empty() || options.client_ids.iter().any(|id| id.trim().is_empty())
648        {
649            return Err(AuthError::Config(
650                "client_id is required: the client id(s) this relying party is".into(),
651            ));
652        }
653        let max_age = options
654            .max_age
655            .unwrap_or(Duration::from_secs(DEFAULT_LOGOUT_TOKEN_MAX_AGE_SECONDS));
656        if max_age.is_zero() {
657            return Err(AuthError::Config(
658                "max_age must be a positive duration".into(),
659            ));
660        }
661        let now = options.now.unwrap_or_else(|| {
662            SystemTime::now()
663                .duration_since(UNIX_EPOCH)
664                .map(|d| d.as_secs_f64())
665                .unwrap_or(0.0)
666        });
667        let reject = |reason: LogoutFailure| AuthError::from(reason);
668        let parts: Vec<&str> = token.split('.').collect();
669        if token.len() > 16_384 || parts.len() != 3 {
670            return Err(reject(LogoutFailure::Signature));
671        }
672        let object = |segment: &str| -> Option<Map<String, Value>> {
673            let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
674                .decode(segment.trim_end_matches('='))
675                .ok()?;
676            match serde_json::from_slice::<Value>(&bytes).ok()? {
677                Value::Object(map) => Some(map),
678                _ => None,
679            }
680        };
681        let (Some(header), Some(unverified)) = (object(parts[0]), object(parts[1])) else {
682            return Err(reject(LogoutFailure::Signature));
683        };
684        if !is_logout_typ(header.get("typ").and_then(Value::as_str)) {
685            return Err(reject(LogoutFailure::Typ));
686        }
687        // `iss` only routes here; it is trusted after the signature verifies against that issuer's keys.
688        let state = unverified
689            .get("iss")
690            .and_then(Value::as_str)
691            .and_then(|iss| self.issuers.get(iss))
692            .ok_or_else(|| reject(LogoutFailure::Issuer))?;
693        let kid = header.get("kid").and_then(Value::as_str).unwrap_or("");
694        let key = match self.key_for_kid(state, kid).await {
695            Ok(key) => key,
696            Err(AuthError::Jwt { .. }) => return Err(reject(LogoutFailure::Key)),
697            Err(other) => return Err(other),
698        };
699        // The signature is checked over exactly the two segments the claims were read from, under the algorithm the
700        // KEY dictates; a header that names any other algorithm is refused. The claims are not parsed by the JOSE
701        // library, so a malformed time claim is a claims failure (below), not a signature failure.
702        if header.get("alg").and_then(Value::as_str) != Some(algorithm_name(key.alg)) {
703            return Err(reject(LogoutFailure::Signature));
704        }
705        let signed = format!("{}.{}", parts[0], parts[1]);
706        if !jsonwebtoken::crypto::verify(parts[2], signed.as_bytes(), &key.key, key.alg)
707            .unwrap_or(false)
708        {
709            return Err(reject(LogoutFailure::Signature));
710        }
711        let claims = unverified;
712        let skew = self.clock_skew.as_secs_f64();
713        for name in ["exp", "nbf", "iat"] {
714            if claims.contains_key(name)
715                && !claims
716                    .get(name)
717                    .and_then(Value::as_f64)
718                    .is_some_and(f64::is_finite)
719            {
720                return Err(reject(LogoutFailure::Claims));
721            }
722        }
723        let number = |name: &str| claims.get(name).and_then(Value::as_f64);
724        if number("exp").is_some_and(|exp| exp <= now - skew) {
725            return Err(reject(LogoutFailure::Expired));
726        }
727        if number("nbf").is_some_and(|nbf| nbf > now + skew) {
728            return Err(reject(LogoutFailure::Claims));
729        }
730        let result = check_logout_claims(
731            &claims,
732            &options.client_ids,
733            now,
734            max_age.as_secs_f64(),
735            skew,
736        )
737        .map_err(AuthError::LogoutToken)?;
738        if let Some(consume) = &options.consume_jti {
739            if !consume(&result.jti, result.expires_at).await {
740                return Err(reject(LogoutFailure::Replay));
741            }
742        }
743        Ok(result)
744    }
745
746    /// Verify an access token and return the CurrentUser (with the verified
747    /// `issuer`). Audience defaults to the verifier's configured value; the
748    /// issuer allow-list is required (strict convenience surface —
749    /// `verify_claims` for raw policy semantics, which also fail closed when
750    /// issuers are pinned).
751    pub async fn verify(&self, token: &str) -> Result<CurrentUser, AuthError> {
752        self.verify_with(token, Some(self.audience.clone()), None)
753            .await
754    }
755
756    /// `issuer` may only narrow to one allow-listed issuer.
757    pub async fn verify_with(
758        &self,
759        token: &str,
760        audience: Option<Vec<String>>,
761        issuer: Option<String>,
762    ) -> Result<CurrentUser, AuthError> {
763        let trusted: Vec<String> = match issuer {
764            Some(issuer) => vec![normalize_issuer(&issuer)],
765            None => self.order.clone(),
766        };
767        let aud = audience
768            .filter(|auds| auds.iter().any(|a| !a.trim().is_empty()))
769            .unwrap_or_else(|| self.audience.clone());
770        // Fail closed on a blank pin, before any network call (WP-09c R-09c.1).
771        if trusted.is_empty() || trusted.iter().any(|iss| iss.trim().is_empty()) {
772            return Err(AuthError::jwt(
773                "verifier issuer pin is empty: pass the exact issuer",
774                "issuer_mismatch",
775            ));
776        }
777        if let Some(unlisted) = trusted.iter().find(|iss| !self.issuers.contains_key(*iss)) {
778            return Err(AuthError::jwt(
779                format!("{unlisted} is not an allow-listed issuer"),
780                "issuer_mismatch",
781            ));
782        }
783        if aud.is_empty() {
784            return Err(AuthError::jwt(
785                "verifier audience pin is empty: pass the audience this resource server accepts",
786                "audience_mismatch",
787            ));
788        }
789        let mut policy = ValidationPolicy::access().with_trusted_issuers(trusted.clone());
790        policy = policy.with_expected_audiences(aud);
791        if !self.require_at_jwt {
792            policy = policy.allow_legacy_typ();
793        }
794        let claims = self.verify_claims(token, &policy).await?;
795        // Strict issuer pin: this surface requires iss present and matching
796        // (parity with the pre-WP-05a SDK contract).
797        match claims.get("iss").and_then(Value::as_str) {
798            Some(iss) if trusted.iter().any(|t| t == iss) => {}
799            Some(iss) => {
800                return Err(AuthError::jwt(
801                    format!("Issuer mismatch: {iss} is not in {trusted:?}"),
802                    "issuer_mismatch",
803                ))
804            }
805            None => {
806                return Err(AuthError::jwt(
807                    "missing required claim iss",
808                    "issuer_mismatch",
809                ))
810            }
811        }
812        claims_to_user(claims)
813    }
814}
815
816/// Replay protection for logout tokens: called once with `(jti, expires_at)` after every other check passed; return
817/// `false` when that `jti` was seen before.
818pub type ConsumeJti =
819    Arc<dyn Fn(&str, f64) -> Pin<Box<dyn Future<Output = bool> + Send>> + Send + Sync>;
820
821/// What [`MultiIssuerVerifier::verify_logout_token`] needs besides the token.
822#[derive(Clone)]
823pub struct LogoutTokenOptions {
824    client_ids: Vec<String>,
825    now: Option<f64>,
826    max_age: Option<Duration>,
827    consume_jti: Option<ConsumeJti>,
828}
829
830impl std::fmt::Debug for LogoutTokenOptions {
831    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
832        f.debug_struct("LogoutTokenOptions")
833            .field("client_ids", &self.client_ids)
834            .field("now", &self.now)
835            .field("max_age", &self.max_age)
836            .field("consume_jti", &self.consume_jti.is_some())
837            .finish()
838    }
839}
840
841impl LogoutTokenOptions {
842    /// The client id this relying party is: the logout token's `aud` must name it.
843    pub fn new(client_id: impl Into<String>) -> Self {
844        Self {
845            client_ids: vec![client_id.into()],
846            now: None,
847            max_age: None,
848            consume_jti: None,
849        }
850    }
851    /// A relying party known by several client ids.
852    pub fn with_client_ids(ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
853        Self {
854            client_ids: ids.into_iter().map(Into::into).collect(),
855            now: None,
856            max_age: None,
857            consume_jti: None,
858        }
859    }
860    /// The current time as unix seconds. For tests: the default is the system clock.
861    pub fn with_now(mut self, unix_seconds: f64) -> Self {
862        self.now = Some(unix_seconds);
863        self
864    }
865    /// How old a token's `iat` may be (default ten minutes). Zero is refused rather than disabling the bound.
866    pub fn with_max_age(mut self, max_age: Duration) -> Self {
867        self.max_age = Some(max_age);
868        self
869    }
870    /// Replay protection: `consume(jti, expires_at)` returns `false` for a `jti` seen before.
871    pub fn with_consume_jti(
872        mut self,
873        consume: impl Fn(&str, f64) -> bool + Send + Sync + 'static,
874    ) -> Self {
875        self.consume_jti = Some(Arc::new(move |jti, expires_at| {
876            let seen_before = !consume(jti, expires_at);
877            Box::pin(async move { !seen_before })
878        }));
879        self
880    }
881    /// Replay protection that needs to await (a database, a cache).
882    pub fn with_consume_jti_async(mut self, consume: ConsumeJti) -> Self {
883        self.consume_jti = Some(consume);
884        self
885    }
886}
887
888/// Single-issuer verifier: the original API, as a one-issuer
889/// [`MultiIssuerVerifier`]. The issuer and audience pins are required; a blank
890/// one fails closed at verification time, before any network call.
891pub struct Verifier {
892    inner: MultiIssuerVerifier,
893    issuer: String,
894}
895
896impl Verifier {
897    /// Pin the exact issuer and the audience this resource server accepts. Both
898    /// are required (WP-09c): a verifier with no audience pin would accept any
899    /// token the issuer ever signed, for any resource. A blank issuer or
900    /// audience cannot be rejected here (the constructor is infallible), so
901    /// `verify` fails closed with a `jwt` error before any network call.
902    pub fn new(issuer_url: impl Into<String>, audience: impl Into<String>) -> Self {
903        let issuer = normalize_issuer(&issuer_url.into());
904        Self {
905            inner: MultiIssuerVerifier::new(audience).with_issuer(issuer.clone()),
906            issuer,
907        }
908    }
909    /// Accept one more audience in addition to the one given to `new`. Blank
910    /// values are ignored.
911    pub fn with_audience(mut self, aud: impl Into<String>) -> Self {
912        self.inner = self.inner.with_audience(aud);
913        self
914    }
915    /// Accept several more audiences. Blank values are ignored.
916    pub fn with_audiences(mut self, auds: Vec<String>) -> Self {
917        self.inner = self.inner.with_audiences(auds);
918        self
919    }
920    pub fn with_jwks_uri(mut self, uri: impl Into<String>) -> Self {
921        if let Some(state) = self.inner.issuers.get_mut(&self.issuer) {
922            state.jwks_uri = Some(uri.into());
923        }
924        self
925    }
926    pub fn with_ttl(mut self, ttl: Duration) -> Self {
927        self.inner = self.inner.with_ttl(ttl);
928        self
929    }
930    /// Minimum interval between JWKS fetches (the kid-miss DoS bound).
931    /// `Duration::ZERO` disables it — for tests and static-JWKS fixtures.
932    pub fn with_min_fetch_interval(mut self, interval: Duration) -> Self {
933        self.inner = self.inner.with_min_fetch_interval(interval);
934        self
935    }
936    /// Compat window: accept access tokens without the `at+jwt` JOSE typ
937    /// (pre-WP-03b mints). Off by default — production consumers should
938    /// require the profile marker.
939    pub fn allow_legacy_typ(mut self) -> Self {
940        self.inner = self.inner.allow_legacy_typ();
941        self
942    }
943    /// Tolerate this much clock difference when judging expiry. See [`MultiIssuerVerifier::with_clock_skew`].
944    pub fn with_clock_skew(mut self, skew: Duration) -> Self {
945        self.inner = self.inner.with_clock_skew(skew);
946        self
947    }
948    /// The pinned issuer, as a one-element allow-list.
949    pub fn issuers(&self) -> Vec<String> {
950        self.inner.issuers()
951    }
952    /// See [`MultiIssuerVerifier::verify_logout_token`].
953    pub async fn verify_logout_token(
954        &self,
955        token: &str,
956        options: &LogoutTokenOptions,
957    ) -> Result<LogoutToken, AuthError> {
958        self.inner.verify_logout_token(token, options).await
959    }
960    /// See [`MultiIssuerVerifier::verify_claims`].
961    pub async fn verify_claims(
962        &self,
963        token: &str,
964        policy: &ValidationPolicy,
965    ) -> Result<Map<String, Value>, AuthError> {
966        self.inner.verify_claims(token, policy).await
967    }
968    /// See [`MultiIssuerVerifier::verify`].
969    pub async fn verify(&self, token: &str) -> Result<CurrentUser, AuthError> {
970        self.inner.verify(token).await
971    }
972    /// See [`MultiIssuerVerifier::verify_with`]; `issuer` may only name the
973    /// pinned issuer.
974    pub async fn verify_with(
975        &self,
976        token: &str,
977        audience: Option<Vec<String>>,
978        issuer: Option<String>,
979    ) -> Result<CurrentUser, AuthError> {
980        self.inner.verify_with(token, audience, issuer).await
981    }
982}
983
984pub fn create_multi_issuer_verifier(audience: impl Into<String>) -> MultiIssuerVerifier {
985    MultiIssuerVerifier::new(audience)
986}
987
988pub fn create_verifier(issuer_url: impl Into<String>, audience: impl Into<String>) -> Verifier {
989    Verifier::new(issuer_url, audience)
990}
991
992/// PKCE helpers (S256, 43-char unpadded base64url)
993pub fn generate_code_verifier() -> String {
994    use rand::RngCore;
995    let mut buf = [0u8; 32];
996    rand::thread_rng().fill_bytes(&mut buf);
997    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf)
998}
999pub fn generate_code_challenge(verifier: &str) -> String {
1000    use sha2::Digest;
1001    let hash = sha2::Sha256::digest(verifier.as_bytes());
1002    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hash)
1003}
1004
1005/// The leeway of the library's expiry check, which counts whole seconds. A sub-second skew rounds up, so asking for
1006/// some tolerance never silently becomes none.
1007fn leeway_seconds(skew: Duration) -> u64 {
1008    skew.as_secs()
1009        .saturating_add(u64::from(skew.subsec_nanos() > 0))
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014    use super::leeway_seconds;
1015    use std::time::Duration;
1016
1017    #[test]
1018    fn a_sub_second_skew_rounds_up_so_it_is_never_silently_zero() {
1019        assert_eq!(leeway_seconds(Duration::ZERO), 0);
1020        assert_eq!(leeway_seconds(Duration::from_millis(1)), 1);
1021        assert_eq!(leeway_seconds(Duration::from_millis(500)), 1);
1022        assert_eq!(leeway_seconds(Duration::from_secs(5)), 5);
1023        assert_eq!(leeway_seconds(Duration::from_millis(5_001)), 6);
1024        assert_eq!(leeway_seconds(Duration::MAX), u64::MAX);
1025    }
1026}