plexus-auth-core 0.3.4

Sealed-type primitives for the Plexus auth framework: AuthContext, VerifiedUser, Principal.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! `OidcValidator` — RS256 token validation against a discovered JWKS
//! (UT-1, UT-S01 D1; caching per AUTH-8; test matrix per AUTH-2).

use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use serde::Deserialize;
use url::Url;

use crate::auth::AuthContext;
use crate::oidc::config::{AudienceClaim, OidcConfig};
use crate::oidc::fetch::JwksFetcher;
use crate::oidc::jwks;
use crate::tenant::types::{TenantError, TenantId};
use crate::verified_user::VerifiedUser;

/// Validation failure modes.
///
/// The matrix-relevant rejections (`Expired`, `WrongIssuer`,
/// `WrongAudience`, `InvalidSignature`, `UnknownKeyId`) are distinct
/// variants so backends can log precisely; all of them must collapse to
/// one generic auth failure on the wire (no oracle about *why* a token
/// was rejected). `SessionValidator` impls do this naturally by
/// returning `None`.
#[derive(Debug)]
pub enum OidcError {
    /// Discovery document could not be fetched / parsed / trusted, and no
    /// previously discovered `jwks_uri` was cached.
    Discovery(String),
    /// JWKS could not be fetched and no cached keys exist (cold cache +
    /// unreachable IdP). With a warm cache the validator degrades instead
    /// of erroring — see the module-level caching policy.
    JwksUnavailable(String),
    /// The token header carries no `kid`. The UT-S01 IdP contract is
    /// "signs RS256 with `kid`"; kid-less tokens are rejected outright.
    MissingKeyId,
    /// The token's `kid` is not in the JWKS even after the policy's one
    /// unconditional refresh.
    UnknownKeyId(String),
    /// The token's `alg` is not RS256 (RS256-only posture; the EdDSA
    /// extension lands here and in `jwks::admit_key`).
    UnsupportedAlgorithm(String),
    /// Signature verification failed (tampered or foreign-key token).
    InvalidSignature,
    /// `exp` is in the past. Zero leeway — no grace (AUTH-8), online or
    /// offline.
    Expired,
    /// `iss` does not match the configured issuer.
    WrongIssuer,
    /// `aud` does not match the configured audience.
    WrongAudience,
    /// `nbf` is in the future (zero leeway; IDENTITY-27).
    NotYetValid,
    /// `iat` is in the future (zero leeway).
    IssuedInFuture {
        /// The token's `iat`.
        iat: i64,
        /// The validator's clock at check time.
        now: i64,
    },
    /// The token is structurally broken (not a JWT, undecodable claims,
    /// missing required claims).
    MalformedToken(String),
    /// The token carried an `org_id` claim that fails [`TenantId`]
    /// validation. Rejected rather than treated as tenantless: a
    /// malformed tenant claim must not silently widen (or collapse) the
    /// caller's isolation scope.
    InvalidTenantClaim(TenantError),
}

impl fmt::Display for OidcError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Discovery(m) => write!(f, "OIDC discovery failed: {m}"),
            Self::JwksUnavailable(m) => write!(f, "JWKS unavailable and no cached keys: {m}"),
            Self::MissingKeyId => f.write_str("token header carries no kid"),
            Self::UnknownKeyId(kid) => {
                write!(f, "kid {kid:?} not in JWKS after one refresh")
            }
            Self::UnsupportedAlgorithm(alg) => {
                write!(f, "unsupported token algorithm {alg} (RS256-only)")
            }
            Self::InvalidSignature => f.write_str("token signature invalid"),
            Self::Expired => f.write_str("token expired (exp in the past, zero leeway)"),
            Self::NotYetValid => f.write_str("token not yet valid (nbf in the future, zero leeway)"),
            Self::WrongIssuer => f.write_str("token iss does not match configured issuer"),
            Self::WrongAudience => f.write_str("token aud does not match configured audience"),
            Self::IssuedInFuture { iat, now } => {
                write!(f, "token iat {iat} is in the future (now {now})")
            }
            Self::MalformedToken(m) => write!(f, "malformed token: {m}"),
            Self::InvalidTenantClaim(e) => write!(f, "invalid org_id claim: {e}"),
        }
    }
}

impl std::error::Error for OidcError {}

