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::security::secure_jwt::{SecureJwtValidator, SecureJwtConfig};
35//!
36//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
37//! let jwt_validator = SecureJwtValidator::new(SecureJwtConfig::default());
38//! let mut manager = TokenExchangeManager::new(jwt_validator);
39//!
40//! let request = TokenExchangeRequest {
41//!     grant_type: "urn:ietf:params:oauth:grant-type:token-exchange".to_string(),
42//!     subject_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...".to_string(),
43//!     subject_token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(),
44//!     requested_token_type: Some("urn:ietf:params:oauth:token-type:access_token".to_string()),
45//!     // ... other fields
46//!     # actor_token: None,
47//!     # actor_token_type: None,
48//!     # audience: None,
49//!     # scope: None,
50//!     # resource: None,
51//! };
52//!
53//! let response = manager.exchange_token(request, "client_123").await?;
54//! # Ok(())
55//! # }
56//! ```
57
58use crate::errors::{AuthError, Result};
59use crate::security::secure_jwt::{SecureJwtClaims, SecureJwtValidator};
60use crate::server::token_exchange::token_exchange_common::{
61    ServiceComplexityLevel, TokenExchangeCapabilities, TokenExchangeService, TokenValidationResult,
62    ValidationUtils,
63};
64use async_trait::async_trait;
65use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
66use chrono::{Duration, Utc};
67use serde::{Deserialize, Serialize};
68use std::collections::HashMap;
69
70/// Token Exchange Request (RFC 8693)
71#[derive(Clone, Serialize, Deserialize)]
72pub struct TokenExchangeRequest {
73    /// Grant type (must be "urn:ietf:params:oauth:grant-type:token-exchange")
74    pub grant_type: String,
75
76    /// Security token to be exchanged
77    pub subject_token: String,
78
79    /// Type of the subject token
80    pub subject_token_type: String,
81
82    /// Optional actor token (for delegation scenarios)
83    pub actor_token: Option<String>,
84
85    /// Type of the actor token
86    pub actor_token_type: Option<String>,
87
88    /// Requested token type
89    pub requested_token_type: Option<String>,
90
91    /// Target audience for the token
92    pub audience: Option<String>,
93
94    /// Requested scope
95    pub scope: Option<String>,
96
97    /// Resource parameter
98    pub resource: Option<String>,
99}
100
101impl std::fmt::Debug for TokenExchangeRequest {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        let mut d = f.debug_struct("TokenExchangeRequest");
104        d.field("grant_type", &self.grant_type);
105        d.field(
106            "subject_token",
107            &crate::utils::redact::redacted(&self.subject_token),
108        );
109        d.field("subject_token_type", &self.subject_token_type);
110        d.field(
111            "actor_token",
112            &crate::utils::redact::redacted(&self.actor_token),
113        );
114        d.field("actor_token_type", &self.actor_token_type);
115        d.field("requested_token_type", &self.requested_token_type);
116        d.field("audience", &self.audience);
117        d.field("scope", &self.scope);
118        d.field("resource", &self.resource);
119        d.finish()
120    }
121}
122
123/// Token Exchange Response (RFC 8693)
124#[derive(Clone, Serialize, Deserialize)]
125pub struct TokenExchangeResponse {
126    /// Access token issued by authorization server
127    pub access_token: String,
128
129    /// Token type (typically "Bearer")
130    pub token_type: String,
131
132    /// Expires in seconds
133    pub expires_in: Option<i64>,
134
135    /// Refresh token (optional)
136    pub refresh_token: Option<String>,
137
138    /// Scope of the access token
139    pub scope: Option<String>,
140
141    /// Type of the issued token
142    pub issued_token_type: Option<String>,
143}
144
145impl std::fmt::Debug for TokenExchangeResponse {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        let mut d = f.debug_struct("TokenExchangeResponse");
148        d.field(
149            "access_token",
150            &crate::utils::redact::redacted(&self.access_token),
151        );
152        d.field("token_type", &self.token_type);
153        d.field("expires_in", &self.expires_in);
154        d.field(
155            "refresh_token",
156            &crate::utils::redact::redacted(&self.refresh_token),
157        );
158        d.field("scope", &self.scope);
159        d.field("issued_token_type", &self.issued_token_type);
160        d.finish()
161    }
162}
163
164/// Token types defined in RFC 8693
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166pub enum TokenType {
167    /// JWT access token
168    #[serde(rename = "urn:ietf:params:oauth:token-type:access_token")]
169    AccessToken,
170
171    /// JWT refresh token
172    #[serde(rename = "urn:ietf:params:oauth:token-type:refresh_token")]
173    RefreshToken,
174
175    /// OIDC ID token
176    #[serde(rename = "urn:ietf:params:oauth:token-type:id_token")]
177    IdToken,
178
179    /// SAML 2.0 assertion
180    #[serde(rename = "urn:ietf:params:oauth:token-type:saml2")]
181    Saml2,
182
183    /// SAML 1.1 assertion
184    #[serde(rename = "urn:ietf:params:oauth:token-type:saml1")]
185    Saml1,
186
187    /// JWT token (generic)
188    #[serde(rename = "urn:ietf:params:oauth:token-type:jwt")]
189    Jwt,
190}
191
192/// Token exchange context for validation
193#[derive(Debug, Clone)]
194pub struct TokenExchangeContext {
195    /// Subject token claims
196    pub subject_claims: SecureJwtClaims,
197
198    /// Actor token claims (if present)
199    pub actor_claims: Option<SecureJwtClaims>,
200
201    /// Client identifier
202    pub client_id: String,
203
204    /// Requested audience
205    pub audience: Option<String>,
206
207    /// Requested scope
208    pub scope: Option<Vec<String>>,
209
210    /// Resource parameter
211    pub resource: Option<String>,
212}
213
214/// Token exchange policy
215#[derive(Debug, Clone)]
216pub struct TokenExchangePolicy {
217    /// Allowed subject token types
218    pub allowed_subject_token_types: Vec<TokenType>,
219
220    /// Allowed actor token types
221    pub allowed_actor_token_types: Vec<TokenType>,
222
223    /// Allowed token exchange scenarios
224    pub allowed_scenarios: Vec<ExchangeScenario>,
225
226    /// Maximum token lifetime for exchanged tokens
227    pub max_token_lifetime: Duration,
228
229    /// Whether to require actor tokens for delegation
230    pub require_actor_for_delegation: bool,
231
232    /// Allowed audience values
233    pub allowed_audiences: Vec<String>,
234
235    /// Scope mapping rules
236    pub scope_mapping: HashMap<String, Vec<String>>,
237}
238
239/// Token exchange scenarios
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub enum ExchangeScenario {
242    /// Acting as the subject (impersonation)
243    ActingAs,
244
245    /// Acting on behalf of the subject (delegation)
246    OnBehalfOf,
247
248    /// Token format conversion
249    TokenConversion,
250
251    /// Audience restriction
252    AudienceRestriction,
253
254    /// Scope reduction
255    ScopeReduction,
256}
257
258/// Token Exchange Manager
259pub struct TokenExchangeManager {
260    /// JWT validator for token validation
261    jwt_validator: SecureJwtValidator,
262
263    /// Token exchange policies
264    policies: tokio::sync::RwLock<HashMap<String, TokenExchangePolicy>>,
265
266    /// Active exchanges for tracking
267    active_exchanges: tokio::sync::RwLock<HashMap<String, TokenExchangeContext>>,
268}
269
270impl TokenExchangeManager {
271    /// Supported subject token types
272    const SUBJECT_TOKEN_TYPES: &'static [&'static str] = &[
273        "urn:ietf:params:oauth:token-type:jwt",
274        "urn:ietf:params:oauth:token-type:access_token",
275        "urn:ietf:params:oauth:token-type:id_token",
276        "urn:ietf:params:oauth:token-type:saml2",
277    ];
278
279    /// Supported requested token types
280    const REQUESTED_TOKEN_TYPES: &'static [&'static str] = &[
281        "urn:ietf:params:oauth:token-type:jwt",
282        "urn:ietf:params:oauth:token-type:access_token",
283        "urn:ietf:params:oauth:token-type:refresh_token",
284    ];
285
286    /// Create a new token exchange manager
287    pub fn new(jwt_validator: SecureJwtValidator) -> Self {
288        Self {
289            jwt_validator,
290            policies: tokio::sync::RwLock::new(HashMap::new()),
291            active_exchanges: tokio::sync::RwLock::new(HashMap::new()),
292        }
293    }
294
295    /// Register a token exchange policy for a client
296    pub async fn register_policy(&self, client_id: String, policy: TokenExchangePolicy) {
297        let mut policies = self.policies.write().await;
298        policies.insert(client_id, policy);
299    }
300
301    /// Process a token exchange request
302    pub async fn exchange_token(
303        &self,
304        request: TokenExchangeRequest,
305        client_id: &str,
306    ) -> Result<TokenExchangeResponse> {
307        // Validate grant type
308        if request.grant_type != "urn:ietf:params:oauth:grant-type:token-exchange" {
309            return Err(AuthError::auth_method(
310                "token_exchange",
311                "Invalid grant type for token exchange",
312            ));
313        }
314
315        // Get client policy
316        let policies = self.policies.read().await;
317        let policy = policies.get(client_id).ok_or_else(|| {
318            AuthError::auth_method("token_exchange", "No token exchange policy for client")
319        })?;
320
321        // Validate and parse subject token
322        let subject_claims = self.validate_subject_token(&request, policy).await?;
323
324        // Validate and parse actor token (if present)
325        let actor_claims = if let Some(ref actor_token) = request.actor_token {
326            Some(
327                self.validate_actor_token(actor_token, &request.actor_token_type, policy)
328                    .await?,
329            )
330        } else {
331            None
332        };
333
334        // Create exchange context
335        let context = TokenExchangeContext {
336            subject_claims,
337            actor_claims,
338            client_id: client_id.to_string(),
339            audience: request.audience.clone(),
340            scope: request
341                .scope
342                .as_ref()
343                .map(|s| s.split(' ').map(String::from).collect()),
344            resource: request.resource.clone(),
345        };
346
347        // Validate exchange scenario
348        let scenario = self.determine_exchange_scenario(&context, policy)?;
349        self.validate_exchange_scenario(&scenario, &context, policy)?;
350
351        // Generate new token
352        let response = self
353            .generate_exchanged_token(&context, &request, policy)
354            .await?;
355
356        // Track the exchange
357        let exchange_id = uuid::Uuid::new_v4().to_string();
358        let mut exchanges = self.active_exchanges.write().await;
359        exchanges.insert(exchange_id, context);
360
361        Ok(response)
362    }
363
364    /// Validate subject token
365    async fn validate_subject_token(
366        &self,
367        request: &TokenExchangeRequest,
368        policy: &TokenExchangePolicy,
369    ) -> Result<SecureJwtClaims> {
370        // Parse token type
371        let token_type = self.parse_token_type(&request.subject_token_type)?;
372
373        // Check if token type is allowed
374        if !policy.allowed_subject_token_types.contains(&token_type) {
375            return Err(AuthError::auth_method(
376                "token_exchange",
377                "Subject token type not allowed",
378            ));
379        }
380
381        // Validate JWT token (simplified - would need different validation for different types)
382        match token_type {
383            TokenType::AccessToken
384            | TokenType::RefreshToken
385            | TokenType::IdToken
386            | TokenType::Jwt => {
387                // For JWT tokens, validate using JWT validator
388                // In a real implementation, you'd need appropriate decoding keys
389                self.validate_jwt_token(&request.subject_token).await
390            }
391            TokenType::Saml2 | TokenType::Saml1 => {
392                // For SAML tokens, perform basic validation
393                self.validate_saml_token(&request.subject_token, &token_type)
394                    .await
395            }
396        }
397    }
398
399    /// Validate actor token
400    async fn validate_actor_token(
401        &self,
402        actor_token: &str,
403        actor_token_type: &Option<String>,
404        policy: &TokenExchangePolicy,
405    ) -> Result<SecureJwtClaims> {
406        let token_type_str = actor_token_type
407            .as_ref()
408            .ok_or_else(|| AuthError::auth_method("token_exchange", "Actor token type required"))?;
409
410        let token_type = self.parse_token_type(token_type_str)?;
411
412        if !policy.allowed_actor_token_types.contains(&token_type) {
413            return Err(AuthError::auth_method(
414                "token_exchange",
415                "Actor token type not allowed",
416            ));
417        }
418
419        self.validate_jwt_token(actor_token).await
420    }
421
422    /// Validate JWT token using SECURE cryptographic verification
423    async fn validate_jwt_token(&self, token: &str) -> Result<SecureJwtClaims> {
424        // SECURITY FIX: Use proper key management from SecureJwtValidator
425        // Get the proper decoding key from the configured JWT validator
426        let decoding_key = self.jwt_validator.get_decoding_key();
427
428        // Use secure JWT validation with proper cryptographic verification
429        self.jwt_validator
430            .validate_token(token, &decoding_key, true)
431            .map_err(|e| {
432                AuthError::auth_method("token_exchange", format!("JWT validation failed: {}", e))
433            })
434    }
435
436    /// SAML subject tokens are refused in this release line.
437    ///
438    /// Earlier releases accepted any text that looked like a SAML assertion, without checking a
439    /// signature. This line has no XML signature verifier, so it cannot accept one safely; the
440    /// 0.5 and 0.6 lines verify the signature under a certificate you configure.
441    async fn validate_saml_token(
442        &self,
443        _token: &str,
444        _token_type: &TokenType,
445    ) -> Result<SecureJwtClaims> {
446        Err(AuthError::auth_method(
447            "token_exchange",
448            "SAML subject tokens are not accepted by this release line: their signature cannot be verified here. Use a release line with SAML signature verification, or exchange a JWT",
449        ))
450    }
451
452    /// Parse token type from string
453    fn parse_token_type(&self, token_type: &str) -> Result<TokenType> {
454        match token_type {
455            "urn:ietf:params:oauth:token-type:access_token" => Ok(TokenType::AccessToken),
456            "urn:ietf:params:oauth:token-type:refresh_token" => Ok(TokenType::RefreshToken),
457            "urn:ietf:params:oauth:token-type:id_token" => Ok(TokenType::IdToken),
458            "urn:ietf:params:oauth:token-type:saml2" => Ok(TokenType::Saml2),
459            "urn:ietf:params:oauth:token-type:saml1" => Ok(TokenType::Saml1),
460            "urn:ietf:params:oauth:token-type:jwt" => Ok(TokenType::Jwt),
461            _ => Err(AuthError::auth_method(
462                "token_exchange",
463                "Unknown token type",
464            )),
465        }
466    }
467
468    /// Determine exchange scenario based on context
469    fn determine_exchange_scenario(
470        &self,
471        context: &TokenExchangeContext,
472        _policy: &TokenExchangePolicy,
473    ) -> Result<ExchangeScenario> {
474        // If actor token is present, it's delegation (on-behalf-of)
475        if context.actor_claims.is_some() {
476            return Ok(ExchangeScenario::OnBehalfOf);
477        }
478
479        // If audience is different, it's audience restriction
480        if context.audience.is_some()
481            && context.audience.as_ref() != Some(&context.subject_claims.aud)
482        {
483            return Ok(ExchangeScenario::AudienceRestriction);
484        }
485
486        // If scope is reduced, it's scope reduction
487        if let Some(requested_scope) = &context.scope {
488            let current_scope: Vec<&str> = context.subject_claims.scope.split(' ').collect();
489            if requested_scope.len() < current_scope.len() {
490                return Ok(ExchangeScenario::ScopeReduction);
491            }
492        }
493
494        // Default to acting-as (impersonation)
495        Ok(ExchangeScenario::ActingAs)
496    }
497
498    /// Validate exchange scenario
499    fn validate_exchange_scenario(
500        &self,
501        scenario: &ExchangeScenario,
502        context: &TokenExchangeContext,
503        policy: &TokenExchangePolicy,
504    ) -> Result<()> {
505        if !policy.allowed_scenarios.contains(scenario) {
506            return Err(AuthError::auth_method(
507                "token_exchange",
508                "Exchange scenario not allowed",
509            ));
510        }
511
512        match scenario {
513            ExchangeScenario::OnBehalfOf => {
514                if policy.require_actor_for_delegation && context.actor_claims.is_none() {
515                    return Err(AuthError::auth_method(
516                        "token_exchange",
517                        "Actor token required for delegation",
518                    ));
519                }
520            }
521            ExchangeScenario::AudienceRestriction => {
522                if let Some(ref audience) = context.audience
523                    && !policy.allowed_audiences.is_empty()
524                    && !policy.allowed_audiences.contains(audience)
525                {
526                    return Err(AuthError::auth_method(
527                        "token_exchange",
528                        "Audience not allowed",
529                    ));
530                }
531            }
532            _ => {
533                // Other scenarios don't need special validation for now
534            }
535        }
536
537        Ok(())
538    }
539
540    /// Generate exchanged token
541    async fn generate_exchanged_token(
542        &self,
543        context: &TokenExchangeContext,
544        request: &TokenExchangeRequest,
545        policy: &TokenExchangePolicy,
546    ) -> Result<TokenExchangeResponse> {
547        let now = Utc::now();
548        let expires_in = policy.max_token_lifetime.num_seconds();
549        let exp = now + policy.max_token_lifetime;
550
551        // Create new claims based on exchange scenario
552        let mut new_claims = context.subject_claims.clone();
553
554        // Update expiration
555        new_claims.exp = exp.timestamp();
556        new_claims.iat = now.timestamp();
557        new_claims.jti = uuid::Uuid::new_v4().to_string();
558
559        // Update audience if specified
560        if let Some(ref audience) = request.audience {
561            new_claims.aud = audience.clone();
562        }
563
564        // Update scope if specified and apply mapping
565        if let Some(ref requested_scope) = request.scope {
566            if let Some(mapped_scopes) = policy.scope_mapping.get(requested_scope) {
567                new_claims.scope = mapped_scopes.join(" ");
568            } else {
569                new_claims.scope = requested_scope.clone();
570            }
571        }
572
573        // Add actor information for delegation
574        if let Some(ref actor_claims) = context.actor_claims {
575            new_claims.client_id = Some(actor_claims.sub.clone());
576        }
577
578        // Generate JWT (simplified - would use proper signing in production)
579        let access_token = format!(
580            "exchanged_token_{}_{}",
581            new_claims.jti,
582            URL_SAFE_NO_PAD.encode(&new_claims.sub)
583        );
584
585        // Determine issued token type
586        let issued_token_type = request
587            .requested_token_type
588            .clone()
589            .unwrap_or_else(|| "urn:ietf:params:oauth:token-type:access_token".to_string());
590
591        Ok(TokenExchangeResponse {
592            access_token,
593            token_type: "Bearer".to_string(),
594            expires_in: Some(expires_in),
595            refresh_token: None, // Could generate refresh token in some scenarios
596            scope: Some(new_claims.scope),
597            issued_token_type: Some(issued_token_type),
598        })
599    }
600
601    /// Get appropriate JWT decoding key for token validation
602    fn get_jwt_decoding_key(&self, token: &str) -> Result<jsonwebtoken::DecodingKey> {
603        use jsonwebtoken::DecodingKey;
604
605        // Extract JWT header to determine key ID and algorithm
606        let token_parts: Vec<&str> = token.split('.').collect();
607        if token_parts.len() < 2 {
608            return Err(AuthError::InvalidToken("Invalid JWT format".to_string()));
609        }
610
611        let header_b64 = token_parts[0];
612        let header_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
613            .decode(header_b64)
614            .map_err(|_| AuthError::InvalidToken("Invalid JWT header encoding".to_string()))?;
615
616        let header: serde_json::Value = serde_json::from_slice(&header_bytes)
617            .map_err(|_| AuthError::InvalidToken("Invalid JWT header JSON".to_string()))?;
618
619        // In production, this would:
620        // 1. Extract 'kid' (key ID) from header
621        // 2. Look up appropriate key from JWKS endpoint or key store
622        // 3. Support multiple algorithms (RS256, ES256, etc.)
623
624        let algorithm = header
625            .get("alg")
626            .and_then(|a| a.as_str())
627            .unwrap_or("HS256");
628
629        match algorithm {
630            "HS256" => {
631                // Load HMAC secret from configuration
632                let secret = std::env::var("JWT_HMAC_SECRET")
633                    .unwrap_or_else(|_| "default_hmac_secret_for_development".to_string());
634                Ok(DecodingKey::from_secret(secret.as_bytes()))
635            }
636            "RS256" => {
637                // Load RSA public key from configuration or JWKS
638                let public_key_pem = std::env::var("JWT_RSA_PUBLIC_KEY")
639                    .unwrap_or_else(|_| include_str!("../../../public.pem").to_string());
640                DecodingKey::from_rsa_pem(public_key_pem.as_bytes())
641                    .map_err(|e| AuthError::InvalidToken(format!("Invalid RSA key: {}", e)))
642            }
643            _ => {
644                // Fallback for development
645                Ok(DecodingKey::from_secret("fallback_secret".as_bytes()))
646            }
647        }
648    }
649}
650
651impl Default for TokenExchangePolicy {
652    fn default() -> Self {
653        Self {
654            allowed_subject_token_types: vec![
655                TokenType::AccessToken,
656                TokenType::RefreshToken,
657                TokenType::IdToken,
658            ],
659            allowed_actor_token_types: vec![TokenType::AccessToken, TokenType::IdToken],
660            allowed_scenarios: vec![
661                ExchangeScenario::ActingAs,
662                ExchangeScenario::OnBehalfOf,
663                ExchangeScenario::AudienceRestriction,
664                ExchangeScenario::ScopeReduction,
665            ],
666            max_token_lifetime: Duration::hours(1),
667            require_actor_for_delegation: true,
668            allowed_audiences: Vec::new(), // Empty means all audiences allowed
669            scope_mapping: HashMap::new(),
670        }
671    }
672}
673
674/// Implementation of the common TokenExchangeService trait
675#[async_trait]
676impl TokenExchangeService for TokenExchangeManager {
677    type Request = (TokenExchangeRequest, String); // Request + client_id
678    type Response = TokenExchangeResponse;
679    type Config = SecureJwtValidator; // Configuration is the JWT validator
680
681    /// Exchange a token following RFC 8693 (basic implementation)
682    async fn exchange_token(&self, request: Self::Request) -> Result<Self::Response> {
683        let (token_request, client_id) = request;
684        self.exchange_token(token_request, &client_id).await
685    }
686
687    /// Validate a token using the internal JWT validator
688    async fn validate_token(&self, token: &str, token_type: &str) -> Result<TokenValidationResult> {
689        // Use shared validation utilities
690        let supported_types = self.supported_subject_token_types();
691        ValidationUtils::validate_token_type(token_type, &supported_types)?;
692
693        match self.parse_token_type(token_type)? {
694            TokenType::Jwt | TokenType::AccessToken | TokenType::IdToken => {
695                // Load proper JWT validation key from configuration
696                let decoding_key = self.get_jwt_decoding_key(token)?;
697
698                match self
699                    .jwt_validator
700                    .validate_token(token, &decoding_key, true)
701                {
702                    Ok(claims) => {
703                        // Convert timestamp to DateTime
704                        use chrono::{TimeZone, Utc};
705                        let expires_at = Utc.timestamp_opt(claims.exp, 0).single();
706
707                        // Convert audience string to vector
708                        let audience = if claims.aud.is_empty() {
709                            Vec::new()
710                        } else {
711                            vec![claims.aud.clone()]
712                        };
713
714                        // Extract scopes from scope string
715                        let scopes = if claims.scope.is_empty() {
716                            Vec::new()
717                        } else {
718                            claims
719                                .scope
720                                .split_whitespace()
721                                .map(|s| s.to_string())
722                                .collect()
723                        };
724
725                        // Create metadata from available claims
726                        let mut metadata = HashMap::new();
727                        metadata.insert(
728                            "sub".to_string(),
729                            serde_json::Value::String(claims.sub.clone()),
730                        );
731                        metadata.insert(
732                            "iss".to_string(),
733                            serde_json::Value::String(claims.iss.clone()),
734                        );
735                        metadata.insert(
736                            "aud".to_string(),
737                            serde_json::Value::String(claims.aud.clone()),
738                        );
739                        metadata.insert(
740                            "scope".to_string(),
741                            serde_json::Value::String(claims.scope.clone()),
742                        );
743                        metadata.insert(
744                            "typ".to_string(),
745                            serde_json::Value::String(claims.typ.clone()),
746                        );
747                        if let Some(ref sid) = claims.sid {
748                            metadata
749                                .insert("sid".to_string(), serde_json::Value::String(sid.clone()));
750                        }
751                        if let Some(ref client_id) = claims.client_id {
752                            metadata.insert(
753                                "client_id".to_string(),
754                                serde_json::Value::String(client_id.clone()),
755                            );
756                        }
757
758                        Ok(TokenValidationResult {
759                            is_valid: true,
760                            subject: Some(claims.sub),
761                            issuer: Some(claims.iss),
762                            audience,
763                            scopes,
764                            expires_at,
765                            metadata,
766                            validation_messages: Vec::new(),
767                        })
768                    }
769                    Err(e) => Ok(TokenValidationResult {
770                        is_valid: false,
771                        subject: None,
772                        issuer: None,
773                        audience: Vec::new(),
774                        scopes: Vec::new(),
775                        expires_at: None,
776                        metadata: HashMap::new(),
777                        validation_messages: vec![format!("JWT validation failed: {}", e)],
778                    }),
779                }
780            }
781            TokenType::Saml2 | TokenType::Saml1 => {
782                // No signature verifier in this release line: a SAML token is never valid here.
783                Ok(TokenValidationResult {
784                    is_valid: false,
785                    subject: None,
786                    issuer: None,
787                    audience: Vec::new(),
788                    scopes: Vec::new(),
789                    expires_at: None,
790                    metadata: HashMap::new(),
791                    validation_messages: vec![
792                        "SAML tokens cannot be validated in this release line".to_string(),
793                    ],
794                })
795            }
796            _ => Err(AuthError::InvalidRequest(format!(
797                "Token validation not supported for type: {}",
798                token_type
799            ))),
800        }
801    }
802
803    /// Get supported subject token types
804    fn supported_subject_token_types(&self) -> Vec<String> {
805        Self::SUBJECT_TOKEN_TYPES
806            .iter()
807            .map(|s| s.to_string())
808            .collect()
809    }
810
811    /// Get supported requested token types
812    fn supported_requested_token_types(&self) -> Vec<String> {
813        Self::REQUESTED_TOKEN_TYPES
814            .iter()
815            .map(|s| s.to_string())
816            .collect()
817    }
818
819    /// Get service capabilities
820    fn capabilities(&self) -> TokenExchangeCapabilities {
821        TokenExchangeCapabilities {
822            basic_exchange: true,
823            multi_party_chains: false,
824            context_preservation: false,
825            audit_trail: false,
826            session_integration: false,
827            jwt_operations: false,
828            policy_control: true,
829            cross_domain_exchange: false,
830            max_delegation_depth: 3,
831            complexity_level: ServiceComplexityLevel::Basic,
832        }
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use super::*;
839    use crate::security::secure_jwt::SecureJwtConfig;
840
841    fn create_test_manager() -> TokenExchangeManager {
842        let jwt_config = SecureJwtConfig::default();
843        let jwt_validator = SecureJwtValidator::new(jwt_config);
844        TokenExchangeManager::new(jwt_validator)
845    }
846
847    fn create_test_request() -> TokenExchangeRequest {
848        TokenExchangeRequest {
849            grant_type: "urn:ietf:params:oauth:grant-type:token-exchange".to_string(),
850            subject_token: "dummy.jwt.token".to_string(),
851            subject_token_type: "urn:ietf:params:oauth:token-type:access_token".to_string(),
852            actor_token: None,
853            actor_token_type: None,
854            requested_token_type: Some("urn:ietf:params:oauth:token-type:access_token".to_string()),
855            audience: Some("api.example.com".to_string()),
856            scope: Some("read write".to_string()),
857            resource: None,
858        }
859    }
860
861    #[tokio::test]
862    async fn test_token_exchange_manager_creation() {
863        let manager = create_test_manager();
864
865        // Register a policy
866        let policy = TokenExchangePolicy::default();
867        manager
868            .register_policy("test_client".to_string(), policy)
869            .await;
870    }
871
872    #[test]
873    fn test_token_type_parsing() {
874        let manager = create_test_manager();
875
876        assert_eq!(
877            manager
878                .parse_token_type("urn:ietf:params:oauth:token-type:access_token")
879                .unwrap(),
880            TokenType::AccessToken
881        );
882
883        assert_eq!(
884            manager
885                .parse_token_type("urn:ietf:params:oauth:token-type:id_token")
886                .unwrap(),
887            TokenType::IdToken
888        );
889
890        assert!(manager.parse_token_type("invalid_token_type").is_err());
891    }
892
893    #[test]
894    fn test_exchange_scenario_determination() {
895        let manager = create_test_manager();
896        let policy = TokenExchangePolicy::default();
897
898        // Test audience restriction scenario
899        let context = TokenExchangeContext {
900            subject_claims: SecureJwtClaims {
901                sub: "user123".to_string(),
902                iss: "auth.example.com".to_string(),
903                aud: "api.example.com".to_string(),
904                exp: chrono::Utc::now().timestamp() + 3600,
905                nbf: chrono::Utc::now().timestamp(),
906                iat: chrono::Utc::now().timestamp(),
907                jti: "token123".to_string(),
908                scope: "read write".to_string(),
909                typ: "access".to_string(),
910                sid: None,
911                client_id: None,
912                auth_ctx_hash: None,
913            },
914            actor_claims: None,
915            client_id: "test_client".to_string(),
916            audience: Some("different.api.com".to_string()),
917            scope: None,
918            resource: None,
919        };
920
921        let scenario = manager
922            .determine_exchange_scenario(&context, &policy)
923            .unwrap();
924        assert_eq!(scenario, ExchangeScenario::AudienceRestriction);
925    }
926
927    #[tokio::test]
928    async fn test_invalid_grant_type() {
929        let manager = create_test_manager();
930        let policy = TokenExchangePolicy::default();
931        manager
932            .register_policy("test_client".to_string(), policy)
933            .await;
934
935        let mut request = create_test_request();
936        request.grant_type = "invalid_grant_type".to_string();
937
938        let result = manager.exchange_token(request, "test_client").await;
939        assert!(result.is_err());
940    }
941}