1use serde_json::{Map, Value};
23
24use crate::error::AuthError;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum TokenPurpose {
29 Access,
30 IdToken,
31 Refresh,
32 InternalAssertion,
33}
34
35#[derive(Debug, Clone)]
37pub struct ValidationPolicy {
38 pub purpose: TokenPurpose,
39 pub trusted_issuers: Vec<String>,
41 pub expected_audiences: Vec<String>,
43 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 pub fn access() -> Self {
61 Self::for_purpose(TokenPurpose::Access, true)
62 }
63
64 pub fn id_token() -> Self {
68 Self::for_purpose(TokenPurpose::IdToken, false)
69 }
70
71 pub fn refresh() -> Self {
73 Self::for_purpose(TokenPurpose::Refresh, false)
74 }
75
76 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 pub fn allow_legacy_typ(mut self) -> Self {
104 self.require_at_jwt = false;
105 self
106 }
107}
108
109pub 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
127fn purpose_requires_at_jwt(purpose: TokenPurpose) -> bool {
129 matches!(
130 purpose,
131 TokenPurpose::Access | TokenPurpose::InternalAssertion
132 )
133}
134
135pub 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
193pub 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 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}