/// The claims the validator reads. Standard five plus the tenancy claim
/// and the optional plexus extensions (UT-S01 D2 negative space: `roles`
/// / `username` must be optional for validation — and they are).
///
/// `aud` is deliberately absent here: audience matching is enforced by
/// `jsonwebtoken`'s `Validation` (which handles both string and
/// string-array forms); the value itself is not needed afterwards.
#[derive(Debug, Deserialize)]
struct OidcClaims {
    sub: String,
    iss: String,
    exp: i64,
    iat: i64,
    /// Tenancy claim (UT-S01 D3 — Auth0 Organizations convention).
    #[serde(default)]
    org_id: Option<String>,
    /// OIDC session id, used for `AuthContext::session_id` when present.
    #[serde(default)]
    sid: Option<String>,
    /// JWT id — `session_id` fallback when `sid` is absent.
    #[serde(default)]
    jti: Option<String>,
    /// Plexus extension; optional for validation.
    #[serde(default)]
    roles: Option<Vec<String>>,
    /// Plexus extension; optional for validation.
    #[serde(default)]
    username: Option<String>,
    /// Every other claim, kept for provider adapters (IDENTITY-13): Auth0
    /// puts roles under a namespaced claim, and names under `nickname`,
    /// `name` or `email`.
    #[serde(flatten)]
    extra: serde_json::Map<String, serde_json::Value>,
}

/// The OIDC discovery document fields the validator needs.
#[derive(Debug, Deserialize)]
struct DiscoveryDoc {
    issuer: String,
    jwks_uri: String,
}

/// How often an unknown `kid` may cause a JWKS refetch, for the whole
/// validator (IDENTITY-27). A burst of tokens naming kids the IdP never
/// published costs one fetch a minute, not one each.
const KID_MISS_REFRESH_INTERVAL: Duration = Duration::from_secs(60);

/// JWKS cache state, guarded by a `std::sync::Mutex` that is **never
/// held across an await** (lock → copy/update → drop; fetches happen
/// unlocked). Refreshes themselves are single-flight (IDENTITY-27): they
/// run under the validator's async `refresh_lock`, and a caller that
/// waited on it while another refreshed uses that refresh instead of
/// fetching again (`generation`).
struct CacheState {
    /// Discovered `jwks_uri`. Cached for the validator's lifetime once
    /// resolved; refreshed only if a later refresh cycle needs it again.
    jwks_uri: Option<Url>,
    /// kid → verification key.
    keys: HashMap<String, DecodingKey>,
    /// When the keys were last successfully fetched. `None` ⇔ cold.
    fetched_at: Option<Instant>,
    /// TTL derived from the JWKS response's `Cache-Control` (AUTH-8:
    /// min(max-age, 3600 s)).
    ttl: Duration,
    /// Whether the validator is in degraded (stale-cache) mode. Drives
    /// the `auth_provider_degraded` / `auth_provider_restored` event
    /// transitions.
    degraded: bool,
    /// Counts refresh attempts (successful or not). A caller notes it
    /// before waiting on `refresh_lock`; if it moved meanwhile, someone
    /// else refreshed, and the caller uses that result.
    generation: u64,
    /// The last refresh attempt's failure, reported to callers that
    /// waited on it when no cached keys exist.
    last_error: Option<String>,
    /// When an unknown `kid` last caused a refresh: at most one per
    /// [`KID_MISS_REFRESH_INTERVAL`], validator-wide.
    kid_miss_at: Option<Instant>,
}

/// Outcome of a refresh attempt.
#[derive(Clone, Copy, PartialEq)]
enum RefreshOutcome {
    /// Fresh keys fetched and stored.
    Fresh,
    /// Fetch failed but cached keys exist — validation proceeds with the
    /// stale cache (degraded mode).
    Degraded,
}

/// Locally validates RS256 tokens issued by one trusted OIDC issuer.
///
/// See the [module docs](crate::oidc) for the resolution model, caching
/// policy, and interchangeability bar. Construction:
///
/// - [`OidcValidator::with_fetcher`] — inject any [`JwksFetcher`]
///   (tests, custom HTTP stacks).
/// - `OidcValidator::new` — batteries-included `reqwest` fetcher;
///   requires the `oidc-reqwest` feature.
///
/// The validator is `Send + Sync`; share one instance per backend (the
/// JWKS cache lives inside it).
pub struct OidcValidator {
    config: OidcConfig,
    fetcher: Arc<dyn JwksFetcher>,
    state: Mutex<CacheState>,
    /// Held across a refresh's fetches, so concurrent refreshes coalesce
    /// into one (IDENTITY-27).
    refresh_lock: tokio::sync::Mutex<()>,
}

