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").into(),
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    /// Where revoked token ids are looked up (`revoked_token:{jti}`). Without one,
377    /// revocation is not consulted.
378    revocation_store: Option<std::sync::Arc<dyn crate::storage::AuthStorage>>,
379
380    /// The certificates SAML subject tokens are accepted under, per issuer. Empty means no SAML
381    /// subject token is accepted.
382    #[cfg(feature = "saml")]
383    saml_trust: SamlTrustAnchors,
384}
385
386impl TokenExchangeManager {
387    /// Supported subject token types
388    const SUBJECT_TOKEN_TYPES: &'static [&'static str] = &[
389        "urn:ietf:params:oauth:token-type:jwt",
390        "urn:ietf:params:oauth:token-type:access_token",
391        "urn:ietf:params:oauth:token-type:id_token",
392        "urn:ietf:params:oauth:token-type:saml1",
393        "urn:ietf:params:oauth:token-type:saml2",
394    ];
395
396    /// Supported requested token types
397    const REQUESTED_TOKEN_TYPES: &'static [&'static str] = &[
398        "urn:ietf:params:oauth:token-type:jwt",
399        "urn:ietf:params:oauth:token-type:access_token",
400        "urn:ietf:params:oauth:token-type:refresh_token",
401    ];
402
403    /// Create a new token exchange manager
404    pub fn new(jwt_validator: SecureJwtValidator) -> Self {
405        Self {
406            jwt_validator,
407            policies: tokio::sync::RwLock::new(HashMap::new()),
408            active_exchanges: tokio::sync::RwLock::new(HashMap::new()),
409            revocation_store: None,
410            #[cfg(feature = "saml")]
411            saml_trust: SamlTrustAnchors::new(),
412        }
413    }
414
415    /// Accept SAML subject tokens issued by `issuer` (the `saml:Issuer` they name) when they are
416    /// signed under `certificate` (PEM `CERTIFICATE` or bare base64 DER). Call again to pin a second
417    /// certificate for a rollover. A SAML subject token from any other issuer, or signed under any
418    /// other key (including one the token carries itself), is refused; with none configured, every
419    /// SAML subject token is.
420    #[cfg(feature = "saml")]
421    pub fn with_trusted_saml_issuer(
422        mut self,
423        issuer: impl Into<String>,
424        certificate: &str,
425    ) -> Result<Self> {
426        self.saml_trust.trust_pem(issuer, certificate)?;
427        Ok(self)
428    }
429
430    /// Consult the framework's revocation list (written by logout and revocation) so that
431    /// revoked tokens cannot be presented as subject or actor tokens. An unreadable list
432    /// rejects the token.
433    pub fn with_revocation_store(
434        mut self,
435        store: std::sync::Arc<dyn crate::storage::AuthStorage>,
436    ) -> Self {
437        self.revocation_store = Some(store);
438        self
439    }
440
441    /// Register a token exchange policy for a client
442    pub async fn register_policy(&self, client_id: String, policy: TokenExchangePolicy) {
443        let mut policies = self.policies.write().await;
444        policies.insert(client_id, policy);
445    }
446
447    /// Process a token exchange request
448    pub async fn exchange_token(
449        &self,
450        request: TokenExchangeRequest,
451        client_id: &str,
452    ) -> Result<TokenExchangeResponse> {
453        // Validate grant type
454        if request.grant_type != "urn:ietf:params:oauth:grant-type:token-exchange" {
455            return Err(AuthError::auth_method(
456                "token_exchange",
457                "Invalid grant type for token exchange",
458            ));
459        }
460
461        // Get client policy
462        let policies = self.policies.read().await;
463        let policy = policies.get(client_id).ok_or_else(|| {
464            AuthError::auth_method("token_exchange", "No token exchange policy for client")
465        })?;
466
467        // Validate and parse subject token
468        let subject_claims = self.validate_subject_token(&request, policy).await?;
469
470        // Validate and parse actor token (if present)
471        let actor_claims = if let Some(ref actor_token) = request.actor_token {
472            Some(
473                self.validate_actor_token(actor_token, &request.actor_token_type, policy)
474                    .await?,
475            )
476        } else {
477            None
478        };
479
480        // Create exchange context
481        let context = TokenExchangeContext {
482            subject_claims,
483            actor_claims,
484            client_id: client_id.to_string(),
485            audience: request.audience.clone(),
486            scope: request
487                .scope
488                .as_ref()
489                .map(|s| s.split(' ').map(String::from).collect()),
490            resource: request.resource.clone(),
491        };
492
493        // Validate exchange scenario
494        let scenario = self.determine_exchange_scenario(&context, policy)?;
495        self.validate_exchange_scenario(&scenario, &context, policy)?;
496
497        // Generate new token
498        let response = self
499            .generate_exchanged_token(&context, &request, policy)
500            .await?;
501
502        // Track the exchange
503        let exchange_id = uuid::Uuid::new_v4().to_string();
504        let mut exchanges = self.active_exchanges.write().await;
505        exchanges.insert(exchange_id, context);
506
507        Ok(response)
508    }
509
510    /// Validate subject token
511    async fn validate_subject_token(
512        &self,
513        request: &TokenExchangeRequest,
514        policy: &TokenExchangePolicy,
515    ) -> Result<SecureJwtClaims> {
516        // Parse token type
517        let token_type = self.parse_token_type(&request.subject_token_type)?;
518
519        // Check if token type is allowed
520        if !policy.allowed_subject_token_types.contains(&token_type) {
521            return Err(AuthError::auth_method(
522                "token_exchange",
523                "Subject token type not allowed",
524            ));
525        }
526
527        // Validate JWT token (simplified - would need different validation for different types)
528        match token_type {
529            TokenType::AccessToken
530            | TokenType::RefreshToken
531            | TokenType::IdToken
532            | TokenType::Jwt => {
533                // For JWT tokens, validate using JWT validator
534                // In a real implementation, you'd need appropriate decoding keys.
535                // Only a subject token declared as a refresh token may be one.
536                self.validate_jwt_token(
537                    &request.subject_token,
538                    token_type == TokenType::RefreshToken,
539                )
540                .await
541            }
542            TokenType::Saml2 | TokenType::Saml1 => {
543                // For SAML tokens, perform basic validation
544                self.validate_saml_token(&request.subject_token, &token_type)
545                    .await
546            }
547        }
548    }
549
550    /// Validate actor token
551    async fn validate_actor_token(
552        &self,
553        actor_token: &str,
554        actor_token_type: &Option<String>,
555        policy: &TokenExchangePolicy,
556    ) -> Result<SecureJwtClaims> {
557        let token_type_str = actor_token_type
558            .as_ref()
559            .ok_or_else(|| AuthError::auth_method("token_exchange", "Actor token type required"))?;
560
561        let token_type = self.parse_token_type(token_type_str)?;
562
563        if !policy.allowed_actor_token_types.contains(&token_type) {
564            return Err(AuthError::auth_method(
565                "token_exchange",
566                "Actor token type not allowed",
567            ));
568        }
569
570        self.validate_jwt_token(actor_token, false).await
571    }
572
573    /// Validate JWT token using SECURE cryptographic verification
574    async fn validate_jwt_token(
575        &self,
576        token: &str,
577        allow_refresh: bool,
578    ) -> Result<SecureJwtClaims> {
579        // Delegate to SecureJwtValidator::validate which handles algorithm allow-list
580        // enforcement, key selection, and full claims validation.
581        let claims = self.jwt_validator.validate(token).map_err(|e| {
582            AuthError::auth_method("token_exchange", format!("JWT validation failed: {}", e))
583        })?;
584
585        // A refresh token is only acceptable where a refresh token was declared.
586        if !allow_refresh && crate::security::secure_jwt::is_refresh_typ(&claims.typ) {
587            return Err(AuthError::auth_method(
588                "token_exchange",
589                "A refresh token cannot be used here",
590            ));
591        }
592
593        // Revoked tokens (logout / revocation) are refused; an unreadable list fails closed.
594        if let Some(store) = &self.revocation_store {
595            match store.get_kv(&format!("revoked_token:{}", claims.jti)).await {
596                Ok(None) => {}
597                Ok(Some(_)) => {
598                    return Err(AuthError::auth_method(
599                        "token_exchange",
600                        "The token has been revoked",
601                    ));
602                }
603                Err(e) => {
604                    tracing::error!("Could not check token revocation list: {}", e);
605                    return Err(AuthError::auth_method(
606                        "token_exchange",
607                        "Unable to verify token status",
608                    ));
609                }
610            }
611        }
612        Ok(claims)
613    }
614
615    fn extract_saml_xml(&self, token: &str) -> Result<String> {
616        if token.trim().is_empty() {
617            return Err(AuthError::auth_method(
618                "token_exchange",
619                "Empty SAML token provided",
620            ));
621        }
622
623        let decoded = if token.trim_start().starts_with('<') {
624            token.to_string()
625        } else {
626            String::from_utf8(
627                base64::engine::general_purpose::STANDARD
628                    .decode(token)
629                    .map_err(|e| {
630                        AuthError::auth_method(
631                            "token_exchange",
632                            format!("Invalid base64-encoded SAML token: {}", e),
633                        )
634                    })?,
635            )
636            .map_err(|e| {
637                AuthError::auth_method(
638                    "token_exchange",
639                    format!("Invalid UTF-8 in SAML token: {}", e),
640                )
641            })?
642        };
643
644        let has_saml_markers = decoded.contains("<saml:")
645            || decoded.contains("<saml2:")
646            || decoded.contains("<Assertion")
647            || decoded.contains("<Response")
648            || decoded.contains("urn:oasis:names:tc:SAML");
649
650        if !has_saml_markers {
651            return Err(AuthError::auth_method(
652                "token_exchange",
653                "Invalid SAML token format - missing SAML namespace markers",
654            ));
655        }
656
657        Ok(decoded)
658    }
659
660    #[cfg(feature = "saml")]
661    fn extract_xml_text(&self, xml: &str, local_name: &str) -> Option<String> {
662        let patterns = [
663            format!("<{local_name}>"),
664            format!("<saml:{local_name}>"),
665            format!("<saml2:{local_name}>"),
666            format!("<{local_name} "),
667            format!("<saml:{local_name} "),
668            format!("<saml2:{local_name} "),
669        ];
670
671        for pattern in patterns {
672            if let Some(start) = xml.find(&pattern) {
673                let content_start = xml[start..].find('>').map(|index| start + index + 1)?;
674                let end_patterns = [
675                    format!("</{local_name}>"),
676                    format!("</saml:{local_name}>"),
677                    format!("</saml2:{local_name}>"),
678                ];
679
680                for end_pattern in end_patterns {
681                    if let Some(relative_end) = xml[content_start..].find(&end_pattern) {
682                        return Some(
683                            xml[content_start..content_start + relative_end]
684                                .trim()
685                                .to_string(),
686                        );
687                    }
688                }
689            }
690        }
691
692        None
693    }
694
695    #[cfg(feature = "saml")]
696    fn extract_xml_attribute(&self, xml: &str, attribute_name: &str) -> Option<String> {
697        for pattern in [
698            format!("{attribute_name}=\""),
699            format!("{attribute_name}='"),
700        ] {
701            if let Some(start) = xml.find(&pattern) {
702                let value_start = start + pattern.len();
703                if let Some(relative_end) = xml[value_start..].find(['"', '\'']) {
704                    return Some(xml[value_start..value_start + relative_end].to_string());
705                }
706            }
707        }
708
709        None
710    }
711
712    #[cfg(feature = "saml")]
713    fn parse_saml_timestamp(&self, timestamp: &str) -> Result<i64> {
714        chrono::DateTime::parse_from_rfc3339(timestamp)
715            .or_else(|_| chrono::DateTime::parse_from_str(timestamp, "%Y-%m-%dT%H:%M:%S%.fZ"))
716            .or_else(|_| chrono::DateTime::parse_from_str(timestamp, "%Y-%m-%dT%H:%M:%SZ"))
717            .map(|dt| dt.timestamp())
718            .map_err(|_| {
719                AuthError::auth_method(
720                    "token_exchange",
721                    format!("Invalid SAML timestamp: {}", timestamp),
722                )
723            })
724    }
725
726    #[cfg(feature = "saml")]
727    fn extract_saml_timestamp(&self, xml: &str, attribute_name: &str) -> Result<Option<i64>> {
728        match self.extract_xml_attribute(xml, attribute_name) {
729            Some(timestamp) => self.parse_saml_timestamp(&timestamp).map(Some),
730            None => Ok(None),
731        }
732    }
733
734    #[cfg(feature = "saml")]
735    fn validate_saml_assertion_xml(
736        &self,
737        xml: &str,
738        token_type: &TokenType,
739    ) -> Result<SecureJwtClaims> {
740        // The key comes from configuration, every digest is recomputed, and only the signed
741        // assertion is read from here on: the rest of `xml` is attacker-controlled text.
742        let verified = verify_signed_assertion(xml, &self.saml_trust).map_err(|e| {
743            AuthError::auth_method(
744                "token_exchange",
745                format!("SAML signature validation failed: {}", e),
746            )
747        })?;
748        let xml = verified.assertion_xml.as_str();
749
750        let subject = self.extract_xml_text(xml, "NameID").ok_or_else(|| {
751            AuthError::auth_method("token_exchange", "SAML assertion is missing NameID")
752        })?;
753        let issuer = verified.issuer.clone();
754        let audience = self.extract_xml_text(xml, "Audience");
755        let issue_instant = self.extract_saml_timestamp(xml, "IssueInstant")?;
756        let not_before = self.extract_saml_timestamp(xml, "NotBefore")?;
757        let not_on_or_after = self.extract_saml_timestamp(xml, "NotOnOrAfter")?;
758        let session_id = self.extract_xml_attribute(xml, "SessionIndex");
759
760        let now = chrono::Utc::now().timestamp();
761        if let Some(value) = issue_instant {
762            if value > now + 30 {
763                return Err(AuthError::auth_method(
764                    "token_exchange",
765                    "SAML assertion issue instant is in the future",
766                ));
767            }
768            if now - value > 300 {
769                return Err(AuthError::auth_method(
770                    "token_exchange",
771                    "SAML assertion is too old",
772                ));
773            }
774        }
775        if let Some(value) = not_before
776            && now < value
777        {
778            return Err(AuthError::auth_method(
779                "token_exchange",
780                "SAML assertion is not yet valid",
781            ));
782        }
783        if let Some(value) = not_on_or_after
784            && now >= value
785        {
786            return Err(AuthError::auth_method(
787                "token_exchange",
788                "SAML assertion has expired",
789            ));
790        }
791
792        let mut scopes = Vec::new();
793        if xml.contains("emailaddress") {
794            scopes.push("email".to_string());
795        }
796        if xml.contains("identity/claims/name") || xml.contains("givenname") {
797            scopes.push("profile".to_string());
798        }
799        if xml.contains("claims/groups") || xml.contains("role") || xml.contains("Role") {
800            scopes.push("groups".to_string());
801        }
802        if scopes.is_empty() {
803            scopes.push("saml_authenticated".to_string());
804        }
805
806        Ok(SecureJwtClaims {
807            iss: issuer,
808            sub: subject,
809            aud: audience.unwrap_or_else(|| "target_audience".to_string()),
810            exp: not_on_or_after.unwrap_or(now + 3600),
811            nbf: not_before.unwrap_or(now),
812            iat: issue_instant.unwrap_or(now),
813            jti: format!("saml_token_{}", uuid::Uuid::new_v4()),
814            scope: scopes.join(" "),
815            typ: match token_type {
816                TokenType::Saml2 => "urn:ietf:params:oauth:token-type:saml2",
817                TokenType::Saml1 => "urn:ietf:params:oauth:token-type:saml1",
818                _ => "urn:ietf:params:oauth:token-type:saml2",
819            }
820            .to_string(),
821            sid: session_id,
822            client_id: None,
823            auth_ctx_hash: Some(format!("saml_ctx_{}", uuid::Uuid::new_v4())),
824        })
825    }
826
827    #[cfg(not(feature = "saml"))]
828    fn validate_saml_assertion_xml(
829        &self,
830        _xml: &str,
831        _token_type: &TokenType,
832    ) -> Result<SecureJwtClaims> {
833        Err(AuthError::auth_method(
834            "token_exchange",
835            "SAML validation requires the 'saml' feature to be enabled",
836        ))
837    }
838
839    /// Validate SAML token structure and basic properties
840    async fn validate_saml_token(
841        &self,
842        token: &str,
843        token_type: &TokenType,
844    ) -> Result<SecureJwtClaims> {
845        let xml = self.extract_saml_xml(token)?;
846        let claims = self.validate_saml_assertion_xml(&xml, token_type)?;
847
848        tracing::info!(
849            "SAML token validation completed - parsed subject: {}, issuer: {}, scopes: {}",
850            claims.sub,
851            claims.iss,
852            claims.scope
853        );
854        Ok(claims)
855    }
856
857    /// Parse token type from string
858    fn parse_token_type(&self, token_type: &str) -> Result<TokenType> {
859        match token_type {
860            "urn:ietf:params:oauth:token-type:access_token" => Ok(TokenType::AccessToken),
861            "urn:ietf:params:oauth:token-type:refresh_token" => Ok(TokenType::RefreshToken),
862            "urn:ietf:params:oauth:token-type:id_token" => Ok(TokenType::IdToken),
863            "urn:ietf:params:oauth:token-type:saml2" => Ok(TokenType::Saml2),
864            "urn:ietf:params:oauth:token-type:saml1" => Ok(TokenType::Saml1),
865            "urn:ietf:params:oauth:token-type:jwt" => Ok(TokenType::Jwt),
866            _ => Err(AuthError::auth_method(
867                "token_exchange",
868                "Unknown token type",
869            )),
870        }
871    }
872
873    /// Determine exchange scenario based on context
874    fn determine_exchange_scenario(
875        &self,
876        context: &TokenExchangeContext,
877        _policy: &TokenExchangePolicy,
878    ) -> Result<ExchangeScenario> {
879        if context.actor_claims.is_some() {
880            return Ok(ExchangeScenario::OnBehalfOf);
881        }
882
883        if let Some(audience) = context.audience.as_ref()
884            && audience != &context.subject_claims.aud
885        {
886            return Ok(ExchangeScenario::AudienceRestriction);
887        }
888
889        if let Some(requested_scope) = &context.scope {
890            let current_scope: Vec<&str> = context.subject_claims.scope.split(' ').collect();
891            if requested_scope.len() < current_scope.len() {
892                return Ok(ExchangeScenario::ScopeReduction);
893            }
894        }
895
896        Ok(ExchangeScenario::ActingAs)
897    }
898
899    fn validate_exchange_scenario(
900        &self,
901        scenario: &ExchangeScenario,
902        context: &TokenExchangeContext,
903        policy: &TokenExchangePolicy,
904    ) -> Result<()> {
905        if !policy.allowed_scenarios.is_empty() && !policy.allowed_scenarios.contains(scenario) {
906            return Err(AuthError::auth_method(
907                "token_exchange",
908                "Exchange scenario is not permitted by policy",
909            ));
910        }
911
912        match scenario {
913            ExchangeScenario::OnBehalfOf => {
914                if policy.require_actor_for_delegation && context.actor_claims.is_none() {
915                    return Err(AuthError::auth_method(
916                        "token_exchange",
917                        "Actor token required for delegation",
918                    ));
919                }
920            }
921            ExchangeScenario::AudienceRestriction => {
922                if let Some(audience) = context.audience.as_ref()
923                    && !policy.allowed_audiences.is_empty()
924                    && !policy.allowed_audiences.contains(audience)
925                {
926                    return Err(AuthError::auth_method(
927                        "token_exchange",
928                        "Audience not allowed",
929                    ));
930                }
931            }
932            _ => {}
933        }
934
935        Ok(())
936    }
937
938    /// Generate exchanged token
939    async fn generate_exchanged_token(
940        &self,
941        context: &TokenExchangeContext,
942        request: &TokenExchangeRequest,
943        policy: &TokenExchangePolicy,
944    ) -> Result<TokenExchangeResponse> {
945        let now = Utc::now();
946        let expires_in = policy.max_token_lifetime.num_seconds();
947        let exp = now + policy.max_token_lifetime;
948
949        // Create new claims based on exchange scenario
950        let mut new_claims = context.subject_claims.clone();
951
952        // Update expiration
953        new_claims.exp = exp.timestamp();
954        new_claims.iat = now.timestamp();
955        new_claims.jti = uuid::Uuid::new_v4().to_string();
956
957        // Update audience if specified
958        if let Some(ref audience) = request.audience {
959            new_claims.aud = audience.clone();
960        }
961
962        // Update scope if specified and apply mapping
963        if let Some(ref requested_scope) = request.scope {
964            if let Some(mapped_scopes) = policy.scope_mapping.get(requested_scope) {
965                new_claims.scope = mapped_scopes.join(" ");
966            } else {
967                new_claims.scope = requested_scope.clone();
968            }
969        }
970
971        // Add actor information for delegation
972        if let Some(ref actor_claims) = context.actor_claims {
973            new_claims.client_id = Some(actor_claims.sub.clone());
974        }
975
976        // Generate a proper HMAC-signed JWT from the exchange claims
977        let access_token = encode(
978            &Header::new(Algorithm::HS256),
979            &new_claims,
980            &self.jwt_validator.get_encoding_key(),
981        )
982        .map_err(|e| AuthError::internal(format!("Failed to sign exchanged token: {}", e)))?;
983
984        // Determine issued token type
985        let issued_token_type = request
986            .requested_token_type
987            .clone()
988            .unwrap_or_else(|| "urn:ietf:params:oauth:token-type:access_token".to_string());
989
990        Ok(TokenExchangeResponse {
991            access_token,
992            token_type: "Bearer".to_string(),
993            expires_in: Some(expires_in),
994            refresh_token: None, // Could generate refresh token in some scenarios
995            scope: Some(new_claims.scope),
996            issued_token_type: Some(issued_token_type),
997        })
998    }
999}
1000
1001impl Default for TokenExchangePolicy {
1002    fn default() -> Self {
1003        Self {
1004            allowed_subject_token_types: vec![
1005                TokenType::AccessToken,
1006                TokenType::RefreshToken,
1007                TokenType::IdToken,
1008            ],
1009            allowed_actor_token_types: vec![TokenType::AccessToken, TokenType::IdToken],
1010            allowed_scenarios: vec![
1011                ExchangeScenario::ActingAs,
1012                ExchangeScenario::OnBehalfOf,
1013                ExchangeScenario::AudienceRestriction,
1014                ExchangeScenario::ScopeReduction,
1015            ],
1016            max_token_lifetime: Duration::hours(1),
1017            require_actor_for_delegation: true,
1018            allowed_audiences: Vec::new(), // Empty means all audiences allowed
1019            scope_mapping: HashMap::new(),
1020        }
1021    }
1022}
1023
1024/// Implementation of the common TokenExchangeService trait
1025#[async_trait]
1026impl TokenExchangeService for TokenExchangeManager {
1027    type Request = (TokenExchangeRequest, String); // Request + client_id
1028    type Response = TokenExchangeResponse;
1029    type Config = SecureJwtValidator; // Configuration is the JWT validator
1030
1031    /// Exchange a token following RFC 8693 (basic implementation)
1032    async fn exchange_token(&self, request: Self::Request) -> Result<Self::Response> {
1033        let (token_request, client_id) = request;
1034        self.exchange_token(token_request, &client_id).await
1035    }
1036
1037    /// Validate a token using the internal JWT validator
1038    async fn validate_token(&self, token: &str, token_type: &str) -> Result<TokenValidationResult> {
1039        // Use shared validation utilities
1040        let supported_types = self.supported_subject_token_types();
1041        ValidationUtils::validate_token_type(token_type, &supported_types)?;
1042
1043        match self.parse_token_type(token_type)? {
1044            TokenType::Jwt | TokenType::AccessToken | TokenType::IdToken => {
1045                // Use the secure validate path which handles algorithm checking
1046                // and key selection internally — no caller-supplied key needed.
1047                match self.jwt_validator.validate(token) {
1048                    Ok(claims) => {
1049                        // Convert timestamp to DateTime
1050                        use chrono::{TimeZone, Utc};
1051                        let expires_at = Utc.timestamp_opt(claims.exp, 0).single();
1052
1053                        // Convert audience string to vector
1054                        let audience = if claims.aud.is_empty() {
1055                            Vec::new()
1056                        } else {
1057                            vec![claims.aud.clone()]
1058                        };
1059
1060                        // Extract scopes from scope string
1061                        let scopes = if claims.scope.is_empty() {
1062                            Vec::new()
1063                        } else {
1064                            claims
1065                                .scope
1066                                .split_whitespace()
1067                                .map(|s| s.to_string())
1068                                .collect()
1069                        };
1070
1071                        // Create metadata from available claims
1072                        let mut metadata = HashMap::new();
1073                        metadata.insert(
1074                            "sub".to_string(),
1075                            serde_json::Value::String(claims.sub.clone()),
1076                        );
1077                        metadata.insert(
1078                            "iss".to_string(),
1079                            serde_json::Value::String(claims.iss.clone()),
1080                        );
1081                        metadata.insert(
1082                            "aud".to_string(),
1083                            serde_json::Value::String(claims.aud.clone()),
1084                        );
1085                        metadata.insert(
1086                            "scope".to_string(),
1087                            serde_json::Value::String(claims.scope.clone()),
1088                        );
1089                        metadata.insert(
1090                            "typ".to_string(),
1091                            serde_json::Value::String(claims.typ.clone()),
1092                        );
1093                        if let Some(ref sid) = claims.sid {
1094                            metadata
1095                                .insert("sid".to_string(), serde_json::Value::String(sid.clone()));
1096                        }
1097                        if let Some(ref client_id) = claims.client_id {
1098                            metadata.insert(
1099                                "client_id".to_string(),
1100                                serde_json::Value::String(client_id.clone()),
1101                            );
1102                        }
1103
1104                        Ok(TokenValidationResult {
1105                            is_valid: true,
1106                            subject: Some(claims.sub),
1107                            issuer: Some(claims.iss),
1108                            audience,
1109                            scopes,
1110                            expires_at,
1111                            metadata,
1112                            validation_messages: Vec::new(),
1113                        })
1114                    }
1115                    Err(e) => Ok(TokenValidationResult {
1116                        is_valid: false,
1117                        subject: None,
1118                        issuer: None,
1119                        audience: Vec::new(),
1120                        scopes: Vec::new(),
1121                        expires_at: None,
1122                        metadata: HashMap::new(),
1123                        validation_messages: vec![format!("JWT validation failed: {}", e)],
1124                    }),
1125                }
1126            }
1127            TokenType::Saml2 | TokenType::Saml1 => {
1128                match self
1129                    .validate_saml_token(token, &self.parse_token_type(token_type)?)
1130                    .await
1131                {
1132                    Ok(claims) => {
1133                        use chrono::{TimeZone, Utc};
1134                        let expires_at = Utc.timestamp_opt(claims.exp, 0).single();
1135                        let audience = if claims.aud.is_empty() {
1136                            Vec::new()
1137                        } else {
1138                            vec![claims.aud.clone()]
1139                        };
1140                        let scopes = if claims.scope.is_empty() {
1141                            Vec::new()
1142                        } else {
1143                            claims
1144                                .scope
1145                                .split_whitespace()
1146                                .map(|scope| scope.to_string())
1147                                .collect()
1148                        };
1149
1150                        let mut metadata = HashMap::new();
1151                        metadata.insert(
1152                            "sub".to_string(),
1153                            serde_json::Value::String(claims.sub.clone()),
1154                        );
1155                        metadata.insert(
1156                            "iss".to_string(),
1157                            serde_json::Value::String(claims.iss.clone()),
1158                        );
1159                        metadata.insert(
1160                            "aud".to_string(),
1161                            serde_json::Value::String(claims.aud.clone()),
1162                        );
1163                        metadata.insert(
1164                            "scope".to_string(),
1165                            serde_json::Value::String(claims.scope.clone()),
1166                        );
1167                        metadata.insert(
1168                            "typ".to_string(),
1169                            serde_json::Value::String(claims.typ.clone()),
1170                        );
1171                        if let Some(ref sid) = claims.sid {
1172                            metadata
1173                                .insert("sid".to_string(), serde_json::Value::String(sid.clone()));
1174                        }
1175
1176                        Ok(TokenValidationResult {
1177                            is_valid: true,
1178                            subject: Some(claims.sub),
1179                            issuer: Some(claims.iss),
1180                            audience,
1181                            scopes,
1182                            expires_at,
1183                            metadata,
1184                            validation_messages: Vec::new(),
1185                        })
1186                    }
1187                    Err(error) => Ok(TokenValidationResult {
1188                        is_valid: false,
1189                        subject: None,
1190                        issuer: None,
1191                        audience: Vec::new(),
1192                        scopes: Vec::new(),
1193                        expires_at: None,
1194                        metadata: HashMap::new(),
1195                        validation_messages: vec![error.to_string()],
1196                    }),
1197                }
1198            }
1199            _ => Err(AuthError::InvalidRequest(format!(
1200                "Token validation not supported for type: {}",
1201                token_type
1202            ))),
1203        }
1204    }
1205
1206    /// Get supported subject token types
1207    fn supported_subject_token_types(&self) -> Vec<String> {
1208        Self::SUBJECT_TOKEN_TYPES
1209            .iter()
1210            .map(|s| s.to_string())
1211            .collect()
1212    }
1213
1214    /// Get supported requested token types
1215    fn supported_requested_token_types(&self) -> Vec<String> {
1216        Self::REQUESTED_TOKEN_TYPES
1217            .iter()
1218            .map(|s| s.to_string())
1219            .collect()
1220    }
1221
1222    /// Get service capabilities
1223    fn capabilities(&self) -> TokenExchangeCapabilities {
1224        TokenExchangeCapabilities {
1225            basic_exchange: true,
1226            multi_party_chains: false,
1227            context_preservation: false,
1228            audit_trail: false,
1229            session_integration: false,
1230            jwt_operations: false,
1231            policy_control: true,
1232            cross_domain_exchange: false,
1233            max_delegation_depth: 3,
1234            complexity_level: ServiceComplexityLevel::Basic,
1235        }
1236    }
1237}
1238
1239#[cfg(test)]
1240mod tests {
1241    use super::*;
1242    use crate::security::secure_jwt::SecureJwtConfig;
1243    use crate::storage::AuthStorage as _;
1244
1245    fn create_test_manager() -> TokenExchangeManager {
1246        let jwt_config = SecureJwtConfig::default();
1247        let jwt_validator = SecureJwtValidator::new(jwt_config).expect("test JWT config");
1248        TokenExchangeManager::new(jwt_validator)
1249    }
1250
1251    fn create_test_request() -> TokenExchangeRequest {
1252        TokenExchangeRequest {
1253            grant_type: "urn:ietf:params:oauth:grant-type:token-exchange".to_string(),
1254            subject_token: "dummy.jwt.token".to_string(),
1255            subject_token_type: "urn:ietf:params:oauth:token-type:access_token".to_string(),
1256            actor_token: None,
1257            actor_token_type: None,
1258            requested_token_type: Some("urn:ietf:params:oauth:token-type:access_token".to_string()),
1259            audience: Some("api.example.com".to_string()),
1260            scope: Some("read write".to_string()),
1261            resource: None,
1262        }
1263    }
1264
1265    /// A manager sharing a revocation list, plus a signer for tokens it will accept.
1266    fn manager_with_store() -> (
1267        TokenExchangeManager,
1268        std::sync::Arc<crate::storage::MemoryStorage>,
1269        impl Fn(&str, &str) -> String,
1270    ) {
1271        let config = SecureJwtConfig::default();
1272        let secret = config.jwt_secret.to_string();
1273        let validator = SecureJwtValidator::new(config).expect("test JWT config");
1274        let store = std::sync::Arc::new(crate::storage::MemoryStorage::new());
1275        let manager = TokenExchangeManager::new(validator).with_revocation_store(store.clone());
1276        let sign = move |jti: &str, typ: &str| {
1277            let now = chrono::Utc::now().timestamp();
1278            let claims = SecureJwtClaims {
1279                sub: "user123".to_string(),
1280                iss: "auth-framework".to_string(),
1281                aud: "api.example.com".to_string(),
1282                exp: now + 600,
1283                nbf: now - 5,
1284                iat: now,
1285                jti: jti.to_string(),
1286                scope: "read".to_string(),
1287                typ: typ.to_string(),
1288                sid: None,
1289                client_id: None,
1290                auth_ctx_hash: None,
1291            };
1292            encode(
1293                &Header::new(Algorithm::HS256),
1294                &claims,
1295                &jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()),
1296            )
1297            .unwrap()
1298        };
1299        (manager, store, sign)
1300    }
1301
1302    #[tokio::test]
1303    async fn a_revoked_token_cannot_be_exchanged() {
1304        let (manager, store, sign) = manager_with_store();
1305        let live = sign("jti-live", "access");
1306        assert!(manager.validate_jwt_token(&live, false).await.is_ok());
1307
1308        let dead = sign("jti-dead", "access");
1309        store
1310            .store_kv("revoked_token:jti-dead", b"revoked", None)
1311            .await
1312            .unwrap();
1313        assert!(manager.validate_jwt_token(&dead, false).await.is_err());
1314        assert!(manager.validate_jwt_token(&dead, true).await.is_err());
1315    }
1316
1317    #[tokio::test]
1318    async fn a_refresh_token_is_only_accepted_where_one_was_declared() {
1319        let (manager, _store, sign) = manager_with_store();
1320        let refresh = sign("jti-r", "refresh");
1321        assert!(manager.validate_jwt_token(&refresh, false).await.is_err());
1322        assert!(manager.validate_jwt_token(&refresh, true).await.is_ok());
1323    }
1324
1325    /// Both spellings the crate mints ("refresh" for exchange/CIBA, "refresh_token" for FAPI)
1326    /// are refresh tokens. The validator is configured to ADMIT the second spelling so the
1327    /// rule itself, not an allow-list rejection, is what is being tested.
1328    #[tokio::test]
1329    async fn every_refresh_spelling_is_a_refresh_token() {
1330        let mut config = SecureJwtConfig::default();
1331        config
1332            .allowed_token_types
1333            .insert("refresh_token".to_string());
1334        let secret = config.jwt_secret.to_string();
1335        let manager = TokenExchangeManager::new(SecureJwtValidator::new(config).unwrap());
1336        let sign = |typ: &str| {
1337            let now = chrono::Utc::now().timestamp();
1338            let claims = SecureJwtClaims {
1339                sub: "user123".to_string(),
1340                iss: "auth-framework".to_string(),
1341                aud: "api.example.com".to_string(),
1342                exp: now + 600,
1343                nbf: now - 5,
1344                iat: now,
1345                jti: format!("jti-{typ}"),
1346                scope: "read".to_string(),
1347                typ: typ.to_string(),
1348                sid: None,
1349                client_id: None,
1350                auth_ctx_hash: None,
1351            };
1352            encode(
1353                &Header::new(Algorithm::HS256),
1354                &claims,
1355                &jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()),
1356            )
1357            .unwrap()
1358        };
1359        for typ in ["refresh", "refresh_token"] {
1360            let token = sign(typ);
1361            assert!(
1362                manager.validate_jwt_token(&token, false).await.is_err(),
1363                "{typ} must be refused where a refresh token was not declared"
1364            );
1365            assert!(
1366                manager.validate_jwt_token(&token, true).await.is_ok(),
1367                "{typ} is acceptable where a refresh token was declared"
1368            );
1369        }
1370        // an access token is unaffected
1371        assert!(
1372            manager
1373                .validate_jwt_token(&sign("access"), false)
1374                .await
1375                .is_ok()
1376        );
1377    }
1378
1379    #[tokio::test]
1380    async fn test_token_exchange_manager_creation() {
1381        let manager = create_test_manager();
1382
1383        // Register a policy
1384        let policy = TokenExchangePolicy::default();
1385        manager
1386            .register_policy("test_client".to_string(), policy)
1387            .await;
1388    }
1389
1390    #[test]
1391    fn test_token_type_parsing() {
1392        let manager = create_test_manager();
1393
1394        assert_eq!(
1395            manager
1396                .parse_token_type("urn:ietf:params:oauth:token-type:access_token")
1397                .unwrap(),
1398            TokenType::AccessToken
1399        );
1400
1401        assert_eq!(
1402            manager
1403                .parse_token_type("urn:ietf:params:oauth:token-type:id_token")
1404                .unwrap(),
1405            TokenType::IdToken
1406        );
1407
1408        assert!(manager.parse_token_type("invalid_token_type").is_err());
1409    }
1410
1411    #[test]
1412    fn test_exchange_scenario_determination() {
1413        let manager = create_test_manager();
1414        let policy = TokenExchangePolicy::default();
1415
1416        // Test audience restriction scenario
1417        let context = TokenExchangeContext {
1418            subject_claims: SecureJwtClaims {
1419                sub: "user123".to_string(),
1420                iss: "auth.example.com".to_string(),
1421                aud: "api.example.com".to_string(),
1422                exp: chrono::Utc::now().timestamp() + 3600,
1423                nbf: chrono::Utc::now().timestamp(),
1424                iat: chrono::Utc::now().timestamp(),
1425                jti: "token123".to_string(),
1426                scope: "read write".to_string(),
1427                typ: "access".to_string(),
1428                sid: None,
1429                client_id: None,
1430                auth_ctx_hash: None,
1431            },
1432            actor_claims: None,
1433            client_id: "test_client".to_string(),
1434            audience: Some("different.api.com".to_string()),
1435            scope: None,
1436            resource: None,
1437        };
1438
1439        let scenario = manager
1440            .determine_exchange_scenario(&context, &policy)
1441            .unwrap();
1442        assert_eq!(scenario, ExchangeScenario::AudienceRestriction);
1443    }
1444
1445    #[tokio::test]
1446    async fn test_invalid_grant_type() {
1447        let manager = create_test_manager();
1448        let policy = TokenExchangePolicy::default();
1449        manager
1450            .register_policy("test_client".to_string(), policy)
1451            .await;
1452
1453        let mut request = create_test_request();
1454        request.grant_type = "invalid_grant_type".to_string();
1455
1456        let result = manager.exchange_token(request, "test_client").await;
1457        assert!(result.is_err());
1458    }
1459
1460    #[test]
1461    fn test_token_exchange_policy_builder() {
1462        let policy = TokenExchangePolicy::builder()
1463            .max_token_lifetime(Duration::minutes(30))
1464            .require_actor_for_delegation(false)
1465            .audience("api.example.com")
1466            .audience("internal.example.com")
1467            .scope_map("admin", vec!["read".into(), "write".into()])
1468            .build();
1469
1470        assert_eq!(policy.max_token_lifetime, Duration::minutes(30));
1471        assert!(!policy.require_actor_for_delegation);
1472        assert_eq!(policy.allowed_audiences.len(), 2);
1473        assert_eq!(policy.scope_mapping.get("admin").unwrap().len(), 2);
1474        // Builder starts from default so subject types are populated
1475        assert!(!policy.allowed_subject_token_types.is_empty());
1476    }
1477
1478    #[test]
1479    fn test_token_exchange_policy_jwt_only_preset() {
1480        let policy = TokenExchangePolicy::jwt_only();
1481        assert_eq!(policy.allowed_subject_token_types.len(), 2);
1482        assert!(policy.allowed_subject_token_types.contains(&TokenType::Jwt));
1483        assert!(
1484            policy
1485                .allowed_subject_token_types
1486                .contains(&TokenType::AccessToken)
1487        );
1488        assert!(policy.require_actor_for_delegation);
1489    }
1490
1491    #[tokio::test]
1492    async fn test_token_exchange_policy_builder_register() {
1493        let manager = create_test_manager();
1494        let policy = TokenExchangePolicy::builder()
1495            .scenarios(vec![
1496                ExchangeScenario::OnBehalfOf,
1497                ExchangeScenario::AudienceRestriction,
1498            ])
1499            .max_token_lifetime(Duration::minutes(15))
1500            .build();
1501        manager
1502            .register_policy("test_client".to_string(), policy)
1503            .await;
1504    }
1505}