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 pub fn new(error: OidcErrorCode) -> OidcErrorResponseBuilder {
201 OidcErrorResponseBuilder {
202 inner: OidcErrorResponse {
203 error,
204 error_description: None,
205 error_uri: None,
206 state: None,
207 additional_details: HashMap::new(),
208 },
209 }
210 }
211}
212
213pub struct OidcErrorResponseBuilder {
215 inner: OidcErrorResponse,
216}
217
218impl OidcErrorResponseBuilder {
219 pub fn description(mut self, desc: impl Into<String>) -> Self {
221 self.inner.error_description = Some(desc.into());
222 self
223 }
224
225 pub fn error_uri(mut self, uri: impl Into<String>) -> Self {
227 self.inner.error_uri = Some(uri.into());
228 self
229 }
230
231 pub fn state(mut self, state: impl Into<String>) -> Self {
233 self.inner.state = Some(state.into());
234 self
235 }
236
237 pub fn detail(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
239 self.inner.additional_details.insert(key.into(), value);
240 self
241 }
242
243 pub fn details(mut self, details: HashMap<String, serde_json::Value>) -> Self {
245 self.inner.additional_details = details;
246 self
247 }
248
249 pub fn build(self) -> OidcErrorResponse {
251 self.inner
252 }
253}
254
255#[derive(Debug, Clone, Serialize, Deserialize)]
257pub struct AuthenticationRequirements {
258 #[serde(skip_serializing_if = "Option::is_none")]
260 pub acr_values: Option<Vec<String>>,
261 #[serde(skip_serializing_if = "Option::is_none")]
263 pub amr_values: Option<Vec<String>>,
264 #[serde(skip_serializing_if = "Option::is_none")]
266 pub max_age: Option<u64>,
267 #[serde(skip_serializing_if = "Option::is_none")]
269 pub identity_assurance_level: Option<String>,
270}
271
272#[derive(Debug, Clone)]
274pub struct OidcErrorManager {
275 error_base_uri: String,
277 custom_error_mappings: HashMap<String, OidcErrorCode>,
279}
280
281impl Default for OidcErrorManager {
282 fn default() -> Self {
283 Self {
284 error_base_uri: "https://openid.net/specs/openid-connect-core-1_0.html#AuthError"
285 .to_string(),
286 custom_error_mappings: HashMap::new(),
287 }
288 }
289}
290
291impl OidcErrorCode {
292 pub fn get_description(&self) -> &'static str {
294 match self {
295 Self::InvalidRequest => {
296 "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed."
297 }
298 Self::InvalidClient => {
299 "Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)."
300 }
301 Self::InvalidGrant => {
302 "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."
303 }
304 Self::UnauthorizedClient => {
305 "The authenticated client is not authorized to use this authorization grant type."
306 }
307 Self::UnsupportedGrantType => {
308 "The authorization grant type is not supported by the authorization server."
309 }
310 Self::InvalidScope => "The requested scope is invalid, unknown, or malformed.",
311
312 Self::InteractionRequired => {
313 "The authorization server requires end-user interaction of some form to proceed."
314 }
315 Self::LoginRequired => "The authorization server requires end-user authentication.",
316 Self::AccountSelectionRequired => {
317 "The end-user is required to select a session at the authorization server."
318 }
319 Self::ConsentRequired => "The authorization server requires end-user consent.",
320 Self::InvalidRequestUri => {
321 "The request_uri in the authorization request returns an error or contains invalid data."
322 }
323 Self::InvalidRequestObject => {
324 "The request parameter contains an invalid request object."
325 }
326 Self::RequestNotSupported => {
327 "The authorization server does not support use of the request parameter."
328 }
329 Self::RequestUriNotSupported => {
330 "The authorization server does not support use of the request_uri parameter."
331 }
332 Self::RegistrationNotSupported => {
333 "The authorization server does not support use of the registration parameter."
334 }
335
336 Self::UnmetAuthenticationRequirements => {
338 "The authentication performed does not meet the authentication requirements specified in the request."
339 }
340 Self::UnmetAuthenticationContextRequirements => {
341 "The requested authentication context class reference values were not satisfied by the performed authentication."
342 }
343 Self::SessionSelectionRequired => {
344 "Multiple active sessions exist, and the end-user must select which session to use."
345 }
346 Self::AuthenticationMethodRequired => {
347 "The authorization server requires the end-user to authenticate using a specific authentication method."
348 }
349 Self::InsufficientIdentityAssurance => {
350 "The level of identity assurance achieved does not meet the requirements for this request."
351 }
352 Self::TemporarilyUnavailable => {
353 "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server."
354 }
355 Self::RegistrationRequired => {
356 "The end-user must complete a registration process before authentication can proceed."
357 }
358 Self::UnsupportedPromptValue => {
359 "The authorization server does not support the requested prompt value."
360 }
361 Self::UserSelectionRequired => {
362 "Multiple users match the provided identification, and selection is required."
363 }
364 }
365 }
366
367 pub fn requires_interaction(&self) -> bool {
369 matches!(
370 self,
371 Self::InteractionRequired
372 | Self::LoginRequired
373 | Self::AccountSelectionRequired
374 | Self::ConsentRequired
375 | Self::SessionSelectionRequired
376 | Self::AuthenticationMethodRequired
377 | Self::RegistrationRequired
378 | Self::UserSelectionRequired
379 )
380 }
381
382 pub fn is_authentication_error(&self) -> bool {
384 matches!(
385 self,
386 Self::LoginRequired
387 | Self::UnmetAuthenticationRequirements
388 | Self::UnmetAuthenticationContextRequirements
389 | Self::AuthenticationMethodRequired
390 | Self::InsufficientIdentityAssurance
391 )
392 }
393}
394
395impl OidcErrorManager {
396 pub fn new(error_base_uri: String) -> Self {
398 Self {
399 error_base_uri,
400 custom_error_mappings: HashMap::new(),
401 }
402 }
403
404 pub fn create_unmet_auth_requirements_error(
406 &self,
407 requirements: AuthenticationRequirements,
408 state: Option<String>,
409 ) -> OidcErrorResponse {
410 let mut builder = OidcErrorResponse::new(OidcErrorCode::UnmetAuthenticationRequirements)
411 .description(
412 OidcErrorCode::UnmetAuthenticationRequirements
413 .get_description()
414 .to_string(),
415 )
416 .error_uri(format!(
417 "{}#UnmetAuthenticationRequirements",
418 self.error_base_uri
419 ));
420
421 if let Some(s) = state {
422 builder = builder.state(s);
423 }
424
425 if let Some(acr_values) = &requirements.acr_values {
426 builder = builder.detail(
427 "required_acr_values",
428 serde_json::to_value(acr_values).unwrap_or_default(),
429 );
430 }
431
432 if let Some(amr_values) = &requirements.amr_values {
433 builder = builder.detail(
434 "required_amr_values",
435 serde_json::to_value(amr_values).unwrap_or_default(),
436 );
437 }
438
439 if let Some(max_age) = requirements.max_age {
440 builder = builder.detail(
441 "max_age",
442 serde_json::Value::Number(serde_json::Number::from(max_age)),
443 );
444 }
445
446 builder.build()
447 }
448
449 pub fn create_insufficient_acr_error(
451 &self,
452 required_acr: Vec<String>,
453 achieved_acr: Option<String>,
454 state: Option<String>,
455 ) -> OidcErrorResponse {
456 let mut builder =
457 OidcErrorResponse::new(OidcErrorCode::UnmetAuthenticationContextRequirements)
458 .description(
459 OidcErrorCode::UnmetAuthenticationContextRequirements
460 .get_description()
461 .to_string(),
462 )
463 .error_uri(format!("{}#ACRRequirements", self.error_base_uri))
464 .detail(
465 "required_acr_values",
466 serde_json::to_value(required_acr).unwrap_or_default(),
467 );
468
469 if let Some(acr) = achieved_acr {
470 builder = builder.detail("achieved_acr", serde_json::Value::String(acr));
471 }
472
473 if let Some(s) = state {
474 builder = builder.state(s);
475 }
476
477 builder.build()
478 }
479
480 pub fn create_error_response(
482 &self,
483 error_code: OidcErrorCode,
484 custom_description: Option<String>,
485 state: Option<String>,
486 additional_details: HashMap<String, serde_json::Value>,
487 ) -> OidcErrorResponse {
488 let mut builder = OidcErrorResponse::new(error_code.clone())
489 .description(
490 custom_description.unwrap_or_else(|| error_code.get_description().to_string()),
491 )
492 .error_uri(format!("{}#{:?}", self.error_base_uri, error_code))
493 .details(additional_details);
494
495 if let Some(s) = state {
496 builder = builder.state(s);
497 }
498
499 builder.build()
500 }
501
502 pub fn add_custom_error_mapping(&mut self, identifier: String, error_code: OidcErrorCode) {
504 self.custom_error_mappings.insert(identifier, error_code);
505 }
506
507 pub fn remove_custom_error_mapping(&mut self, identifier: &str) -> Option<OidcErrorCode> {
509 self.custom_error_mappings.remove(identifier)
510 }
511
512 pub fn resolve_error_code(&self, identifier: &str) -> Option<OidcErrorCode> {
514 if let Some(error_code) = self.custom_error_mappings.get(identifier) {
516 return Some(error_code.clone());
517 }
518
519 identifier.parse::<OidcErrorCode>().ok()
521 }
522
523 pub fn create_error_response_from_identifier(
525 &self,
526 error_identifier: &str,
527 custom_description: Option<String>,
528 state: Option<String>,
529 additional_details: HashMap<String, serde_json::Value>,
530 ) -> Result<OidcErrorResponse> {
531 match self.resolve_error_code(error_identifier) {
532 Some(error_code) => Ok(self.create_error_response(
533 error_code,
534 custom_description,
535 state,
536 additional_details,
537 )),
538 None => Err(AuthError::validation(format!(
539 "Unknown error code identifier: {}",
540 error_identifier
541 ))),
542 }
543 }
544
545 pub fn get_custom_mappings(&self) -> &HashMap<String, OidcErrorCode> {
547 &self.custom_error_mappings
548 }
549
550 pub fn clear_custom_mappings(&mut self) {
552 self.custom_error_mappings.clear();
553 }
554
555 pub fn has_custom_mapping(&self, identifier: &str) -> bool {
557 self.custom_error_mappings.contains_key(identifier)
558 }
559
560 pub fn validate_authentication_requirements(
562 &self,
563 requirements: &AuthenticationRequirements,
564 performed_acr: Option<&str>,
565 performed_amr: Option<&[String]>,
566 auth_time: Option<u64>,
567 current_time: u64,
568 ) -> Result<()> {
569 if let Some(required_acr) = &requirements.acr_values {
571 match performed_acr {
572 Some(acr) => {
573 if !required_acr.contains(&acr.to_string()) {
574 return Err(AuthError::validation(
575 "Authentication context class requirements not met",
576 ));
577 }
578 }
579 None => {
580 return Err(AuthError::validation(
581 "No authentication context class provided",
582 ));
583 }
584 }
585 }
586
587 if let Some(required_amr) = &requirements.amr_values {
589 match performed_amr {
590 Some(amr) => {
591 for required in required_amr {
592 if !amr.contains(required) {
593 return Err(AuthError::validation(
594 "Authentication method requirements not met",
595 ));
596 }
597 }
598 }
599 None => {
600 return Err(AuthError::validation("No authentication methods provided"));
601 }
602 }
603 }
604
605 if let Some(max_age) = requirements.max_age {
607 if let Some(auth_time) = auth_time {
608 if current_time - auth_time > max_age {
609 return Err(AuthError::validation(
610 "Authentication is too old (exceeds max_age)",
611 ));
612 }
613 } else {
614 return Err(AuthError::validation(
615 "Authentication time not available for max_age validation",
616 ));
617 }
618 }
619
620 Ok(())
621 }
622}
623
624#[cfg(test)]
625mod tests {
626 use super::*;
627
628 #[test]
629 fn test_error_code_descriptions() {
630 assert!(
631 !OidcErrorCode::UnmetAuthenticationRequirements
632 .get_description()
633 .is_empty()
634 );
635 assert!(OidcErrorCode::LoginRequired.requires_interaction());
636 assert!(OidcErrorCode::UnmetAuthenticationRequirements.is_authentication_error());
637 }
638
639 #[test]
640 fn test_oidc_error_code_display_roundtrip() {
641 let codes = vec![
643 OidcErrorCode::InvalidRequest,
644 OidcErrorCode::InvalidClient,
645 OidcErrorCode::InvalidGrant,
646 OidcErrorCode::UnauthorizedClient,
647 OidcErrorCode::UnsupportedGrantType,
648 OidcErrorCode::InvalidScope,
649 OidcErrorCode::InteractionRequired,
650 OidcErrorCode::LoginRequired,
651 OidcErrorCode::AccountSelectionRequired,
652 OidcErrorCode::ConsentRequired,
653 OidcErrorCode::InvalidRequestUri,
654 OidcErrorCode::InvalidRequestObject,
655 OidcErrorCode::RequestNotSupported,
656 OidcErrorCode::RequestUriNotSupported,
657 OidcErrorCode::RegistrationNotSupported,
658 OidcErrorCode::UnmetAuthenticationRequirements,
659 OidcErrorCode::UnmetAuthenticationContextRequirements,
660 OidcErrorCode::SessionSelectionRequired,
661 OidcErrorCode::AuthenticationMethodRequired,
662 OidcErrorCode::InsufficientIdentityAssurance,
663 OidcErrorCode::TemporarilyUnavailable,
664 OidcErrorCode::RegistrationRequired,
665 OidcErrorCode::UnsupportedPromptValue,
666 OidcErrorCode::UserSelectionRequired,
667 ];
668
669 for code in codes {
670 let s = code.to_string();
671 let parsed: OidcErrorCode = s.parse().unwrap();
672 assert_eq!(parsed, code);
673 }
674 }
675
676 #[test]
677 fn test_oidc_error_code_from_str_invalid() {
678 let result = "not_a_real_error".parse::<OidcErrorCode>();
679 assert!(result.is_err());
680 }
681
682 #[test]
683 fn test_oidc_error_response_builder() {
684 let resp = OidcErrorResponse::new(OidcErrorCode::LoginRequired)
685 .description("Session expired")
686 .error_uri("https://example.com/errors#login")
687 .state("abc123")
688 .detail("session_id", serde_json::json!("sess-42"))
689 .build();
690
691 assert_eq!(resp.error, OidcErrorCode::LoginRequired);
692 assert_eq!(resp.error_description.as_deref(), Some("Session expired"));
693 assert_eq!(
694 resp.error_uri.as_deref(),
695 Some("https://example.com/errors#login")
696 );
697 assert_eq!(resp.state.as_deref(), Some("abc123"));
698 assert_eq!(
699 resp.additional_details.get("session_id"),
700 Some(&serde_json::json!("sess-42"))
701 );
702 }
703
704 #[test]
705 fn test_unmet_auth_requirements_error() {
706 let manager = OidcErrorManager::default();
707 let requirements = AuthenticationRequirements {
708 acr_values: Some(vec!["urn:mace:incommon:iap:silver".to_string()]),
709 amr_values: Some(vec!["pwd".to_string(), "mfa".to_string()]),
710 max_age: Some(3600),
711 identity_assurance_level: None,
712 };
713
714 let error = manager
715 .create_unmet_auth_requirements_error(requirements, Some("state123".to_string()));
716
717 assert_eq!(error.error, OidcErrorCode::UnmetAuthenticationRequirements);
718 assert!(error.error_description.is_some());
719 assert_eq!(error.state.as_ref().unwrap(), "state123");
720 assert!(error.additional_details.contains_key("required_acr_values"));
721 assert!(error.additional_details.contains_key("required_amr_values"));
722 }
723
724 #[test]
725 fn test_custom_error_mappings() {
726 let mut manager = OidcErrorManager::default();
727
728 manager.add_custom_error_mapping(
730 "custom_validation_failed".to_string(),
731 OidcErrorCode::InvalidRequest,
732 );
733
734 let resolved = manager.resolve_error_code("custom_validation_failed");
736 assert_eq!(resolved, Some(OidcErrorCode::InvalidRequest));
737
738 let standard = manager.resolve_error_code("login_required");
740 assert_eq!(standard, Some(OidcErrorCode::LoginRequired));
741
742 let unknown = manager.resolve_error_code("nonexistent_error");
744 assert_eq!(unknown, None);
745
746 assert!(manager.has_custom_mapping("custom_validation_failed"));
748 assert!(!manager.has_custom_mapping("login_required"));
749
750 let error_response = manager
752 .create_error_response_from_identifier(
753 "custom_validation_failed",
754 Some("Custom validation error".to_string()),
755 Some("state123".to_string()),
756 HashMap::new(),
757 )
758 .unwrap();
759
760 assert_eq!(error_response.error, OidcErrorCode::InvalidRequest);
761 assert_eq!(error_response.state.as_ref().unwrap(), "state123");
762
763 let removed = manager.remove_custom_error_mapping("custom_validation_failed");
765 assert_eq!(removed, Some(OidcErrorCode::InvalidRequest));
766 assert!(!manager.has_custom_mapping("custom_validation_failed"));
767
768 manager.add_custom_error_mapping("test1".to_string(), OidcErrorCode::InvalidScope);
770 manager.add_custom_error_mapping("test2".to_string(), OidcErrorCode::ConsentRequired);
771 assert_eq!(manager.get_custom_mappings().len(), 2);
772
773 manager.clear_custom_mappings();
774 assert_eq!(manager.get_custom_mappings().len(), 0);
775 }
776
777 #[test]
778 fn test_error_response_from_unknown_identifier() {
779 let manager = OidcErrorManager::default();
780
781 let result = manager.create_error_response_from_identifier(
782 "unknown_error_code",
783 None,
784 None,
785 HashMap::new(),
786 );
787
788 assert!(result.is_err());
789 assert!(
790 result
791 .unwrap_err()
792 .to_string()
793 .contains("Unknown error code identifier")
794 );
795 }
796
797 #[test]
798 fn test_custom_error_mappings_real_world_scenario() {
799 let mut manager = OidcErrorManager::default();
800
801 manager.add_custom_error_mapping(
803 "account_frozen".to_string(),
804 OidcErrorCode::AuthenticationMethodRequired,
805 );
806 manager.add_custom_error_mapping(
807 "kyc_verification_required".to_string(),
808 OidcErrorCode::InsufficientIdentityAssurance,
809 );
810 manager.add_custom_error_mapping(
811 "payment_limit_exceeded".to_string(),
812 OidcErrorCode::ConsentRequired,
813 );
814
815 let mut additional_details = HashMap::new();
817 additional_details.insert(
818 "account_id".to_string(),
819 serde_json::Value::String("acc-12345".to_string()),
820 );
821 additional_details.insert(
822 "freeze_reason".to_string(),
823 serde_json::Value::String("Suspicious activity detected".to_string()),
824 );
825
826 let error_response = manager
827 .create_error_response_from_identifier(
828 "account_frozen",
829 Some("Account authentication required due to security freeze".to_string()),
830 Some("banking-session-456".to_string()),
831 additional_details,
832 )
833 .unwrap();
834
835 assert_eq!(
836 error_response.error,
837 OidcErrorCode::AuthenticationMethodRequired
838 );
839 assert_eq!(
840 error_response.error_description.as_ref().unwrap(),
841 "Account authentication required due to security freeze"
842 );
843 assert_eq!(
844 error_response.state.as_ref().unwrap(),
845 "banking-session-456"
846 );
847 assert!(error_response.additional_details.contains_key("account_id"));
848 assert!(
849 error_response
850 .additional_details
851 .contains_key("freeze_reason")
852 );
853
854 manager.add_custom_error_mapping(
856 "login_required".to_string(),
857 OidcErrorCode::RegistrationRequired, );
859
860 let overridden_response = manager
861 .create_error_response_from_identifier(
862 "login_required",
863 Some("User registration required before login".to_string()),
864 None,
865 HashMap::new(),
866 )
867 .unwrap();
868
869 assert_eq!(
870 overridden_response.error,
871 OidcErrorCode::RegistrationRequired
872 );
873
874 assert_eq!(manager.get_custom_mappings().len(), 4);
876 assert!(manager.has_custom_mapping("account_frozen"));
877 assert!(!manager.has_custom_mapping("nonexistent_mapping"));
878
879 let removed = manager.remove_custom_error_mapping("account_frozen");
881 assert_eq!(removed, Some(OidcErrorCode::AuthenticationMethodRequired));
882 assert!(!manager.has_custom_mapping("account_frozen"));
883
884 manager.clear_custom_mappings();
886 assert_eq!(manager.get_custom_mappings().len(), 0);
887 }
888
889 #[test]
890 fn test_standard_error_code_resolution() {
891 let manager = OidcErrorManager::default();
892
893 assert_eq!(
895 manager.resolve_error_code("invalid_request"),
896 Some(OidcErrorCode::InvalidRequest)
897 );
898 assert_eq!(
899 manager.resolve_error_code("unmet_authentication_requirements"),
900 Some(OidcErrorCode::UnmetAuthenticationRequirements)
901 );
902 assert_eq!(
903 manager.resolve_error_code("session_selection_required"),
904 Some(OidcErrorCode::SessionSelectionRequired)
905 );
906
907 let mut manager = OidcErrorManager::default();
909 manager.add_custom_error_mapping(
910 "login_required".to_string(),
911 OidcErrorCode::ConsentRequired, );
913
914 assert_eq!(
915 manager.resolve_error_code("login_required"),
916 Some(OidcErrorCode::ConsentRequired) );
918 }
919}