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