rvoip-auth-core 0.3.8

OAuth2 and token-based authentication for RVoIP services
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! JWKS-fetching [`BearerValidator`] for OIDC-style deployments.
//!
//! Connects the [`crate::jwt::JwtValidator`] surface to real identity
//! providers (Auth0, Okta, Cognito, Keycloak, ...) that publish their
//! signing keys at a `/.well-known/jwks.json` endpoint. Behavior:
//!
//! 1. Parse the incoming JWT's *header* (no signature check yet) to
//!    extract the `kid`.
//! 2. Look up the kid in the local cache. Cache miss → fetch the JWKS
//!    document, parse every key, store by kid with the configured TTL.
//! 3. Validate the full token against the resolved [`DecodingKey`] +
//!    the configured [`Validation`].
//! 4. Map `sub` / `scope` / `scopes` to
//!    `rvoip_core::identity::IdentityAssurance::UserAuthorized`.
//!
//! The cache holds parsed keys, not raw JWKS bytes, so the validate hot
//! path is signature-verify only. TTL defaults to 1 hour — typical
//! issuers rotate keys on the order of days, so 1h cache + on-miss
//! refresh handles rotation without thundering-herd refetches.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use async_trait::async_trait;
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use moka::future::Cache;
use rvoip_core_traits::identity::IdentityAssurance;
use rvoip_core_traits::ids::IdentityId;
use serde::Deserialize;
use tracing::{debug, warn};
use url::Url;

use crate::bearer::{
    unix_time_from_seconds, validate_optional_token_id, AuthenticatedPrincipal,
    AuthenticationMethod, BearerAuthError, BearerValidator, ValidatedBearer,
};
use crate::providers::{
    CredentialAuthError, TokenRevocationChecker, TokenRevocationContext, TokenRevocationStatus,
};

/// Default JWKS cache TTL. Issuers typically rotate signing keys on
/// the order of days; 1h covers normal operation without burning
/// requests on every validate. Tune via [`JwksJwtValidator::with_cache_ttl`].
pub const DEFAULT_JWKS_CACHE_TTL: Duration = Duration::from_secs(3600);

/// Maximum number of keys cached. JWKS documents usually carry 1-5
/// keys (current + a small set of rotating ones), so 64 is plenty
/// without paying for an unbounded cache.
const JWKS_CACHE_MAX_CAPACITY: u64 = 64;

#[derive(Deserialize)]
struct JwksDocument {
    keys: Vec<JwksKey>,
}

impl fmt::Debug for JwksDocument {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("JwksDocument")
            .field("key_count", &self.keys.len())
            .finish()
    }
}

#[derive(Deserialize)]
struct JwksKey {
    kty: String,
    kid: Option<String>,
    // RSA fields.
    n: Option<String>,
    e: Option<String>,
    // EC fields.
    #[allow(dead_code)] // surfaced for future per-curve dispatch
    crv: Option<String>,
    x: Option<String>,
    y: Option<String>,
}

impl fmt::Debug for JwksKey {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("JwksKey")
            .field("key_type_class", &jwk_key_type_class(&self.kty))
            .field("key_id_present", &self.kid.is_some())
            .field("key_id_bytes", &self.kid.as_ref().map_or(0, String::len))
            .field("rsa_modulus_present", &self.n.is_some())
            .field("rsa_modulus_bytes", &self.n.as_ref().map_or(0, String::len))
            .field("rsa_exponent_present", &self.e.is_some())
            .field(
                "rsa_exponent_bytes",
                &self.e.as_ref().map_or(0, String::len),
            )
            .field("curve_present", &self.crv.is_some())
            .field("curve_bytes", &self.crv.as_ref().map_or(0, String::len))
            .field("x_coordinate_present", &self.x.is_some())
            .field(
                "x_coordinate_bytes",
                &self.x.as_ref().map_or(0, String::len),
            )
            .field("y_coordinate_present", &self.y.is_some())
            .field(
                "y_coordinate_bytes",
                &self.y.as_ref().map_or(0, String::len),
            )
            .finish()
    }
}

fn jwk_key_type_class(key_type: &str) -> &'static str {
    match key_type {
        "RSA" => "rsa",
        "EC" => "ec",
        "oct" => "symmetric",
        _ => "other",
    }
}

