1use crate::errors::{AuthError, Result};
7use chrono::{Duration, Utc};
8use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, json};
11use std::collections::HashMap;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct JwtIntrospectionClaims {
16 pub iss: String,
18
19 pub aud: Vec<String>,
21
22 pub jti: String,
24
25 pub iat: i64,
27
28 pub exp: i64,
30
31 pub sub: Option<String>,
33
34 pub client_id: Option<String>,
36
37 pub active: bool,
39
40 pub token_type: Option<String>,
42
43 pub scope: Option<String>,
45
46 pub username: Option<String>,
48
49 pub token_exp: Option<i64>,
51
52 pub token_iat: Option<i64>,
54
55 pub token_nbf: Option<i64>,
57
58 pub token_aud: Option<Vec<String>>,
60
61 pub token_iss: Option<String>,
63
64 #[serde(flatten)]
66 pub additional_claims: HashMap<String, Value>,
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct BasicIntrospectionResponse {
72 pub active: bool,
74
75 pub scope: Option<String>,
77
78 pub client_id: Option<String>,
80
81 pub username: Option<String>,
83
84 pub token_type: Option<String>,
86
87 pub exp: Option<i64>,
89
90 pub iat: Option<i64>,
92
93 pub nbf: Option<i64>,
95
96 pub sub: Option<String>,
98
99 pub aud: Option<Vec<String>>,
101
102 pub iss: Option<String>,
104
105 pub jti: Option<String>,
107
108 #[serde(flatten)]
110 pub additional_claims: HashMap<String, Value>,
111}
112
113#[derive(Debug, Clone)]
115pub struct JwtIntrospectionConfig {
116 pub issuer: String,
118
119 pub default_audience: Vec<String>,
121
122 pub response_expiration: i64,
124
125 pub signing_algorithm: Algorithm,
127
128 pub include_token_claims: bool,
130
131 pub validate_audience: bool,
133}
134
135impl Default for JwtIntrospectionConfig {
136 fn default() -> Self {
137 Self {
138 issuer: "https://auth.example.com".to_string(),
139 default_audience: vec!["https://api.example.com".to_string()],
140 response_expiration: 300, signing_algorithm: Algorithm::HS256,
142 include_token_claims: true,
143 validate_audience: true,
144 }
145 }
146}
147
148pub struct JwtIntrospectionManager {
150 config: JwtIntrospectionConfig,
151 private_key: EncodingKey,
152 public_key: DecodingKey,
153}
154
155impl JwtIntrospectionManager {
156 pub const MIN_HMAC_SECRET_LEN: usize = 32;
158
159 pub fn new(config: JwtIntrospectionConfig) -> Result<Self> {
169 use ring::rand::{SecureRandom, SystemRandom};
170 let mut key_bytes = [0u8; 32];
171 SystemRandom::new().fill(&mut key_bytes).map_err(|_| {
172 AuthError::crypto("System CSPRNG unavailable; cannot create an introspection key")
173 })?;
174 Self::with_hmac_secret(config, &key_bytes)
175 }
176
177 pub fn with_hmac_secret(config: JwtIntrospectionConfig, secret: &[u8]) -> Result<Self> {
185 if secret.len() < Self::MIN_HMAC_SECRET_LEN {
186 return Err(AuthError::config(format!(
187 "the introspection HMAC secret must be at least {} bytes",
188 Self::MIN_HMAC_SECRET_LEN
189 )));
190 }
191 Ok(Self {
192 config,
193 private_key: EncodingKey::from_secret(secret),
194 public_key: DecodingKey::from_secret(secret),
195 })
196 }
197
198 pub fn create_jwt_response(
200 &self,
201 basic_response: BasicIntrospectionResponse,
202 audience: Option<Vec<String>>,
203 token_jti: Option<String>,
204 ) -> Result<String> {
205 let now = Utc::now();
206 let exp = now + Duration::seconds(self.config.response_expiration);
207
208 let claims = JwtIntrospectionClaims {
209 iss: self.config.issuer.clone(),
210 aud: audience.unwrap_or_else(|| self.config.default_audience.clone()),
211 jti: token_jti.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
212 iat: now.timestamp(),
213 exp: exp.timestamp(),
214 sub: basic_response.sub,
215 client_id: basic_response.client_id,
216 active: basic_response.active,
217 token_type: basic_response.token_type,
218 scope: basic_response.scope,
219 username: basic_response.username,
220 token_exp: basic_response.exp,
221 token_iat: basic_response.iat,
222 token_nbf: basic_response.nbf,
223 token_aud: basic_response.aud,
224 token_iss: basic_response.iss,
225 additional_claims: basic_response.additional_claims,
226 };
227
228 let header = Header::new(self.config.signing_algorithm);
229 let token = jsonwebtoken::encode(&header, &claims, &self.private_key).map_err(|e| {
230 AuthError::crypto(format!(
231 "Failed to create JWT introspection response: {}",
232 e
233 ))
234 })?;
235
236 Ok(token)
237 }
238
239 pub fn verify_jwt_response(&self, jwt_token: &str) -> Result<JwtIntrospectionClaims> {
241 let mut validation = Validation::new(self.config.signing_algorithm);
242 validation.set_issuer(&[&self.config.issuer]);
243
244 if self.config.validate_audience {
245 validation.set_audience(&self.config.default_audience);
246 } else {
247 validation.validate_aud = false;
248 }
249
250 let token_data = jsonwebtoken::decode::<JwtIntrospectionClaims>(
251 jwt_token,
252 &self.public_key,
253 &validation,
254 )
255 .map_err(|e| {
256 AuthError::crypto(format!(
257 "Failed to verify JWT introspection response: {}",
258 e
259 ))
260 })?;
261
262 Ok(token_data.claims)
263 }
264
265 pub fn create_inactive_response(
267 &self,
268 audience: Option<Vec<String>>,
269 token_jti: Option<String>,
270 ) -> Result<String> {
271 let basic_response = BasicIntrospectionResponse {
272 active: false,
273 scope: None,
274 client_id: None,
275 username: None,
276 token_type: None,
277 exp: None,
278 iat: None,
279 nbf: None,
280 sub: None,
281 aud: None,
282 iss: None,
283 jti: None,
284 additional_claims: HashMap::new(),
285 };
286
287 self.create_jwt_response(basic_response, audience, token_jti)
288 }
289
290 pub fn jwt_to_basic_response(
292 &self,
293 claims: &JwtIntrospectionClaims,
294 ) -> BasicIntrospectionResponse {
295 BasicIntrospectionResponse {
296 active: claims.active,
297 scope: claims.scope.clone(),
298 client_id: claims.client_id.clone(),
299 username: claims.username.clone(),
300 token_type: claims.token_type.clone(),
301 exp: claims.token_exp,
302 iat: claims.token_iat,
303 nbf: claims.token_nbf,
304 sub: claims.sub.clone(),
305 aud: claims.token_aud.clone(),
306 iss: claims.token_iss.clone(),
307 jti: Some(claims.jti.clone()),
308 additional_claims: claims.additional_claims.clone(),
309 }
310 }
311
312 pub fn validate_request_audience(&self, requested_audience: &[String]) -> bool {
314 if !self.config.validate_audience {
315 return true;
316 }
317
318 requested_audience
320 .iter()
321 .any(|aud| self.config.default_audience.contains(aud))
322 }
323
324 pub fn get_issuer(&self) -> &str {
326 &self.config.issuer
327 }
328
329 pub fn get_default_audience(&self) -> &[String] {
331 &self.config.default_audience
332 }
333
334 pub fn create_error_response(&self, error: &str, error_description: Option<&str>) -> Value {
336 let mut response = json!({
337 "error": error,
338 "active": false
339 });
340
341 if let Some(description) = error_description {
342 response["error_description"] = json!(description);
343 }
344
345 response
346 }
347
348 pub fn create_introspection_metadata(&self) -> Value {
350 json!({
351 "introspection_endpoint": format!("{}/introspect", self.config.issuer),
352 "introspection_endpoint_auth_methods_supported": [
353 "client_secret_basic",
354 "client_secret_post",
355 "private_key_jwt"
356 ],
357 "introspection_endpoint_auth_signing_alg_values_supported": [
358 "RS256", "RS384", "RS512",
359 "ES256", "ES384", "ES512",
360 "PS256", "PS384", "PS512"
361 ],
362 "introspection_signing_alg_values_supported": [
363 format!("{:?}", self.config.signing_algorithm)
364 ],
365 "introspection_response_format": "jwt"
366 })
367 }
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373 use std::collections::HashMap;
374
375 #[test]
376 fn test_jwt_introspection_response_creation() {
377 let config = JwtIntrospectionConfig::default();
378 let manager = JwtIntrospectionManager::new(config).unwrap();
379
380 let basic_response = BasicIntrospectionResponse {
381 active: true,
382 scope: Some("read write".to_string()),
383 client_id: Some("test_client".to_string()),
384 username: Some("user123".to_string()),
385 token_type: Some("access_token".to_string()),
386 exp: Some(Utc::now().timestamp() + 3600),
387 iat: Some(Utc::now().timestamp()),
388 nbf: None,
389 sub: Some("user123".to_string()),
390 aud: Some(vec!["https://api.example.com".to_string()]),
391 iss: Some("https://auth.example.com".to_string()),
392 jti: Some("token123".to_string()),
393 additional_claims: HashMap::new(),
394 };
395
396 let jwt_response = manager
397 .create_jwt_response(
398 basic_response,
399 Some(vec!["https://api.example.com".to_string()]),
400 Some("introspection123".to_string()),
401 )
402 .unwrap();
403
404 assert!(!jwt_response.is_empty());
405 assert!(jwt_response.split('.').count() == 3); }
407
408 #[test]
409 fn test_jwt_introspection_verification() {
410 let config = JwtIntrospectionConfig::default();
411 let manager = JwtIntrospectionManager::new(config).unwrap();
412
413 let basic_response = BasicIntrospectionResponse {
414 active: true,
415 scope: Some("read".to_string()),
416 client_id: Some("test_client".to_string()),
417 username: Some("user123".to_string()),
418 token_type: Some("access_token".to_string()),
419 exp: Some(Utc::now().timestamp() + 3600),
420 iat: Some(Utc::now().timestamp()),
421 nbf: None,
422 sub: Some("user123".to_string()),
423 aud: Some(vec!["https://api.example.com".to_string()]),
424 iss: Some("https://auth.example.com".to_string()),
425 jti: Some("token123".to_string()),
426 additional_claims: HashMap::new(),
427 };
428
429 let jwt_response = manager
430 .create_jwt_response(basic_response.clone(), None, None)
431 .unwrap();
432
433 let verified_claims = manager.verify_jwt_response(&jwt_response).unwrap();
434
435 assert_eq!(verified_claims.active, basic_response.active);
436 assert_eq!(verified_claims.scope, basic_response.scope);
437 assert_eq!(verified_claims.client_id, basic_response.client_id);
438 assert_eq!(verified_claims.username, basic_response.username);
439 }
440
441 #[test]
442 fn test_inactive_token_response() {
443 let config = JwtIntrospectionConfig::default();
444 let manager = JwtIntrospectionManager::new(config).unwrap();
445
446 let jwt_response = manager.create_inactive_response(None, None).unwrap();
447 let verified_claims = manager.verify_jwt_response(&jwt_response).unwrap();
448
449 assert!(!verified_claims.active);
450 assert!(verified_claims.scope.is_none());
451 assert!(verified_claims.client_id.is_none());
452 }
453
454 #[test]
455 fn test_audience_validation() {
456 let config = JwtIntrospectionConfig::default();
457 let manager = JwtIntrospectionManager::new(config).unwrap();
458
459 let valid_audience = vec!["https://api.example.com".to_string()];
460 assert!(manager.validate_request_audience(&valid_audience));
461
462 let invalid_audience = vec!["https://malicious.example.com".to_string()];
463 assert!(!manager.validate_request_audience(&invalid_audience));
464 }
465}