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