1use crate::errors::{AuthError, Result};
92use crate::server::oidc::oidc_session_management::SessionManager;
93use crate::server::token_exchange::token_exchange_common::{
94 ServiceComplexityLevel, TokenExchangeCapabilities, TokenExchangeService, TokenValidationResult,
95 ValidationUtils,
96};
97
98use async_trait::async_trait;
99use chrono::{DateTime, Duration, Utc};
100use jsonwebtoken::{DecodingKey, EncodingKey};
101use serde::{Deserialize, Serialize};
102use std::collections::{HashMap, HashSet};
103use std::str::FromStr;
104use std::sync::Arc;
105use uuid::Uuid;
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
109pub enum AuthLevel {
110 Basic = 1,
112 Mfa = 2,
114 High = 3,
116}
117
118impl FromStr for AuthLevel {
119 type Err = AuthError;
120
121 fn from_str(s: &str) -> Result<Self, Self::Err> {
122 match s.to_lowercase().as_str() {
123 "basic" => Ok(AuthLevel::Basic),
124 "mfa" => Ok(AuthLevel::Mfa),
125 "high" => Ok(AuthLevel::High),
126 _ => Err(AuthError::InvalidRequest(format!(
127 "Invalid auth level: {}",
128 s
129 ))),
130 }
131 }
132}
133
134impl std::fmt::Display for AuthLevel {
135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136 let level_str = match self {
137 AuthLevel::Basic => "basic",
138 AuthLevel::Mfa => "mfa",
139 AuthLevel::High => "high",
140 };
141 write!(f, "{}", level_str)
142 }
143}
144
145#[derive(Clone, Serialize, Deserialize)]
147pub struct AdvancedTokenExchangeConfig {
148 pub enable_multi_party_chains: bool,
150
151 pub max_delegation_depth: usize,
153
154 pub require_audit_trail: bool,
156
157 pub enable_context_preservation: bool,
159
160 pub default_token_lifetime: Duration,
162
163 pub supported_subject_token_types: Vec<String>,
165
166 pub supported_requested_token_types: Vec<String>,
168
169 pub exchange_policies: Vec<TokenExchangePolicy>,
171
172 pub cross_domain_settings: CrossDomainExchangeSettings,
174
175 pub jwt_signing_key: String,
177
178 pub jwt_verification_key: String,
180
181 pub trusted_issuers: Vec<String>,
183}
184
185impl std::fmt::Debug for AdvancedTokenExchangeConfig {
186 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187 let mut d = f.debug_struct("AdvancedTokenExchangeConfig");
188 d.field("enable_multi_party_chains", &self.enable_multi_party_chains);
189 d.field("max_delegation_depth", &self.max_delegation_depth);
190 d.field("require_audit_trail", &self.require_audit_trail);
191 d.field(
192 "enable_context_preservation",
193 &self.enable_context_preservation,
194 );
195 d.field("default_token_lifetime", &self.default_token_lifetime);
196 d.field(
197 "supported_subject_token_types",
198 &self.supported_subject_token_types,
199 );
200 d.field(
201 "supported_requested_token_types",
202 &self.supported_requested_token_types,
203 );
204 d.field("exchange_policies", &self.exchange_policies);
205 d.field("cross_domain_settings", &self.cross_domain_settings);
206 d.field(
207 "jwt_signing_key",
208 &crate::utils::redact::redacted(&self.jwt_signing_key),
209 );
210 d.field(
211 "jwt_verification_key",
212 &crate::utils::redact::redacted(&self.jwt_verification_key),
213 );
214 d.field("trusted_issuers", &self.trusted_issuers);
215 d.finish()
216 }
217}
218
219impl Default for AdvancedTokenExchangeConfig {
220 fn default() -> Self {
221 Self {
222 enable_multi_party_chains: true,
223 max_delegation_depth: 3,
224 require_audit_trail: true,
225 enable_context_preservation: true,
226 default_token_lifetime: Duration::try_hours(1).unwrap_or(Duration::zero()),
227 supported_subject_token_types: vec![
228 "urn:ietf:params:oauth:token-type:jwt".to_string(),
229 "urn:ietf:params:oauth:token-type:access_token".to_string(),
230 "urn:ietf:params:oauth:token-type:refresh_token".to_string(),
231 "urn:ietf:params:oauth:token-type:id_token".to_string(),
232 "urn:ietf:params:oauth:token-type:saml2".to_string(),
233 ],
234 supported_requested_token_types: vec![
235 "urn:ietf:params:oauth:token-type:jwt".to_string(),
236 "urn:ietf:params:oauth:token-type:access_token".to_string(),
237 "urn:ietf:params:oauth:token-type:refresh_token".to_string(),
238 ],
239 exchange_policies: Vec::new(),
240 cross_domain_settings: CrossDomainExchangeSettings::default(),
241 jwt_signing_key: "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA...".to_string(), jwt_verification_key: "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B...".to_string(), trusted_issuers: vec![
244 "https://auth.example.com".to_string(),
245 "https://login.example.org".to_string(),
246 ],
247 }
248 }
249}
250
251#[derive(Clone, Serialize, Deserialize)]
253pub struct AdvancedTokenExchangeRequest {
254 pub grant_type: String,
256
257 pub subject_token: String,
259
260 pub subject_token_type: String,
262
263 pub actor_token: Option<String>,
265
266 pub actor_token_type: Option<String>,
268
269 pub requested_token_type: String,
271
272 pub scope: Option<String>,
274
275 pub audience: Vec<String>,
277
278 pub resource: Vec<String>,
280
281 pub exchange_context: Option<ExchangeContext>,
283
284 pub policy_requirements: Vec<String>,
286
287 pub custom_parameters: HashMap<String, serde_json::Value>,
289}
290
291impl std::fmt::Debug for AdvancedTokenExchangeRequest {
292 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
293 let mut d = f.debug_struct("AdvancedTokenExchangeRequest");
294 d.field("grant_type", &self.grant_type);
295 d.field(
296 "subject_token",
297 &crate::utils::redact::redacted(&self.subject_token),
298 );
299 d.field("subject_token_type", &self.subject_token_type);
300 d.field(
301 "actor_token",
302 &crate::utils::redact::redacted(&self.actor_token),
303 );
304 d.field("actor_token_type", &self.actor_token_type);
305 d.field("requested_token_type", &self.requested_token_type);
306 d.field("scope", &self.scope);
307 d.field("audience", &self.audience);
308 d.field("resource", &self.resource);
309 d.field("exchange_context", &self.exchange_context);
310 d.field("policy_requirements", &self.policy_requirements);
311 d.field(
312 "custom_parameters",
313 &crate::utils::redact::redacted(&self.custom_parameters),
314 );
315 d.finish()
316 }
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize)]
321pub struct ExchangeContext {
322 pub transaction_id: String,
324
325 pub business_context: serde_json::Value,
327
328 pub delegation_chain: Vec<DelegationLink>,
330
331 pub original_request: Option<RequestMetadata>,
333
334 pub security_context: Option<SecurityContext>,
336
337 pub custom_fields: HashMap<String, serde_json::Value>,
339}
340
341#[derive(Debug, Clone, Serialize, Deserialize)]
343pub struct DelegationLink {
344 pub delegator: String,
346
347 pub delegatee: String,
349
350 pub delegated_at: DateTime<Utc>,
352
353 pub delegation_reason: String,
355
356 pub delegated_scopes: Vec<String>,
358
359 pub restrictions: Vec<DelegationRestriction>,
361}
362
363#[derive(Debug, Clone, Serialize, Deserialize)]
365#[serde(tag = "type", rename_all = "snake_case")]
366pub enum DelegationRestriction {
367 TimeLimit { expires_at: DateTime<Utc> },
369
370 UsageLimit { max_uses: u32, current_uses: u32 },
372
373 IpRestriction { allowed_ips: Vec<String> },
375
376 ScopeRestriction { restricted_scopes: Vec<String> },
378
379 Custom {
381 restriction_type: String,
382 parameters: HashMap<String, serde_json::Value>,
383 },
384}
385
386#[derive(Clone, Serialize, Deserialize)]
388pub struct RequestMetadata {
389 pub client_id: String,
391
392 pub user_agent: Option<String>,
394
395 pub ip_address: Option<String>,
397
398 pub timestamp: DateTime<Utc>,
400
401 pub headers: HashMap<String, String>,
403}
404
405impl std::fmt::Debug for RequestMetadata {
406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407 let mut d = f.debug_struct("RequestMetadata");
408 d.field("client_id", &self.client_id);
409 d.field("user_agent", &self.user_agent);
410 d.field("ip_address", &self.ip_address);
411 d.field("timestamp", &self.timestamp);
412 d.field("headers", &crate::utils::redact::redacted(&self.headers));
413 d.finish()
414 }
415}
416
417#[derive(Clone, Serialize, Deserialize)]
419pub struct SecurityContext {
420 pub session_id: Option<String>,
422
423 pub authentication_level: String,
425
426 pub mfa_completed: bool,
428
429 pub risk_score: f64,
431
432 pub device_info: Option<DeviceContext>,
434
435 pub location_info: Option<LocationContext>,
437}
438
439impl std::fmt::Debug for SecurityContext {
440 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
441 let mut d = f.debug_struct("SecurityContext");
442 d.field(
443 "session_id",
444 &crate::utils::redact::redacted(&self.session_id),
445 );
446 d.field("authentication_level", &self.authentication_level);
447 d.field("mfa_completed", &self.mfa_completed);
448 d.field("risk_score", &self.risk_score);
449 d.field("device_info", &self.device_info);
450 d.field("location_info", &self.location_info);
451 d.finish()
452 }
453}
454
455#[derive(Debug, Clone, Serialize, Deserialize)]
457pub struct DeviceContext {
458 pub device_id: String,
460
461 pub device_type: String,
463
464 pub trust_level: String,
466
467 pub fingerprint: Option<String>,
469}
470
471#[derive(Debug, Clone, Serialize, Deserialize)]
473pub struct LocationContext {
474 pub country: Option<String>,
476
477 pub city: Option<String>,
479
480 pub geo_data: Option<serde_json::Value>,
482
483 pub network_info: Option<String>,
485}
486
487#[derive(Debug, Clone, Serialize, Deserialize)]
489pub struct TokenExchangePolicy {
490 pub id: String,
492
493 pub name: String,
495
496 pub conditions: Vec<PolicyCondition>,
498
499 pub actions: Vec<PolicyAction>,
501
502 pub mandatory: bool,
504}
505
506#[derive(Debug, Clone, Serialize, Deserialize)]
508#[serde(tag = "type", rename_all = "snake_case")]
509pub enum PolicyCondition {
510 SubjectTokenType { allowed_types: Vec<String> },
512
513 ScopeRequirement {
515 required_scopes: Vec<String>,
516 all_required: bool,
517 },
518
519 DelegationDepth { max_depth: usize },
521
522 ClientAuthorization { authorized_clients: Vec<String> },
524
525 TimeRestriction {
527 allowed_hours: Vec<u8>,
528 timezone: String,
529 },
530
531 Custom {
533 condition_type: String,
534 parameters: HashMap<String, serde_json::Value>,
535 },
536}
537
538#[derive(Debug, Clone, Serialize, Deserialize)]
540#[serde(tag = "type", rename_all = "snake_case")]
541pub enum PolicyAction {
542 Allow,
544
545 Deny { reason: String },
547
548 RequireStepUp { required_level: String },
550
551 RestrictScopes { allowed_scopes: Vec<String> },
553
554 RestrictLifetime { max_lifetime: Duration },
556
557 Custom {
559 action_type: String,
560 parameters: HashMap<String, serde_json::Value>,
561 },
562}
563
564#[derive(Debug, Clone, Serialize, Deserialize)]
566pub struct CrossDomainExchangeSettings {
567 pub enabled: bool,
569
570 pub trusted_domains: Vec<String>,
572
573 pub cross_domain_policies: Vec<CrossDomainPolicy>,
575
576 pub require_domain_validation: bool,
578}
579
580impl Default for CrossDomainExchangeSettings {
581 fn default() -> Self {
582 Self {
583 enabled: false,
584 trusted_domains: Vec::new(),
585 cross_domain_policies: Vec::new(),
586 require_domain_validation: true,
587 }
588 }
589}
590
591#[derive(Debug, Clone, Serialize, Deserialize)]
593pub struct CrossDomainPolicy {
594 pub id: String,
596
597 pub source_domain: String,
599
600 pub target_domain: String,
602
603 pub allowed_token_types: Vec<String>,
605
606 pub required_claims: Vec<String>,
608
609 pub scope_mappings: HashMap<String, String>,
611}
612
613#[derive(Clone, Serialize, Deserialize)]
615pub struct AdvancedTokenExchangeResponse {
616 pub access_token: String,
618
619 pub issued_token_type: String,
621
622 pub token_type: String,
624
625 pub expires_in: Option<u64>,
627
628 pub scope: Option<String>,
630
631 pub refresh_token: Option<String>,
633
634 pub exchange_audit: Option<ExchangeAuditInfo>,
636
637 pub preserved_context: Option<ExchangeContext>,
639
640 pub additional_parameters: HashMap<String, serde_json::Value>,
642}
643
644impl std::fmt::Debug for AdvancedTokenExchangeResponse {
645 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
646 let mut d = f.debug_struct("AdvancedTokenExchangeResponse");
647 d.field(
648 "access_token",
649 &crate::utils::redact::redacted(&self.access_token),
650 );
651 d.field("issued_token_type", &self.issued_token_type);
652 d.field("token_type", &self.token_type);
653 d.field("expires_in", &self.expires_in);
654 d.field("scope", &self.scope);
655 d.field(
656 "refresh_token",
657 &crate::utils::redact::redacted(&self.refresh_token),
658 );
659 d.field("exchange_audit", &self.exchange_audit);
660 d.field("preserved_context", &self.preserved_context);
661 d.field(
662 "additional_parameters",
663 &crate::utils::redact::redacted(&self.additional_parameters),
664 );
665 d.finish()
666 }
667}
668
669#[derive(Debug, Clone, Serialize, Deserialize)]
671pub struct ExchangeAuditInfo {
672 pub exchange_id: Uuid,
674
675 pub timestamp: DateTime<Utc>,
677
678 pub exchange_type: TokenExchangeType,
680
681 pub subject_info: SubjectInfo,
683
684 pub actor_info: Option<ActorInfo>,
686
687 pub policy_decisions: Vec<PolicyDecision>,
689
690 pub security_assessments: Vec<SecurityAssessment>,
692}
693
694#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
696#[serde(rename_all = "snake_case")]
697pub enum TokenExchangeType {
698 Impersonation,
700
701 Delegation,
703
704 Translation,
706
707 ContextExchange,
709
710 Federation,
712
713 PrivilegeEscalation,
715}
716
717#[derive(Debug, Clone, Serialize, Deserialize)]
719pub struct SubjectInfo {
720 pub subject: String,
722
723 pub subject_type: String,
725
726 pub original_token_info: TokenInfo,
728
729 pub attributes: HashMap<String, serde_json::Value>,
731}
732
733#[derive(Debug, Clone, Serialize, Deserialize)]
735pub struct ActorInfo {
736 pub actor: String,
738
739 pub actor_type: String,
741
742 pub actor_token_info: TokenInfo,
744
745 pub attributes: HashMap<String, serde_json::Value>,
747}
748
749#[derive(Debug, Clone, Serialize, Deserialize)]
751pub struct TokenInfo {
752 pub token_type: String,
754
755 pub issuer: String,
757
758 pub audience: Vec<String>,
760
761 pub scopes: Vec<String>,
763
764 pub expires_at: Option<DateTime<Utc>>,
766
767 pub metadata: HashMap<String, serde_json::Value>,
769}
770
771#[derive(Debug, Clone, Serialize, Deserialize)]
773pub struct PolicyDecision {
774 pub policy_id: String,
776
777 pub decision: PolicyDecisionResult,
779
780 pub reason: String,
782
783 pub applied_modifications: Vec<String>,
785}
786
787#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
789#[serde(rename_all = "snake_case")]
790pub enum PolicyDecisionResult {
791 Allow,
793
794 Deny,
796
797 Modify,
799
800 RequireVerification,
802}
803
804#[derive(Debug, Clone, Serialize, Deserialize)]
806pub struct SecurityAssessment {
807 pub assessment_type: String,
809
810 pub result: SecurityAssessmentResult,
812
813 pub risk_score: f64,
815
816 pub details: HashMap<String, serde_json::Value>,
818}
819
820#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
822#[serde(rename_all = "snake_case")]
823pub enum SecurityAssessmentResult {
824 Pass,
826
827 Fail,
829
830 RequiresReview,
832
833 Inconclusive,
835}
836
837#[async_trait]
839pub trait TokenExchangeProcessor: Send + Sync {
840 async fn process_exchange(
842 &self,
843 request: &AdvancedTokenExchangeRequest,
844 context: &ExchangeContext,
845 ) -> Result<AdvancedTokenExchangeResponse>;
846
847 async fn validate_subject_token(&self, token: &str, token_type: &str) -> Result<TokenInfo>;
849
850 async fn validate_actor_token(&self, token: &str, token_type: &str) -> Result<TokenInfo>;
852
853 async fn generate_exchanged_token(
855 &self,
856 subject_info: &SubjectInfo,
857 actor_info: Option<&ActorInfo>,
858 request: &AdvancedTokenExchangeRequest,
859 ) -> Result<String>;
860}
861
862pub struct AdvancedTokenExchangeManager {
864 config: AdvancedTokenExchangeConfig,
866
867 session_manager: Arc<SessionManager>,
869
870 processors: HashMap<String, Arc<dyn TokenExchangeProcessor>>,
872
873 exchange_audit: Arc<tokio::sync::RwLock<Vec<ExchangeAuditInfo>>>,
875
876 encoding_key: EncodingKey,
878
879 decoding_key: DecodingKey,
881}
882
883impl AdvancedTokenExchangeManager {
884 pub fn new(
886 config: AdvancedTokenExchangeConfig,
887 session_manager: Arc<SessionManager>,
888 ) -> Result<Self> {
889 let encoding_key = EncodingKey::from_rsa_pem(config.jwt_signing_key.as_bytes())?;
891 let decoding_key = DecodingKey::from_rsa_pem(config.jwt_verification_key.as_bytes())?;
892
893 Ok(Self {
894 config,
895 session_manager,
896 processors: HashMap::new(),
897 exchange_audit: Arc::new(tokio::sync::RwLock::new(Vec::new())),
898 encoding_key,
899 decoding_key,
900 })
901 }
902
903 pub fn register_processor(
905 &mut self,
906 token_type: String,
907 processor: Arc<dyn TokenExchangeProcessor>,
908 ) {
909 self.processors.insert(token_type, processor);
910 }
911
912 pub async fn exchange_token(
914 &self,
915 request: AdvancedTokenExchangeRequest,
916 ) -> Result<AdvancedTokenExchangeResponse> {
917 self.validate_exchange_request(&request).await?;
919
920 let context = request
922 .exchange_context
923 .clone()
924 .unwrap_or_else(|| ExchangeContext {
925 transaction_id: Uuid::new_v4().to_string(),
926 business_context: serde_json::Value::Null,
927 delegation_chain: Vec::new(),
928 original_request: None,
929 security_context: None,
930 custom_fields: HashMap::new(),
931 });
932
933 if context.delegation_chain.len() > self.config.max_delegation_depth {
935 return Err(AuthError::InvalidRequest(
936 "Maximum delegation depth exceeded".to_string(),
937 ));
938 }
939
940 self.apply_exchange_policies(&request, &context).await?;
942
943 let subject_info = self.validate_and_extract_subject_info(&request).await?;
945
946 let actor_info = if request.actor_token.is_some() {
948 Some(self.validate_and_extract_actor_info(&request).await?)
949 } else {
950 None
951 };
952
953 let exchange_type = self.determine_exchange_type(&request, &subject_info, &actor_info);
955
956 let processor = self.get_processor(&request.requested_token_type)?;
958 let mut response = processor.process_exchange(&request, &context).await?;
959
960 let audit_info = self
962 .create_audit_info(
963 exchange_type,
964 &subject_info,
965 &actor_info,
966 &request,
967 &context,
968 )
969 .await?;
970
971 {
973 let mut audit_log = self.exchange_audit.write().await;
974 audit_log.push(audit_info.clone());
975 }
976
977 if self.config.require_audit_trail {
979 response.exchange_audit = Some(audit_info.clone());
980
981 let audit_token = self.generate_audit_token(&audit_info)?;
983 response.additional_parameters.insert(
984 "audit_token".to_string(),
985 serde_json::Value::String(audit_token),
986 );
987 }
988
989 if self.config.enable_context_preservation {
991 let preserved_context = context.clone();
992 response.preserved_context = Some(preserved_context.clone());
993
994 let delegation_token = self.generate_delegation_token(&preserved_context)?;
996 response.additional_parameters.insert(
997 "delegation_token".to_string(),
998 serde_json::Value::String(delegation_token),
999 );
1000 }
1001
1002 Ok(response)
1003 }
1004
1005 pub async fn get_exchange_audit(&self) -> Vec<ExchangeAuditInfo> {
1007 let audit_log = self.exchange_audit.read().await;
1008 audit_log.clone()
1009 }
1010
1011 async fn validate_exchange_request(
1013 &self,
1014 request: &AdvancedTokenExchangeRequest,
1015 ) -> Result<()> {
1016 if request.grant_type != "urn:ietf:params:oauth:grant-type:token-exchange" {
1018 return Err(AuthError::InvalidRequest(
1019 "Invalid grant type for token exchange".to_string(),
1020 ));
1021 }
1022
1023 if !self
1025 .config
1026 .supported_subject_token_types
1027 .contains(&request.subject_token_type)
1028 {
1029 return Err(AuthError::InvalidRequest(format!(
1030 "Unsupported subject token type: {}",
1031 request.subject_token_type
1032 )));
1033 }
1034
1035 if !self
1037 .config
1038 .supported_requested_token_types
1039 .contains(&request.requested_token_type)
1040 {
1041 return Err(AuthError::InvalidRequest(format!(
1042 "Unsupported requested token type: {}",
1043 request.requested_token_type
1044 )));
1045 }
1046
1047 if let Some(ref actor_token_type) = request.actor_token_type
1049 && !self
1050 .config
1051 .supported_subject_token_types
1052 .contains(actor_token_type)
1053 {
1054 return Err(AuthError::InvalidRequest(format!(
1055 "Unsupported actor token type: {}",
1056 actor_token_type
1057 )));
1058 }
1059
1060 Ok(())
1061 }
1062
1063 async fn apply_exchange_policies(
1065 &self,
1066 request: &AdvancedTokenExchangeRequest,
1067 context: &ExchangeContext,
1068 ) -> Result<()> {
1069 if request.subject_token_type == "urn:ietf:params:oauth:token-type:jwt" {
1071 match self.introspect_jwt_token(&request.subject_token) {
1072 Ok(token_claims) => {
1073 if let Some(iss) = token_claims.get("iss").and_then(|v| v.as_str())
1075 && !self.config.trusted_issuers.contains(&iss.to_string())
1076 {
1077 return Err(AuthError::InvalidRequest(format!(
1078 "Token issued by untrusted issuer: {}",
1079 iss
1080 )));
1081 }
1082 }
1083 Err(_) => {
1084 }
1087 }
1088 }
1089
1090 for policy in &self.config.exchange_policies {
1091 let policy_applies = self.evaluate_policy_conditions(policy, request, context)?;
1092
1093 if policy_applies {
1094 for action in &policy.actions {
1095 match action {
1096 PolicyAction::Deny { reason } => {
1097 return Err(AuthError::InvalidRequest(format!(
1098 "Exchange denied by policy '{}': {}",
1099 policy.name, reason
1100 )));
1101 }
1102 PolicyAction::RequireStepUp { required_level } => {
1103 let auth_level = required_level.parse::<AuthLevel>().map_err(|_| {
1105 AuthError::InvalidRequest(format!(
1106 "Invalid authentication level: {}",
1107 required_level
1108 ))
1109 })?;
1110 return self
1111 .handle_step_up_authentication(auth_level, context)
1112 .await;
1113 }
1114 _ => {
1115 }
1117 }
1118 }
1119 }
1120 }
1121
1122 Ok(())
1123 }
1124
1125 fn evaluate_policy_conditions(
1127 &self,
1128 policy: &TokenExchangePolicy,
1129 request: &AdvancedTokenExchangeRequest,
1130 context: &ExchangeContext,
1131 ) -> Result<bool> {
1132 for condition in &policy.conditions {
1133 match condition {
1134 PolicyCondition::SubjectTokenType { allowed_types } => {
1135 if !allowed_types.contains(&request.subject_token_type) {
1136 return Ok(false);
1137 }
1138 }
1139 PolicyCondition::DelegationDepth { max_depth } => {
1140 if context.delegation_chain.len() > *max_depth {
1141 return Ok(false);
1142 }
1143 }
1144 PolicyCondition::ScopeRequirement {
1145 required_scopes,
1146 all_required,
1147 } => {
1148 if let Some(ref scope) = request.scope {
1149 let request_scopes: HashSet<&str> = scope.split(' ').collect();
1150 let required: HashSet<&str> =
1151 required_scopes.iter().map(|s| s.as_str()).collect();
1152
1153 if *all_required {
1154 if !required.is_subset(&request_scopes) {
1155 return Ok(false);
1156 }
1157 } else if required.is_disjoint(&request_scopes) {
1158 return Ok(false);
1159 }
1160 }
1161 }
1162 _ => {
1163 }
1165 }
1166 }
1167
1168 Ok(true)
1169 }
1170
1171 async fn validate_and_extract_subject_info(
1173 &self,
1174 request: &AdvancedTokenExchangeRequest,
1175 ) -> Result<SubjectInfo> {
1176 let processor = self.get_processor(&request.subject_token_type)?;
1177 let token_info = processor
1178 .validate_subject_token(&request.subject_token, &request.subject_token_type)
1179 .await?;
1180
1181 Ok(SubjectInfo {
1182 subject: token_info
1183 .metadata
1184 .get("sub")
1185 .and_then(|v| v.as_str())
1186 .unwrap_or("unknown")
1187 .to_string(),
1188 subject_type: "user".to_string(), original_token_info: token_info,
1190 attributes: HashMap::new(),
1191 })
1192 }
1193
1194 async fn validate_and_extract_actor_info(
1196 &self,
1197 request: &AdvancedTokenExchangeRequest,
1198 ) -> Result<ActorInfo> {
1199 let actor_token = request.actor_token.as_ref().unwrap();
1200 let actor_token_type = request.actor_token_type.as_ref().unwrap();
1201
1202 let processor = self.get_processor(actor_token_type)?;
1203 let token_info = processor
1204 .validate_actor_token(actor_token, actor_token_type)
1205 .await?;
1206
1207 Ok(ActorInfo {
1208 actor: token_info
1209 .metadata
1210 .get("sub")
1211 .and_then(|v| v.as_str())
1212 .unwrap_or("unknown")
1213 .to_string(),
1214 actor_type: "service".to_string(), actor_token_info: token_info,
1216 attributes: HashMap::new(),
1217 })
1218 }
1219
1220 fn determine_exchange_type(
1222 &self,
1223 request: &AdvancedTokenExchangeRequest,
1224 _subject_info: &SubjectInfo,
1225 actor_info: &Option<ActorInfo>,
1226 ) -> TokenExchangeType {
1227 if actor_info.is_some() {
1228 TokenExchangeType::Delegation
1229 } else if request.exchange_context.is_some() {
1230 TokenExchangeType::ContextExchange
1231 } else if request.subject_token_type != request.requested_token_type {
1232 TokenExchangeType::Translation
1233 } else {
1234 TokenExchangeType::Impersonation
1235 }
1236 }
1237
1238 fn get_processor(&self, token_type: &str) -> Result<Arc<dyn TokenExchangeProcessor>> {
1240 self.processors.get(token_type).cloned().ok_or_else(|| {
1241 AuthError::InvalidRequest(format!(
1242 "No processor registered for token type: {}",
1243 token_type
1244 ))
1245 })
1246 }
1247
1248 async fn create_audit_info(
1250 &self,
1251 exchange_type: TokenExchangeType,
1252 _subject_info: &SubjectInfo,
1253 actor_info: &Option<ActorInfo>,
1254 _request: &AdvancedTokenExchangeRequest,
1255 _context: &ExchangeContext,
1256 ) -> Result<ExchangeAuditInfo> {
1257 Ok(ExchangeAuditInfo {
1258 exchange_id: Uuid::new_v4(),
1259 timestamp: Utc::now(),
1260 exchange_type,
1261 subject_info: _subject_info.clone(),
1262 actor_info: actor_info.clone(),
1263 policy_decisions: Vec::new(), security_assessments: Vec::new(), })
1266 }
1267
1268 pub async fn cleanup_old_audit_entries(&self, older_than: DateTime<Utc>) -> usize {
1270 let mut audit_log = self.exchange_audit.write().await;
1271 let original_len = audit_log.len();
1272
1273 audit_log.retain(|entry| entry.timestamp > older_than);
1274
1275 original_len - audit_log.len()
1276 }
1277
1278 pub fn generate_audit_token(&self, audit_info: &ExchangeAuditInfo) -> Result<String> {
1280 use jsonwebtoken::{Algorithm, Header, encode};
1281 use serde_json::json;
1282
1283 let header = Header::new(Algorithm::HS256);
1284
1285 let claims = json!({
1286 "iss": "advanced-token-exchange",
1287 "sub": audit_info.subject_info.subject,
1288 "aud": "audit-verification",
1289 "exp": (Utc::now() + Duration::seconds(3600)).timestamp(),
1290 "iat": Utc::now().timestamp(),
1291 "exchange_id": audit_info.exchange_id,
1292 "exchange_type": audit_info.exchange_type,
1293 "timestamp": audit_info.timestamp,
1294 "policy_decisions": audit_info.policy_decisions.len(),
1295 "security_assessments": audit_info.security_assessments.len()
1296 });
1297
1298 encode(&header, &claims, &self.encoding_key).map_err(|e| {
1299 AuthError::TokenGeneration(format!("Failed to generate audit token: {}", e))
1300 })
1301 }
1302
1303 pub fn validate_delegation_token(&self, token: &str) -> Result<serde_json::Value> {
1305 use jsonwebtoken::{Algorithm, Validation, decode};
1306
1307 let mut validation = Validation::new(Algorithm::HS256);
1308 validation.set_audience(&["delegation-context"]);
1309 validation.set_issuer(&["advanced-token-exchange"]);
1310
1311 let token_data = decode::<serde_json::Value>(token, &self.decoding_key, &validation)
1312 .map_err(|e| AuthError::InvalidToken(format!("Invalid delegation token: {}", e)))?;
1313
1314 Ok(token_data.claims)
1315 }
1316
1317 pub fn generate_delegation_token(&self, context: &ExchangeContext) -> Result<String> {
1319 use jsonwebtoken::{Algorithm, Header, encode};
1320 use serde_json::json;
1321
1322 let header = Header::new(Algorithm::RS256);
1323
1324 let claims = json!({
1325 "iss": "advanced-token-exchange",
1326 "aud": "delegation-context",
1327 "exp": (Utc::now() + Duration::seconds(1800)).timestamp(), "iat": Utc::now().timestamp(),
1329 "transaction_id": context.transaction_id,
1330 "delegation_chain_length": context.delegation_chain.len(),
1331 "delegation_chain": context.delegation_chain,
1332 "business_context": context.business_context,
1333 "custom_fields": context.custom_fields
1334 });
1335
1336 encode(&header, &claims, &self.encoding_key).map_err(|e| {
1337 AuthError::TokenGeneration(format!("Failed to generate delegation token: {}", e))
1338 })
1339 }
1340
1341 pub fn introspect_jwt_token(&self, token: &str) -> Result<serde_json::Value> {
1343 use jsonwebtoken::{Algorithm, Validation, decode};
1344
1345 let mut validation = Validation::new(Algorithm::RS256);
1346 validation.insecure_disable_signature_validation(); let token_data = decode::<serde_json::Value>(token, &self.decoding_key, &validation)
1349 .map_err(|e| AuthError::InvalidToken(format!("Token introspection failed: {}", e)))?;
1350
1351 Ok(token_data.claims)
1352 }
1353
1354 async fn handle_step_up_authentication(
1356 &self,
1357 required_level: AuthLevel,
1358 context: &ExchangeContext,
1359 ) -> Result<()> {
1360 if let Some(session_id) = context
1362 .security_context
1363 .as_ref()
1364 .and_then(|sc| sc.session_id.as_ref())
1365 {
1366 match self.session_manager.get_session(session_id) {
1368 Some(session) => {
1369 if let Some(current_level) = session
1371 .metadata
1372 .get("auth_level")
1373 .map(|v| v.as_str())
1374 .and_then(|s| s.parse::<AuthLevel>().ok())
1375 && current_level >= required_level
1376 {
1377 return Ok(());
1379 }
1380
1381 Err(AuthError::StepUpRequired {
1383 current_level: session
1384 .metadata
1385 .get("auth_level")
1386 .map(|v| v.as_str())
1387 .unwrap_or("basic")
1388 .to_string(),
1389 required_level: required_level.to_string(),
1390 step_up_url: format!(
1391 "/auth/step-up?session_id={}&level={}",
1392 session_id, required_level
1393 ),
1394 })
1395 }
1396 None => {
1397 Err(AuthError::Unauthorized(
1399 "No active session found".to_string(),
1400 ))
1401 }
1402 }
1403 } else {
1404 Err(AuthError::Unauthorized(
1406 "No session context available".to_string(),
1407 ))
1408 }
1409 }
1410}
1411
1412#[async_trait]
1414impl TokenExchangeService for AdvancedTokenExchangeManager {
1415 type Request = AdvancedTokenExchangeRequest;
1416 type Response = AdvancedTokenExchangeResponse;
1417 type Config = AdvancedTokenExchangeConfig;
1418
1419 async fn exchange_token(&self, request: Self::Request) -> Result<Self::Response> {
1421 self.exchange_token(request).await
1422 }
1423
1424 async fn validate_token(&self, token: &str, token_type: &str) -> Result<TokenValidationResult> {
1426 let supported_types = self.supported_subject_token_types();
1428 ValidationUtils::validate_token_type(token_type, &supported_types)?;
1429
1430 if ValidationUtils::is_jwt_token_type(token_type) {
1432 match self.introspect_jwt_token(token) {
1433 Ok(claims) => {
1434 let subject = ValidationUtils::extract_subject(
1436 &claims
1437 .as_object()
1438 .unwrap_or(&serde_json::Map::new())
1439 .iter()
1440 .map(|(k, v)| (k.clone(), v.clone()))
1441 .collect(),
1442 );
1443
1444 let scopes = ValidationUtils::extract_scopes(
1445 &claims
1446 .as_object()
1447 .unwrap_or(&serde_json::Map::new())
1448 .iter()
1449 .map(|(k, v)| (k.clone(), v.clone()))
1450 .collect(),
1451 None,
1452 );
1453
1454 Ok(TokenValidationResult {
1455 is_valid: true,
1456 subject,
1457 issuer: claims
1458 .get("iss")
1459 .and_then(|v| v.as_str())
1460 .map(|s| s.to_string()),
1461 audience: claims
1462 .get("aud")
1463 .and_then(|v| v.as_str())
1464 .map(|s| vec![s.to_string()])
1465 .unwrap_or_default(),
1466 scopes,
1467 expires_at: claims.get("exp").and_then(|v| v.as_i64()).and_then(|exp| {
1468 use chrono::{TimeZone, Utc};
1469 Utc.timestamp_opt(exp, 0).single()
1470 }),
1471 metadata: claims
1472 .as_object()
1473 .unwrap_or(&serde_json::Map::new())
1474 .iter()
1475 .map(|(k, v)| (k.clone(), v.clone()))
1476 .collect(),
1477 validation_messages: Vec::new(),
1478 })
1479 }
1480 Err(e) => Ok(TokenValidationResult {
1481 is_valid: false,
1482 subject: None,
1483 issuer: None,
1484 audience: Vec::new(),
1485 scopes: Vec::new(),
1486 expires_at: None,
1487 metadata: std::collections::HashMap::new(),
1488 validation_messages: vec![format!("JWT validation failed: {}", e)],
1489 }),
1490 }
1491 } else {
1492 Ok(TokenValidationResult {
1494 is_valid: true, subject: None,
1496 issuer: None,
1497 audience: Vec::new(),
1498 scopes: Vec::new(),
1499 expires_at: None,
1500 metadata: std::collections::HashMap::new(),
1501 validation_messages: vec![format!(
1502 "Basic validation for token type: {}",
1503 token_type
1504 )],
1505 })
1506 }
1507 }
1508
1509 fn supported_subject_token_types(&self) -> Vec<String> {
1511 self.config.supported_subject_token_types.clone()
1512 }
1513
1514 fn supported_requested_token_types(&self) -> Vec<String> {
1516 self.config.supported_requested_token_types.clone()
1517 }
1518
1519 fn capabilities(&self) -> TokenExchangeCapabilities {
1521 TokenExchangeCapabilities {
1522 basic_exchange: true,
1523 multi_party_chains: self.config.enable_multi_party_chains,
1524 context_preservation: self.config.enable_context_preservation,
1525 audit_trail: self.config.require_audit_trail,
1526 session_integration: true, jwt_operations: true, policy_control: true, cross_domain_exchange: self.config.cross_domain_settings.enabled,
1530 max_delegation_depth: self.config.max_delegation_depth,
1531 complexity_level: ServiceComplexityLevel::Advanced,
1532 }
1533 }
1534}
1535
1536#[cfg(test)]
1537mod tests {
1538 use super::*;
1539
1540 #[tokio::test]
1541 async fn test_config_creation() {
1542 let config = AdvancedTokenExchangeConfig::default();
1543 assert!(config.enable_multi_party_chains);
1544 assert!(!config.supported_subject_token_types.is_empty());
1545 assert!(!config.supported_requested_token_types.is_empty());
1546 assert!(!config.trusted_issuers.is_empty());
1547 }
1548
1549 #[test]
1550 fn test_jwt_key_functionality() {
1551 use crate::server::oidc::oidc_session_management::SessionManager;
1552 use jsonwebtoken::{DecodingKey, EncodingKey};
1553
1554 let secret = b"test-secret-key-32-bytes-minimum!";
1556 let encoding_key = EncodingKey::from_secret(secret);
1557 let decoding_key = DecodingKey::from_secret(secret);
1558
1559 let config = AdvancedTokenExchangeConfig {
1560 jwt_signing_key: "test-secret-key-32-bytes-minimum!".to_string(),
1561 jwt_verification_key: "test-secret-key-32-bytes-minimum!".to_string(),
1562 ..Default::default()
1563 };
1564
1565 let session_manager = Arc::new(SessionManager::new(Default::default()));
1566
1567 let manager = AdvancedTokenExchangeManager {
1569 config,
1570 session_manager,
1571 processors: HashMap::new(),
1572 exchange_audit: Arc::new(tokio::sync::RwLock::new(Vec::new())),
1573 encoding_key,
1574 decoding_key,
1575 };
1576
1577 let audit_info = ExchangeAuditInfo {
1579 exchange_id: Uuid::new_v4(),
1580 timestamp: Utc::now(),
1581 exchange_type: TokenExchangeType::Delegation,
1582 subject_info: SubjectInfo {
1583 subject: "test_user".to_string(),
1584 subject_type: "user".to_string(),
1585 original_token_info: TokenInfo {
1586 token_type: "jwt".to_string(),
1587 issuer: "test".to_string(),
1588 audience: vec!["test".to_string()],
1589 scopes: vec!["read".to_string()],
1590 expires_at: None,
1591 metadata: HashMap::new(),
1592 },
1593 attributes: HashMap::new(),
1594 },
1595 actor_info: None,
1596 policy_decisions: Vec::new(),
1597 security_assessments: Vec::new(),
1598 };
1599
1600 let result = manager.generate_audit_token(&audit_info);
1602 assert!(
1603 result.is_ok(),
1604 "JWT keys should be properly initialized for signing"
1605 );
1606 }
1607
1608 #[test]
1609 fn test_exchange_request_creation() {
1610 let request = AdvancedTokenExchangeRequest {
1611 grant_type: "urn:ietf:params:oauth:grant-type:token-exchange".to_string(),
1612 subject_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9".to_string(),
1613 subject_token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(),
1614 requested_token_type: "urn:ietf:params:oauth:token-type:access_token".to_string(),
1615 actor_token: None,
1616 actor_token_type: None,
1617 scope: Some("read write".to_string()),
1618 audience: vec!["https://api.example.com".to_string()],
1619 resource: Vec::new(),
1620 exchange_context: None,
1621 policy_requirements: Vec::new(),
1622 custom_parameters: HashMap::new(),
1623 };
1624
1625 assert_eq!(
1626 request.grant_type,
1627 "urn:ietf:params:oauth:grant-type:token-exchange"
1628 );
1629 assert_eq!(
1630 request.subject_token_type,
1631 "urn:ietf:params:oauth:token-type:jwt"
1632 );
1633 }
1634
1635 #[test]
1636 fn test_exchange_context_creation() {
1637 let context = ExchangeContext {
1638 transaction_id: "txn_123".to_string(),
1639 business_context: serde_json::json!({
1640 "operation": "payment",
1641 "amount": 100.0
1642 }),
1643 delegation_chain: Vec::new(),
1644 original_request: None,
1645 security_context: None,
1646 custom_fields: HashMap::new(),
1647 };
1648
1649 assert_eq!(context.transaction_id, "txn_123");
1650 assert_eq!(context.business_context["operation"], "payment");
1651 }
1652
1653 #[test]
1654 fn test_delegation_link_creation() {
1655 let link = DelegationLink {
1656 delegator: "service_a".to_string(),
1657 delegatee: "service_b".to_string(),
1658 delegated_at: Utc::now(),
1659 delegation_reason: "API call forwarding".to_string(),
1660 delegated_scopes: vec!["read".to_string(), "write".to_string()],
1661 restrictions: Vec::new(),
1662 };
1663
1664 assert_eq!(link.delegator, "service_a");
1665 assert_eq!(link.delegated_scopes.len(), 2);
1666 }
1667}