Skip to main content

auth_framework/server/token_exchange/
core.rs

1//! OAuth 2.0 Token Exchange (RFC 8693) - Basic Implementation
2//!
3//! This module implements RFC 8693, which defines a protocol for exchanging
4//! one security token for another, enabling delegation and acting-as scenarios.
5//!
6//! This is the **basic** implementation suitable for simple token exchange scenarios.
7//! For enterprise-grade features like multi-party chains, audit trails, and session
8//! integration, use `AdvancedTokenExchangeManager` instead.
9//!
10//! ## When to Use This Manager
11//!
12//! Use `TokenExchangeManager` when you need:
13//! - Simple RFC 8693 compliant token exchange
14//! - Lightweight implementation with minimal dependencies
15//! - Basic delegation scenarios (OnBehalfOf, ActingAs)
16//! - Client-specific policies
17//! - Standard token validation (JWT, SAML)
18//!
19//! ## When to Use Advanced Manager
20//!
21//! Use `AdvancedTokenExchangeManager` when you need:
22//! - Multi-party delegation chains
23//! - Context preservation across exchanges
24//! - Comprehensive audit trails
25//! - Session integration and step-up authentication
26//! - Policy-driven exchange control
27//! - Cross-domain exchanges
28//! - JWT cryptographic operations
29//!
30//! ## Example Usage
31//!
32//! ```rust,no_run
33//! use auth_framework::server::token_exchange::{TokenExchangeManager, TokenExchangeRequest};
34//! use auth_framework::{SecureJwtValidator, SecureJwtConfig};
35//!
36//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
37//! // Default generates a cryptographically random per-instance secret.
38//! // For stable keys shared across nodes, set `jwt_secret` explicitly.
39//! let jwt_validator = SecureJwtValidator::new(SecureJwtConfig {
40//!     jwt_secret: std::env::var("JWT_SECRET").expect("JWT_SECRET must be set"),
41//!     ..SecureJwtConfig::default()
42//! })?;
43//! let mut manager = TokenExchangeManager::new(jwt_validator);
44//!
45//! let request = TokenExchangeRequest {
46//!     grant_type: "urn:ietf:params:oauth:grant-type:token-exchange".to_string(),
47//!     subject_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...".to_string(),
48//!     subject_token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(),
49//!     requested_token_type: Some("urn:ietf:params:oauth:token-type:access_token".to_string()),
50//!     // ... other fields
51//!     # actor_token: None,
52//!     # actor_token_type: None,
53//!     # audience: None,
54//!     # scope: None,
55//!     # resource: None,
56//! };
57//!
58//! let response = manager.exchange_token(request, "client_123").await?;
59//! # Ok(())
60//! # }
61//! ```
62
63use 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/// Token Exchange Request (RFC 8693)
79#[derive(Clone, Serialize, Deserialize)]
80pub struct TokenExchangeRequest {
81    /// Grant type (must be "urn:ietf:params:oauth:grant-type:token-exchange")
82    pub grant_type: String,
83
84    /// Security token to be exchanged
85    pub subject_token: String,
86
87    /// Type of the subject token
88    pub subject_token_type: String,
89
90    /// Optional actor token (for delegation scenarios)
91    pub actor_token: Option<String>,
92
93    /// Type of the actor token
94    pub actor_token_type: Option<String>,
95
96    /// Type of the requested security token
97    pub requested_token_type: Option<String>,
98
99    /// Intended audience for the requested token
100    pub audience: Option<String>,
101
102    /// Scope of the access token
103    pub scope: Option<String>,
104
105    /// Requested resource for the exchanged token
106    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/// Token Exchange Response (RFC 8693)
132#[derive(Clone, Serialize, Deserialize)]
133pub struct TokenExchangeResponse {
134    /// The security token issued by the authorization server
135    pub access_token: String,
136
137    /// Token type (typically "Bearer")
138    pub token_type: String,
139
140    /// Expires in seconds
141    pub expires_in: Option<i64>,
142
143    /// Refresh token (optional)
144    pub refresh_token: Option<String>,
145
146    /// Scope of the access token
147    pub scope: Option<String>,
148
149    /// Type of the issued token
150    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/// Token types defined in RFC 8693
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174pub enum TokenType {
175    /// JWT access token
176    #[serde(rename = "urn:ietf:params:oauth:token-type:access_token")]
177    AccessToken,
178
179    /// JWT refresh token
180    #[serde(rename = "urn:ietf:params:oauth:token-type:refresh_token")]
181    RefreshToken,
182
183    /// OIDC ID token
184    #[serde(rename = "urn:ietf:params:oauth:token-type:id_token")]
185    IdToken,
186
187    /// SAML 2.0 assertion
188    #[serde(rename = "urn:ietf:params:oauth:token-type:saml2")]
189    Saml2,
190
191    /// SAML 1.1 assertion
192    #[serde(rename = "urn:ietf:params:oauth:token-type:saml1")]
193    Saml1,
194
195    /// JWT token (generic)
196    #[serde(rename = "urn:ietf:params:oauth:token-type:jwt")]
197    Jwt,
198}
199
200/// Token exchange context for validation
201#[derive(Debug, Clone)]
202pub struct TokenExchangeContext {
203    /// Subject token claims
204    pub subject_claims: SecureJwtClaims,
205
206    /// Actor token claims (if present)
207    pub actor_claims: Option<SecureJwtClaims>,
208
209    /// Client identifier
210    pub client_id: String,
211
212    /// Requested audience
213    pub audience: Option<String>,
214
215    /// Requested scope
216    pub scope: Option<Vec<String>>,
217
218    /// Resource parameter
219    pub resource: Option<String>,
220}
221
222/// Token exchange policy
223#[derive(Debug, Clone)]
224pub struct TokenExchangePolicy {
225    /// Allowed subject token types
226    pub allowed_subject_token_types: Vec<TokenType>,
227
228    /// Allowed actor token types
229    pub allowed_actor_token_types: Vec<TokenType>,
230
231    /// Allowed token exchange scenarios
232    pub allowed_scenarios: Vec<ExchangeScenario>,
233
234    /// Maximum token lifetime for exchanged tokens
235    pub max_token_lifetime: Duration,
236
237    /// Whether to require actor tokens for delegation
238    pub require_actor_for_delegation: bool,
239
240    /// Allowed audience values
241    pub allowed_audiences: Vec<String>,
242
243    /// Scope mapping rules
244    pub scope_mapping: HashMap<String, Vec<String>>,
245}
246
247impl TokenExchangePolicy {
248    /// Create a builder for `TokenExchangePolicy` starting from defaults.
249    ///
250    /// # Example
251    /// ```rust
252    /// use auth_framework::server::token_exchange::TokenExchangePolicy;
253    ///
254    /// let policy = TokenExchangePolicy::builder()
255    ///     .max_token_lifetime(chrono::Duration::minutes(30))
256    ///     .require_actor_for_delegation(false)
257    ///     .audience("api.example.com")
258    ///     .build();
259    /// ```
260    pub fn builder() -> TokenExchangePolicyBuilder {
261        TokenExchangePolicyBuilder {
262            inner: Self::default(),
263        }
264    }
265
266    /// Preset: JWT-only token exchange policy.
267    ///
268    /// Only allows JWT and access-token subject types, JWT requested types,
269    /// and delegation/audience-restriction scenarios.
270    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
286/// Builder for [`TokenExchangePolicy`].
287pub struct TokenExchangePolicyBuilder {
288    inner: TokenExchangePolicy,
289}
290
291impl TokenExchangePolicyBuilder {
292    /// Set the allowed subject token types.
293    pub fn subject_token_types(mut self, types: Vec<TokenType>) -> Self {
294        self.inner.allowed_subject_token_types = types;
295        self
296    }
297
298    /// Set the allowed actor token types.
299    pub fn actor_token_types(mut self, types: Vec<TokenType>) -> Self {
300        self.inner.allowed_actor_token_types = types;
301        self
302    }
303
304    /// Set the allowed exchange scenarios.
305    pub fn scenarios(mut self, scenarios: Vec<ExchangeScenario>) -> Self {
306        self.inner.allowed_scenarios = scenarios;
307        self
308    }
309
310    /// Set the maximum token lifetime for exchanged tokens.
311    pub fn max_token_lifetime(mut self, lifetime: Duration) -> Self {
312        self.inner.max_token_lifetime = lifetime;
313        self
314    }
315
316    /// Set whether actor tokens are required for delegation.
317    pub fn require_actor_for_delegation(mut self, required: bool) -> Self {
318        self.inner.require_actor_for_delegation = required;
319        self
320    }
321
322    /// Add a single allowed audience.
323    pub fn audience(mut self, aud: impl Into<String>) -> Self {
324        self.inner.allowed_audiences.push(aud.into());
325        self
326    }
327
328    /// Set all allowed audiences.
329    pub fn audiences(mut self, auds: Vec<String>) -> Self {
330        self.inner.allowed_audiences = auds;
331        self
332    }
333
334    /// Add a scope mapping entry (source scope → allowed target scopes).
335    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    /// Build the [`TokenExchangePolicy`].
341    pub fn build(self) -> TokenExchangePolicy {
342        self.inner
343    }
344}
345
346/// Token exchange scenarios
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub enum ExchangeScenario {
349    /// Acting as the subject (impersonation)
350    ActingAs,
351
352    /// Acting on behalf of the subject (delegation)
353    OnBehalfOf,
354
355    /// Token format conversion
356    TokenConversion,
357
358    /// Audience restriction
359    AudienceRestriction,
360
361    /// Scope reduction
362    ScopeReduction,
363}
364
365/// Token Exchange Manager
366pub struct TokenExchangeManager {
367    /// JWT validator for token validation
368    jwt_validator: SecureJwtValidator,
369
370    /// Token exchange policies
371    policies: tokio::sync::RwLock<HashMap<String, TokenExchangePolicy>>,
372
373    /// Active exchanges for tracking
374    active_exchanges: tokio::sync::RwLock<HashMap<String, TokenExchangeContext>>,
375
376    /// The certificates SAML subject tokens are accepted under, per issuer. Empty means no SAML
377    /// subject token is accepted.
378    #[cfg(feature = "saml")]
379    saml_trust: SamlTrustAnchors,
380}
381
382impl TokenExchangeManager {
383    /// Supported subject token types
384    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    /// Supported requested token types
393    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    /// Create a new token exchange manager
400    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    /// Accept SAML subject tokens issued by `issuer` (the `saml:Issuer` they name) when they are
411    /// signed under `certificate` (PEM `CERTIFICATE` or bare base64 DER). Call again to pin a second
412    /// certificate for a rollover. A SAML subject token from any other issuer, or signed under any
413    /// other key (including one the token carries itself), is refused; with none configured, every
414    /// SAML subject token is.
415    #[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    /// Register a token exchange policy for a client
426    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    /// Process a token exchange request
432    pub async fn exchange_token(
433        &self,
434        request: TokenExchangeRequest,
435        client_id: &str,
436    ) -> Result<TokenExchangeResponse> {
437        // Validate grant type
438        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        // Get client policy
446        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        // Validate and parse subject token
452        let subject_claims = self.validate_subject_token(&request, policy).await?;
453
454        // Validate and parse actor token (if present)
455        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        // Create exchange context
465        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        // Validate exchange scenario
478        let scenario = self.determine_exchange_scenario(&context, policy)?;
479        self.validate_exchange_scenario(&scenario, &context, policy)?;
480
481        // Generate new token
482        let response = self
483            .generate_exchanged_token(&context, &request, policy)
484            .await?;
485
486        // Track the exchange
487        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    /// Validate subject token
495    async fn validate_subject_token(
496        &self,
497        request: &TokenExchangeRequest,
498        policy: &TokenExchangePolicy,
499    ) -> Result<SecureJwtClaims> {
500        // Parse token type
501        let token_type = self.parse_token_type(&request.subject_token_type)?;
502
503        // Check if token type is allowed
504        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        // Validate JWT token (simplified - would need different validation for different types)
512        match token_type {
513            TokenType::AccessToken
514            | TokenType::RefreshToken
515            | TokenType::IdToken
516            | TokenType::Jwt => {
517                // For JWT tokens, validate using JWT validator
518                // In a real implementation, you'd need appropriate decoding keys
519                self.validate_jwt_token(&request.subject_token).await
520            }
521            TokenType::Saml2 | TokenType::Saml1 => {
522                // For SAML tokens, perform basic validation
523                self.validate_saml_token(&request.subject_token, &token_type)
524                    .await
525            }
526        }
527    }
528
529    /// Validate actor token
530    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    /// Validate JWT token using SECURE cryptographic verification
553    async fn validate_jwt_token(&self, token: &str) -> Result<SecureJwtClaims> {
554        // Delegate entirely to SecureJwtValidator::validate which handles
555        // algorithm allow-list enforcement, key selection, and full claims validation.
556        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(&timestamp).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        // The key comes from configuration, every digest is recomputed, and only the signed
687        // assertion is read from here on: the rest of `xml` is attacker-controlled text.
688        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    /// Validate SAML token structure and basic properties
786    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    /// Parse token type from string
804    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    /// Determine exchange scenario based on context
820    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    /// Generate exchanged token
885    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        // Create new claims based on exchange scenario
896        let mut new_claims = context.subject_claims.clone();
897
898        // Update expiration
899        new_claims.exp = exp.timestamp();
900        new_claims.iat = now.timestamp();
901        new_claims.jti = uuid::Uuid::new_v4().to_string();
902
903        // Update audience if specified
904        if let Some(ref audience) = request.audience {
905            new_claims.aud = audience.clone();
906        }
907
908        // Update scope if specified and apply mapping
909        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        // Add actor information for delegation
918        if let Some(ref actor_claims) = context.actor_claims {
919            new_claims.client_id = Some(actor_claims.sub.clone());
920        }
921
922        // Generate a proper HMAC-signed JWT from the exchange claims
923        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        // Determine issued token type
931        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, // Could generate refresh token in some scenarios
941            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(), // Empty means all audiences allowed
965            scope_mapping: HashMap::new(),
966        }
967    }
968}
969
970/// Implementation of the common TokenExchangeService trait
971#[async_trait]
972impl TokenExchangeService for TokenExchangeManager {
973    type Request = (TokenExchangeRequest, String); // Request + client_id
974    type Response = TokenExchangeResponse;
975    type Config = SecureJwtValidator; // Configuration is the JWT validator
976
977    /// Exchange a token following RFC 8693 (basic implementation)
978    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    /// Validate a token using the internal JWT validator
984    async fn validate_token(&self, token: &str, token_type: &str) -> Result<TokenValidationResult> {
985        // Use shared validation utilities
986        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                // Use the secure validate path which handles algorithm checking
992                // and key selection internally — no caller-supplied key needed.
993                match self.jwt_validator.validate(token) {
994                    Ok(claims) => {
995                        // Convert timestamp to DateTime
996                        use chrono::{TimeZone, Utc};
997                        let expires_at = Utc.timestamp_opt(claims.exp, 0).single();
998
999                        // Convert audience string to vector
1000                        let audience = if claims.aud.is_empty() {
1001                            Vec::new()
1002                        } else {
1003                            vec![claims.aud.clone()]
1004                        };
1005
1006                        // Extract scopes from scope string
1007                        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                        // Create metadata from available claims
1018                        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    /// Get supported subject token types
1153    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    /// Get supported requested token types
1161    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    /// Get service capabilities
1169    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        // Register a policy
1215        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        // Test audience restriction scenario
1248        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        // Builder starts from default so subject types are populated
1306        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}