#[derive(Deserialize)]
struct TokenClaims {
    sub: String,
    #[serde(default)]
    iss: Option<String>,
    #[serde(default)]
    iat: Option<u64>,
    #[serde(default)]
    exp: Option<u64>,
    #[serde(default)]
    jti: Option<String>,
    #[serde(default)]
    scope: Option<String>,
    #[serde(default)]
    scopes: Option<Vec<String>>,
    #[serde(default)]
    roles: Option<Vec<String>>,
    #[serde(default)]
    realm_access: Option<RoleAccess>,
    #[serde(default)]
    resource_access: Option<HashMap<String, RoleAccess>>,
    #[serde(default, alias = "tenant", alias = "tid")]
    tenant_id: Option<String>,
}

impl fmt::Debug for TokenClaims {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TokenClaims")
            .field("subject_present", &!self.sub.is_empty())
            .field("issuer_present", &self.iss.is_some())
            .field("issued_at_present", &self.iat.is_some())
            .field("expires_at_present", &self.exp.is_some())
            .field("token_id_present", &self.jti.is_some())
            .field("scope_present", &self.scope.is_some())
            .field("scope_bytes", &self.scope.as_ref().map_or(0, String::len))
            .field(
                "scope_list_count",
                &self.scopes.as_ref().map_or(0, Vec::len),
            )
            .field("role_count", &self.roles.as_ref().map_or(0, Vec::len))
            .field("realm_access_present", &self.realm_access.is_some())
            .field(
                "resource_access_count",
                &self.resource_access.as_ref().map_or(0, HashMap::len),
            )
            .field("tenant_present", &self.tenant_id.is_some())
            .finish()
    }
}

#[derive(Deserialize)]
struct RoleAccess {
    #[serde(default)]
    roles: Vec<String>,
}

impl fmt::Debug for RoleAccess {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RoleAccess")
            .field("role_count", &self.roles.len())
            .finish()
    }
}

/// Bearer validator that resolves signing keys from a remote JWKS
/// endpoint. See module-level docs for behavior. Cheap to clone (the
/// inner state is an Arc).
#[derive(Clone)]
pub struct JwksJwtValidator {
    inner: Arc<Inner>,
}

struct Inner {
    jwks_url: Url,
    client: reqwest::Client,
    cache: Cache<String, DecodingKey>,
    validation: Validation,
    revocation_checker: Option<Arc<dyn TokenRevocationChecker>>,
    require_jti: bool,
}

impl JwksJwtValidator {
    /// Build a validator against the given JWKS URL. The JWKS isn't
    /// fetched until the first validate call (lazy bootstrap so
    /// construction can't fail on transient network errors). Default
    /// algorithm: RS256 (the dominant OIDC choice). Callers needing
    /// ES256 / EdDSA tokens override via [`Self::with_algorithms`].
    pub fn new(jwks_url: Url) -> Self {
        let mut validation = Validation::new(Algorithm::RS256);
        validation.validate_aud = false;
        Self::new_with_validation(jwks_url, validation)
    }

    /// Variant with an explicit `Validation` config (allows tuning
    /// algorithms, leeway, required claims). Most callers should use
    /// [`Self::new`] + the `with_*` builders.
    pub fn new_with_validation(jwks_url: Url, validation: Validation) -> Self {
        let client = reqwest::Client::builder()
            .user_agent("rvoip-auth-core/0.1 (jwks)")
            .timeout(Duration::from_secs(10))
            .build()
            .expect("reqwest::Client::builder default config never fails");
        Self {
            inner: Arc::new(Inner {
                jwks_url,
                client,
                cache: Cache::builder()
                    .max_capacity(JWKS_CACHE_MAX_CAPACITY)
                    .time_to_live(DEFAULT_JWKS_CACHE_TTL)
                    .build(),
                validation,
                revocation_checker: None,
                require_jti: false,
            }),
        }
    }

