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