Skip to main content

plexus_auth_core/oidc/
validator.rs

1//! `OidcValidator` — RS256 token validation against a discovered JWKS
2//! (UT-1, UT-S01 D1; caching per AUTH-8; test matrix per AUTH-2).
3
4use std::collections::HashMap;
5use std::fmt;
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, Instant};
8
9use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
10use serde::Deserialize;
11use url::Url;
12
13use crate::auth::AuthContext;
14use crate::oidc::config::{AudienceClaim, OidcConfig};
15use crate::oidc::fetch::JwksFetcher;
16use crate::oidc::jwks;
17use crate::tenant::types::{TenantError, TenantId};
18use crate::verified_user::VerifiedUser;
19
20/// Validation failure modes.
21///
22/// The matrix-relevant rejections (`Expired`, `WrongIssuer`,
23/// `WrongAudience`, `InvalidSignature`, `UnknownKeyId`) are distinct
24/// variants so backends can log precisely; all of them must collapse to
25/// one generic auth failure on the wire (no oracle about *why* a token
26/// was rejected). `SessionValidator` impls do this naturally by
27/// returning `None`.
28#[derive(Debug)]
29pub enum OidcError {
30    /// Discovery document could not be fetched / parsed / trusted, and no
31    /// previously discovered `jwks_uri` was cached.
32    Discovery(String),
33    /// JWKS could not be fetched and no cached keys exist (cold cache +
34    /// unreachable IdP). With a warm cache the validator degrades instead
35    /// of erroring — see the module-level caching policy.
36    JwksUnavailable(String),
37    /// The token header carries no `kid`. The UT-S01 IdP contract is
38    /// "signs RS256 with `kid`"; kid-less tokens are rejected outright.
39    MissingKeyId,
40    /// The token's `kid` is not in the JWKS even after the policy's one
41    /// unconditional refresh.
42    UnknownKeyId(String),
43    /// The token's `alg` is not RS256 (RS256-only posture; the EdDSA
44    /// extension lands here and in `jwks::admit_key`).
45    UnsupportedAlgorithm(String),
46    /// Signature verification failed (tampered or foreign-key token).
47    InvalidSignature,
48    /// `exp` is in the past. Zero leeway — no grace (AUTH-8), online or
49    /// offline.
50    Expired,
51    /// `iss` does not match the configured issuer.
52    WrongIssuer,
53    /// `aud` does not match the configured audience.
54    WrongAudience,
55    /// `nbf` is in the future (zero leeway; IDENTITY-27).
56    NotYetValid,
57    /// `iat` is in the future (zero leeway).
58    IssuedInFuture {
59        /// The token's `iat`.
60        iat: i64,
61        /// The validator's clock at check time.
62        now: i64,
63    },
64    /// The token is structurally broken (not a JWT, undecodable claims,
65    /// missing required claims).
66    MalformedToken(String),
67    /// The token carried an `org_id` claim that fails [`TenantId`]
68    /// validation. Rejected rather than treated as tenantless: a
69    /// malformed tenant claim must not silently widen (or collapse) the
70    /// caller's isolation scope.
71    InvalidTenantClaim(TenantError),
72}
73
74impl fmt::Display for OidcError {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        match self {
77            Self::Discovery(m) => write!(f, "OIDC discovery failed: {m}"),
78            Self::JwksUnavailable(m) => write!(f, "JWKS unavailable and no cached keys: {m}"),
79            Self::MissingKeyId => f.write_str("token header carries no kid"),
80            Self::UnknownKeyId(kid) => {
81                write!(f, "kid {kid:?} not in JWKS after one refresh")
82            }
83            Self::UnsupportedAlgorithm(alg) => {
84                write!(f, "unsupported token algorithm {alg} (RS256-only)")
85            }
86            Self::InvalidSignature => f.write_str("token signature invalid"),
87            Self::Expired => f.write_str("token expired (exp in the past, zero leeway)"),
88            Self::NotYetValid => f.write_str("token not yet valid (nbf in the future, zero leeway)"),
89            Self::WrongIssuer => f.write_str("token iss does not match configured issuer"),
90            Self::WrongAudience => f.write_str("token aud does not match configured audience"),
91            Self::IssuedInFuture { iat, now } => {
92                write!(f, "token iat {iat} is in the future (now {now})")
93            }
94            Self::MalformedToken(m) => write!(f, "malformed token: {m}"),
95            Self::InvalidTenantClaim(e) => write!(f, "invalid org_id claim: {e}"),
96        }
97    }
98}
99
100impl std::error::Error for OidcError {}
101
102/// The claims the validator reads. Standard five plus the tenancy claim
103/// and the optional plexus extensions (UT-S01 D2 negative space: `roles`
104/// / `username` must be optional for validation — and they are).
105///
106/// `aud` is deliberately absent here: audience matching is enforced by
107/// `jsonwebtoken`'s `Validation` (which handles both string and
108/// string-array forms); the value itself is not needed afterwards.
109#[derive(Debug, Deserialize)]
110struct OidcClaims {
111    sub: String,
112    iss: String,
113    exp: i64,
114    iat: i64,
115    /// Tenancy claim (UT-S01 D3 — Auth0 Organizations convention).
116    #[serde(default)]
117    org_id: Option<String>,
118    /// OIDC session id, used for `AuthContext::session_id` when present.
119    #[serde(default)]
120    sid: Option<String>,
121    /// JWT id — `session_id` fallback when `sid` is absent.
122    #[serde(default)]
123    jti: Option<String>,
124    /// Plexus extension; optional for validation.
125    #[serde(default)]
126    roles: Option<Vec<String>>,
127    /// Plexus extension; optional for validation.
128    #[serde(default)]
129    username: Option<String>,
130    /// Every other claim, kept for provider adapters (IDENTITY-13): Auth0
131    /// puts roles under a namespaced claim, and names under `nickname`,
132    /// `name` or `email`.
133    #[serde(flatten)]
134    extra: serde_json::Map<String, serde_json::Value>,
135}
136
137/// The OIDC discovery document fields the validator needs.
138#[derive(Debug, Deserialize)]
139struct DiscoveryDoc {
140    issuer: String,
141    jwks_uri: String,
142}
143
144/// How often an unknown `kid` may cause a JWKS refetch, for the whole
145/// validator (IDENTITY-27). A burst of tokens naming kids the IdP never
146/// published costs one fetch a minute, not one each.
147const KID_MISS_REFRESH_INTERVAL: Duration = Duration::from_secs(60);
148
149/// JWKS cache state, guarded by a `std::sync::Mutex` that is **never
150/// held across an await** (lock → copy/update → drop; fetches happen
151/// unlocked). Refreshes themselves are single-flight (IDENTITY-27): they
152/// run under the validator's async `refresh_lock`, and a caller that
153/// waited on it while another refreshed uses that refresh instead of
154/// fetching again (`generation`).
155struct CacheState {
156    /// Discovered `jwks_uri`. Cached for the validator's lifetime once
157    /// resolved; refreshed only if a later refresh cycle needs it again.
158    jwks_uri: Option<Url>,
159    /// kid → verification key.
160    keys: HashMap<String, DecodingKey>,
161    /// When the keys were last successfully fetched. `None` ⇔ cold.
162    fetched_at: Option<Instant>,
163    /// TTL derived from the JWKS response's `Cache-Control` (AUTH-8:
164    /// min(max-age, 3600 s)).
165    ttl: Duration,
166    /// Whether the validator is in degraded (stale-cache) mode. Drives
167    /// the `auth_provider_degraded` / `auth_provider_restored` event
168    /// transitions.
169    degraded: bool,
170    /// Counts refresh attempts (successful or not). A caller notes it
171    /// before waiting on `refresh_lock`; if it moved meanwhile, someone
172    /// else refreshed, and the caller uses that result.
173    generation: u64,
174    /// The last refresh attempt's failure, reported to callers that
175    /// waited on it when no cached keys exist.
176    last_error: Option<String>,
177    /// When an unknown `kid` last caused a refresh: at most one per
178    /// [`KID_MISS_REFRESH_INTERVAL`], validator-wide.
179    kid_miss_at: Option<Instant>,
180}
181
182/// Outcome of a refresh attempt.
183#[derive(Clone, Copy, PartialEq)]
184enum RefreshOutcome {
185    /// Fresh keys fetched and stored.
186    Fresh,
187    /// Fetch failed but cached keys exist — validation proceeds with the
188    /// stale cache (degraded mode).
189    Degraded,
190}
191
192/// Locally validates RS256 tokens issued by one trusted OIDC issuer.
193///
194/// See the [module docs](crate::oidc) for the resolution model, caching
195/// policy, and interchangeability bar. Construction:
196///
197/// - [`OidcValidator::with_fetcher`] — inject any [`JwksFetcher`]
198///   (tests, custom HTTP stacks).
199/// - `OidcValidator::new` — batteries-included `reqwest` fetcher;
200///   requires the `oidc-reqwest` feature.
201///
202/// The validator is `Send + Sync`; share one instance per backend (the
203/// JWKS cache lives inside it).
204pub struct OidcValidator {
205    config: OidcConfig,
206    fetcher: Arc<dyn JwksFetcher>,
207    state: Mutex<CacheState>,
208    /// Held across a refresh's fetches, so concurrent refreshes coalesce
209    /// into one (IDENTITY-27).
210    refresh_lock: tokio::sync::Mutex<()>,
211}
212
213impl OidcValidator {
214    /// Build a validator with the default `reqwest` fetcher.
215    #[cfg(feature = "oidc-reqwest")]
216    pub fn new(config: OidcConfig) -> Self {
217        Self::with_fetcher(config, Arc::new(crate::oidc::fetch::ReqwestJwksFetcher::new()))
218    }
219
220    /// Build a validator over an injected fetcher.
221    pub fn with_fetcher(config: OidcConfig, fetcher: Arc<dyn JwksFetcher>) -> Self {
222        Self {
223            config,
224            fetcher,
225            state: Mutex::new(CacheState {
226                jwks_uri: None,
227                keys: HashMap::new(),
228                fetched_at: None,
229                ttl: Duration::from_secs(0),
230                degraded: false,
231                generation: 0,
232                last_error: None,
233                kid_miss_at: None,
234            }),
235            refresh_lock: tokio::sync::Mutex::new(()),
236        }
237    }
238
239    /// Treat the cached keys as stale and forget the last kid-miss
240    /// refresh, so the next validation refetches. Costs one fetch and
241    /// weakens nothing; it exists so tests can step past the 60 s floors
242    /// without sleeping.
243    #[doc(hidden)]
244    pub fn expire_cache(&self) {
245        let mut st = self.state.lock().unwrap();
246        st.fetched_at = None;
247        st.kid_miss_at = None;
248    }
249
250    /// The validator's configuration.
251    pub fn config(&self) -> &OidcConfig {
252        &self.config
253    }
254
255    /// Validate a token end-to-end and mint the sealed proof.
256    ///
257    /// Steps: header gate (`alg` == RS256, `kid` present) → cache
258    /// freshness (refresh on cold/expired TTL; degrade to stale keys if
259    /// the IdP is unreachable and a cache exists) → kid lookup (miss →
260    /// one refresh — at most one a minute per validator — then reject) → RS256 signature
261    /// + `iss`/`aud`/`exp` with zero leeway → `iat` not in the future →
262    /// `org_id` → [`TenantId`] → [`VerifiedUser`] minted.
263    pub async fn validate_token(&self, token: &str) -> Result<VerifiedToken, OidcError> {
264        // ── Header gate ───────────────────────────────────────────────
265        let header =
266            decode_header(token).map_err(|e| OidcError::MalformedToken(e.to_string()))?;
267        if header.alg != Algorithm::RS256 {
268            return Err(OidcError::UnsupportedAlgorithm(format!("{:?}", header.alg)));
269        }
270        let kid = header.kid.ok_or(OidcError::MissingKeyId)?;
271
272        // ── Cache freshness ───────────────────────────────────────────
273        let (needs_refresh, generation) = {
274            let st = self.state.lock().unwrap();
275            (st.fetched_at.is_none_or(|at| at.elapsed() >= st.ttl), st.generation)
276        };
277        let mut refresh_attempted = false;
278        if needs_refresh {
279            self.refresh(generation, false).await?;
280            refresh_attempted = true;
281        }
282
283        // ── Key selection (kid-miss → one refresh — AUTH-8; at most one
284        //    a minute per validator, single-flight — IDENTITY-27) ───────
285        let key = match self.lookup(&kid) {
286            Some(k) => k,
287            None => {
288                if !refresh_attempted {
289                    // The refresh the policy grants a kid-miss
290                    // (key-rotation case: a new kid published inside the
291                    // TTL window). If this call already refreshed above,
292                    // that refresh *was* the one.
293                    let generation = self.state.lock().unwrap().generation;
294                    self.refresh(generation, true).await?;
295                }
296                self.lookup(&kid).ok_or(OidcError::UnknownKeyId(kid.clone()))?
297            }
298        };
299
300        // ── Signature + standard claims ───────────────────────────────
301        let mut validation = Validation::new(Algorithm::RS256);
302        // No grace anywhere (AUTH-8): default leeway is 60 s — zero it.
303        validation.leeway = 0;
304        // IDENTITY-27: `nbf`, when present, is honoured with the same
305        // zero leeway (jsonwebtoken leaves it unchecked by default).
306        validation.validate_nbf = true;
307        // Trailing-slash tolerance: `Url` normalizes a root issuer to a
308        // trailing slash while many IdPs mint `iss` without one (and
309        // Auth0 mints *with* one). Both spellings of the *same* issuer
310        // are accepted; any other issuer fails.
311        let issuer_str = self.config.issuer().as_url().as_str();
312        validation.set_issuer(&[issuer_str, issuer_str.trim_end_matches('/')]);
313        match self.config.audience_claim() {
314            AudienceClaim::Aud => {
315                validation.set_audience(&[self.config.audience().as_str()]);
316                validation.set_required_spec_claims(&["sub", "exp", "iss", "aud"]);
317            }
318            AudienceClaim::ClientId => {
319                // IDENTITY-30: no `aud` to check; `client_id` is, below.
320                validation.validate_aud = false;
321                validation.set_required_spec_claims(&["sub", "exp", "iss"]);
322            }
323        }
324
325        let data = decode::<OidcClaims>(token, &key, &validation).map_err(map_jwt_error)?;
326        let claims = data.claims;
327
328        // ── client_id: the audience, where the provider names it there
329        //    (WorkOS); absent or another client's ⇒ reject. ─────────────
330        if self.config.audience_claim() == AudienceClaim::ClientId
331            && claims.extra.get("client_id").and_then(serde_json::Value::as_str) != Some(self.config.audience().as_str())
332        {
333            return Err(OidcError::WrongAudience);
334        }
335
336        // ── iat: required by OidcClaims' non-optional field; must not be
337        //    in the future (zero leeway, symmetric with exp). ───────────
338        let now = chrono::Utc::now().timestamp();
339        if claims.iat > now {
340            return Err(OidcError::IssuedInFuture { iat: claims.iat, now });
341        }
342
343        // ── Tenancy (UT-S01 D3): org_id → TenantId; absent claim ⇒
344        //    valid-but-tenantless; malformed claim ⇒ reject. ───────────
345        let tenant = claims
346            .org_id
347            .as_deref()
348            .map(TenantId::try_new)
349            .transpose()
350            .map_err(OidcError::InvalidTenantClaim)?;
351
352        // ── session_id: AuthContext::is_authenticated() requires a
353        //    non-empty session_id; prefer the OIDC `sid`, then `jti`,
354        //    then the token's signature segment (stable per token,
355        //    non-empty for any signed JWT). ─────────────────────────────
356        let session_id = claims
357            .sid
358            .clone()
359            .or_else(|| claims.jti.clone())
360            .unwrap_or_else(|| token.rsplit('.').next().unwrap_or_default().to_string());
361
362        let user = VerifiedUser::new_sealed(
363            claims.sub,
364            claims.iss,
365            claims.iat,
366            claims.exp,
367            tenant,
368        );
369
370        Ok(VerifiedToken {
371            user,
372            roles: claims.roles.unwrap_or_default(),
373            username: claims.username,
374            session_id,
375            extra: claims.extra,
376        })
377    }
378
379    /// Clone the key for `kid` out of the cache (lock scope stays tiny;
380    /// `DecodingKey` is cheaply clonable).
381    fn lookup(&self, kid: &str) -> Option<DecodingKey> {
382        self.state.lock().unwrap().keys.get(kid).cloned()
383    }
384
385    /// Refresh the JWKS (discovering `jwks_uri` first if needed).
386    ///
387    /// - Success → fresh keys + TTL stored; if the validator was
388    ///   degraded, emit `auth_provider_restored`.
389    /// - Failure with cached keys → flip to degraded (emit
390    ///   `auth_provider_degraded` on the transition), keep serving the
391    ///   stale cache. Cached keys remain usable only for tokens whose
392    ///   `exp` is still in the future, because `exp` is enforced with
393    ///   zero grace regardless (AUTH-8).
394    /// - Failure with no cache → error.
395    ///
396    /// Single-flight (IDENTITY-27): `seen` is the `generation` the caller
397    /// read before deciding to refresh. Once it holds `refresh_lock`, a
398    /// moved generation means another caller refreshed meanwhile — that
399    /// refresh is this one's. A `kid_miss` refresh additionally fetches at
400    /// most once per [`KID_MISS_REFRESH_INTERVAL`]; inside it, the cache
401    /// stands as it is.
402    async fn refresh(&self, seen: u64, kid_miss: bool) -> Result<RefreshOutcome, OidcError> {
403        let _flight = self.refresh_lock.lock().await;
404        {
405            let mut st = self.state.lock().unwrap();
406            if st.generation != seen {
407                return Self::settled(&st);
408            }
409            if kid_miss {
410                if st.kid_miss_at.is_some_and(|at| at.elapsed() < KID_MISS_REFRESH_INTERVAL) {
411                    tracing::debug!(
412                        target: "plexus::auth",
413                        issuer = %self.config.issuer(),
414                        "unknown kid: JWKS refreshed for a kid-miss within the last minute; not refetching"
415                    );
416                    return Self::settled(&st);
417                }
418                st.kid_miss_at = Some(Instant::now());
419            }
420        }
421        let fetched = self.try_fetch_keys().await;
422        let mut st = self.state.lock().unwrap();
423        st.generation += 1;
424        match fetched {
425            Ok((keys, ttl, jwks_uri)) => {
426                st.last_error = None;
427                if st.degraded {
428                    tracing::info!(
429                        target: "plexus::auth",
430                        issuer = %self.config.issuer(),
431                        "auth_provider_restored: JWKS refresh succeeded; leaving degraded mode"
432                    );
433                }
434                st.keys = keys;
435                st.ttl = ttl;
436                st.fetched_at = Some(Instant::now());
437                st.jwks_uri = Some(jwks_uri);
438                st.degraded = false;
439                Ok(RefreshOutcome::Fresh)
440            }
441            Err(err) => {
442                st.last_error = Some(err.to_string());
443                if st.keys.is_empty() {
444                    return Err(err);
445                }
446                if !st.degraded {
447                    st.degraded = true;
448                    tracing::warn!(
449                        target: "plexus::auth",
450                        issuer = %self.config.issuer(),
451                        error = %err,
452                        "auth_provider_degraded: IdP unreachable; serving cached JWKS \
453                         (future-exp tokens only — exp has no grace)"
454                    );
455                }
456                Ok(RefreshOutcome::Degraded)
457            }
458        }
459    }
460
461    /// The outcome of a refresh another caller made (or that the kid-miss
462    /// interval skipped): the cache as it stands.
463    fn settled(st: &CacheState) -> Result<RefreshOutcome, OidcError> {
464        if st.keys.is_empty() {
465            if let Some(e) = &st.last_error {
466                return Err(OidcError::JwksUnavailable(e.clone()));
467            }
468        }
469        Ok(if st.degraded { RefreshOutcome::Degraded } else { RefreshOutcome::Fresh })
470    }
471
472    /// Fetch (and, if needed, discover) the JWKS. Pure fetch+parse; no
473    /// state mutation — the caller decides how the result lands.
474    async fn try_fetch_keys(
475        &self,
476    ) -> Result<(HashMap<String, DecodingKey>, Duration, Url), OidcError> {
477        let cached_uri = self.state.lock().unwrap().jwks_uri.clone();
478        let jwks_uri = match cached_uri {
479            Some(u) => u,
480            None => self.discover().await?,
481        };
482
483        let doc = self
484            .fetcher
485            .fetch(&jwks_uri)
486            .await
487            .map_err(|e| OidcError::JwksUnavailable(e.to_string()))?;
488        let keys = jwks::parse_jwks(&doc.body).map_err(OidcError::JwksUnavailable)?;
489        let ttl = jwks::ttl_from_cache_control(doc.cache_control.as_deref());
490        Ok((keys, ttl, jwks_uri))
491    }
492
493    /// Fetch the discovery document and extract a trusted `jwks_uri`.
494    ///
495    /// The document's `issuer` must equal the configured issuer (OIDC
496    /// Discovery §4.3 — defends against a misrouted or spoofed discovery
497    /// host), trailing-slash tolerant.
498    async fn discover(&self) -> Result<Url, OidcError> {
499        let url = self.config.discovery_url();
500        let doc = self
501            .fetcher
502            .fetch(&url)
503            .await
504            .map_err(|e| OidcError::Discovery(e.to_string()))?;
505        let parsed: DiscoveryDoc = serde_json::from_str(&doc.body)
506            .map_err(|e| OidcError::Discovery(format!("discovery document parse error: {e}")))?;
507
508        let configured = self.config.issuer().as_url().as_str().trim_end_matches('/');
509        if parsed.issuer.trim_end_matches('/') != configured {
510            return Err(OidcError::Discovery(format!(
511                "discovery document issuer {:?} does not match configured issuer {:?}",
512                parsed.issuer, configured
513            )));
514        }
515
516        let jwks_uri = Url::parse(&parsed.jwks_uri)
517            .map_err(|e| OidcError::Discovery(format!("invalid jwks_uri: {e}")))?;
518        trusted_jwks_uri(self.config.issuer().as_url(), &jwks_uri)?;
519        Ok(jwks_uri)
520    }
521}
522
523/// IDENTITY-27: the discovery document may not point the validator at an
524/// arbitrary host. `jwks_uri` is trusted when it is `https`, or when it is
525/// on the issuer's own origin (scheme, host and port) — which is what lets
526/// a loopback `http` issuer in a test publish its keys beside itself.
527fn trusted_jwks_uri(issuer: &Url, jwks_uri: &Url) -> Result<(), OidcError> {
528    let same_origin = jwks_uri.scheme() == issuer.scheme()
529        && jwks_uri.host_str() == issuer.host_str()
530        && jwks_uri.port_or_known_default() == issuer.port_or_known_default();
531    if jwks_uri.scheme() == "https" || same_origin {
532        Ok(())
533    } else {
534        Err(OidcError::Discovery(format!(
535            "jwks_uri {jwks_uri} is neither https nor on the issuer's origin"
536        )))
537    }
538}
539
540/// Map `jsonwebtoken` failures onto the matrix-relevant variants.
541fn map_jwt_error(e: jsonwebtoken::errors::Error) -> OidcError {
542    use jsonwebtoken::errors::ErrorKind;
543    match e.kind() {
544        ErrorKind::ExpiredSignature => OidcError::Expired,
545        ErrorKind::ImmatureSignature => OidcError::NotYetValid,
546        ErrorKind::InvalidIssuer => OidcError::WrongIssuer,
547        ErrorKind::InvalidAudience => OidcError::WrongAudience,
548        ErrorKind::InvalidSignature => OidcError::InvalidSignature,
549        _ => OidcError::MalformedToken(e.to_string()),
550    }
551}
552
553/// The successful outcome of [`OidcValidator::validate_token`].
554///
555/// Wraps the sealed [`VerifiedUser`] proof together with the optional
556/// plexus extension claims a backend may want for its `AuthContext`.
557/// Sealed like the proof it carries: no public constructor, no public
558/// fields — the only mint path is the validator.
559#[derive(Debug, Clone)]
560pub struct VerifiedToken {
561    user: VerifiedUser,
562    roles: Vec<String>,
563    username: Option<String>,
564    session_id: String,
565    /// Claims beyond the ones read above, verified with them.
566    extra: serde_json::Map<String, serde_json::Value>,
567}
568
569impl VerifiedToken {
570    /// The sealed proof (claims: `sub`, `iss`, `iat`, `exp`, tenant).
571    pub fn user(&self) -> &VerifiedUser {
572        &self.user
573    }
574
575    /// The verified tenant identity from `org_id`, if the token carried
576    /// one. `None` ⇔ valid-but-tenantless (UT-S01 D3).
577    pub fn tenant_id(&self) -> Option<&TenantId> {
578        self.user.tenant_id()
579    }
580
581    /// The `roles` extension claim (empty when absent — optional for
582    /// validation per the interchangeability bar).
583    pub fn roles(&self) -> &[String] {
584        &self.roles
585    }
586
587    /// The `username` extension claim, if present.
588    pub fn username(&self) -> Option<&str> {
589        self.username.as_deref()
590    }
591
592    /// Any other verified claim by name: `nickname`, `email`, or a
593    /// provider's namespaced claim such as `https://menger.example/roles`.
594    /// The claims read into fields above (`sub`, `iss`, `exp`, `iat`,
595    /// `org_id`, `sid`, `jti`, `roles`, `username`) are not repeated here.
596    pub fn claim(&self, name: &str) -> Option<&serde_json::Value> {
597        self.extra.get(name)
598    }
599
600    /// The session identifier (`sid`, else `jti`, else the token's
601    /// signature segment). Always non-empty, so the
602    /// [`AuthContext`] built from this token reports
603    /// `is_authenticated() == true`.
604    pub fn session_id(&self) -> &str {
605        &self.session_id
606    }
607
608    /// Build the per-connection [`AuthContext`].
609    ///
610    /// Metadata written:
611    ///
612    /// - `org_id` **and** `tenant_id` — the same value under both keys
613    ///   for one deprecation window (UT-S01 D3), so pre-cutover
614    ///   `ClaimTenantResolver` configurations keep resolving;
615    /// - `iss` — the verified issuer;
616    /// - `username` — when the extension claim was present;
617    /// - `auth_method: "oidc"` — parity with the API-key path's
618    ///   `auth_method` marker in the trak reference;
619    /// - `expires_at` — the token's `exp`, seconds since the epoch
620    ///   (IDENTITY-27).
621    pub fn into_auth_context(self) -> AuthContext {
622        let mut metadata = serde_json::Map::new();
623        if let Some(t) = self.user.tenant_id() {
624            let v = serde_json::Value::String(t.as_str().to_string());
625            metadata.insert("org_id".into(), v.clone());
626            // Deprecation alias — remove after one release window
627            // (UT-S01 D3).
628            metadata.insert("tenant_id".into(), v);
629        }
630        metadata.insert(
631            "iss".into(),
632            serde_json::Value::String(self.user.issuer().to_string()),
633        );
634        if let Some(u) = &self.username {
635            metadata.insert("username".into(), serde_json::Value::String(u.clone()));
636        }
637        metadata.insert(
638            "auth_method".into(),
639            serde_json::Value::String("oidc".into()),
640        );
641        // IDENTITY-27: the token's `exp`, so a service can stop honouring
642        // a connection its token no longer vouches for.
643        metadata.insert("expires_at".into(), serde_json::Value::from(self.user.expires_at()));
644
645        AuthContext::new(
646            self.user.user_id().to_string(),
647            self.session_id,
648            self.roles,
649            serde_json::Value::Object(metadata),
650        )
651    }
652}