impl OidcValidator {
    /// Build a validator with the default `reqwest` fetcher.
    #[cfg(feature = "oidc-reqwest")]
    pub fn new(config: OidcConfig) -> Self {
        Self::with_fetcher(config, Arc::new(crate::oidc::fetch::ReqwestJwksFetcher::new()))
    }

    /// Build a validator over an injected fetcher.
    pub fn with_fetcher(config: OidcConfig, fetcher: Arc<dyn JwksFetcher>) -> Self {
        Self {
            config,
            fetcher,
            state: Mutex::new(CacheState {
                jwks_uri: None,
                keys: HashMap::new(),
                fetched_at: None,
                ttl: Duration::from_secs(0),
                degraded: false,
                generation: 0,
                last_error: None,
                kid_miss_at: None,
            }),
            refresh_lock: tokio::sync::Mutex::new(()),
        }
    }

    /// Treat the cached keys as stale and forget the last kid-miss
    /// refresh, so the next validation refetches. Costs one fetch and
    /// weakens nothing; it exists so tests can step past the 60 s floors
    /// without sleeping.
    #[doc(hidden)]
    pub fn expire_cache(&self) {
        let mut st = self.state.lock().unwrap();
        st.fetched_at = None;
        st.kid_miss_at = None;
    }

    /// The validator's configuration.
    pub fn config(&self) -> &OidcConfig {
        &self.config
    }

    /// Validate a token end-to-end and mint the sealed proof.
    ///
    /// Steps: header gate (`alg` == RS256, `kid` present) → cache
    /// freshness (refresh on cold/expired TTL; degrade to stale keys if
    /// the IdP is unreachable and a cache exists) → kid lookup (miss →
    /// one refresh — at most one a minute per validator — then reject) → RS256 signature
    /// + `iss`/`aud`/`exp` with zero leeway → `iat` not in the future →
    /// `org_id` → [`TenantId`] → [`VerifiedUser`] minted.
    pub async fn validate_token(&self, token: &str) -> Result<VerifiedToken, OidcError> {
        // ── Header gate ───────────────────────────────────────────────
        let header =
            decode_header(token).map_err(|e| OidcError::MalformedToken(e.to_string()))?;
        if header.alg != Algorithm::RS256 {
            return Err(OidcError::UnsupportedAlgorithm(format!("{:?}", header.alg)));
        }
        let kid = header.kid.ok_or(OidcError::MissingKeyId)?;

        // ── Cache freshness ───────────────────────────────────────────
        let (needs_refresh, generation) = {
            let st = self.state.lock().unwrap();
            (st.fetched_at.is_none_or(|at| at.elapsed() >= st.ttl), st.generation)
        };
        let mut refresh_attempted = false;
        if needs_refresh {
            self.refresh(generation, false).await?;
            refresh_attempted = true;
        }

        // ── Key selection (kid-miss → one refresh — AUTH-8; at most one
        //    a minute per validator, single-flight — IDENTITY-27) ───────
        let key = match self.lookup(&kid) {
            Some(k) => k,
            None => {
                if !refresh_attempted {
                    // The refresh the policy grants a kid-miss
                    // (key-rotation case: a new kid published inside the
                    // TTL window). If this call already refreshed above,
                    // that refresh *was* the one.
                    let generation = self.state.lock().unwrap().generation;
                    self.refresh(generation, true).await?;
                }
                self.lookup(&kid).ok_or(OidcError::UnknownKeyId(kid.clone()))?
            }
        };

        // ── Signature + standard claims ───────────────────────────────
        let mut validation = Validation::new(Algorithm::RS256);
        // No grace anywhere (AUTH-8): default leeway is 60 s — zero it.
        validation.leeway = 0;
        // IDENTITY-27: `nbf`, when present, is honoured with the same
        // zero leeway (jsonwebtoken leaves it unchecked by default).
        validation.validate_nbf = true;
        // Trailing-slash tolerance: `Url` normalizes a root issuer to a
        // trailing slash while many IdPs mint `iss` without one (and
        // Auth0 mints *with* one). Both spellings of the *same* issuer
        // are accepted; any other issuer fails.
        let issuer_str = self.config.issuer().as_url().as_str();
        validation.set_issuer(&[issuer_str, issuer_str.trim_end_matches('/')]);
        match self.config.audience_claim() {
            AudienceClaim::Aud => {
                validation.set_audience(&[self.config.audience().as_str()]);
                validation.set_required_spec_claims(&["sub", "exp", "iss", "aud"]);
            }
            AudienceClaim::ClientId => {
                // IDENTITY-30: no `aud` to check; `client_id` is, below.
                validation.validate_aud = false;
                validation.set_required_spec_claims(&["sub", "exp", "iss"]);
            }
        }

        let data = decode::<OidcClaims>(token, &key, &validation).map_err(map_jwt_error)?;
        let claims = data.claims;

        // ── client_id: the audience, where the provider names it there
        //    (WorkOS); absent or another client's ⇒ reject. ─────────────
        if self.config.audience_claim() == AudienceClaim::ClientId
            && claims.extra.get("client_id").and_then(serde_json::Value::as_str) != Some(self.config.audience().as_str())
        {
            return Err(OidcError::WrongAudience);
        }

        // ── iat: required by OidcClaims' non-optional field; must not be
        //    in the future (zero leeway, symmetric with exp). ───────────
        let now = chrono::Utc::now().timestamp();
        if claims.iat > now {
            return Err(OidcError::IssuedInFuture { iat: claims.iat, now });
        }

        // ── Tenancy (UT-S01 D3): org_id → TenantId; absent claim ⇒
        //    valid-but-tenantless; malformed claim ⇒ reject. ───────────
        let tenant = claims
            .org_id
            .as_deref()
            .map(TenantId::try_new)
            .transpose()
            .map_err(OidcError::InvalidTenantClaim)?;

        // ── session_id: AuthContext::is_authenticated() requires a
        //    non-empty session_id; prefer the OIDC `sid`, then `jti`,
        //    then the token's signature segment (stable per token,
        //    non-empty for any signed JWT). ─────────────────────────────
        let session_id = claims
            .sid
            .clone()
            .or_else(|| claims.jti.clone())
            .unwrap_or_else(|| token.rsplit('.').next().unwrap_or_default().to_string());

        let user = VerifiedUser::new_sealed(
            claims.sub,
            claims.iss,
            claims.iat,
            claims.exp,
            tenant,
        );

        Ok(VerifiedToken {
            user,
            roles: claims.roles.unwrap_or_default(),
            username: claims.username,
            session_id,
            extra: claims.extra,
        })
    }

