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