1use 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#[derive(Clone, Serialize, Deserialize)]
72pub struct TokenExchangeRequest {
73 pub grant_type: String,
75
76 pub subject_token: String,
78
79 pub subject_token_type: String,
81
82 pub actor_token: Option<String>,
84
85 pub actor_token_type: Option<String>,
87
88 pub requested_token_type: Option<String>,
90
91 pub audience: Option<String>,
93
94 pub scope: Option<String>,
96
97 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#[derive(Clone, Serialize, Deserialize)]
125pub struct TokenExchangeResponse {
126 pub access_token: String,
128
129 pub token_type: String,
131
132 pub expires_in: Option<i64>,
134
135 pub refresh_token: Option<String>,
137
138 pub scope: Option<String>,
140
141 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166pub enum TokenType {
167 #[serde(rename = "urn:ietf:params:oauth:token-type:access_token")]
169 AccessToken,
170
171 #[serde(rename = "urn:ietf:params:oauth:token-type:refresh_token")]
173 RefreshToken,
174
175 #[serde(rename = "urn:ietf:params:oauth:token-type:id_token")]
177 IdToken,
178
179 #[serde(rename = "urn:ietf:params:oauth:token-type:saml2")]
181 Saml2,
182
183 #[serde(rename = "urn:ietf:params:oauth:token-type:saml1")]
185 Saml1,
186
187 #[serde(rename = "urn:ietf:params:oauth:token-type:jwt")]
189 Jwt,
190}
191
192#[derive(Debug, Clone)]
194pub struct TokenExchangeContext {
195 pub subject_claims: SecureJwtClaims,
197
198 pub actor_claims: Option<SecureJwtClaims>,
200
201 pub client_id: String,
203
204 pub audience: Option<String>,
206
207 pub scope: Option<Vec<String>>,
209
210 pub resource: Option<String>,
212}
213
214#[derive(Debug, Clone)]
216pub struct TokenExchangePolicy {
217 pub allowed_subject_token_types: Vec<TokenType>,
219
220 pub allowed_actor_token_types: Vec<TokenType>,
222
223 pub allowed_scenarios: Vec<ExchangeScenario>,
225
226 pub max_token_lifetime: Duration,
228
229 pub require_actor_for_delegation: bool,
231
232 pub allowed_audiences: Vec<String>,
234
235 pub scope_mapping: HashMap<String, Vec<String>>,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq)]
241pub enum ExchangeScenario {
242 ActingAs,
244
245 OnBehalfOf,
247
248 TokenConversion,
250
251 AudienceRestriction,
253
254 ScopeReduction,
256}
257
258pub struct TokenExchangeManager {
260 jwt_validator: SecureJwtValidator,
262
263 policies: tokio::sync::RwLock<HashMap<String, TokenExchangePolicy>>,
265
266 active_exchanges: tokio::sync::RwLock<HashMap<String, TokenExchangeContext>>,
268}
269
270impl TokenExchangeManager {
271 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 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 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 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 pub async fn exchange_token(
303 &self,
304 request: TokenExchangeRequest,
305 client_id: &str,
306 ) -> Result<TokenExchangeResponse> {
307 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 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 let subject_claims = self.validate_subject_token(&request, policy).await?;
323
324 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 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 let scenario = self.determine_exchange_scenario(&context, policy)?;
349 self.validate_exchange_scenario(&scenario, &context, policy)?;
350
351 let response = self
353 .generate_exchanged_token(&context, &request, policy)
354 .await?;
355
356 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 async fn validate_subject_token(
366 &self,
367 request: &TokenExchangeRequest,
368 policy: &TokenExchangePolicy,
369 ) -> Result<SecureJwtClaims> {
370 let token_type = self.parse_token_type(&request.subject_token_type)?;
372
373 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 match token_type {
383 TokenType::AccessToken
384 | TokenType::RefreshToken
385 | TokenType::IdToken
386 | TokenType::Jwt => {
387 self.validate_jwt_token(&request.subject_token).await
390 }
391 TokenType::Saml2 | TokenType::Saml1 => {
392 self.validate_saml_token(&request.subject_token, &token_type)
394 .await
395 }
396 }
397 }
398
399 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 async fn validate_jwt_token(&self, token: &str) -> Result<SecureJwtClaims> {
424 let decoding_key = self.jwt_validator.get_decoding_key();
427
428 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 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 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 fn determine_exchange_scenario(
470 &self,
471 context: &TokenExchangeContext,
472 _policy: &TokenExchangePolicy,
473 ) -> Result<ExchangeScenario> {
474 if context.actor_claims.is_some() {
476 return Ok(ExchangeScenario::OnBehalfOf);
477 }
478
479 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 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 Ok(ExchangeScenario::ActingAs)
496 }
497
498 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 }
535 }
536
537 Ok(())
538 }
539
540 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 let mut new_claims = context.subject_claims.clone();
553
554 new_claims.exp = exp.timestamp();
556 new_claims.iat = now.timestamp();
557 new_claims.jti = uuid::Uuid::new_v4().to_string();
558
559 if let Some(ref audience) = request.audience {
561 new_claims.aud = audience.clone();
562 }
563
564 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 if let Some(ref actor_claims) = context.actor_claims {
575 new_claims.client_id = Some(actor_claims.sub.clone());
576 }
577
578 let access_token = format!(
580 "exchanged_token_{}_{}",
581 new_claims.jti,
582 URL_SAFE_NO_PAD.encode(&new_claims.sub)
583 );
584
585 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, scope: Some(new_claims.scope),
597 issued_token_type: Some(issued_token_type),
598 })
599 }
600
601 fn get_jwt_decoding_key(&self, token: &str) -> Result<jsonwebtoken::DecodingKey> {
603 use jsonwebtoken::DecodingKey;
604
605 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 let algorithm = header
625 .get("alg")
626 .and_then(|a| a.as_str())
627 .unwrap_or("HS256");
628
629 match algorithm {
630 "HS256" => {
631 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 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 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(), scope_mapping: HashMap::new(),
670 }
671 }
672}
673
674#[async_trait]
676impl TokenExchangeService for TokenExchangeManager {
677 type Request = (TokenExchangeRequest, String); type Response = TokenExchangeResponse;
679 type Config = SecureJwtValidator; 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 async fn validate_token(&self, token: &str, token_type: &str) -> Result<TokenValidationResult> {
689 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 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 use chrono::{TimeZone, Utc};
705 let expires_at = Utc.timestamp_opt(claims.exp, 0).single();
706
707 let audience = if claims.aud.is_empty() {
709 Vec::new()
710 } else {
711 vec![claims.aud.clone()]
712 };
713
714 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 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 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 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 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 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 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 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}