    /// Override the JWKS cache TTL. Drops the existing cache contents
    /// (call before tokens start flowing).
    pub fn with_cache_ttl(self, ttl: Duration) -> Self {
        let inner = &*self.inner;
        let new_cache = Cache::builder()
            .max_capacity(JWKS_CACHE_MAX_CAPACITY)
            .time_to_live(ttl)
            .build();
        Self {
            inner: Arc::new(Inner {
                jwks_url: inner.jwks_url.clone(),
                client: inner.client.clone(),
                cache: new_cache,
                validation: inner.validation.clone(),
                revocation_checker: inner.revocation_checker.clone(),
                require_jti: inner.require_jti,
            }),
        }
    }

    /// Require the token's `aud` claim to match one of `audiences`.
    pub fn with_audience<I, S>(self, audiences: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let inner = &*self.inner;
        let mut validation = inner.validation.clone();
        let auds: HashSet<String> = audiences
            .into_iter()
            .map(|s| s.as_ref().to_string())
            .collect();
        validation.set_audience(&auds.into_iter().collect::<Vec<_>>());
        validation.validate_aud = true;
        Self {
            inner: Arc::new(Inner {
                jwks_url: inner.jwks_url.clone(),
                client: inner.client.clone(),
                cache: inner.cache.clone(),
                validation,
                revocation_checker: inner.revocation_checker.clone(),
                require_jti: inner.require_jti,
            }),
        }
    }

    /// Require the token's `iss` claim to match one of `issuers`.
    pub fn with_issuer<I, S>(self, issuers: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let inner = &*self.inner;
        let mut validation = inner.validation.clone();
        validation.set_issuer(
            &issuers
                .into_iter()
                .map(|s| s.as_ref().to_string())
                .collect::<Vec<_>>(),
        );
        Self {
            inner: Arc::new(Inner {
                jwks_url: inner.jwks_url.clone(),
                client: inner.client.clone(),
                cache: inner.cache.clone(),
                validation,
                revocation_checker: inner.revocation_checker.clone(),
                require_jti: inner.require_jti,
            }),
        }
    }

    /// Restrict allowed algorithms (default is RS256 + ES256).
    pub fn with_algorithms(self, algorithms: Vec<Algorithm>) -> Self {
        let inner = &*self.inner;
        let mut validation = inner.validation.clone();
        validation.algorithms = algorithms;
        Self {
            inner: Arc::new(Inner {
                jwks_url: inner.jwks_url.clone(),
                client: inner.client.clone(),
                cache: inner.cache.clone(),
                validation,
                revocation_checker: inner.revocation_checker.clone(),
                require_jti: inner.require_jti,
            }),
        }
    }

    /// Reject JWTs whose `jti` appears in a revocation store.
    ///
    /// When configured, tokens without a `jti` claim are rejected because they
    /// cannot participate in revocation checks.
    pub fn with_revocation_checker(self, checker: Arc<dyn TokenRevocationChecker>) -> Self {
        let inner = &*self.inner;
        Self {
            inner: Arc::new(Inner {
                jwks_url: inner.jwks_url.clone(),
                client: inner.client.clone(),
                cache: inner.cache.clone(),
                validation: inner.validation.clone(),
                revocation_checker: Some(checker),
                require_jti: inner.require_jti,
            }),
        }
    }

    /// Require a non-empty, bounded JWT `jti` even without a revocation store.
    ///
    /// Production deployments that use token IDs for replay, lease, or audit
    /// correlation should enable this policy. Configuring a revocation checker
    /// already requires `jti` regardless of this setting.
    pub fn with_required_jti(self) -> Self {
        let inner = &*self.inner;
        Self {
            inner: Arc::new(Inner {
                jwks_url: inner.jwks_url.clone(),
                client: inner.client.clone(),
                cache: inner.cache.clone(),
                validation: inner.validation.clone(),
                revocation_checker: inner.revocation_checker.clone(),
                require_jti: true,
            }),
        }
    }

    /// Build into a `Arc<dyn BearerValidator>` for adapter config.
    pub fn into_arc(self) -> Arc<dyn BearerValidator> {
        Arc::new(self)
    }

