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(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
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#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct TokenIntrospectionResponse {
49 pub active: bool,
51
52 #[serde(skip_serializing_if = "Option::is_none")]
54 pub scope: Option<String>,
55
56 #[serde(skip_serializing_if = "Option::is_none")]
58 pub client_id: Option<String>,
59
60 #[serde(skip_serializing_if = "Option::is_none")]
62 pub username: Option<String>,
63
64 #[serde(skip_serializing_if = "Option::is_none")]
66 pub token_type: Option<String>,
67
68 #[serde(skip_serializing_if = "Option::is_none")]
70 pub exp: Option<i64>,
71
72 #[serde(skip_serializing_if = "Option::is_none")]
74 pub iat: Option<i64>,
75
76 #[serde(skip_serializing_if = "Option::is_none")]
78 pub nbf: Option<i64>,
79
80 #[serde(skip_serializing_if = "Option::is_none")]
82 pub sub: Option<String>,
83
84 #[serde(skip_serializing_if = "Option::is_none")]
86 pub aud: Option<Vec<String>>,
87
88 #[serde(skip_serializing_if = "Option::is_none")]
90 pub iss: Option<String>,
91
92 #[serde(skip_serializing_if = "Option::is_none")]
94 pub jti: Option<String>,
95
96 #[serde(flatten)]
98 pub additional_attributes: HashMap<String, serde_json::Value>,
99}
100
101impl TokenIntrospectionResponse {
102 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 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, iss: issuer,
143 jti: Some(token.token_id.clone()),
144 additional_attributes: HashMap::new(),
145 }
146 }
147}
148
149#[derive(Debug, Clone)]
151pub struct TokenIntrospectionConfig {
152 pub enabled: bool,
154
155 pub issuer: String,
157
158 pub include_detailed_info: bool,
160
161 pub rate_limit_per_minute: u32,
163
164 pub supported_token_types: Vec<String>,
166
167 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#[derive(Clone)]
186pub struct IntrospectionClientCredentials {
187 pub client_id: String,
189
190 pub client_secret: Option<String>,
192
193 pub client_assertion: Option<String>,
195
196 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#[derive(Debug, Clone, PartialEq, Eq)]
219pub enum ClientAuthMethod {
220 ClientSecretBasic,
222
223 ClientSecretPost,
225
226 ClientSecretJwt,
228
229 PrivateKeyJwt,
231
232 None,
234}
235
236pub struct TokenIntrospectionService {
238 config: TokenIntrospectionConfig,
240
241 storage: Arc<dyn AuthStorage>,
243
244 #[allow(dead_code)]
246 token_manager: Arc<TokenManager>,
248
249 jwt_validator: Option<JwtAccessTokenValidator>,
251
252 rate_limiter: Arc<tokio::sync::RwLock<HashMap<String, Vec<DateTime<Utc>>>>>,
254}
255
256impl TokenIntrospectionService {
257 pub fn new(
259 config: TokenIntrospectionConfig,
260 storage: Arc<dyn AuthStorage>,
261 token_manager: Arc<TokenManager>,
262 jwt_validator: Option<JwtAccessTokenValidator>,
263 ) -> Self {
264 Self {
265 config,
266 storage,
267 token_manager,
268 jwt_validator,
269 rate_limiter: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
270 }
271 }
272
273 pub async fn introspect_token(
275 &self,
276 request: TokenIntrospectionRequest,
277 client_credentials: Option<IntrospectionClientCredentials>,
278 ) -> Result<TokenIntrospectionResponse> {
279 if !self.config.enabled {
281 return Err(AuthError::access_denied("Token introspection is disabled"));
282 }
283
284 if self.config.require_client_authentication {
286 let credentials = client_credentials.ok_or_else(|| {
287 AuthError::access_denied("Client authentication required for token introspection")
288 })?;
289
290 self.validate_client_credentials(&credentials).await?;
291
292 self.check_rate_limit(&credentials.client_id).await?;
294 }
295
296 let token_type = request.token_type_hint.as_deref().unwrap_or("access_token");
298
299 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
306 async fn introspect_access_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
308 if let Some(ref jwt_validator) = self.jwt_validator
310 && let Ok(claims) = jwt_validator.validate_jwt_access_token(token)
311 {
312 return Ok(TokenIntrospectionResponse {
313 active: true,
314 scope: claims.scope,
315 client_id: Some(claims.client_id),
316 username: Some(claims.sub.clone()),
317 token_type: Some("Bearer".to_string()),
318 exp: Some(claims.exp),
319 iat: Some(claims.iat),
320 nbf: claims.nbf,
321 sub: Some(claims.sub),
322 aud: Some(claims.aud),
323 iss: Some(claims.iss),
324 jti: Some(claims.jti),
325 additional_attributes: HashMap::new(),
326 });
327 }
328
329 match self.storage.get_token(token).await? {
331 Some(auth_token) => {
332 if auth_token.is_expired() {
333 Ok(TokenIntrospectionResponse::inactive())
334 } else {
335 Ok(TokenIntrospectionResponse::from_auth_token(
336 &auth_token,
337 None, Some(self.config.issuer.clone()),
339 ))
340 }
341 }
342 None => Ok(TokenIntrospectionResponse::inactive()),
343 }
344 }
345
346 async fn introspect_refresh_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
348 match self.storage.get_token(token).await? {
351 Some(auth_token) => {
352 if let Some(ref refresh_token) = auth_token.refresh_token {
353 let token_matches: bool =
354 refresh_token.as_bytes().ct_eq(token.as_bytes()).into();
355 if token_matches && !auth_token.is_expired() {
356 let mut response = TokenIntrospectionResponse::from_auth_token(
357 &auth_token,
358 None,
359 Some(self.config.issuer.clone()),
360 );
361 response.token_type = Some("refresh_token".to_string());
362 Ok(response)
363 } else {
364 Ok(TokenIntrospectionResponse::inactive())
365 }
366 } else {
367 Ok(TokenIntrospectionResponse::inactive())
368 }
369 }
370 None => Ok(TokenIntrospectionResponse::inactive()),
371 }
372 }
373
374 async fn introspect_unknown_token(&self, token: &str) -> Result<TokenIntrospectionResponse> {
376 let access_result = self.introspect_access_token(token).await?;
378 if access_result.active {
379 return Ok(access_result);
380 }
381
382 self.introspect_refresh_token(token).await
383 }
384
385 async fn validate_client_credentials(
387 &self,
388 credentials: &IntrospectionClientCredentials,
389 ) -> Result<()> {
390 if credentials.client_id.is_empty() {
391 return Err(AuthError::access_denied("Invalid client_id"));
392 }
393
394 match credentials.auth_method {
395 ClientAuthMethod::ClientSecretBasic | ClientAuthMethod::ClientSecretPost => {
396 if let Some(client_secret) = &credentials.client_secret {
397 let client_key = format!("oauth_client:{}", credentials.client_id);
399 if let Some(client_data) = self.storage.get_kv(&client_key).await? {
400 let client_str = std::str::from_utf8(&client_data).map_err(|e| {
401 AuthError::internal(format!("Invalid UTF-8 in client data: {}", e))
402 })?;
403 let client: serde_json::Value =
404 serde_json::from_str(client_str).map_err(|e| {
405 AuthError::internal(format!("Failed to deserialize client: {}", e))
406 })?;
407
408 if let Some(stored_secret) =
409 client.get("client_secret").and_then(|v| v.as_str())
410 {
411 if !crate::security::secure_utils::constant_time_compare(
412 client_secret.as_bytes(),
413 stored_secret.as_bytes(),
414 ) {
415 return Err(AuthError::access_denied("Invalid client secret"));
416 }
417 } else {
418 return Err(AuthError::access_denied("Client secret not found"));
419 }
420 } else {
421 return Err(AuthError::access_denied("Client not found"));
422 }
423 } else {
424 return Err(AuthError::access_denied("Client secret required"));
425 }
426 }
427 ClientAuthMethod::ClientSecretJwt | ClientAuthMethod::PrivateKeyJwt => {
428 return Err(AuthError::access_denied(
436 "JWT client authentication is not supported at the introspection endpoint",
437 ));
438 }
439 ClientAuthMethod::None => {
440 }
442 }
443
444 Ok(())
445 }
446
447 async fn check_rate_limit(&self, client_id: &str) -> Result<()> {
449 let mut rate_limiter = self.rate_limiter.write().await;
450 let now = Utc::now();
451 let one_minute_ago = now - chrono::Duration::minutes(1);
452
453 let requests = rate_limiter
455 .entry(client_id.to_string())
456 .or_insert_with(Vec::new);
457 requests.retain(|×tamp| timestamp > one_minute_ago);
458
459 if requests.len() >= self.config.rate_limit_per_minute as usize {
460 return Err(AuthError::access_denied(
461 "Rate limit exceeded for token introspection",
462 ));
463 }
464
465 requests.push(now);
466 Ok(())
467 }
468
469 pub fn get_metadata(&self) -> HashMap<String, serde_json::Value> {
471 let mut metadata = HashMap::new();
472
473 metadata.insert(
474 "introspection_endpoint".to_string(),
475 serde_json::Value::String(format!("{}/introspect", self.config.issuer)),
476 );
477
478 metadata.insert(
479 "introspection_endpoint_auth_methods_supported".to_string(),
480 serde_json::Value::Array(vec![
481 serde_json::Value::String("client_secret_basic".to_string()),
482 serde_json::Value::String("client_secret_post".to_string()),
483 ]),
484 );
485
486 metadata.insert(
487 "token_introspection_supported".to_string(),
488 serde_json::Value::Bool(self.config.enabled),
489 );
490
491 metadata
492 }
493}
494
495pub struct TokenIntrospectionHandler {
497 service: Arc<TokenIntrospectionService>,
499}
500
501impl TokenIntrospectionHandler {
502 pub fn new(service: Arc<TokenIntrospectionService>) -> Self {
504 Self { service }
505 }
506
507 pub async fn handle_introspection_request(
509 &self,
510 request_body: &str,
511 authorization_header: Option<&str>,
512 ) -> Result<String> {
513 let request = self.parse_introspection_request(request_body)?;
515
516 let client_credentials =
518 self.extract_client_credentials(authorization_header, request_body)?;
519
520 let response = self
522 .service
523 .introspect_token(request, client_credentials)
524 .await?;
525
526 serde_json::to_string(&response).map_err(|e| {
528 AuthError::internal(format!("Failed to serialize introspection response: {}", e))
529 })
530 }
531
532 fn parse_introspection_request(&self, body: &str) -> Result<TokenIntrospectionRequest> {
534 let mut token = None;
535 let mut token_type_hint = None;
536 let mut additional_params = HashMap::new();
537
538 for pair in body.split('&') {
539 if let Some((key, value)) = pair.split_once('=') {
540 let key = urlencoding::decode(key).map_err(|e| {
541 AuthError::validation(format!("Invalid URL encoding in key: {}", e))
542 })?;
543 let value = urlencoding::decode(value).map_err(|e| {
544 AuthError::validation(format!("Invalid URL encoding in value: {}", e))
545 })?;
546
547 match key.as_ref() {
548 "token" => token = Some(value.to_string()),
549 "token_type_hint" => token_type_hint = Some(value.to_string()),
550 _ => {
551 additional_params.insert(key.to_string(), value.to_string());
552 }
553 }
554 }
555 }
556
557 let token =
558 token.ok_or_else(|| AuthError::validation("Missing required parameter: token"))?;
559
560 Ok(TokenIntrospectionRequest {
561 token,
562 token_type_hint,
563 additional_params,
564 })
565 }
566
567 fn extract_client_credentials(
569 &self,
570 authorization_header: Option<&str>,
571 request_body: &str,
572 ) -> Result<Option<IntrospectionClientCredentials>> {
573 if let Some(auth_header) = authorization_header
575 && let Some(encoded) = auth_header.strip_prefix("Basic ")
576 {
577 let decoded = general_purpose::STANDARD.decode(encoded).map_err(|e| {
578 AuthError::validation(format!("Invalid Basic auth encoding: {}", e))
579 })?;
580 let credentials = String::from_utf8(decoded)
581 .map_err(|e| AuthError::validation(format!("Invalid Basic auth UTF-8: {}", e)))?;
582
583 if let Some((client_id, client_secret)) = credentials.split_once(':') {
584 return Ok(Some(IntrospectionClientCredentials {
585 client_id: client_id.to_string(),
586 client_secret: Some(client_secret.to_string()),
587 client_assertion: None,
588 auth_method: ClientAuthMethod::ClientSecretBasic,
589 }));
590 }
591 }
592
593 let mut client_id = None;
595 let mut client_secret = None;
596
597 for pair in request_body.split('&') {
598 if let Some((key, value)) = pair.split_once('=') {
599 let key = urlencoding::decode(key).unwrap_or_default();
600 let value = urlencoding::decode(value).unwrap_or_default();
601
602 match key.as_ref() {
603 "client_id" => client_id = Some(value.to_string()),
604 "client_secret" => client_secret = Some(value.to_string()),
605 _ => {}
606 }
607 }
608 }
609
610 if let Some(client_id) = client_id {
611 return Ok(Some(IntrospectionClientCredentials {
612 client_id,
613 client_secret,
614 client_assertion: None,
615 auth_method: ClientAuthMethod::ClientSecretPost,
616 }));
617 }
618
619 Ok(None)
620 }
621}
622
623#[cfg(test)]
624mod tests {
625 use super::*;
626 use crate::testing::MockStorage;
627 use crate::tokens::TokenManager;
628 use chrono::Duration;
629
630 fn create_test_service() -> TokenIntrospectionService {
631 let config = TokenIntrospectionConfig::default();
632 let storage = Arc::new(MockStorage::new());
633 let secret = b"test-secret-key-32-bytes-minimum!";
634 let token_manager = Arc::new(TokenManager::new_hmac(
635 secret,
636 "test-issuer",
637 "test-audience",
638 ));
639
640 TokenIntrospectionService::new(config, storage, token_manager, None)
641 }
642
643 #[tokio::test]
644 async fn test_inactive_token_introspection() {
645 let service = create_test_service();
646
647 let client_data = serde_json::json!({
649 "client_id": "test-client",
650 "client_secret": "test-secret"
651 });
652 service
653 .storage
654 .store_kv(
655 "oauth_client:test-client",
656 client_data.to_string().as_bytes(),
657 None,
658 )
659 .await
660 .unwrap();
661
662 let client_credentials = IntrospectionClientCredentials {
664 client_id: "test-client".to_string(),
665 client_secret: Some("test-secret".to_string()),
666 client_assertion: None,
667 auth_method: ClientAuthMethod::ClientSecretBasic,
668 };
669
670 let request = TokenIntrospectionRequest {
671 token: "invalid-token".to_string(),
672 token_type_hint: Some("access_token".to_string()),
673 additional_params: HashMap::new(),
674 };
675
676 let response = service
677 .introspect_token(request, Some(client_credentials))
678 .await
679 .unwrap();
680 assert!(!response.active);
681 }
682
683 #[tokio::test]
684 async fn test_client_credentials_validation() {
685 let service = create_test_service();
686
687 let client_data = serde_json::json!({
689 "client_id": "test-client",
690 "client_secret": "test-secret"
691 });
692 service
693 .storage
694 .store_kv(
695 "oauth_client:test-client",
696 client_data.to_string().as_bytes(),
697 None,
698 )
699 .await
700 .unwrap();
701
702 let valid_credentials = IntrospectionClientCredentials {
703 client_id: "test-client".to_string(),
704 client_secret: Some("test-secret".to_string()),
705 client_assertion: None,
706 auth_method: ClientAuthMethod::ClientSecretBasic,
707 };
708
709 assert!(
711 service
712 .validate_client_credentials(&valid_credentials)
713 .await
714 .is_ok()
715 );
716
717 let invalid_credentials = IntrospectionClientCredentials {
718 client_id: "".to_string(),
719 client_secret: None,
720 client_assertion: None,
721 auth_method: ClientAuthMethod::ClientSecretBasic,
722 };
723
724 assert!(
726 service
727 .validate_client_credentials(&invalid_credentials)
728 .await
729 .is_err()
730 );
731 }
732
733 #[tokio::test]
734 async fn test_rate_limiting() {
735 let service = create_test_service();
736 let client_id = "test-client";
737
738 for _ in 0..10 {
740 assert!(service.check_rate_limit(client_id).await.is_ok());
741 }
742
743 for _ in 0..service.config.rate_limit_per_minute {
745 let _ = service.check_rate_limit(client_id).await;
746 }
747
748 assert!(service.check_rate_limit(client_id).await.is_err());
750 }
751
752 #[tokio::test]
753 async fn test_token_introspection_response_creation() {
754 let token = AuthToken {
755 token_id: "test-token".to_string(),
756 user_id: "test-user".to_string(),
757 access_token: "test-access-token".to_string(),
758 token_type: Some("Bearer".to_string()),
759 subject: None,
760 issuer: None,
761 refresh_token: None,
762 issued_at: Utc::now(),
763 expires_at: Utc::now() + Duration::hours(1),
764 scopes: vec!["read".to_string(), "write".to_string()].into(),
765 auth_method: "test".to_string(),
766 client_id: None,
767 user_profile: None,
768 permissions: vec!["read:data".to_string(), "write:data".to_string()].into(),
769 roles: vec!["user".to_string()].into(),
770 metadata: Default::default(),
771 };
772
773 let response = TokenIntrospectionResponse::from_auth_token(
774 &token,
775 Some("test-client".to_string()),
776 Some("https://auth.example.com".to_string()),
777 );
778
779 assert!(response.active);
780 assert_eq!(response.client_id.unwrap(), "test-client");
781 assert_eq!(response.username.unwrap(), "test-user");
782 assert_eq!(response.scope.unwrap(), "read write");
783 assert_eq!(response.token_type.unwrap(), "Bearer");
784 assert_eq!(response.iss.unwrap(), "https://auth.example.com");
785 }
786
787 #[test]
788 fn test_introspection_handler_request_parsing() {
789 let service = create_test_service();
790 let handler = TokenIntrospectionHandler::new(Arc::new(service));
791
792 let request_body = "token=test-token&token_type_hint=access_token";
793 let request = handler.parse_introspection_request(request_body).unwrap();
794
795 assert_eq!(request.token, "test-token");
796 assert_eq!(request.token_type_hint.unwrap(), "access_token");
797 }
798
799 #[test]
800 fn test_client_credentials_extraction() {
801 let service = create_test_service();
802 let handler = TokenIntrospectionHandler::new(Arc::new(service));
803
804 let auth_header = "Basic dGVzdC1jbGllbnQ6dGVzdC1zZWNyZXQ="; let credentials = handler
807 .extract_client_credentials(Some(auth_header), "")
808 .unwrap()
809 .unwrap();
810
811 assert_eq!(credentials.client_id, "test-client");
812 assert_eq!(credentials.client_secret.unwrap(), "test-secret");
813 assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretBasic);
814
815 let request_body = "token=test&client_id=test-client&client_secret=test-secret";
817 let credentials = handler
818 .extract_client_credentials(None, request_body)
819 .unwrap()
820 .unwrap();
821
822 assert_eq!(credentials.client_id, "test-client");
823 assert_eq!(credentials.client_secret.unwrap(), "test-secret");
824 assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretPost);
825 }
826
827 #[test]
828 fn test_metadata_generation() {
829 let service = create_test_service();
830 let metadata = service.get_metadata();
831
832 assert!(metadata.contains_key("introspection_endpoint"));
833 assert!(metadata.contains_key("introspection_endpoint_auth_methods_supported"));
834 assert!(metadata.contains_key("token_introspection_supported"));
835 }
836}