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