    /// Clone the key for `kid` out of the cache (lock scope stays tiny;
    /// `DecodingKey` is cheaply clonable).
    fn lookup(&self, kid: &str) -> Option<DecodingKey> {
        self.state.lock().unwrap().keys.get(kid).cloned()
    }

    /// Refresh the JWKS (discovering `jwks_uri` first if needed).
    ///
    /// - Success → fresh keys + TTL stored; if the validator was
    ///   degraded, emit `auth_provider_restored`.
    /// - Failure with cached keys → flip to degraded (emit
    ///   `auth_provider_degraded` on the transition), keep serving the
    ///   stale cache. Cached keys remain usable only for tokens whose
    ///   `exp` is still in the future, because `exp` is enforced with
    ///   zero grace regardless (AUTH-8).
    /// - Failure with no cache → error.
    ///
    /// Single-flight (IDENTITY-27): `seen` is the `generation` the caller
    /// read before deciding to refresh. Once it holds `refresh_lock`, a
    /// moved generation means another caller refreshed meanwhile — that
    /// refresh is this one's. A `kid_miss` refresh additionally fetches at
    /// most once per [`KID_MISS_REFRESH_INTERVAL`]; inside it, the cache
    /// stands as it is.
    async fn refresh(&self, seen: u64, kid_miss: bool) -> Result<RefreshOutcome, OidcError> {
        let _flight = self.refresh_lock.lock().await;
        {
            let mut st = self.state.lock().unwrap();
            if st.generation != seen {
                return Self::settled(&st);
            }
            if kid_miss {
                if st.kid_miss_at.is_some_and(|at| at.elapsed() < KID_MISS_REFRESH_INTERVAL) {
                    tracing::debug!(
                        target: "plexus::auth",
                        issuer = %self.config.issuer(),
                        "unknown kid: JWKS refreshed for a kid-miss within the last minute; not refetching"
                    );
                    return Self::settled(&st);
                }
                st.kid_miss_at = Some(Instant::now());
            }
        }
        let fetched = self.try_fetch_keys().await;
        let mut st = self.state.lock().unwrap();
        st.generation += 1;
        match fetched {
            Ok((keys, ttl, jwks_uri)) => {
                st.last_error = None;
                if st.degraded {
                    tracing::info!(
                        target: "plexus::auth",
                        issuer = %self.config.issuer(),
                        "auth_provider_restored: JWKS refresh succeeded; leaving degraded mode"
                    );
                }
                st.keys = keys;
                st.ttl = ttl;
                st.fetched_at = Some(Instant::now());
                st.jwks_uri = Some(jwks_uri);
                st.degraded = false;
                Ok(RefreshOutcome::Fresh)
            }
            Err(err) => {
                st.last_error = Some(err.to_string());
                if st.keys.is_empty() {
                    return Err(err);
                }
                if !st.degraded {
                    st.degraded = true;
                    tracing::warn!(
                        target: "plexus::auth",
                        issuer = %self.config.issuer(),
                        error = %err,
                        "auth_provider_degraded: IdP unreachable; serving cached JWKS \
                         (future-exp tokens only — exp has no grace)"
                    );
                }
                Ok(RefreshOutcome::Degraded)
            }
        }
    }

