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 the client registry (`oauth2_client:{id}`, with the
409                    // old `oauth_client:{id}` key still read and moved)
410                    match crate::server::core::client_registry::load_record(
411                        self.storage.as_ref(),
412                        &credentials.client_id,
413                    )
414                    .await?
415                    {
416                        Some(record) if crate::client_secret::is_confidential(&record) => {
417                            if !crate::client_secret::authenticate(
418                                self.storage.as_ref(),
419                                &credentials.client_id,
420                                &record,
421                                client_secret,
422                            )
423                            .await
424                            {
425                                return Err(AuthError::access_denied("Invalid client secret"));
426                            }
427                        }
428                        Some(_) => {
429                            return Err(AuthError::access_denied("Client secret not found"));
430                        }
431                        None => 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                if let Some(client_assertion) = &credentials.client_assertion {
439                    // Validate JWT assertion
440                    if let Ok(claims) = self.token_manager.validate_jwt_token(client_assertion) {
441                        // An access, session or refresh token that merely names the client is
442                        // not a client assertion: the assertion must declare itself one.
443                        if claims.token_use() != Some("client_assertion") {
444                            return Err(AuthError::access_denied("Not a client assertion"));
445                        }
446                        if claims.sub != credentials.client_id {
447                            return Err(AuthError::access_denied(
448                                "JWT subject doesn't match client_id",
449                            ));
450                        }
451                        if claims.aud.is_empty() || !claims.aud.contains(&self.config.issuer) {
452                            return Err(AuthError::access_denied("Invalid JWT audience"));
453                        }
454                    } else {
455                        return Err(AuthError::access_denied("Invalid JWT assertion"));
456                    }
457                } else {
458                    return Err(AuthError::access_denied(
459                        "Client assertion required for JWT auth",
460                    ));
461                }
462            }
463            ClientAuthMethod::None => {
464                // Public client - no validation needed
465            }
466        }
467
468        Ok(())
469    }
470
471    /// Check rate limiting for introspection requests
472    async fn check_rate_limit(&self, client_id: &str) -> Result<()> {
473        let mut rate_limiter = self.rate_limiter.write().await;
474        let now = Utc::now();
475        let one_minute_ago = now - chrono::Duration::minutes(1);
476
477        // Clean up old entries and count recent requests
478        let requests = rate_limiter
479            .entry(client_id.to_string())
480            .or_insert_with(Vec::new);
481        requests.retain(|&timestamp| timestamp > one_minute_ago);
482
483        if requests.len() >= self.config.rate_limit_per_minute as usize {
484            return Err(AuthError::access_denied(
485                "Rate limit exceeded for token introspection",
486            ));
487        }
488
489        requests.push(now);
490        Ok(())
491    }
492
493    /// Get introspection endpoint metadata
494    pub fn get_metadata(&self) -> HashMap<String, serde_json::Value> {
495        let mut metadata = HashMap::new();
496
497        metadata.insert(
498            "introspection_endpoint".to_string(),
499            serde_json::Value::String(format!("{}/introspect", self.config.issuer)),
500        );
501
502        metadata.insert(
503            "introspection_endpoint_auth_methods_supported".to_string(),
504            serde_json::Value::Array(vec![
505                serde_json::Value::String("client_secret_basic".to_string()),
506                serde_json::Value::String("client_secret_post".to_string()),
507            ]),
508        );
509
510        metadata.insert(
511            "token_introspection_supported".to_string(),
512            serde_json::Value::Bool(self.config.enabled),
513        );
514
515        metadata
516    }
517}
518
519/// HTTP handler for token introspection endpoint
520pub struct TokenIntrospectionHandler {
521    /// Introspection service
522    service: Arc<TokenIntrospectionService>,
523}
524
525impl TokenIntrospectionHandler {
526    /// Create a new introspection handler
527    pub fn new(service: Arc<TokenIntrospectionService>) -> Self {
528        Self { service }
529    }
530
531    /// Handle HTTP POST request to introspection endpoint
532    pub async fn handle_introspection_request(
533        &self,
534        request_body: &str,
535        authorization_header: Option<&str>,
536    ) -> Result<String> {
537        // Parse request body (application/x-www-form-urlencoded)
538        let request = self.parse_introspection_request(request_body)?;
539
540        // Extract client credentials from Authorization header or request body
541        let client_credentials =
542            self.extract_client_credentials(authorization_header, request_body)?;
543
544        // Perform introspection
545        let response = self
546            .service
547            .introspect_token(request, client_credentials)
548            .await?;
549
550        // Serialize response as JSON
551        serde_json::to_string(&response).map_err(|e| {
552            AuthError::internal(format!("Failed to serialize introspection response: {}", e))
553        })
554    }
555
556    /// Parse introspection request from form data
557    fn parse_introspection_request(&self, body: &str) -> Result<TokenIntrospectionRequest> {
558        let mut token = None;
559        let mut token_type_hint = None;
560        let mut additional_params = HashMap::new();
561
562        for pair in body.split('&') {
563            if let Some((key, value)) = pair.split_once('=') {
564                let key = urlencoding::decode(key).map_err(|e| {
565                    AuthError::validation(format!("Invalid URL encoding in key: {}", e))
566                })?;
567                let value = urlencoding::decode(value).map_err(|e| {
568                    AuthError::validation(format!("Invalid URL encoding in value: {}", e))
569                })?;
570
571                match key.as_ref() {
572                    "token" => token = Some(value.to_string()),
573                    "token_type_hint" => token_type_hint = Some(value.to_string()),
574                    _ => {
575                        additional_params.insert(key.to_string(), value.to_string());
576                    }
577                }
578            }
579        }
580
581        let token =
582            token.ok_or_else(|| AuthError::validation("Missing required parameter: token"))?;
583
584        Ok(TokenIntrospectionRequest {
585            token,
586            token_type_hint,
587            additional_params,
588        })
589    }
590
591    /// Extract client credentials from Authorization header or request body
592    fn extract_client_credentials(
593        &self,
594        authorization_header: Option<&str>,
595        request_body: &str,
596    ) -> Result<Option<IntrospectionClientCredentials>> {
597        // Try Basic authentication first
598        if let Some(auth_header) = authorization_header
599            && let Some(encoded) = auth_header.strip_prefix("Basic ")
600        {
601            let decoded = general_purpose::STANDARD.decode(encoded).map_err(|e| {
602                AuthError::validation(format!("Invalid Basic auth encoding: {}", e))
603            })?;
604            let credentials = String::from_utf8(decoded)
605                .map_err(|e| AuthError::validation(format!("Invalid Basic auth UTF-8: {}", e)))?;
606
607            if let Some((client_id, client_secret)) = credentials.split_once(':') {
608                return Ok(Some(IntrospectionClientCredentials {
609                    client_id: client_id.to_string(),
610                    client_secret: Some(client_secret.to_string()),
611                    client_assertion: None,
612                    auth_method: ClientAuthMethod::ClientSecretBasic,
613                }));
614            }
615        }
616
617        // Try POST body credentials
618        let mut client_id = None;
619        let mut client_secret = None;
620
621        for pair in request_body.split('&') {
622            if let Some((key, value)) = pair.split_once('=') {
623                let key = urlencoding::decode(key).unwrap_or_default();
624                let value = urlencoding::decode(value).unwrap_or_default();
625
626                match key.as_ref() {
627                    "client_id" => client_id = Some(value.to_string()),
628                    "client_secret" => client_secret = Some(value.to_string()),
629                    _ => {}
630                }
631            }
632        }
633
634        if let Some(client_id) = client_id {
635            return Ok(Some(IntrospectionClientCredentials {
636                client_id,
637                client_secret,
638                client_assertion: None,
639                auth_method: ClientAuthMethod::ClientSecretPost,
640            }));
641        }
642
643        Ok(None)
644    }
645}
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650    use crate::testing::MockStorage;
651    use crate::tokens::TokenManager;
652    use chrono::Duration;
653
654    fn create_test_service() -> TokenIntrospectionService {
655        let config = TokenIntrospectionConfig::default();
656        let storage = Arc::new(MockStorage::new());
657        let secret = b"test-secret-key-32-bytes-minimum!";
658        let token_manager = Arc::new(TokenManager::new_hmac(
659            secret,
660            "test-issuer",
661            "test-audience",
662        ));
663
664        TokenIntrospectionService::new(config, storage, token_manager, None)
665    }
666
667    /// A token issued to a client is reported only to that client; another authenticated client
668    /// gets an inactive answer. A token with no client stays introspectable by any of them.
669    #[tokio::test]
670    async fn a_token_issued_to_a_client_is_reported_only_to_that_client() {
671        let service = create_test_service();
672        for (id, secret) in [("lib-a", "secret-a"), ("lib-b", "secret-b")] {
673            service
674                .storage
675                .store_kv(
676                    &format!("oauth_client:{id}"),
677                    serde_json::json!({"client_id": id, "client_secret": secret})
678                        .to_string()
679                        .as_bytes(),
680                    None,
681                )
682                .await
683                .unwrap();
684        }
685        let mut bound = AuthToken::new(
686            "alice",
687            "access-bound",
688            std::time::Duration::from_secs(300),
689            "test",
690        )
691        .with_client_id("lib-a");
692        bound.token_id = "opaque-bound".to_string();
693        let mut unbound = AuthToken::new(
694            "alice",
695            "access-unbound",
696            std::time::Duration::from_secs(300),
697            "test",
698        );
699        unbound.token_id = "opaque-unbound".to_string();
700        service.storage.store_token(&bound).await.unwrap();
701        service.storage.store_token(&unbound).await.unwrap();
702
703        let ask = |caller: &'static str, secret: &'static str, token: &'static str| {
704            let service = &service;
705            async move {
706                service
707                    .introspect_token(
708                        TokenIntrospectionRequest {
709                            token: token.to_string(),
710                            token_type_hint: Some("access_token".to_string()),
711                            additional_params: HashMap::new(),
712                        },
713                        Some(IntrospectionClientCredentials {
714                            client_id: caller.to_string(),
715                            client_secret: Some(secret.to_string()),
716                            client_assertion: None,
717                            auth_method: ClientAuthMethod::ClientSecretBasic,
718                        }),
719                    )
720                    .await
721                    .unwrap()
722            }
723        };
724
725        let owner = ask("lib-a", "secret-a", "opaque-bound").await;
726        assert!(owner.active);
727        assert_eq!(owner.client_id.as_deref(), Some("lib-a"));
728
729        let other = ask("lib-b", "secret-b", "opaque-bound").await;
730        assert!(!other.active, "another client must not see the token");
731        assert!(other.sub.is_none() && other.scope.is_none() && other.client_id.is_none());
732
733        // The limit: a token with no client is introspectable by any authenticated client.
734        assert!(ask("lib-b", "secret-b", "opaque-unbound").await.active);
735    }
736
737    /// A JWT-based client assertion is not an access/session token that happens to name the client.
738    #[tokio::test]
739    async fn a_client_assertion_must_declare_itself_one() {
740        let config = TokenIntrospectionConfig::default();
741        let issuer = config.issuer.clone();
742        let tm = Arc::new(TokenManager::new_hmac(
743            b"test-secret-key-32-bytes-minimum!",
744            "client-issuer",
745            issuer,
746        ));
747        let service =
748            TokenIntrospectionService::new(config, Arc::new(MockStorage::new()), tm.clone(), None);
749        let creds = |assertion: String| IntrospectionClientCredentials {
750            client_id: "rs-client".to_string(),
751            client_secret: None,
752            client_assertion: Some(assertion),
753            auth_method: ClientAuthMethod::PrivateKeyJwt,
754        };
755        let ttl = Some(std::time::Duration::from_secs(60));
756
757        // an ordinary access token whose subject happens to be the client id
758        let access = tm.create_jwt_token("rs-client", vec![], ttl).unwrap();
759        assert!(
760            service
761                .validate_client_credentials(&creds(access))
762                .await
763                .is_err()
764        );
765        // a refresh token likewise
766        let refresh = tm.create_refresh_jwt_token("rs-client", ttl).unwrap();
767        assert!(
768            service
769                .validate_client_credentials(&creds(refresh))
770                .await
771                .is_err()
772        );
773        // a token that declares itself a client assertion is accepted
774        let assertion = tm
775            .create_typed_jwt_token("rs-client", vec![], ttl, "client_assertion")
776            .unwrap();
777        assert!(
778            service
779                .validate_client_credentials(&creds(assertion))
780                .await
781                .is_ok()
782        );
783    }
784
785    #[tokio::test]
786    async fn test_inactive_token_introspection() {
787        let service = create_test_service();
788
789        // Register a test client first
790        let client_data = serde_json::json!({
791            "client_id": "test-client",
792            "client_secret": "test-secret"
793        });
794        service
795            .storage
796            .store_kv(
797                "oauth_client:test-client",
798                client_data.to_string().as_bytes(),
799                None,
800            )
801            .await
802            .unwrap();
803
804        // Provide client credentials for introspection
805        let client_credentials = IntrospectionClientCredentials {
806            client_id: "test-client".to_string(),
807            client_secret: Some("test-secret".to_string()),
808            client_assertion: None,
809            auth_method: ClientAuthMethod::ClientSecretBasic,
810        };
811
812        let request = TokenIntrospectionRequest {
813            token: "invalid-token".to_string(),
814            token_type_hint: Some("access_token".to_string()),
815            additional_params: HashMap::new(),
816        };
817
818        let response = service
819            .introspect_token(request, Some(client_credentials))
820            .await
821            .unwrap();
822        assert!(!response.active);
823    }
824
825    #[tokio::test]
826    async fn test_client_credentials_validation() {
827        let service = create_test_service();
828
829        // Register the test client in storage first
830        let client_data = serde_json::json!({
831            "client_id": "test-client",
832            "client_secret": "test-secret"
833        });
834        service
835            .storage
836            .store_kv(
837                "oauth_client:test-client",
838                client_data.to_string().as_bytes(),
839                None,
840            )
841            .await
842            .unwrap();
843
844        let valid_credentials = IntrospectionClientCredentials {
845            client_id: "test-client".to_string(),
846            client_secret: Some("test-secret".to_string()),
847            client_assertion: None,
848            auth_method: ClientAuthMethod::ClientSecretBasic,
849        };
850
851        // Should not error with valid credentials
852        assert!(
853            service
854                .validate_client_credentials(&valid_credentials)
855                .await
856                .is_ok()
857        );
858
859        let invalid_credentials = IntrospectionClientCredentials {
860            client_id: "".to_string(),
861            client_secret: None,
862            client_assertion: None,
863            auth_method: ClientAuthMethod::ClientSecretBasic,
864        };
865
866        // Should error with invalid credentials
867        assert!(
868            service
869                .validate_client_credentials(&invalid_credentials)
870                .await
871                .is_err()
872        );
873    }
874
875    #[tokio::test]
876    async fn test_rate_limiting() {
877        let service = create_test_service();
878        let client_id = "test-client";
879
880        // Should allow requests under the limit
881        for _ in 0..10 {
882            assert!(service.check_rate_limit(client_id).await.is_ok());
883        }
884
885        // Should deny requests over the limit
886        for _ in 0..service.config.rate_limit_per_minute {
887            let _ = service.check_rate_limit(client_id).await;
888        }
889
890        // This should be rate limited
891        assert!(service.check_rate_limit(client_id).await.is_err());
892    }
893
894    #[tokio::test]
895    async fn test_token_introspection_response_creation() {
896        let token = AuthToken {
897            token_id: "test-token".to_string(),
898            user_id: "test-user".to_string(),
899            access_token: "test-access-token".to_string(),
900            token_type: Some("Bearer".to_string()),
901            subject: None,
902            issuer: None,
903            refresh_token: None,
904            issued_at: Utc::now(),
905            expires_at: Utc::now() + Duration::hours(1),
906            scopes: vec!["read".to_string(), "write".to_string()].into(),
907            auth_method: "test".to_string(),
908            client_id: None,
909            user_profile: None,
910            permissions: vec!["read:data".to_string(), "write:data".to_string()].into(),
911            roles: vec!["user".to_string()].into(),
912            metadata: Default::default(),
913        };
914
915        let response = TokenIntrospectionResponse::from_auth_token(
916            &token,
917            Some("test-client".to_string()),
918            Some("https://auth.example.com".to_string()),
919        );
920
921        assert!(response.active);
922        assert_eq!(response.client_id.unwrap(), "test-client");
923        assert_eq!(response.username.unwrap(), "test-user");
924        assert_eq!(response.scope.unwrap(), "read write");
925        assert_eq!(response.token_type.unwrap(), "Bearer");
926        assert_eq!(response.iss.unwrap(), "https://auth.example.com");
927    }
928
929    #[test]
930    fn test_introspection_handler_request_parsing() {
931        let service = create_test_service();
932        let handler = TokenIntrospectionHandler::new(Arc::new(service));
933
934        let request_body = "token=test-token&token_type_hint=access_token";
935        let request = handler.parse_introspection_request(request_body).unwrap();
936
937        assert_eq!(request.token, "test-token");
938        assert_eq!(request.token_type_hint.unwrap(), "access_token");
939    }
940
941    #[test]
942    fn test_client_credentials_extraction() {
943        let service = create_test_service();
944        let handler = TokenIntrospectionHandler::new(Arc::new(service));
945
946        // Test Basic authentication
947        let auth_header = "Basic dGVzdC1jbGllbnQ6dGVzdC1zZWNyZXQ="; // test-client:test-secret
948        let credentials = handler
949            .extract_client_credentials(Some(auth_header), "")
950            .unwrap()
951            .unwrap();
952
953        assert_eq!(credentials.client_id, "test-client");
954        assert_eq!(credentials.client_secret.unwrap(), "test-secret");
955        assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretBasic);
956
957        // Test POST body authentication
958        let request_body = "token=test&client_id=test-client&client_secret=test-secret";
959        let credentials = handler
960            .extract_client_credentials(None, request_body)
961            .unwrap()
962            .unwrap();
963
964        assert_eq!(credentials.client_id, "test-client");
965        assert_eq!(credentials.client_secret.unwrap(), "test-secret");
966        assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretPost);
967    }
968
969    #[test]
970    fn test_metadata_generation() {
971        let service = create_test_service();
972        let metadata = service.get_metadata();
973
974        assert!(metadata.contains_key("introspection_endpoint"));
975        assert!(metadata.contains_key("introspection_endpoint_auth_methods_supported"));
976        assert!(metadata.contains_key("token_introspection_supported"));
977    }
978}