1use crate::errors::{AuthError, Result};
49use serde::{Deserialize, Serialize};
50use std::collections::HashMap;
51
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
54#[serde(rename_all = "snake_case")]
55pub enum OidcErrorCode {
56 InvalidRequest,
58 InvalidClient,
59 InvalidGrant,
60 UnauthorizedClient,
61 UnsupportedGrantType,
62 InvalidScope,
63
64 InteractionRequired,
66 LoginRequired,
67 AccountSelectionRequired,
68 ConsentRequired,
69 InvalidRequestUri,
70 InvalidRequestObject,
71 RequestNotSupported,
72 RequestUriNotSupported,
73 RegistrationNotSupported,
74
75 UnmetAuthenticationRequirements,
78 UnmetAuthenticationContextRequirements,
80 SessionSelectionRequired,
82 AuthenticationMethodRequired,
84 InsufficientIdentityAssurance,
86 TemporarilyUnavailable,
88 RegistrationRequired,
90 UnsupportedPromptValue,
92 UserSelectionRequired,
94}
95
96impl std::fmt::Display for OidcErrorCode {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 let s = match self {
99 Self::InvalidRequest => "invalid_request",
100 Self::InvalidClient => "invalid_client",
101 Self::InvalidGrant => "invalid_grant",
102 Self::UnauthorizedClient => "unauthorized_client",
103 Self::UnsupportedGrantType => "unsupported_grant_type",
104 Self::InvalidScope => "invalid_scope",
105 Self::InteractionRequired => "interaction_required",
106 Self::LoginRequired => "login_required",
107 Self::AccountSelectionRequired => "account_selection_required",
108 Self::ConsentRequired => "consent_required",
109 Self::InvalidRequestUri => "invalid_request_uri",
110 Self::InvalidRequestObject => "invalid_request_object",
111 Self::RequestNotSupported => "request_not_supported",
112 Self::RequestUriNotSupported => "request_uri_not_supported",
113 Self::RegistrationNotSupported => "registration_not_supported",
114 Self::UnmetAuthenticationRequirements => "unmet_authentication_requirements",
115 Self::UnmetAuthenticationContextRequirements => {
116 "unmet_authentication_context_requirements"
117 }
118 Self::SessionSelectionRequired => "session_selection_required",
119 Self::AuthenticationMethodRequired => "authentication_method_required",
120 Self::InsufficientIdentityAssurance => "insufficient_identity_assurance",
121 Self::TemporarilyUnavailable => "temporarily_unavailable",
122 Self::RegistrationRequired => "registration_required",
123 Self::UnsupportedPromptValue => "unsupported_prompt_value",
124 Self::UserSelectionRequired => "user_selection_required",
125 };
126 f.write_str(s)
127 }
128}
129
130impl std::str::FromStr for OidcErrorCode {
131 type Err = AuthError;
132
133 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
134 match s {
135 "invalid_request" => Ok(Self::InvalidRequest),
136 "invalid_client" => Ok(Self::InvalidClient),
137 "invalid_grant" => Ok(Self::InvalidGrant),
138 "unauthorized_client" => Ok(Self::UnauthorizedClient),
139 "unsupported_grant_type" => Ok(Self::UnsupportedGrantType),
140 "invalid_scope" => Ok(Self::InvalidScope),
141 "interaction_required" => Ok(Self::InteractionRequired),
142 "login_required" => Ok(Self::LoginRequired),
143 "account_selection_required" => Ok(Self::AccountSelectionRequired),
144 "consent_required" => Ok(Self::ConsentRequired),
145 "invalid_request_uri" => Ok(Self::InvalidRequestUri),
146 "invalid_request_object" => Ok(Self::InvalidRequestObject),
147 "request_not_supported" => Ok(Self::RequestNotSupported),
148 "request_uri_not_supported" => Ok(Self::RequestUriNotSupported),
149 "registration_not_supported" => Ok(Self::RegistrationNotSupported),
150 "unmet_authentication_requirements" => Ok(Self::UnmetAuthenticationRequirements),
151 "unmet_authentication_context_requirements" => {
152 Ok(Self::UnmetAuthenticationContextRequirements)
153 }
154 "session_selection_required" => Ok(Self::SessionSelectionRequired),
155 "authentication_method_required" => Ok(Self::AuthenticationMethodRequired),
156 "insufficient_identity_assurance" => Ok(Self::InsufficientIdentityAssurance),
157 "temporarily_unavailable" => Ok(Self::TemporarilyUnavailable),
158 "registration_required" => Ok(Self::RegistrationRequired),
159 "unsupported_prompt_value" => Ok(Self::UnsupportedPromptValue),
160 "user_selection_required" => Ok(Self::UserSelectionRequired),
161 other => Err(AuthError::validation(format!(
162 "Unknown OIDC error code: {other}"
163 ))),
164 }
165 }
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct OidcErrorResponse {
171 pub error: OidcErrorCode,
173 #[serde(skip_serializing_if = "Option::is_none")]
175 pub error_description: Option<String>,
176 #[serde(skip_serializing_if = "Option::is_none")]
178 pub error_uri: Option<String>,
179 #[serde(skip_serializing_if = "Option::is_none")]
181 pub state: Option<String>,
182 #[serde(flatten)]
184 pub additional_details: HashMap<String, serde_json::Value>,
185}
186
187impl OidcErrorResponse {
188 #[allow(
204 clippy::new_ret_no_self,
205 reason = "new returns the builder; renaming is a public API change"
206 )]
207 pub fn new(error: OidcErrorCode) -> OidcErrorResponseBuilder {
208 OidcErrorResponseBuilder {
209 inner: OidcErrorResponse {
210 error,
211 error_description: None,
212 error_uri: None,
213 state: None,
214 additional_details: HashMap::new(),
215 },
216 }
217 }
218}
219
220pub struct OidcErrorResponseBuilder {
222 inner: OidcErrorResponse,
223}
224
225impl OidcErrorResponseBuilder {
226 pub fn description(mut self, desc: impl Into<String>) -> Self {
228 self.inner.error_description = Some(desc.into());
229 self
230 }
231
232 pub fn error_uri(mut self, uri: impl Into<String>) -> Self {
234 self.inner.error_uri = Some(uri.into());
235 self
236 }
237
238 pub fn state(mut self, state: impl Into<String>) -> Self {
240 self.inner.state = Some(state.into());
241 self
242 }
243
244 pub fn detail(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
246 self.inner.additional_details.insert(key.into(), value);
247 self
248 }
249
250 pub fn details(mut self, details: HashMap<String, serde_json::Value>) -> Self {
252 self.inner.additional_details = details;
253 self
254 }
255
256 pub fn build(self) -> OidcErrorResponse {
258 self.inner
259 }
260}
261
262#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct AuthenticationRequirements {
265 #[serde(skip_serializing_if = "Option::is_none")]
267 pub acr_values: Option<Vec<String>>,
268 #[serde(skip_serializing_if = "Option::is_none")]
270 pub amr_values: Option<Vec<String>>,
271 #[serde(skip_serializing_if = "Option::is_none")]
273 pub max_age: Option<u64>,
274 #[serde(skip_serializing_if = "Option::is_none")]
276 pub identity_assurance_level: Option<String>,
277}
278
279#[derive(Debug, Clone)]
281pub struct OidcErrorManager {
282 error_base_uri: String,
284 custom_error_mappings: HashMap<String, OidcErrorCode>,
286}
287
288impl Default for OidcErrorManager {
289 fn default() -> Self {
290 Self {
291 error_base_uri: "https://openid.net/specs/openid-connect-core-1_0.html#AuthError"
292 .to_string(),
293 custom_error_mappings: HashMap::new(),
294 }
295 }
296}
297
298impl OidcErrorCode {
299 pub fn get_description(&self) -> &'static str {
301 match self {
302 Self::InvalidRequest => {
303 "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed."
304 }
305 Self::InvalidClient => {
306 "Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)."
307 }
308 Self::InvalidGrant => {
309 "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
310 }
311 Self::UnauthorizedClient => {
312 "The authenticated client is not authorized to use this authorization grant type."
313 }
314 Self::UnsupportedGrantType => {
315 "The authorization grant type is not supported by the authorization server."
316 }
317 Self::InvalidScope => "The requested scope is invalid, unknown, or malformed.",
318
319 Self::InteractionRequired => {
320 "The authorization server requires end-user interaction of some form to proceed."
321 }
322 Self::LoginRequired => "The authorization server requires end-user authentication.",
323 Self::AccountSelectionRequired => {
324 "The end-user is required to select a session at the authorization server."
325 }
326 Self::ConsentRequired => "The authorization server requires end-user consent.",
327 Self::InvalidRequestUri => {
328 "The request_uri in the authorization request returns an error or contains invalid data."
329 }
330 Self::InvalidRequestObject => {
331 "The request parameter contains an invalid request object."
332 }
333 Self::RequestNotSupported => {
334 "The authorization server does not support use of the request parameter."
335 }
336 Self::RequestUriNotSupported => {
337 "The authorization server does not support use of the request_uri parameter."
338 }
339 Self::RegistrationNotSupported => {
340 "The authorization server does not support use of the registration parameter."
341 }
342
343 Self::UnmetAuthenticationRequirements => {
345 "The authentication performed does not meet the authentication requirements specified in the request."
346 }
347 Self::UnmetAuthenticationContextRequirements => {
348 "The requested authentication context class reference values were not satisfied by the performed authentication."
349 }
350 Self::SessionSelectionRequired => {
351 "Multiple active sessions exist, and the end-user must select which session to use."
352 }
353 Self::AuthenticationMethodRequired => {
354 "The authorization server requires the end-user to authenticate using a specific authentication method."
355 }
356 Self::InsufficientIdentityAssurance => {
357 "The level of identity assurance achieved does not meet the requirements for this request."
358 }
359 Self::TemporarilyUnavailable => {
360 "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server."
361 }
362 Self::RegistrationRequired => {
363 "The end-user must complete a registration process before authentication can proceed."
364 }
365 Self::UnsupportedPromptValue => {
366 "The authorization server does not support the requested prompt value."
367 }
368 Self::UserSelectionRequired => {
369 "Multiple users match the provided identification, and selection is required."
370 }
371 }
372 }
373
374 pub fn requires_interaction(&self) -> bool {
376 matches!(
377 self,
378 Self::InteractionRequired
379 | Self::LoginRequired
380 | Self::AccountSelectionRequired
381 | Self::ConsentRequired
382 | Self::SessionSelectionRequired
383 | Self::AuthenticationMethodRequired
384 | Self::RegistrationRequired
385 | Self::UserSelectionRequired
386 )
387 }
388
389 pub fn is_authentication_error(&self) -> bool {
391 matches!(
392 self,
393 Self::LoginRequired
394 | Self::UnmetAuthenticationRequirements
395 | Self::UnmetAuthenticationContextRequirements
396 | Self::AuthenticationMethodRequired
397 | Self::InsufficientIdentityAssurance
398 )
399 }
400}
401
402impl OidcErrorManager {
403 pub fn new(error_base_uri: String) -> Self {
405 Self {
406 error_base_uri,
407 custom_error_mappings: HashMap::new(),
408 }
409 }
410
411 pub fn create_unmet_auth_requirements_error(
413 &self,
414 requirements: AuthenticationRequirements,
415 state: Option<String>,
416 ) -> OidcErrorResponse {
417 let mut builder = OidcErrorResponse::new(OidcErrorCode::UnmetAuthenticationRequirements)
418 .description(
419 OidcErrorCode::UnmetAuthenticationRequirements
420 .get_description()
421 .to_string(),
422 )
423 .error_uri(format!(
424 "{}#UnmetAuthenticationRequirements",
425 self.error_base_uri
426 ));
427
428 if let Some(s) = state {
429 builder = builder.state(s);
430 }
431
432 if let Some(acr_values) = &requirements.acr_values {
433 builder = builder.detail(
434 "required_acr_values",
435 serde_json::to_value(acr_values).unwrap_or_default(),
436 );
437 }
438
439 if let Some(amr_values) = &requirements.amr_values {
440 builder = builder.detail(
441 "required_amr_values",
442 serde_json::to_value(amr_values).unwrap_or_default(),
443 );
444 }
445
446 if let Some(max_age) = requirements.max_age {
447 builder = builder.detail(
448 "max_age",
449 serde_json::Value::Number(serde_json::Number::from(max_age)),
450 );
451 }
452
453 builder.build()
454 }
455
456 pub fn create_insufficient_acr_error(
458 &self,
459 required_acr: Vec<String>,
460 achieved_acr: Option<String>,
461 state: Option<String>,
462 ) -> OidcErrorResponse {
463 let mut builder =
464 OidcErrorResponse::new(OidcErrorCode::UnmetAuthenticationContextRequirements)
465 .description(
466 OidcErrorCode::UnmetAuthenticationContextRequirements
467 .get_description()
468 .to_string(),
469 )
470 .error_uri(format!("{}#ACRRequirements", self.error_base_uri))
471 .detail(
472 "required_acr_values",
473 serde_json::to_value(required_acr).unwrap_or_default(),
474 );
475
476 if let Some(acr) = achieved_acr {
477 builder = builder.detail("achieved_acr", serde_json::Value::String(acr));
478 }
479
480 if let Some(s) = state {
481 builder = builder.state(s);
482 }
483
484 builder.build()
485 }
486
487 pub fn create_error_response(
489 &self,
490 error_code: OidcErrorCode,
491 custom_description: Option<String>,
492 state: Option<String>,
493 additional_details: HashMap<String, serde_json::Value>,
494 ) -> OidcErrorResponse {
495 let mut builder = OidcErrorResponse::new(error_code.clone())
496 .description(
497 custom_description.unwrap_or_else(|| error_code.get_description().to_string()),
498 )
499 .error_uri(format!("{}#{:?}", self.error_base_uri, error_code))
500 .details(additional_details);
501
502 if let Some(s) = state {
503 builder = builder.state(s);
504 }
505
506 builder.build()
507 }
508
509 pub fn add_custom_error_mapping(&mut self, identifier: String, error_code: OidcErrorCode) {
511 self.custom_error_mappings.insert(identifier, error_code);
512 }
513
514 pub fn remove_custom_error_mapping(&mut self, identifier: &str) -> Option<OidcErrorCode> {
516 self.custom_error_mappings.remove(identifier)
517 }
518
519 pub fn resolve_error_code(&self, identifier: &str) -> Option<OidcErrorCode> {
521 if let Some(error_code) = self.custom_error_mappings.get(identifier) {
523 return Some(error_code.clone());
524 }
525
526 identifier.parse::<OidcErrorCode>().ok()
528 }
529
530 pub fn create_error_response_from_identifier(
532 &self,
533 error_identifier: &str,
534 custom_description: Option<String>,
535 state: Option<String>,
536 additional_details: HashMap<String, serde_json::Value>,
537 ) -> Result<OidcErrorResponse> {
538 match self.resolve_error_code(error_identifier) {
539 Some(error_code) => Ok(self.create_error_response(
540 error_code,
541 custom_description,
542 state,
543 additional_details,
544 )),
545 None => Err(AuthError::validation(format!(
546 "Unknown error code identifier: {}",
547 error_identifier
548 ))),
549 }
550 }
551
552 pub fn get_custom_mappings(&self) -> &HashMap<String, OidcErrorCode> {
554 &self.custom_error_mappings
555 }
556
557 pub fn clear_custom_mappings(&mut self) {
559 self.custom_error_mappings.clear();
560 }
561
562 pub fn has_custom_mapping(&self, identifier: &str) -> bool {
564 self.custom_error_mappings.contains_key(identifier)
565 }
566
567 pub fn validate_authentication_requirements(
569 &self,
570 requirements: &AuthenticationRequirements,
571 performed_acr: Option<&str>,
572 performed_amr: Option<&[String]>,
573 auth_time: Option<u64>,
574 current_time: u64,
575 ) -> Result<()> {
576 if let Some(required_acr) = &requirements.acr_values {
578 match performed_acr {
579 Some(acr) => {
580 if !required_acr.contains(&acr.to_string()) {
581 return Err(AuthError::validation(
582 "Authentication context class requirements not met",
583 ));
584 }
585 }
586 None => {
587 return Err(AuthError::validation(
588 "No authentication context class provided",
589 ));
590 }
591 }
592 }
593
594 if let Some(required_amr) = &requirements.amr_values {
596 match performed_amr {
597 Some(amr) => {
598 for required in required_amr {
599 if !amr.contains(required) {
600 return Err(AuthError::validation(
601 "Authentication method requirements not met",
602 ));
603 }
604 }
605 }
606 None => {
607 return Err(AuthError::validation("No authentication methods provided"));
608 }
609 }
610 }
611
612 if let Some(max_age) = requirements.max_age {
614 if let Some(auth_time) = auth_time {
615 if current_time - auth_time > max_age {
616 return Err(AuthError::validation(
617 "Authentication is too old (exceeds max_age)",
618 ));
619 }
620 } else {
621 return Err(AuthError::validation(
622 "Authentication time not available for max_age validation",
623 ));
624 }
625 }
626
627 Ok(())
628 }
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634
635 #[test]
636 fn test_error_code_descriptions() {
637 assert!(
638 !OidcErrorCode::UnmetAuthenticationRequirements
639 .get_description()
640 .is_empty()
641 );
642 assert!(OidcErrorCode::LoginRequired.requires_interaction());
643 assert!(OidcErrorCode::UnmetAuthenticationRequirements.is_authentication_error());
644 }
645
646 #[test]
647 fn test_oidc_error_code_display_roundtrip() {
648 let codes = vec![
650 OidcErrorCode::InvalidRequest,
651 OidcErrorCode::InvalidClient,
652 OidcErrorCode::InvalidGrant,
653 OidcErrorCode::UnauthorizedClient,
654 OidcErrorCode::UnsupportedGrantType,
655 OidcErrorCode::InvalidScope,
656 OidcErrorCode::InteractionRequired,
657 OidcErrorCode::LoginRequired,
658 OidcErrorCode::AccountSelectionRequired,
659 OidcErrorCode::ConsentRequired,
660 OidcErrorCode::InvalidRequestUri,
661 OidcErrorCode::InvalidRequestObject,
662 OidcErrorCode::RequestNotSupported,
663 OidcErrorCode::RequestUriNotSupported,
664 OidcErrorCode::RegistrationNotSupported,
665 OidcErrorCode::UnmetAuthenticationRequirements,
666 OidcErrorCode::UnmetAuthenticationContextRequirements,
667 OidcErrorCode::SessionSelectionRequired,
668 OidcErrorCode::AuthenticationMethodRequired,
669 OidcErrorCode::InsufficientIdentityAssurance,
670 OidcErrorCode::TemporarilyUnavailable,
671 OidcErrorCode::RegistrationRequired,
672 OidcErrorCode::UnsupportedPromptValue,
673 OidcErrorCode::UserSelectionRequired,
674 ];
675
676 for code in codes {
677 let s = code.to_string();
678 let parsed: OidcErrorCode = s.parse().unwrap();
679 assert_eq!(parsed, code);
680 }
681 }
682
683 #[test]
684 fn test_oidc_error_code_from_str_invalid() {
685 let result = "not_a_real_error".parse::<OidcErrorCode>();
686 assert!(result.is_err());
687 }
688
689 #[test]
690 fn test_oidc_error_response_builder() {
691 let resp = OidcErrorResponse::new(OidcErrorCode::LoginRequired)
692 .description("Session expired")
693 .error_uri("https://example.com/errors#login")
694 .state("abc123")
695 .detail("session_id", serde_json::json!("sess-42"))
696 .build();
697
698 assert_eq!(resp.error, OidcErrorCode::LoginRequired);
699 assert_eq!(resp.error_description.as_deref(), Some("Session expired"));
700 assert_eq!(
701 resp.error_uri.as_deref(),
702 Some("https://example.com/errors#login")
703 );
704 assert_eq!(resp.state.as_deref(), Some("abc123"));
705 assert_eq!(
706 resp.additional_details.get("session_id"),
707 Some(&serde_json::json!("sess-42"))
708 );
709 }
710
711 #[test]
712 fn test_unmet_auth_requirements_error() {
713 let manager = OidcErrorManager::default();
714 let requirements = AuthenticationRequirements {
715 acr_values: Some(vec!["urn:mace:incommon:iap:silver".to_string()]),
716 amr_values: Some(vec!["pwd".to_string(), "mfa".to_string()]),
717 max_age: Some(3600),
718 identity_assurance_level: None,
719 };
720
721 let error = manager
722 .create_unmet_auth_requirements_error(requirements, Some("state123".to_string()));
723
724 assert_eq!(error.error, OidcErrorCode::UnmetAuthenticationRequirements);
725 assert!(error.error_description.is_some());
726 assert_eq!(error.state.as_ref().unwrap(), "state123");
727 assert!(error.additional_details.contains_key("required_acr_values"));
728 assert!(error.additional_details.contains_key("required_amr_values"));
729 }
730
731 #[test]
732 fn test_custom_error_mappings() {
733 let mut manager = OidcErrorManager::default();
734
735 manager.add_custom_error_mapping(
737 "custom_validation_failed".to_string(),
738 OidcErrorCode::InvalidRequest,
739 );
740
741 let resolved = manager.resolve_error_code("custom_validation_failed");
743 assert_eq!(resolved, Some(OidcErrorCode::InvalidRequest));
744
745 let standard = manager.resolve_error_code("login_required");
747 assert_eq!(standard, Some(OidcErrorCode::LoginRequired));
748
749 let unknown = manager.resolve_error_code("nonexistent_error");
751 assert_eq!(unknown, None);
752
753 assert!(manager.has_custom_mapping("custom_validation_failed"));
755 assert!(!manager.has_custom_mapping("login_required"));
756
757 let error_response = manager
759 .create_error_response_from_identifier(
760 "custom_validation_failed",
761 Some("Custom validation error".to_string()),
762 Some("state123".to_string()),
763 HashMap::new(),
764 )
765 .unwrap();
766
767 assert_eq!(error_response.error, OidcErrorCode::InvalidRequest);
768 assert_eq!(error_response.state.as_ref().unwrap(), "state123");
769
770 let removed = manager.remove_custom_error_mapping("custom_validation_failed");
772 assert_eq!(removed, Some(OidcErrorCode::InvalidRequest));
773 assert!(!manager.has_custom_mapping("custom_validation_failed"));
774
775 manager.add_custom_error_mapping("test1".to_string(), OidcErrorCode::InvalidScope);
777 manager.add_custom_error_mapping("test2".to_string(), OidcErrorCode::ConsentRequired);
778 assert_eq!(manager.get_custom_mappings().len(), 2);
779
780 manager.clear_custom_mappings();
781 assert_eq!(manager.get_custom_mappings().len(), 0);
782 }
783
784 #[test]
785 fn test_error_response_from_unknown_identifier() {
786 let manager = OidcErrorManager::default();
787
788 let result = manager.create_error_response_from_identifier(
789 "unknown_error_code",
790 None,
791 None,
792 HashMap::new(),
793 );
794
795 assert!(result.is_err());
796 assert!(
797 result
798 .unwrap_err()
799 .to_string()
800 .contains("Unknown error code identifier")
801 );
802 }
803
804 #[test]
805 fn test_custom_error_mappings_real_world_scenario() {
806 let mut manager = OidcErrorManager::default();
807
808 manager.add_custom_error_mapping(
810 "account_frozen".to_string(),
811 OidcErrorCode::AuthenticationMethodRequired,
812 );
813 manager.add_custom_error_mapping(
814 "kyc_verification_required".to_string(),
815 OidcErrorCode::InsufficientIdentityAssurance,
816 );
817 manager.add_custom_error_mapping(
818 "payment_limit_exceeded".to_string(),
819 OidcErrorCode::ConsentRequired,
820 );
821
822 let mut additional_details = HashMap::new();
824 additional_details.insert(
825 "account_id".to_string(),
826 serde_json::Value::String("acc-12345".to_string()),
827 );
828 additional_details.insert(
829 "freeze_reason".to_string(),
830 serde_json::Value::String("Suspicious activity detected".to_string()),
831 );
832
833 let error_response = manager
834 .create_error_response_from_identifier(
835 "account_frozen",
836 Some("Account authentication required due to security freeze".to_string()),
837 Some("banking-session-456".to_string()),
838 additional_details,
839 )
840 .unwrap();
841
842 assert_eq!(
843 error_response.error,
844 OidcErrorCode::AuthenticationMethodRequired
845 );
846 assert_eq!(
847 error_response.error_description.as_ref().unwrap(),
848 "Account authentication required due to security freeze"
849 );
850 assert_eq!(
851 error_response.state.as_ref().unwrap(),
852 "banking-session-456"
853 );
854 assert!(error_response.additional_details.contains_key("account_id"));
855 assert!(
856 error_response
857 .additional_details
858 .contains_key("freeze_reason")
859 );
860
861 manager.add_custom_error_mapping(
863 "login_required".to_string(),
864 OidcErrorCode::RegistrationRequired, );
866
867 let overridden_response = manager
868 .create_error_response_from_identifier(
869 "login_required",
870 Some("User registration required before login".to_string()),
871 None,
872 HashMap::new(),
873 )
874 .unwrap();
875
876 assert_eq!(
877 overridden_response.error,
878 OidcErrorCode::RegistrationRequired
879 );
880
881 assert_eq!(manager.get_custom_mappings().len(), 4);
883 assert!(manager.has_custom_mapping("account_frozen"));
884 assert!(!manager.has_custom_mapping("nonexistent_mapping"));
885
886 let removed = manager.remove_custom_error_mapping("account_frozen");
888 assert_eq!(removed, Some(OidcErrorCode::AuthenticationMethodRequired));
889 assert!(!manager.has_custom_mapping("account_frozen"));
890
891 manager.clear_custom_mappings();
893 assert_eq!(manager.get_custom_mappings().len(), 0);
894 }
895
896 #[test]
897 fn test_standard_error_code_resolution() {
898 let manager = OidcErrorManager::default();
899
900 assert_eq!(
902 manager.resolve_error_code("invalid_request"),
903 Some(OidcErrorCode::InvalidRequest)
904 );
905 assert_eq!(
906 manager.resolve_error_code("unmet_authentication_requirements"),
907 Some(OidcErrorCode::UnmetAuthenticationRequirements)
908 );
909 assert_eq!(
910 manager.resolve_error_code("session_selection_required"),
911 Some(OidcErrorCode::SessionSelectionRequired)
912 );
913
914 let mut manager = OidcErrorManager::default();
916 manager.add_custom_error_mapping(
917 "login_required".to_string(),
918 OidcErrorCode::ConsentRequired, );
920
921 assert_eq!(
922 manager.resolve_error_code("login_required"),
923 Some(OidcErrorCode::ConsentRequired) );
925 }
926}