    /// The outcome of a refresh another caller made (or that the kid-miss
    /// interval skipped): the cache as it stands.
    fn settled(st: &CacheState) -> Result<RefreshOutcome, OidcError> {
        if st.keys.is_empty() {
            if let Some(e) = &st.last_error {
                return Err(OidcError::JwksUnavailable(e.clone()));
            }
        }
        Ok(if st.degraded { RefreshOutcome::Degraded } else { RefreshOutcome::Fresh })
    }

    /// Fetch (and, if needed, discover) the JWKS. Pure fetch+parse; no
    /// state mutation — the caller decides how the result lands.
    async fn try_fetch_keys(
        &self,
    ) -> Result<(HashMap<String, DecodingKey>, Duration, Url), OidcError> {
        let cached_uri = self.state.lock().unwrap().jwks_uri.clone();
        let jwks_uri = match cached_uri {
            Some(u) => u,
            None => self.discover().await?,
        };

        let doc = self
            .fetcher
            .fetch(&jwks_uri)
            .await
            .map_err(|e| OidcError::JwksUnavailable(e.to_string()))?;
        let keys = jwks::parse_jwks(&doc.body).map_err(OidcError::JwksUnavailable)?;
        let ttl = jwks::ttl_from_cache_control(doc.cache_control.as_deref());
        Ok((keys, ttl, jwks_uri))
    }

    /// Fetch the discovery document and extract a trusted `jwks_uri`.
    ///
    /// The document's `issuer` must equal the configured issuer (OIDC
    /// Discovery §4.3 — defends against a misrouted or spoofed discovery
    /// host), trailing-slash tolerant.
    async fn discover(&self) -> Result<Url, OidcError> {
        let url = self.config.discovery_url();
        let doc = self
            .fetcher
            .fetch(&url)
            .await
            .map_err(|e| OidcError::Discovery(e.to_string()))?;
        let parsed: DiscoveryDoc = serde_json::from_str(&doc.body)
            .map_err(|e| OidcError::Discovery(format!("discovery document parse error: {e}")))?;

        let configured = self.config.issuer().as_url().as_str().trim_end_matches('/');
        if parsed.issuer.trim_end_matches('/') != configured {
            return Err(OidcError::Discovery(format!(
                "discovery document issuer {:?} does not match configured issuer {:?}",
                parsed.issuer, configured
            )));
        }

        let jwks_uri = Url::parse(&parsed.jwks_uri)
            .map_err(|e| OidcError::Discovery(format!("invalid jwks_uri: {e}")))?;
        trusted_jwks_uri(self.config.issuer().as_url(), &jwks_uri)?;
        Ok(jwks_uri)
    }
}

/// IDENTITY-27: the discovery document may not point the validator at an
/// arbitrary host. `jwks_uri` is trusted when it is `https`, or when it is
/// on the issuer's own origin (scheme, host and port) — which is what lets
/// a loopback `http` issuer in a test publish its keys beside itself.
fn trusted_jwks_uri(issuer: &Url, jwks_uri: &Url) -> Result<(), OidcError> {
    let same_origin = jwks_uri.scheme() == issuer.scheme()
        && jwks_uri.host_str() == issuer.host_str()
        && jwks_uri.port_or_known_default() == issuer.port_or_known_default();
    if jwks_uri.scheme() == "https" || same_origin {
        Ok(())
    } else {
        Err(OidcError::Discovery(format!(
            "jwks_uri {jwks_uri} is neither https nor on the issuer's origin"
        )))
    }
}

