Skip to main content

grow_oidc/
oidc.rs

1//! Provider-neutral OIDC access-token verification (service-owned).
2//!
3//! JWKS discovery, caching and rotation; RS256/384/512, PS256/384/512, ES256, ES384 and EdDSA (via
4//! `ring`, which has no P-521, so ES512 is not supported); `iss`/`aud`/`exp`/`nbf` checks with a
5//! clock skew (default 60 s); roles from a configurable claim.
6
7use std::collections::HashMap;
8use std::fmt;
9use std::sync::{Arc, RwLock};
10use std::time::{Duration, SystemTime, UNIX_EPOCH};
11
12use base64::engine::general_purpose::URL_SAFE_NO_PAD;
13use base64::Engine as _;
14use ring::signature::{self, UnparsedPublicKey};
15use serde_json::{Map, Value};
16
17use crate::core::{Error, ErrorCode, Result};
18
19/// Accepted algorithms by default: every supported one (asymmetric only; `none` and HMAC are never
20/// accepted). ES512 is not supported (`ring` has no P-521).
21pub const DEFAULT_ALGORITHMS: [&str; 9] = [
22    "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "EdDSA",
23];
24/// Default tolerance applied to `exp` and `nbf`.
25pub const DEFAULT_CLOCK_SKEW: Duration = Duration::from_secs(60);
26/// Default JWKS cache lifetime.
27pub const DEFAULT_JWKS_CACHE_TTL: Duration = Duration::from_secs(600);
28/// Default minimum interval between two unknown-`kid` refetches.
29pub const DEFAULT_JWKS_REFRESH_COOLDOWN: Duration = Duration::from_secs(30);
30/// Default timeout of discovery and JWKS requests.
31pub const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(10);
32
33/// The authenticated user of a verified access token.
34#[derive(Debug, Clone, PartialEq)]
35pub struct AuthUser {
36    /// `sub` claim.
37    pub sub: String,
38    /// `email` claim when present.
39    pub email: Option<String>,
40    /// `name` claim, else `preferred_username`, when present.
41    pub name: Option<String>,
42    /// Role names from the roles claim (strings, or Casdoor-style `{name}` objects).
43    pub roles: Vec<String>,
44    /// Every claim of the token.
45    pub claims: Map<String, Value>,
46}
47
48impl AuthUser {
49    /// True when the user has at least one of `roles` (case-insensitive).
50    pub fn has_role(&self, roles: &[&str]) -> bool {
51        has_any_role(&self.roles, roles)
52    }
53}
54
55/// A clock returning the current time (tests inject a fake one).
56pub type ClockFn = Arc<dyn Fn() -> SystemTime + Send + Sync>;
57
58/// Options of a [`Verifier`]. `Default` gives the documented defaults (issuer/audience empty).
59#[derive(Clone)]
60pub struct VerifierOptions {
61    /// Expected `iss` (exact, except that trailing slashes on either side are ignored); discovery
62    /// uses `<issuer without trailing slashes>/.well-known/openid-configuration`.
63    pub issuer: String,
64    /// Expected `aud` (the token's `aud` must contain it).
65    pub audience: String,
66    /// JWKS URL; skips discovery when set.
67    pub jwks_url: Option<String>,
68    /// Claim (or dotted path such as `realm_access.roles`) with the roles; default `roles`.
69    pub roles_claim: Option<String>,
70    /// Allow-list, a subset of [`DEFAULT_ALGORITHMS`]; empty = all of them.
71    pub algorithms: Vec<String>,
72    /// `exp`/`nbf` tolerance (default 60 s).
73    pub clock_skew: Duration,
74    /// JWKS cache lifetime (default 10 min).
75    pub jwks_cache_ttl: Duration,
76    /// Minimum interval between unknown-`kid` refetches (default 30 s).
77    pub jwks_refresh_cooldown: Duration,
78    /// Timeout of discovery/JWKS requests (default 10 s).
79    pub http_timeout: Duration,
80    /// HTTP client (proxies, TLS); default a new client with `http_timeout`.
81    pub http_client: Option<reqwest::Client>,
82    /// Clock (tests); default `SystemTime::now`.
83    pub now: Option<ClockFn>,
84}
85
86impl Default for VerifierOptions {
87    fn default() -> Self {
88        Self {
89            issuer: String::new(),
90            audience: String::new(),
91            jwks_url: None,
92            roles_claim: None,
93            algorithms: Vec::new(),
94            clock_skew: DEFAULT_CLOCK_SKEW,
95            jwks_cache_ttl: DEFAULT_JWKS_CACHE_TTL,
96            jwks_refresh_cooldown: DEFAULT_JWKS_REFRESH_COOLDOWN,
97            http_timeout: DEFAULT_HTTP_TIMEOUT,
98            http_client: None,
99            now: None,
100        }
101    }
102}
103
104impl fmt::Debug for VerifierOptions {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        f.debug_struct("VerifierOptions")
107            .field("issuer", &self.issuer)
108            .field("audience", &self.audience)
109            .field("jwks_url", &self.jwks_url)
110            .field("roles_claim", &self.roles_claim)
111            .field("algorithms", &self.algorithms)
112            .field("clock_skew", &self.clock_skew)
113            .finish_non_exhaustive()
114    }
115}
116
117#[derive(Clone)]
118struct Key {
119    kid: Option<String>,
120    alg: Option<String>,
121    usage: Option<String>,
122    kind: KeyKind,
123}
124
125#[derive(Clone, Copy, PartialEq, Eq)]
126enum Curve {
127    P256,
128    P384,
129}
130
131#[derive(Clone)]
132enum KeyKind {
133    Rsa { n: Vec<u8>, e: Vec<u8> },
134    Ec { curve: Curve, point: Vec<u8> },
135    Ed(Vec<u8>),
136}
137
138/// How `ring` verifies one algorithm.
139enum Verification {
140    Rsa(&'static signature::RsaParameters),
141    Raw(&'static dyn signature::VerificationAlgorithm),
142}
143
144/// The `ring` verification for `alg` with a key of `kind`, or `None` when the key type (and the
145/// curve of an EC key) does not match `alg`: the token header never picks a mismatching algorithm.
146fn verification(kind: &KeyKind, alg: &str) -> Option<Verification> {
147    use Verification::{Raw, Rsa};
148    Some(match (kind, alg) {
149        (KeyKind::Rsa { .. }, "RS256") => Rsa(&signature::RSA_PKCS1_2048_8192_SHA256),
150        (KeyKind::Rsa { .. }, "RS384") => Rsa(&signature::RSA_PKCS1_2048_8192_SHA384),
151        (KeyKind::Rsa { .. }, "RS512") => Rsa(&signature::RSA_PKCS1_2048_8192_SHA512),
152        (KeyKind::Rsa { .. }, "PS256") => Rsa(&signature::RSA_PSS_2048_8192_SHA256),
153        (KeyKind::Rsa { .. }, "PS384") => Rsa(&signature::RSA_PSS_2048_8192_SHA384),
154        (KeyKind::Rsa { .. }, "PS512") => Rsa(&signature::RSA_PSS_2048_8192_SHA512),
155        (
156            KeyKind::Ec {
157                curve: Curve::P256, ..
158            },
159            "ES256",
160        ) => Raw(&signature::ECDSA_P256_SHA256_FIXED),
161        (
162            KeyKind::Ec {
163                curve: Curve::P384, ..
164            },
165            "ES384",
166        ) => Raw(&signature::ECDSA_P384_SHA384_FIXED),
167        (KeyKind::Ed(_), "EdDSA") => Raw(&signature::ED25519),
168        _ => return None,
169    })
170}
171
172impl Key {
173    fn compatible(&self, alg: &str) -> bool {
174        if self.usage.as_deref() == Some("enc") || self.alg.as_deref().is_some_and(|a| a != alg) {
175            return false;
176        }
177        verification(&self.kind, alg).is_some()
178    }
179
180    fn verify(&self, alg: &str, signed: &[u8], sig: &[u8]) -> bool {
181        match (verification(&self.kind, alg), &self.kind) {
182            (Some(Verification::Rsa(params)), KeyKind::Rsa { n, e }) => {
183                signature::RsaPublicKeyComponents { n, e }
184                    .verify(params, signed, sig)
185                    .is_ok()
186            }
187            (
188                Some(Verification::Raw(algorithm)),
189                KeyKind::Ec { point: bytes, .. } | KeyKind::Ed(bytes),
190            ) => UnparsedPublicKey::new(algorithm, bytes)
191                .verify(signed, sig)
192                .is_ok(),
193            _ => false,
194        }
195    }
196}
197
198fn b64(text: &str) -> Option<Vec<u8>> {
199    URL_SAFE_NO_PAD.decode(text.trim_end_matches('=')).ok()
200}
201
202fn parse_key(raw: &Value) -> Option<Key> {
203    let obj = raw.as_object()?;
204    let text = |name: &str| obj.get(name).and_then(Value::as_str).map(str::to_owned);
205    let field = |name: &str| text(name).as_deref().and_then(b64);
206    let kind = match (text("kty").as_deref(), text("crv").as_deref()) {
207        (Some("RSA"), _) => {
208            let (n, e) = (field("n")?, field("e")?);
209            (n.len() >= 256 && !e.is_empty()).then_some(KeyKind::Rsa { n, e })?
210        }
211        (Some("EC"), Some(crv @ ("P-256" | "P-384"))) => {
212            let (curve, size) = if crv == "P-256" {
213                (Curve::P256, 32)
214            } else {
215                (Curve::P384, 48)
216            };
217            let (x, y) = (field("x")?, field("y")?);
218            if x.len() != size || y.len() != size {
219                return None;
220            }
221            let mut point = vec![4u8];
222            point.extend_from_slice(&x);
223            point.extend_from_slice(&y);
224            KeyKind::Ec { curve, point }
225        }
226        (Some("OKP"), Some("Ed25519")) => {
227            let x = field("x")?;
228            (x.len() == 32).then_some(KeyKind::Ed(x))?
229        }
230        _ => return None,
231    };
232    Some(Key {
233        kid: text("kid"),
234        alg: text("alg"),
235        usage: text("use"),
236        kind,
237    })
238}
239
240struct KeySet {
241    keys: Vec<Key>,
242    fetched_at: SystemTime,
243}
244
245struct Inner {
246    issuer: String,
247    audience: String,
248    roles_claim: String,
249    jwks_url: Option<String>,
250    algorithms: Vec<String>,
251    skew: Duration,
252    ttl: Duration,
253    cooldown: Duration,
254    http: reqwest::Client,
255    now: ClockFn,
256    resolved: RwLock<Option<String>>,
257    keys: RwLock<Option<Arc<KeySet>>>,
258    fetch: tokio::sync::Mutex<()>,
259}
260
261/// Verifies OIDC access tokens (JWT) against the issuer's JWKS. Cheap to clone; thread-safe.
262///
263/// Errors: [`Error::Authentication`] for every invalid token (the message names the failed check,
264/// never the token), [`Error::Unavailable`] when discovery or the JWKS cannot be fetched and
265/// [`Error::Config`] for invalid options.
266#[derive(Clone)]
267pub struct Verifier {
268    inner: Arc<Inner>,
269}
270
271impl fmt::Debug for Verifier {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        f.debug_struct("Verifier")
274            .field("issuer", &self.inner.issuer)
275            .field("audience", &self.inner.audience)
276            .finish_non_exhaustive()
277    }
278}
279
280fn check_url(name: &str, value: &str) -> Result<()> {
281    match url::Url::parse(value) {
282        Ok(u) if (u.scheme() == "http" || u.scheme() == "https") && u.has_host() => Ok(()),
283        _ => Err(Error::config(format!(
284            "oidc: {name} must be an http or https URL"
285        ))),
286    }
287}
288
289fn auth(reason: impl fmt::Display) -> Error {
290    Error::new(ErrorCode::Authentication, format!("verify: {reason}"))
291}
292
293fn non_empty(value: Option<&String>) -> Option<String> {
294    value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())
295}
296
297impl Verifier {
298    /// Validates `options` and builds a verifier (no network call).
299    pub fn new(options: VerifierOptions) -> Result<Self> {
300        let issuer = options.issuer.trim().to_owned();
301        let audience = options.audience.trim().to_owned();
302        if issuer.is_empty() {
303            return Err(Error::config("oidc: issuer is required"));
304        }
305        if audience.is_empty() {
306            return Err(Error::config("oidc: audience is required"));
307        }
308        check_url("issuer", &issuer)?;
309        let jwks_url = non_empty(options.jwks_url.as_ref());
310        if let Some(url) = &jwks_url {
311            check_url("jwks_url", url)?;
312        }
313        let algorithms = if options.algorithms.is_empty() {
314            DEFAULT_ALGORITHMS.iter().map(|a| (*a).to_owned()).collect()
315        } else {
316            options.algorithms.clone()
317        };
318        if algorithms
319            .iter()
320            .any(|a| !DEFAULT_ALGORITHMS.contains(&a.as_str()))
321        {
322            return Err(Error::config(
323                "oidc: algorithms must be a subset of RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, EdDSA",
324            ));
325        }
326        let http = match options.http_client {
327            Some(client) => client,
328            None => reqwest::Client::builder()
329                .timeout(options.http_timeout)
330                .build()
331                .map_err(|e| Error::config("oidc: cannot build the HTTP client").with_source(e))?,
332        };
333        Ok(Self {
334            inner: Arc::new(Inner {
335                issuer,
336                audience,
337                roles_claim: non_empty(options.roles_claim.as_ref())
338                    .unwrap_or_else(|| "roles".into()),
339                jwks_url,
340                algorithms,
341                skew: options.clock_skew,
342                ttl: options.jwks_cache_ttl,
343                cooldown: options.jwks_refresh_cooldown,
344                http,
345                now: options.now.unwrap_or_else(|| Arc::new(SystemTime::now)),
346                resolved: RwLock::new(None),
347                keys: RwLock::new(None),
348                fetch: tokio::sync::Mutex::new(()),
349            }),
350        })
351    }
352
353    /// Builds a verifier from `GROW_AUTH_ISSUER` (required), `GROW_AUTH_AUDIENCE` (default
354    /// `GROW_AUTH_CLIENT_ID`), `GROW_AUTH_JWKS_URL`, `GROW_AUTH_ROLES_CLAIM` (default `roles`) and
355    /// `GROW_AUTH_CLOCK_SKEW` (duration, default `60s`).
356    pub fn from_env() -> Result<Self> {
357        Self::from_env_map(&std::env::vars().collect())
358    }
359
360    /// [`Verifier::from_env`] with an explicit environment map (tests).
361    pub fn from_env_map(env: &HashMap<String, String>) -> Result<Self> {
362        let get = |name: &str| non_empty(env.get(name));
363        let issuer = get("GROW_AUTH_ISSUER")
364            .ok_or_else(|| Error::config("oidc: GROW_AUTH_ISSUER is required"))?;
365        let audience = get("GROW_AUTH_AUDIENCE")
366            .or_else(|| get("GROW_AUTH_CLIENT_ID"))
367            .ok_or_else(|| {
368                Error::config("oidc: GROW_AUTH_AUDIENCE (or GROW_AUTH_CLIENT_ID) is required")
369            })?;
370        let mut options = VerifierOptions {
371            issuer,
372            audience,
373            jwks_url: get("GROW_AUTH_JWKS_URL"),
374            roles_claim: get("GROW_AUTH_ROLES_CLAIM"),
375            ..VerifierOptions::default()
376        };
377        if let Some(skew) = get("GROW_AUTH_CLOCK_SKEW") {
378            options.clock_skew = crate::core::parse_duration(&skew)
379                .ok_or_else(|| Error::config("oidc: GROW_AUTH_CLOCK_SKEW is not a duration"))?;
380        }
381        Self::new(options)
382    }
383
384    /// The expected issuer.
385    pub fn issuer(&self) -> &str {
386        &self.inner.issuer
387    }
388
389    /// The expected audience.
390    pub fn audience(&self) -> &str {
391        &self.inner.audience
392    }
393
394    /// The roles claim path.
395    pub fn roles_claim(&self) -> &str {
396        &self.inner.roles_claim
397    }
398
399    /// The `exp`/`nbf` tolerance.
400    pub fn clock_skew(&self) -> Duration {
401        self.inner.skew
402    }
403
404    /// Drops the cached JWKS so the next verification refetches it.
405    pub fn clear_cache(&self) {
406        *self.inner.keys.write().unwrap_or_else(|e| e.into_inner()) = None;
407    }
408
409    /// Verifies a raw JWT access token and returns its user.
410    pub async fn verify(&self, token: &str) -> Result<AuthUser> {
411        let parts: Vec<&str> = token.split('.').collect();
412        let [head, payload, sig] = parts.as_slice() else {
413            return Err(auth("malformed token"));
414        };
415        let header: Map<String, Value> = b64(head)
416            .and_then(|raw| serde_json::from_slice(&raw).ok())
417            .ok_or_else(|| auth("malformed token header"))?;
418        let alg = header.get("alg").and_then(Value::as_str).unwrap_or("");
419        if !self.inner.algorithms.iter().any(|a| a == alg) {
420            let shown: String = if alg.is_empty() {
421                "(none)".into()
422            } else {
423                alg.chars().take(16).collect()
424            };
425            return Err(auth(format_args!("algorithm {shown} is not allowed")));
426        }
427        let kid = header.get("kid").and_then(Value::as_str);
428        let claims: Map<String, Value> = b64(payload)
429            .and_then(|raw| serde_json::from_slice(&raw).ok())
430            .ok_or_else(|| auth("malformed token payload"))?;
431        let sig = b64(sig).ok_or_else(|| auth("malformed token signature"))?;
432
433        let mut set = self.key_set(false).await?;
434        let elapsed = (self.inner.now)()
435            .duration_since(set.fetched_at)
436            .unwrap_or_default();
437        if matching(&set, alg, kid).is_empty() && kid.is_some() && elapsed >= self.inner.cooldown {
438            set = self.key_set(true).await?;
439        }
440        let candidates = matching(&set, alg, kid);
441        if candidates.is_empty() {
442            return Err(auth(format_args!(
443                "no key matches kid {}",
444                kid.unwrap_or("(none)")
445            )));
446        }
447        let signed = format!("{head}.{payload}");
448        if !candidates
449            .iter()
450            .any(|k| k.verify(alg, signed.as_bytes(), &sig))
451        {
452            return Err(auth("signature is invalid"));
453        }
454        self.check_claims(&claims)?;
455        Ok(self.to_user(claims))
456    }
457
458    fn check_claims(&self, claims: &Map<String, Value>) -> Result<()> {
459        let i = &self.inner;
460        // Exact match except trailing slashes (Authentik's `iss` always ends with "/").
461        let iss = claims.get("iss").and_then(Value::as_str);
462        if iss.map(|s| s.trim_end_matches('/')) != Some(i.issuer.trim_end_matches('/')) {
463            return Err(auth("claim iss is invalid (unexpected value)"));
464        }
465        let aud_ok = match claims.get("aud") {
466            Some(Value::String(a)) => *a == i.audience,
467            Some(Value::Array(list)) => {
468                list.iter().any(|a| a.as_str() == Some(i.audience.as_str()))
469            }
470            _ => false,
471        };
472        if !aud_ok {
473            return Err(auth("claim aud is invalid (unexpected value)"));
474        }
475        let now = (i.now)()
476            .duration_since(UNIX_EPOCH)
477            .unwrap_or_default()
478            .as_secs_f64();
479        let skew = i.skew.as_secs_f64();
480        let number = |name: &str| -> Result<Option<f64>> {
481            match claims.get(name) {
482                None => Ok(None),
483                Some(v) => v
484                    .as_f64()
485                    .map(Some)
486                    .ok_or_else(|| auth(format_args!("claim {name} is invalid (not a number)"))),
487            }
488        };
489        let exp = number("exp")?.ok_or_else(|| auth("claim exp is invalid (missing)"))?;
490        if now > exp + skew {
491            return Err(auth("token expired"));
492        }
493        if number("nbf")?.is_some_and(|nbf| now + skew < nbf) {
494            return Err(auth("claim nbf is invalid (not yet valid)"));
495        }
496        if claims
497            .get("sub")
498            .and_then(Value::as_str)
499            .is_none_or(str::is_empty)
500        {
501            return Err(auth("claim sub is invalid (missing)"));
502        }
503        Ok(())
504    }
505
506    fn to_user(&self, claims: Map<String, Value>) -> AuthUser {
507        let text = |name: &str| claims.get(name).and_then(Value::as_str).map(str::to_owned);
508        AuthUser {
509            sub: text("sub").unwrap_or_default(),
510            email: text("email"),
511            name: text("name").or_else(|| text("preferred_username")),
512            roles: extract_roles(&claims, &self.inner.roles_claim),
513            claims,
514        }
515    }
516
517    async fn key_set(&self, force: bool) -> Result<Arc<KeySet>> {
518        let i = &self.inner;
519        let cached = i.keys.read().unwrap_or_else(|e| e.into_inner()).clone();
520        let fresh =
521            |set: &KeySet| (i.now)().duration_since(set.fetched_at).unwrap_or_default() < i.ttl;
522        if let Some(set) = &cached {
523            if !force && fresh(set) {
524                return Ok(set.clone());
525            }
526        }
527        let _guard = i.fetch.lock().await;
528        let current = i.keys.read().unwrap_or_else(|e| e.into_inner()).clone();
529        if let Some(set) = current {
530            let replaced = cached.as_ref().is_none_or(|c| !Arc::ptr_eq(c, &set));
531            if replaced {
532                return Ok(set); // fetched by another task meanwhile
533            }
534        }
535        let url = match i
536            .jwks_url
537            .clone()
538            .or_else(|| i.resolved.read().unwrap_or_else(|e| e.into_inner()).clone())
539        {
540            Some(url) => url,
541            None => {
542                let discovery = format!(
543                    "{}/.well-known/openid-configuration",
544                    i.issuer.trim_end_matches('/')
545                );
546                let doc = self.get_json("discovery", &discovery).await?;
547                let uri = doc
548                    .get("jwks_uri")
549                    .and_then(Value::as_str)
550                    .filter(|u| !u.is_empty())
551                    .ok_or_else(|| Error::unavailable("discovery: document has no jwks_uri"))?
552                    .to_owned();
553                *i.resolved.write().unwrap_or_else(|e| e.into_inner()) = Some(uri.clone());
554                uri
555            }
556        };
557        let body = self.get_json("jwks", &url).await?;
558        let keys = body
559            .get("keys")
560            .and_then(Value::as_array)
561            .ok_or_else(|| Error::unavailable("jwks: response has no keys array"))?
562            .iter()
563            .filter_map(parse_key)
564            .collect();
565        let set = Arc::new(KeySet {
566            keys,
567            fetched_at: (i.now)(),
568        });
569        *i.keys.write().unwrap_or_else(|e| e.into_inner()) = Some(set.clone());
570        Ok(set)
571    }
572
573    async fn get_json(&self, operation: &str, url: &str) -> Result<Value> {
574        let res = self
575            .inner
576            .http
577            .get(url)
578            .header("accept", "application/json")
579            .send()
580            .await
581            .map_err(|e| {
582                Error::unavailable(format!("{operation}: request failed")).with_source(e)
583            })?;
584        let status = res.status().as_u16();
585        if !res.status().is_success() {
586            return Err(Error::unavailable(format!(
587                "{operation}: unexpected response (HTTP {status})"
588            ))
589            .with_status(status));
590        }
591        let bytes = res.bytes().await.map_err(|e| {
592            Error::unavailable(format!("{operation}: request failed")).with_source(e)
593        })?;
594        match serde_json::from_slice::<Value>(&bytes) {
595            Ok(v @ Value::Object(_)) => Ok(v),
596            _ => Err(Error::unavailable(format!(
597                "{operation}: response is not JSON"
598            ))),
599        }
600    }
601}
602
603fn matching<'a>(set: &'a KeySet, alg: &str, kid: Option<&str>) -> Vec<&'a Key> {
604    set.keys
605        .iter()
606        .filter(|k| kid.is_none_or(|kid| k.kid.as_deref() == Some(kid)) && k.compatible(alg))
607        .collect()
608}
609
610/// Returns the bearer token of an `Authorization` header value (scheme case-insensitive).
611pub fn bearer_token(authorization: &str) -> Option<&str> {
612    let mut parts = authorization.split_whitespace();
613    match (parts.next(), parts.next(), parts.next()) {
614        (Some(scheme), Some(token), None) if scheme.eq_ignore_ascii_case("bearer") => Some(token),
615        _ => None,
616    }
617}
618
619/// Value at a claim name (`roles`) or dotted path (`realm_access.roles`); an exact top-level
620/// match wins.
621pub fn claim_at<'a>(claims: &'a Map<String, Value>, path: &str) -> Option<&'a Value> {
622    if let Some(v) = claims.get(path) {
623        return Some(v);
624    }
625    let mut parts = path.split('.');
626    let mut current = claims.get(parts.next()?)?;
627    for part in parts {
628        current = current.as_object()?.get(part)?;
629    }
630    Some(current)
631}
632
633fn role_name(entry: &Value) -> Option<String> {
634    let name = match entry {
635        Value::String(s) => s.as_str(),
636        Value::Object(obj) => ["name", "code", "role", "value"].iter().find_map(|k| {
637            obj.get(*k)
638                .and_then(Value::as_str)
639                .filter(|s| !s.trim().is_empty())
640        })?,
641        _ => return None,
642    };
643    Some(name.trim().to_owned()).filter(|n| !n.is_empty())
644}
645
646/// Role names of the claim at `roles_claim`: a string is split on commas and whitespace; an array
647/// yields each string, or each object's `name` (Casdoor), `code`, `role` or `value`. Duplicates
648/// are removed, order is kept.
649pub fn extract_roles(claims: &Map<String, Value>, roles_claim: &str) -> Vec<String> {
650    let path = if roles_claim.trim().is_empty() {
651        "roles"
652    } else {
653        roles_claim
654    };
655    let names: Vec<String> = match claim_at(claims, path) {
656        Some(Value::String(s)) => s
657            .split(|c: char| c == ',' || c.is_whitespace())
658            .map(str::to_owned)
659            .collect(),
660        Some(Value::Array(list)) => list.iter().filter_map(role_name).collect(),
661        _ => Vec::new(),
662    };
663    let mut out: Vec<String> = Vec::new();
664    for name in names {
665        if !name.is_empty() && !out.contains(&name) {
666            out.push(name);
667        }
668    }
669    out
670}
671
672/// True when `have` contains at least one of `required` (case-insensitive); an empty `required`
673/// means any authenticated user.
674pub fn has_any_role<S: AsRef<str>>(have: &[S], required: &[&str]) -> bool {
675    required.is_empty()
676        || required
677            .iter()
678            .any(|r| have.iter().any(|h| h.as_ref().eq_ignore_ascii_case(r)))
679}