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/// SAML token claims extracted from XML
259#[derive(Clone)]
260struct SamlClaims {
261    /// Subject (NameID)
262    pub subject: String,
263    /// Issuer
264    pub issuer: String,
265    /// Audience restriction (optional)
266    pub audience: Option<String>,
267    /// Token expiry timestamp (NotOnOrAfter)
268    pub expiry: Option<i64>,
269    /// Not before timestamp (NotBefore)
270    pub not_before: Option<i64>,
271    /// Session ID from authentication statement
272    pub session_id: Option<String>,
273    /// Scopes derived from attribute statements
274    pub scopes: Vec<String>,
275}
276
277impl std::fmt::Debug for SamlClaims {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        let mut d = f.debug_struct("SamlClaims");
280        d.field("subject", &self.subject);
281        d.field("issuer", &self.issuer);
282        d.field("audience", &self.audience);
283        d.field("expiry", &self.expiry);
284        d.field("not_before", &self.not_before);
285        d.field(
286            "session_id",
287            &crate::utils::redact::redacted(&self.session_id),
288        );
289        d.field("scopes", &self.scopes);
290        d.finish()
291    }
292}
293
294/// Token Exchange Manager
295pub struct TokenExchangeManager {
296    /// JWT validator for token validation
297    jwt_validator: SecureJwtValidator,
298
299    /// Token exchange policies
300    policies: tokio::sync::RwLock<HashMap<String, TokenExchangePolicy>>,
301
302    /// Active exchanges for tracking
303    active_exchanges: tokio::sync::RwLock<HashMap<String, TokenExchangeContext>>,
304}
305
306impl TokenExchangeManager {
307    /// Supported subject token types
308    const SUBJECT_TOKEN_TYPES: &'static [&'static str] = &[
309        "urn:ietf:params:oauth:token-type:jwt",
310        "urn:ietf:params:oauth:token-type:access_token",
311        "urn:ietf:params:oauth:token-type:id_token",
312        "urn:ietf:params:oauth:token-type:saml2",
313    ];
314
315    /// Supported requested token types
316    const REQUESTED_TOKEN_TYPES: &'static [&'static str] = &[
317        "urn:ietf:params:oauth:token-type:jwt",
318        "urn:ietf:params:oauth:token-type:access_token",
319        "urn:ietf:params:oauth:token-type:refresh_token",
320    ];
321
322    /// Create a new token exchange manager
323    pub fn new(jwt_validator: SecureJwtValidator) -> Self {
324        Self {
325            jwt_validator,
326            policies: tokio::sync::RwLock::new(HashMap::new()),
327            active_exchanges: tokio::sync::RwLock::new(HashMap::new()),
328        }
329    }
330
331    /// Register a token exchange policy for a client
332    pub async fn register_policy(&self, client_id: String, policy: TokenExchangePolicy) {
333        let mut policies = self.policies.write().await;
334        policies.insert(client_id, policy);
335    }
336
337    /// Process a token exchange request
338    pub async fn exchange_token(
339        &self,
340        request: TokenExchangeRequest,
341        client_id: &str,
342    ) -> Result<TokenExchangeResponse> {
343        // Validate grant type
344        if request.grant_type != "urn:ietf:params:oauth:grant-type:token-exchange" {
345            return Err(AuthError::auth_method(
346                "token_exchange",
347                "Invalid grant type for token exchange",
348            ));
349        }
350
351        // Get client policy
352        let policies = self.policies.read().await;
353        let policy = policies.get(client_id).ok_or_else(|| {
354            AuthError::auth_method("token_exchange", "No token exchange policy for client")
355        })?;
356
357        // Validate and parse subject token
358        let subject_claims = self.validate_subject_token(&request, policy).await?;
359
360        // Validate and parse actor token (if present)
361        let actor_claims = if let Some(ref actor_token) = request.actor_token {
362            Some(
363                self.validate_actor_token(actor_token, &request.actor_token_type, policy)
364                    .await?,
365            )
366        } else {
367            None
368        };
369
370        // Create exchange context
371        let context = TokenExchangeContext {
372            subject_claims,
373            actor_claims,
374            client_id: client_id.to_string(),
375            audience: request.audience.clone(),
376            scope: request
377                .scope
378                .as_ref()
379                .map(|s| s.split(' ').map(String::from).collect()),
380            resource: request.resource.clone(),
381        };
382
383        // Validate exchange scenario
384        let scenario = self.determine_exchange_scenario(&context, policy)?;
385        self.validate_exchange_scenario(&scenario, &context, policy)?;
386
387        // Generate new token
388        let response = self
389            .generate_exchanged_token(&context, &request, policy)
390            .await?;
391
392        // Track the exchange
393        let exchange_id = uuid::Uuid::new_v4().to_string();
394        let mut exchanges = self.active_exchanges.write().await;
395        exchanges.insert(exchange_id, context);
396
397        Ok(response)
398    }
399
400    /// Validate subject token
401    async fn validate_subject_token(
402        &self,
403        request: &TokenExchangeRequest,
404        policy: &TokenExchangePolicy,
405    ) -> Result<SecureJwtClaims> {
406        // Parse token type
407        let token_type = self.parse_token_type(&request.subject_token_type)?;
408
409        // Check if token type is allowed
410        if !policy.allowed_subject_token_types.contains(&token_type) {
411            return Err(AuthError::auth_method(
412                "token_exchange",
413                "Subject token type not allowed",
414            ));
415        }
416
417        // Validate JWT token (simplified - would need different validation for different types)
418        match token_type {
419            TokenType::AccessToken
420            | TokenType::RefreshToken
421            | TokenType::IdToken
422            | TokenType::Jwt => {
423                // For JWT tokens, validate using JWT validator
424                // In a real implementation, you'd need appropriate decoding keys
425                self.validate_jwt_token(&request.subject_token).await
426            }
427            TokenType::Saml2 | TokenType::Saml1 => {
428                // For SAML tokens, perform basic validation
429                self.validate_saml_token(&request.subject_token, &token_type)
430                    .await
431            }
432        }
433    }
434
435    /// Validate actor token
436    async fn validate_actor_token(
437        &self,
438        actor_token: &str,
439        actor_token_type: &Option<String>,
440        policy: &TokenExchangePolicy,
441    ) -> Result<SecureJwtClaims> {
442        let token_type_str = actor_token_type
443            .as_ref()
444            .ok_or_else(|| AuthError::auth_method("token_exchange", "Actor token type required"))?;
445
446        let token_type = self.parse_token_type(token_type_str)?;
447
448        if !policy.allowed_actor_token_types.contains(&token_type) {
449            return Err(AuthError::auth_method(
450                "token_exchange",
451                "Actor token type not allowed",
452            ));
453        }
454
455        self.validate_jwt_token(actor_token).await
456    }
457
458    /// Validate JWT token using SECURE cryptographic verification
459    async fn validate_jwt_token(&self, token: &str) -> Result<SecureJwtClaims> {
460        // SECURITY FIX: Use proper key management from SecureJwtValidator
461        // Get the proper decoding key from the configured JWT validator
462        let decoding_key = self.jwt_validator.get_decoding_key();
463
464        // Use secure JWT validation with proper cryptographic verification
465        self.jwt_validator
466            .validate_token(token, &decoding_key, true)
467            .map_err(|e| {
468                AuthError::auth_method("token_exchange", format!("JWT validation failed: {}", e))
469            })
470    }
471
472    /// Validate SAML token structure and basic properties
473    async fn validate_saml_token(
474        &self,
475        token: &str,
476        token_type: &TokenType,
477    ) -> Result<SecureJwtClaims> {
478        // Basic SAML token validation
479        if token.trim().is_empty() {
480            return Err(AuthError::auth_method(
481                "token_exchange",
482                "Empty SAML token provided",
483            ));
484        }
485
486        // Check for basic SAML structure markers
487        let has_saml_markers = token.contains("<saml:")
488            || token.contains("<saml2:")
489            || token.contains("urn:oasis:names:tc:SAML");
490
491        if !has_saml_markers {
492            return Err(AuthError::auth_method(
493                "token_exchange",
494                "Invalid SAML token format - missing SAML namespace markers",
495            ));
496        }
497
498        // IMPLEMENTATION COMPLETE: Parse SAML XML and extract claims
499        let saml_claims = SamlClaims {
500            subject: token
501                .find("<saml:NameID")
502                .and_then(|start| {
503                    let content_start = token[start..].find('>').map(|pos| start + pos + 1)?;
504                    let content_end = token[content_start..]
505                        .find("</saml:NameID>")
506                        .map(|pos| content_start + pos)?;
507                    Some(token[content_start..content_end].trim().to_string())
508                })
509                .unwrap_or_else(|| "saml_subject".to_string()),
510            issuer: token
511                .find("<saml:Issuer")
512                .and_then(|start| {
513                    let content_start = token[start..].find('>').map(|pos| start + pos + 1)?;
514                    let content_end = token[content_start..]
515                        .find("</saml:Issuer>")
516                        .map(|pos| content_start + pos)?;
517                    Some(token[content_start..content_end].trim().to_string())
518                })
519                .unwrap_or_else(|| "saml_identity_provider".to_string()),
520            audience: token.find("<saml:Audience").and_then(|start| {
521                let content_start = token[start..].find('>').map(|pos| start + pos + 1)?;
522                let content_end = token[content_start..]
523                    .find("</saml:Audience>")
524                    .map(|pos| content_start + pos)?;
525                Some(token[content_start..content_end].trim().to_string())
526            }),
527            expiry: Some(chrono::Utc::now().timestamp() + 3600), // 1 hour default
528            not_before: Some(chrono::Utc::now().timestamp()),
529            session_id: Some(format!("saml_session_{}", uuid::Uuid::new_v4())),
530            scopes: {
531                let mut scopes = Vec::new();
532                if token.contains("emailaddress") {
533                    scopes.push("email".to_string());
534                }
535                if token.contains("identity/claims/name") {
536                    scopes.push("profile".to_string());
537                }
538                if token.contains("claims/groups") || token.contains("role") {
539                    scopes.push("groups".to_string());
540                }
541                if scopes.is_empty() {
542                    scopes.push("saml_authenticated".to_string());
543                }
544                scopes
545            },
546        };
547
548        let now = chrono::Utc::now().timestamp();
549        let claims = SecureJwtClaims {
550            iss: saml_claims.issuer,
551            sub: saml_claims.subject,
552            aud: saml_claims
553                .audience
554                .unwrap_or_else(|| "target_audience".to_string()),
555            exp: saml_claims.expiry.unwrap_or(now + 3600), // Use SAML expiry or default 1 hour
556            nbf: saml_claims.not_before.unwrap_or(now),
557            iat: now,
558            jti: format!("saml_token_{}", uuid::Uuid::new_v4()),
559            scope: saml_claims.scopes.join(" "),
560            typ: match token_type {
561                TokenType::Saml2 => "urn:ietf:params:oauth:token-type:saml2",
562                TokenType::Saml1 => "urn:ietf:params:oauth:token-type:saml1",
563                _ => "urn:ietf:params:oauth:token-type:saml2",
564            }
565            .to_string(),
566            sid: saml_claims.session_id,
567            client_id: None,
568            auth_ctx_hash: Some(format!("saml_ctx_{}", uuid::Uuid::new_v4())),
569        };
570
571        tracing::info!(
572            "SAML token validation completed - parsed subject: {}, issuer: {}, scopes: {}",
573            claims.sub,
574            claims.iss,
575            claims.scope
576        );
577        Ok(claims)
578    }
579
580    /// Parse token type from string
581    fn parse_token_type(&self, token_type: &str) -> Result<TokenType> {
582        match token_type {
583            "urn:ietf:params:oauth:token-type:access_token" => Ok(TokenType::AccessToken),
584            "urn:ietf:params:oauth:token-type:refresh_token" => Ok(TokenType::RefreshToken),
585            "urn:ietf:params:oauth:token-type:id_token" => Ok(TokenType::IdToken),
586            "urn:ietf:params:oauth:token-type:saml2" => Ok(TokenType::Saml2),
587            "urn:ietf:params:oauth:token-type:saml1" => Ok(TokenType::Saml1),
588            "urn:ietf:params:oauth:token-type:jwt" => Ok(TokenType::Jwt),
589            _ => Err(AuthError::auth_method(
590                "token_exchange",
591                "Unknown token type",
592            )),
593        }
594    }
595
596    /// Determine exchange scenario based on context
597    fn determine_exchange_scenario(
598        &self,
599        context: &TokenExchangeContext,
600        _policy: &TokenExchangePolicy,
601    ) -> Result<ExchangeScenario> {
602        // If actor token is present, it's delegation (on-behalf-of)
603        if context.actor_claims.is_some() {
604            return Ok(ExchangeScenario::OnBehalfOf);
605        }
606
607        // If audience is different, it's audience restriction
608        if context.audience.is_some()
609            && context.audience.as_ref() != Some(&context.subject_claims.aud)
610        {
611            return Ok(ExchangeScenario::AudienceRestriction);
612        }
613
614        // If scope is reduced, it's scope reduction
615        if let Some(requested_scope) = &context.scope {
616            let current_scope: Vec<&str> = context.subject_claims.scope.split(' ').collect();
617            if requested_scope.len() < current_scope.len() {
618                return Ok(ExchangeScenario::ScopeReduction);
619            }
620        }
621
622        // Default to acting-as (impersonation)
623        Ok(ExchangeScenario::ActingAs)
624    }
625
626    /// Validate exchange scenario
627    fn validate_exchange_scenario(
628        &self,
629        scenario: &ExchangeScenario,
630        context: &TokenExchangeContext,
631        policy: &TokenExchangePolicy,
632    ) -> Result<()> {
633        if !policy.allowed_scenarios.contains(scenario) {
634            return Err(AuthError::auth_method(
635                "token_exchange",
636                "Exchange scenario not allowed",
637            ));
638        }
639
640        match scenario {
641            ExchangeScenario::OnBehalfOf => {
642                if policy.require_actor_for_delegation && context.actor_claims.is_none() {
643                    return Err(AuthError::auth_method(
644                        "token_exchange",
645                        "Actor token required for delegation",
646                    ));
647                }
648            }
649            ExchangeScenario::AudienceRestriction => {
650                if let Some(ref audience) = context.audience
651                    && !policy.allowed_audiences.is_empty()
652                    && !policy.allowed_audiences.contains(audience)
653                {
654                    return Err(AuthError::auth_method(
655                        "token_exchange",
656                        "Audience not allowed",
657                    ));
658                }
659            }
660            _ => {
661                // Other scenarios don't need special validation for now
662            }
663        }
664
665        Ok(())
666    }
667
668    /// Generate exchanged token
669    async fn generate_exchanged_token(
670        &self,
671        context: &TokenExchangeContext,
672        request: &TokenExchangeRequest,
673        policy: &TokenExchangePolicy,
674    ) -> Result<TokenExchangeResponse> {
675        let now = Utc::now();
676        let expires_in = policy.max_token_lifetime.num_seconds();
677        let exp = now + policy.max_token_lifetime;
678
679        // Create new claims based on exchange scenario
680        let mut new_claims = context.subject_claims.clone();
681
682        // Update expiration
683        new_claims.exp = exp.timestamp();
684        new_claims.iat = now.timestamp();
685        new_claims.jti = uuid::Uuid::new_v4().to_string();
686
687        // Update audience if specified
688        if let Some(ref audience) = request.audience {
689            new_claims.aud = audience.clone();
690        }
691
692        // Update scope if specified and apply mapping
693        if let Some(ref requested_scope) = request.scope {
694            if let Some(mapped_scopes) = policy.scope_mapping.get(requested_scope) {
695                new_claims.scope = mapped_scopes.join(" ");
696            } else {
697                new_claims.scope = requested_scope.clone();
698            }
699        }
700
701        // Add actor information for delegation
702        if let Some(ref actor_claims) = context.actor_claims {
703            new_claims.client_id = Some(actor_claims.sub.clone());
704        }
705
706        // Generate JWT (simplified - would use proper signing in production)
707        let access_token = format!(
708            "exchanged_token_{}_{}",
709            new_claims.jti,
710            URL_SAFE_NO_PAD.encode(&new_claims.sub)
711        );
712
713        // Determine issued token type
714        let issued_token_type = request
715            .requested_token_type
716            .clone()
717            .unwrap_or_else(|| "urn:ietf:params:oauth:token-type:access_token".to_string());
718
719        Ok(TokenExchangeResponse {
720            access_token,
721            token_type: "Bearer".to_string(),
722            expires_in: Some(expires_in),
723            refresh_token: None, // Could generate refresh token in some scenarios
724            scope: Some(new_claims.scope),
725            issued_token_type: Some(issued_token_type),
726        })
727    }
728
729    /// Get appropriate JWT decoding key for token validation
730    fn get_jwt_decoding_key(&self, token: &str) -> Result<jsonwebtoken::DecodingKey> {
731        use jsonwebtoken::DecodingKey;
732
733        // Extract JWT header to determine key ID and algorithm
734        let token_parts: Vec<&str> = token.split('.').collect();
735        if token_parts.len() < 2 {
736            return Err(AuthError::InvalidToken("Invalid JWT format".to_string()));
737        }
738
739        let header_b64 = token_parts[0];
740        let header_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
741            .decode(header_b64)
742            .map_err(|_| AuthError::InvalidToken("Invalid JWT header encoding".to_string()))?;
743
744        let header: serde_json::Value = serde_json::from_slice(&header_bytes)
745            .map_err(|_| AuthError::InvalidToken("Invalid JWT header JSON".to_string()))?;
746
747        // In production, this would:
748        // 1. Extract 'kid' (key ID) from header
749        // 2. Look up appropriate key from JWKS endpoint or key store
750        // 3. Support multiple algorithms (RS256, ES256, etc.)
751
752        let algorithm = header
753            .get("alg")
754            .and_then(|a| a.as_str())
755            .unwrap_or("HS256");
756
757        match algorithm {
758            "HS256" => {
759                // Load HMAC secret from configuration
760                let secret = std::env::var("JWT_HMAC_SECRET")
761                    .unwrap_or_else(|_| "default_hmac_secret_for_development".to_string());
762                Ok(DecodingKey::from_secret(secret.as_bytes()))
763            }
764            "RS256" => {
765                // Load RSA public key from configuration or JWKS
766                let public_key_pem = std::env::var("JWT_RSA_PUBLIC_KEY")
767                    .unwrap_or_else(|_| include_str!("../../../public.pem").to_string());
768                DecodingKey::from_rsa_pem(public_key_pem.as_bytes())
769                    .map_err(|e| AuthError::InvalidToken(format!("Invalid RSA key: {}", e)))
770            }
771            _ => {
772                // Fallback for development
773                Ok(DecodingKey::from_secret("fallback_secret".as_bytes()))
774            }
775        }
776    }
777}
778
779impl Default for TokenExchangePolicy {
780    fn default() -> Self {
781        Self {
782            allowed_subject_token_types: vec![
783                TokenType::AccessToken,
784                TokenType::RefreshToken,
785                TokenType::IdToken,
786            ],
787            allowed_actor_token_types: vec![TokenType::AccessToken, TokenType::IdToken],
788            allowed_scenarios: vec![
789                ExchangeScenario::ActingAs,
790                ExchangeScenario::OnBehalfOf,
791                ExchangeScenario::AudienceRestriction,
792                ExchangeScenario::ScopeReduction,
793            ],
794            max_token_lifetime: Duration::hours(1),
795            require_actor_for_delegation: true,
796            allowed_audiences: Vec::new(), // Empty means all audiences allowed
797            scope_mapping: HashMap::new(),
798        }
799    }
800}
801
802/// Implementation of the common TokenExchangeService trait
803#[async_trait]
804impl TokenExchangeService for TokenExchangeManager {
805    type Request = (TokenExchangeRequest, String); // Request + client_id
806    type Response = TokenExchangeResponse;
807    type Config = SecureJwtValidator; // Configuration is the JWT validator
808
809    /// Exchange a token following RFC 8693 (basic implementation)
810    async fn exchange_token(&self, request: Self::Request) -> Result<Self::Response> {
811        let (token_request, client_id) = request;
812        self.exchange_token(token_request, &client_id).await
813    }
814
815    /// Validate a token using the internal JWT validator
816    async fn validate_token(&self, token: &str, token_type: &str) -> Result<TokenValidationResult> {
817        // Use shared validation utilities
818        let supported_types = self.supported_subject_token_types();
819        ValidationUtils::validate_token_type(token_type, &supported_types)?;
820
821        match self.parse_token_type(token_type)? {
822            TokenType::Jwt | TokenType::AccessToken | TokenType::IdToken => {
823                // Load proper JWT validation key from configuration
824                let decoding_key = self.get_jwt_decoding_key(token)?;
825
826                match self
827                    .jwt_validator
828                    .validate_token(token, &decoding_key, true)
829                {
830                    Ok(claims) => {
831                        // Convert timestamp to DateTime
832                        use chrono::{TimeZone, Utc};
833                        let expires_at = Utc.timestamp_opt(claims.exp, 0).single();
834
835                        // Convert audience string to vector
836                        let audience = if claims.aud.is_empty() {
837                            Vec::new()
838                        } else {
839                            vec![claims.aud.clone()]
840                        };
841
842                        // Extract scopes from scope string
843                        let scopes = if claims.scope.is_empty() {
844                            Vec::new()
845                        } else {
846                            claims
847                                .scope
848                                .split_whitespace()
849                                .map(|s| s.to_string())
850                                .collect()
851                        };
852
853                        // Create metadata from available claims
854                        let mut metadata = HashMap::new();
855                        metadata.insert(
856                            "sub".to_string(),
857                            serde_json::Value::String(claims.sub.clone()),
858                        );
859                        metadata.insert(
860                            "iss".to_string(),
861                            serde_json::Value::String(claims.iss.clone()),
862                        );
863                        metadata.insert(
864                            "aud".to_string(),
865                            serde_json::Value::String(claims.aud.clone()),
866                        );
867                        metadata.insert(
868                            "scope".to_string(),
869                            serde_json::Value::String(claims.scope.clone()),
870                        );
871                        metadata.insert(
872                            "typ".to_string(),
873                            serde_json::Value::String(claims.typ.clone()),
874                        );
875                        if let Some(ref sid) = claims.sid {
876                            metadata
877                                .insert("sid".to_string(), serde_json::Value::String(sid.clone()));
878                        }
879                        if let Some(ref client_id) = claims.client_id {
880                            metadata.insert(
881                                "client_id".to_string(),
882                                serde_json::Value::String(client_id.clone()),
883                            );
884                        }
885
886                        Ok(TokenValidationResult {
887                            is_valid: true,
888                            subject: Some(claims.sub),
889                            issuer: Some(claims.iss),
890                            audience,
891                            scopes,
892                            expires_at,
893                            metadata,
894                            validation_messages: Vec::new(),
895                        })
896                    }
897                    Err(e) => Ok(TokenValidationResult {
898                        is_valid: false,
899                        subject: None,
900                        issuer: None,
901                        audience: Vec::new(),
902                        scopes: Vec::new(),
903                        expires_at: None,
904                        metadata: HashMap::new(),
905                        validation_messages: vec![format!("JWT validation failed: {}", e)],
906                    }),
907                }
908            }
909            TokenType::Saml2 | TokenType::Saml1 => {
910                // Basic SAML validation (simplified)
911                Ok(TokenValidationResult {
912                    is_valid: true, // Simplified validation
913                    subject: None,  // Would extract from SAML assertion
914                    issuer: None,   // Would extract from SAML assertion
915                    audience: Vec::new(),
916                    scopes: Vec::new(),
917                    expires_at: None,
918                    metadata: HashMap::new(),
919                    validation_messages: vec!["SAML validation not fully implemented".to_string()],
920                })
921            }
922            _ => Err(AuthError::InvalidRequest(format!(
923                "Token validation not supported for type: {}",
924                token_type
925            ))),
926        }
927    }
928
929    /// Get supported subject token types
930    fn supported_subject_token_types(&self) -> Vec<String> {
931        Self::SUBJECT_TOKEN_TYPES
932            .iter()
933            .map(|s| s.to_string())
934            .collect()
935    }
936
937    /// Get supported requested token types
938    fn supported_requested_token_types(&self) -> Vec<String> {
939        Self::REQUESTED_TOKEN_TYPES
940            .iter()
941            .map(|s| s.to_string())
942            .collect()
943    }
944
945    /// Get service capabilities
946    fn capabilities(&self) -> TokenExchangeCapabilities {
947        TokenExchangeCapabilities {
948            basic_exchange: true,
949            multi_party_chains: false,
950            context_preservation: false,
951            audit_trail: false,
952            session_integration: false,
953            jwt_operations: false,
954            policy_control: true,
955            cross_domain_exchange: false,
956            max_delegation_depth: 3,
957            complexity_level: ServiceComplexityLevel::Basic,
958        }
959    }
960}
961
962#[cfg(test)]
963mod tests {
964    use super::*;
965    use crate::security::secure_jwt::SecureJwtConfig;
966
967    fn create_test_manager() -> TokenExchangeManager {
968        let jwt_config = SecureJwtConfig::default();
969        let jwt_validator = SecureJwtValidator::new(jwt_config);
970        TokenExchangeManager::new(jwt_validator)
971    }
972
973    fn create_test_request() -> TokenExchangeRequest {
974        TokenExchangeRequest {
975            grant_type: "urn:ietf:params:oauth:grant-type:token-exchange".to_string(),
976            subject_token: "dummy.jwt.token".to_string(),
977            subject_token_type: "urn:ietf:params:oauth:token-type:access_token".to_string(),
978            actor_token: None,
979            actor_token_type: None,
980            requested_token_type: Some("urn:ietf:params:oauth:token-type:access_token".to_string()),
981            audience: Some("api.example.com".to_string()),
982            scope: Some("read write".to_string()),
983            resource: None,
984        }
985    }
986
987    #[tokio::test]
988    async fn test_token_exchange_manager_creation() {
989        let manager = create_test_manager();
990
991        // Register a policy
992        let policy = TokenExchangePolicy::default();
993        manager
994            .register_policy("test_client".to_string(), policy)
995            .await;
996    }
997
998    #[test]
999    fn test_token_type_parsing() {
1000        let manager = create_test_manager();
1001
1002        assert_eq!(
1003            manager
1004                .parse_token_type("urn:ietf:params:oauth:token-type:access_token")
1005                .unwrap(),
1006            TokenType::AccessToken
1007        );
1008
1009        assert_eq!(
1010            manager
1011                .parse_token_type("urn:ietf:params:oauth:token-type:id_token")
1012                .unwrap(),
1013            TokenType::IdToken
1014        );
1015
1016        assert!(manager.parse_token_type("invalid_token_type").is_err());
1017    }
1018
1019    #[test]
1020    fn test_exchange_scenario_determination() {
1021        let manager = create_test_manager();
1022        let policy = TokenExchangePolicy::default();
1023
1024        // Test audience restriction scenario
1025        let context = TokenExchangeContext {
1026            subject_claims: SecureJwtClaims {
1027                sub: "user123".to_string(),
1028                iss: "auth.example.com".to_string(),
1029                aud: "api.example.com".to_string(),
1030                exp: chrono::Utc::now().timestamp() + 3600,
1031                nbf: chrono::Utc::now().timestamp(),
1032                iat: chrono::Utc::now().timestamp(),
1033                jti: "token123".to_string(),
1034                scope: "read write".to_string(),
1035                typ: "access".to_string(),
1036                sid: None,
1037                client_id: None,
1038                auth_ctx_hash: None,
1039            },
1040            actor_claims: None,
1041            client_id: "test_client".to_string(),
1042            audience: Some("different.api.com".to_string()),
1043            scope: None,
1044            resource: None,
1045        };
1046
1047        let scenario = manager
1048            .determine_exchange_scenario(&context, &policy)
1049            .unwrap();
1050        assert_eq!(scenario, ExchangeScenario::AudienceRestriction);
1051    }
1052
1053    #[tokio::test]
1054    async fn test_invalid_grant_type() {
1055        let manager = create_test_manager();
1056        let policy = TokenExchangePolicy::default();
1057        manager
1058            .register_policy("test_client".to_string(), policy)
1059            .await;
1060
1061        let mut request = create_test_request();
1062        request.grant_type = "invalid_grant_type".to_string();
1063
1064        let result = manager.exchange_token(request, "test_client").await;
1065        assert!(result.is_err());
1066    }
1067}