/// Map `jsonwebtoken` failures onto the matrix-relevant variants.
fn map_jwt_error(e: jsonwebtoken::errors::Error) -> OidcError {
    use jsonwebtoken::errors::ErrorKind;
    match e.kind() {
        ErrorKind::ExpiredSignature => OidcError::Expired,
        ErrorKind::ImmatureSignature => OidcError::NotYetValid,
        ErrorKind::InvalidIssuer => OidcError::WrongIssuer,
        ErrorKind::InvalidAudience => OidcError::WrongAudience,
        ErrorKind::InvalidSignature => OidcError::InvalidSignature,
        _ => OidcError::MalformedToken(e.to_string()),
    }
}

/// The successful outcome of [`OidcValidator::validate_token`].
///
/// Wraps the sealed [`VerifiedUser`] proof together with the optional
/// plexus extension claims a backend may want for its `AuthContext`.
/// Sealed like the proof it carries: no public constructor, no public
/// fields — the only mint path is the validator.
#[derive(Debug, Clone)]
pub struct VerifiedToken {
    user: VerifiedUser,
    roles: Vec<String>,
    username: Option<String>,
    session_id: String,
    /// Claims beyond the ones read above, verified with them.
    extra: serde_json::Map<String, serde_json::Value>,
}

impl VerifiedToken {
    /// The sealed proof (claims: `sub`, `iss`, `iat`, `exp`, tenant).
    pub fn user(&self) -> &VerifiedUser {
        &self.user
    }

    /// The verified tenant identity from `org_id`, if the token carried
    /// one. `None` ⇔ valid-but-tenantless (UT-S01 D3).
    pub fn tenant_id(&self) -> Option<&TenantId> {
        self.user.tenant_id()
    }

    /// The `roles` extension claim (empty when absent — optional for
    /// validation per the interchangeability bar).
    pub fn roles(&self) -> &[String] {
        &self.roles
    }

    /// The `username` extension claim, if present.
    pub fn username(&self) -> Option<&str> {
        self.username.as_deref()
    }

    /// Any other verified claim by name: `nickname`, `email`, or a
    /// provider's namespaced claim such as `https://menger.example/roles`.
    /// The claims read into fields above (`sub`, `iss`, `exp`, `iat`,
    /// `org_id`, `sid`, `jti`, `roles`, `username`) are not repeated here.
    pub fn claim(&self, name: &str) -> Option<&serde_json::Value> {
        self.extra.get(name)
    }

    /// The session identifier (`sid`, else `jti`, else the token's
    /// signature segment). Always non-empty, so the
    /// [`AuthContext`] built from this token reports
    /// `is_authenticated() == true`.
    pub fn session_id(&self) -> &str {
        &self.session_id
    }

    /// Build the per-connection [`AuthContext`].
    ///
    /// Metadata written:
    ///
    /// - `org_id` **and** `tenant_id` — the same value under both keys
    ///   for one deprecation window (UT-S01 D3), so pre-cutover
    ///   `ClaimTenantResolver` configurations keep resolving;
    /// - `iss` — the verified issuer;
    /// - `username` — when the extension claim was present;
    /// - `auth_method: "oidc"` — parity with the API-key path's
    ///   `auth_method` marker in the trak reference;
    /// - `expires_at` — the token's `exp`, seconds since the epoch
    ///   (IDENTITY-27).
    pub fn into_auth_context(self) -> AuthContext {
        let mut metadata = serde_json::Map::new();
        if let Some(t) = self.user.tenant_id() {
            let v = serde_json::Value::String(t.as_str().to_string());
            metadata.insert("org_id".into(), v.clone());
            // Deprecation alias — remove after one release window
            // (UT-S01 D3).
            metadata.insert("tenant_id".into(), v);
        }
        metadata.insert(
            "iss".into(),
            serde_json::Value::String(self.user.issuer().to_string()),
        );
        if let Some(u) = &self.username {
            metadata.insert("username".into(), serde_json::Value::String(u.clone()));
        }
        metadata.insert(
            "auth_method".into(),
            serde_json::Value::String("oidc".into()),
        );
        // IDENTITY-27: the token's `exp`, so a service can stop honouring
        // a connection its token no longer vouches for.
        metadata.insert("expires_at".into(), serde_json::Value::from(self.user.expires_at()));

        AuthContext::new(
            self.user.user_id().to_string(),
            self.session_id,
            self.roles,
            serde_json::Value::Object(metadata),
        )
    }
}