1use crate::errors::{AuthError, Result};
59use crate::security::secure_jwt::{SecureJwtClaims, SecureJwtValidator};
60use crate::server::token_exchange::token_exchange_common::{
61 ServiceComplexityLevel, TokenExchangeCapabilities, TokenExchangeService, TokenValidationResult,
62 ValidationUtils,
63};
64use async_trait::async_trait;
65use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
66use chrono::{Duration, Utc};
67use serde::{Deserialize, Serialize};
68use std::collections::HashMap;
69
70#[derive(Clone, Serialize, Deserialize)]
72pub struct TokenExchangeRequest {
73 pub grant_type: String,
75
76 pub subject_token: String,
78
79 pub subject_token_type: String,
81
82 pub actor_token: Option<String>,
84
85 pub actor_token_type: Option<String>,
87
88 pub requested_token_type: Option<String>,
90
91 pub audience: Option<String>,
93
94 pub scope: Option<String>,
96
97 pub resource: Option<String>,
99}
100
101impl std::fmt::Debug for TokenExchangeRequest {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 let mut d = f.debug_struct("TokenExchangeRequest");
104 d.field("grant_type", &self.grant_type);
105 d.field(
106 "subject_token",
107 &crate::utils::redact::redacted(&self.subject_token),
108 );
109 d.field("subject_token_type", &self.subject_token_type);
110 d.field(
111 "actor_token",
112 &crate::utils::redact::redacted(&self.actor_token),
113 );
114 d.field("actor_token_type", &self.actor_token_type);
115 d.field("requested_token_type", &self.requested_token_type);
116 d.field("audience", &self.audience);
117 d.field("scope", &self.scope);
118 d.field("resource", &self.resource);
119 d.finish()
120 }
121}
122
123#[derive(Clone, Serialize, Deserialize)]
125pub struct TokenExchangeResponse {
126 pub access_token: String,
128
129 pub token_type: String,
131
132 pub expires_in: Option<i64>,
134
135 pub refresh_token: Option<String>,
137
138 pub scope: Option<String>,
140
141 pub issued_token_type: Option<String>,
143}
144
145impl std::fmt::Debug for TokenExchangeResponse {
146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147 let mut d = f.debug_struct("TokenExchangeResponse");
148 d.field(
149 "access_token",
150 &crate::utils::redact::redacted(&self.access_token),
151 );
152 d.field("token_type", &self.token_type);
153 d.field("expires_in", &self.expires_in);
154 d.field(
155 "refresh_token",
156 &crate::utils::redact::redacted(&self.refresh_token),
157 );
158 d.field("scope", &self.scope);
159 d.field("issued_token_type", &self.issued_token_type);
160 d.finish()
161 }
162}
163
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166pub enum TokenType {
167 #[serde(rename = "urn:ietf:params:oauth:token-type:access_token")]
169 AccessToken,
170
171 #[serde(rename = "urn:ietf:params:oauth:token-type:refresh_token")]
173 RefreshToken,
174
175 #[serde(rename = "urn:ietf:params:oauth:token-type:id_token")]
177 IdToken,
178
179 #[serde(rename = "urn:ietf:params:oauth:token-type:saml2")]
181 Saml2,
182
183 #[serde(rename = "urn:ietf:params:oauth:token-type:saml1")]
185 Saml1,
186
187 #[serde(rename = "urn:ietf:params:oauth:token-type:jwt")]
189 Jwt,
190}
191
192#[derive(Debug, Clone)]
194pub struct TokenExchangeContext {
195 pub subject_claims: SecureJwtClaims,
197
198 pub actor_claims: Option<SecureJwtClaims>,
200
201 pub client_id: String,
203
204 pub audience: Option<String>,
206
207 pub scope: Option<Vec<String>>,
209
210 pub resource: Option<String>,
212}
213
214#[derive(Debug, Clone)]
216pub struct TokenExchangePolicy {
217 pub allowed_subject_token_types: Vec<TokenType>,
219
220 pub allowed_actor_token_types: Vec<TokenType>,
222
223 pub allowed_scenarios: Vec<ExchangeScenario>,
225
226 pub max_token_lifetime: Duration,
228
229 pub require_actor_for_delegation: bool,
231
232 pub allowed_audiences: Vec<String>,
234
235 pub scope_mapping: HashMap<String, Vec<String>>,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq)]
241pub enum ExchangeScenario {
242 ActingAs,
244
245 OnBehalfOf,
247
248 TokenConversion,
250
251 AudienceRestriction,
253
254 ScopeReduction,
256}
257
258#[derive(Clone)]
260struct SamlClaims {
261 pub subject: String,
263 pub issuer: String,
265 pub audience: Option<String>,
267 pub expiry: Option<i64>,
269 pub not_before: Option<i64>,
271 pub session_id: Option<String>,
273 pub scopes: Vec<String>,
275}
276
277impl std::fmt::Debug for SamlClaims {
278 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279 let mut d = f.debug_struct("SamlClaims");
280 d.field("subject", &self.subject);
281 d.field("issuer", &self.issuer);
282 d.field("audience", &self.audience);
283 d.field("expiry", &self.expiry);
284 d.field("not_before", &self.not_before);
285 d.field(
286 "session_id",
287 &crate::utils::redact::redacted(&self.session_id),
288 );
289 d.field("scopes", &self.scopes);
290 d.finish()
291 }
292}
293
294pub struct TokenExchangeManager {
296 jwt_validator: SecureJwtValidator,
298
299 policies: tokio::sync::RwLock<HashMap<String, TokenExchangePolicy>>,
301
302 active_exchanges: tokio::sync::RwLock<HashMap<String, TokenExchangeContext>>,
304}
305
306impl TokenExchangeManager {
307 const SUBJECT_TOKEN_TYPES: &'static [&'static str] = &[
309 "urn:ietf:params:oauth:token-type:jwt",
310 "urn:ietf:params:oauth:token-type:access_token",
311 "urn:ietf:params:oauth:token-type:id_token",
312 "urn:ietf:params:oauth:token-type:saml2",
313 ];
314
315 const REQUESTED_TOKEN_TYPES: &'static [&'static str] = &[
317 "urn:ietf:params:oauth:token-type:jwt",
318 "urn:ietf:params:oauth:token-type:access_token",
319 "urn:ietf:params:oauth:token-type:refresh_token",
320 ];
321
322 pub fn new(jwt_validator: SecureJwtValidator) -> Self {
324 Self {
325 jwt_validator,
326 policies: tokio::sync::RwLock::new(HashMap::new()),
327 active_exchanges: tokio::sync::RwLock::new(HashMap::new()),
328 }
329 }
330
331 pub async fn register_policy(&self, client_id: String, policy: TokenExchangePolicy) {
333 let mut policies = self.policies.write().await;
334 policies.insert(client_id, policy);
335 }
336
337 pub async fn exchange_token(
339 &self,
340 request: TokenExchangeRequest,
341 client_id: &str,
342 ) -> Result<TokenExchangeResponse> {
343 if request.grant_type != "urn:ietf:params:oauth:grant-type:token-exchange" {
345 return Err(AuthError::auth_method(
346 "token_exchange",
347 "Invalid grant type for token exchange",
348 ));
349 }
350
351 let policies = self.policies.read().await;
353 let policy = policies.get(client_id).ok_or_else(|| {
354 AuthError::auth_method("token_exchange", "No token exchange policy for client")
355 })?;
356
357 let subject_claims = self.validate_subject_token(&request, policy).await?;
359
360 let actor_claims = if let Some(ref actor_token) = request.actor_token {
362 Some(
363 self.validate_actor_token(actor_token, &request.actor_token_type, policy)
364 .await?,
365 )
366 } else {
367 None
368 };
369
370 let context = TokenExchangeContext {
372 subject_claims,
373 actor_claims,
374 client_id: client_id.to_string(),
375 audience: request.audience.clone(),
376 scope: request
377 .scope
378 .as_ref()
379 .map(|s| s.split(' ').map(String::from).collect()),
380 resource: request.resource.clone(),
381 };
382
383 let scenario = self.determine_exchange_scenario(&context, policy)?;
385 self.validate_exchange_scenario(&scenario, &context, policy)?;
386
387 let response = self
389 .generate_exchanged_token(&context, &request, policy)
390 .await?;
391
392 let exchange_id = uuid::Uuid::new_v4().to_string();
394 let mut exchanges = self.active_exchanges.write().await;
395 exchanges.insert(exchange_id, context);
396
397 Ok(response)
398 }
399
400 async fn validate_subject_token(
402 &self,
403 request: &TokenExchangeRequest,
404 policy: &TokenExchangePolicy,
405 ) -> Result<SecureJwtClaims> {
406 let token_type = self.parse_token_type(&request.subject_token_type)?;
408
409 if !policy.allowed_subject_token_types.contains(&token_type) {
411 return Err(AuthError::auth_method(
412 "token_exchange",
413 "Subject token type not allowed",
414 ));
415 }
416
417 match token_type {
419 TokenType::AccessToken
420 | TokenType::RefreshToken
421 | TokenType::IdToken
422 | TokenType::Jwt => {
423 self.validate_jwt_token(&request.subject_token).await
426 }
427 TokenType::Saml2 | TokenType::Saml1 => {
428 self.validate_saml_token(&request.subject_token, &token_type)
430 .await
431 }
432 }
433 }
434
435 async fn validate_actor_token(
437 &self,
438 actor_token: &str,
439 actor_token_type: &Option<String>,
440 policy: &TokenExchangePolicy,
441 ) -> Result<SecureJwtClaims> {
442 let token_type_str = actor_token_type
443 .as_ref()
444 .ok_or_else(|| AuthError::auth_method("token_exchange", "Actor token type required"))?;
445
446 let token_type = self.parse_token_type(token_type_str)?;
447
448 if !policy.allowed_actor_token_types.contains(&token_type) {
449 return Err(AuthError::auth_method(
450 "token_exchange",
451 "Actor token type not allowed",
452 ));
453 }
454
455 self.validate_jwt_token(actor_token).await
456 }
457
458 async fn validate_jwt_token(&self, token: &str) -> Result<SecureJwtClaims> {
460 let decoding_key = self.jwt_validator.get_decoding_key();
463
464 self.jwt_validator
466 .validate_token(token, &decoding_key, true)
467 .map_err(|e| {
468 AuthError::auth_method("token_exchange", format!("JWT validation failed: {}", e))
469 })
470 }
471
472 async fn validate_saml_token(
474 &self,
475 token: &str,
476 token_type: &TokenType,
477 ) -> Result<SecureJwtClaims> {
478 if token.trim().is_empty() {
480 return Err(AuthError::auth_method(
481 "token_exchange",
482 "Empty SAML token provided",
483 ));
484 }
485
486 let has_saml_markers = token.contains("<saml:")
488 || token.contains("<saml2:")
489 || token.contains("urn:oasis:names:tc:SAML");
490
491 if !has_saml_markers {
492 return Err(AuthError::auth_method(
493 "token_exchange",
494 "Invalid SAML token format - missing SAML namespace markers",
495 ));
496 }
497
498 let saml_claims = SamlClaims {
500 subject: token
501 .find("<saml:NameID")
502 .and_then(|start| {
503 let content_start = token[start..].find('>').map(|pos| start + pos + 1)?;
504 let content_end = token[content_start..]
505 .find("</saml:NameID>")
506 .map(|pos| content_start + pos)?;
507 Some(token[content_start..content_end].trim().to_string())
508 })
509 .unwrap_or_else(|| "saml_subject".to_string()),
510 issuer: token
511 .find("<saml:Issuer")
512 .and_then(|start| {
513 let content_start = token[start..].find('>').map(|pos| start + pos + 1)?;
514 let content_end = token[content_start..]
515 .find("</saml:Issuer>")
516 .map(|pos| content_start + pos)?;
517 Some(token[content_start..content_end].trim().to_string())
518 })
519 .unwrap_or_else(|| "saml_identity_provider".to_string()),
520 audience: token.find("<saml:Audience").and_then(|start| {
521 let content_start = token[start..].find('>').map(|pos| start + pos + 1)?;
522 let content_end = token[content_start..]
523 .find("</saml:Audience>")
524 .map(|pos| content_start + pos)?;
525 Some(token[content_start..content_end].trim().to_string())
526 }),
527 expiry: Some(chrono::Utc::now().timestamp() + 3600), not_before: Some(chrono::Utc::now().timestamp()),
529 session_id: Some(format!("saml_session_{}", uuid::Uuid::new_v4())),
530 scopes: {
531 let mut scopes = Vec::new();
532 if token.contains("emailaddress") {
533 scopes.push("email".to_string());
534 }
535 if token.contains("identity/claims/name") {
536 scopes.push("profile".to_string());
537 }
538 if token.contains("claims/groups") || token.contains("role") {
539 scopes.push("groups".to_string());
540 }
541 if scopes.is_empty() {
542 scopes.push("saml_authenticated".to_string());
543 }
544 scopes
545 },
546 };
547
548 let now = chrono::Utc::now().timestamp();
549 let claims = SecureJwtClaims {
550 iss: saml_claims.issuer,
551 sub: saml_claims.subject,
552 aud: saml_claims
553 .audience
554 .unwrap_or_else(|| "target_audience".to_string()),
555 exp: saml_claims.expiry.unwrap_or(now + 3600), nbf: saml_claims.not_before.unwrap_or(now),
557 iat: now,
558 jti: format!("saml_token_{}", uuid::Uuid::new_v4()),
559 scope: saml_claims.scopes.join(" "),
560 typ: match token_type {
561 TokenType::Saml2 => "urn:ietf:params:oauth:token-type:saml2",
562 TokenType::Saml1 => "urn:ietf:params:oauth:token-type:saml1",
563 _ => "urn:ietf:params:oauth:token-type:saml2",
564 }
565 .to_string(),
566 sid: saml_claims.session_id,
567 client_id: None,
568 auth_ctx_hash: Some(format!("saml_ctx_{}", uuid::Uuid::new_v4())),
569 };
570
571 tracing::info!(
572 "SAML token validation completed - parsed subject: {}, issuer: {}, scopes: {}",
573 claims.sub,
574 claims.iss,
575 claims.scope
576 );
577 Ok(claims)
578 }
579
580 fn parse_token_type(&self, token_type: &str) -> Result<TokenType> {
582 match token_type {
583 "urn:ietf:params:oauth:token-type:access_token" => Ok(TokenType::AccessToken),
584 "urn:ietf:params:oauth:token-type:refresh_token" => Ok(TokenType::RefreshToken),
585 "urn:ietf:params:oauth:token-type:id_token" => Ok(TokenType::IdToken),
586 "urn:ietf:params:oauth:token-type:saml2" => Ok(TokenType::Saml2),
587 "urn:ietf:params:oauth:token-type:saml1" => Ok(TokenType::Saml1),
588 "urn:ietf:params:oauth:token-type:jwt" => Ok(TokenType::Jwt),
589 _ => Err(AuthError::auth_method(
590 "token_exchange",
591 "Unknown token type",
592 )),
593 }
594 }
595
596 fn determine_exchange_scenario(
598 &self,
599 context: &TokenExchangeContext,
600 _policy: &TokenExchangePolicy,
601 ) -> Result<ExchangeScenario> {
602 if context.actor_claims.is_some() {
604 return Ok(ExchangeScenario::OnBehalfOf);
605 }
606
607 if context.audience.is_some()
609 && context.audience.as_ref() != Some(&context.subject_claims.aud)
610 {
611 return Ok(ExchangeScenario::AudienceRestriction);
612 }
613
614 if let Some(requested_scope) = &context.scope {
616 let current_scope: Vec<&str> = context.subject_claims.scope.split(' ').collect();
617 if requested_scope.len() < current_scope.len() {
618 return Ok(ExchangeScenario::ScopeReduction);
619 }
620 }
621
622 Ok(ExchangeScenario::ActingAs)
624 }
625
626 fn validate_exchange_scenario(
628 &self,
629 scenario: &ExchangeScenario,
630 context: &TokenExchangeContext,
631 policy: &TokenExchangePolicy,
632 ) -> Result<()> {
633 if !policy.allowed_scenarios.contains(scenario) {
634 return Err(AuthError::auth_method(
635 "token_exchange",
636 "Exchange scenario not allowed",
637 ));
638 }
639
640 match scenario {
641 ExchangeScenario::OnBehalfOf => {
642 if policy.require_actor_for_delegation && context.actor_claims.is_none() {
643 return Err(AuthError::auth_method(
644 "token_exchange",
645 "Actor token required for delegation",
646 ));
647 }
648 }
649 ExchangeScenario::AudienceRestriction => {
650 if let Some(ref audience) = context.audience
651 && !policy.allowed_audiences.is_empty()
652 && !policy.allowed_audiences.contains(audience)
653 {
654 return Err(AuthError::auth_method(
655 "token_exchange",
656 "Audience not allowed",
657 ));
658 }
659 }
660 _ => {
661 }
663 }
664
665 Ok(())
666 }
667
668 async fn generate_exchanged_token(
670 &self,
671 context: &TokenExchangeContext,
672 request: &TokenExchangeRequest,
673 policy: &TokenExchangePolicy,
674 ) -> Result<TokenExchangeResponse> {
675 let now = Utc::now();
676 let expires_in = policy.max_token_lifetime.num_seconds();
677 let exp = now + policy.max_token_lifetime;
678
679 let mut new_claims = context.subject_claims.clone();
681
682 new_claims.exp = exp.timestamp();
684 new_claims.iat = now.timestamp();
685 new_claims.jti = uuid::Uuid::new_v4().to_string();
686
687 if let Some(ref audience) = request.audience {
689 new_claims.aud = audience.clone();
690 }
691
692 if let Some(ref requested_scope) = request.scope {
694 if let Some(mapped_scopes) = policy.scope_mapping.get(requested_scope) {
695 new_claims.scope = mapped_scopes.join(" ");
696 } else {
697 new_claims.scope = requested_scope.clone();
698 }
699 }
700
701 if let Some(ref actor_claims) = context.actor_claims {
703 new_claims.client_id = Some(actor_claims.sub.clone());
704 }
705
706 let access_token = format!(
708 "exchanged_token_{}_{}",
709 new_claims.jti,
710 URL_SAFE_NO_PAD.encode(&new_claims.sub)
711 );
712
713 let issued_token_type = request
715 .requested_token_type
716 .clone()
717 .unwrap_or_else(|| "urn:ietf:params:oauth:token-type:access_token".to_string());
718
719 Ok(TokenExchangeResponse {
720 access_token,
721 token_type: "Bearer".to_string(),
722 expires_in: Some(expires_in),
723 refresh_token: None, scope: Some(new_claims.scope),
725 issued_token_type: Some(issued_token_type),
726 })
727 }
728
729 fn get_jwt_decoding_key(&self, token: &str) -> Result<jsonwebtoken::DecodingKey> {
731 use jsonwebtoken::DecodingKey;
732
733 let token_parts: Vec<&str> = token.split('.').collect();
735 if token_parts.len() < 2 {
736 return Err(AuthError::InvalidToken("Invalid JWT format".to_string()));
737 }
738
739 let header_b64 = token_parts[0];
740 let header_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
741 .decode(header_b64)
742 .map_err(|_| AuthError::InvalidToken("Invalid JWT header encoding".to_string()))?;
743
744 let header: serde_json::Value = serde_json::from_slice(&header_bytes)
745 .map_err(|_| AuthError::InvalidToken("Invalid JWT header JSON".to_string()))?;
746
747 let algorithm = header
753 .get("alg")
754 .and_then(|a| a.as_str())
755 .unwrap_or("HS256");
756
757 match algorithm {
758 "HS256" => {
759 let secret = std::env::var("JWT_HMAC_SECRET")
761 .unwrap_or_else(|_| "default_hmac_secret_for_development".to_string());
762 Ok(DecodingKey::from_secret(secret.as_bytes()))
763 }
764 "RS256" => {
765 let public_key_pem = std::env::var("JWT_RSA_PUBLIC_KEY")
767 .unwrap_or_else(|_| include_str!("../../../public.pem").to_string());
768 DecodingKey::from_rsa_pem(public_key_pem.as_bytes())
769 .map_err(|e| AuthError::InvalidToken(format!("Invalid RSA key: {}", e)))
770 }
771 _ => {
772 Ok(DecodingKey::from_secret("fallback_secret".as_bytes()))
774 }
775 }
776 }
777}
778
779impl Default for TokenExchangePolicy {
780 fn default() -> Self {
781 Self {
782 allowed_subject_token_types: vec![
783 TokenType::AccessToken,
784 TokenType::RefreshToken,
785 TokenType::IdToken,
786 ],
787 allowed_actor_token_types: vec![TokenType::AccessToken, TokenType::IdToken],
788 allowed_scenarios: vec![
789 ExchangeScenario::ActingAs,
790 ExchangeScenario::OnBehalfOf,
791 ExchangeScenario::AudienceRestriction,
792 ExchangeScenario::ScopeReduction,
793 ],
794 max_token_lifetime: Duration::hours(1),
795 require_actor_for_delegation: true,
796 allowed_audiences: Vec::new(), scope_mapping: HashMap::new(),
798 }
799 }
800}
801
802#[async_trait]
804impl TokenExchangeService for TokenExchangeManager {
805 type Request = (TokenExchangeRequest, String); type Response = TokenExchangeResponse;
807 type Config = SecureJwtValidator; async fn exchange_token(&self, request: Self::Request) -> Result<Self::Response> {
811 let (token_request, client_id) = request;
812 self.exchange_token(token_request, &client_id).await
813 }
814
815 async fn validate_token(&self, token: &str, token_type: &str) -> Result<TokenValidationResult> {
817 let supported_types = self.supported_subject_token_types();
819 ValidationUtils::validate_token_type(token_type, &supported_types)?;
820
821 match self.parse_token_type(token_type)? {
822 TokenType::Jwt | TokenType::AccessToken | TokenType::IdToken => {
823 let decoding_key = self.get_jwt_decoding_key(token)?;
825
826 match self
827 .jwt_validator
828 .validate_token(token, &decoding_key, true)
829 {
830 Ok(claims) => {
831 use chrono::{TimeZone, Utc};
833 let expires_at = Utc.timestamp_opt(claims.exp, 0).single();
834
835 let audience = if claims.aud.is_empty() {
837 Vec::new()
838 } else {
839 vec![claims.aud.clone()]
840 };
841
842 let scopes = if claims.scope.is_empty() {
844 Vec::new()
845 } else {
846 claims
847 .scope
848 .split_whitespace()
849 .map(|s| s.to_string())
850 .collect()
851 };
852
853 let mut metadata = HashMap::new();
855 metadata.insert(
856 "sub".to_string(),
857 serde_json::Value::String(claims.sub.clone()),
858 );
859 metadata.insert(
860 "iss".to_string(),
861 serde_json::Value::String(claims.iss.clone()),
862 );
863 metadata.insert(
864 "aud".to_string(),
865 serde_json::Value::String(claims.aud.clone()),
866 );
867 metadata.insert(
868 "scope".to_string(),
869 serde_json::Value::String(claims.scope.clone()),
870 );
871 metadata.insert(
872 "typ".to_string(),
873 serde_json::Value::String(claims.typ.clone()),
874 );
875 if let Some(ref sid) = claims.sid {
876 metadata
877 .insert("sid".to_string(), serde_json::Value::String(sid.clone()));
878 }
879 if let Some(ref client_id) = claims.client_id {
880 metadata.insert(
881 "client_id".to_string(),
882 serde_json::Value::String(client_id.clone()),
883 );
884 }
885
886 Ok(TokenValidationResult {
887 is_valid: true,
888 subject: Some(claims.sub),
889 issuer: Some(claims.iss),
890 audience,
891 scopes,
892 expires_at,
893 metadata,
894 validation_messages: Vec::new(),
895 })
896 }
897 Err(e) => Ok(TokenValidationResult {
898 is_valid: false,
899 subject: None,
900 issuer: None,
901 audience: Vec::new(),
902 scopes: Vec::new(),
903 expires_at: None,
904 metadata: HashMap::new(),
905 validation_messages: vec![format!("JWT validation failed: {}", e)],
906 }),
907 }
908 }
909 TokenType::Saml2 | TokenType::Saml1 => {
910 Ok(TokenValidationResult {
912 is_valid: true, subject: None, issuer: None, audience: Vec::new(),
916 scopes: Vec::new(),
917 expires_at: None,
918 metadata: HashMap::new(),
919 validation_messages: vec!["SAML validation not fully implemented".to_string()],
920 })
921 }
922 _ => Err(AuthError::InvalidRequest(format!(
923 "Token validation not supported for type: {}",
924 token_type
925 ))),
926 }
927 }
928
929 fn supported_subject_token_types(&self) -> Vec<String> {
931 Self::SUBJECT_TOKEN_TYPES
932 .iter()
933 .map(|s| s.to_string())
934 .collect()
935 }
936
937 fn supported_requested_token_types(&self) -> Vec<String> {
939 Self::REQUESTED_TOKEN_TYPES
940 .iter()
941 .map(|s| s.to_string())
942 .collect()
943 }
944
945 fn capabilities(&self) -> TokenExchangeCapabilities {
947 TokenExchangeCapabilities {
948 basic_exchange: true,
949 multi_party_chains: false,
950 context_preservation: false,
951 audit_trail: false,
952 session_integration: false,
953 jwt_operations: false,
954 policy_control: true,
955 cross_domain_exchange: false,
956 max_delegation_depth: 3,
957 complexity_level: ServiceComplexityLevel::Basic,
958 }
959 }
960}
961
962#[cfg(test)]
963mod tests {
964 use super::*;
965 use crate::security::secure_jwt::SecureJwtConfig;
966
967 fn create_test_manager() -> TokenExchangeManager {
968 let jwt_config = SecureJwtConfig::default();
969 let jwt_validator = SecureJwtValidator::new(jwt_config);
970 TokenExchangeManager::new(jwt_validator)
971 }
972
973 fn create_test_request() -> TokenExchangeRequest {
974 TokenExchangeRequest {
975 grant_type: "urn:ietf:params:oauth:grant-type:token-exchange".to_string(),
976 subject_token: "dummy.jwt.token".to_string(),
977 subject_token_type: "urn:ietf:params:oauth:token-type:access_token".to_string(),
978 actor_token: None,
979 actor_token_type: None,
980 requested_token_type: Some("urn:ietf:params:oauth:token-type:access_token".to_string()),
981 audience: Some("api.example.com".to_string()),
982 scope: Some("read write".to_string()),
983 resource: None,
984 }
985 }
986
987 #[tokio::test]
988 async fn test_token_exchange_manager_creation() {
989 let manager = create_test_manager();
990
991 let policy = TokenExchangePolicy::default();
993 manager
994 .register_policy("test_client".to_string(), policy)
995 .await;
996 }
997
998 #[test]
999 fn test_token_type_parsing() {
1000 let manager = create_test_manager();
1001
1002 assert_eq!(
1003 manager
1004 .parse_token_type("urn:ietf:params:oauth:token-type:access_token")
1005 .unwrap(),
1006 TokenType::AccessToken
1007 );
1008
1009 assert_eq!(
1010 manager
1011 .parse_token_type("urn:ietf:params:oauth:token-type:id_token")
1012 .unwrap(),
1013 TokenType::IdToken
1014 );
1015
1016 assert!(manager.parse_token_type("invalid_token_type").is_err());
1017 }
1018
1019 #[test]
1020 fn test_exchange_scenario_determination() {
1021 let manager = create_test_manager();
1022 let policy = TokenExchangePolicy::default();
1023
1024 let context = TokenExchangeContext {
1026 subject_claims: SecureJwtClaims {
1027 sub: "user123".to_string(),
1028 iss: "auth.example.com".to_string(),
1029 aud: "api.example.com".to_string(),
1030 exp: chrono::Utc::now().timestamp() + 3600,
1031 nbf: chrono::Utc::now().timestamp(),
1032 iat: chrono::Utc::now().timestamp(),
1033 jti: "token123".to_string(),
1034 scope: "read write".to_string(),
1035 typ: "access".to_string(),
1036 sid: None,
1037 client_id: None,
1038 auth_ctx_hash: None,
1039 },
1040 actor_claims: None,
1041 client_id: "test_client".to_string(),
1042 audience: Some("different.api.com".to_string()),
1043 scope: None,
1044 resource: None,
1045 };
1046
1047 let scenario = manager
1048 .determine_exchange_scenario(&context, &policy)
1049 .unwrap();
1050 assert_eq!(scenario, ExchangeScenario::AudienceRestriction);
1051 }
1052
1053 #[tokio::test]
1054 async fn test_invalid_grant_type() {
1055 let manager = create_test_manager();
1056 let policy = TokenExchangePolicy::default();
1057 manager
1058 .register_policy("test_client".to_string(), policy)
1059 .await;
1060
1061 let mut request = create_test_request();
1062 request.grant_type = "invalid_grant_type".to_string();
1063
1064 let result = manager.exchange_token(request, "test_client").await;
1065 assert!(result.is_err());
1066 }
1067}