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