Skip to main content

auth_framework/server/token_exchange/
token_introspection.rs

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