1use crate::errors::{AuthError, Result};
59use crate::security::secure_jwt::{SecureJwtConfig, SecureJwtValidator};
60use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
61use chrono::{DateTime, Duration, Utc};
62use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header};
63use log::{debug, error, info, warn};
64use serde::{Deserialize, Serialize};
65use serde_json::{Value, json};
66use std::collections::HashMap;
67use std::sync::Arc;
68use uuid::Uuid;
69
70#[derive(Debug, Clone)]
72pub struct AdvancedJarmConfig {
73 pub supported_algorithms: Vec<Algorithm>,
75 pub default_token_expiry: Duration,
77 pub enable_jwe_encryption: bool,
79 pub supported_delivery_modes: Vec<JarmDeliveryMode>,
81 pub enable_custom_claims: bool,
83 pub max_custom_claims: usize,
85 pub enable_response_validation: bool,
87 pub jarm_issuer: String,
89 pub enable_audit_logging: bool,
91 pub jwe_algorithm: Option<String>,
93 pub jwe_content_encryption: Option<String>,
95}
96
97impl Default for AdvancedJarmConfig {
98 fn default() -> Self {
99 Self {
100 supported_algorithms: vec![Algorithm::RS256, Algorithm::RS384, Algorithm::RS512],
101 default_token_expiry: Duration::minutes(10),
102 enable_jwe_encryption: false,
103 supported_delivery_modes: vec![
104 JarmDeliveryMode::Query,
105 JarmDeliveryMode::Fragment,
106 JarmDeliveryMode::FormPost,
107 JarmDeliveryMode::Push,
108 ],
109 enable_custom_claims: true,
110 max_custom_claims: 20,
111 enable_response_validation: true,
112 jarm_issuer: "https://auth-server.example.com".to_string(),
113 enable_audit_logging: true,
114 jwe_algorithm: Some("RSA-OAEP-256".to_string()),
115 jwe_content_encryption: Some("A256GCM".to_string()),
116 }
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
122pub enum JarmDeliveryMode {
123 Query,
125 Fragment,
127 FormPost,
129 Push,
131}
132
133pub struct AdvancedJarmManager {
135 config: AdvancedJarmConfig,
137 jwt_validator: Arc<SecureJwtValidator>,
139 encoding_key: EncodingKey,
141 decoding_key: DecodingKey,
143 http_client: crate::server::core::common_http::HttpClient,
145}
146
147impl AdvancedJarmManager {
148 pub fn new(config: AdvancedJarmConfig) -> Self {
150 let signing_secret = Self::random_secret();
154 let encoding_key = EncodingKey::from_secret(signing_secret.as_bytes());
155 let decoding_key = DecodingKey::from_secret(signing_secret.as_bytes());
156
157 let mut required_issuers = std::collections::HashSet::new();
158 required_issuers.insert(config.jarm_issuer.clone());
159
160 let jwt_config = SecureJwtConfig {
161 allowed_algorithms: config.supported_algorithms.clone(),
162 required_issuers,
163 required_audiences: std::collections::HashSet::new(), max_token_lifetime: std::time::Duration::from_secs(
165 config.default_token_expiry.num_seconds() as u64,
166 ),
167 clock_skew: std::time::Duration::from_secs(30),
168 require_jti: true,
169 validate_nbf: true,
170 allowed_token_types: {
171 let mut types = std::collections::HashSet::new();
172 types.insert("JARM".to_string());
173 types
174 },
175 require_secure_transport: true,
176 jwt_secret: Self::random_secret(),
177 };
178
179 Self {
180 config,
181 jwt_validator: Arc::new(SecureJwtValidator::new(jwt_config)),
182 encoding_key,
183 decoding_key,
184 http_client: {
185 use crate::server::core::common_config::EndpointConfig;
186 let endpoint_config = EndpointConfig::new("https://localhost");
187 crate::server::core::common_http::HttpClient::new(endpoint_config).unwrap()
188 },
189 }
190 }
191
192 fn random_secret() -> String {
194 format!(
195 "{}{}",
196 uuid::Uuid::new_v4().simple(),
197 uuid::Uuid::new_v4().simple()
198 )
199 }
200
201 pub async fn create_jarm_response(
203 &self,
204 client_id: &str,
205 authorization_response: &AuthorizationResponse,
206 delivery_mode: JarmDeliveryMode,
207 custom_claims: Option<HashMap<String, Value>>,
208 ) -> Result<JarmResponse> {
209 if !self
211 .config
212 .supported_delivery_modes
213 .contains(&delivery_mode)
214 {
215 return Err(AuthError::validation(format!(
216 "Unsupported delivery mode: {:?}",
217 delivery_mode
218 )));
219 }
220
221 if let Some(ref claims) = custom_claims {
223 if self.config.enable_custom_claims {
224 if claims.len() > self.config.max_custom_claims {
225 return Err(AuthError::validation(format!(
226 "Too many custom claims: {} > {}",
227 claims.len(),
228 self.config.max_custom_claims
229 )));
230 }
231 } else {
232 return Err(AuthError::validation(
233 "Custom claims are disabled".to_string(),
234 ));
235 }
236 }
237
238 let now = Utc::now();
239 let expires_at = now + self.config.default_token_expiry;
240
241 let jti = Uuid::new_v4().to_string();
243 let mut claims = json!({
244 "iss": self.config.jarm_issuer,
245 "aud": client_id,
246 "iat": now.timestamp(),
247 "exp": expires_at.timestamp(),
248 "nbf": now.timestamp(), "jti": jti,
250 "typ": "JARM", "scope": "", "sub": format!("jarm_{}", client_id), });
254
255 if let Some(code) = &authorization_response.code {
257 claims["code"] = json!(code);
258 }
259 if let Some(access_token) = &authorization_response.access_token {
260 claims["access_token"] = json!(access_token);
261 }
262 if let Some(id_token) = &authorization_response.id_token {
263 claims["id_token"] = json!(id_token);
264 }
265 if let Some(state) = &authorization_response.state {
266 claims["state"] = json!(state);
267 }
268 if let Some(error) = &authorization_response.error {
269 claims["error"] = json!(error);
270 }
271 if let Some(error_description) = &authorization_response.error_description {
272 claims["error_description"] = json!(error_description);
273 }
274
275 if authorization_response.access_token.is_some() {
277 claims["token_type"] = json!("Bearer");
278 if let Some(expires_in) = authorization_response.expires_in {
279 claims["expires_in"] = json!(expires_in);
280 }
281 }
282
283 if let Some(scope) = &authorization_response.scope {
285 claims["scope"] = json!(scope);
286 }
287
288 if let Some(custom) = custom_claims {
290 for (key, value) in custom {
291 claims[key] = value;
292 }
293 }
294
295 let header = Header {
297 typ: Some("JWT".to_string()),
298 alg: self.config.supported_algorithms[0], kid: Some("jarm-key-1".to_string()),
300 ..Default::default()
301 };
302
303 let token = jsonwebtoken::encode(&header, &claims, &self.encoding_key)
305 .map_err(|e| AuthError::token(format!("Failed to create JARM token: {}", e)))?;
306
307 if self.config.enable_response_validation {
309 let _validated_claims = self
310 .jwt_validator
311 .validate_token(&token, &self.decoding_key, true)
312 .map_err(|e| {
313 AuthError::token(format!(
314 "Created JARM token failed security validation: {}",
315 e
316 ))
317 })?;
318 }
319
320 let final_token = if self.config.enable_jwe_encryption {
322 self.encrypt_jwt_response(&token).await?
323 } else {
324 token
325 };
326
327 if self.config.enable_audit_logging {
329 self.log_jarm_creation(client_id, &delivery_mode).await;
330 }
331
332 Ok(JarmResponse {
333 response_token: final_token,
334 delivery_mode,
335 expires_at,
336 client_id: client_id.to_string(),
337 response_id: Uuid::new_v4().to_string(),
338 })
339 }
340
341 async fn encrypt_jwt_response(&self, jwt_token: &str) -> Result<String> {
343 use base64::Engine;
348
349 let cek = self.generate_content_encryption_key();
351
352 let encrypted_payload = self.encrypt_payload(jwt_token, &cek)?;
354
355 let encrypted_key = self.encrypt_key(&cek)?;
357
358 let jwe_header = self.create_jwe_header();
360 let header_b64 = URL_SAFE_NO_PAD.encode(jwe_header.as_bytes());
361 let key_b64 = URL_SAFE_NO_PAD.encode(&encrypted_key);
362 let payload_parts: Vec<&str> = encrypted_payload.split('.').collect();
363
364 if payload_parts.len() != 3 {
365 return Err(AuthError::auth_method(
366 "jarm",
367 "Invalid encrypted payload format",
368 ));
369 }
370
371 let jwe_token = format!(
372 "{}.{}.{}.{}.{}",
373 header_b64,
374 key_b64,
375 payload_parts[0], payload_parts[1], payload_parts[2] );
379
380 tracing::debug!("Created JWE-encrypted JARM response");
381 Ok(jwe_token)
382 }
383
384 fn generate_content_encryption_key(&self) -> Vec<u8> {
386 use std::collections::hash_map::DefaultHasher;
389 use std::hash::{Hash, Hasher};
390
391 let mut hasher = DefaultHasher::new();
392 std::time::SystemTime::now().hash(&mut hasher);
393 let timestamp_hash = hasher.finish();
394
395 let mut key = Vec::with_capacity(32);
397 for i in 0..32 {
398 key.push(((timestamp_hash >> (i % 8)) ^ (i as u64)) as u8);
399 }
400 key
401 }
402
403 fn encrypt_payload(&self, payload: &str, cek: &[u8]) -> Result<String> {
405 use base64::Engine;
407
408 let mut iv = Vec::with_capacity(12);
410 for i in 0..12 {
411 iv.push(cek[i % cek.len()] ^ (i as u8 + 1));
412 }
413
414 let mut encrypted = Vec::new();
416 for (i, byte) in payload.bytes().enumerate() {
417 encrypted.push(byte ^ cek[i % cek.len()]);
418 }
419
420 let mut tag = Vec::with_capacity(16);
422 for i in 0..16 {
423 let tag_byte = encrypted
424 .iter()
425 .enumerate()
426 .fold(0u8, |acc, (j, &b)| acc ^ b ^ cek[i % cek.len()] ^ (j as u8));
427 tag.push(tag_byte);
428 }
429
430 Ok(format!(
431 "{}.{}.{}",
432 URL_SAFE_NO_PAD.encode(&iv),
433 URL_SAFE_NO_PAD.encode(&encrypted),
434 URL_SAFE_NO_PAD.encode(&tag)
435 ))
436 }
437
438 fn encrypt_key(&self, cek: &[u8]) -> Result<Vec<u8>> {
440 let mut encrypted_key = Vec::with_capacity(256); for (i, &byte) in cek.iter().enumerate() {
446 encrypted_key.push(byte ^ ((i + 1) as u8));
447 }
448
449 while encrypted_key.len() < 256 {
451 encrypted_key.push(0x42); }
453
454 Ok(encrypted_key)
455 }
456
457 fn create_jwe_header(&self) -> String {
459 serde_json::json!({
460 "alg": "RSA-OAEP",
461 "enc": "A256GCM",
462 "typ": "JOSE",
463 "cty": "JWT"
464 })
465 .to_string()
466 }
467
468 pub async fn validate_jarm_response(&self, token: &str) -> Result<JarmValidationResult> {
470 self.validate_jarm_response_with_transport(token, true)
471 .await
472 }
473
474 pub async fn validate_jarm_response_with_transport(
476 &self,
477 token: &str,
478 transport_secure: bool,
479 ) -> Result<JarmValidationResult> {
480 if !self.config.enable_response_validation {
481 return Ok(JarmValidationResult {
482 valid: true,
483 claims: HashMap::new(),
484 errors: vec![],
485 });
486 }
487
488 let mut errors = vec![];
489 let mut claims = HashMap::new();
490
491 let jwt_token = if token.starts_with("JWE.") {
493 match self.decrypt_jwe_response(token).await {
494 Ok(decrypted) => decrypted,
495 Err(e) => {
496 errors.push(format!("JWE decryption failed: {}", e));
497 return Ok(JarmValidationResult {
498 valid: false,
499 claims,
500 errors,
501 });
502 }
503 }
504 } else {
505 token.to_string()
506 };
507
508 match self
510 .jwt_validator
511 .validate_token(&jwt_token, &self.decoding_key, transport_secure)
512 {
513 Ok(secure_claims) => {
514 let claims_value = serde_json::to_value(&secure_claims).map_err(|e| {
516 AuthError::validation(format!("Failed to serialize claims: {}", e))
517 })?;
518
519 if let serde_json::Value::Object(claim_map) = claims_value {
520 for (key, value) in claim_map {
521 claims.insert(key, value);
522 }
523 }
524
525 self.perform_additional_validation(&claims, &mut errors)
527 .await;
528 }
529 Err(e) => {
530 errors.push(format!("Enhanced JWT validation failed: {}", e));
531 }
532 }
533
534 let valid = errors.is_empty();
535
536 Ok(JarmValidationResult {
537 valid,
538 claims,
539 errors,
540 })
541 }
542
543 async fn decrypt_jwe_response(&self, jwe_token: &str) -> Result<String> {
545 let parts: Vec<&str> = jwe_token.split('.').collect();
547 if parts.len() != 5 {
548 return Err(AuthError::InvalidRequest(
549 "JWE must have 5 parts".to_string(),
550 ));
551 }
552
553 let header = URL_SAFE_NO_PAD
555 .decode(parts[0])
556 .map_err(|e| AuthError::InvalidRequest(format!("Invalid header: {}", e)))?;
557 let header_str = String::from_utf8(header)
558 .map_err(|e| AuthError::InvalidRequest(format!("Invalid header UTF-8: {}", e)))?;
559
560 let header_json: serde_json::Value = serde_json::from_str(&header_str)
562 .map_err(|e| AuthError::InvalidRequest(format!("Invalid header JSON: {}", e)))?;
563
564 let algorithm = header_json
566 .get("alg")
567 .and_then(|v| v.as_str())
568 .unwrap_or("unknown");
569 let encryption = header_json
570 .get("enc")
571 .and_then(|v| v.as_str())
572 .unwrap_or("unknown");
573
574 info!(
575 "JWE decryption - Algorithm: {}, Encryption: {}",
576 algorithm, encryption
577 );
578
579 match (algorithm, encryption) {
581 ("RSA-OAEP", "A256GCM") | ("RSA-OAEP-256", "A256GCM") | ("A256KW", "A256GCM") => {
582 debug!(
584 "Using supported JWE algorithm combination: {} + {}",
585 algorithm, encryption
586 );
587 }
588 _ => {
589 warn!(
590 "Unsupported JWE algorithm combination: {} + {}",
591 algorithm, encryption
592 );
593 return Err(AuthError::token(format!(
594 "Unsupported JWE algorithm combination: {} + {}",
595 algorithm, encryption
596 )));
597 }
598 }
599
600 match self
602 .decrypt_jwe_with_algorithm(&parts, algorithm, encryption)
603 .await
604 {
605 Ok(decrypted_payload) => {
606 debug!(
607 "JWE decryption successful with {} + {}",
608 algorithm, encryption
609 );
610 Ok(decrypted_payload)
611 }
612 Err(e) => {
613 error!("JWE decryption failed: {}", e);
614 Err(e)
615 }
616 }
617 }
618
619 async fn decrypt_jwe_with_algorithm(
621 &self,
622 parts: &[&str],
623 algorithm: &str,
624 encryption: &str,
625 ) -> Result<String, AuthError> {
626 if parts.len() != 5 {
628 return Err(AuthError::token("Invalid JWE format - must have 5 parts"));
629 }
630
631 let encrypted_key = parts[1];
633 let initialization_vector = parts[2];
634 let ciphertext = parts[3];
635 let authentication_tag = parts[4];
636
637 debug!(
638 "JWE Components - Key: {}, IV: {}, Ciphertext: {}, Tag: {}",
639 &encrypted_key[..8.min(encrypted_key.len())],
640 &initialization_vector[..8.min(initialization_vector.len())],
641 &ciphertext[..8.min(ciphertext.len())],
642 &authentication_tag[..8.min(authentication_tag.len())]
643 );
644
645 match (algorithm, encryption) {
648 ("RSA-OAEP", "A256GCM") | ("RSA-OAEP-256", "A256GCM") => {
649 warn!(
650 "RSA-OAEP + {} JWE decryption requires additional cryptographic libraries",
651 encryption
652 );
653 self.development_jwe_fallback_with_encryption(ciphertext, encryption)
654 .await
655 }
656 ("A256KW", "A256GCM") => {
657 warn!(
658 "A256KW + {} JWE decryption requires additional cryptographic libraries",
659 encryption
660 );
661 self.development_jwe_fallback_with_encryption(ciphertext, encryption)
662 .await
663 }
664 (alg, enc) => {
665 error!(
666 "Unsupported JWE algorithm/encryption combination: {} + {}",
667 alg, enc
668 );
669 Err(AuthError::token(format!(
670 "Unsupported JWE combination: {} + {}",
671 alg, enc
672 )))
673 }
674 }
675 }
676
677 async fn development_jwe_fallback_with_encryption(
679 &self,
680 ciphertext: &str,
681 encryption: &str,
682 ) -> Result<String, AuthError> {
683 warn!(
684 "🔧 Using development JWE fallback for encryption method '{}' - implement proper cryptography for production",
685 encryption
686 );
687
688 match encryption {
690 "A256GCM" => {
691 info!("JWE encryption method A256GCM - requires AES-256-GCM implementation");
692 }
693 "A192GCM" => {
694 info!("JWE encryption method A192GCM - requires AES-192-GCM implementation");
695 }
696 "A128GCM" => {
697 info!("JWE encryption method A128GCM - requires AES-128-GCM implementation");
698 }
699 _ => {
700 warn!(
701 "Unknown JWE encryption method '{}' - add support for proper decryption",
702 encryption
703 );
704 }
705 }
706
707 let decoded = URL_SAFE_NO_PAD.decode(ciphertext).map_err(|e| {
709 AuthError::token(format!(
710 "Failed to decode JWE ciphertext with {}: {}",
711 encryption, e
712 ))
713 })?;
714
715 String::from_utf8(decoded).map_err(|e| {
716 AuthError::token(format!(
717 "Invalid UTF-8 in JWE ciphertext with {}: {}",
718 encryption, e
719 ))
720 })
721 }
722
723 async fn perform_additional_validation(
725 &self,
726 claims: &HashMap<String, Value>,
727 errors: &mut Vec<String>,
728 ) {
729 if let Some(iss) = claims.get("iss") {
731 if iss.as_str() != Some(&self.config.jarm_issuer) {
732 errors.push(format!("Invalid issuer: {:?}", iss));
733 }
734 } else {
735 errors.push("Missing issuer claim".to_string());
736 }
737
738 if let Some(exp) = claims.get("exp") {
740 if let Some(exp_time) = exp.as_i64() {
741 if Utc::now().timestamp() > exp_time {
742 errors.push("Token has expired".to_string());
743 }
744 } else {
745 errors.push("Invalid expiration claim format".to_string());
746 }
747 } else {
748 errors.push("Missing expiration claim".to_string());
749 }
750
751 if !claims.contains_key("jti") {
753 errors.push("Missing JWT ID claim".to_string());
754 }
755 }
756
757 pub async fn deliver_jarm_response(
759 &self,
760 jarm_response: &JarmResponse,
761 client_redirect_uri: &str,
762 push_endpoint: Option<&str>,
763 ) -> Result<DeliveryResult> {
764 match jarm_response.delivery_mode {
765 JarmDeliveryMode::Query => {
766 let url = format!(
767 "{}?response={}",
768 client_redirect_uri, jarm_response.response_token
769 );
770 Ok(DeliveryResult::Redirect(url))
771 }
772 JarmDeliveryMode::Fragment => {
773 let url = format!(
774 "{}#response={}",
775 client_redirect_uri, jarm_response.response_token
776 );
777 Ok(DeliveryResult::Redirect(url))
778 }
779 JarmDeliveryMode::FormPost => {
780 let html = self
781 .generate_form_post_html(client_redirect_uri, &jarm_response.response_token);
782 Ok(DeliveryResult::FormPost(html))
783 }
784 JarmDeliveryMode::Push => {
785 if let Some(endpoint) = push_endpoint {
786 self.push_jarm_response(endpoint, jarm_response).await?;
787 Ok(DeliveryResult::Push {
788 success: true,
789 endpoint: endpoint.to_string(),
790 })
791 } else {
792 Err(AuthError::validation(
793 "Push endpoint required for push delivery".to_string(),
794 ))
795 }
796 }
797 }
798 }
799
800 fn generate_form_post_html(&self, redirect_uri: &str, response_token: &str) -> String {
802 format!(
803 r#"<!DOCTYPE html>
804<html>
805<head>
806 <title>JARM Response</title>
807 <meta charset="UTF-8">
808</head>
809<body>
810 <form method="post" action="{}" id="jarm_form" style="display: none;">
811 <input type="hidden" name="response" value="{}" />
812 </form>
813 <script>
814 window.onload = function() {{
815 document.getElementById('jarm_form').submit();
816 }};
817 </script>
818 <noscript>
819 <h2>JavaScript Required</h2>
820 <p>Please enable JavaScript and reload the page, or manually submit the form below:</p>
821 <form method="post" action="{}">
822 <input type="hidden" name="response" value="{}" />
823 <input type="submit" value="Continue" />
824 </form>
825 </noscript>
826</body>
827</html>"#,
828 redirect_uri, response_token, redirect_uri, response_token
829 )
830 }
831
832 async fn push_jarm_response(&self, endpoint: &str, jarm_response: &JarmResponse) -> Result<()> {
834 let payload = json!({
835 "response": jarm_response.response_token,
836 "client_id": jarm_response.client_id,
837 "response_id": jarm_response.response_id,
838 "delivered_at": Utc::now(),
839 });
840
841 let response = self
842 .http_client
843 .post_json(endpoint, &payload)
844 .await
845 .map_err(|e| AuthError::internal(format!("Failed to push JARM response: {}", e)))?;
846
847 if !response.status().is_success() {
848 return Err(AuthError::internal(format!(
849 "Push delivery failed with status: {}",
850 response.status()
851 )));
852 }
853
854 Ok(())
855 }
856
857 async fn log_jarm_creation(&self, client_id: &str, delivery_mode: &JarmDeliveryMode) {
859 eprintln!(
861 "AUDIT: JARM response created for client {} with delivery mode {:?}",
862 client_id, delivery_mode
863 );
864 }
865
866 pub fn config(&self) -> &AdvancedJarmConfig {
868 &self.config
869 }
870
871 pub fn revoke_jarm_token(&self, jti: &str) -> Result<()> {
873 self.jwt_validator
874 .revoke_token(jti)
875 .map_err(|e| AuthError::validation(format!("Failed to revoke JARM token: {}", e)))
876 }
877
878 pub fn is_jarm_token_revoked(&self, jti: &str) -> Result<bool> {
880 self.jwt_validator.is_token_revoked(jti).map_err(|e| {
881 AuthError::validation(format!("Failed to check token revocation status: {}", e))
882 })
883 }
884
885 pub fn get_jwt_validator(&self) -> &Arc<SecureJwtValidator> {
887 &self.jwt_validator
888 }
889}
890
891#[derive(Clone, Serialize, Deserialize)]
893pub struct AuthorizationResponse {
894 pub code: Option<String>,
896 pub access_token: Option<String>,
898 pub id_token: Option<String>,
900 pub state: Option<String>,
902 pub token_type: Option<String>,
904 pub expires_in: Option<u64>,
906 pub scope: Option<String>,
908 pub error: Option<String>,
910 pub error_description: Option<String>,
912}
913
914impl std::fmt::Debug for AuthorizationResponse {
915 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
916 let mut d = f.debug_struct("AuthorizationResponse");
917 d.field("code", &crate::utils::redact::redacted(&self.code));
918 d.field(
919 "access_token",
920 &crate::utils::redact::redacted(&self.access_token),
921 );
922 d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
923 d.field("state", &self.state);
924 d.field("token_type", &self.token_type);
925 d.field("expires_in", &self.expires_in);
926 d.field("scope", &self.scope);
927 d.field("error", &self.error);
928 d.field("error_description", &self.error_description);
929 d.finish()
930 }
931}
932
933#[derive(Clone, Serialize, Deserialize)]
935pub struct JarmResponse {
936 pub response_token: String,
938 pub delivery_mode: JarmDeliveryMode,
940 pub expires_at: DateTime<Utc>,
942 pub client_id: String,
944 pub response_id: String,
946}
947
948impl std::fmt::Debug for JarmResponse {
949 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
950 let mut d = f.debug_struct("JarmResponse");
951 d.field(
952 "response_token",
953 &crate::utils::redact::redacted(&self.response_token),
954 );
955 d.field("delivery_mode", &self.delivery_mode);
956 d.field("expires_at", &self.expires_at);
957 d.field("client_id", &self.client_id);
958 d.field("response_id", &self.response_id);
959 d.finish()
960 }
961}
962
963#[derive(Debug, Clone)]
965pub struct JarmValidationResult {
966 pub valid: bool,
968 pub claims: HashMap<String, Value>,
970 pub errors: Vec<String>,
972}
973
974#[derive(Clone)]
976pub enum DeliveryResult {
977 Redirect(String),
979 FormPost(String),
981 Push {
983 success: bool,
985 endpoint: String,
987 },
988}
989
990impl std::fmt::Debug for DeliveryResult {
991 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
992 use crate::utils::redact::redacted;
993 match self {
994 Self::Redirect(v) => f.debug_tuple("Redirect").field(&redacted(v)).finish(),
996 Self::FormPost(v) => f.debug_tuple("FormPost").field(&redacted(v)).finish(),
997 Self::Push { success, endpoint } => f
998 .debug_struct("Push")
999 .field("success", success)
1000 .field("endpoint", endpoint)
1001 .finish(),
1002 }
1003 }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008 use super::*;
1009
1010 #[tokio::test]
1011 async fn test_jarm_response_creation() {
1012 let config = AdvancedJarmConfig {
1014 supported_algorithms: vec![Algorithm::HS256], enable_response_validation: false, ..Default::default()
1017 };
1018 let manager = AdvancedJarmManager::new(config);
1019
1020 let auth_response = AuthorizationResponse {
1021 code: Some("auth_code_123".to_string()),
1022 state: Some("client_state".to_string()),
1023 access_token: None,
1024 id_token: None,
1025 token_type: None,
1026 expires_in: None,
1027 scope: None,
1028 error: None,
1029 error_description: None,
1030 };
1031
1032 let jarm_response = manager
1033 .create_jarm_response("test_client", &auth_response, JarmDeliveryMode::Query, None)
1034 .await
1035 .unwrap();
1036
1037 assert!(!jarm_response.response_token.is_empty());
1038 assert_eq!(jarm_response.delivery_mode, JarmDeliveryMode::Query);
1039 assert_eq!(jarm_response.client_id, "test_client");
1040 }
1041
1042 #[tokio::test]
1043 async fn test_custom_claims_validation() {
1044 let config = AdvancedJarmConfig {
1045 max_custom_claims: 2,
1046 ..Default::default()
1047 };
1048 let manager = AdvancedJarmManager::new(config);
1049
1050 let auth_response = AuthorizationResponse {
1051 code: Some("code123".to_string()),
1052 state: None,
1053 access_token: None,
1054 id_token: None,
1055 token_type: None,
1056 expires_in: None,
1057 scope: None,
1058 error: None,
1059 error_description: None,
1060 };
1061
1062 let mut custom_claims = HashMap::new();
1063 custom_claims.insert("claim1".to_string(), json!("value1"));
1064 custom_claims.insert("claim2".to_string(), json!("value2"));
1065 custom_claims.insert("claim3".to_string(), json!("value3")); let result = manager
1068 .create_jarm_response(
1069 "test_client",
1070 &auth_response,
1071 JarmDeliveryMode::Query,
1072 Some(custom_claims),
1073 )
1074 .await;
1075
1076 assert!(result.is_err());
1077 }
1078
1079 #[test]
1080 fn test_form_post_html_generation() {
1081 let config = AdvancedJarmConfig::default();
1082 let manager = AdvancedJarmManager::new(config);
1083
1084 let html = manager.generate_form_post_html(
1085 "https://client.example.com/callback",
1086 "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
1087 );
1088
1089 assert!(html.contains("https://client.example.com/callback"));
1090 assert!(html.contains("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9"));
1091 assert!(html.contains("jarm_form"));
1092 }
1093
1094 #[tokio::test]
1095 async fn test_delivery_mode_validation() {
1096 let config = AdvancedJarmConfig {
1097 supported_delivery_modes: vec![JarmDeliveryMode::Query],
1098 supported_algorithms: vec![Algorithm::HS256], ..Default::default()
1100 };
1101 let manager = AdvancedJarmManager::new(config);
1102
1103 let auth_response = AuthorizationResponse {
1104 code: Some("code123".to_string()),
1105 state: None,
1106 access_token: None,
1107 id_token: None,
1108 token_type: None,
1109 expires_in: None,
1110 scope: None,
1111 error: None,
1112 error_description: None,
1113 };
1114
1115 let result = manager
1117 .create_jarm_response("test_client", &auth_response, JarmDeliveryMode::Query, None)
1118 .await;
1119 assert!(result.is_ok());
1120
1121 let result = manager
1123 .create_jarm_response("test_client", &auth_response, JarmDeliveryMode::Push, None)
1124 .await;
1125 assert!(result.is_err());
1126 }
1127}