Skip to main content

auth_framework/server/oidc/
oidc_error_extensions.rs

1//! OpenID Connect Core Error Code Extensions
2//!
3//! This module implements additional error codes for OpenID Connect,
4//! including the `unmet_authentication_requirements` error code and other
5//! enhanced error handling capabilities.
6//!
7//! # Implemented Error Extensions
8//!
9//! - `unmet_authentication_requirements` - Authentication requirements not met
10//! - Enhanced error descriptions and URIs
11//! - Structured error reporting
12//! - Error code validation and mapping
13//! - Custom error code mappings for extensible error handling
14//!
15//! # Custom Error Mappings
16//!
17//! The `OidcErrorManager` supports custom error code mappings that allow:
18//! - Mapping custom string identifiers to standard or extended error codes
19//! - Runtime extensibility for domain-specific error codes
20//! - Override standard error code mappings for specialized behavior
21//! - Error code resolution from string identifiers
22//!
23//! # Usage Examples
24//!
25//! ```rust,no_run
26//! use auth_framework::server::oidc::oidc_error_extensions::{OidcErrorManager, OidcErrorCode, OidcErrorResponse};
27//!
28//! // Parse error codes from strings (e.g. from HTTP query params):
29//! let code: OidcErrorCode = "invalid_request".parse().unwrap();
30//! assert_eq!(code.to_string(), "invalid_request");
31//!
32//! // Build an error response fluently:
33//! let response = OidcErrorResponse::new(OidcErrorCode::LoginRequired)
34//!     .description("Session expired, please log in again")
35//!     .state("state123")
36//!     .detail("session_age", serde_json::json!(7200))
37//!     .build();
38//!
39//! // OidcErrorManager with custom mappings:
40//! let mut manager = OidcErrorManager::default();
41//! manager.add_custom_error_mapping(
42//!     "payment_required".to_string(),
43//!     OidcErrorCode::InsufficientIdentityAssurance,
44//! );
45//! let error_code = manager.resolve_error_code("payment_required");
46//! ```
47
48use crate::errors::{AuthError, Result};
49use serde::{Deserialize, Serialize};
50use std::collections::HashMap;
51
52/// Extended OpenID Connect error codes
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
54#[serde(rename_all = "snake_case")]
55pub enum OidcErrorCode {
56    // Standard OAuth 2.0 errors
57    InvalidRequest,
58    InvalidClient,
59    InvalidGrant,
60    UnauthorizedClient,
61    UnsupportedGrantType,
62    InvalidScope,
63
64    // Standard OpenID Connect errors
65    InteractionRequired,
66    LoginRequired,
67    AccountSelectionRequired,
68    ConsentRequired,
69    InvalidRequestUri,
70    InvalidRequestObject,
71    RequestNotSupported,
72    RequestUriNotSupported,
73    RegistrationNotSupported,
74
75    // Extended error codes
76    /// Authentication requirements specified in the request were not met
77    UnmetAuthenticationRequirements,
78    /// The requested authentication context class reference values were not satisfied
79    UnmetAuthenticationContextRequirements,
80    /// Session selection required for multi-session scenarios
81    SessionSelectionRequired,
82    /// The authorization server requires user authentication via a different method
83    AuthenticationMethodRequired,
84    /// The requested identity verification level could not be satisfied
85    InsufficientIdentityAssurance,
86    /// The authorization server temporarily cannot service the request
87    TemporarilyUnavailable,
88    /// The request requires user registration/enrollment
89    RegistrationRequired,
90    /// The requested prompt value is not supported
91    UnsupportedPromptValue,
92    /// Multiple matching users found, selection required
93    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/// OpenID Connect error response
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct OidcErrorResponse {
171    /// The error code
172    pub error: OidcErrorCode,
173    /// Human-readable error description
174    #[serde(skip_serializing_if = "Option::is_none")]
175    pub error_description: Option<String>,
176    /// URI to error documentation
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub error_uri: Option<String>,
179    /// State parameter from the request
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub state: Option<String>,
182    /// Additional error details
183    #[serde(flatten)]
184    pub additional_details: HashMap<String, serde_json::Value>,
185}
186
187impl OidcErrorResponse {
188    /// Start building an error response for the given error code.
189    ///
190    /// # Example
191    ///
192    /// ```rust,no_run
193    /// use auth_framework::server::oidc::oidc_error_extensions::{OidcErrorCode, OidcErrorResponse};
194    ///
195    /// let resp = OidcErrorResponse::new(OidcErrorCode::LoginRequired)
196    ///     .description("Session expired")
197    ///     .state("abc123")
198    ///     .build();
199    /// ```
200    #[allow(clippy::new_ret_no_self)] // constructor of a builder type; renaming would be a breaking change
201    pub fn new(error: OidcErrorCode) -> OidcErrorResponseBuilder {
202        OidcErrorResponseBuilder {
203            inner: OidcErrorResponse {
204                error,
205                error_description: None,
206                error_uri: None,
207                state: None,
208                additional_details: HashMap::new(),
209            },
210        }
211    }
212}
213
214/// Fluent builder for [`OidcErrorResponse`].
215pub struct OidcErrorResponseBuilder {
216    inner: OidcErrorResponse,
217}
218
219impl OidcErrorResponseBuilder {
220    /// Set a human-readable error description.
221    pub fn description(mut self, desc: impl Into<String>) -> Self {
222        self.inner.error_description = Some(desc.into());
223        self
224    }
225
226    /// Set the error documentation URI.
227    pub fn error_uri(mut self, uri: impl Into<String>) -> Self {
228        self.inner.error_uri = Some(uri.into());
229        self
230    }
231
232    /// Set the OAuth `state` parameter.
233    pub fn state(mut self, state: impl Into<String>) -> Self {
234        self.inner.state = Some(state.into());
235        self
236    }
237
238    /// Add a single additional detail.
239    pub fn detail(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
240        self.inner.additional_details.insert(key.into(), value);
241        self
242    }
243
244    /// Set all additional details at once (replaces any previously added).
245    pub fn details(mut self, details: HashMap<String, serde_json::Value>) -> Self {
246        self.inner.additional_details = details;
247        self
248    }
249
250    /// Consume the builder and return the [`OidcErrorResponse`].
251    pub fn build(self) -> OidcErrorResponse {
252        self.inner
253    }
254}
255
256/// Authentication requirements details
257#[derive(Debug, Clone, Serialize, Deserialize)]
258pub struct AuthenticationRequirements {
259    /// Required authentication context class references
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub acr_values: Option<Vec<String>>,
262    /// Required authentication methods references
263    #[serde(skip_serializing_if = "Option::is_none")]
264    pub amr_values: Option<Vec<String>>,
265    /// Maximum authentication age
266    #[serde(skip_serializing_if = "Option::is_none")]
267    pub max_age: Option<u64>,
268    /// Required identity assurance level
269    #[serde(skip_serializing_if = "Option::is_none")]
270    pub identity_assurance_level: Option<String>,
271}
272
273/// Error handling manager for OpenID Connect
274#[derive(Debug, Clone)]
275pub struct OidcErrorManager {
276    /// Base error documentation URI
277    error_base_uri: String,
278    /// Custom error mappings
279    custom_error_mappings: HashMap<String, OidcErrorCode>,
280}
281
282impl Default for OidcErrorManager {
283    fn default() -> Self {
284        Self {
285            error_base_uri: "https://openid.net/specs/openid-connect-core-1_0.html#AuthError"
286                .to_string(),
287            custom_error_mappings: HashMap::new(),
288        }
289    }
290}
291
292impl OidcErrorCode {
293    /// Get standard error description for error code
294    pub fn get_description(&self) -> &'static str {
295        match self {
296            Self::InvalidRequest => {
297                "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed."
298            }
299            Self::InvalidClient => {
300                "Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)."
301            }
302            Self::InvalidGrant => {
303                "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."
304            }
305            Self::UnauthorizedClient => {
306                "The authenticated client is not authorized to use this authorization grant type."
307            }
308            Self::UnsupportedGrantType => {
309                "The authorization grant type is not supported by the authorization server."
310            }
311            Self::InvalidScope => "The requested scope is invalid, unknown, or malformed.",
312
313            Self::InteractionRequired => {
314                "The authorization server requires end-user interaction of some form to proceed."
315            }
316            Self::LoginRequired => "The authorization server requires end-user authentication.",
317            Self::AccountSelectionRequired => {
318                "The end-user is required to select a session at the authorization server."
319            }
320            Self::ConsentRequired => "The authorization server requires end-user consent.",
321            Self::InvalidRequestUri => {
322                "The request_uri in the authorization request returns an error or contains invalid data."
323            }
324            Self::InvalidRequestObject => {
325                "The request parameter contains an invalid request object."
326            }
327            Self::RequestNotSupported => {
328                "The authorization server does not support use of the request parameter."
329            }
330            Self::RequestUriNotSupported => {
331                "The authorization server does not support use of the request_uri parameter."
332            }
333            Self::RegistrationNotSupported => {
334                "The authorization server does not support use of the registration parameter."
335            }
336
337            // Extended error codes
338            Self::UnmetAuthenticationRequirements => {
339                "The authentication performed does not meet the authentication requirements specified in the request."
340            }
341            Self::UnmetAuthenticationContextRequirements => {
342                "The requested authentication context class reference values were not satisfied by the performed authentication."
343            }
344            Self::SessionSelectionRequired => {
345                "Multiple active sessions exist, and the end-user must select which session to use."
346            }
347            Self::AuthenticationMethodRequired => {
348                "The authorization server requires the end-user to authenticate using a specific authentication method."
349            }
350            Self::InsufficientIdentityAssurance => {
351                "The level of identity assurance achieved does not meet the requirements for this request."
352            }
353            Self::TemporarilyUnavailable => {
354                "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server."
355            }
356            Self::RegistrationRequired => {
357                "The end-user must complete a registration process before authentication can proceed."
358            }
359            Self::UnsupportedPromptValue => {
360                "The authorization server does not support the requested prompt value."
361            }
362            Self::UserSelectionRequired => {
363                "Multiple users match the provided identification, and selection is required."
364            }
365        }
366    }
367
368    /// Check if this error code requires user interaction
369    pub fn requires_interaction(&self) -> bool {
370        matches!(
371            self,
372            Self::InteractionRequired
373                | Self::LoginRequired
374                | Self::AccountSelectionRequired
375                | Self::ConsentRequired
376                | Self::SessionSelectionRequired
377                | Self::AuthenticationMethodRequired
378                | Self::RegistrationRequired
379                | Self::UserSelectionRequired
380        )
381    }
382
383    /// Check if this error code indicates an authentication issue
384    pub fn is_authentication_error(&self) -> bool {
385        matches!(
386            self,
387            Self::LoginRequired
388                | Self::UnmetAuthenticationRequirements
389                | Self::UnmetAuthenticationContextRequirements
390                | Self::AuthenticationMethodRequired
391                | Self::InsufficientIdentityAssurance
392        )
393    }
394}
395
396impl OidcErrorManager {
397    /// Create new error manager
398    pub fn new(error_base_uri: String) -> Self {
399        Self {
400            error_base_uri,
401            custom_error_mappings: HashMap::new(),
402        }
403    }
404
405    /// Create error response for unmet authentication requirements
406    pub fn create_unmet_auth_requirements_error(
407        &self,
408        requirements: AuthenticationRequirements,
409        state: Option<String>,
410    ) -> OidcErrorResponse {
411        let mut builder = OidcErrorResponse::new(OidcErrorCode::UnmetAuthenticationRequirements)
412            .description(
413                OidcErrorCode::UnmetAuthenticationRequirements
414                    .get_description()
415                    .to_string(),
416            )
417            .error_uri(format!(
418                "{}#UnmetAuthenticationRequirements",
419                self.error_base_uri
420            ));
421
422        if let Some(s) = state {
423            builder = builder.state(s);
424        }
425
426        if let Some(acr_values) = &requirements.acr_values {
427            builder = builder.detail(
428                "required_acr_values",
429                serde_json::to_value(acr_values).unwrap_or_default(),
430            );
431        }
432
433        if let Some(amr_values) = &requirements.amr_values {
434            builder = builder.detail(
435                "required_amr_values",
436                serde_json::to_value(amr_values).unwrap_or_default(),
437            );
438        }
439
440        if let Some(max_age) = requirements.max_age {
441            builder = builder.detail(
442                "max_age",
443                serde_json::Value::Number(serde_json::Number::from(max_age)),
444            );
445        }
446
447        builder.build()
448    }
449
450    /// Create error response for insufficient ACR
451    pub fn create_insufficient_acr_error(
452        &self,
453        required_acr: Vec<String>,
454        achieved_acr: Option<String>,
455        state: Option<String>,
456    ) -> OidcErrorResponse {
457        let mut builder =
458            OidcErrorResponse::new(OidcErrorCode::UnmetAuthenticationContextRequirements)
459                .description(
460                    OidcErrorCode::UnmetAuthenticationContextRequirements
461                        .get_description()
462                        .to_string(),
463                )
464                .error_uri(format!("{}#ACRRequirements", self.error_base_uri))
465                .detail(
466                    "required_acr_values",
467                    serde_json::to_value(required_acr).unwrap_or_default(),
468                );
469
470        if let Some(acr) = achieved_acr {
471            builder = builder.detail("achieved_acr", serde_json::Value::String(acr));
472        }
473
474        if let Some(s) = state {
475            builder = builder.state(s);
476        }
477
478        builder.build()
479    }
480
481    /// Create generic error response
482    pub fn create_error_response(
483        &self,
484        error_code: OidcErrorCode,
485        custom_description: Option<String>,
486        state: Option<String>,
487        additional_details: HashMap<String, serde_json::Value>,
488    ) -> OidcErrorResponse {
489        let mut builder = OidcErrorResponse::new(error_code.clone())
490            .description(
491                custom_description.unwrap_or_else(|| error_code.get_description().to_string()),
492            )
493            .error_uri(format!("{}#{:?}", self.error_base_uri, error_code))
494            .details(additional_details);
495
496        if let Some(s) = state {
497            builder = builder.state(s);
498        }
499
500        builder.build()
501    }
502
503    /// Add custom error mapping
504    pub fn add_custom_error_mapping(&mut self, identifier: String, error_code: OidcErrorCode) {
505        self.custom_error_mappings.insert(identifier, error_code);
506    }
507
508    /// Remove custom error mapping
509    pub fn remove_custom_error_mapping(&mut self, identifier: &str) -> Option<OidcErrorCode> {
510        self.custom_error_mappings.remove(identifier)
511    }
512
513    /// Get error code from string identifier (checks custom mappings first, then standard codes)
514    pub fn resolve_error_code(&self, identifier: &str) -> Option<OidcErrorCode> {
515        // Check custom mappings first
516        if let Some(error_code) = self.custom_error_mappings.get(identifier) {
517            return Some(error_code.clone());
518        }
519
520        // Delegate to FromStr for standard error codes
521        identifier.parse::<OidcErrorCode>().ok()
522    }
523
524    /// Create error response from string identifier
525    pub fn create_error_response_from_identifier(
526        &self,
527        error_identifier: &str,
528        custom_description: Option<String>,
529        state: Option<String>,
530        additional_details: HashMap<String, serde_json::Value>,
531    ) -> Result<OidcErrorResponse> {
532        match self.resolve_error_code(error_identifier) {
533            Some(error_code) => Ok(self.create_error_response(
534                error_code,
535                custom_description,
536                state,
537                additional_details,
538            )),
539            None => Err(AuthError::validation(format!(
540                "Unknown error code identifier: {}",
541                error_identifier
542            ))),
543        }
544    }
545
546    /// Get all custom error mappings
547    pub fn get_custom_mappings(&self) -> &HashMap<String, OidcErrorCode> {
548        &self.custom_error_mappings
549    }
550
551    /// Clear all custom error mappings
552    pub fn clear_custom_mappings(&mut self) {
553        self.custom_error_mappings.clear();
554    }
555
556    /// Check if custom mapping exists
557    pub fn has_custom_mapping(&self, identifier: &str) -> bool {
558        self.custom_error_mappings.contains_key(identifier)
559    }
560
561    /// Validate authentication requirements against performed authentication
562    pub fn validate_authentication_requirements(
563        &self,
564        requirements: &AuthenticationRequirements,
565        performed_acr: Option<&str>,
566        performed_amr: Option<&[String]>,
567        auth_time: Option<u64>,
568        current_time: u64,
569    ) -> Result<()> {
570        // Check ACR requirements
571        if let Some(required_acr) = &requirements.acr_values {
572            match performed_acr {
573                Some(acr) => {
574                    if !required_acr.contains(&acr.to_string()) {
575                        return Err(AuthError::validation(
576                            "Authentication context class requirements not met",
577                        ));
578                    }
579                }
580                None => {
581                    return Err(AuthError::validation(
582                        "No authentication context class provided",
583                    ));
584                }
585            }
586        }
587
588        // Check AMR requirements
589        if let Some(required_amr) = &requirements.amr_values {
590            match performed_amr {
591                Some(amr) => {
592                    for required in required_amr {
593                        if !amr.contains(required) {
594                            return Err(AuthError::validation(
595                                "Authentication method requirements not met",
596                            ));
597                        }
598                    }
599                }
600                None => {
601                    return Err(AuthError::validation("No authentication methods provided"));
602                }
603            }
604        }
605
606        // Check max_age requirement
607        if let Some(max_age) = requirements.max_age {
608            if let Some(auth_time) = auth_time {
609                if current_time - auth_time > max_age {
610                    return Err(AuthError::validation(
611                        "Authentication is too old (exceeds max_age)",
612                    ));
613                }
614            } else {
615                return Err(AuthError::validation(
616                    "Authentication time not available for max_age validation",
617                ));
618            }
619        }
620
621        Ok(())
622    }
623}
624
625#[cfg(test)]
626mod tests {
627    use super::*;
628
629    #[test]
630    fn test_error_code_descriptions() {
631        assert!(
632            !OidcErrorCode::UnmetAuthenticationRequirements
633                .get_description()
634                .is_empty()
635        );
636        assert!(OidcErrorCode::LoginRequired.requires_interaction());
637        assert!(OidcErrorCode::UnmetAuthenticationRequirements.is_authentication_error());
638    }
639
640    #[test]
641    fn test_oidc_error_code_display_roundtrip() {
642        // Every variant should round-trip through Display → FromStr
643        let codes = vec![
644            OidcErrorCode::InvalidRequest,
645            OidcErrorCode::InvalidClient,
646            OidcErrorCode::InvalidGrant,
647            OidcErrorCode::UnauthorizedClient,
648            OidcErrorCode::UnsupportedGrantType,
649            OidcErrorCode::InvalidScope,
650            OidcErrorCode::InteractionRequired,
651            OidcErrorCode::LoginRequired,
652            OidcErrorCode::AccountSelectionRequired,
653            OidcErrorCode::ConsentRequired,
654            OidcErrorCode::InvalidRequestUri,
655            OidcErrorCode::InvalidRequestObject,
656            OidcErrorCode::RequestNotSupported,
657            OidcErrorCode::RequestUriNotSupported,
658            OidcErrorCode::RegistrationNotSupported,
659            OidcErrorCode::UnmetAuthenticationRequirements,
660            OidcErrorCode::UnmetAuthenticationContextRequirements,
661            OidcErrorCode::SessionSelectionRequired,
662            OidcErrorCode::AuthenticationMethodRequired,
663            OidcErrorCode::InsufficientIdentityAssurance,
664            OidcErrorCode::TemporarilyUnavailable,
665            OidcErrorCode::RegistrationRequired,
666            OidcErrorCode::UnsupportedPromptValue,
667            OidcErrorCode::UserSelectionRequired,
668        ];
669
670        for code in codes {
671            let s = code.to_string();
672            let parsed: OidcErrorCode = s.parse().unwrap();
673            assert_eq!(parsed, code);
674        }
675    }
676
677    #[test]
678    fn test_oidc_error_code_from_str_invalid() {
679        let result = "not_a_real_error".parse::<OidcErrorCode>();
680        assert!(result.is_err());
681    }
682
683    #[test]
684    fn test_oidc_error_response_builder() {
685        let resp = OidcErrorResponse::new(OidcErrorCode::LoginRequired)
686            .description("Session expired")
687            .error_uri("https://example.com/errors#login")
688            .state("abc123")
689            .detail("session_id", serde_json::json!("sess-42"))
690            .build();
691
692        assert_eq!(resp.error, OidcErrorCode::LoginRequired);
693        assert_eq!(resp.error_description.as_deref(), Some("Session expired"));
694        assert_eq!(
695            resp.error_uri.as_deref(),
696            Some("https://example.com/errors#login")
697        );
698        assert_eq!(resp.state.as_deref(), Some("abc123"));
699        assert_eq!(
700            resp.additional_details.get("session_id"),
701            Some(&serde_json::json!("sess-42"))
702        );
703    }
704
705    #[test]
706    fn test_unmet_auth_requirements_error() {
707        let manager = OidcErrorManager::default();
708        let requirements = AuthenticationRequirements {
709            acr_values: Some(vec!["urn:mace:incommon:iap:silver".to_string()]),
710            amr_values: Some(vec!["pwd".to_string(), "mfa".to_string()]),
711            max_age: Some(3600),
712            identity_assurance_level: None,
713        };
714
715        let error = manager
716            .create_unmet_auth_requirements_error(requirements, Some("state123".to_string()));
717
718        assert_eq!(error.error, OidcErrorCode::UnmetAuthenticationRequirements);
719        assert!(error.error_description.is_some());
720        assert_eq!(error.state.as_ref().unwrap(), "state123");
721        assert!(error.additional_details.contains_key("required_acr_values"));
722        assert!(error.additional_details.contains_key("required_amr_values"));
723    }
724
725    #[test]
726    fn test_custom_error_mappings() {
727        let mut manager = OidcErrorManager::default();
728
729        // Test adding custom error mapping
730        manager.add_custom_error_mapping(
731            "custom_validation_failed".to_string(),
732            OidcErrorCode::InvalidRequest,
733        );
734
735        // Test resolving custom error code
736        let resolved = manager.resolve_error_code("custom_validation_failed");
737        assert_eq!(resolved, Some(OidcErrorCode::InvalidRequest));
738
739        // Test resolving standard error code
740        let standard = manager.resolve_error_code("login_required");
741        assert_eq!(standard, Some(OidcErrorCode::LoginRequired));
742
743        // Test resolving unknown error code
744        let unknown = manager.resolve_error_code("nonexistent_error");
745        assert_eq!(unknown, None);
746
747        // Test has_custom_mapping
748        assert!(manager.has_custom_mapping("custom_validation_failed"));
749        assert!(!manager.has_custom_mapping("login_required"));
750
751        // Test creating error response from identifier
752        let error_response = manager
753            .create_error_response_from_identifier(
754                "custom_validation_failed",
755                Some("Custom validation error".to_string()),
756                Some("state123".to_string()),
757                HashMap::new(),
758            )
759            .unwrap();
760
761        assert_eq!(error_response.error, OidcErrorCode::InvalidRequest);
762        assert_eq!(error_response.state.as_ref().unwrap(), "state123");
763
764        // Test remove custom mapping
765        let removed = manager.remove_custom_error_mapping("custom_validation_failed");
766        assert_eq!(removed, Some(OidcErrorCode::InvalidRequest));
767        assert!(!manager.has_custom_mapping("custom_validation_failed"));
768
769        // Test clear all mappings
770        manager.add_custom_error_mapping("test1".to_string(), OidcErrorCode::InvalidScope);
771        manager.add_custom_error_mapping("test2".to_string(), OidcErrorCode::ConsentRequired);
772        assert_eq!(manager.get_custom_mappings().len(), 2);
773
774        manager.clear_custom_mappings();
775        assert_eq!(manager.get_custom_mappings().len(), 0);
776    }
777
778    #[test]
779    fn test_error_response_from_unknown_identifier() {
780        let manager = OidcErrorManager::default();
781
782        let result = manager.create_error_response_from_identifier(
783            "unknown_error_code",
784            None,
785            None,
786            HashMap::new(),
787        );
788
789        assert!(result.is_err());
790        assert!(
791            result
792                .unwrap_err()
793                .to_string()
794                .contains("Unknown error code identifier")
795        );
796    }
797
798    #[test]
799    fn test_custom_error_mappings_real_world_scenario() {
800        let mut manager = OidcErrorManager::default();
801
802        // Add domain-specific error mappings for a banking application
803        manager.add_custom_error_mapping(
804            "account_frozen".to_string(),
805            OidcErrorCode::AuthenticationMethodRequired,
806        );
807        manager.add_custom_error_mapping(
808            "kyc_verification_required".to_string(),
809            OidcErrorCode::InsufficientIdentityAssurance,
810        );
811        manager.add_custom_error_mapping(
812            "payment_limit_exceeded".to_string(),
813            OidcErrorCode::ConsentRequired,
814        );
815
816        // Demonstrate custom error response creation
817        let mut additional_details = HashMap::new();
818        additional_details.insert(
819            "account_id".to_string(),
820            serde_json::Value::String("acc-12345".to_string()),
821        );
822        additional_details.insert(
823            "freeze_reason".to_string(),
824            serde_json::Value::String("Suspicious activity detected".to_string()),
825        );
826
827        let error_response = manager
828            .create_error_response_from_identifier(
829                "account_frozen",
830                Some("Account authentication required due to security freeze".to_string()),
831                Some("banking-session-456".to_string()),
832                additional_details,
833            )
834            .unwrap();
835
836        assert_eq!(
837            error_response.error,
838            OidcErrorCode::AuthenticationMethodRequired
839        );
840        assert_eq!(
841            error_response.error_description.as_ref().unwrap(),
842            "Account authentication required due to security freeze"
843        );
844        assert_eq!(
845            error_response.state.as_ref().unwrap(),
846            "banking-session-456"
847        );
848        assert!(error_response.additional_details.contains_key("account_id"));
849        assert!(
850            error_response
851                .additional_details
852                .contains_key("freeze_reason")
853        );
854
855        // Verify custom mappings take precedence over standard ones
856        manager.add_custom_error_mapping(
857            "login_required".to_string(),
858            OidcErrorCode::RegistrationRequired, // Override standard behavior
859        );
860
861        let overridden_response = manager
862            .create_error_response_from_identifier(
863                "login_required",
864                Some("User registration required before login".to_string()),
865                None,
866                HashMap::new(),
867            )
868            .unwrap();
869
870        assert_eq!(
871            overridden_response.error,
872            OidcErrorCode::RegistrationRequired
873        );
874
875        // Verify management functions
876        assert_eq!(manager.get_custom_mappings().len(), 4);
877        assert!(manager.has_custom_mapping("account_frozen"));
878        assert!(!manager.has_custom_mapping("nonexistent_mapping"));
879
880        // Clean up specific mapping
881        let removed = manager.remove_custom_error_mapping("account_frozen");
882        assert_eq!(removed, Some(OidcErrorCode::AuthenticationMethodRequired));
883        assert!(!manager.has_custom_mapping("account_frozen"));
884
885        // Test clear all
886        manager.clear_custom_mappings();
887        assert_eq!(manager.get_custom_mappings().len(), 0);
888    }
889
890    #[test]
891    fn test_standard_error_code_resolution() {
892        let manager = OidcErrorManager::default();
893
894        // Test all standard error codes
895        assert_eq!(
896            manager.resolve_error_code("invalid_request"),
897            Some(OidcErrorCode::InvalidRequest)
898        );
899        assert_eq!(
900            manager.resolve_error_code("unmet_authentication_requirements"),
901            Some(OidcErrorCode::UnmetAuthenticationRequirements)
902        );
903        assert_eq!(
904            manager.resolve_error_code("session_selection_required"),
905            Some(OidcErrorCode::SessionSelectionRequired)
906        );
907
908        // Custom mappings take precedence over standard codes
909        let mut manager = OidcErrorManager::default();
910        manager.add_custom_error_mapping(
911            "login_required".to_string(),
912            OidcErrorCode::ConsentRequired, // Override standard mapping
913        );
914
915        assert_eq!(
916            manager.resolve_error_code("login_required"),
917            Some(OidcErrorCode::ConsentRequired) // Should return custom mapping
918        );
919    }
920}