    /// Resolve a signing key for `kid` from the cache, fetching the
    /// JWKS document on cache miss. Keys with unsupported `kty` /
    /// missing components are skipped silently; an `Invalid` error
    /// surfaces only when the kid still isn't found after a fresh
    /// fetch.
    async fn resolve_key(&self, kid: &str) -> Result<DecodingKey, BearerAuthError> {
        if let Some(key) = self.inner.cache.get(kid).await {
            return Ok(key);
        }
        // Cache miss — fetch JWKS, populate every parseable key, then
        // re-check the cache for the kid we want.
        debug!(
            key_id_present = !kid.is_empty(),
            "jwks: cache miss, refetching"
        );
        let doc = self.fetch_jwks().await?;
        for jwk in doc.keys {
            let Some(jwk_kid) = jwk.kid.clone() else {
                // No kid on this entry — skip; we can't address it
                // from the token header.
                continue;
            };
            match decoding_key_from_jwk(&jwk) {
                Ok(key) => {
                    self.inner.cache.insert(jwk_kid, key).await;
                }
                Err(_) => {
                    warn!(
                        key_id_present = !jwk_kid.is_empty(),
                        error_class = "invalid-jwk",
                        "jwks: skipping unparseable key"
                    );
                }
            }
        }
        self.inner
            .cache
            .get(kid)
            .await
            .ok_or_else(|| BearerAuthError::Invalid(format!("no signing key for kid={}", kid)))
    }

    async fn fetch_jwks(&self) -> Result<JwksDocument, BearerAuthError> {
        let resp = self
            .inner
            .client
            .get(self.inner.jwks_url.clone())
            .send()
            .await
            .map_err(|e| BearerAuthError::Unavailable(format!("JWKS fetch: {e}")))?;
        if !resp.status().is_success() {
            return Err(BearerAuthError::Unavailable(format!(
                "JWKS endpoint returned {}",
                resp.status()
            )));
        }
        resp.json::<JwksDocument>()
            .await
            .map_err(|e| BearerAuthError::Unavailable(format!("JWKS parse: {e}")))
    }
}

fn decoding_key_from_jwk(jwk: &JwksKey) -> Result<DecodingKey, BearerAuthError> {
    match jwk.kty.as_str() {
        "RSA" => {
            let n = jwk
                .n
                .as_deref()
                .ok_or_else(|| BearerAuthError::Invalid("RSA jwk missing n".into()))?;
            let e = jwk
                .e
                .as_deref()
                .ok_or_else(|| BearerAuthError::Invalid("RSA jwk missing e".into()))?;
            DecodingKey::from_rsa_components(n, e)
                .map_err(|err| BearerAuthError::Invalid(format!("RSA jwk: {err}")))
        }
        "EC" => {
            let x = jwk
                .x
                .as_deref()
                .ok_or_else(|| BearerAuthError::Invalid("EC jwk missing x".into()))?;
            let y = jwk
                .y
                .as_deref()
                .ok_or_else(|| BearerAuthError::Invalid("EC jwk missing y".into()))?;
            // `from_ec_components` requires `crv` info implicitly via
            // jsonwebtoken's algorithm match. We pass x/y; downstream
            // validation enforces the right algorithm.
            let _ = jwk.crv.as_deref().unwrap_or("P-256");
            DecodingKey::from_ec_components(x, y)
                .map_err(|err| BearerAuthError::Invalid(format!("EC jwk: {err}")))
        }
        "oct" => {
            // RFC 7518 §6.4 oct (symmetric) keys are uncommon in JWKS
            // and call for a separate validator anyway — the JWKS
            // path's whole point is asymmetric verification with
            // public keys distributed via the well-known endpoint.
            // Callers with shared secrets should use
            // `JwtValidator::from_hmac_secret` directly.
            Err(BearerAuthError::Invalid(
                "oct (symmetric) keys in JWKS not supported; use HMAC JwtValidator directly".into(),
            ))
        }
        other => Err(BearerAuthError::Invalid(format!("unsupported kty={other}"))),
    }
}

#[async_trait]
impl BearerValidator for JwksJwtValidator {
    async fn validate(&self, token: &str) -> Result<IdentityAssurance, BearerAuthError> {
        Ok(self.validate_credential(token).await?.principal.assurance)
    }

    async fn validate_principal(
        &self,
        token: &str,
    ) -> Result<AuthenticatedPrincipal, BearerAuthError> {
        Ok(self.validate_credential(token).await?.principal)
    }

