1use crate::errors::{AuthError, Result};
64#[cfg(feature = "saml")]
65use crate::methods::saml::{SamlTrustAnchors, verify_signed_assertion};
66use crate::security::secure_jwt::{SecureJwtClaims, SecureJwtValidator};
67use crate::server::token_exchange::token_exchange_common::{
68 ServiceComplexityLevel, TokenExchangeCapabilities, TokenExchangeService, TokenValidationResult,
69 ValidationUtils,
70};
71use async_trait::async_trait;
72use base64::Engine as _;
73use chrono::{Duration, Utc};
74use jsonwebtoken::{Algorithm, Header, encode};
75use serde::{Deserialize, Serialize};
76use std::collections::HashMap;
77
78#[derive(Clone, Serialize, Deserialize)]
80pub struct TokenExchangeRequest {
81 pub grant_type: String,
83
84 pub subject_token: String,
86
87 pub subject_token_type: String,
89
90 pub actor_token: Option<String>,
92
93 pub actor_token_type: Option<String>,
95
96 pub requested_token_type: Option<String>,
98
99 pub audience: Option<String>,
101
102 pub scope: Option<String>,
104
105 pub resource: Option<String>,
107}
108
109impl std::fmt::Debug for TokenExchangeRequest {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 let mut d = f.debug_struct("TokenExchangeRequest");
112 d.field("grant_type", &self.grant_type);
113 d.field(
114 "subject_token",
115 &crate::utils::redact::redacted(&self.subject_token),
116 );
117 d.field("subject_token_type", &self.subject_token_type);
118 d.field(
119 "actor_token",
120 &crate::utils::redact::redacted(&self.actor_token),
121 );
122 d.field("actor_token_type", &self.actor_token_type);
123 d.field("requested_token_type", &self.requested_token_type);
124 d.field("audience", &self.audience);
125 d.field("scope", &self.scope);
126 d.field("resource", &self.resource);
127 d.finish()
128 }
129}
130
131#[derive(Clone, Serialize, Deserialize)]
133pub struct TokenExchangeResponse {
134 pub access_token: String,
136
137 pub token_type: String,
139
140 pub expires_in: Option<i64>,
142
143 pub refresh_token: Option<String>,
145
146 pub scope: Option<String>,
148
149 pub issued_token_type: Option<String>,
151}
152
153impl std::fmt::Debug for TokenExchangeResponse {
154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 let mut d = f.debug_struct("TokenExchangeResponse");
156 d.field(
157 "access_token",
158 &crate::utils::redact::redacted(&self.access_token),
159 );
160 d.field("token_type", &self.token_type);
161 d.field("expires_in", &self.expires_in);
162 d.field(
163 "refresh_token",
164 &crate::utils::redact::redacted(&self.refresh_token),
165 );
166 d.field("scope", &self.scope);
167 d.field("issued_token_type", &self.issued_token_type);
168 d.finish()
169 }
170}
171
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174pub enum TokenType {
175 #[serde(rename = "urn:ietf:params:oauth:token-type:access_token")]
177 AccessToken,
178
179 #[serde(rename = "urn:ietf:params:oauth:token-type:refresh_token")]
181 RefreshToken,
182
183 #[serde(rename = "urn:ietf:params:oauth:token-type:id_token")]
185 IdToken,
186
187 #[serde(rename = "urn:ietf:params:oauth:token-type:saml2")]
189 Saml2,
190
191 #[serde(rename = "urn:ietf:params:oauth:token-type:saml1")]
193 Saml1,
194
195 #[serde(rename = "urn:ietf:params:oauth:token-type:jwt")]
197 Jwt,
198}
199
200#[derive(Debug, Clone)]
202pub struct TokenExchangeContext {
203 pub subject_claims: SecureJwtClaims,
205
206 pub actor_claims: Option<SecureJwtClaims>,
208
209 pub client_id: String,
211
212 pub audience: Option<String>,
214
215 pub scope: Option<Vec<String>>,
217
218 pub resource: Option<String>,
220}
221
222#[derive(Debug, Clone)]
224pub struct TokenExchangePolicy {
225 pub allowed_subject_token_types: Vec<TokenType>,
227
228 pub allowed_actor_token_types: Vec<TokenType>,
230
231 pub allowed_scenarios: Vec<ExchangeScenario>,
233
234 pub max_token_lifetime: Duration,
236
237 pub require_actor_for_delegation: bool,
239
240 pub allowed_audiences: Vec<String>,
242
243 pub scope_mapping: HashMap<String, Vec<String>>,
245}
246
247impl TokenExchangePolicy {
248 pub fn builder() -> TokenExchangePolicyBuilder {
261 TokenExchangePolicyBuilder {
262 inner: Self::default(),
263 }
264 }
265
266 pub fn jwt_only() -> Self {
271 Self {
272 allowed_subject_token_types: vec![TokenType::Jwt, TokenType::AccessToken],
273 allowed_actor_token_types: vec![TokenType::AccessToken],
274 allowed_scenarios: vec![
275 ExchangeScenario::OnBehalfOf,
276 ExchangeScenario::AudienceRestriction,
277 ],
278 max_token_lifetime: Duration::hours(1),
279 require_actor_for_delegation: true,
280 allowed_audiences: Vec::new(),
281 scope_mapping: HashMap::new(),
282 }
283 }
284}
285
286pub struct TokenExchangePolicyBuilder {
288 inner: TokenExchangePolicy,
289}
290
291impl TokenExchangePolicyBuilder {
292 pub fn subject_token_types(mut self, types: Vec<TokenType>) -> Self {
294 self.inner.allowed_subject_token_types = types;
295 self
296 }
297
298 pub fn actor_token_types(mut self, types: Vec<TokenType>) -> Self {
300 self.inner.allowed_actor_token_types = types;
301 self
302 }
303
304 pub fn scenarios(mut self, scenarios: Vec<ExchangeScenario>) -> Self {
306 self.inner.allowed_scenarios = scenarios;
307 self
308 }
309
310 pub fn max_token_lifetime(mut self, lifetime: Duration) -> Self {
312 self.inner.max_token_lifetime = lifetime;
313 self
314 }
315
316 pub fn require_actor_for_delegation(mut self, required: bool) -> Self {
318 self.inner.require_actor_for_delegation = required;
319 self
320 }
321
322 pub fn audience(mut self, aud: impl Into<String>) -> Self {
324 self.inner.allowed_audiences.push(aud.into());
325 self
326 }
327
328 pub fn audiences(mut self, auds: Vec<String>) -> Self {
330 self.inner.allowed_audiences = auds;
331 self
332 }
333
334 pub fn scope_map(mut self, source: impl Into<String>, targets: Vec<String>) -> Self {
336 self.inner.scope_mapping.insert(source.into(), targets);
337 self
338 }
339
340 pub fn build(self) -> TokenExchangePolicy {
342 self.inner
343 }
344}
345
346#[derive(Debug, Clone, PartialEq, Eq)]
348pub enum ExchangeScenario {
349 ActingAs,
351
352 OnBehalfOf,
354
355 TokenConversion,
357
358 AudienceRestriction,
360
361 ScopeReduction,
363}
364
365pub struct TokenExchangeManager {
367 jwt_validator: SecureJwtValidator,
369
370 policies: tokio::sync::RwLock<HashMap<String, TokenExchangePolicy>>,
372
373 active_exchanges: tokio::sync::RwLock<HashMap<String, TokenExchangeContext>>,
375
376 #[cfg(feature = "saml")]
379 saml_trust: SamlTrustAnchors,
380}
381
382impl TokenExchangeManager {
383 const SUBJECT_TOKEN_TYPES: &'static [&'static str] = &[
385 "urn:ietf:params:oauth:token-type:jwt",
386 "urn:ietf:params:oauth:token-type:access_token",
387 "urn:ietf:params:oauth:token-type:id_token",
388 "urn:ietf:params:oauth:token-type:saml1",
389 "urn:ietf:params:oauth:token-type:saml2",
390 ];
391
392 const REQUESTED_TOKEN_TYPES: &'static [&'static str] = &[
394 "urn:ietf:params:oauth:token-type:jwt",
395 "urn:ietf:params:oauth:token-type:access_token",
396 "urn:ietf:params:oauth:token-type:refresh_token",
397 ];
398
399 pub fn new(jwt_validator: SecureJwtValidator) -> Self {
401 Self {
402 jwt_validator,
403 policies: tokio::sync::RwLock::new(HashMap::new()),
404 active_exchanges: tokio::sync::RwLock::new(HashMap::new()),
405 #[cfg(feature = "saml")]
406 saml_trust: SamlTrustAnchors::new(),
407 }
408 }
409
410 #[cfg(feature = "saml")]
416 pub fn with_trusted_saml_issuer(
417 mut self,
418 issuer: impl Into<String>,
419 certificate: &str,
420 ) -> Result<Self> {
421 self.saml_trust.trust_pem(issuer, certificate)?;
422 Ok(self)
423 }
424
425 pub async fn register_policy(&self, client_id: String, policy: TokenExchangePolicy) {
427 let mut policies = self.policies.write().await;
428 policies.insert(client_id, policy);
429 }
430
431 pub async fn exchange_token(
433 &self,
434 request: TokenExchangeRequest,
435 client_id: &str,
436 ) -> Result<TokenExchangeResponse> {
437 if request.grant_type != "urn:ietf:params:oauth:grant-type:token-exchange" {
439 return Err(AuthError::auth_method(
440 "token_exchange",
441 "Invalid grant type for token exchange",
442 ));
443 }
444
445 let policies = self.policies.read().await;
447 let policy = policies.get(client_id).ok_or_else(|| {
448 AuthError::auth_method("token_exchange", "No token exchange policy for client")
449 })?;
450
451 let subject_claims = self.validate_subject_token(&request, policy).await?;
453
454 let actor_claims = if let Some(ref actor_token) = request.actor_token {
456 Some(
457 self.validate_actor_token(actor_token, &request.actor_token_type, policy)
458 .await?,
459 )
460 } else {
461 None
462 };
463
464 let context = TokenExchangeContext {
466 subject_claims,
467 actor_claims,
468 client_id: client_id.to_string(),
469 audience: request.audience.clone(),
470 scope: request
471 .scope
472 .as_ref()
473 .map(|s| s.split(' ').map(String::from).collect()),
474 resource: request.resource.clone(),
475 };
476
477 let scenario = self.determine_exchange_scenario(&context, policy)?;
479 self.validate_exchange_scenario(&scenario, &context, policy)?;
480
481 let response = self
483 .generate_exchanged_token(&context, &request, policy)
484 .await?;
485
486 let exchange_id = uuid::Uuid::new_v4().to_string();
488 let mut exchanges = self.active_exchanges.write().await;
489 exchanges.insert(exchange_id, context);
490
491 Ok(response)
492 }
493
494 async fn validate_subject_token(
496 &self,
497 request: &TokenExchangeRequest,
498 policy: &TokenExchangePolicy,
499 ) -> Result<SecureJwtClaims> {
500 let token_type = self.parse_token_type(&request.subject_token_type)?;
502
503 if !policy.allowed_subject_token_types.contains(&token_type) {
505 return Err(AuthError::auth_method(
506 "token_exchange",
507 "Subject token type not allowed",
508 ));
509 }
510
511 match token_type {
513 TokenType::AccessToken
514 | TokenType::RefreshToken
515 | TokenType::IdToken
516 | TokenType::Jwt => {
517 self.validate_jwt_token(&request.subject_token).await
520 }
521 TokenType::Saml2 | TokenType::Saml1 => {
522 self.validate_saml_token(&request.subject_token, &token_type)
524 .await
525 }
526 }
527 }
528
529 async fn validate_actor_token(
531 &self,
532 actor_token: &str,
533 actor_token_type: &Option<String>,
534 policy: &TokenExchangePolicy,
535 ) -> Result<SecureJwtClaims> {
536 let token_type_str = actor_token_type
537 .as_ref()
538 .ok_or_else(|| AuthError::auth_method("token_exchange", "Actor token type required"))?;
539
540 let token_type = self.parse_token_type(token_type_str)?;
541
542 if !policy.allowed_actor_token_types.contains(&token_type) {
543 return Err(AuthError::auth_method(
544 "token_exchange",
545 "Actor token type not allowed",
546 ));
547 }
548
549 self.validate_jwt_token(actor_token).await
550 }
551
552 async fn validate_jwt_token(&self, token: &str) -> Result<SecureJwtClaims> {
554 self.jwt_validator.validate(token).map_err(|e| {
557 AuthError::auth_method("token_exchange", format!("JWT validation failed: {}", e))
558 })
559 }
560
561 fn extract_saml_xml(&self, token: &str) -> Result<String> {
562 if token.trim().is_empty() {
563 return Err(AuthError::auth_method(
564 "token_exchange",
565 "Empty SAML token provided",
566 ));
567 }
568
569 let decoded = if token.trim_start().starts_with('<') {
570 token.to_string()
571 } else {
572 String::from_utf8(
573 base64::engine::general_purpose::STANDARD
574 .decode(token)
575 .map_err(|e| {
576 AuthError::auth_method(
577 "token_exchange",
578 format!("Invalid base64-encoded SAML token: {}", e),
579 )
580 })?,
581 )
582 .map_err(|e| {
583 AuthError::auth_method(
584 "token_exchange",
585 format!("Invalid UTF-8 in SAML token: {}", e),
586 )
587 })?
588 };
589
590 let has_saml_markers = decoded.contains("<saml:")
591 || decoded.contains("<saml2:")
592 || decoded.contains("<Assertion")
593 || decoded.contains("<Response")
594 || decoded.contains("urn:oasis:names:tc:SAML");
595
596 if !has_saml_markers {
597 return Err(AuthError::auth_method(
598 "token_exchange",
599 "Invalid SAML token format - missing SAML namespace markers",
600 ));
601 }
602
603 Ok(decoded)
604 }
605
606 #[cfg(feature = "saml")]
607 fn extract_xml_text(&self, xml: &str, local_name: &str) -> Option<String> {
608 let patterns = [
609 format!("<{local_name}>"),
610 format!("<saml:{local_name}>"),
611 format!("<saml2:{local_name}>"),
612 format!("<{local_name} "),
613 format!("<saml:{local_name} "),
614 format!("<saml2:{local_name} "),
615 ];
616
617 for pattern in patterns {
618 if let Some(start) = xml.find(&pattern) {
619 let content_start = xml[start..].find('>').map(|index| start + index + 1)?;
620 let end_patterns = [
621 format!("</{local_name}>"),
622 format!("</saml:{local_name}>"),
623 format!("</saml2:{local_name}>"),
624 ];
625
626 for end_pattern in end_patterns {
627 if let Some(relative_end) = xml[content_start..].find(&end_pattern) {
628 return Some(
629 xml[content_start..content_start + relative_end]
630 .trim()
631 .to_string(),
632 );
633 }
634 }
635 }
636 }
637
638 None
639 }
640
641 #[cfg(feature = "saml")]
642 fn extract_xml_attribute(&self, xml: &str, attribute_name: &str) -> Option<String> {
643 for pattern in [
644 format!("{attribute_name}=\""),
645 format!("{attribute_name}='"),
646 ] {
647 if let Some(start) = xml.find(&pattern) {
648 let value_start = start + pattern.len();
649 if let Some(relative_end) = xml[value_start..].find(['"', '\'']) {
650 return Some(xml[value_start..value_start + relative_end].to_string());
651 }
652 }
653 }
654
655 None
656 }
657
658 #[cfg(feature = "saml")]
659 fn parse_saml_timestamp(&self, timestamp: &str) -> Result<i64> {
660 chrono::DateTime::parse_from_rfc3339(timestamp)
661 .or_else(|_| chrono::DateTime::parse_from_str(timestamp, "%Y-%m-%dT%H:%M:%S%.fZ"))
662 .or_else(|_| chrono::DateTime::parse_from_str(timestamp, "%Y-%m-%dT%H:%M:%SZ"))
663 .map(|dt| dt.timestamp())
664 .map_err(|_| {
665 AuthError::auth_method(
666 "token_exchange",
667 format!("Invalid SAML timestamp: {}", timestamp),
668 )
669 })
670 }
671
672 #[cfg(feature = "saml")]
673 fn extract_saml_timestamp(&self, xml: &str, attribute_name: &str) -> Result<Option<i64>> {
674 match self.extract_xml_attribute(xml, attribute_name) {
675 Some(timestamp) => self.parse_saml_timestamp(×tamp).map(Some),
676 None => Ok(None),
677 }
678 }
679
680 #[cfg(feature = "saml")]
681 fn validate_saml_assertion_xml(
682 &self,
683 xml: &str,
684 token_type: &TokenType,
685 ) -> Result<SecureJwtClaims> {
686 let verified = verify_signed_assertion(xml, &self.saml_trust).map_err(|e| {
689 AuthError::auth_method(
690 "token_exchange",
691 format!("SAML signature validation failed: {}", e),
692 )
693 })?;
694 let xml = verified.assertion_xml.as_str();
695
696 let subject = self.extract_xml_text(xml, "NameID").ok_or_else(|| {
697 AuthError::auth_method("token_exchange", "SAML assertion is missing NameID")
698 })?;
699 let issuer = verified.issuer.clone();
700 let audience = self.extract_xml_text(xml, "Audience");
701 let issue_instant = self.extract_saml_timestamp(xml, "IssueInstant")?;
702 let not_before = self.extract_saml_timestamp(xml, "NotBefore")?;
703 let not_on_or_after = self.extract_saml_timestamp(xml, "NotOnOrAfter")?;
704 let session_id = self.extract_xml_attribute(xml, "SessionIndex");
705
706 let now = chrono::Utc::now().timestamp();
707 if let Some(value) = issue_instant {
708 if value > now + 30 {
709 return Err(AuthError::auth_method(
710 "token_exchange",
711 "SAML assertion issue instant is in the future",
712 ));
713 }
714 if now - value > 300 {
715 return Err(AuthError::auth_method(
716 "token_exchange",
717 "SAML assertion is too old",
718 ));
719 }
720 }
721 if let Some(value) = not_before
722 && now < value
723 {
724 return Err(AuthError::auth_method(
725 "token_exchange",
726 "SAML assertion is not yet valid",
727 ));
728 }
729 if let Some(value) = not_on_or_after
730 && now >= value
731 {
732 return Err(AuthError::auth_method(
733 "token_exchange",
734 "SAML assertion has expired",
735 ));
736 }
737
738 let mut scopes = Vec::new();
739 if xml.contains("emailaddress") {
740 scopes.push("email".to_string());
741 }
742 if xml.contains("identity/claims/name") || xml.contains("givenname") {
743 scopes.push("profile".to_string());
744 }
745 if xml.contains("claims/groups") || xml.contains("role") || xml.contains("Role") {
746 scopes.push("groups".to_string());
747 }
748 if scopes.is_empty() {
749 scopes.push("saml_authenticated".to_string());
750 }
751
752 Ok(SecureJwtClaims {
753 iss: issuer,
754 sub: subject,
755 aud: audience.unwrap_or_else(|| "target_audience".to_string()),
756 exp: not_on_or_after.unwrap_or(now + 3600),
757 nbf: not_before.unwrap_or(now),
758 iat: issue_instant.unwrap_or(now),
759 jti: format!("saml_token_{}", uuid::Uuid::new_v4()),
760 scope: scopes.join(" "),
761 typ: match token_type {
762 TokenType::Saml2 => "urn:ietf:params:oauth:token-type:saml2",
763 TokenType::Saml1 => "urn:ietf:params:oauth:token-type:saml1",
764 _ => "urn:ietf:params:oauth:token-type:saml2",
765 }
766 .to_string(),
767 sid: session_id,
768 client_id: None,
769 auth_ctx_hash: Some(format!("saml_ctx_{}", uuid::Uuid::new_v4())),
770 })
771 }
772
773 #[cfg(not(feature = "saml"))]
774 fn validate_saml_assertion_xml(
775 &self,
776 _xml: &str,
777 _token_type: &TokenType,
778 ) -> Result<SecureJwtClaims> {
779 Err(AuthError::auth_method(
780 "token_exchange",
781 "SAML validation requires the 'saml' feature to be enabled",
782 ))
783 }
784
785 async fn validate_saml_token(
787 &self,
788 token: &str,
789 token_type: &TokenType,
790 ) -> Result<SecureJwtClaims> {
791 let xml = self.extract_saml_xml(token)?;
792 let claims = self.validate_saml_assertion_xml(&xml, token_type)?;
793
794 tracing::info!(
795 "SAML token validation completed - parsed subject: {}, issuer: {}, scopes: {}",
796 claims.sub,
797 claims.iss,
798 claims.scope
799 );
800 Ok(claims)
801 }
802
803 fn parse_token_type(&self, token_type: &str) -> Result<TokenType> {
805 match token_type {
806 "urn:ietf:params:oauth:token-type:access_token" => Ok(TokenType::AccessToken),
807 "urn:ietf:params:oauth:token-type:refresh_token" => Ok(TokenType::RefreshToken),
808 "urn:ietf:params:oauth:token-type:id_token" => Ok(TokenType::IdToken),
809 "urn:ietf:params:oauth:token-type:saml2" => Ok(TokenType::Saml2),
810 "urn:ietf:params:oauth:token-type:saml1" => Ok(TokenType::Saml1),
811 "urn:ietf:params:oauth:token-type:jwt" => Ok(TokenType::Jwt),
812 _ => Err(AuthError::auth_method(
813 "token_exchange",
814 "Unknown token type",
815 )),
816 }
817 }
818
819 fn determine_exchange_scenario(
821 &self,
822 context: &TokenExchangeContext,
823 _policy: &TokenExchangePolicy,
824 ) -> Result<ExchangeScenario> {
825 if context.actor_claims.is_some() {
826 return Ok(ExchangeScenario::OnBehalfOf);
827 }
828
829 if let Some(audience) = context.audience.as_ref()
830 && audience != &context.subject_claims.aud
831 {
832 return Ok(ExchangeScenario::AudienceRestriction);
833 }
834
835 if let Some(requested_scope) = &context.scope {
836 let current_scope: Vec<&str> = context.subject_claims.scope.split(' ').collect();
837 if requested_scope.len() < current_scope.len() {
838 return Ok(ExchangeScenario::ScopeReduction);
839 }
840 }
841
842 Ok(ExchangeScenario::ActingAs)
843 }
844
845 fn validate_exchange_scenario(
846 &self,
847 scenario: &ExchangeScenario,
848 context: &TokenExchangeContext,
849 policy: &TokenExchangePolicy,
850 ) -> Result<()> {
851 if !policy.allowed_scenarios.is_empty() && !policy.allowed_scenarios.contains(scenario) {
852 return Err(AuthError::auth_method(
853 "token_exchange",
854 "Exchange scenario is not permitted by policy",
855 ));
856 }
857
858 match scenario {
859 ExchangeScenario::OnBehalfOf => {
860 if policy.require_actor_for_delegation && context.actor_claims.is_none() {
861 return Err(AuthError::auth_method(
862 "token_exchange",
863 "Actor token required for delegation",
864 ));
865 }
866 }
867 ExchangeScenario::AudienceRestriction => {
868 if let Some(audience) = context.audience.as_ref()
869 && !policy.allowed_audiences.is_empty()
870 && !policy.allowed_audiences.contains(audience)
871 {
872 return Err(AuthError::auth_method(
873 "token_exchange",
874 "Audience not allowed",
875 ));
876 }
877 }
878 _ => {}
879 }
880
881 Ok(())
882 }
883
884 async fn generate_exchanged_token(
886 &self,
887 context: &TokenExchangeContext,
888 request: &TokenExchangeRequest,
889 policy: &TokenExchangePolicy,
890 ) -> Result<TokenExchangeResponse> {
891 let now = Utc::now();
892 let expires_in = policy.max_token_lifetime.num_seconds();
893 let exp = now + policy.max_token_lifetime;
894
895 let mut new_claims = context.subject_claims.clone();
897
898 new_claims.exp = exp.timestamp();
900 new_claims.iat = now.timestamp();
901 new_claims.jti = uuid::Uuid::new_v4().to_string();
902
903 if let Some(ref audience) = request.audience {
905 new_claims.aud = audience.clone();
906 }
907
908 if let Some(ref requested_scope) = request.scope {
910 if let Some(mapped_scopes) = policy.scope_mapping.get(requested_scope) {
911 new_claims.scope = mapped_scopes.join(" ");
912 } else {
913 new_claims.scope = requested_scope.clone();
914 }
915 }
916
917 if let Some(ref actor_claims) = context.actor_claims {
919 new_claims.client_id = Some(actor_claims.sub.clone());
920 }
921
922 let access_token = encode(
924 &Header::new(Algorithm::HS256),
925 &new_claims,
926 &self.jwt_validator.get_encoding_key(),
927 )
928 .map_err(|e| AuthError::internal(format!("Failed to sign exchanged token: {}", e)))?;
929
930 let issued_token_type = request
932 .requested_token_type
933 .clone()
934 .unwrap_or_else(|| "urn:ietf:params:oauth:token-type:access_token".to_string());
935
936 Ok(TokenExchangeResponse {
937 access_token,
938 token_type: "Bearer".to_string(),
939 expires_in: Some(expires_in),
940 refresh_token: None, scope: Some(new_claims.scope),
942 issued_token_type: Some(issued_token_type),
943 })
944 }
945}
946
947impl Default for TokenExchangePolicy {
948 fn default() -> Self {
949 Self {
950 allowed_subject_token_types: vec![
951 TokenType::AccessToken,
952 TokenType::RefreshToken,
953 TokenType::IdToken,
954 ],
955 allowed_actor_token_types: vec![TokenType::AccessToken, TokenType::IdToken],
956 allowed_scenarios: vec![
957 ExchangeScenario::ActingAs,
958 ExchangeScenario::OnBehalfOf,
959 ExchangeScenario::AudienceRestriction,
960 ExchangeScenario::ScopeReduction,
961 ],
962 max_token_lifetime: Duration::hours(1),
963 require_actor_for_delegation: true,
964 allowed_audiences: Vec::new(), scope_mapping: HashMap::new(),
966 }
967 }
968}
969
970#[async_trait]
972impl TokenExchangeService for TokenExchangeManager {
973 type Request = (TokenExchangeRequest, String); type Response = TokenExchangeResponse;
975 type Config = SecureJwtValidator; async fn exchange_token(&self, request: Self::Request) -> Result<Self::Response> {
979 let (token_request, client_id) = request;
980 self.exchange_token(token_request, &client_id).await
981 }
982
983 async fn validate_token(&self, token: &str, token_type: &str) -> Result<TokenValidationResult> {
985 let supported_types = self.supported_subject_token_types();
987 ValidationUtils::validate_token_type(token_type, &supported_types)?;
988
989 match self.parse_token_type(token_type)? {
990 TokenType::Jwt | TokenType::AccessToken | TokenType::IdToken => {
991 match self.jwt_validator.validate(token) {
994 Ok(claims) => {
995 use chrono::{TimeZone, Utc};
997 let expires_at = Utc.timestamp_opt(claims.exp, 0).single();
998
999 let audience = if claims.aud.is_empty() {
1001 Vec::new()
1002 } else {
1003 vec![claims.aud.clone()]
1004 };
1005
1006 let scopes = if claims.scope.is_empty() {
1008 Vec::new()
1009 } else {
1010 claims
1011 .scope
1012 .split_whitespace()
1013 .map(|s| s.to_string())
1014 .collect()
1015 };
1016
1017 let mut metadata = HashMap::new();
1019 metadata.insert(
1020 "sub".to_string(),
1021 serde_json::Value::String(claims.sub.clone()),
1022 );
1023 metadata.insert(
1024 "iss".to_string(),
1025 serde_json::Value::String(claims.iss.clone()),
1026 );
1027 metadata.insert(
1028 "aud".to_string(),
1029 serde_json::Value::String(claims.aud.clone()),
1030 );
1031 metadata.insert(
1032 "scope".to_string(),
1033 serde_json::Value::String(claims.scope.clone()),
1034 );
1035 metadata.insert(
1036 "typ".to_string(),
1037 serde_json::Value::String(claims.typ.clone()),
1038 );
1039 if let Some(ref sid) = claims.sid {
1040 metadata
1041 .insert("sid".to_string(), serde_json::Value::String(sid.clone()));
1042 }
1043 if let Some(ref client_id) = claims.client_id {
1044 metadata.insert(
1045 "client_id".to_string(),
1046 serde_json::Value::String(client_id.clone()),
1047 );
1048 }
1049
1050 Ok(TokenValidationResult {
1051 is_valid: true,
1052 subject: Some(claims.sub),
1053 issuer: Some(claims.iss),
1054 audience,
1055 scopes,
1056 expires_at,
1057 metadata,
1058 validation_messages: Vec::new(),
1059 })
1060 }
1061 Err(e) => Ok(TokenValidationResult {
1062 is_valid: false,
1063 subject: None,
1064 issuer: None,
1065 audience: Vec::new(),
1066 scopes: Vec::new(),
1067 expires_at: None,
1068 metadata: HashMap::new(),
1069 validation_messages: vec![format!("JWT validation failed: {}", e)],
1070 }),
1071 }
1072 }
1073 TokenType::Saml2 | TokenType::Saml1 => {
1074 match self
1075 .validate_saml_token(token, &self.parse_token_type(token_type)?)
1076 .await
1077 {
1078 Ok(claims) => {
1079 use chrono::{TimeZone, Utc};
1080 let expires_at = Utc.timestamp_opt(claims.exp, 0).single();
1081 let audience = if claims.aud.is_empty() {
1082 Vec::new()
1083 } else {
1084 vec![claims.aud.clone()]
1085 };
1086 let scopes = if claims.scope.is_empty() {
1087 Vec::new()
1088 } else {
1089 claims
1090 .scope
1091 .split_whitespace()
1092 .map(|scope| scope.to_string())
1093 .collect()
1094 };
1095
1096 let mut metadata = HashMap::new();
1097 metadata.insert(
1098 "sub".to_string(),
1099 serde_json::Value::String(claims.sub.clone()),
1100 );
1101 metadata.insert(
1102 "iss".to_string(),
1103 serde_json::Value::String(claims.iss.clone()),
1104 );
1105 metadata.insert(
1106 "aud".to_string(),
1107 serde_json::Value::String(claims.aud.clone()),
1108 );
1109 metadata.insert(
1110 "scope".to_string(),
1111 serde_json::Value::String(claims.scope.clone()),
1112 );
1113 metadata.insert(
1114 "typ".to_string(),
1115 serde_json::Value::String(claims.typ.clone()),
1116 );
1117 if let Some(ref sid) = claims.sid {
1118 metadata
1119 .insert("sid".to_string(), serde_json::Value::String(sid.clone()));
1120 }
1121
1122 Ok(TokenValidationResult {
1123 is_valid: true,
1124 subject: Some(claims.sub),
1125 issuer: Some(claims.iss),
1126 audience,
1127 scopes,
1128 expires_at,
1129 metadata,
1130 validation_messages: Vec::new(),
1131 })
1132 }
1133 Err(error) => Ok(TokenValidationResult {
1134 is_valid: false,
1135 subject: None,
1136 issuer: None,
1137 audience: Vec::new(),
1138 scopes: Vec::new(),
1139 expires_at: None,
1140 metadata: HashMap::new(),
1141 validation_messages: vec![error.to_string()],
1142 }),
1143 }
1144 }
1145 _ => Err(AuthError::InvalidRequest(format!(
1146 "Token validation not supported for type: {}",
1147 token_type
1148 ))),
1149 }
1150 }
1151
1152 fn supported_subject_token_types(&self) -> Vec<String> {
1154 Self::SUBJECT_TOKEN_TYPES
1155 .iter()
1156 .map(|s| s.to_string())
1157 .collect()
1158 }
1159
1160 fn supported_requested_token_types(&self) -> Vec<String> {
1162 Self::REQUESTED_TOKEN_TYPES
1163 .iter()
1164 .map(|s| s.to_string())
1165 .collect()
1166 }
1167
1168 fn capabilities(&self) -> TokenExchangeCapabilities {
1170 TokenExchangeCapabilities {
1171 basic_exchange: true,
1172 multi_party_chains: false,
1173 context_preservation: false,
1174 audit_trail: false,
1175 session_integration: false,
1176 jwt_operations: false,
1177 policy_control: true,
1178 cross_domain_exchange: false,
1179 max_delegation_depth: 3,
1180 complexity_level: ServiceComplexityLevel::Basic,
1181 }
1182 }
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187 use super::*;
1188 use crate::security::secure_jwt::SecureJwtConfig;
1189
1190 fn create_test_manager() -> TokenExchangeManager {
1191 let jwt_config = SecureJwtConfig::default();
1192 let jwt_validator = SecureJwtValidator::new(jwt_config).expect("test JWT config");
1193 TokenExchangeManager::new(jwt_validator)
1194 }
1195
1196 fn create_test_request() -> TokenExchangeRequest {
1197 TokenExchangeRequest {
1198 grant_type: "urn:ietf:params:oauth:grant-type:token-exchange".to_string(),
1199 subject_token: "dummy.jwt.token".to_string(),
1200 subject_token_type: "urn:ietf:params:oauth:token-type:access_token".to_string(),
1201 actor_token: None,
1202 actor_token_type: None,
1203 requested_token_type: Some("urn:ietf:params:oauth:token-type:access_token".to_string()),
1204 audience: Some("api.example.com".to_string()),
1205 scope: Some("read write".to_string()),
1206 resource: None,
1207 }
1208 }
1209
1210 #[tokio::test]
1211 async fn test_token_exchange_manager_creation() {
1212 let manager = create_test_manager();
1213
1214 let policy = TokenExchangePolicy::default();
1216 manager
1217 .register_policy("test_client".to_string(), policy)
1218 .await;
1219 }
1220
1221 #[test]
1222 fn test_token_type_parsing() {
1223 let manager = create_test_manager();
1224
1225 assert_eq!(
1226 manager
1227 .parse_token_type("urn:ietf:params:oauth:token-type:access_token")
1228 .unwrap(),
1229 TokenType::AccessToken
1230 );
1231
1232 assert_eq!(
1233 manager
1234 .parse_token_type("urn:ietf:params:oauth:token-type:id_token")
1235 .unwrap(),
1236 TokenType::IdToken
1237 );
1238
1239 assert!(manager.parse_token_type("invalid_token_type").is_err());
1240 }
1241
1242 #[test]
1243 fn test_exchange_scenario_determination() {
1244 let manager = create_test_manager();
1245 let policy = TokenExchangePolicy::default();
1246
1247 let context = TokenExchangeContext {
1249 subject_claims: SecureJwtClaims {
1250 sub: "user123".to_string(),
1251 iss: "auth.example.com".to_string(),
1252 aud: "api.example.com".to_string(),
1253 exp: chrono::Utc::now().timestamp() + 3600,
1254 nbf: chrono::Utc::now().timestamp(),
1255 iat: chrono::Utc::now().timestamp(),
1256 jti: "token123".to_string(),
1257 scope: "read write".to_string(),
1258 typ: "access".to_string(),
1259 sid: None,
1260 client_id: None,
1261 auth_ctx_hash: None,
1262 },
1263 actor_claims: None,
1264 client_id: "test_client".to_string(),
1265 audience: Some("different.api.com".to_string()),
1266 scope: None,
1267 resource: None,
1268 };
1269
1270 let scenario = manager
1271 .determine_exchange_scenario(&context, &policy)
1272 .unwrap();
1273 assert_eq!(scenario, ExchangeScenario::AudienceRestriction);
1274 }
1275
1276 #[tokio::test]
1277 async fn test_invalid_grant_type() {
1278 let manager = create_test_manager();
1279 let policy = TokenExchangePolicy::default();
1280 manager
1281 .register_policy("test_client".to_string(), policy)
1282 .await;
1283
1284 let mut request = create_test_request();
1285 request.grant_type = "invalid_grant_type".to_string();
1286
1287 let result = manager.exchange_token(request, "test_client").await;
1288 assert!(result.is_err());
1289 }
1290
1291 #[test]
1292 fn test_token_exchange_policy_builder() {
1293 let policy = TokenExchangePolicy::builder()
1294 .max_token_lifetime(Duration::minutes(30))
1295 .require_actor_for_delegation(false)
1296 .audience("api.example.com")
1297 .audience("internal.example.com")
1298 .scope_map("admin", vec!["read".into(), "write".into()])
1299 .build();
1300
1301 assert_eq!(policy.max_token_lifetime, Duration::minutes(30));
1302 assert!(!policy.require_actor_for_delegation);
1303 assert_eq!(policy.allowed_audiences.len(), 2);
1304 assert_eq!(policy.scope_mapping.get("admin").unwrap().len(), 2);
1305 assert!(!policy.allowed_subject_token_types.is_empty());
1307 }
1308
1309 #[test]
1310 fn test_token_exchange_policy_jwt_only_preset() {
1311 let policy = TokenExchangePolicy::jwt_only();
1312 assert_eq!(policy.allowed_subject_token_types.len(), 2);
1313 assert!(policy.allowed_subject_token_types.contains(&TokenType::Jwt));
1314 assert!(
1315 policy
1316 .allowed_subject_token_types
1317 .contains(&TokenType::AccessToken)
1318 );
1319 assert!(policy.require_actor_for_delegation);
1320 }
1321
1322 #[tokio::test]
1323 async fn test_token_exchange_policy_builder_register() {
1324 let manager = create_test_manager();
1325 let policy = TokenExchangePolicy::builder()
1326 .scenarios(vec![
1327 ExchangeScenario::OnBehalfOf,
1328 ExchangeScenario::AudienceRestriction,
1329 ])
1330 .max_token_lifetime(Duration::minutes(15))
1331 .build();
1332 manager
1333 .register_policy("test_client".to_string(), policy)
1334 .await;
1335 }
1336}