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 if let Some(client_assertion) = &credentials.client_assertion {
397 if let Ok(claims) = self.token_manager.validate_jwt_token(client_assertion) {
399 if claims.token_use() != Some("client_assertion") {
402 return Err(AuthError::access_denied("Not a client assertion"));
403 }
404 if claims.sub != credentials.client_id {
405 return Err(AuthError::access_denied(
406 "JWT subject doesn't match client_id",
407 ));
408 }
409 if claims.aud.is_empty() || !claims.aud.contains(&self.config.issuer) {
410 return Err(AuthError::access_denied("Invalid JWT audience"));
411 }
412 } else {
413 return Err(AuthError::access_denied("Invalid JWT assertion"));
414 }
415 } else {
416 return Err(AuthError::access_denied(
417 "Client assertion required for JWT auth",
418 ));
419 }
420 }
421 ClientAuthMethod::None => {
422 }
424 }
425
426 Ok(())
427 }
428
429 async fn check_rate_limit(&self, client_id: &str) -> Result<()> {
431 let mut rate_limiter = self.rate_limiter.write().await;
432 let now = Utc::now();
433 let one_minute_ago = now - chrono::Duration::minutes(1);
434
435 let requests = rate_limiter
437 .entry(client_id.to_string())
438 .or_insert_with(Vec::new);
439 requests.retain(|×tamp| timestamp > one_minute_ago);
440
441 if requests.len() >= self.config.rate_limit_per_minute as usize {
442 return Err(AuthError::access_denied(
443 "Rate limit exceeded for token introspection",
444 ));
445 }
446
447 requests.push(now);
448 Ok(())
449 }
450
451 pub fn get_metadata(&self) -> HashMap<String, serde_json::Value> {
453 let mut metadata = HashMap::new();
454
455 metadata.insert(
456 "introspection_endpoint".to_string(),
457 serde_json::Value::String(format!("{}/introspect", self.config.issuer)),
458 );
459
460 metadata.insert(
461 "introspection_endpoint_auth_methods_supported".to_string(),
462 serde_json::Value::Array(vec![
463 serde_json::Value::String("client_secret_basic".to_string()),
464 serde_json::Value::String("client_secret_post".to_string()),
465 ]),
466 );
467
468 metadata.insert(
469 "token_introspection_supported".to_string(),
470 serde_json::Value::Bool(self.config.enabled),
471 );
472
473 metadata
474 }
475}
476
477pub struct TokenIntrospectionHandler {
479 service: Arc<TokenIntrospectionService>,
481}
482
483impl TokenIntrospectionHandler {
484 pub fn new(service: Arc<TokenIntrospectionService>) -> Self {
486 Self { service }
487 }
488
489 pub async fn handle_introspection_request(
491 &self,
492 request_body: &str,
493 authorization_header: Option<&str>,
494 ) -> Result<String> {
495 let request = self.parse_introspection_request(request_body)?;
497
498 let client_credentials =
500 self.extract_client_credentials(authorization_header, request_body)?;
501
502 let response = self
504 .service
505 .introspect_token(request, client_credentials)
506 .await?;
507
508 serde_json::to_string(&response).map_err(|e| {
510 AuthError::internal(format!("Failed to serialize introspection response: {}", e))
511 })
512 }
513
514 fn parse_introspection_request(&self, body: &str) -> Result<TokenIntrospectionRequest> {
516 let mut token = None;
517 let mut token_type_hint = None;
518 let mut additional_params = HashMap::new();
519
520 for pair in body.split('&') {
521 if let Some((key, value)) = pair.split_once('=') {
522 let key = urlencoding::decode(key).map_err(|e| {
523 AuthError::validation(format!("Invalid URL encoding in key: {}", e))
524 })?;
525 let value = urlencoding::decode(value).map_err(|e| {
526 AuthError::validation(format!("Invalid URL encoding in value: {}", e))
527 })?;
528
529 match key.as_ref() {
530 "token" => token = Some(value.to_string()),
531 "token_type_hint" => token_type_hint = Some(value.to_string()),
532 _ => {
533 additional_params.insert(key.to_string(), value.to_string());
534 }
535 }
536 }
537 }
538
539 let token =
540 token.ok_or_else(|| AuthError::validation("Missing required parameter: token"))?;
541
542 Ok(TokenIntrospectionRequest {
543 token,
544 token_type_hint,
545 additional_params,
546 })
547 }
548
549 fn extract_client_credentials(
551 &self,
552 authorization_header: Option<&str>,
553 request_body: &str,
554 ) -> Result<Option<IntrospectionClientCredentials>> {
555 if let Some(auth_header) = authorization_header
557 && let Some(encoded) = auth_header.strip_prefix("Basic ")
558 {
559 let decoded = general_purpose::STANDARD.decode(encoded).map_err(|e| {
560 AuthError::validation(format!("Invalid Basic auth encoding: {}", e))
561 })?;
562 let credentials = String::from_utf8(decoded)
563 .map_err(|e| AuthError::validation(format!("Invalid Basic auth UTF-8: {}", e)))?;
564
565 if let Some((client_id, client_secret)) = credentials.split_once(':') {
566 return Ok(Some(IntrospectionClientCredentials {
567 client_id: client_id.to_string(),
568 client_secret: Some(client_secret.to_string()),
569 client_assertion: None,
570 auth_method: ClientAuthMethod::ClientSecretBasic,
571 }));
572 }
573 }
574
575 let mut client_id = None;
577 let mut client_secret = None;
578
579 for pair in request_body.split('&') {
580 if let Some((key, value)) = pair.split_once('=') {
581 let key = urlencoding::decode(key).unwrap_or_default();
582 let value = urlencoding::decode(value).unwrap_or_default();
583
584 match key.as_ref() {
585 "client_id" => client_id = Some(value.to_string()),
586 "client_secret" => client_secret = Some(value.to_string()),
587 _ => {}
588 }
589 }
590 }
591
592 if let Some(client_id) = client_id {
593 return Ok(Some(IntrospectionClientCredentials {
594 client_id,
595 client_secret,
596 client_assertion: None,
597 auth_method: ClientAuthMethod::ClientSecretPost,
598 }));
599 }
600
601 Ok(None)
602 }
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608 use crate::testing::MockStorage;
609 use crate::tokens::TokenManager;
610 use chrono::Duration;
611
612 fn create_test_service() -> TokenIntrospectionService {
613 let config = TokenIntrospectionConfig::default();
614 let storage = Arc::new(MockStorage::new());
615 let secret = b"test-secret-key-32-bytes-minimum!";
616 let token_manager = Arc::new(TokenManager::new_hmac(
617 secret,
618 "test-issuer",
619 "test-audience",
620 ));
621
622 TokenIntrospectionService::new(config, storage, token_manager, None)
623 }
624
625 #[tokio::test]
627 async fn a_client_assertion_must_declare_itself_one() {
628 let config = TokenIntrospectionConfig::default();
629 let issuer = config.issuer.clone();
630 let tm = Arc::new(TokenManager::new_hmac(
631 b"test-secret-key-32-bytes-minimum!",
632 "client-issuer",
633 issuer,
634 ));
635 let service =
636 TokenIntrospectionService::new(config, Arc::new(MockStorage::new()), tm.clone(), None);
637 let creds = |assertion: String| IntrospectionClientCredentials {
638 client_id: "rs-client".to_string(),
639 client_secret: None,
640 client_assertion: Some(assertion),
641 auth_method: ClientAuthMethod::PrivateKeyJwt,
642 };
643 let ttl = Some(std::time::Duration::from_secs(60));
644
645 let access = tm.create_jwt_token("rs-client", vec![], ttl).unwrap();
647 assert!(
648 service
649 .validate_client_credentials(&creds(access))
650 .await
651 .is_err()
652 );
653 let refresh = tm.create_refresh_jwt_token("rs-client", ttl).unwrap();
655 assert!(
656 service
657 .validate_client_credentials(&creds(refresh))
658 .await
659 .is_err()
660 );
661 let assertion = tm
663 .create_typed_jwt_token("rs-client", vec![], ttl, "client_assertion")
664 .unwrap();
665 assert!(
666 service
667 .validate_client_credentials(&creds(assertion))
668 .await
669 .is_ok()
670 );
671 }
672
673 #[tokio::test]
674 async fn test_inactive_token_introspection() {
675 let service = create_test_service();
676
677 let client_data = serde_json::json!({
679 "client_id": "test-client",
680 "client_secret": "test-secret"
681 });
682 service
683 .storage
684 .store_kv(
685 "oauth_client:test-client",
686 client_data.to_string().as_bytes(),
687 None,
688 )
689 .await
690 .unwrap();
691
692 let client_credentials = IntrospectionClientCredentials {
694 client_id: "test-client".to_string(),
695 client_secret: Some("test-secret".to_string()),
696 client_assertion: None,
697 auth_method: ClientAuthMethod::ClientSecretBasic,
698 };
699
700 let request = TokenIntrospectionRequest {
701 token: "invalid-token".to_string(),
702 token_type_hint: Some("access_token".to_string()),
703 additional_params: HashMap::new(),
704 };
705
706 let response = service
707 .introspect_token(request, Some(client_credentials))
708 .await
709 .unwrap();
710 assert!(!response.active);
711 }
712
713 #[tokio::test]
714 async fn test_client_credentials_validation() {
715 let service = create_test_service();
716
717 let client_data = serde_json::json!({
719 "client_id": "test-client",
720 "client_secret": "test-secret"
721 });
722 service
723 .storage
724 .store_kv(
725 "oauth_client:test-client",
726 client_data.to_string().as_bytes(),
727 None,
728 )
729 .await
730 .unwrap();
731
732 let valid_credentials = IntrospectionClientCredentials {
733 client_id: "test-client".to_string(),
734 client_secret: Some("test-secret".to_string()),
735 client_assertion: None,
736 auth_method: ClientAuthMethod::ClientSecretBasic,
737 };
738
739 assert!(
741 service
742 .validate_client_credentials(&valid_credentials)
743 .await
744 .is_ok()
745 );
746
747 let invalid_credentials = IntrospectionClientCredentials {
748 client_id: "".to_string(),
749 client_secret: None,
750 client_assertion: None,
751 auth_method: ClientAuthMethod::ClientSecretBasic,
752 };
753
754 assert!(
756 service
757 .validate_client_credentials(&invalid_credentials)
758 .await
759 .is_err()
760 );
761 }
762
763 #[tokio::test]
764 async fn test_rate_limiting() {
765 let service = create_test_service();
766 let client_id = "test-client";
767
768 for _ in 0..10 {
770 assert!(service.check_rate_limit(client_id).await.is_ok());
771 }
772
773 for _ in 0..service.config.rate_limit_per_minute {
775 let _ = service.check_rate_limit(client_id).await;
776 }
777
778 assert!(service.check_rate_limit(client_id).await.is_err());
780 }
781
782 #[tokio::test]
783 async fn test_token_introspection_response_creation() {
784 let token = AuthToken {
785 token_id: "test-token".to_string(),
786 user_id: "test-user".to_string(),
787 access_token: "test-access-token".to_string(),
788 token_type: Some("Bearer".to_string()),
789 subject: None,
790 issuer: None,
791 refresh_token: None,
792 issued_at: Utc::now(),
793 expires_at: Utc::now() + Duration::hours(1),
794 scopes: vec!["read".to_string(), "write".to_string()].into(),
795 auth_method: "test".to_string(),
796 client_id: None,
797 user_profile: None,
798 permissions: vec!["read:data".to_string(), "write:data".to_string()].into(),
799 roles: vec!["user".to_string()].into(),
800 metadata: Default::default(),
801 };
802
803 let response = TokenIntrospectionResponse::from_auth_token(
804 &token,
805 Some("test-client".to_string()),
806 Some("https://auth.example.com".to_string()),
807 );
808
809 assert!(response.active);
810 assert_eq!(response.client_id.unwrap(), "test-client");
811 assert_eq!(response.username.unwrap(), "test-user");
812 assert_eq!(response.scope.unwrap(), "read write");
813 assert_eq!(response.token_type.unwrap(), "Bearer");
814 assert_eq!(response.iss.unwrap(), "https://auth.example.com");
815 }
816
817 #[test]
818 fn test_introspection_handler_request_parsing() {
819 let service = create_test_service();
820 let handler = TokenIntrospectionHandler::new(Arc::new(service));
821
822 let request_body = "token=test-token&token_type_hint=access_token";
823 let request = handler.parse_introspection_request(request_body).unwrap();
824
825 assert_eq!(request.token, "test-token");
826 assert_eq!(request.token_type_hint.unwrap(), "access_token");
827 }
828
829 #[test]
830 fn test_client_credentials_extraction() {
831 let service = create_test_service();
832 let handler = TokenIntrospectionHandler::new(Arc::new(service));
833
834 let auth_header = "Basic dGVzdC1jbGllbnQ6dGVzdC1zZWNyZXQ="; let credentials = handler
837 .extract_client_credentials(Some(auth_header), "")
838 .unwrap()
839 .unwrap();
840
841 assert_eq!(credentials.client_id, "test-client");
842 assert_eq!(credentials.client_secret.unwrap(), "test-secret");
843 assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretBasic);
844
845 let request_body = "token=test&client_id=test-client&client_secret=test-secret";
847 let credentials = handler
848 .extract_client_credentials(None, request_body)
849 .unwrap()
850 .unwrap();
851
852 assert_eq!(credentials.client_id, "test-client");
853 assert_eq!(credentials.client_secret.unwrap(), "test-secret");
854 assert_eq!(credentials.auth_method, ClientAuthMethod::ClientSecretPost);
855 }
856
857 #[test]
858 fn test_metadata_generation() {
859 let service = create_test_service();
860 let metadata = service.get_metadata();
861
862 assert!(metadata.contains_key("introspection_endpoint"));
863 assert!(metadata.contains_key("introspection_endpoint_auth_methods_supported"));
864 assert!(metadata.contains_key("token_introspection_supported"));
865 }
866}