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