Skip to main content

beyondigital_auth_sdk/
policy.rs

1//! Purpose-bound claim validation — a faithful port of auth_service's
2//! `crypto/jwt.rs` `ValidationPolicy`/`TokenPurpose`/`validate_claims` so
3//! consumers apply exactly the contract the issuer enforces.
4//!
5//! Semantics mirrored from `backends/rust/auth_service/src/crypto/jwt.rs`:
6//!   * trusted_issuers: exact-match allow-list; empty = no issuer pinning.
7//!     A pinned policy requires a nonblank string `iss` in that allow-list.
8//!     Issuer-less compatibility requires an explicitly unpinned raw policy.
9//!   * expected_audiences: empty = unpinned; non-empty requires the token's
10//!     `aud` (string or array) to intersect the expected set.
11//!   * purpose binds the `type` claim + required claims (`sub`/`exp`/`iat`,
12//!     `iss`/`aud`/`auth_time` for ID tokens, `sub == client_id` for
13//!     internal assertions).
14//!
15//! WP-05a adds the RFC 9068 §2.1 JOSE `typ` check layered on top:
16//! [`ValidationPolicy::require_at_jwt`] (default on for access purposes)
17//! demands a `typ` header of `at+jwt` (or the media-type form
18//! `application/at+jwt`), which auth_service mints on every access token
19//! since WP-03b. `allow_legacy_typ()` opens the compat window for tokens
20//! minted before the profile landed.
21
22use serde_json::{Map, Value};
23
24use crate::error::AuthError;
25
26/// The purpose a validated credential must serve (mirrors `TokenPurpose`).
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum TokenPurpose {
29    Access,
30    IdToken,
31    Refresh,
32    InternalAssertion,
33}
34
35/// Claim-level validation applied after signature verification.
36#[derive(Debug, Clone)]
37pub struct ValidationPolicy {
38    pub purpose: TokenPurpose,
39    /// Exact-match issuer allow-list; empty = no issuer pinning.
40    pub trusted_issuers: Vec<String>,
41    /// Audience allow-list; empty = no audience pinning.
42    pub expected_audiences: Vec<String>,
43    /// Require the RFC 9068 `at+jwt` JOSE `typ` on access-purpose tokens.
44    pub require_at_jwt: bool,
45}
46
47impl ValidationPolicy {
48    fn for_purpose(purpose: TokenPurpose, require_at_jwt: bool) -> Self {
49        Self {
50            purpose,
51            trusted_issuers: Vec::new(),
52            expected_audiences: Vec::new(),
53            require_at_jwt,
54        }
55    }
56
57    /// Access-token policy: `type="access"`, `sub`/`exp`/`iat` required, and
58    /// the `at+jwt` JOSE typ pinned (RFC 9068 §2.1 — every auth_service mint
59    /// carries it since WP-03b).
60    pub fn access() -> Self {
61        Self::for_purpose(TokenPurpose::Access, true)
62    }
63
64    /// ID-token policy. `typ` is not pinned: OIDC ID tokens are plain `JWT`s
65    /// and the `type` claim itself tolerates absence on pre-SEC-02 mints (the
66    /// only legacy compat window, matching the service).
67    pub fn id_token() -> Self {
68        Self::for_purpose(TokenPurpose::IdToken, false)
69    }
70
71    /// Refresh-credential policy (`type="refresh"`; no `typ` pin).
72    pub fn refresh() -> Self {
73        Self::for_purpose(TokenPurpose::Refresh, false)
74    }
75
76    /// Service/client-credentials assertion: an access-shaped token whose
77    /// `sub` IS the `client_id`. Carries the `at+jwt` typ.
78    pub fn internal_assertion() -> Self {
79        Self::for_purpose(TokenPurpose::InternalAssertion, true)
80    }
81
82    pub fn with_trusted_issuers<I, S>(mut self, issuers: I) -> Self
83    where
84        I: IntoIterator<Item = S>,
85        S: Into<String>,
86    {
87        self.trusted_issuers = issuers.into_iter().map(Into::into).collect();
88        self
89    }
90
91    pub fn with_expected_audiences<I, S>(mut self, audiences: I) -> Self
92    where
93        I: IntoIterator<Item = S>,
94        S: Into<String>,
95    {
96        self.expected_audiences = audiences.into_iter().map(Into::into).collect();
97        self
98    }
99
100    /// Compat window for pre-WP-03b access tokens that carry no `typ` header.
101    /// Keep this off in production; it exists so consumers can ride out an
102    /// issuer upgrade without rejecting in-flight tokens.
103    pub fn allow_legacy_typ(mut self) -> Self {
104        self.require_at_jwt = false;
105        self
106    }
107}
108
109/// Returns true when the JOSE `typ` header names the RFC 9068 profile.
110/// `typ` compares case-insensitively as a media type; `application/at+jwt`
111/// is the explicit-registration equivalent of `at+jwt`.
112pub fn is_at_jwt_typ(typ: Option<&str>) -> bool {
113    match typ {
114        None => false,
115        Some(raw) => {
116            let normalized = raw
117                .split(';')
118                .next()
119                .unwrap_or("")
120                .trim()
121                .to_ascii_lowercase();
122            normalized == "at+jwt" || normalized == "application/at+jwt"
123        }
124    }
125}
126
127/// Whether `purpose` carries the RFC 9068 access-token `typ`.
128fn purpose_requires_at_jwt(purpose: TokenPurpose) -> bool {
129    matches!(
130        purpose,
131        TokenPurpose::Access | TokenPurpose::InternalAssertion
132    )
133}
134
135/// Check the JOSE `typ` header for the policy's purpose. Call before
136/// signature verification — a wrong `typ` means the token is not even the
137/// right credential class.
138pub fn validate_typ_header(typ: Option<&str>, policy: &ValidationPolicy) -> Result<(), AuthError> {
139    if policy.require_at_jwt && purpose_requires_at_jwt(policy.purpose) && !is_at_jwt_typ(typ) {
140        return Err(AuthError::jwt(
141            format!("JOSE typ {typ:?} is not \"at+jwt\" on this path"),
142            "invalid",
143        ));
144    }
145    Ok(())
146}
147
148fn claim_audiences(claims: &Map<String, Value>) -> Vec<String> {
149    match claims.get("aud") {
150        Some(Value::String(audience)) if !audience.is_empty() => vec![audience.clone()],
151        Some(Value::Array(audiences))
152            if audiences
153                .iter()
154                .all(|a| a.as_str().is_some_and(|a| !a.trim().is_empty())) =>
155        {
156            audiences
157                .iter()
158                .filter_map(|a| a.as_str())
159                .filter(|a| !a.is_empty())
160                .map(str::to_owned)
161                .collect()
162        }
163        _ => Vec::new(),
164    }
165}
166
167fn require_claims(claims: &Map<String, Value>, required: &[&'static str]) -> Result<(), AuthError> {
168    for name in required {
169        if claims.get(*name).is_none() {
170            return Err(AuthError::jwt(
171                format!("missing required claim {name}"),
172                "invalid",
173            ));
174        }
175    }
176    Ok(())
177}
178
179fn require_type(claims: &Map<String, Value>, expected: &str) -> Result<(), AuthError> {
180    match claims.get("type").and_then(Value::as_str) {
181        Some(actual) if actual == expected => Ok(()),
182        Some(actual) => Err(AuthError::jwt(
183            format!("token type {actual:?} is not {expected:?} on this path"),
184            "invalid",
185        )),
186        None => Err(AuthError::jwt(
187            format!("missing required claim type (expected {expected:?})"),
188            "invalid",
189        )),
190    }
191}
192
193/// Bind a verified claim set to its purpose: exact `type`, required claims,
194/// issuer allow-list, audience allow-list. Byte-for-byte port of the
195/// service's `validate_claims`.
196pub fn validate_claims(
197    claims: &Map<String, Value>,
198    policy: &ValidationPolicy,
199) -> Result<(), AuthError> {
200    match policy.purpose {
201        TokenPurpose::Access => {
202            require_type(claims, "access")?;
203            require_claims(claims, &["sub", "exp", "iat"])?;
204        }
205        TokenPurpose::Refresh => {
206            require_type(claims, "refresh")?;
207            require_claims(claims, &["sub", "exp", "iat"])?;
208        }
209        TokenPurpose::IdToken => {
210            // `type="id"` on current mints; absent on pre-SEC-02 mints — the
211            // only legacy compat window, and only on this path.
212            if let Some(actual) = claims.get("type").and_then(Value::as_str) {
213                if actual != "id" {
214                    return Err(AuthError::jwt(
215                        format!("token type {actual:?} is not \"id\" on this path"),
216                        "invalid",
217                    ));
218                }
219            }
220            require_claims(claims, &["iss", "sub", "aud", "exp", "iat", "auth_time"])?;
221        }
222        TokenPurpose::InternalAssertion => {
223            require_type(claims, "access")?;
224            require_claims(claims, &["sub", "client_id", "exp", "iat"])?;
225            if claims.get("sub") != claims.get("client_id") {
226                return Err(AuthError::jwt(
227                    "internal assertion requires sub == client_id",
228                    "invalid",
229                ));
230            }
231        }
232    }
233
234    if !policy.trusted_issuers.is_empty() {
235        let trusted = claims
236            .get("iss")
237            .and_then(Value::as_str)
238            .is_some_and(|iss| {
239                !iss.trim().is_empty()
240                    && policy
241                        .trusted_issuers
242                        .iter()
243                        .any(|expected| expected == iss)
244            });
245        if !trusted {
246            return Err(AuthError::jwt(
247                "missing or untrusted issuer",
248                "issuer_mismatch",
249            ));
250        }
251    }
252
253    if !policy.expected_audiences.is_empty() {
254        let audiences = claim_audiences(claims);
255        let ok = audiences
256            .iter()
257            .any(|a| policy.expected_audiences.iter().any(|e| e == a));
258        if !ok {
259            return Err(AuthError::jwt(
260                "token audience is not expected on this path".to_string(),
261                "audience_mismatch",
262            ));
263        }
264    }
265
266    Ok(())
267}