Skip to main content

auth_framework/server/jwt/
jwt_introspection.rs

1//! RFC 9701 - JSON Web Token (JWT) Response for OAuth Token Introspection
2//!
3//! This module implements JWT-formatted responses for OAuth 2.0 token introspection
4//! as defined in RFC 9701.
5
6use 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/// JWT introspection response claims as defined in RFC 9701
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct JwtIntrospectionClaims {
16    /// Issuer of the introspection response
17    pub iss: String,
18
19    /// Audience(s) for the introspection response
20    pub aud: Vec<String>,
21
22    /// Token identifier being introspected
23    pub jti: String,
24
25    /// Issued at time
26    pub iat: i64,
27
28    /// Expiration time of the introspection response
29    pub exp: i64,
30
31    /// Subject of the token being introspected
32    pub sub: Option<String>,
33
34    /// Client identifier
35    pub client_id: Option<String>,
36
37    /// Whether the token is active
38    pub active: bool,
39
40    /// Token type (e.g., "access_token", "refresh_token")
41    pub token_type: Option<String>,
42
43    /// Scope values associated with the token
44    pub scope: Option<String>,
45
46    /// Username of the resource owner
47    pub username: Option<String>,
48
49    /// Expiration time of the token being introspected
50    pub token_exp: Option<i64>,
51
52    /// Issued at time of the token being introspected
53    pub token_iat: Option<i64>,
54
55    /// Not before time of the token being introspected
56    pub token_nbf: Option<i64>,
57
58    /// Audience of the token being introspected
59    pub token_aud: Option<Vec<String>>,
60
61    /// Issuer of the token being introspected
62    pub token_iss: Option<String>,
63
64    /// Additional claims from the original token
65    #[serde(flatten)]
66    pub additional_claims: HashMap<String, Value>,
67}
68
69/// Basic introspection response (RFC 7662)
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct BasicIntrospectionResponse {
72    /// Whether the token is active
73    pub active: bool,
74
75    /// Scope values associated with the token
76    pub scope: Option<String>,
77
78    /// Client identifier
79    pub client_id: Option<String>,
80
81    /// Username of the resource owner
82    pub username: Option<String>,
83
84    /// Token type
85    pub token_type: Option<String>,
86
87    /// Expiration time
88    pub exp: Option<i64>,
89
90    /// Issued at time
91    pub iat: Option<i64>,
92
93    /// Not before time
94    pub nbf: Option<i64>,
95
96    /// Subject
97    pub sub: Option<String>,
98
99    /// Audience
100    pub aud: Option<Vec<String>>,
101
102    /// Issuer
103    pub iss: Option<String>,
104
105    /// Token identifier
106    pub jti: Option<String>,
107
108    /// Additional claims
109    #[serde(flatten)]
110    pub additional_claims: HashMap<String, Value>,
111}
112
113/// Configuration for JWT introspection responses
114#[derive(Debug, Clone)]
115pub struct JwtIntrospectionConfig {
116    /// Issuer identifier for introspection responses
117    pub issuer: String,
118
119    /// Default audience for introspection responses
120    pub default_audience: Vec<String>,
121
122    /// Expiration time for introspection responses (seconds)
123    pub response_expiration: i64,
124
125    /// Algorithm for signing introspection responses
126    pub signing_algorithm: Algorithm,
127
128    /// Whether to include the original token claims
129    pub include_token_claims: bool,
130
131    /// Whether to validate the audience in the introspection request
132    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, // 5 minutes
141            signing_algorithm: Algorithm::HS256,
142            include_token_claims: true,
143            validate_audience: true,
144        }
145    }
146}
147
148/// JWT Token Introspection Manager
149pub struct JwtIntrospectionManager {
150    config: JwtIntrospectionConfig,
151    private_key: EncodingKey,
152    public_key: DecodingKey,
153}
154
155impl JwtIntrospectionManager {
156    /// The shortest HMAC secret [`Self::with_hmac_secret`] accepts, in bytes.
157    pub const MIN_HMAC_SECRET_LEN: usize = 32;
158
159    /// Create a new JWT introspection manager that signs with a random key generated for this
160    /// instance.
161    ///
162    /// The key is not shared with any other instance or deployment, so responses verify only through
163    /// this manager. A resource server that verifies responses issued by another process needs both
164    /// ends to use the same secret: use [`Self::with_hmac_secret`].
165    ///
166    /// # Errors
167    /// If the operating system cannot provide randomness.
168    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    /// Create a manager that signs and verifies with the HMAC secret `secret`.
178    ///
179    /// Use this when the issuer and the verifier are different processes. The secret must be at least
180    /// [`Self::MIN_HMAC_SECRET_LEN`] bytes of random data; shorter secrets are refused.
181    ///
182    /// # Errors
183    /// If `secret` is shorter than [`Self::MIN_HMAC_SECRET_LEN`].
184    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    /// Create a JWT introspection response from basic introspection data
199    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    /// Verify and parse a JWT introspection response
240    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    /// Create an inactive token response (for expired or invalid tokens)
266    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    /// Convert JWT introspection claims back to basic response format
291    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    /// Validate introspection request audience
313    pub fn validate_request_audience(&self, requested_audience: &[String]) -> bool {
314        if !self.config.validate_audience {
315            return true;
316        }
317
318        // Check if any requested audience is in our allowed audiences
319        requested_audience
320            .iter()
321            .any(|aud| self.config.default_audience.contains(aud))
322    }
323
324    /// Get the issuer for introspection responses
325    pub fn get_issuer(&self) -> &str {
326        &self.config.issuer
327    }
328
329    /// Get the default audience
330    pub fn get_default_audience(&self) -> &[String] {
331        &self.config.default_audience
332    }
333
334    /// Create an error response for invalid requests
335    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    /// Create introspection metadata for discovery
349    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); // Valid JWT format
406    }
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}