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 token_manager: Arc<TokenManager>,
216
217 jwt_validator: Option<JwtAccessTokenValidator>,
219
220 rate_limiter: Arc<tokio::sync::RwLock<HashMap<String, Vec<DateTime<Utc>>>>>,
222}
223
224impl TokenIntrospectionService {
225 pub fn new(
227 config: TokenIntrospectionConfig,
228 storage: Arc<dyn AuthStorage>,
229 token_manager: Arc<TokenManager>,
230 jwt_validator: Option<JwtAccessTokenValidator>,
231 ) -> Self {
232 Self {
233 config,
234 storage,
235 token_manager,
236 jwt_validator,
237 rate_limiter: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
238 }
239 }
240
241 pub async fn introspect_token(
243 &self,
244 request: TokenIntrospectionRequest,
245 client_credentials: Option<IntrospectionClientCredentials>,
246 ) -> Result<TokenIntrospectionResponse> {
247 if !self.config.enabled {
249 return Err(AuthError::access_denied("Token introspection is disabled"));
250 }
251
252 if self.config.require_client_authentication {
254 let credentials = client_credentials.ok_or_else(|| {
255 AuthError::access_denied("Client authentication required for token introspection")
256 })?;
257
258 self.validate_client_credentials(&credentials).await?;
259
260 self.check_rate_limit(&credentials.client_id).await?;
262 }
263
264 let token_type = request.token_type_hint.as_deref().unwrap_or("access_token");
266
267 match token_type {
268 "access_token" => self.introspect_access_token(&request.token).await,
269 "refresh_token" => self.introspect_refresh_token(&request.token).await,
270 _ => self.introspect_unknown_token(&request.token).await,
271 }
272 }
273
274 async fn introspect_access_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
276 if let Some(ref jwt_validator) = self.jwt_validator
278 && let Ok(claims) = jwt_validator.validate_jwt_access_token(token)
279 {
280 return Ok(TokenIntrospectionResponse {
281 active: true,
282 scope: claims.scope,
283 client_id: Some(claims.client_id),
284 username: Some(claims.sub.clone()),
285 token_type: Some("Bearer".to_string()),
286 exp: Some(claims.exp),
287 iat: Some(claims.iat),
288 nbf: claims.nbf,
289 sub: Some(claims.sub),
290 aud: Some(claims.aud),
291 iss: Some(claims.iss),
292 jti: Some(claims.jti),
293 additional_attributes: HashMap::new(),
294 });
295 }
296
297 match self.storage.get_token(token).await? {
299 Some(auth_token) => {
300 if auth_token.is_expired() {
301 Ok(TokenIntrospectionResponse::inactive())
302 } else {
303 Ok(TokenIntrospectionResponse::from_auth_token(
304 &auth_token,
305 None, Some(self.config.issuer.clone()),
307 ))
308 }
309 }
310 None => Ok(TokenIntrospectionResponse::inactive()),
311 }
312 }
313
314 async fn introspect_refresh_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
316 match self.storage.get_token(token).await? {
319 Some(auth_token) => {
320 if let Some(ref refresh_token) = auth_token.refresh_token {
321 let token_matches: bool =
322 refresh_token.as_bytes().ct_eq(token.as_bytes()).into();
323 if token_matches && !auth_token.is_expired() {
324 let mut response = TokenIntrospectionResponse::from_auth_token(
325 &auth_token,
326 None,
327 Some(self.config.issuer.clone()),
328 );
329 response.token_type = Some("refresh_token".to_string());
330 Ok(response)
331 } else {
332 Ok(TokenIntrospectionResponse::inactive())
333 }
334 } else {
335 Ok(TokenIntrospectionResponse::inactive())
336 }
337 }
338 None => Ok(TokenIntrospectionResponse::inactive()),
339 }
340 }
341
342 async fn introspect_unknown_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
344 let access_result = self.introspect_access_token(token).await?;
346 if access_result.active {
347 return Ok(access_result);
348 }
349
350 self.introspect_refresh_token(token).await
351 }
352
353 async fn validate_client_credentials(
355 &self,
356 credentials: &IntrospectionClientCredentials,
357 ) -> Result<()> {
358 if credentials.client_id.is_empty() {
359 return Err(AuthError::access_denied("Invalid client_id"));
360 }
361
362 match credentials.auth_method {
363 ClientAuthMethod::ClientSecretBasic | ClientAuthMethod::ClientSecretPost => {
364 if let Some(client_secret) = &credentials.client_secret {
365 let client_key = format!("oauth_client:{}", credentials.client_id);
367 if let Some(client_data) = self.storage.get_kv(&client_key).await? {
368 let client_str = std::str::from_utf8(&client_data).map_err(|e| {
369 AuthError::internal(format!("Invalid UTF-8 in client data: {}", e))
370 })?;
371 let client: serde_json::Value =
372 serde_json::from_str(client_str).map_err(|e| {
373 AuthError::internal(format!("Failed to deserialize client: {}", e))
374 })?;
375
376 if let Some(stored_secret) =
377 client.get("client_secret").and_then(|v| v.as_str())
378 {
379 if !crate::security::secure_utils::constant_time_compare(
380 client_secret.as_bytes(),
381 stored_secret.as_bytes(),
382 ) {
383 return Err(AuthError::access_denied("Invalid client secret"));
384 }
385 } else {
386 return Err(AuthError::access_denied("Client secret not found"));
387 }
388 } else {
389 return Err(AuthError::access_denied("Client not found"));
390 }
391 } else {
392 return Err(AuthError::access_denied("Client secret required"));
393 }
394 }
395 ClientAuthMethod::ClientSecretJwt | ClientAuthMethod::PrivateKeyJwt => {
396 return Err(AuthError::access_denied(
404 "JWT client authentication is not supported at the introspection endpoint",
405 ));
406 }
407 ClientAuthMethod::None => {
408 }
410 }
411
412 Ok(())
413 }
414
415 async fn check_rate_limit(&self, client_id: &str) -> Result<()> {
417 let mut rate_limiter = self.rate_limiter.write().await;
418 let now = Utc::now();
419 let one_minute_ago = now - chrono::Duration::minutes(1);
420
421 let requests = rate_limiter
423 .entry(client_id.to_string())
424 .or_insert_with(Vec::new);
425 requests.retain(|×tamp| timestamp > one_minute_ago);
426
427 if requests.len() >= self.config.rate_limit_per_minute as usize {
428 return Err(AuthError::access_denied(
429 "Rate limit exceeded for token introspection",
430 ));
431 }
432
433 requests.push(now);
434 Ok(())
435 }
436
437 pub fn get_metadata(&self) -> HashMap<String, serde_json::Value> {
439 let mut metadata = HashMap::new();
440
441 metadata.insert(
442 "introspection_endpoint".to_string(),
443 serde_json::Value::String(format!("{}/introspect", self.config.issuer)),
444 );
445
446 metadata.insert(
447 "introspection_endpoint_auth_methods_supported".to_string(),
448 serde_json::Value::Array(vec![
449 serde_json::Value::String("client_secret_basic".to_string()),
450 serde_json::Value::String("client_secret_post".to_string()),
451 ]),
452 );
453
454 metadata.insert(
455 "token_introspection_supported".to_string(),
456 serde_json::Value::Bool(self.config.enabled),
457 );
458
459 metadata
460 }
461}
462
463pub struct TokenIntrospectionHandler {
465 service: Arc<TokenIntrospectionService>,
467}
468
469impl TokenIntrospectionHandler {
470 pub fn new(service: Arc<TokenIntrospectionService>) -> Self {
472 Self { service }
473 }
474
475 pub async fn handle_introspection_request(
477 &self,
478 request_body: &str,
479 authorization_header: Option<&str>,
480 ) -> Result<String> {
481 let request = self.parse_introspection_request(request_body)?;
483
484 let client_credentials =
486 self.extract_client_credentials(authorization_header, request_body)?;
487
488 let response = self
490 .service
491 .introspect_token(request, client_credentials)
492 .await?;
493
494 serde_json::to_string(&response).map_err(|e| {
496 AuthError::internal(format!("Failed to serialize introspection response: {}", e))
497 })
498 }
499
500 fn parse_introspection_request(&self, body: &str) -> Result<TokenIntrospectionRequest> {
502 let mut token = None;
503 let mut token_type_hint = None;
504 let mut additional_params = HashMap::new();
505
506 for pair in body.split('&') {
507 if let Some((key, value)) = pair.split_once('=') {
508 let key = urlencoding::decode(key).map_err(|e| {
509 AuthError::validation(format!("Invalid URL encoding in key: {}", e))
510 })?;
511 let value = urlencoding::decode(value).map_err(|e| {
512 AuthError::validation(format!("Invalid URL encoding in value: {}", e))
513 })?;
514
515 match key.as_ref() {
516 "token" => token = Some(value.to_string()),
517 "token_type_hint" => token_type_hint = Some(value.to_string()),
518 _ => {
519 additional_params.insert(key.to_string(), value.to_string());
520 }
521 }
522 }
523 }
524
525 let token =
526 token.ok_or_else(|| AuthError::validation("Missing required parameter: token"))?;
527
528 Ok(TokenIntrospectionRequest {
529 token,
530 token_type_hint,
531 additional_params,
532 })
533 }
534
535 fn extract_client_credentials(
537 &self,
538 authorization_header: Option<&str>,
539 request_body: &str,
540 ) -> Result<Option<IntrospectionClientCredentials>> {
541 if let Some(auth_header) = authorization_header
543 && let Some(encoded) = auth_header.strip_prefix("Basic ")
544 {
545 let decoded = general_purpose::STANDARD.decode(encoded).map_err(|e| {
546 AuthError::validation(format!("Invalid Basic auth encoding: {}", e))
547 })?;
548 let credentials = String::from_utf8(decoded)
549 .map_err(|e| AuthError::validation(format!("Invalid Basic auth UTF-8: {}", e)))?;
550
551 if let Some((client_id, client_secret)) = credentials.split_once(':') {
552 return Ok(Some(IntrospectionClientCredentials {
553 client_id: client_id.to_string(),
554 client_secret: Some(client_secret.to_string()),
555 client_assertion: None,
556 auth_method: ClientAuthMethod::ClientSecretBasic,
557 }));
558 }
559 }
560
561 let mut client_id = None;
563 let mut client_secret = None;
564
565 for pair in request_body.split('&') {
566 if let Some((key, value)) = pair.split_once('=') {
567 let key = urlencoding::decode(key).unwrap_or_default();
568 let value = urlencoding::decode(value).unwrap_or_default();
569
570 match key.as_ref() {
571 "client_id" => client_id = Some(value.to_string()),
572 "client_secret" => client_secret = Some(value.to_string()),
573 _ => {}
574 }
575 }
576 }
577
578 if let Some(client_id) = client_id {
579 return Ok(Some(IntrospectionClientCredentials {
580 client_id,
581 client_secret,
582 client_assertion: None,
583 auth_method: ClientAuthMethod::ClientSecretPost,
584 }));
585 }
586
587 Ok(None)
588 }
589}
590
591#[cfg(test)]
592mod tests {
593 use super::*;
594 use crate::testing::MockStorage;
595 use crate::tokens::TokenManager;
596 use chrono::Duration;
597
598 fn create_test_service() -> TokenIntrospectionService {
599 let config = TokenIntrospectionConfig::default();
600 let storage = Arc::new(MockStorage::new());
601 let secret = b"test-secret-key-32-bytes-minimum!";
602 let token_manager = Arc::new(TokenManager::new_hmac(
603 secret,
604 "test-issuer",
605 "test-audience",
606 ));
607
608 TokenIntrospectionService::new(config, storage, token_manager, None)
609 }
610
611 #[tokio::test]
612 async fn test_inactive_token_introspection() {
613 let service = create_test_service();
614
615 let client_data = serde_json::json!({
617 "client_id": "test-client",
618 "client_secret": "test-secret"
619 });
620 service
621 .storage
622 .store_kv(
623 "oauth_client:test-client",
624 client_data.to_string().as_bytes(),
625 None,
626 )
627 .await
628 .unwrap();
629
630 let client_credentials = IntrospectionClientCredentials {
632 client_id: "test-client".to_string(),
633 client_secret: Some("test-secret".to_string()),
634 client_assertion: None,
635 auth_method: ClientAuthMethod::ClientSecretBasic,
636 };
637
638 let request = TokenIntrospectionRequest {
639 token: "invalid-token".to_string(),
640 token_type_hint: Some("access_token".to_string()),
641 additional_params: HashMap::new(),
642 };
643
644 let response = service
645 .introspect_token(request, Some(client_credentials))
646 .await
647 .unwrap();
648 assert!(!response.active);
649 }
650
651 #[tokio::test]
652 async fn test_client_credentials_validation() {
653 let service = create_test_service();
654
655 let client_data = serde_json::json!({
657 "client_id": "test-client",
658 "client_secret": "test-secret"
659 });
660 service
661 .storage
662 .store_kv(
663 "oauth_client:test-client",
664 client_data.to_string().as_bytes(),
665 None,
666 )
667 .await
668 .unwrap();
669
670 let valid_credentials = IntrospectionClientCredentials {
671 client_id: "test-client".to_string(),
672 client_secret: Some("test-secret".to_string()),
673 client_assertion: None,
674 auth_method: ClientAuthMethod::ClientSecretBasic,
675 };
676
677 assert!(
679 service
680 .validate_client_credentials(&valid_credentials)
681 .await
682 .is_ok()
683 );
684
685 let invalid_credentials = IntrospectionClientCredentials {
686 client_id: "".to_string(),
687 client_secret: None,
688 client_assertion: None,
689 auth_method: ClientAuthMethod::ClientSecretBasic,
690 };
691
692 assert!(
694 service
695 .validate_client_credentials(&invalid_credentials)
696 .await
697 .is_err()
698 );
699 }
700
701 #[tokio::test]
702 async fn test_rate_limiting() {
703 let service = create_test_service();
704 let client_id = "test-client";
705
706 for _ in 0..10 {
708 assert!(service.check_rate_limit(client_id).await.is_ok());
709 }
710
711 for _ in 0..service.config.rate_limit_per_minute {
713 let _ = service.check_rate_limit(client_id).await;
714 }
715
716 assert!(service.check_rate_limit(client_id).await.is_err());
718 }
719
720 #[tokio::test]
721 async fn test_token_introspection_response_creation() {
722 let token = AuthToken {
723 token_id: "test-token".to_string(),
724 user_id: "test-user".to_string(),
725 access_token: "test-access-token".to_string(),
726 token_type: Some("Bearer".to_string()),
727 subject: None,
728 issuer: None,
729 refresh_token: None,
730 issued_at: Utc::now(),
731 expires_at: Utc::now() + Duration::hours(1),
732 scopes: vec!["read".to_string(), "write".to_string()].into(),
733 auth_method: "test".to_string(),
734 client_id: None,
735 user_profile: None,
736 permissions: vec!["read:data".to_string(), "write:data".to_string()].into(),
737 roles: vec!["user".to_string()].into(),
738 metadata: Default::default(),
739 };
740
741 let response = TokenIntrospectionResponse::from_auth_token(
742 &token,
743 Some("test-client".to_string()),
744 Some("https://auth.example.com".to_string()),
745 );
746
747 assert!(response.active);
748 assert_eq!(response.client_id.unwrap(), "test-client");
749 assert_eq!(response.username.unwrap(), "test-user");
750 assert_eq!(response.scope.unwrap(), "read write");
751 assert_eq!(response.token_type.unwrap(), "Bearer");
752 assert_eq!(response.iss.unwrap(), "https://auth.example.com");
753 }
754
755 #[test]
756 fn test_introspection_handler_request_parsing() {
757 let service = create_test_service();
758 let handler = TokenIntrospectionHandler::new(Arc::new(service));
759
760 let request_body = "token=test-token&token_type_hint=access_token";
761 let request = handler.parse_introspection_request(request_body).unwrap();
762
763 assert_eq!(request.token, "test-token");
764 assert_eq!(request.token_type_hint.unwrap(), "access_token");
765 }
766
767 #[test]
768 fn test_client_credentials_extraction() {
769 let service = create_test_service();
770 let handler = TokenIntrospectionHandler::new(Arc::new(service));
771
772 let auth_header = "Basic dGVzdC1jbGllbnQ6dGVzdC1zZWNyZXQ="; let credentials = handler
775 .extract_client_credentials(Some(auth_header), "")
776 .unwrap()
777 .unwrap();
778
779 assert_eq!(credentials.client_id, "test-client");
780 assert_eq!(credentials.client_secret.unwrap(), "test-secret");
781 assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretBasic);
782
783 let request_body = "token=test&client_id=test-client&client_secret=test-secret";
785 let credentials = handler
786 .extract_client_credentials(None, request_body)
787 .unwrap()
788 .unwrap();
789
790 assert_eq!(credentials.client_id, "test-client");
791 assert_eq!(credentials.client_secret.unwrap(), "test-secret");
792 assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretPost);
793 }
794
795 #[test]
796 fn test_metadata_generation() {
797 let service = create_test_service();
798 let metadata = service.get_metadata();
799
800 assert!(metadata.contains_key("introspection_endpoint"));
801 assert!(metadata.contains_key("introspection_endpoint_auth_methods_supported"));
802 assert!(metadata.contains_key("token_introspection_supported"));
803 }
804}