1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct TokenIntrospectionRequest {
21 pub token: String,
23
24 #[serde(skip_serializing_if = "Option::is_none")]
26 pub token_type_hint: Option<String>,
27
28 #[serde(flatten)]
30 pub additional_params: HashMap<String, String>,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct TokenIntrospectionResponse {
36 pub active: bool,
38
39 #[serde(skip_serializing_if = "Option::is_none")]
41 pub scope: Option<String>,
42
43 #[serde(skip_serializing_if = "Option::is_none")]
45 pub client_id: Option<String>,
46
47 #[serde(skip_serializing_if = "Option::is_none")]
49 pub username: Option<String>,
50
51 #[serde(skip_serializing_if = "Option::is_none")]
53 pub token_type: Option<String>,
54
55 #[serde(skip_serializing_if = "Option::is_none")]
57 pub exp: Option<i64>,
58
59 #[serde(skip_serializing_if = "Option::is_none")]
61 pub iat: Option<i64>,
62
63 #[serde(skip_serializing_if = "Option::is_none")]
65 pub nbf: Option<i64>,
66
67 #[serde(skip_serializing_if = "Option::is_none")]
69 pub sub: Option<String>,
70
71 #[serde(skip_serializing_if = "Option::is_none")]
73 pub aud: Option<Vec<String>>,
74
75 #[serde(skip_serializing_if = "Option::is_none")]
77 pub iss: Option<String>,
78
79 #[serde(skip_serializing_if = "Option::is_none")]
81 pub jti: Option<String>,
82
83 #[serde(flatten)]
85 pub additional_attributes: HashMap<String, serde_json::Value>,
86}
87
88impl TokenIntrospectionResponse {
89 pub fn inactive() -> Self {
91 Self {
92 active: false,
93 scope: None,
94 client_id: None,
95 username: None,
96 token_type: None,
97 exp: None,
98 iat: None,
99 nbf: None,
100 sub: None,
101 aud: None,
102 iss: None,
103 jti: None,
104 additional_attributes: HashMap::new(),
105 }
106 }
107
108 pub fn from_auth_token(
110 token: &AuthToken,
111 client_id: Option<String>,
112 issuer: Option<String>,
113 ) -> Self {
114 Self {
115 active: !token.is_expired(),
116 scope: if token.scopes.is_empty() {
117 None
118 } else {
119 Some(token.scopes.join(" "))
120 },
121 client_id,
122 username: Some(token.user_id.clone()),
123 token_type: Some("Bearer".to_string()),
124 exp: Some(token.expires_at.timestamp()),
125 iat: Some(token.issued_at.timestamp()),
126 nbf: Some(token.issued_at.timestamp()),
127 sub: Some(token.user_id.clone()),
128 aud: None, iss: issuer,
130 jti: Some(token.token_id.clone()),
131 additional_attributes: HashMap::new(),
132 }
133 }
134}
135
136#[derive(Debug, Clone)]
138pub struct TokenIntrospectionConfig {
139 pub enabled: bool,
141
142 pub issuer: String,
144
145 pub include_detailed_info: bool,
147
148 pub rate_limit_per_minute: u32,
150
151 pub supported_token_types: Vec<String>,
153
154 pub require_client_authentication: bool,
156}
157
158impl Default for TokenIntrospectionConfig {
159 fn default() -> Self {
160 Self {
161 enabled: true,
162 issuer: "https://auth.example.com".to_string(),
163 include_detailed_info: true,
164 rate_limit_per_minute: 100,
165 supported_token_types: vec!["access_token".to_string(), "refresh_token".to_string()],
166 require_client_authentication: true,
167 }
168 }
169}
170
171#[derive(Debug, Clone)]
173pub struct IntrospectionClientCredentials {
174 pub client_id: String,
176
177 pub client_secret: Option<String>,
179
180 pub client_assertion: Option<String>,
182
183 pub auth_method: ClientAuthMethod,
185}
186
187#[derive(Debug, Clone, PartialEq, Eq)]
189pub enum ClientAuthMethod {
190 ClientSecretBasic,
192
193 ClientSecretPost,
195
196 ClientSecretJwt,
198
199 PrivateKeyJwt,
201
202 None,
204}
205
206pub struct TokenIntrospectionService {
208 config: TokenIntrospectionConfig,
210
211 storage: Arc<dyn AuthStorage>,
213
214 #[allow(dead_code)]
216 token_manager: Arc<TokenManager>,
218
219 jwt_validator: Option<JwtAccessTokenValidator>,
221
222 rate_limiter: Arc<tokio::sync::RwLock<HashMap<String, Vec<DateTime<Utc>>>>>,
224}
225
226impl TokenIntrospectionService {
227 pub fn new(
229 config: TokenIntrospectionConfig,
230 storage: Arc<dyn AuthStorage>,
231 token_manager: Arc<TokenManager>,
232 jwt_validator: Option<JwtAccessTokenValidator>,
233 ) -> Self {
234 Self {
235 config,
236 storage,
237 token_manager,
238 jwt_validator,
239 rate_limiter: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
240 }
241 }
242
243 pub async fn introspect_token(
245 &self,
246 request: TokenIntrospectionRequest,
247 client_credentials: Option<IntrospectionClientCredentials>,
248 ) -> Result<TokenIntrospectionResponse> {
249 if !self.config.enabled {
251 return Err(AuthError::access_denied("Token introspection is disabled"));
252 }
253
254 if self.config.require_client_authentication {
256 let credentials = client_credentials.ok_or_else(|| {
257 AuthError::access_denied("Client authentication required for token introspection")
258 })?;
259
260 self.validate_client_credentials(&credentials).await?;
261
262 self.check_rate_limit(&credentials.client_id).await?;
264 }
265
266 let token_type = request.token_type_hint.as_deref().unwrap_or("access_token");
268
269 match token_type {
270 "access_token" => self.introspect_access_token(&request.token).await,
271 "refresh_token" => self.introspect_refresh_token(&request.token).await,
272 _ => self.introspect_unknown_token(&request.token).await,
273 }
274 }
275
276 async fn introspect_access_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
278 if let Some(ref jwt_validator) = self.jwt_validator
280 && let Ok(claims) = jwt_validator.validate_jwt_access_token(token)
281 {
282 return Ok(TokenIntrospectionResponse {
283 active: true,
284 scope: claims.scope,
285 client_id: Some(claims.client_id),
286 username: Some(claims.sub.clone()),
287 token_type: Some("Bearer".to_string()),
288 exp: Some(claims.exp),
289 iat: Some(claims.iat),
290 nbf: claims.nbf,
291 sub: Some(claims.sub),
292 aud: Some(claims.aud),
293 iss: Some(claims.iss),
294 jti: Some(claims.jti),
295 additional_attributes: HashMap::new(),
296 });
297 }
298
299 match self.storage.get_token(token).await? {
301 Some(auth_token) => {
302 if auth_token.is_expired() {
303 Ok(TokenIntrospectionResponse::inactive())
304 } else {
305 Ok(TokenIntrospectionResponse::from_auth_token(
306 &auth_token,
307 None, Some(self.config.issuer.clone()),
309 ))
310 }
311 }
312 None => Ok(TokenIntrospectionResponse::inactive()),
313 }
314 }
315
316 async fn introspect_refresh_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
318 match self.storage.get_token(token).await? {
321 Some(auth_token) => {
322 if let Some(ref refresh_token) = auth_token.refresh_token {
323 let token_matches: bool =
324 refresh_token.as_bytes().ct_eq(token.as_bytes()).into();
325 if token_matches && !auth_token.is_expired() {
326 let mut response = TokenIntrospectionResponse::from_auth_token(
327 &auth_token,
328 None,
329 Some(self.config.issuer.clone()),
330 );
331 response.token_type = Some("refresh_token".to_string());
332 Ok(response)
333 } else {
334 Ok(TokenIntrospectionResponse::inactive())
335 }
336 } else {
337 Ok(TokenIntrospectionResponse::inactive())
338 }
339 }
340 None => Ok(TokenIntrospectionResponse::inactive()),
341 }
342 }
343
344 async fn introspect_unknown_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
346 let access_result = self.introspect_access_token(token).await?;
348 if access_result.active {
349 return Ok(access_result);
350 }
351
352 self.introspect_refresh_token(token).await
353 }
354
355 async fn validate_client_credentials(
357 &self,
358 credentials: &IntrospectionClientCredentials,
359 ) -> Result<()> {
360 if credentials.client_id.is_empty() {
361 return Err(AuthError::access_denied("Invalid client_id"));
362 }
363
364 match credentials.auth_method {
365 ClientAuthMethod::ClientSecretBasic | ClientAuthMethod::ClientSecretPost => {
366 if let Some(client_secret) = &credentials.client_secret {
367 let client_key = format!("oauth_client:{}", credentials.client_id);
369 if let Some(client_data) = self.storage.get_kv(&client_key).await? {
370 let client_str = std::str::from_utf8(&client_data).map_err(|e| {
371 AuthError::internal(format!("Invalid UTF-8 in client data: {}", e))
372 })?;
373 let client: serde_json::Value =
374 serde_json::from_str(client_str).map_err(|e| {
375 AuthError::internal(format!("Failed to deserialize client: {}", e))
376 })?;
377
378 if let Some(stored_secret) =
379 client.get("client_secret").and_then(|v| v.as_str())
380 {
381 if !crate::security::secure_utils::constant_time_compare(
382 client_secret.as_bytes(),
383 stored_secret.as_bytes(),
384 ) {
385 return Err(AuthError::access_denied("Invalid client secret"));
386 }
387 } else {
388 return Err(AuthError::access_denied("Client secret not found"));
389 }
390 } else {
391 return Err(AuthError::access_denied("Client not found"));
392 }
393 } else {
394 return Err(AuthError::access_denied("Client secret required"));
395 }
396 }
397 ClientAuthMethod::ClientSecretJwt | ClientAuthMethod::PrivateKeyJwt => {
398 return Err(AuthError::access_denied(
406 "JWT client authentication is not supported at the introspection endpoint",
407 ));
408 }
409 ClientAuthMethod::None => {
410 }
412 }
413
414 Ok(())
415 }
416
417 async fn check_rate_limit(&self, client_id: &str) -> Result<()> {
419 let mut rate_limiter = self.rate_limiter.write().await;
420 let now = Utc::now();
421 let one_minute_ago = now - chrono::Duration::minutes(1);
422
423 let requests = rate_limiter
425 .entry(client_id.to_string())
426 .or_insert_with(Vec::new);
427 requests.retain(|×tamp| timestamp > one_minute_ago);
428
429 if requests.len() >= self.config.rate_limit_per_minute as usize {
430 return Err(AuthError::access_denied(
431 "Rate limit exceeded for token introspection",
432 ));
433 }
434
435 requests.push(now);
436 Ok(())
437 }
438
439 pub fn get_metadata(&self) -> HashMap<String, serde_json::Value> {
441 let mut metadata = HashMap::new();
442
443 metadata.insert(
444 "introspection_endpoint".to_string(),
445 serde_json::Value::String(format!("{}/introspect", self.config.issuer)),
446 );
447
448 metadata.insert(
449 "introspection_endpoint_auth_methods_supported".to_string(),
450 serde_json::Value::Array(vec![
451 serde_json::Value::String("client_secret_basic".to_string()),
452 serde_json::Value::String("client_secret_post".to_string()),
453 ]),
454 );
455
456 metadata.insert(
457 "token_introspection_supported".to_string(),
458 serde_json::Value::Bool(self.config.enabled),
459 );
460
461 metadata
462 }
463}
464
465pub struct TokenIntrospectionHandler {
467 service: Arc<TokenIntrospectionService>,
469}
470
471impl TokenIntrospectionHandler {
472 pub fn new(service: Arc<TokenIntrospectionService>) -> Self {
474 Self { service }
475 }
476
477 pub async fn handle_introspection_request(
479 &self,
480 request_body: &str,
481 authorization_header: Option<&str>,
482 ) -> Result<String> {
483 let request = self.parse_introspection_request(request_body)?;
485
486 let client_credentials =
488 self.extract_client_credentials(authorization_header, request_body)?;
489
490 let response = self
492 .service
493 .introspect_token(request, client_credentials)
494 .await?;
495
496 serde_json::to_string(&response).map_err(|e| {
498 AuthError::internal(format!("Failed to serialize introspection response: {}", e))
499 })
500 }
501
502 fn parse_introspection_request(&self, body: &str) -> Result<TokenIntrospectionRequest> {
504 let mut token = None;
505 let mut token_type_hint = None;
506 let mut additional_params = HashMap::new();
507
508 for pair in body.split('&') {
509 if let Some((key, value)) = pair.split_once('=') {
510 let key = urlencoding::decode(key).map_err(|e| {
511 AuthError::validation(format!("Invalid URL encoding in key: {}", e))
512 })?;
513 let value = urlencoding::decode(value).map_err(|e| {
514 AuthError::validation(format!("Invalid URL encoding in value: {}", e))
515 })?;
516
517 match key.as_ref() {
518 "token" => token = Some(value.to_string()),
519 "token_type_hint" => token_type_hint = Some(value.to_string()),
520 _ => {
521 additional_params.insert(key.to_string(), value.to_string());
522 }
523 }
524 }
525 }
526
527 let token =
528 token.ok_or_else(|| AuthError::validation("Missing required parameter: token"))?;
529
530 Ok(TokenIntrospectionRequest {
531 token,
532 token_type_hint,
533 additional_params,
534 })
535 }
536
537 fn extract_client_credentials(
539 &self,
540 authorization_header: Option<&str>,
541 request_body: &str,
542 ) -> Result<Option<IntrospectionClientCredentials>> {
543 if let Some(auth_header) = authorization_header
545 && let Some(encoded) = auth_header.strip_prefix("Basic ")
546 {
547 let decoded = general_purpose::STANDARD.decode(encoded).map_err(|e| {
548 AuthError::validation(format!("Invalid Basic auth encoding: {}", e))
549 })?;
550 let credentials = String::from_utf8(decoded)
551 .map_err(|e| AuthError::validation(format!("Invalid Basic auth UTF-8: {}", e)))?;
552
553 if let Some((client_id, client_secret)) = credentials.split_once(':') {
554 return Ok(Some(IntrospectionClientCredentials {
555 client_id: client_id.to_string(),
556 client_secret: Some(client_secret.to_string()),
557 client_assertion: None,
558 auth_method: ClientAuthMethod::ClientSecretBasic,
559 }));
560 }
561 }
562
563 let mut client_id = None;
565 let mut client_secret = None;
566
567 for pair in request_body.split('&') {
568 if let Some((key, value)) = pair.split_once('=') {
569 let key = urlencoding::decode(key).unwrap_or_default();
570 let value = urlencoding::decode(value).unwrap_or_default();
571
572 match key.as_ref() {
573 "client_id" => client_id = Some(value.to_string()),
574 "client_secret" => client_secret = Some(value.to_string()),
575 _ => {}
576 }
577 }
578 }
579
580 if let Some(client_id) = client_id {
581 return Ok(Some(IntrospectionClientCredentials {
582 client_id,
583 client_secret,
584 client_assertion: None,
585 auth_method: ClientAuthMethod::ClientSecretPost,
586 }));
587 }
588
589 Ok(None)
590 }
591}
592
593#[cfg(test)]
594mod tests {
595 use super::*;
596 use crate::testing::MockStorage;
597 use crate::tokens::TokenManager;
598 use chrono::Duration;
599
600 fn create_test_service() -> TokenIntrospectionService {
601 let config = TokenIntrospectionConfig::default();
602 let storage = Arc::new(MockStorage::new());
603 let secret = b"test-secret-key-32-bytes-minimum!";
604 let token_manager = Arc::new(TokenManager::new_hmac(
605 secret,
606 "test-issuer",
607 "test-audience",
608 ));
609
610 TokenIntrospectionService::new(config, storage, token_manager, None)
611 }
612
613 #[tokio::test]
614 async fn test_inactive_token_introspection() {
615 let service = create_test_service();
616
617 let client_data = serde_json::json!({
619 "client_id": "test-client",
620 "client_secret": "test-secret"
621 });
622 service
623 .storage
624 .store_kv(
625 "oauth_client:test-client",
626 client_data.to_string().as_bytes(),
627 None,
628 )
629 .await
630 .unwrap();
631
632 let client_credentials = IntrospectionClientCredentials {
634 client_id: "test-client".to_string(),
635 client_secret: Some("test-secret".to_string()),
636 client_assertion: None,
637 auth_method: ClientAuthMethod::ClientSecretBasic,
638 };
639
640 let request = TokenIntrospectionRequest {
641 token: "invalid-token".to_string(),
642 token_type_hint: Some("access_token".to_string()),
643 additional_params: HashMap::new(),
644 };
645
646 let response = service
647 .introspect_token(request, Some(client_credentials))
648 .await
649 .unwrap();
650 assert!(!response.active);
651 }
652
653 #[tokio::test]
654 async fn test_client_credentials_validation() {
655 let service = create_test_service();
656
657 let client_data = serde_json::json!({
659 "client_id": "test-client",
660 "client_secret": "test-secret"
661 });
662 service
663 .storage
664 .store_kv(
665 "oauth_client:test-client",
666 client_data.to_string().as_bytes(),
667 None,
668 )
669 .await
670 .unwrap();
671
672 let valid_credentials = IntrospectionClientCredentials {
673 client_id: "test-client".to_string(),
674 client_secret: Some("test-secret".to_string()),
675 client_assertion: None,
676 auth_method: ClientAuthMethod::ClientSecretBasic,
677 };
678
679 assert!(
681 service
682 .validate_client_credentials(&valid_credentials)
683 .await
684 .is_ok()
685 );
686
687 let invalid_credentials = IntrospectionClientCredentials {
688 client_id: "".to_string(),
689 client_secret: None,
690 client_assertion: None,
691 auth_method: ClientAuthMethod::ClientSecretBasic,
692 };
693
694 assert!(
696 service
697 .validate_client_credentials(&invalid_credentials)
698 .await
699 .is_err()
700 );
701 }
702
703 #[tokio::test]
704 async fn test_rate_limiting() {
705 let service = create_test_service();
706 let client_id = "test-client";
707
708 for _ in 0..10 {
710 assert!(service.check_rate_limit(client_id).await.is_ok());
711 }
712
713 for _ in 0..service.config.rate_limit_per_minute {
715 let _ = service.check_rate_limit(client_id).await;
716 }
717
718 assert!(service.check_rate_limit(client_id).await.is_err());
720 }
721
722 #[tokio::test]
723 async fn test_token_introspection_response_creation() {
724 let token = AuthToken {
725 token_id: "test-token".to_string(),
726 user_id: "test-user".to_string(),
727 access_token: "test-access-token".to_string(),
728 token_type: Some("Bearer".to_string()),
729 subject: None,
730 issuer: None,
731 refresh_token: None,
732 issued_at: Utc::now(),
733 expires_at: Utc::now() + Duration::hours(1),
734 scopes: vec!["read".to_string(), "write".to_string()].into(),
735 auth_method: "test".to_string(),
736 client_id: None,
737 user_profile: None,
738 permissions: vec!["read:data".to_string(), "write:data".to_string()].into(),
739 roles: vec!["user".to_string()].into(),
740 metadata: Default::default(),
741 };
742
743 let response = TokenIntrospectionResponse::from_auth_token(
744 &token,
745 Some("test-client".to_string()),
746 Some("https://auth.example.com".to_string()),
747 );
748
749 assert!(response.active);
750 assert_eq!(response.client_id.unwrap(), "test-client");
751 assert_eq!(response.username.unwrap(), "test-user");
752 assert_eq!(response.scope.unwrap(), "read write");
753 assert_eq!(response.token_type.unwrap(), "Bearer");
754 assert_eq!(response.iss.unwrap(), "https://auth.example.com");
755 }
756
757 #[test]
758 fn test_introspection_handler_request_parsing() {
759 let service = create_test_service();
760 let handler = TokenIntrospectionHandler::new(Arc::new(service));
761
762 let request_body = "token=test-token&token_type_hint=access_token";
763 let request = handler.parse_introspection_request(request_body).unwrap();
764
765 assert_eq!(request.token, "test-token");
766 assert_eq!(request.token_type_hint.unwrap(), "access_token");
767 }
768
769 #[test]
770 fn test_client_credentials_extraction() {
771 let service = create_test_service();
772 let handler = TokenIntrospectionHandler::new(Arc::new(service));
773
774 let auth_header = "Basic dGVzdC1jbGllbnQ6dGVzdC1zZWNyZXQ="; let credentials = handler
777 .extract_client_credentials(Some(auth_header), "")
778 .unwrap()
779 .unwrap();
780
781 assert_eq!(credentials.client_id, "test-client");
782 assert_eq!(credentials.client_secret.unwrap(), "test-secret");
783 assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretBasic);
784
785 let request_body = "token=test&client_id=test-client&client_secret=test-secret";
787 let credentials = handler
788 .extract_client_credentials(None, request_body)
789 .unwrap()
790 .unwrap();
791
792 assert_eq!(credentials.client_id, "test-client");
793 assert_eq!(credentials.client_secret.unwrap(), "test-secret");
794 assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretPost);
795 }
796
797 #[test]
798 fn test_metadata_generation() {
799 let service = create_test_service();
800 let metadata = service.get_metadata();
801
802 assert!(metadata.contains_key("introspection_endpoint"));
803 assert!(metadata.contains_key("introspection_endpoint_auth_methods_supported"));
804 assert!(metadata.contains_key("token_introspection_supported"));
805 }
806}