Skip to main content

rs_identity_model/jwt/
claims_validation.rs

1//! Injectable, composable claims validation (issue #603; Rust port of the
2//! Python foundation #623).
3//!
4//! After [`crate::validate_token`] verifies the signature, the algorithm
5//! allowlist, and the registered/configured claims, it runs an optional
6//! caller-supplied *claims validator* — the hook an application uses to enforce
7//! its own rules on the decoded claims (tenant membership, custom scopes, role
8//! checks, ...). This module makes that contract first-class and composable:
9//!
10//! * [`ClaimsValidator`] — the trait a validator implements (any
11//!   `Fn(&Claims) -> Result<(), IdentityError>` can be wrapped into one with
12//!   [`from_fn`]).
13//! * [`ClaimsValidationError`] — a structured rejection carrying a `reason` and
14//!   an optional offending `claim`. It converts into
15//!   [`IdentityError::ClaimsValidation`] so a rejection integrates with the
16//!   crate error type and surfaces *why* without parsing a message string.
17//! * [`combine_claims_validators`] — compose several validators into one
18//!   (all-must-pass or any-must-pass).
19//! * Ready-made, portable validators: [`require_claims`], [`require_claim_value`],
20//!   [`require_scopes`].
21//!
22//! The same interface shape is intended to be mirrored across the Python, Go,
23//! and Rust libraries so a resource server can express the same policy in any
24//! language. That parity is enforced by the shared conformance vectors in
25//! `spec/test-fixtures/claims-validation/vectors.json` (driven by
26//! `tests/it/conformance/claims_validation.rs`). For a runnable end-to-end
27//! demonstration of composing these validators, see
28//! `examples/combined_claims_validator.rs`
29//! (`cargo run --example combined_claims_validator`).
30//!
31//! ```
32//! use rs_identity_model::{ValidationOptions, require_scopes};
33//!
34//! # fn main() -> Result<(), rs_identity_model::IdentityError> {
35//! let options = ValidationOptions::builder()
36//!     .issuer("https://accounts.example.com")
37//!     .claims_validator(require_scopes(["read"])?)
38//!     .build();
39//! # let _ = options;
40//! # Ok(())
41//! # }
42//! ```
43
44use std::collections::HashSet;
45use std::fmt;
46
47use serde_json::Value;
48
49use crate::{IdentityError, Result};
50
51use super::Claims;
52
53/// A composable validator run over decoded [`Claims`] after the standard
54/// signature, algorithm, and registered-claim checks pass.
55///
56/// Return `Ok(())` to accept. To reject *cleanly*, return a
57/// [`ClaimsValidationError`] converted into [`IdentityError`] (e.g.
58/// `Err(ClaimsValidationError::new("...").into())`, or use one of the
59/// ready-made validators). Returning any *other* [`IdentityError`] variant is
60/// treated as a hard failure that propagates immediately rather than an
61/// aggregatable rejection — see [`combine_claims_validators`].
62///
63/// Any `Fn(&Claims) -> Result<(), IdentityError> + Send + Sync` can be turned
64/// into a `ClaimsValidator` with [`from_fn`].
65pub trait ClaimsValidator: Send + Sync {
66    /// Validates the decoded claims, returning `Ok(())` to accept.
67    fn validate(&self, claims: &Claims) -> Result<()>;
68}
69
70/// A type-erased, heap-allocated [`ClaimsValidator`] — the boxed-closure form of
71/// the trait. Produced by [`boxed`] and consumed by [`combine_claims_validators`].
72pub type BoxedClaimsValidator = Box<dyn ClaimsValidator>;
73
74/// A structured claims-validation rejection: a human-readable `reason` and,
75/// when the validator identified one, the offending `claim` name.
76///
77/// Converts into [`IdentityError::ClaimsValidation`] via `From`, so a validator
78/// rejects with `Err(err.into())` and the structured reason survives to the
79/// caller. This is the Rust analogue of the Python `ClaimsValidationError`
80/// (a `TokenValidationException` subclass).
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct ClaimsValidationError {
83    /// Why the claims were rejected.
84    pub reason: String,
85    /// The offending claim name, when the validator identified one.
86    pub claim: Option<String>,
87}
88
89impl ClaimsValidationError {
90    /// Builds a rejection with a `reason` and no specific claim.
91    pub fn new(reason: impl Into<String>) -> Self {
92        Self {
93            reason: reason.into(),
94            claim: None,
95        }
96    }
97
98    /// Builds a rejection naming the offending `claim`.
99    pub fn for_claim(reason: impl Into<String>, claim: impl Into<String>) -> Self {
100        Self {
101            reason: reason.into(),
102            claim: Some(claim.into()),
103        }
104    }
105
106    /// Attaches (or replaces) the offending claim name.
107    #[must_use]
108    pub fn with_claim(mut self, claim: impl Into<String>) -> Self {
109        self.claim = Some(claim.into());
110        self
111    }
112}
113
114impl fmt::Display for ClaimsValidationError {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        match &self.claim {
117            Some(claim) => write!(f, "{} (claim {claim:?})", self.reason),
118            None => write!(f, "{}", self.reason),
119        }
120    }
121}
122
123impl std::error::Error for ClaimsValidationError {}
124
125impl From<ClaimsValidationError> for IdentityError {
126    fn from(err: ClaimsValidationError) -> Self {
127        IdentityError::ClaimsValidation {
128            reason: err.reason,
129            claim: err.claim,
130        }
131    }
132}
133
134/// Wraps a closure into a [`ClaimsValidator`]. Internal; the public entry points
135/// are [`from_fn`] and the ready-made `require_*` validators.
136struct FnClaimsValidator<F>(F);
137
138impl<F> ClaimsValidator for FnClaimsValidator<F>
139where
140    F: Fn(&Claims) -> Result<()> + Send + Sync,
141{
142    fn validate(&self, claims: &Claims) -> Result<()> {
143        (self.0)(claims)
144    }
145}
146
147/// Adapts a plain closure into a [`ClaimsValidator`], the boxed-closure form of
148/// the trait.
149///
150/// ```
151/// use rs_identity_model::{from_fn, ClaimsValidationError, IdentityError};
152///
153/// let tenant_bound = from_fn(|claims| -> Result<(), IdentityError> {
154///     if claims.has("tid") {
155///         Ok(())
156///     } else {
157///         Err(ClaimsValidationError::for_claim("no tenant", "tid").into())
158///     }
159/// });
160/// # let _: &dyn rs_identity_model::ClaimsValidator = &tenant_bound;
161/// ```
162pub fn from_fn<F>(validator: F) -> impl ClaimsValidator
163where
164    F: Fn(&Claims) -> Result<()> + Send + Sync + 'static,
165{
166    FnClaimsValidator(validator)
167}
168
169/// Boxes any [`ClaimsValidator`] into a [`BoxedClaimsValidator`] so validators
170/// of different concrete types can share a collection (e.g. the argument to
171/// [`combine_claims_validators`]).
172pub fn boxed<V>(validator: V) -> BoxedClaimsValidator
173where
174    V: ClaimsValidator + 'static,
175{
176    Box::new(validator)
177}
178
179/// How [`combine_claims_validators`] combines its members.
180#[derive(Clone, Copy, Debug, PartialEq, Eq)]
181pub enum CombineMode {
182    /// Every member must accept; the combined validator fails fast on the first
183    /// rejection (or propagates the first non-`ClaimsValidation` error).
184    All,
185    /// At least one member must accept; the combined validator rejects only if
186    /// *all* members reject, aggregating their reasons.
187    Any,
188}
189
190/// A [`ClaimsValidator`] composed from several members via
191/// [`combine_claims_validators`].
192pub struct CombinedValidator {
193    members: Vec<BoxedClaimsValidator>,
194    mode: CombineMode,
195}
196
197impl ClaimsValidator for CombinedValidator {
198    fn validate(&self, claims: &Claims) -> Result<()> {
199        match self.mode {
200            CombineMode::All => {
201                // Fail fast: the first member to reject (or otherwise error)
202                // determines the outcome.
203                for member in &self.members {
204                    member.validate(claims)?;
205                }
206                Ok(())
207            }
208            CombineMode::Any => {
209                let mut reasons: Vec<String> = Vec::with_capacity(self.members.len());
210                for member in &self.members {
211                    match member.validate(claims) {
212                        Ok(()) => return Ok(()),
213                        // Only a clean claims rejection is aggregated and the
214                        // next member tried. Any other error (Http,
215                        // Configuration, KeyNotFound, ...) is a hard failure and
216                        // propagates immediately — the load-bearing invariant
217                        // mirrored from the Python `any` mode.
218                        Err(IdentityError::ClaimsValidation { reason, .. }) => reasons.push(reason),
219                        Err(other) => return Err(other),
220                    }
221                }
222                Err(ClaimsValidationError::new(format!(
223                    "no validator accepted the claims: {}",
224                    reasons.join("; ")
225                ))
226                .into())
227            }
228        }
229    }
230}
231
232/// Composes `validators` into a single [`CombinedValidator`].
233///
234/// * [`CombineMode::All`] — every member must accept; the combined validator
235///   rejects with the first member's error (fail fast). An empty `All` set is a
236///   no-op that accepts everything (harmless).
237/// * [`CombineMode::Any`] — at least one member must accept; the combined
238///   validator rejects with a [`ClaimsValidationError`] aggregating every
239///   member's reason only if all of them reject. In `Any` mode only a clean
240///   [`IdentityError::ClaimsValidation`] rejection is aggregated; any other
241///   error propagates immediately.
242///
243/// # Errors
244///
245/// Returns [`IdentityError::Configuration`] if [`CombineMode::Any`] is given no
246/// validators — an empty any-of set can never be satisfied, so it would reject
247/// every token. (The Python API also guards an invalid `require` string; here
248/// [`CombineMode`] makes that state unrepresentable.)
249pub fn combine_claims_validators(
250    validators: impl IntoIterator<Item = BoxedClaimsValidator>,
251    mode: CombineMode,
252) -> Result<CombinedValidator> {
253    let members: Vec<BoxedClaimsValidator> = validators.into_iter().collect();
254    if mode == CombineMode::Any && members.is_empty() {
255        return Err(IdentityError::Configuration(
256            "combine_claims_validators(Any) needs at least one validator; an empty any-of set \
257             rejects every token"
258                .to_string(),
259        ));
260    }
261    Ok(CombinedValidator { members, mode })
262}
263
264/// Returns a validator that rejects unless every named claim is present with a
265/// meaningful value.
266///
267/// A claim that is absent, JSON `null`, an empty string, or an empty
268/// array/object is treated as missing — the same presence notion the built-in
269/// [`crate::ValidationOptions`] `required_claims` (JWT-012) enforces, so the two
270/// required-claim surfaces agree and a present-but-null `aud` cannot slip
271/// through the typed-field reconstruction. This is marginally stricter than the
272/// Python `require_claims` (which treats only `None`/absent as missing); the
273/// difference — rejecting present-but-empty values — is fail-closed.
274///
275/// # Errors
276///
277/// Returns [`IdentityError::Configuration`] if no claim names are supplied.
278pub fn require_claims<I, S>(names: I) -> Result<impl ClaimsValidator>
279where
280    I: IntoIterator<Item = S>,
281    S: Into<String>,
282{
283    let names: Vec<String> = names.into_iter().map(Into::into).collect();
284    if names.is_empty() {
285        return Err(IdentityError::Configuration(
286            "require_claims needs at least one claim name".to_string(),
287        ));
288    }
289    Ok(FnClaimsValidator(move |claims: &Claims| {
290        for name in &names {
291            if is_missing(claims, name) {
292                return Err(ClaimsValidationError::for_claim(
293                    format!("required claim '{name}' is missing"),
294                    name.as_str(),
295                )
296                .into());
297            }
298        }
299        Ok(())
300    }))
301}
302
303/// Returns a validator that rejects unless claim `name` is present *and* equals
304/// `value`.
305///
306/// An absent claim always rejects — including when `value` is
307/// [`Value::Null`], so `require_claim_value("x", Value::Null)` means "`x` must
308/// be present and null", not "`x` may be missing" (the fail-open a plain
309/// "get-or-default != value" would allow).
310///
311/// # Comparison semantics
312///
313/// The claim is compared against the decoded [`Claims`] representation, not the
314/// raw token JSON. Two consequences, both **fail-closed** (a mismatch rejects,
315/// never accepts):
316///
317/// * The `aud` claim is normalised to an array of strings, so
318///   `require_claim_value("aud", "acme")` does **not** match a token carrying
319///   `aud: "acme"`. To assert an audience, prefer the token-validation
320///   `audience` check, or compare against the array form
321///   (`require_claim_value("aud", serde_json::json!(["acme"]))`).
322/// * Numeric equality is exact by JSON number type: an integer `1` in the token
323///   is not equal to a float `1.0` passed here.
324///
325/// For the common case — string claims such as `role`, `tid`, or `iss` — this
326/// is exactly the intended behaviour.
327pub fn require_claim_value(
328    name: impl Into<String>,
329    value: impl Into<Value>,
330) -> impl ClaimsValidator {
331    let name = name.into();
332    let expected = value.into();
333    FnClaimsValidator(move |claims: &Claims| {
334        let matches = claims.has(&name) && claim_value(claims, &name).as_ref() == Some(&expected);
335        if matches {
336            Ok(())
337        } else {
338            Err(ClaimsValidationError::for_claim(
339                format!("claim '{name}' must equal {expected}"),
340                name.as_str(),
341            )
342            .into())
343        }
344    })
345}
346
347/// Returns a validator that rejects unless the token grants every named scope.
348///
349/// Scopes are read from the OAuth 2.0 `scope` (space-delimited string) or `scp`
350/// (array) claim. An absent or empty-string `scope` falls through to `scp`; a
351/// malformed `scope` (any other JSON shape) yields no scopes and therefore
352/// rejects (fail closed); non-string members of an array claim are ignored.
353///
354/// # Errors
355///
356/// Returns [`IdentityError::Configuration`] if no scopes are supplied.
357pub fn require_scopes<I, S>(scopes: I) -> Result<impl ClaimsValidator>
358where
359    I: IntoIterator<Item = S>,
360    S: Into<String>,
361{
362    let scopes: Vec<String> = scopes.into_iter().map(Into::into).collect();
363    if scopes.is_empty() {
364        return Err(IdentityError::Configuration(
365            "require_scopes needs at least one scope".to_string(),
366        ));
367    }
368    Ok(FnClaimsValidator(move |claims: &Claims| {
369        let granted = granted_scopes(claims);
370        let missing: Vec<&str> = scopes
371            .iter()
372            .filter(|scope| !granted.contains(scope.as_str()))
373            .map(String::as_str)
374            .collect();
375        if missing.is_empty() {
376            Ok(())
377        } else {
378            Err(ClaimsValidationError::for_claim(
379                format!("missing required scope(s): {}", missing.join(", ")),
380                "scope",
381            )
382            .into())
383        }
384    }))
385}
386
387/// The JSON value of any top-level claim — modelled field or unmodelled `extra`
388/// — as it appeared in the token, or `None` if the claim was absent. A claim
389/// present as JSON `null` returns `Some(Value::Null)`.
390///
391/// [`Claims`] parses the registered claims into typed fields, so their raw JSON
392/// is reconstructed here; every other claim is read straight from `extra`.
393fn claim_value(claims: &Claims, name: &str) -> Option<Value> {
394    if let Some(value) = claims.get(name) {
395        return Some(value.clone());
396    }
397    match name {
398        "iss" => claims.issuer.clone().map(Value::String),
399        "sub" => claims.subject.clone().map(Value::String),
400        "jti" => claims.id.clone().map(Value::String),
401        "nonce" => claims.nonce.clone().map(Value::String),
402        "azp" => claims.authorized_party.clone().map(Value::String),
403        "exp" => claims.expiry.map(Value::from),
404        "nbf" => claims.not_before.map(Value::from),
405        "iat" => claims.issued_at.map(Value::from),
406        "aud" if claims.has("aud") => Some(Value::Array(
407            claims
408                .audience
409                .values()
410                .iter()
411                .cloned()
412                .map(Value::String)
413                .collect(),
414        )),
415        _ => None,
416    }
417}
418
419/// Whether `name` is missing for `require_claims`.
420///
421/// Routed through the crate's own presence logic ([`Claims::has_meaningful`],
422/// the `meaningful` set the built-in `required_claims` uses) rather than the
423/// lossy typed-field reconstruction in [`claim_value`]: a present-but-`null`
424/// `aud` reconstructs to an empty array, which would otherwise read as present.
425/// Delegating keeps the injectable and built-in required-claim checks in
426/// agreement and fails closed on `null`/empty (marginally stricter than the
427/// Python `_missing`, which treats only `None`/absent as missing).
428fn is_missing(claims: &Claims, name: &str) -> bool {
429    !claims.has_meaningful(name)
430}
431
432/// The scopes the token grants, from `scope` (space-delimited string) or `scp`
433/// (array). Any other shape yields no granted scopes rather than erroring — a
434/// malformed scope claim must fail closed, not crash validation.
435fn granted_scopes(claims: &Claims) -> HashSet<String> {
436    let mut raw = claims.get("scope");
437    // An absent OR empty-string `scope` falls through to `scp`: some IdPs send
438    // `{"scope": "", "scp": [...]}` and an empty string must not shadow the
439    // populated array. A malformed (non-string) `scope` does NOT fall through —
440    // it yields no scopes and rejects (fail closed).
441    let fall_through = match raw {
442        None => true,
443        Some(Value::String(s)) => s.is_empty(),
444        Some(_) => false,
445    };
446    if fall_through {
447        raw = claims.get("scp");
448    }
449    match raw {
450        Some(Value::String(s)) => s.split_whitespace().map(str::to_owned).collect(),
451        Some(Value::Array(items)) => items
452            .iter()
453            .filter_map(|item| item.as_str().map(str::to_owned))
454            .collect(),
455        _ => HashSet::new(),
456    }
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462    use serde_json::json;
463
464    /// Builds a claim set from a JSON object literal.
465    fn claims(value: Value) -> Claims {
466        Claims::from_value(value).expect("valid claims object")
467    }
468
469    /// Runs a validator and returns the [`IdentityError`] it rejected with.
470    fn reject(validator: &dyn ClaimsValidator, value: Value) -> IdentityError {
471        validator
472            .validate(&claims(value))
473            .expect_err("expected a rejection")
474    }
475
476    /// Runs a validator and returns the structured claims rejection, asserting
477    /// it rejected via [`IdentityError::ClaimsValidation`].
478    fn reject_claims(validator: &dyn ClaimsValidator, value: Value) -> (String, Option<String>) {
479        match reject(validator, value) {
480            IdentityError::ClaimsValidation { reason, claim } => (reason, claim),
481            other => panic!("expected ClaimsValidation, got {other:?}"),
482        }
483    }
484
485    // --- ClaimsValidationError -------------------------------------------------
486
487    #[test]
488    fn claims_validation_error_converts_into_identity_error() {
489        let err: IdentityError = ClaimsValidationError::for_claim("nope", "tenant").into();
490        match err {
491            IdentityError::ClaimsValidation { reason, claim } => {
492                assert_eq!(reason, "nope");
493                assert_eq!(claim.as_deref(), Some("tenant"));
494            }
495            other => panic!("expected ClaimsValidation, got {other:?}"),
496        }
497    }
498
499    #[test]
500    fn claims_validation_error_without_claim() {
501        let err = ClaimsValidationError::new("nope");
502        assert!(err.claim.is_none());
503        assert_eq!(err.to_string(), "nope");
504    }
505
506    // --- require_claims --------------------------------------------------------
507
508    #[test]
509    fn require_claims_accepts_when_all_present() {
510        let v = require_claims(["sub", "tid"]).expect("names supplied");
511        v.validate(&claims(json!({ "sub": "u1", "tid": "t1" })))
512            .expect("all present passes");
513    }
514
515    #[test]
516    fn require_claims_rejects_missing_with_claim_name() {
517        let v = require_claims(["sub", "tid"]).expect("names supplied");
518        let (_, claim) = reject_claims(&v, json!({ "sub": "u1" }));
519        assert_eq!(claim.as_deref(), Some("tid"));
520    }
521
522    #[test]
523    fn require_claims_treats_null_as_missing() {
524        let v = require_claims(["tid"]).expect("names supplied");
525        let (_, claim) = reject_claims(&v, json!({ "tid": null }));
526        assert_eq!(claim.as_deref(), Some("tid"));
527    }
528
529    #[test]
530    fn require_claims_treats_null_aud_as_missing() {
531        // Regression: a present-but-null `aud` reconstructs to an empty audience
532        // via the typed field, so it must be treated as missing (fail closed)
533        // rather than accepted — matching the built-in `required_claims`.
534        let v = require_claims(["aud"]).expect("names supplied");
535        let (_, claim) = reject_claims(&v, json!({ "aud": null }));
536        assert_eq!(claim.as_deref(), Some("aud"));
537    }
538
539    #[test]
540    fn require_claims_treats_empty_value_as_missing() {
541        // Consistent with the built-in required_claims (JWT-012): a present-but-
542        // empty value does not satisfy a required-claim check.
543        let v = require_claims(["x"]).expect("names supplied");
544        reject(&v, json!({ "x": "" }));
545        reject(&v, json!({ "x": [] }));
546        reject(&v, json!({ "x": {} }));
547    }
548
549    #[test]
550    fn require_claims_needs_a_name() {
551        let err = match require_claims(Vec::<String>::new()) {
552            Ok(_) => panic!("empty names must be rejected"),
553            Err(e) => e,
554        };
555        assert!(err.to_string().contains("at least one"), "{err}");
556    }
557
558    // --- require_claim_value ---------------------------------------------------
559
560    #[test]
561    fn require_claim_value_accepts_and_rejects() {
562        let v = require_claim_value("role", "admin");
563        v.validate(&claims(json!({ "role": "admin" })))
564            .expect("matching value passes");
565        let (_, claim) = reject_claims(&v, json!({ "role": "user" }));
566        assert_eq!(claim.as_deref(), Some("role"));
567    }
568
569    #[test]
570    fn require_claim_value_rejects_absent_claim() {
571        let v = require_claim_value("role", "admin");
572        let (_, claim) = reject_claims(&v, json!({}));
573        assert_eq!(claim.as_deref(), Some("role"));
574    }
575
576    #[test]
577    fn require_claim_value_null_requires_present_null_not_absent() {
578        // "must equal null" means present-and-null — an absent claim must NOT
579        // pass (the fail-open a plain get-or-default != value would allow).
580        let v = require_claim_value("x", Value::Null);
581        v.validate(&claims(json!({ "x": null })))
582            .expect("present null matches expected null");
583        reject(&v, json!({}));
584    }
585
586    // --- require_scopes --------------------------------------------------------
587
588    #[test]
589    fn require_scopes_from_space_delimited_string() {
590        let v = require_scopes(["read"]).expect("scopes supplied");
591        v.validate(&claims(json!({ "scope": "read write" })))
592            .expect("space-delimited scope passes");
593    }
594
595    #[test]
596    fn require_scopes_from_scp_list() {
597        let v = require_scopes(["read", "write"]).expect("scopes supplied");
598        v.validate(&claims(json!({ "scp": ["read", "write", "admin"] })))
599            .expect("scp array passes");
600    }
601
602    #[test]
603    fn require_scopes_rejects_missing_and_names_only_them() {
604        let v = require_scopes(["read", "delete"]).expect("scopes supplied");
605        let (reason, claim) = reject_claims(&v, json!({ "scope": "read" }));
606        assert_eq!(claim.as_deref(), Some("scope"));
607        assert!(reason.contains("delete"), "{reason}");
608        assert!(
609            !reason.contains("read"),
610            "only the missing scope is named: {reason}"
611        );
612    }
613
614    #[test]
615    fn require_scopes_malformed_claim_fails_closed() {
616        // A non-string, non-array scope yields no granted scopes -> reject,
617        // never crash.
618        let v = require_scopes(["read"]).expect("scopes supplied");
619        for bad in [json!({ "unexpected": "shape" }), json!(123), json!(null)] {
620            reject(&v, json!({ "scope": bad }));
621        }
622    }
623
624    #[test]
625    fn require_scopes_list_drops_non_string_members_without_crashing() {
626        let read = require_scopes(["read"]).expect("scopes supplied");
627        read.validate(&claims(json!({ "scope": ["read", 7, null] })))
628            .expect("valid string scope still counts");
629        let admin = require_scopes(["admin"]).expect("scopes supplied");
630        reject(&admin, json!({ "scope": ["read", 7, null] }));
631    }
632
633    #[test]
634    fn require_scopes_empty_scope_falls_through_to_scp() {
635        let v = require_scopes(["read"]).expect("scopes supplied");
636        v.validate(&claims(json!({ "scope": "", "scp": ["read", "write"] })))
637            .expect("empty scope must not shadow populated scp");
638    }
639
640    #[test]
641    fn require_scopes_nonempty_scope_takes_precedence_over_scp() {
642        let v = require_scopes(["write"]).expect("scopes supplied");
643        // A present, non-empty `scope` wins; `scp` is not consulted.
644        reject(&v, json!({ "scope": "read", "scp": ["write"] }));
645    }
646
647    #[test]
648    fn require_scopes_needs_a_scope() {
649        let err = match require_scopes(Vec::<String>::new()) {
650            Ok(_) => panic!("empty scopes must be rejected"),
651            Err(e) => e,
652        };
653        assert!(err.to_string().contains("at least one"), "{err}");
654    }
655
656    // --- combine_claims_validators ---------------------------------------------
657
658    #[test]
659    fn combine_all_passes_when_every_validator_passes() {
660        let combined = combine_claims_validators(
661            [
662                boxed(require_claims(["sub"]).unwrap()),
663                boxed(require_scopes(["read"]).unwrap()),
664            ],
665            CombineMode::All,
666        )
667        .expect("non-empty all");
668        combined
669            .validate(&claims(json!({ "sub": "u1", "scope": "read" })))
670            .expect("both pass");
671    }
672
673    #[test]
674    fn combine_all_raises_first_failure() {
675        let combined = combine_claims_validators(
676            [
677                boxed(require_claims(["sub"]).unwrap()),
678                boxed(require_claim_value("role", "admin")),
679            ],
680            CombineMode::All,
681        )
682        .expect("non-empty all");
683        let (_, claim) = reject_claims(&combined, json!({ "sub": "u1", "role": "user" }));
684        assert_eq!(claim.as_deref(), Some("role"));
685    }
686
687    #[test]
688    fn combine_any_passes_when_one_passes() {
689        let combined = combine_claims_validators(
690            [
691                boxed(require_claim_value("role", "admin")),
692                boxed(require_scopes(["read"]).unwrap()),
693            ],
694            CombineMode::Any,
695        )
696        .expect("non-empty any");
697        // The second member accepts.
698        combined
699            .validate(&claims(json!({ "role": "user", "scope": "read" })))
700            .expect("one passing member accepts");
701    }
702
703    #[test]
704    fn combine_any_aggregates_reasons_when_all_reject() {
705        let combined = combine_claims_validators(
706            [
707                boxed(require_claims(["a"]).unwrap()),
708                boxed(require_claims(["b"]).unwrap()),
709            ],
710            CombineMode::Any,
711        )
712        .expect("non-empty any");
713        let (reason, _) = reject_claims(&combined, json!({ "c": 1 }));
714        assert!(reason.contains("'a'"), "{reason}");
715        assert!(reason.contains("'b'"), "{reason}");
716    }
717
718    #[test]
719    fn combine_any_empty_is_rejected_at_construction() {
720        let err = match combine_claims_validators(Vec::new(), CombineMode::Any) {
721            Ok(_) => panic!("empty any must be rejected at construction"),
722            Err(e) => e,
723        };
724        assert!(err.to_string().contains("at least one"), "{err}");
725    }
726
727    #[test]
728    fn combine_all_empty_is_a_noop() {
729        let combined =
730            combine_claims_validators(Vec::new(), CombineMode::All).expect("empty all is a no-op");
731        combined
732            .validate(&claims(json!({ "anything": true })))
733            .expect("empty all accepts");
734    }
735
736    #[test]
737    fn combine_all_propagates_non_claims_error() {
738        // A non-ClaimsValidation error from a member is not swallowed as a
739        // rejection — it propagates.
740        let combined = combine_claims_validators(
741            [boxed(from_fn(|_| {
742                Err(IdentityError::Configuration("bug".to_string()))
743            }))],
744            CombineMode::All,
745        )
746        .expect("non-empty all");
747        assert!(matches!(
748            reject(&combined, json!({})),
749            IdentityError::Configuration(_)
750        ));
751    }
752
753    #[test]
754    fn combine_any_propagates_non_claims_error() {
755        // The load-bearing invariant: `Any` aggregates only ClaimsValidation
756        // rejections, so a member's hard error is NOT recorded as a rejection
757        // reason (which could flip the result to accept) — it propagates.
758        let combined = combine_claims_validators(
759            [
760                boxed(from_fn(|_| {
761                    Err(IdentityError::Configuration("bug".to_string()))
762                })),
763                boxed(require_claims(["sub"]).unwrap()),
764            ],
765            CombineMode::Any,
766        )
767        .expect("non-empty any");
768        assert!(matches!(
769            reject(&combined, json!({})),
770            IdentityError::Configuration(_)
771        ));
772    }
773
774    // --- nesting / trait plumbing ----------------------------------------------
775
776    #[test]
777    fn combined_validators_nest() {
778        // A CombinedValidator is itself a ClaimsValidator, so it can be boxed
779        // into another combination.
780        let inner =
781            combine_claims_validators([boxed(require_claims(["sub"]).unwrap())], CombineMode::All)
782                .expect("inner all");
783        let outer = combine_claims_validators(
784            [boxed(inner), boxed(require_scopes(["read"]).unwrap())],
785            CombineMode::All,
786        )
787        .expect("outer all");
788        outer
789            .validate(&claims(json!({ "sub": "u1", "scope": "read" })))
790            .expect("nested combination passes");
791    }
792}