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    // Intentional builder-entry-point naming: `new` starts the fluent chain shown in the
201    // doc example above and in existing callers; renaming to `builder` would be a breaking
202    // public API change out of scope for a lint cleanup.
203    #[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
220/// Fluent builder for [`OidcErrorResponse`].
221pub struct OidcErrorResponseBuilder {
222    inner: OidcErrorResponse,
223}
224
225impl OidcErrorResponseBuilder {
226    /// Set a human-readable error description.
227    pub fn description(mut self, desc: impl Into<String>) -> Self {
228        self.inner.error_description = Some(desc.into());
229        self
230    }
231
232    /// Set the error documentation URI.
233    pub fn error_uri(mut self, uri: impl Into<String>) -> Self {
234        self.inner.error_uri = Some(uri.into());
235        self
236    }
237
238    /// Set the OAuth `state` parameter.
239    pub fn state(mut self, state: impl Into<String>) -> Self {
240        self.inner.state = Some(state.into());
241        self
242    }
243
244    /// Add a single additional detail.
245    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    /// Set all additional details at once (replaces any previously added).
251    pub fn details(mut self, details: HashMap<String, serde_json::Value>) -> Self {
252        self.inner.additional_details = details;
253        self
254    }
255
256    /// Consume the builder and return the [`OidcErrorResponse`].
257    pub fn build(self) -> OidcErrorResponse {
258        self.inner
259    }
260}
261
262/// Authentication requirements details
263#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct AuthenticationRequirements {
265    /// Required authentication context class references
266    #[serde(skip_serializing_if = "Option::is_none")]
267    pub acr_values: Option<Vec<String>>,
268    /// Required authentication methods references
269    #[serde(skip_serializing_if = "Option::is_none")]
270    pub amr_values: Option<Vec<String>>,
271    /// Maximum authentication age
272    #[serde(skip_serializing_if = "Option::is_none")]
273    pub max_age: Option<u64>,
274    /// Required identity assurance level
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub identity_assurance_level: Option<String>,
277}
278
279/// Error handling manager for OpenID Connect
280#[derive(Debug, Clone)]
281pub struct OidcErrorManager {
282    /// Base error documentation URI
283    error_base_uri: String,
284    /// Custom error mappings
285    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    /// Get standard error description for error code
300    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            // Extended error codes
344            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    /// Check if this error code requires user interaction
375    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    /// Check if this error code indicates an authentication issue
390    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    /// Create new error manager
404    pub fn new(error_base_uri: String) -> Self {
405        Self {
406            error_base_uri,
407            custom_error_mappings: HashMap::new(),
408        }
409    }
410
411    /// Create error response for unmet authentication requirements
412    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    /// Create error response for insufficient ACR
457    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    /// Create generic error response
488    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    /// Add custom error mapping
510    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    /// Remove custom error mapping
515    pub fn remove_custom_error_mapping(&mut self, identifier: &str) -> Option<OidcErrorCode> {
516        self.custom_error_mappings.remove(identifier)
517    }
518
519    /// Get error code from string identifier (checks custom mappings first, then standard codes)
520    pub fn resolve_error_code(&self, identifier: &str) -> Option<OidcErrorCode> {
521        // Check custom mappings first
522        if let Some(error_code) = self.custom_error_mappings.get(identifier) {
523            return Some(error_code.clone());
524        }
525
526        // Delegate to FromStr for standard error codes
527        identifier.parse::<OidcErrorCode>().ok()
528    }
529
530    /// Create error response from string identifier
531    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    /// Get all custom error mappings
553    pub fn get_custom_mappings(&self) -> &HashMap<String, OidcErrorCode> {
554        &self.custom_error_mappings
555    }
556
557    /// Clear all custom error mappings
558    pub fn clear_custom_mappings(&mut self) {
559        self.custom_error_mappings.clear();
560    }
561
562    /// Check if custom mapping exists
563    pub fn has_custom_mapping(&self, identifier: &str) -> bool {
564        self.custom_error_mappings.contains_key(identifier)
565    }
566
567    /// Validate authentication requirements against performed authentication
568    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        // Check ACR requirements
577        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        // Check AMR requirements
595        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        // Check max_age requirement
613        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        // Every variant should round-trip through Display → FromStr
649        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        // Test adding custom error mapping
736        manager.add_custom_error_mapping(
737            "custom_validation_failed".to_string(),
738            OidcErrorCode::InvalidRequest,
739        );
740
741        // Test resolving custom error code
742        let resolved = manager.resolve_error_code("custom_validation_failed");
743        assert_eq!(resolved, Some(OidcErrorCode::InvalidRequest));
744
745        // Test resolving standard error code
746        let standard = manager.resolve_error_code("login_required");
747        assert_eq!(standard, Some(OidcErrorCode::LoginRequired));
748
749        // Test resolving unknown error code
750        let unknown = manager.resolve_error_code("nonexistent_error");
751        assert_eq!(unknown, None);
752
753        // Test has_custom_mapping
754        assert!(manager.has_custom_mapping("custom_validation_failed"));
755        assert!(!manager.has_custom_mapping("login_required"));
756
757        // Test creating error response from identifier
758        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        // Test remove custom mapping
771        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        // Test clear all mappings
776        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        // Add domain-specific error mappings for a banking application
809        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        // Demonstrate custom error response creation
823        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        // Verify custom mappings take precedence over standard ones
862        manager.add_custom_error_mapping(
863            "login_required".to_string(),
864            OidcErrorCode::RegistrationRequired, // Override standard behavior
865        );
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        // Verify management functions
882        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        // Clean up specific mapping
887        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        // Test clear all
892        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        // Test all standard error codes
901        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        // Custom mappings take precedence over standard codes
915        let mut manager = OidcErrorManager::default();
916        manager.add_custom_error_mapping(
917            "login_required".to_string(),
918            OidcErrorCode::ConsentRequired, // Override standard mapping
919        );
920
921        assert_eq!(
922            manager.resolve_error_code("login_required"),
923            Some(OidcErrorCode::ConsentRequired) // Should return custom mapping
924        );
925    }
926}