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