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