Skip to main content

auth_framework/server/token_exchange/
token_introspection.rs

1//! OAuth 2.0 Token Introspection (RFC 7662)
2//!
3//! This module implements RFC 7662, which defines a method for a protected resource
4//! to query an OAuth 2.0 authorization server to determine meta-information about
5//! an OAuth 2.0 token.
6
7use crate::errors::{AuthError, Result};
8use crate::server::jwt::jwt_access_tokens::JwtAccessTokenValidator;
9use crate::storage::AuthStorage;
10use crate::tokens::{AuthToken, TokenManager};
11use base64::{Engine as _, engine::general_purpose};
12use chrono::{DateTime, Utc};
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15use std::sync::Arc;
16use subtle::ConstantTimeEq;
17
18/// Token introspection request (RFC 7662)
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct TokenIntrospectionRequest {
21    /// The string value of the token
22    pub token: String,
23
24    /// Optional hint about the type of token being introspected
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub token_type_hint: Option<String>,
27
28    /// Additional parameters for extension specifications
29    #[serde(flatten)]
30    pub additional_params: HashMap<String, String>,
31}
32
33/// Token introspection response (RFC 7662)
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct TokenIntrospectionResponse {
36    /// Boolean indicator of whether the token is currently active
37    pub active: bool,
38
39    /// Space-separated list of scopes associated with the token
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub scope: Option<String>,
42
43    /// Client identifier for the OAuth 2.0 client
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub client_id: Option<String>,
46
47    /// Human-readable identifier for the resource owner
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub username: Option<String>,
50
51    /// Type of the token (e.g., "Bearer")
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub token_type: Option<String>,
54
55    /// Integer timestamp of when the token expires
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub exp: Option<i64>,
58
59    /// Integer timestamp of when the token was issued
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub iat: Option<i64>,
62
63    /// Integer timestamp of when the token is not to be used before
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub nbf: Option<i64>,
66
67    /// Subject of the token (usually a machine-readable identifier)
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub sub: Option<String>,
70
71    /// Intended audience for the token
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub aud: Option<Vec<String>>,
74
75    /// Issuer of the token
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub iss: Option<String>,
78
79    /// Unique identifier for the token
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub jti: Option<String>,
82
83    /// Additional token attributes
84    #[serde(flatten)]
85    pub additional_attributes: HashMap<String, serde_json::Value>,
86}
87
88impl TokenIntrospectionResponse {
89    /// Create an inactive token response
90    pub fn inactive() -> Self {
91        Self {
92            active: false,
93            scope: None,
94            client_id: None,
95            username: None,
96            token_type: None,
97            exp: None,
98            iat: None,
99            nbf: None,
100            sub: None,
101            aud: None,
102            iss: None,
103            jti: None,
104            additional_attributes: HashMap::new(),
105        }
106    }
107
108    /// Create an active token response from AuthToken
109    pub fn from_auth_token(
110        token: &AuthToken,
111        client_id: Option<String>,
112        issuer: Option<String>,
113    ) -> Self {
114        Self {
115            active: !token.is_expired(),
116            scope: if token.scopes.is_empty() {
117                None
118            } else {
119                Some(token.scopes.join(" "))
120            },
121            client_id,
122            username: Some(token.user_id.clone()),
123            token_type: Some("Bearer".to_string()),
124            exp: Some(token.expires_at.timestamp()),
125            iat: Some(token.issued_at.timestamp()),
126            nbf: Some(token.issued_at.timestamp()),
127            sub: Some(token.user_id.clone()),
128            aud: None, // Set based on configuration
129            iss: issuer,
130            jti: Some(token.token_id.clone()),
131            additional_attributes: HashMap::new(),
132        }
133    }
134}
135
136/// Token introspection endpoint configuration
137#[derive(Debug, Clone)]
138pub struct TokenIntrospectionConfig {
139    /// Whether introspection is enabled
140    pub enabled: bool,
141
142    /// Issuer identifier
143    pub issuer: String,
144
145    /// Whether to include detailed token information
146    pub include_detailed_info: bool,
147
148    /// Maximum number of introspection requests per client per minute
149    pub rate_limit_per_minute: u32,
150
151    /// Supported token types for introspection
152    pub supported_token_types: Vec<String>,
153
154    /// Whether to validate client credentials for introspection
155    pub require_client_authentication: bool,
156}
157
158impl Default for TokenIntrospectionConfig {
159    fn default() -> Self {
160        Self {
161            enabled: true,
162            issuer: "https://auth.example.com".to_string(),
163            include_detailed_info: true,
164            rate_limit_per_minute: 100,
165            supported_token_types: vec!["access_token".to_string(), "refresh_token".to_string()],
166            require_client_authentication: true,
167        }
168    }
169}
170
171/// Token introspection client credentials
172#[derive(Clone)]
173pub struct IntrospectionClientCredentials {
174    /// Client identifier
175    pub client_id: String,
176
177    /// Client secret (if required)
178    pub client_secret: Option<String>,
179
180    /// Client assertion for JWT authentication
181    pub client_assertion: Option<String>,
182
183    /// Client authentication method
184    pub auth_method: ClientAuthMethod,
185}
186
187impl std::fmt::Debug for IntrospectionClientCredentials {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        let mut d = f.debug_struct("IntrospectionClientCredentials");
190        d.field("client_id", &self.client_id);
191        d.field(
192            "client_secret",
193            &crate::utils::redact::redacted(&self.client_secret),
194        );
195        d.field("client_assertion", &self.client_assertion);
196        d.field("auth_method", &self.auth_method);
197        d.finish()
198    }
199}
200
201/// Client authentication methods for introspection
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub enum ClientAuthMethod {
204    /// HTTP Basic authentication with client_id and client_secret
205    ClientSecretBasic,
206
207    /// POST body authentication with client_id and client_secret
208    ClientSecretPost,
209
210    /// JWT-based client authentication
211    ClientSecretJwt,
212
213    /// Private key JWT authentication
214    PrivateKeyJwt,
215
216    /// No authentication (public clients)
217    None,
218}
219
220/// Token introspection service
221pub struct TokenIntrospectionService {
222    /// Configuration
223    config: TokenIntrospectionConfig,
224
225    /// Storage backend
226    storage: Arc<dyn AuthStorage>,
227
228    /// Token manager for JWT validation
229    token_manager: Arc<TokenManager>,
230
231    /// JWT access token validator
232    jwt_validator: Option<JwtAccessTokenValidator>,
233
234    /// Rate limiting tracker
235    rate_limiter: Arc<tokio::sync::RwLock<HashMap<String, Vec<DateTime<Utc>>>>>,
236}
237
238impl TokenIntrospectionService {
239    /// Create a new token introspection service
240    pub fn new(
241        config: TokenIntrospectionConfig,
242        storage: Arc<dyn AuthStorage>,
243        token_manager: Arc<TokenManager>,
244        jwt_validator: Option<JwtAccessTokenValidator>,
245    ) -> Self {
246        Self {
247            config,
248            storage,
249            token_manager,
250            jwt_validator,
251            rate_limiter: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
252        }
253    }
254
255    /// Handle token introspection request
256    pub async fn introspect_token(
257        &self,
258        request: TokenIntrospectionRequest,
259        client_credentials: Option<IntrospectionClientCredentials>,
260    ) -> Result<TokenIntrospectionResponse> {
261        // Check if introspection is enabled
262        if !self.config.enabled {
263            return Err(AuthError::access_denied("Token introspection is disabled"));
264        }
265
266        // Validate client credentials if required
267        if self.config.require_client_authentication {
268            let credentials = client_credentials.ok_or_else(|| {
269                AuthError::access_denied("Client authentication required for token introspection")
270            })?;
271
272            self.validate_client_credentials(&credentials).await?;
273
274            // Check rate limiting
275            self.check_rate_limit(&credentials.client_id).await?;
276        }
277
278        // Determine token type and introspect accordingly
279        let token_type = request.token_type_hint.as_deref().unwrap_or("access_token");
280
281        match token_type {
282            "access_token" => self.introspect_access_token(&request.token).await,
283            "refresh_token" => self.introspect_refresh_token(&request.token).await,
284            _ => self.introspect_unknown_token(&request.token).await,
285        }
286    }
287
288    /// Introspect an access token
289    async fn introspect_access_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
290        // Try JWT access token first if validator is available
291        if let Some(ref jwt_validator) = self.jwt_validator
292            && let Ok(claims) = jwt_validator.validate_jwt_access_token(token)
293        {
294            return Ok(TokenIntrospectionResponse {
295                active: true,
296                scope: claims.scope,
297                client_id: Some(claims.client_id),
298                username: Some(claims.sub.clone()),
299                token_type: Some("Bearer".to_string()),
300                exp: Some(claims.exp),
301                iat: Some(claims.iat),
302                nbf: claims.nbf,
303                sub: Some(claims.sub),
304                aud: Some(claims.aud),
305                iss: Some(claims.iss),
306                jti: Some(claims.jti),
307                additional_attributes: HashMap::new(),
308            });
309        }
310
311        // Try opaque token lookup in storage
312        match self.storage.get_token(token).await? {
313            Some(auth_token) => {
314                if auth_token.is_expired() {
315                    Ok(TokenIntrospectionResponse::inactive())
316                } else {
317                    Ok(TokenIntrospectionResponse::from_auth_token(
318                        &auth_token,
319                        None, // Would need client ID from token metadata
320                        Some(self.config.issuer.clone()),
321                    ))
322                }
323            }
324            None => Ok(TokenIntrospectionResponse::inactive()),
325        }
326    }
327
328    /// Introspect a refresh token
329    async fn introspect_refresh_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
330        // Look up refresh token in storage
331        // This would need to be implemented in the storage backend
332        match self.storage.get_token(token).await? {
333            Some(auth_token) => {
334                if let Some(ref refresh_token) = auth_token.refresh_token {
335                    let token_matches: bool =
336                        refresh_token.as_bytes().ct_eq(token.as_bytes()).into();
337                    if token_matches && !auth_token.is_expired() {
338                        let mut response = TokenIntrospectionResponse::from_auth_token(
339                            &auth_token,
340                            None,
341                            Some(self.config.issuer.clone()),
342                        );
343                        response.token_type = Some("refresh_token".to_string());
344                        Ok(response)
345                    } else {
346                        Ok(TokenIntrospectionResponse::inactive())
347                    }
348                } else {
349                    Ok(TokenIntrospectionResponse::inactive())
350                }
351            }
352            None => Ok(TokenIntrospectionResponse::inactive()),
353        }
354    }
355
356    /// Introspect an unknown token type
357    async fn introspect_unknown_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
358        // Try as access token first, then refresh token
359        let access_result = self.introspect_access_token(token).await?;
360        if access_result.active {
361            return Ok(access_result);
362        }
363
364        self.introspect_refresh_token(token).await
365    }
366
367    /// Validate client credentials for introspection
368    async fn validate_client_credentials(
369        &self,
370        credentials: &IntrospectionClientCredentials,
371    ) -> Result<()> {
372        if credentials.client_id.is_empty() {
373            return Err(AuthError::access_denied("Invalid client_id"));
374        }
375
376        match credentials.auth_method {
377            ClientAuthMethod::ClientSecretBasic | ClientAuthMethod::ClientSecretPost => {
378                if let Some(client_secret) = &credentials.client_secret {
379                    // Validate against client registry if available
380                    let client_key = format!("oauth_client:{}", credentials.client_id);
381                    if let Some(client_data) = self.storage.get_kv(&client_key).await? {
382                        let client_str = std::str::from_utf8(&client_data).map_err(|e| {
383                            AuthError::internal(format!("Invalid UTF-8 in client data: {}", e))
384                        })?;
385                        let client: serde_json::Value =
386                            serde_json::from_str(client_str).map_err(|e| {
387                                AuthError::internal(format!("Failed to deserialize client: {}", e))
388                            })?;
389
390                        if let Some(stored_secret) =
391                            client.get("client_secret").and_then(|v| v.as_str())
392                        {
393                            if !crate::security::secure_utils::constant_time_compare(
394                                client_secret.as_bytes(),
395                                stored_secret.as_bytes(),
396                            ) {
397                                return Err(AuthError::access_denied("Invalid client secret"));
398                            }
399                        } else {
400                            return Err(AuthError::access_denied("Client secret not found"));
401                        }
402                    } else {
403                        return Err(AuthError::access_denied("Client not found"));
404                    }
405                } else {
406                    return Err(AuthError::access_denied("Client secret required"));
407                }
408            }
409            ClientAuthMethod::ClientSecretJwt | ClientAuthMethod::PrivateKeyJwt => {
410                if let Some(client_assertion) = &credentials.client_assertion {
411                    // Validate JWT assertion
412                    if let Ok(claims) = self.token_manager.validate_jwt_token(client_assertion) {
413                        // An access, session or refresh token that merely names the client is
414                        // not a client assertion: the assertion must declare itself one.
415                        if claims.token_use() != Some("client_assertion") {
416                            return Err(AuthError::access_denied("Not a client assertion"));
417                        }
418                        if claims.sub != credentials.client_id {
419                            return Err(AuthError::access_denied(
420                                "JWT subject doesn't match client_id",
421                            ));
422                        }
423                        if claims.aud.is_empty() || !claims.aud.contains(&self.config.issuer) {
424                            return Err(AuthError::access_denied("Invalid JWT audience"));
425                        }
426                    } else {
427                        return Err(AuthError::access_denied("Invalid JWT assertion"));
428                    }
429                } else {
430                    return Err(AuthError::access_denied(
431                        "Client assertion required for JWT auth",
432                    ));
433                }
434            }
435            ClientAuthMethod::None => {
436                // Public client - no validation needed
437            }
438        }
439
440        Ok(())
441    }
442
443    /// Check rate limiting for introspection requests
444    async fn check_rate_limit(&self, client_id: &str) -> Result<()> {
445        let mut rate_limiter = self.rate_limiter.write().await;
446        let now = Utc::now();
447        let one_minute_ago = now - chrono::Duration::minutes(1);
448
449        // Clean up old entries and count recent requests
450        let requests = rate_limiter
451            .entry(client_id.to_string())
452            .or_insert_with(Vec::new);
453        requests.retain(|&timestamp| timestamp > one_minute_ago);
454
455        if requests.len() >= self.config.rate_limit_per_minute as usize {
456            return Err(AuthError::access_denied(
457                "Rate limit exceeded for token introspection",
458            ));
459        }
460
461        requests.push(now);
462        Ok(())
463    }
464
465    /// Get introspection endpoint metadata
466    pub fn get_metadata(&self) -> HashMap<String, serde_json::Value> {
467        let mut metadata = HashMap::new();
468
469        metadata.insert(
470            "introspection_endpoint".to_string(),
471            serde_json::Value::String(format!("{}/introspect", self.config.issuer)),
472        );
473
474        metadata.insert(
475            "introspection_endpoint_auth_methods_supported".to_string(),
476            serde_json::Value::Array(vec![
477                serde_json::Value::String("client_secret_basic".to_string()),
478                serde_json::Value::String("client_secret_post".to_string()),
479            ]),
480        );
481
482        metadata.insert(
483            "token_introspection_supported".to_string(),
484            serde_json::Value::Bool(self.config.enabled),
485        );
486
487        metadata
488    }
489}
490
491/// HTTP handler for token introspection endpoint
492pub struct TokenIntrospectionHandler {
493    /// Introspection service
494    service: Arc<TokenIntrospectionService>,
495}
496
497impl TokenIntrospectionHandler {
498    /// Create a new introspection handler
499    pub fn new(service: Arc<TokenIntrospectionService>) -> Self {
500        Self { service }
501    }
502
503    /// Handle HTTP POST request to introspection endpoint
504    pub async fn handle_introspection_request(
505        &self,
506        request_body: &str,
507        authorization_header: Option<&str>,
508    ) -> Result<String> {
509        // Parse request body (application/x-www-form-urlencoded)
510        let request = self.parse_introspection_request(request_body)?;
511
512        // Extract client credentials from Authorization header or request body
513        let client_credentials =
514            self.extract_client_credentials(authorization_header, request_body)?;
515
516        // Perform introspection
517        let response = self
518            .service
519            .introspect_token(request, client_credentials)
520            .await?;
521
522        // Serialize response as JSON
523        serde_json::to_string(&response).map_err(|e| {
524            AuthError::internal(format!("Failed to serialize introspection response: {}", e))
525        })
526    }
527
528    /// Parse introspection request from form data
529    fn parse_introspection_request(&self, body: &str) -> Result<TokenIntrospectionRequest> {
530        let mut token = None;
531        let mut token_type_hint = None;
532        let mut additional_params = HashMap::new();
533
534        for pair in body.split('&') {
535            if let Some((key, value)) = pair.split_once('=') {
536                let key = urlencoding::decode(key).map_err(|e| {
537                    AuthError::validation(format!("Invalid URL encoding in key: {}", e))
538                })?;
539                let value = urlencoding::decode(value).map_err(|e| {
540                    AuthError::validation(format!("Invalid URL encoding in value: {}", e))
541                })?;
542
543                match key.as_ref() {
544                    "token" => token = Some(value.to_string()),
545                    "token_type_hint" => token_type_hint = Some(value.to_string()),
546                    _ => {
547                        additional_params.insert(key.to_string(), value.to_string());
548                    }
549                }
550            }
551        }
552
553        let token =
554            token.ok_or_else(|| AuthError::validation("Missing required parameter: token"))?;
555
556        Ok(TokenIntrospectionRequest {
557            token,
558            token_type_hint,
559            additional_params,
560        })
561    }
562
563    /// Extract client credentials from Authorization header or request body
564    fn extract_client_credentials(
565        &self,
566        authorization_header: Option<&str>,
567        request_body: &str,
568    ) -> Result<Option<IntrospectionClientCredentials>> {
569        // Try Basic authentication first
570        if let Some(auth_header) = authorization_header
571            && let Some(encoded) = auth_header.strip_prefix("Basic ")
572        {
573            let decoded = general_purpose::STANDARD.decode(encoded).map_err(|e| {
574                AuthError::validation(format!("Invalid Basic auth encoding: {}", e))
575            })?;
576            let credentials = String::from_utf8(decoded)
577                .map_err(|e| AuthError::validation(format!("Invalid Basic auth UTF-8: {}", e)))?;
578
579            if let Some((client_id, client_secret)) = credentials.split_once(':') {
580                return Ok(Some(IntrospectionClientCredentials {
581                    client_id: client_id.to_string(),
582                    client_secret: Some(client_secret.to_string()),
583                    client_assertion: None,
584                    auth_method: ClientAuthMethod::ClientSecretBasic,
585                }));
586            }
587        }
588
589        // Try POST body credentials
590        let mut client_id = None;
591        let mut client_secret = None;
592
593        for pair in request_body.split('&') {
594            if let Some((key, value)) = pair.split_once('=') {
595                let key = urlencoding::decode(key).unwrap_or_default();
596                let value = urlencoding::decode(value).unwrap_or_default();
597
598                match key.as_ref() {
599                    "client_id" => client_id = Some(value.to_string()),
600                    "client_secret" => client_secret = Some(value.to_string()),
601                    _ => {}
602                }
603            }
604        }
605
606        if let Some(client_id) = client_id {
607            return Ok(Some(IntrospectionClientCredentials {
608                client_id,
609                client_secret,
610                client_assertion: None,
611                auth_method: ClientAuthMethod::ClientSecretPost,
612            }));
613        }
614
615        Ok(None)
616    }
617}
618
619#[cfg(test)]
620mod tests {
621    use super::*;
622    use crate::testing::MockStorage;
623    use crate::tokens::TokenManager;
624    use chrono::Duration;
625
626    fn create_test_service() -> TokenIntrospectionService {
627        let config = TokenIntrospectionConfig::default();
628        let storage = Arc::new(MockStorage::new());
629        let secret = b"test-secret-key-32-bytes-minimum!";
630        let token_manager = Arc::new(TokenManager::new_hmac(
631            secret,
632            "test-issuer",
633            "test-audience",
634        ));
635
636        TokenIntrospectionService::new(config, storage, token_manager, None)
637    }
638
639    /// A JWT-based client assertion is not an access/session token that happens to name the client.
640    #[tokio::test]
641    async fn a_client_assertion_must_declare_itself_one() {
642        let config = TokenIntrospectionConfig::default();
643        let issuer = config.issuer.clone();
644        let tm = Arc::new(TokenManager::new_hmac(
645            b"test-secret-key-32-bytes-minimum!",
646            "client-issuer",
647            issuer,
648        ));
649        let service =
650            TokenIntrospectionService::new(config, Arc::new(MockStorage::new()), tm.clone(), None);
651        let creds = |assertion: String| IntrospectionClientCredentials {
652            client_id: "rs-client".to_string(),
653            client_secret: None,
654            client_assertion: Some(assertion),
655            auth_method: ClientAuthMethod::PrivateKeyJwt,
656        };
657        let ttl = Some(std::time::Duration::from_secs(60));
658
659        // an ordinary access token whose subject happens to be the client id
660        let access = tm.create_jwt_token("rs-client", vec![], ttl).unwrap();
661        assert!(
662            service
663                .validate_client_credentials(&creds(access))
664                .await
665                .is_err()
666        );
667        // a refresh token likewise
668        let refresh = tm.create_refresh_jwt_token("rs-client", ttl).unwrap();
669        assert!(
670            service
671                .validate_client_credentials(&creds(refresh))
672                .await
673                .is_err()
674        );
675        // a token that declares itself a client assertion is accepted
676        let assertion = tm
677            .create_typed_jwt_token("rs-client", vec![], ttl, "client_assertion")
678            .unwrap();
679        assert!(
680            service
681                .validate_client_credentials(&creds(assertion))
682                .await
683                .is_ok()
684        );
685    }
686
687    #[tokio::test]
688    async fn test_inactive_token_introspection() {
689        let service = create_test_service();
690
691        // Register a test client first
692        let client_data = serde_json::json!({
693            "client_id": "test-client",
694            "client_secret": "test-secret"
695        });
696        service
697            .storage
698            .store_kv(
699                "oauth_client:test-client",
700                client_data.to_string().as_bytes(),
701                None,
702            )
703            .await
704            .unwrap();
705
706        // Provide client credentials for introspection
707        let client_credentials = IntrospectionClientCredentials {
708            client_id: "test-client".to_string(),
709            client_secret: Some("test-secret".to_string()),
710            client_assertion: None,
711            auth_method: ClientAuthMethod::ClientSecretBasic,
712        };
713
714        let request = TokenIntrospectionRequest {
715            token: "invalid-token".to_string(),
716            token_type_hint: Some("access_token".to_string()),
717            additional_params: HashMap::new(),
718        };
719
720        let response = service
721            .introspect_token(request, Some(client_credentials))
722            .await
723            .unwrap();
724        assert!(!response.active);
725    }
726
727    #[tokio::test]
728    async fn test_client_credentials_validation() {
729        let service = create_test_service();
730
731        // Register the test client in storage first
732        let client_data = serde_json::json!({
733            "client_id": "test-client",
734            "client_secret": "test-secret"
735        });
736        service
737            .storage
738            .store_kv(
739                "oauth_client:test-client",
740                client_data.to_string().as_bytes(),
741                None,
742            )
743            .await
744            .unwrap();
745
746        let valid_credentials = IntrospectionClientCredentials {
747            client_id: "test-client".to_string(),
748            client_secret: Some("test-secret".to_string()),
749            client_assertion: None,
750            auth_method: ClientAuthMethod::ClientSecretBasic,
751        };
752
753        // Should not error with valid credentials
754        assert!(
755            service
756                .validate_client_credentials(&valid_credentials)
757                .await
758                .is_ok()
759        );
760
761        let invalid_credentials = IntrospectionClientCredentials {
762            client_id: "".to_string(),
763            client_secret: None,
764            client_assertion: None,
765            auth_method: ClientAuthMethod::ClientSecretBasic,
766        };
767
768        // Should error with invalid credentials
769        assert!(
770            service
771                .validate_client_credentials(&invalid_credentials)
772                .await
773                .is_err()
774        );
775    }
776
777    #[tokio::test]
778    async fn test_rate_limiting() {
779        let service = create_test_service();
780        let client_id = "test-client";
781
782        // Should allow requests under the limit
783        for _ in 0..10 {
784            assert!(service.check_rate_limit(client_id).await.is_ok());
785        }
786
787        // Should deny requests over the limit
788        for _ in 0..service.config.rate_limit_per_minute {
789            let _ = service.check_rate_limit(client_id).await;
790        }
791
792        // This should be rate limited
793        assert!(service.check_rate_limit(client_id).await.is_err());
794    }
795
796    #[tokio::test]
797    async fn test_token_introspection_response_creation() {
798        let token = AuthToken {
799            token_id: "test-token".to_string(),
800            user_id: "test-user".to_string(),
801            access_token: "test-access-token".to_string(),
802            token_type: Some("Bearer".to_string()),
803            subject: None,
804            issuer: None,
805            refresh_token: None,
806            issued_at: Utc::now(),
807            expires_at: Utc::now() + Duration::hours(1),
808            scopes: vec!["read".to_string(), "write".to_string()].into(),
809            auth_method: "test".to_string(),
810            client_id: None,
811            user_profile: None,
812            permissions: vec!["read:data".to_string(), "write:data".to_string()].into(),
813            roles: vec!["user".to_string()].into(),
814            metadata: Default::default(),
815        };
816
817        let response = TokenIntrospectionResponse::from_auth_token(
818            &token,
819            Some("test-client".to_string()),
820            Some("https://auth.example.com".to_string()),
821        );
822
823        assert!(response.active);
824        assert_eq!(response.client_id.unwrap(), "test-client");
825        assert_eq!(response.username.unwrap(), "test-user");
826        assert_eq!(response.scope.unwrap(), "read write");
827        assert_eq!(response.token_type.unwrap(), "Bearer");
828        assert_eq!(response.iss.unwrap(), "https://auth.example.com");
829    }
830
831    #[test]
832    fn test_introspection_handler_request_parsing() {
833        let service = create_test_service();
834        let handler = TokenIntrospectionHandler::new(Arc::new(service));
835
836        let request_body = "token=test-token&token_type_hint=access_token";
837        let request = handler.parse_introspection_request(request_body).unwrap();
838
839        assert_eq!(request.token, "test-token");
840        assert_eq!(request.token_type_hint.unwrap(), "access_token");
841    }
842
843    #[test]
844    fn test_client_credentials_extraction() {
845        let service = create_test_service();
846        let handler = TokenIntrospectionHandler::new(Arc::new(service));
847
848        // Test Basic authentication
849        let auth_header = "Basic dGVzdC1jbGllbnQ6dGVzdC1zZWNyZXQ="; // test-client:test-secret
850        let credentials = handler
851            .extract_client_credentials(Some(auth_header), "")
852            .unwrap()
853            .unwrap();
854
855        assert_eq!(credentials.client_id, "test-client");
856        assert_eq!(credentials.client_secret.unwrap(), "test-secret");
857        assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretBasic);
858
859        // Test POST body authentication
860        let request_body = "token=test&client_id=test-client&client_secret=test-secret";
861        let credentials = handler
862            .extract_client_credentials(None, request_body)
863            .unwrap()
864            .unwrap();
865
866        assert_eq!(credentials.client_id, "test-client");
867        assert_eq!(credentials.client_secret.unwrap(), "test-secret");
868        assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretPost);
869    }
870
871    #[test]
872    fn test_metadata_generation() {
873        let service = create_test_service();
874        let metadata = service.get_metadata();
875
876        assert!(metadata.contains_key("introspection_endpoint"));
877        assert!(metadata.contains_key("introspection_endpoint_auth_methods_supported"));
878        assert!(metadata.contains_key("token_introspection_supported"));
879    }
880}