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