    async fn validate_credential(&self, token: &str) -> Result<ValidatedBearer, BearerAuthError> {
        if token.is_empty() {
            return Err(BearerAuthError::Empty);
        }
        // 1. Parse header to extract kid. Tokens without a kid can't
        // be resolved against JWKS; reject them up front.
        let header =
            decode_header(token).map_err(|e| BearerAuthError::Invalid(format!("header: {e}")))?;
        let kid = header
            .kid
            .as_ref()
            .ok_or_else(|| BearerAuthError::Invalid("token header missing kid".into()))?;

        // 2. Resolve signing key (cache lookup or JWKS refetch).
        let key = self.resolve_key(kid).await?;

        // 3. Validate the full token.
        let data = decode::<TokenClaims>(token, &key, &self.inner.validation)
            .map_err(|e| BearerAuthError::Invalid(e.to_string()))?;
        let claims = data.claims;
        let token_id = validate_optional_token_id(claims.jti.clone())?;
        if self.inner.require_jti && token_id.is_none() {
            return Err(BearerAuthError::Invalid(
                "token missing required jti".into(),
            ));
        }
        let issued_at = claims
            .iat
            .map(|iat| unix_time_from_seconds(iat, "iat"))
            .transpose()?;
        let expires_at_system = claims
            .exp
            .map(|exp| unix_time_from_seconds(exp, "exp"))
            .transpose()?;
        let revocation_context = revocation_context_from_claims(
            &claims,
            token_id.as_deref(),
            issued_at,
            expires_at_system,
        );
        check_revocation(
            self.inner.revocation_checker.as_ref(),
            revocation_context.as_ref(),
        )
        .await?;

        // 4. Preserve the authorization claims alongside the legacy
        // IdentityAssurance projection.
        let subject = claims.sub.clone();
        let expires_at = claims.exp.map(expiration_from_unix).transpose()?;
        let identity = IdentityId::from_string(subject.clone());
        let scopes = scopes_from_claims(
            claims.scope,
            claims.scopes,
            claims.roles,
            claims.realm_access,
            claims.resource_access,
        );
        let assurance = IdentityAssurance::UserAuthorized {
            identity: identity.clone(),
            user_id: identity,
            scopes: scopes.clone(),
        };
        ValidatedBearer::new(
            AuthenticatedPrincipal {
                subject,
                tenant: claims.tenant_id,
                scopes,
                issuer: claims.iss,
                expires_at,
                method: AuthenticationMethod::Oidc,
                assurance,
            },
            token_id,
            issued_at,
        )
    }
}

fn expiration_from_unix(seconds: u64) -> Result<chrono::DateTime<chrono::Utc>, BearerAuthError> {
    i64::try_from(seconds)
        .ok()
        .and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
        .ok_or_else(|| BearerAuthError::Invalid("token exp is outside the supported range".into()))
}

async fn check_revocation(
    checker: Option<&Arc<dyn TokenRevocationChecker>>,
    context: Option<&TokenRevocationContext>,
) -> Result<(), BearerAuthError> {
    let Some(checker) = checker else {
        return Ok(());
    };
    let Some(context) = context else {
        return Err(BearerAuthError::Invalid(
            "token missing jti for revocation check".into(),
        ));
    };
    match checker.check_token(context).await {
        Ok(TokenRevocationStatus::Active) => Ok(()),
        Ok(TokenRevocationStatus::Revoked) => Err(BearerAuthError::Invalid("token revoked".into())),
        Err(CredentialAuthError::Invalid) | Err(CredentialAuthError::PolicyRejected(_)) => Err(
            BearerAuthError::Invalid("revocation check rejected token".into()),
        ),
        Err(CredentialAuthError::Unavailable(err)) => Err(BearerAuthError::Unavailable(err)),
    }
}

fn revocation_context_from_claims(
    claims: &TokenClaims,
    token_id: Option<&str>,
    issued_at: Option<SystemTime>,
    expires_at: Option<SystemTime>,
) -> Option<TokenRevocationContext> {
    let mut context = TokenRevocationContext::new(token_id?).with_subject(claims.sub.clone());
    if let Some(issuer) = claims.iss.clone() {
        context = context.with_issuer(issuer);
    }
    context = context.with_times(issued_at, expires_at);
    Some(context)
}

