Skip to main content

auth_framework/
errors.rs

1//! Comprehensive error types for the AuthFramework.
2//!
3//! This module defines all error types used throughout the authentication framework,
4//! providing detailed error information for debugging, logging, and user feedback.
5//! All errors implement standard Rust error traits and provide contextual information
6//! to help diagnose issues.
7//!
8//! # Error Categories
9//!
10//! - **Authentication Errors**: Credential validation and method failures
11//! - **Authorization Errors**: Permission and access control failures
12//! - **Token Errors**: JWT creation, validation, and lifecycle issues
13//! - **Configuration Errors**: Setup and configuration problems
14//! - **Storage Errors**: Database and persistence layer issues
15//! - **Network Errors**: External service communication failures
16//! - **Cryptographic Errors**: Security operation failures
17//!
18//! # Error Handling Patterns
19//!
20//! The framework uses structured error handling with:
21//! - Contextual error messages with relevant details
22//! - Error chaining to preserve root cause information
23//! - Categorized errors for appropriate response handling
24//! - Security-safe error messages that don't leak sensitive data
25//!
26//! # Example Error Handling
27//!
28//! ```rust,no_run
29//! use auth_framework::{AuthFramework, AuthError};
30//! use auth_framework::authentication::credentials::Credential;
31//! use auth_framework::authentication::CredentialMetadata;
32//!
33//! # #[tokio::main]
34//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
35//! # let auth_framework: AuthFramework = unimplemented!();
36//! # let credential: Credential = unimplemented!();
37//! # fn handle_success<T>(_: T) {}
38//! # fn respond_with_auth_failure() {}
39//! # fn respond_with_rate_limit(_: Option<u64>) {}
40//! # fn respond_with_system_error() {}
41//! match auth_framework.authenticate("password", credential).await {
42//!     Ok(result) => handle_success(result),
43//!     Err(AuthError::InvalidCredential { credential_type, message, .. }) => {
44//!         tracing::warn!("Invalid {} credential: {}", credential_type, message);
45//!         respond_with_auth_failure()
46//!     },
47//!     Err(AuthError::RateLimit { message, .. }) => {
48//!         respond_with_rate_limit(None)
49//!     },
50//!     Err(e) => {
51//!         tracing::error!("Authentication system error: {}", e);
52//!         respond_with_system_error()
53//!     }
54//! }
55//! # Ok(())
56//! # }
57//! ```
58//!
59//! # Security Considerations
60//!
61//! Error messages are designed to:
62//! - Provide useful debugging information for developers
63//! - Avoid exposing sensitive information to potential attackers
64//! - Enable proper security monitoring and alerting
65//! - Support compliance requirements for audit logging
66
67use thiserror::Error;
68
69/// Type alias for Results in the authentication framework.
70///
71/// This alias simplifies error handling throughout the framework by defaulting
72/// to `AuthError` as the error type while allowing flexibility for other error
73/// types when needed.
74pub type Result<T, E = AuthError> = std::result::Result<T, E>;
75
76/// Comprehensive error type covering all authentication and authorization failures.
77///
78/// `AuthError` provides detailed error information for all aspects of the authentication
79/// framework, from configuration issues to runtime failures. Each error variant includes
80/// contextual information to aid in debugging and provide appropriate user feedback.
81///
82/// This enhanced error type provides:
83/// - **Actionable error messages** with specific suggestions for fixes
84/// - **Documentation links** to relevant guides and troubleshooting
85/// - **Contextual help** that guides users to solutions
86/// - **Security-aware messaging** that doesn't leak sensitive information
87///
88/// # Error Categories
89///
90/// ## Configuration Errors
91/// Errors that occur during framework setup and configuration validation.
92///
93/// ## Authentication Errors
94/// Errors related to credential validation and authentication method execution.
95///
96/// ## Authorization Errors
97/// Errors related to permission checking and access control.
98///
99/// ## Token Errors
100/// JWT token creation, validation, expiration, and lifecycle issues.
101///
102/// ## Storage Errors
103/// Database connectivity, query failures, and data persistence issues.
104///
105/// ## Network Errors
106/// External service communication, timeouts, and connectivity problems.
107///
108/// ## Cryptographic Errors
109/// Encryption, decryption, signing, and other security operation failures.
110///
111/// # Enhanced Error Handling
112///
113/// ```rust,no_run
114/// use auth_framework::AuthError;
115///
116/// # let auth_result: auth_framework::errors::Result<()> = Ok(());
117/// // Enhanced error handling with contextual help
118/// match auth_result {
119///     Err(AuthError::Configuration { message, help, docs_url, .. }) => {
120///         eprintln!("Configuration Error: {}", message);
121///         if let Some(help) = help {
122///             eprintln!("Help: {}", help);
123///         }
124///         if let Some(docs) = docs_url {
125///             eprintln!("See: {}", docs);
126///         }
127///     },
128///     Err(AuthError::InvalidCredential { credential_type, message, .. }) => {
129///         eprintln!("Invalid {}: {}", credential_type, message);
130///     },
131///     // ... handle other error types
132///     _ => {}
133/// }
134/// ```
135///
136/// # Security Notes
137///
138/// Error messages are carefully crafted to:
139/// - Provide sufficient detail for debugging and monitoring
140/// - Avoid exposing sensitive information that could aid attackers
141/// - Enable security teams to identify potential threats
142/// - Support compliance and audit requirements
143/// - Guide users to secure solutions and best practices
144#[derive(Error, Debug)]
145pub enum AuthError {
146    /// Configuration validation and setup errors.
147    ///
148    /// These errors occur when the authentication framework is misconfigured
149    /// or when configuration validation fails during startup.
150    #[error("Configuration error: {message}")]
151    Configuration {
152        message: String,
153        #[source]
154        source: Option<Box<dyn std::error::Error + Send + Sync>>,
155        /// Helpful guidance for fixing the issue
156        help: Option<String>,
157        /// Link to relevant documentation
158        docs_url: Option<String>,
159        /// Specific fix suggestion with commands or code
160        suggested_fix: Option<String>,
161    },
162
163    /// Authentication method execution errors.
164    ///
165    /// These errors occur when a specific authentication method fails to
166    /// execute properly, such as OAuth provider communication failures.
167    #[error("Authentication method '{method}' error: {message}")]
168    AuthMethod {
169        method: String,
170        message: String,
171        /// Helpful guidance for fixing the issue
172        help: Option<String>,
173        /// Link to relevant documentation
174        docs_url: Option<String>,
175        /// Specific fix suggestion
176        suggested_fix: Option<String>,
177    },
178
179    /// Token-related errors
180    #[error("Token error: {0}")]
181    Token(#[from] TokenError),
182
183    /// Permission-related errors
184    #[error("Permission error: {0}")]
185    Permission(#[from] PermissionError),
186
187    /// Storage-related errors
188    #[error("Storage error: {0}")]
189    Storage(#[from] StorageError),
190
191    /// Network/HTTP errors
192    #[error("Network error: {0}")]
193    Network(#[from] reqwest::Error),
194
195    /// JSON parsing errors
196    #[error("JSON error: {0}")]
197    Json(#[from] serde_json::Error),
198
199    /// JWT errors
200    #[error("JWT error: {0}")]
201    Jwt(#[from] jsonwebtoken::errors::Error),
202
203    /// YAML parsing errors
204    #[error("YAML error: {0}")]
205    Yaml(#[from] serde_saphyr::Error),
206
207    /// TOML parsing errors
208    #[error("TOML error: {0}")]
209    Toml(#[from] toml::ser::Error),
210
211    /// Prometheus metrics errors
212    #[cfg(feature = "prometheus")]
213    #[error("Metrics error: {0}")]
214    Metrics(#[from] prometheus::Error),
215
216    /// IO errors
217    #[error("IO error: {0}")]
218    Io(#[from] std::io::Error),
219
220    /// CLI interaction errors
221    #[error("CLI error: {0}")]
222    Cli(String),
223
224    /// System time errors
225    #[error("System time error: {0}")]
226    SystemTime(#[from] std::time::SystemTimeError),
227
228    /// Rate limiting errors
229    #[error("Rate limit exceeded: {message}")]
230    RateLimit { message: String },
231
232    /// Session-related errors
233    #[error(
234        "Too many concurrent sessions for user (limit reached). \
235             Revoke an existing session before creating a new one."
236    )]
237    TooManyConcurrentSessions,
238
239    /// MFA-related errors
240    #[error("MFA error: {0}")]
241    Mfa(#[from] MfaError),
242
243    /// Device flow errors
244    #[error("Device flow error: {0}")]
245    DeviceFlow(#[from] DeviceFlowError),
246
247    /// OAuth provider errors
248    #[error("OAuth provider error: {0}")]
249    OAuthProvider(#[from] OAuthProviderError),
250
251    /// The stored password hash does not match the supplied credential.
252    ///
253    /// This typically means the user entered the wrong password. Do **not**
254    /// reveal which field (username vs. password) was incorrect to the caller.
255    #[error("Password verification failed: {0}")]
256    PasswordVerification(String),
257
258    /// The password hashing algorithm (argon2/bcrypt) encountered an error.
259    #[error("Password hashing failed: {0}")]
260    PasswordHashing(String),
261
262    /// No user record exists for the given identifier.
263    #[error("User not found. The requested user ID does not exist in the store.")]
264    UserNotFound,
265
266    /// A request parameter failed validation (e.g. empty username, invalid email format).
267    #[error("Invalid input: {0}")]
268    InvalidInput(String),
269
270    /// A hardware security key (FIDO2 / WebAuthn) operation failed.
271    #[error("Hardware token error: {0}")]
272    HardwareToken(String),
273
274    /// A one-time backup code was rejected (already used, incorrect, or expired).
275    #[error("Backup code verification failed: {0}")]
276    BackupCodeVerification(String),
277
278    /// Failed to hash a backup code for secure storage.
279    #[error("Backup code hashing failed: {0}")]
280    BackupCodeHashing(String),
281
282    /// The TOTP or MFA secret is in an invalid format (e.g. not valid Base32).
283    #[error("Invalid secret format")]
284    InvalidSecret,
285
286    /// An error occurred while reading or updating a user profile.
287    #[error("User profile error: {message}")]
288    UserProfile { message: String },
289
290    /// Credential validation errors
291    #[error("Invalid credential: {credential_type} - {message}")]
292    InvalidCredential {
293        credential_type: String,
294        message: String,
295    },
296
297    /// An authentication operation did not complete within the allowed window.
298    #[error("Authentication timeout after {timeout_seconds} seconds")]
299    Timeout { timeout_seconds: u64 },
300
301    /// Provider configuration missing
302    #[error(
303        "Provider '{provider}' is not configured or supported. \
304             Add it via AuthConfig::method_config() or check available providers."
305    )]
306    ProviderNotConfigured { provider: String },
307
308    /// Cryptography errors
309    #[error("Cryptography error: {message}")]
310    Crypto { message: String },
311
312    /// Validation errors
313    #[error("Validation error: {message}")]
314    Validation { message: String },
315
316    /// Generic internal errors
317    #[error("Internal error: {message}")]
318    Internal { message: String },
319
320    /// Invalid request error
321    #[error("Invalid request: {0}")]
322    InvalidRequest(String),
323
324    /// Step-up authentication required
325    #[error(
326        "Step-up authentication required: current level '{current_level}', required level '{required_level}'"
327    )]
328    StepUpRequired {
329        current_level: String,
330        required_level: String,
331        step_up_url: String,
332    },
333
334    /// A session-layer error (e.g. session not found, session expired, store failure).
335    #[error("Session error: {0}")]
336    SessionError(String),
337
338    /// The caller lacks valid credentials or the credentials have been revoked.
339    #[error("Unauthorized: {0}")]
340    Unauthorized(String),
341
342    /// Token creation failed at the signing or encoding stage.
343    ///
344    /// Consider using [`AuthError::token`] for richer [`TokenError`] variants.
345    #[error("Token generation error: {0}")]
346    TokenGeneration(String),
347
348    /// Invalid token error.
349    ///
350    /// **Prefer** [`AuthError::token`] which routes through the structured
351    /// [`TokenError`] hierarchy for consistent token error handling.
352    #[deprecated(
353        since = "0.5.0",
354        note = "Use `AuthError::token(msg)` instead — it routes through the structured TokenError hierarchy"
355    )]
356    #[error("Invalid token: {0}")]
357    InvalidToken(String),
358
359    /// The named authentication provider is not compiled in or not recognized.
360    #[error("Unsupported provider: {0}")]
361    UnsupportedProvider(String),
362
363    /// Network error with custom message.
364    ///
365    /// **Prefer** [`AuthError::Internal`] with a descriptive message, or let
366    /// [`reqwest::Error`] convert automatically via the [`From`] impl on
367    /// [`AuthError::Network`].
368    #[deprecated(
369        since = "0.5.0",
370        note = "Use `AuthError::internal(msg)` or let `reqwest::Error` convert via `AuthError::Network` instead"
371    )]
372    #[error("Network error: {0}")]
373    NetworkError(String),
374
375    /// Parse error with custom message.
376    ///
377    /// **Prefer** [`AuthError::Internal`] with a descriptive message, or let
378    /// [`serde_json::Error`] convert automatically via the [`From`] impl on
379    /// [`AuthError::Json`].
380    #[deprecated(
381        since = "0.5.0",
382        note = "Use `AuthError::internal(msg)` or let serde errors convert via `AuthError::Json` instead"
383    )]
384    #[error("Parse error: {0}")]
385    ParseError(String),
386
387    /// Configuration error with custom message.
388    ///
389    /// **Prefer** [`AuthError::config`] or [`AuthError::config_with_help`] which
390    /// carry richer context (help text, docs URL, suggested fix).
391    #[deprecated(
392        since = "0.5.0",
393        note = "Use `AuthError::config(msg)` instead — it provides richer context fields"
394    )]
395    #[error("Configuration error: {0}")]
396    ConfigurationError(String),
397}
398
399/// Token-specific errors.
400///
401/// Covers the lifecycle of authentication tokens: creation, validation,
402/// refresh, and revocation.
403#[derive(Error, Debug)]
404pub enum TokenError {
405    /// The token's `exp` claim is in the past.
406    #[error("Token has expired")]
407    Expired,
408
409    /// The token failed signature verification or structural validation.
410    #[error("Token is invalid: {message}")]
411    Invalid { message: String },
412
413    /// No token matching the given identifier exists in the store.
414    #[error("Token not found")]
415    NotFound,
416
417    /// The request did not include a required token (e.g. missing `Authorization` header).
418    #[error("Token is missing")]
419    Missing,
420
421    /// A new token could not be issued (e.g. signing key unavailable).
422    #[error("Token creation failed: {message}")]
423    CreationFailed { message: String },
424
425    /// An existing token could not be refreshed (e.g. refresh token revoked).
426    #[error("Token refresh failed: {message}")]
427    RefreshFailed { message: String },
428
429    /// Token revocation did not complete (e.g. storage write failure).
430    #[error("Token revocation failed: {message}")]
431    RevocationFailed { message: String },
432}
433
434/// Permission and access-control errors.
435///
436/// Returned when an authenticated principal lacks the required permissions
437/// or roles to perform an operation.
438#[derive(Error, Debug)]
439pub enum PermissionError {
440    /// The principal does not hold the required permission for the target resource.
441    #[error("Access denied: missing permission '{permission}' for resource '{resource}'")]
442    AccessDenied {
443        permission: String,
444        resource: String,
445    },
446
447    /// The specified role does not exist in the role store.
448    #[error("Role '{role}' not found")]
449    RoleNotFound { role: String },
450
451    /// The specified permission identifier does not exist.
452    #[error("Permission '{permission}' not found")]
453    PermissionNotFound { permission: String },
454
455    /// A permission string could not be parsed (e.g. missing `resource:action` separator).
456    #[error("Invalid permission format: {message}")]
457    InvalidFormat { message: String },
458
459    /// General permission denial with a descriptive message.
460    #[error("Permission denied: {message}")]
461    Denied {
462        action: String,
463        resource: String,
464        message: String,
465    },
466}
467
468/// Storage backend errors.
469///
470/// Covers connectivity, query execution, and serialization issues for
471/// all storage backends (Memory, PostgreSQL, Redis, SQLite).
472#[derive(Error, Debug)]
473pub enum StorageError {
474    /// Could not establish a connection to the storage backend.
475    #[error("Connection failed: {message}")]
476    ConnectionFailed { message: String },
477
478    /// A read or write operation against the store failed.
479    #[error("Operation failed: {message}")]
480    OperationFailed { message: String },
481
482    /// Data could not be serialized to or deserialized from the storage format.
483    #[error("Serialization error: {message}")]
484    Serialization { message: String },
485
486    /// The configured storage backend is unreachable or not initialized.
487    #[error("Storage backend not available")]
488    BackendUnavailable,
489}
490
491/// Multi-factor authentication errors.
492#[derive(Error, Debug)]
493pub enum MfaError {
494    /// The MFA challenge window has elapsed; the user must request a new challenge.
495    #[error("MFA challenge expired")]
496    ChallengeExpired,
497
498    /// The TOTP or one-time code provided by the user is incorrect.
499    #[error("Invalid MFA code")]
500    InvalidCode,
501
502    /// The requested MFA method (e.g. SMS, hardware key) is not enabled.
503    #[error("MFA method not supported: {method}")]
504    MethodNotSupported { method: String },
505
506    /// MFA has not been configured for this account yet.
507    #[error("MFA setup required")]
508    SetupRequired,
509
510    /// MFA verification failed for a reason described in `message`.
511    #[error("MFA verification failed: {message}")]
512    VerificationFailed { message: String },
513}
514
515/// Device Authorization Grant (RFC 8628) errors.
516///
517/// These map 1-to-1 to the error codes defined in RFC 8628 §3.5.
518#[derive(Error, Debug)]
519pub enum DeviceFlowError {
520    /// The user has not yet completed authorization on the verification URI.
521    #[error("Authorization pending - user has not yet completed authorization")]
522    AuthorizationPending,
523
524    /// The client is polling faster than the allowed `interval`.
525    #[error("Slow down - polling too frequently")]
526    SlowDown,
527
528    /// The device code has exceeded its `expires_in` window.
529    #[error("Device code expired")]
530    ExpiredToken,
531
532    /// The end user denied the authorization request.
533    #[error("Access denied by user")]
534    AccessDenied,
535
536    /// The device code presented by the client is not recognized.
537    #[error("Invalid device code")]
538    InvalidDeviceCode,
539
540    /// The grant type is not supported by this server.
541    #[error("Unsupported grant type")]
542    UnsupportedGrantType,
543}
544
545/// OAuth 2.0 provider interaction errors.
546///
547/// Covers issues encountered when communicating with upstream OAuth providers
548/// or when validating OAuth protocol messages.
549#[derive(Error, Debug)]
550pub enum OAuthProviderError {
551    /// The authorization code is expired, already consumed, or invalid.
552    #[error("Invalid authorization code")]
553    InvalidAuthorizationCode,
554
555    /// The `redirect_uri` does not match the registered value for the client.
556    #[error("Invalid redirect URI")]
557    InvalidRedirectUri,
558
559    /// The client ID or client secret is incorrect.
560    #[error("Invalid client credentials")]
561    InvalidClientCredentials,
562
563    /// The granted scopes do not satisfy the required scopes for the operation.
564    #[error("Insufficient scope: required '{required}', granted '{granted}'")]
565    InsufficientScope { required: String, granted: String },
566
567    /// The provider does not implement the requested feature.
568    #[error("Provider '{provider}' does not support '{feature}'")]
569    UnsupportedFeature { provider: String, feature: String },
570
571    /// The upstream provider returned a rate-limit response.
572    #[error("Rate limited by provider: {message}")]
573    RateLimited { message: String },
574}
575
576impl AuthError {
577    /// Create a new configuration error.
578    ///
579    /// # Example
580    ///
581    /// ```rust
582    /// use auth_framework::AuthError;
583    ///
584    /// let err = AuthError::config("Missing database URL");
585    /// assert!(err.to_string().contains("Missing database URL"));
586    /// ```
587    pub fn config(message: impl Into<String>) -> Self {
588        Self::Configuration {
589            message: message.into(),
590            source: None,
591            help: None,
592            docs_url: None,
593            suggested_fix: None,
594        }
595    }
596
597    /// Create a configuration error with helpful context.
598    ///
599    /// Includes a human-readable `help` string and an optional `suggested_fix`
600    /// that can be displayed by CLI tools or IDE integrations.
601    ///
602    /// # Example
603    ///
604    /// ```rust
605    /// use auth_framework::AuthError;
606    ///
607    /// let err = AuthError::config_with_help(
608    ///     "JWT secret not set",
609    ///     "Set the JWT_SECRET environment variable",
610    ///     Some("export JWT_SECRET=$(openssl rand -hex 32)".into()),
611    /// );
612    /// assert!(err.to_string().contains("JWT secret not set"));
613    /// ```
614    pub fn config_with_help(
615        message: impl Into<String>,
616        help: impl Into<String>,
617        suggested_fix: Option<String>,
618    ) -> Self {
619        Self::Configuration {
620            message: message.into(),
621            source: None,
622            help: Some(help.into()),
623            docs_url: Some(
624                "https://docs.rs/auth-framework/latest/auth_framework/config/".to_string(),
625            ),
626            suggested_fix,
627        }
628    }
629
630    /// Create a JWT secret validation error with helpful guidance.
631    ///
632    /// # Example
633    ///
634    /// ```rust
635    /// use auth_framework::AuthError;
636    ///
637    /// let err = AuthError::jwt_secret_too_short(16);
638    /// assert!(err.to_string().contains("16 characters"));
639    /// ```
640    pub fn jwt_secret_too_short(current_length: usize) -> Self {
641        Self::Configuration {
642            message: format!(
643                "JWT secret too short (got {} characters, need 32+ for security)",
644                current_length
645            ),
646            source: None,
647            help: Some("Use a cryptographically secure random string of at least 32 characters".to_string()),
648            docs_url: Some("https://docs.rs/auth-framework/latest/auth_framework/config/struct.SecurityConfig.html".to_string()),
649            suggested_fix: Some("Generate a secure secret: `openssl rand -hex 32`".to_string()),
650        }
651    }
652
653    /// Create a production environment error with guidance.
654    ///
655    /// # Example
656    ///
657    /// ```rust
658    /// use auth_framework::AuthError;
659    ///
660    /// let err = AuthError::production_memory_storage();
661    /// assert!(err.to_string().contains("Memory storage"));
662    /// ```
663    pub fn production_memory_storage() -> Self {
664        Self::Configuration {
665            message: "Memory storage is not suitable for production environments".to_string(),
666            source: None,
667            help: Some("Use a persistent storage backend like PostgreSQL or Redis".to_string()),
668            docs_url: Some("https://docs.rs/auth-framework/latest/auth_framework/storage/".to_string()),
669            suggested_fix: Some("Configure PostgreSQL: .with_postgres(\"postgresql://...\") or Redis: .with_redis(\"redis://...\")".to_string()),
670        }
671    }
672
673    /// Create a new auth method error.
674    ///
675    /// # Example
676    ///
677    /// ```rust
678    /// use auth_framework::AuthError;
679    ///
680    /// let err = AuthError::auth_method("oauth2", "token endpoint unreachable");
681    /// assert!(err.to_string().contains("oauth2"));
682    /// ```
683    pub fn auth_method(method: impl Into<String>, message: impl Into<String>) -> Self {
684        Self::AuthMethod {
685            method: method.into(),
686            message: message.into(),
687            help: None,
688            docs_url: None,
689            suggested_fix: None,
690        }
691    }
692
693    /// Create an auth method error with helpful context.
694    ///
695    /// # Example
696    ///
697    /// ```rust
698    /// use auth_framework::AuthError;
699    ///
700    /// let err = AuthError::auth_method_with_help(
701    ///     "saml",
702    ///     "certificate expired",
703    ///     "Renew the SAML signing certificate",
704    ///     Some("openssl x509 -req -in cert.csr -signkey key.pem -out cert.pem".into()),
705    /// );
706    /// assert!(err.to_string().contains("saml"));
707    /// ```
708    pub fn auth_method_with_help(
709        method: impl Into<String>,
710        message: impl Into<String>,
711        help: impl Into<String>,
712        suggested_fix: Option<String>,
713    ) -> Self {
714        Self::AuthMethod {
715            method: method.into(),
716            message: message.into(),
717            help: Some(help.into()),
718            docs_url: Some(
719                "https://docs.rs/auth-framework/latest/auth_framework/methods/".to_string(),
720            ),
721            suggested_fix,
722        }
723    }
724
725    /// Create a new rate limit error.
726    ///
727    /// # Example
728    ///
729    /// ```rust
730    /// use auth_framework::AuthError;
731    ///
732    /// let err = AuthError::rate_limit("too many login attempts");
733    /// assert!(err.to_string().contains("too many login attempts"));
734    /// ```
735    pub fn rate_limit(message: impl Into<String>) -> Self {
736        Self::RateLimit {
737            message: message.into(),
738        }
739    }
740
741    /// Create a new crypto error.
742    ///
743    /// # Example
744    ///
745    /// ```rust
746    /// use auth_framework::AuthError;
747    ///
748    /// let err = AuthError::crypto("HMAC key too short");
749    /// assert!(err.to_string().contains("HMAC key too short"));
750    /// ```
751    pub fn crypto(message: impl Into<String>) -> Self {
752        Self::Crypto {
753            message: message.into(),
754        }
755    }
756
757    /// Create a new validation error.
758    ///
759    /// # Example
760    ///
761    /// ```rust
762    /// use auth_framework::AuthError;
763    ///
764    /// let err = AuthError::validation("email format invalid");
765    /// assert!(err.to_string().contains("email format invalid"));
766    /// ```
767    pub fn validation(message: impl Into<String>) -> Self {
768        Self::Validation {
769            message: message.into(),
770        }
771    }
772
773    /// Create a new internal error.
774    ///
775    /// # Example
776    ///
777    /// ```rust
778    /// use auth_framework::AuthError;
779    ///
780    /// let err = AuthError::internal("unexpected state");
781    /// assert!(err.to_string().contains("unexpected state"));
782    /// ```
783    pub fn internal(message: impl Into<String>) -> Self {
784        Self::Internal {
785            message: message.into(),
786        }
787    }
788
789    /// Create an authorization error.
790    ///
791    /// # Example
792    ///
793    /// ```rust
794    /// use auth_framework::AuthError;
795    ///
796    /// let err = AuthError::authorization("insufficient privileges");
797    /// assert!(err.to_string().contains("insufficient privileges"));
798    /// ```
799    pub fn authorization(message: impl Into<String>) -> Self {
800        Self::Permission(PermissionError::Denied {
801            action: "authorize".to_string(),
802            resource: "resource".to_string(),
803            message: message.into(),
804        })
805    }
806
807    /// Create an access denied error.
808    ///
809    /// # Example
810    ///
811    /// ```rust
812    /// use auth_framework::AuthError;
813    ///
814    /// let err = AuthError::access_denied("admin role required");
815    /// assert!(err.to_string().contains("admin role required"));
816    /// ```
817    pub fn access_denied(message: impl Into<String>) -> Self {
818        Self::Permission(PermissionError::Denied {
819            action: "access".to_string(),
820            resource: "resource".to_string(),
821            message: message.into(),
822        })
823    }
824
825    /// Create a token error.
826    ///
827    /// # Example
828    ///
829    /// ```rust
830    /// use auth_framework::AuthError;
831    ///
832    /// let err = AuthError::token("signature mismatch");
833    /// assert!(err.to_string().contains("signature mismatch"));
834    /// ```
835    pub fn token(message: impl Into<String>) -> Self {
836        Self::Token(TokenError::Invalid {
837            message: message.into(),
838        })
839    }
840
841    /// Create a device flow error.
842    ///
843    /// # Example
844    ///
845    /// ```rust
846    /// use auth_framework::errors::{AuthError, DeviceFlowError};
847    ///
848    /// let err = AuthError::device_flow(DeviceFlowError::ExpiredToken);
849    /// assert!(err.to_string().contains("expired"));
850    /// ```
851    pub fn device_flow(error: DeviceFlowError) -> Self {
852        Self::DeviceFlow(error)
853    }
854
855    /// Create an OAuth provider error.
856    ///
857    /// # Example
858    ///
859    /// ```rust
860    /// use auth_framework::errors::{AuthError, OAuthProviderError};
861    ///
862    /// let err = AuthError::oauth_provider(OAuthProviderError::InvalidRedirectUri);
863    /// assert!(err.to_string().contains("redirect"));
864    /// ```
865    pub fn oauth_provider(error: OAuthProviderError) -> Self {
866        Self::OAuthProvider(error)
867    }
868
869    /// Create a user profile error.
870    ///
871    /// # Example
872    ///
873    /// ```rust
874    /// use auth_framework::AuthError;
875    ///
876    /// let err = AuthError::user_profile("email already in use");
877    /// assert!(err.to_string().contains("email already in use"));
878    /// ```
879    pub fn user_profile(message: impl Into<String>) -> Self {
880        Self::UserProfile {
881            message: message.into(),
882        }
883    }
884
885    /// Create an invalid credential error.
886    ///
887    /// # Example
888    ///
889    /// ```rust
890    /// use auth_framework::AuthError;
891    ///
892    /// let err = AuthError::invalid_credential("password", "too short");
893    /// assert!(err.to_string().contains("password"));
894    /// ```
895    pub fn invalid_credential(
896        credential_type: impl Into<String>,
897        message: impl Into<String>,
898    ) -> Self {
899        Self::InvalidCredential {
900            credential_type: credential_type.into(),
901            message: message.into(),
902        }
903    }
904
905    /// Create a timeout error.
906    ///
907    /// # Example
908    ///
909    /// ```rust
910    /// use auth_framework::AuthError;
911    ///
912    /// let err = AuthError::timeout(30);
913    /// assert!(err.to_string().contains("30"));
914    /// ```
915    pub fn timeout(timeout_seconds: u64) -> Self {
916        Self::Timeout { timeout_seconds }
917    }
918
919    /// Create a provider not configured error.
920    ///
921    /// # Example
922    ///
923    /// ```rust
924    /// use auth_framework::AuthError;
925    ///
926    /// let err = AuthError::provider_not_configured("github");
927    /// assert!(err.to_string().contains("github"));
928    /// ```
929    pub fn provider_not_configured(provider: impl Into<String>) -> Self {
930        Self::ProviderNotConfigured {
931            provider: provider.into(),
932        }
933    }
934
935    /// Create a rate limited error (alias for [`rate_limit`](Self::rate_limit)).
936    ///
937    /// # Example
938    ///
939    /// ```rust
940    /// use auth_framework::AuthError;
941    ///
942    /// let err = AuthError::rate_limited("5 requests per second exceeded");
943    /// assert!(err.to_string().contains("5 requests"));
944    /// ```
945    pub fn rate_limited(message: impl Into<String>) -> Self {
946        Self::RateLimit {
947            message: message.into(),
948        }
949    }
950
951    /// Create a configuration error (alias for [`config`](Self::config)).
952    ///
953    /// # Example
954    ///
955    /// ```rust
956    /// use auth_framework::AuthError;
957    ///
958    /// let err = AuthError::configuration("invalid issuer URL");
959    /// assert!(err.to_string().contains("invalid issuer URL"));
960    /// ```
961    pub fn configuration(message: impl Into<String>) -> Self {
962        Self::Configuration {
963            message: message.into(),
964            source: None,
965            help: None,
966            docs_url: None,
967            suggested_fix: None,
968        }
969    }
970
971    // -----------------------------------------------------------------------
972    // Classification helpers — framework-agnostic error introspection
973    // -----------------------------------------------------------------------
974
975    /// Return the HTTP status code that best represents this error.
976    ///
977    /// This is framework-agnostic and works without enabling any web framework
978    /// feature flag. Web framework integrations (actix-web, axum, …) use this
979    /// internally but you can also call it directly when building custom
980    /// response types.
981    ///
982    /// # Example
983    ///
984    /// ```rust
985    /// use auth_framework::AuthError;
986    ///
987    /// assert_eq!(AuthError::rate_limit("slow down").http_status_code(), 429);
988    /// assert_eq!(AuthError::internal("oops").http_status_code(), 500);
989    /// assert_eq!(AuthError::token("bad jwt").http_status_code(), 401);
990    /// ```
991    pub fn http_status_code(&self) -> u16 {
992        match self {
993            // 400 Bad Request
994            Self::InvalidInput(_)
995            | Self::Validation { .. }
996            | Self::InvalidCredential { .. }
997            | Self::HardwareToken(_)
998            | Self::InvalidRequest(_)
999            | Self::InvalidSecret => 400,
1000
1001            // 401 Unauthorized
1002            Self::Token(_)
1003            | Self::AuthMethod { .. }
1004            | Self::Jwt(_)
1005            | Self::Unauthorized(_)
1006            | Self::PasswordVerification(_) => 401,
1007
1008            // 403 Forbidden
1009            Self::Permission(_) | Self::StepUpRequired { .. } => 403,
1010
1011            // 404 Not Found
1012            Self::UserNotFound | Self::ProviderNotConfigured { .. } => 404,
1013
1014            // 408 Request Timeout
1015            Self::Timeout { .. } => 408,
1016
1017            // 429 Too Many Requests
1018            Self::RateLimit { .. } | Self::TooManyConcurrentSessions => 429,
1019
1020            // 502 Bad Gateway (upstream provider errors)
1021            Self::OAuthProvider(_) | Self::Network(_) => 502,
1022
1023            // 503 Service Unavailable (storage / infra)
1024            Self::Storage(_) => 503,
1025
1026            // 500 Internal Server Error (everything else)
1027            Self::Configuration { .. }
1028            | Self::Crypto { .. }
1029            | Self::Internal { .. }
1030            | Self::Json(_)
1031            | Self::Yaml(_)
1032            | Self::Toml(_)
1033            | Self::Io(_)
1034            | Self::Mfa(_)
1035            | Self::DeviceFlow(_)
1036            | Self::TokenGeneration(_)
1037            | Self::SessionError(_)
1038            | Self::UserProfile { .. }
1039            | Self::Cli(_)
1040            | Self::SystemTime(_)
1041            | Self::PasswordHashing(_)
1042            | Self::BackupCodeVerification(_)
1043            | Self::BackupCodeHashing(_)
1044            | Self::UnsupportedProvider(_) => 500,
1045
1046            #[cfg(feature = "prometheus")]
1047            Self::Metrics(_) => 500,
1048
1049            // Deprecated variants
1050            #[allow(deprecated)]
1051            Self::InvalidToken(_)
1052            | Self::NetworkError(_)
1053            | Self::ParseError(_)
1054            | Self::ConfigurationError(_) => 500,
1055        }
1056    }
1057
1058    /// Whether this error is transient and the operation may succeed on retry.
1059    ///
1060    /// Returns `true` for rate-limit, timeout, network, and storage
1061    /// connectivity errors. Returns `false` for authentication failures,
1062    /// validation errors, and other permanent conditions.
1063    ///
1064    /// # Example
1065    ///
1066    /// ```rust
1067    /// use auth_framework::AuthError;
1068    ///
1069    /// assert!(AuthError::rate_limit("too fast").is_retryable());
1070    /// assert!(AuthError::timeout(30).is_retryable());
1071    /// assert!(!AuthError::token("invalid").is_retryable());
1072    /// assert!(!AuthError::validation("bad input").is_retryable());
1073    /// ```
1074    pub fn is_retryable(&self) -> bool {
1075        matches!(
1076            self,
1077            Self::RateLimit { .. }
1078                | Self::Timeout { .. }
1079                | Self::TooManyConcurrentSessions
1080                | Self::Network(_)
1081                | Self::Storage(StorageError::ConnectionFailed { .. })
1082        )
1083    }
1084
1085    /// A short, stable, machine-readable code for this error category.
1086    ///
1087    /// Useful for API responses, metrics labels, and log filtering.
1088    /// These codes are stable across patch releases.
1089    ///
1090    /// # Example
1091    ///
1092    /// ```rust
1093    /// use auth_framework::AuthError;
1094    ///
1095    /// assert_eq!(AuthError::rate_limit("nope").error_code(), "rate_limit");
1096    /// assert_eq!(AuthError::token("bad").error_code(), "invalid_token");
1097    /// assert_eq!(AuthError::config("bad").error_code(), "configuration");
1098    /// ```
1099    pub fn error_code(&self) -> &'static str {
1100        match self {
1101            Self::Configuration { .. } => "configuration",
1102            Self::AuthMethod { .. } => "auth_method",
1103            Self::Token(_) => "invalid_token",
1104            Self::Permission(_) => "insufficient_permissions",
1105            Self::Storage(_) => "storage",
1106            Self::Network(_) => "network",
1107            Self::Json(_) | Self::Yaml(_) | Self::Toml(_) => "serialization",
1108            Self::Jwt(_) => "jwt",
1109            Self::Io(_) => "io",
1110            Self::RateLimit { .. } => "rate_limit",
1111            Self::TooManyConcurrentSessions => "concurrent_sessions",
1112            Self::Mfa(_) => "mfa",
1113            Self::DeviceFlow(_) => "device_flow",
1114            Self::OAuthProvider(_) => "oauth_provider",
1115            Self::PasswordVerification(_) => "password_verification",
1116            Self::UserNotFound => "user_not_found",
1117            Self::InvalidInput(_) => "invalid_input",
1118            Self::HardwareToken(_) => "hardware_token",
1119            Self::InvalidCredential { .. } => "invalid_credential",
1120            Self::Timeout { .. } => "timeout",
1121            Self::Crypto { .. } => "crypto",
1122            Self::Validation { .. } => "validation",
1123            Self::Internal { .. } => "internal",
1124            Self::StepUpRequired { .. } => "step_up_required",
1125            Self::SessionError(_) => "session",
1126            Self::Unauthorized(_) => "unauthorized",
1127            Self::TokenGeneration(_) => "token_generation",
1128            Self::UserProfile { .. } => "user_profile",
1129            Self::ProviderNotConfigured { .. } => "provider_not_configured",
1130            Self::Cli(_) => "cli",
1131            Self::SystemTime(_) => "internal",
1132            Self::PasswordHashing(_) => "password_hashing",
1133            Self::BackupCodeVerification(_) => "backup_code",
1134            Self::BackupCodeHashing(_) => "backup_code",
1135            Self::InvalidSecret => "invalid_secret",
1136            Self::InvalidRequest(_) => "invalid_request",
1137            Self::UnsupportedProvider(_) => "unsupported_provider",
1138            #[cfg(feature = "prometheus")]
1139            Self::Metrics(_) => "metrics",
1140            #[allow(deprecated)]
1141            Self::InvalidToken(_) => "invalid_token",
1142            #[allow(deprecated)]
1143            Self::NetworkError(_) => "network",
1144            #[allow(deprecated)]
1145            Self::ParseError(_) => "parse",
1146            #[allow(deprecated)]
1147            Self::ConfigurationError(_) => "configuration",
1148        }
1149    }
1150
1151    /// Whether this is a client-side error (4xx status code).
1152    ///
1153    /// # Example
1154    ///
1155    /// ```rust
1156    /// use auth_framework::AuthError;
1157    ///
1158    /// assert!(AuthError::validation("bad").is_client_error());
1159    /// assert!(!AuthError::internal("oops").is_client_error());
1160    /// ```
1161    pub fn is_client_error(&self) -> bool {
1162        (400..500).contains(&self.http_status_code())
1163    }
1164
1165    /// Whether this is a server-side error (5xx status code).
1166    ///
1167    /// # Example
1168    ///
1169    /// ```rust
1170    /// use auth_framework::AuthError;
1171    ///
1172    /// assert!(AuthError::internal("oops").is_server_error());
1173    /// assert!(!AuthError::validation("bad").is_server_error());
1174    /// ```
1175    pub fn is_server_error(&self) -> bool {
1176        self.http_status_code() >= 500
1177    }
1178}
1179
1180impl TokenError {
1181    /// Create a new token creation failed error.
1182    ///
1183    /// # Example
1184    ///
1185    /// ```rust
1186    /// use auth_framework::errors::TokenError;
1187    ///
1188    /// let err = TokenError::creation_failed("signing key unavailable");
1189    /// assert!(err.to_string().contains("signing key unavailable"));
1190    /// ```
1191    pub fn creation_failed(message: impl Into<String>) -> Self {
1192        Self::CreationFailed {
1193            message: message.into(),
1194        }
1195    }
1196
1197    /// Create a new token refresh failed error.
1198    ///
1199    /// # Example
1200    ///
1201    /// ```rust
1202    /// use auth_framework::errors::TokenError;
1203    ///
1204    /// let err = TokenError::refresh_failed("refresh token revoked");
1205    /// assert!(err.to_string().contains("refresh token revoked"));
1206    /// ```
1207    pub fn refresh_failed(message: impl Into<String>) -> Self {
1208        Self::RefreshFailed {
1209            message: message.into(),
1210        }
1211    }
1212
1213    /// Create a new token revocation failed error.
1214    ///
1215    /// # Example
1216    ///
1217    /// ```rust
1218    /// use auth_framework::errors::TokenError;
1219    ///
1220    /// let err = TokenError::revocation_failed("storage write failed");
1221    /// assert!(err.to_string().contains("storage write failed"));
1222    /// ```
1223    pub fn revocation_failed(message: impl Into<String>) -> Self {
1224        Self::RevocationFailed {
1225            message: message.into(),
1226        }
1227    }
1228}
1229
1230impl PermissionError {
1231    /// Create a new access denied error.
1232    ///
1233    /// # Example
1234    ///
1235    /// ```rust
1236    /// use auth_framework::errors::PermissionError;
1237    ///
1238    /// let err = PermissionError::access_denied("write", "documents");
1239    /// assert!(err.to_string().contains("write"));
1240    /// ```
1241    pub fn access_denied(permission: impl Into<String>, resource: impl Into<String>) -> Self {
1242        Self::AccessDenied {
1243            permission: permission.into(),
1244            resource: resource.into(),
1245        }
1246    }
1247
1248    /// Create a new role not found error.
1249    ///
1250    /// # Example
1251    ///
1252    /// ```rust
1253    /// use auth_framework::errors::PermissionError;
1254    ///
1255    /// let err = PermissionError::role_not_found("superadmin");
1256    /// assert!(err.to_string().contains("superadmin"));
1257    /// ```
1258    pub fn role_not_found(role: impl Into<String>) -> Self {
1259        Self::RoleNotFound { role: role.into() }
1260    }
1261
1262    /// Create a new permission not found error.
1263    ///
1264    /// # Example
1265    ///
1266    /// ```rust
1267    /// use auth_framework::errors::PermissionError;
1268    ///
1269    /// let err = PermissionError::permission_not_found("delete_user");
1270    /// assert!(err.to_string().contains("delete_user"));
1271    /// ```
1272    pub fn permission_not_found(permission: impl Into<String>) -> Self {
1273        Self::PermissionNotFound {
1274            permission: permission.into(),
1275        }
1276    }
1277
1278    /// Create a new invalid format error.
1279    ///
1280    /// # Example
1281    ///
1282    /// ```rust
1283    /// use auth_framework::errors::PermissionError;
1284    ///
1285    /// let err = PermissionError::invalid_format("missing resource:action separator");
1286    /// assert!(err.to_string().contains("separator"));
1287    /// ```
1288    pub fn invalid_format(message: impl Into<String>) -> Self {
1289        Self::InvalidFormat {
1290            message: message.into(),
1291        }
1292    }
1293}
1294
1295impl StorageError {
1296    /// Create a new connection failed error.
1297    ///
1298    /// # Example
1299    ///
1300    /// ```rust
1301    /// use auth_framework::errors::StorageError;
1302    ///
1303    /// let err = StorageError::connection_failed("connection refused");
1304    /// assert!(err.to_string().contains("connection refused"));
1305    /// ```
1306    pub fn connection_failed(message: impl Into<String>) -> Self {
1307        Self::ConnectionFailed {
1308            message: message.into(),
1309        }
1310    }
1311
1312    /// Create a new operation failed error.
1313    ///
1314    /// # Example
1315    ///
1316    /// ```rust
1317    /// use auth_framework::errors::StorageError;
1318    ///
1319    /// let err = StorageError::operation_failed("table not found");
1320    /// assert!(err.to_string().contains("table not found"));
1321    /// ```
1322    pub fn operation_failed(message: impl Into<String>) -> Self {
1323        Self::OperationFailed {
1324            message: message.into(),
1325        }
1326    }
1327
1328    /// Create a new serialization error.
1329    ///
1330    /// # Example
1331    ///
1332    /// ```rust
1333    /// use auth_framework::errors::StorageError;
1334    ///
1335    /// let err = StorageError::serialization("invalid JSON");
1336    /// assert!(err.to_string().contains("invalid JSON"));
1337    /// ```
1338    pub fn serialization(message: impl Into<String>) -> Self {
1339        Self::Serialization {
1340            message: message.into(),
1341        }
1342    }
1343}
1344
1345impl MfaError {
1346    /// Create a new method not supported error.
1347    ///
1348    /// # Example
1349    ///
1350    /// ```rust
1351    /// use auth_framework::errors::MfaError;
1352    ///
1353    /// let err = MfaError::method_not_supported("biometric");
1354    /// assert!(err.to_string().contains("biometric"));
1355    /// ```
1356    pub fn method_not_supported(method: impl Into<String>) -> Self {
1357        Self::MethodNotSupported {
1358            method: method.into(),
1359        }
1360    }
1361
1362    /// Create a new verification failed error.
1363    ///
1364    /// # Example
1365    ///
1366    /// ```rust
1367    /// use auth_framework::errors::MfaError;
1368    ///
1369    /// let err = MfaError::verification_failed("code expired");
1370    /// assert!(err.to_string().contains("code expired"));
1371    /// ```
1372    pub fn verification_failed(message: impl Into<String>) -> Self {
1373        Self::VerificationFailed {
1374            message: message.into(),
1375        }
1376    }
1377}
1378
1379// Actix-web ResponseError implementation
1380#[cfg(feature = "actix-web")]
1381impl actix_web::ResponseError for AuthError {
1382    fn error_response(&self) -> actix_web::HttpResponse {
1383        match self {
1384            AuthError::Token(_) => {
1385                actix_web::HttpResponse::Unauthorized().json(serde_json::json!({
1386                    "error": "invalid_token",
1387                    "error_description": self.to_string()
1388                }))
1389            }
1390            AuthError::Permission(_) => {
1391                actix_web::HttpResponse::Forbidden().json(serde_json::json!({
1392                    "error": "insufficient_permissions",
1393                    "error_description": self.to_string()
1394                }))
1395            }
1396            AuthError::RateLimit { .. } => {
1397                actix_web::HttpResponse::TooManyRequests().json(serde_json::json!({
1398                    "error": "rate_limit_exceeded",
1399                    "error_description": self.to_string()
1400                }))
1401            }
1402            AuthError::Configuration { .. }
1403            | AuthError::Storage(_)
1404            | AuthError::Internal { .. } => {
1405                actix_web::HttpResponse::InternalServerError().json(serde_json::json!({
1406                    "error": "internal_error",
1407                    "error_description": "An internal error occurred"
1408                }))
1409            }
1410            _ => actix_web::HttpResponse::BadRequest().json(serde_json::json!({
1411                "error": "bad_request",
1412                "error_description": self.to_string()
1413            })),
1414        }
1415    }
1416
1417    fn status_code(&self) -> actix_web::http::StatusCode {
1418        match self {
1419            AuthError::Token(_) => actix_web::http::StatusCode::UNAUTHORIZED,
1420            AuthError::Permission(_) => actix_web::http::StatusCode::FORBIDDEN,
1421            AuthError::RateLimit { .. } => actix_web::http::StatusCode::TOO_MANY_REQUESTS,
1422            AuthError::Internal { .. }
1423            | AuthError::Configuration { .. }
1424            | AuthError::Storage(_) => actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
1425            _ => actix_web::http::StatusCode::BAD_REQUEST,
1426        }
1427    }
1428}
1429
1430// Additional From implementations for admin tools
1431impl From<Box<dyn std::error::Error + Send + Sync>> for AuthError {
1432    fn from(error: Box<dyn std::error::Error + Send + Sync>) -> Self {
1433        AuthError::Cli(format!("Admin tool error: {}", error))
1434    }
1435}
1436
1437impl From<Box<dyn std::error::Error>> for AuthError {
1438    fn from(error: Box<dyn std::error::Error>) -> Self {
1439        AuthError::Cli(format!("Admin tool error: {}", error))
1440    }
1441}
1442
1443#[cfg(test)]
1444mod tests {
1445    use super::*;
1446    use std::error::Error;
1447
1448    #[test]
1449    fn test_auth_error_creation() {
1450        let token_error = AuthError::token("Invalid JWT signature");
1451        assert!(matches!(token_error, AuthError::Token(_)));
1452        assert!(token_error.to_string().contains("Invalid JWT signature"));
1453
1454        let permission_error = AuthError::access_denied("Access denied");
1455        assert!(matches!(permission_error, AuthError::Permission(_)));
1456        assert!(permission_error.to_string().contains("Access denied"));
1457
1458        let config_error = AuthError::config("Database connection failed");
1459        assert!(matches!(config_error, AuthError::Configuration { .. }));
1460        assert!(
1461            config_error
1462                .to_string()
1463                .contains("Database connection failed")
1464        );
1465    }
1466
1467    #[test]
1468    fn test_auth_error_categorization() {
1469        // Test various error types maintain their category
1470        let errors = vec![
1471            (AuthError::token("test"), "Token"),
1472            (AuthError::access_denied("test"), "Permission"),
1473            (AuthError::config("test"), "Configuration"),
1474            (AuthError::crypto("test"), "Crypto"),
1475            (AuthError::validation("test"), "Validation"),
1476        ];
1477
1478        for (error, expected_category) in errors {
1479            let error_string = format!("{:?}", error);
1480            assert!(
1481                error_string.contains(expected_category),
1482                "Error {:?} should contain category {}",
1483                error,
1484                expected_category
1485            );
1486        }
1487    }
1488
1489    #[test]
1490    fn test_rate_limit_error() {
1491        let rate_limit_error = AuthError::rate_limit("Too many requests");
1492
1493        match rate_limit_error {
1494            AuthError::RateLimit { message } => {
1495                assert_eq!(message, "Too many requests");
1496            }
1497            _ => panic!("Expected RateLimit error"),
1498        }
1499    }
1500
1501    #[test]
1502    fn test_validation_error() {
1503        let validation_error = AuthError::validation("username must not be empty");
1504
1505        match validation_error {
1506            AuthError::Validation { message } => {
1507                assert_eq!(message, "username must not be empty");
1508            }
1509            _ => panic!("Expected Validation error"),
1510        }
1511    }
1512
1513    #[test]
1514    fn test_configuration_error() {
1515        let config_error = AuthError::config("jwt_secret is required");
1516
1517        match config_error {
1518            AuthError::Configuration { message, .. } => {
1519                assert_eq!(message, "jwt_secret is required");
1520            }
1521            _ => panic!("Expected Configuration error"),
1522        }
1523    }
1524
1525    #[test]
1526    fn test_error_chain() {
1527        let root_cause = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
1528        let auth_error = AuthError::internal(format!("Config file error: {}", root_cause));
1529
1530        // Test that error information is preserved
1531        assert!(auth_error.to_string().contains("File not found"));
1532        assert!(auth_error.to_string().contains("Config file error"));
1533    }
1534
1535    #[test]
1536    fn test_error_source() {
1537        let token_error = AuthError::token("JWT parsing failed");
1538
1539        // AuthError implements Error trait
1540        // Token error wraps TokenError, so it should have a source
1541        assert!(token_error.source().is_some());
1542
1543        // Test error display
1544        let error_msg = format!("{}", token_error);
1545        assert!(error_msg.contains("JWT parsing failed"));
1546    }
1547
1548    #[test]
1549    fn test_from_conversions() {
1550        // Test conversion from std::io::Error
1551        let io_error = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "Access denied");
1552        let auth_error: AuthError = io_error.into();
1553        assert!(matches!(auth_error, AuthError::Io(_)));
1554
1555        // Test conversion from serde_json::Error
1556        let json_str = r#"{"invalid": json"#;
1557        let json_error: serde_json::Error =
1558            serde_json::from_str::<serde_json::Value>(json_str).unwrap_err();
1559        let auth_error: AuthError = json_error.into();
1560        assert!(matches!(auth_error, AuthError::Json(_)));
1561    }
1562
1563    #[test]
1564    fn test_error_equality() {
1565        let error1 = AuthError::token("Same message");
1566        let error2 = AuthError::token("Same message");
1567        let error3 = AuthError::token("Different message");
1568
1569        // Test Debug representation for consistency
1570        assert_eq!(format!("{:?}", error1), format!("{:?}", error2));
1571        assert_ne!(format!("{:?}", error1), format!("{:?}", error3));
1572    }
1573
1574    #[test]
1575    fn test_actix_web_integration() {
1576        #[cfg(feature = "actix-web")]
1577        {
1578            use actix_web::ResponseError;
1579
1580            // Test status codes
1581            assert_eq!(
1582                AuthError::token("test").status_code(),
1583                actix_web::http::StatusCode::UNAUTHORIZED
1584            );
1585            assert_eq!(
1586                AuthError::access_denied("test").status_code(),
1587                actix_web::http::StatusCode::FORBIDDEN
1588            );
1589            assert_eq!(
1590                AuthError::rate_limit("test").status_code(),
1591                actix_web::http::StatusCode::TOO_MANY_REQUESTS
1592            );
1593            assert_eq!(
1594                AuthError::internal("test").status_code(),
1595                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
1596            );
1597        }
1598    }
1599
1600    #[test]
1601    fn test_error_message_safety() {
1602        // Ensure error messages don't leak sensitive information
1603        let sensitive_data = "password123";
1604        let safe_error = AuthError::token("Invalid credentials");
1605
1606        // Error message should not contain sensitive data
1607        assert!(!safe_error.to_string().contains(sensitive_data));
1608
1609        // Test that we can create errors without exposing internals
1610        let config_error = AuthError::config("connection failed");
1611        assert!(!config_error.to_string().contains("password"));
1612        assert!(!config_error.to_string().contains("secret"));
1613    }
1614
1615    #[test]
1616    fn test_cli_error_conversion() {
1617        let boxed_error: Box<dyn std::error::Error + Send + Sync> = "CLI operation failed".into();
1618        let auth_error: AuthError = boxed_error.into();
1619
1620        assert!(matches!(auth_error, AuthError::Cli(_)));
1621        assert!(auth_error.to_string().contains("CLI operation failed"));
1622    }
1623
1624    #[test]
1625    fn test_error_variants_coverage() {
1626        // Ensure all error variants can be created and have proper messages
1627        let test_errors = vec![
1628            AuthError::token("token error"),
1629            AuthError::access_denied("permission error"),
1630            AuthError::internal("internal error"),
1631            AuthError::crypto("crypto error"),
1632            AuthError::Cli("cli error".to_string()),
1633            AuthError::validation("validation error"),
1634            AuthError::config("config error"),
1635            AuthError::rate_limit("rate limit error"),
1636        ];
1637
1638        for error in test_errors {
1639            // All errors should have non-empty messages
1640            assert!(
1641                !error.to_string().is_empty(),
1642                "Error should have message: {:?}",
1643                error
1644            );
1645
1646            // All errors should implement Debug
1647            let debug_repr = format!("{:?}", error);
1648            assert!(
1649                !debug_repr.is_empty(),
1650                "Error should have debug representation: {:?}",
1651                error
1652            );
1653        }
1654    }
1655
1656    #[test]
1657    fn test_oauth_specific_errors() {
1658        // Test OAuth-specific error creation using auth_method
1659        let invalid_client = AuthError::auth_method("oauth", "Client authentication failed");
1660        assert!(
1661            invalid_client
1662                .to_string()
1663                .contains("Client authentication failed")
1664        );
1665
1666        let invalid_grant = AuthError::auth_method("oauth", "Authorization code expired");
1667        assert!(
1668            invalid_grant
1669                .to_string()
1670                .contains("Authorization code expired")
1671        );
1672    }
1673
1674    #[test]
1675    fn test_error_context_preservation() {
1676        // Test that errors maintain context through transformations
1677        let original_msg = "Original error message";
1678        let context_msg = "Additional context";
1679
1680        let base_error = AuthError::internal(original_msg);
1681        let contextual_error = AuthError::internal(format!("{}: {}", context_msg, base_error));
1682
1683        assert!(contextual_error.to_string().contains(original_msg));
1684        assert!(contextual_error.to_string().contains(context_msg));
1685    }
1686
1687    #[test]
1688    fn test_error_serialization() {
1689        // Test that errors can be converted to JSON for API responses
1690        let error = AuthError::validation("email invalid format");
1691
1692        // Should be able to include in structured responses
1693        let error_response = serde_json::json!({
1694            "error": "validation_failed",
1695            "message": error.to_string(),
1696            "field": "email"
1697        });
1698
1699        assert!(
1700            error_response["message"]
1701                .as_str()
1702                .unwrap()
1703                .contains("invalid format")
1704        );
1705    }
1706
1707    #[test]
1708    fn test_concurrent_error_creation() {
1709        use std::thread;
1710
1711        let handles: Vec<_> = (0..10)
1712            .map(|i| {
1713                thread::spawn(move || {
1714                    let error = AuthError::token(format!("Concurrent error {}", i));
1715                    assert!(
1716                        error
1717                            .to_string()
1718                            .contains(&format!("Concurrent error {}", i))
1719                    );
1720                    error
1721                })
1722            })
1723            .collect();
1724
1725        // Wait for all threads and verify errors
1726        for handle in handles {
1727            let error = handle.join().unwrap();
1728            assert!(!error.to_string().is_empty());
1729        }
1730    }
1731}