fn scopes_from_claims(
    scope: Option<String>,
    scopes: Option<Vec<String>>,
    roles: Option<Vec<String>>,
    realm_access: Option<RoleAccess>,
    resource_access: Option<HashMap<String, RoleAccess>>,
) -> Vec<String> {
    let mut values = Vec::new();
    if let Some(scope) = scope {
        values.extend(scope.split_whitespace().map(str::to_string));
    }
    if let Some(scopes) = scopes {
        for scope in scopes {
            push_unique(&mut values, scope);
        }
    }
    if let Some(roles) = roles {
        for role in roles {
            push_unique(&mut values, format!("role:{role}"));
        }
    }
    if let Some(realm_access) = realm_access {
        for role in realm_access.roles {
            push_unique(&mut values, format!("realm:{role}"));
        }
    }
    if let Some(resource_access) = resource_access {
        for (client, access) in resource_access {
            for role in access.roles {
                push_unique(&mut values, format!("{client}:{role}"));
            }
        }
    }
    values
}

fn push_unique(values: &mut Vec<String>, value: String) {
    if !values.contains(&value) {
        values.push(value);
    }
}

#[cfg(test)]
mod diagnostic_tests {
    use super::*;

    const CANARY: &str = "jwks-claims-malicious-canary\r\nAuthorization: exposed";

    #[test]
    fn decoded_jwks_keys_keep_exact_values_out_of_debug() {
        let document: JwksDocument = serde_json::from_value(serde_json::json!({
            "keys": [{
                "kty": CANARY,
                "kid": CANARY,
                "n": CANARY,
                "e": CANARY,
                "crv": CANARY,
                "x": CANARY,
                "y": CANARY,
            }]
        }))
        .unwrap();

        let key = &document.keys[0];
        for rendered in [format!("{document:?}"), format!("{key:?}")] {
            assert!(!rendered.contains(CANARY), "JWKS value leaked: {rendered}");
        }
        assert_eq!(key.kty, CANARY);
        assert_eq!(key.kid.as_deref(), Some(CANARY));
        assert_eq!(key.n.as_deref(), Some(CANARY));
        assert_eq!(key.e.as_deref(), Some(CANARY));
        assert_eq!(key.crv.as_deref(), Some(CANARY));
        assert_eq!(key.x.as_deref(), Some(CANARY));
        assert_eq!(key.y.as_deref(), Some(CANARY));
        assert_eq!(jwk_key_type_class(&key.kty), "other");
    }

    #[test]
    fn decoded_claims_keep_values_out_of_debug() {
        let claims: TokenClaims = serde_json::from_value(serde_json::json!({
            "sub": CANARY,
            "iss": CANARY,
            "iat": 1,
            "exp": 2,
            "jti": CANARY,
            "scope": CANARY,
            "scopes": [CANARY],
            "roles": [CANARY],
            "realm_access": { "roles": [CANARY] },
            "resource_access": { (CANARY): { "roles": [CANARY] } },
            "tenant_id": CANARY,
        }))
        .unwrap();

        for rendered in [
            format!("{claims:?}"),
            format!("{:?}", claims.realm_access.as_ref().unwrap()),
            format!(
                "{:?}",
                claims
                    .resource_access
                    .as_ref()
                    .unwrap()
                    .get(CANARY)
                    .unwrap()
            ),
        ] {
            assert!(!rendered.contains(CANARY), "claim leaked: {rendered}");
        }

        assert_eq!(claims.sub, CANARY);
        assert_eq!(claims.iss.as_deref(), Some(CANARY));
        assert_eq!(claims.jti.as_deref(), Some(CANARY));
        assert_eq!(claims.scope.as_deref(), Some(CANARY));
        assert_eq!(claims.scopes.as_deref(), Some(&[CANARY.to_string()][..]));
        assert_eq!(claims.roles.as_deref(), Some(&[CANARY.to_string()][..]));
        assert_eq!(claims.tenant_id.as_deref(), Some(CANARY));
        assert_eq!(
            claims.realm_access.as_ref().unwrap().roles,
            [CANARY.to_string()]
        );
        assert_eq!(
            claims.resource_access.as_ref().unwrap()[CANARY].roles,
            [CANARY.to_string()]
        );
    }
}