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//!
32//! # async fn example(auth_framework: &AuthFramework, credential: Credential) {
33//! match auth_framework.authenticate("password", credential).await {
34//!     Ok(result) => println!("Authentication result: {:?}", result),
35//!     Err(AuthError::InvalidCredential { credential_type, message }) => {
36//!         eprintln!("Invalid {} credential: {}", credential_type, message);
37//!     },
38//!     Err(AuthError::RateLimit { message }) => {
39//!         eprintln!("Rate limited: {}", message);
40//!     },
41//!     Err(e) => {
42//!         eprintln!("Authentication system error: {}", e);
43//!     }
44//! }
45//! # }
46//! ```
47//!
48//! # Security Considerations
49//!
50//! Error messages are designed to:
51//! - Provide useful debugging information for developers
52//! - Avoid exposing sensitive information to potential attackers
53//! - Enable proper security monitoring and alerting
54//! - Support compliance requirements for audit logging
55
56use thiserror::Error;
57
58/// Type alias for Results in the authentication framework.
59///
60/// This alias simplifies error handling throughout the framework by defaulting
61/// to `AuthError` as the error type while allowing flexibility for other error
62/// types when needed.
63pub type Result<T, E = AuthError> = std::result::Result<T, E>;
64
65/// Comprehensive error type covering all authentication and authorization failures.
66///
67/// `AuthError` provides detailed error information for all aspects of the authentication
68/// framework, from configuration issues to runtime failures. Each error variant includes
69/// contextual information to aid in debugging and provide appropriate user feedback.
70///
71/// This enhanced error type provides:
72/// - **Actionable error messages** with specific suggestions for fixes
73/// - **Documentation links** to relevant guides and troubleshooting
74/// - **Contextual help** that guides users to solutions
75/// - **Security-aware messaging** that doesn't leak sensitive information
76///
77/// # Error Categories
78///
79/// ## Configuration Errors
80/// Errors that occur during framework setup and configuration validation.
81///
82/// ## Authentication Errors
83/// Errors related to credential validation and authentication method execution.
84///
85/// ## Authorization Errors
86/// Errors related to permission checking and access control.
87///
88/// ## Token Errors
89/// JWT token creation, validation, expiration, and lifecycle issues.
90///
91/// ## Storage Errors
92/// Database connectivity, query failures, and data persistence issues.
93///
94/// ## Network Errors
95/// External service communication, timeouts, and connectivity problems.
96///
97/// ## Cryptographic Errors
98/// Encryption, decryption, signing, and other security operation failures.
99///
100/// # Enhanced Error Handling
101///
102/// ```rust,no_run
103/// use auth_framework::AuthError;
104///
105/// # fn example(auth_result: Result<(), AuthError>) {
106/// // Enhanced error handling with contextual help
107/// match auth_result {
108///     Err(AuthError::Configuration { message, help, docs_url, .. }) => {
109///         eprintln!("Configuration Error: {}", message);
110///         if let Some(help) = help {
111///             eprintln!("Help: {}", help);
112///         }
113///         if let Some(docs) = docs_url {
114///             eprintln!("See: {}", docs);
115///         }
116///     },
117///     Err(AuthError::InvalidCredential { credential_type, message }) => {
118///         eprintln!("Invalid {}: {}", credential_type, message);
119///     },
120///     // ... handle other error types
121///     _ => {}
122/// }
123/// # }
124/// ```
125///
126/// # Security Notes
127///
128/// Error messages are carefully crafted to:
129/// - Provide sufficient detail for debugging and monitoring
130/// - Avoid exposing sensitive information that could aid attackers
131/// - Enable security teams to identify potential threats
132/// - Support compliance and audit requirements
133/// - Guide users to secure solutions and best practices
134#[derive(Error, Debug)]
135pub enum AuthError {
136    /// Configuration validation and setup errors.
137    ///
138    /// These errors occur when the authentication framework is misconfigured
139    /// or when configuration validation fails during startup.
140    #[error("Configuration error: {message}")]
141    Configuration {
142        message: String,
143        #[source]
144        source: Option<Box<dyn std::error::Error + Send + Sync>>,
145        /// Helpful guidance for fixing the issue
146        help: Option<String>,
147        /// Link to relevant documentation
148        docs_url: Option<String>,
149        /// Specific fix suggestion with commands or code
150        suggested_fix: Option<String>,
151    },
152
153    /// Authentication method execution errors.
154    ///
155    /// These errors occur when a specific authentication method fails to
156    /// execute properly, such as OAuth provider communication failures.
157    #[error("Authentication method '{method}' error: {message}")]
158    AuthMethod {
159        method: String,
160        message: String,
161        /// Helpful guidance for fixing the issue
162        help: Option<String>,
163        /// Link to relevant documentation
164        docs_url: Option<String>,
165        /// Specific fix suggestion
166        suggested_fix: Option<String>,
167    },
168
169    /// Token-related errors
170    #[error("Token error: {0}")]
171    Token(#[from] TokenError),
172
173    /// Permission-related errors
174    #[error("Permission error: {0}")]
175    Permission(#[from] PermissionError),
176
177    /// Storage-related errors
178    #[error("Storage error: {0}")]
179    Storage(#[from] StorageError),
180
181    /// Network/HTTP errors
182    #[error("Network error: {0}")]
183    Network(#[from] reqwest::Error),
184
185    /// JSON parsing errors
186    #[error("JSON error: {0}")]
187    Json(#[from] serde_json::Error),
188
189    /// JWT errors
190    #[error("JWT error: {0}")]
191    Jwt(#[from] jsonwebtoken::errors::Error),
192
193    /// YAML parsing errors
194    #[error("YAML error: {0}")]
195    Yaml(#[from] serde_yaml::Error),
196
197    /// TOML parsing errors
198    #[error("TOML error: {0}")]
199    Toml(#[from] toml::ser::Error),
200
201    /// Prometheus metrics errors
202    #[cfg(feature = "prometheus")]
203    #[error("Metrics error: {0}")]
204    Metrics(#[from] prometheus::Error),
205
206    /// IO errors
207    #[error("IO error: {0}")]
208    Io(#[from] std::io::Error),
209
210    /// CLI interaction errors
211    #[error("CLI error: {0}")]
212    Cli(String),
213
214    /// System time errors
215    #[error("System time error: {0}")]
216    SystemTime(#[from] std::time::SystemTimeError),
217
218    /// Rate limiting errors
219    #[error("Rate limit exceeded: {message}")]
220    RateLimit { message: String },
221
222    /// Session-related errors
223    #[error("Too many concurrent sessions for user")]
224    TooManyConcurrentSessions,
225
226    /// MFA-related errors
227    #[error("MFA error: {0}")]
228    Mfa(#[from] MfaError),
229
230    /// Device flow errors
231    #[error("Device flow error: {0}")]
232    DeviceFlow(#[from] DeviceFlowError),
233
234    /// OAuth provider errors
235    #[error("OAuth provider error: {0}")]
236    OAuthProvider(#[from] OAuthProviderError),
237
238    /// Password verification errors
239    #[error("Password verification failed: {0}")]
240    PasswordVerification(String),
241
242    /// Password hashing errors
243    #[error("Password hashing failed: {0}")]
244    PasswordHashing(String),
245
246    /// User not found error
247    #[error("User not found")]
248    UserNotFound,
249
250    /// Invalid input error
251    #[error("Invalid input: {0}")]
252    InvalidInput(String),
253
254    /// Hardware token errors
255    #[error("Hardware token error: {0}")]
256    HardwareToken(String),
257
258    /// Backup code verification errors
259    #[error("Backup code verification failed: {0}")]
260    BackupCodeVerification(String),
261
262    /// Backup code hashing errors
263    #[error("Backup code hashing failed: {0}")]
264    BackupCodeHashing(String),
265
266    /// Invalid secret error
267    #[error("Invalid secret format")]
268    InvalidSecret,
269
270    /// User profile errors
271    #[error("User profile error: {message}")]
272    UserProfile { message: String },
273
274    /// Credential validation errors
275    #[error("Invalid credential: {credential_type} - {message}")]
276    InvalidCredential {
277        credential_type: String,
278        message: String,
279    },
280
281    /// Authentication timeout
282    #[error("Authentication timeout after {timeout_seconds} seconds")]
283    Timeout { timeout_seconds: u64 },
284
285    /// Provider configuration missing
286    #[error("Provider '{provider}' is not configured or supported")]
287    ProviderNotConfigured { provider: String },
288
289    /// Cryptography errors
290    #[error("Cryptography error: {message}")]
291    Crypto { message: String },
292
293    /// Validation errors
294    #[error("Validation error: {message}")]
295    Validation { message: String },
296
297    /// Generic internal errors
298    #[error("Internal error: {message}")]
299    Internal { message: String },
300
301    /// Invalid request error
302    #[error("Invalid request: {0}")]
303    InvalidRequest(String),
304
305    /// Step-up authentication required
306    #[error(
307        "Step-up authentication required: current level '{current_level}', required level '{required_level}'"
308    )]
309    StepUpRequired {
310        current_level: String,
311        required_level: String,
312        step_up_url: String,
313    },
314
315    /// Session error
316    #[error("Session error: {0}")]
317    SessionError(String),
318
319    /// Unauthorized access
320    #[error("Unauthorized: {0}")]
321    Unauthorized(String),
322
323    /// Token generation error
324    #[error("Token generation error: {0}")]
325    TokenGeneration(String),
326
327    /// Invalid token error
328    #[error("Invalid token: {0}")]
329    InvalidToken(String),
330
331    /// Unsupported provider error
332    #[error("Unsupported provider: {0}")]
333    UnsupportedProvider(String),
334
335    /// Network error with custom message
336    #[error("Network error: {0}")]
337    NetworkError(String),
338
339    /// Parse error with custom message
340    #[error("Parse error: {0}")]
341    ParseError(String),
342
343    /// Configuration error with custom message
344    #[error("Configuration error: {0}")]
345    ConfigurationError(String),
346}
347
348/// Token-specific errors
349#[derive(Error, Debug)]
350pub enum TokenError {
351    #[error("Token has expired")]
352    Expired,
353
354    #[error("Token is invalid: {message}")]
355    Invalid { message: String },
356
357    #[error("Token not found")]
358    NotFound,
359
360    #[error("Token is missing")]
361    Missing,
362
363    #[error("Token creation failed: {message}")]
364    CreationFailed { message: String },
365
366    #[error("Token refresh failed: {message}")]
367    RefreshFailed { message: String },
368
369    #[error("Token revocation failed: {message}")]
370    RevocationFailed { message: String },
371}
372
373/// Permission-specific errors
374#[derive(Error, Debug)]
375pub enum PermissionError {
376    #[error("Access denied: missing permission '{permission}' for resource '{resource}'")]
377    AccessDenied {
378        permission: String,
379        resource: String,
380    },
381
382    #[error("Role '{role}' not found")]
383    RoleNotFound { role: String },
384
385    #[error("Permission '{permission}' not found")]
386    PermissionNotFound { permission: String },
387
388    #[error("Invalid permission format: {message}")]
389    InvalidFormat { message: String },
390
391    #[error("Permission denied: {message}")]
392    Denied {
393        action: String,
394        resource: String,
395        message: String,
396    },
397}
398
399/// Storage-specific errors
400#[derive(Error, Debug)]
401pub enum StorageError {
402    #[error("Connection failed: {message}")]
403    ConnectionFailed { message: String },
404
405    #[error("Operation failed: {message}")]
406    OperationFailed { message: String },
407
408    #[error("Serialization error: {message}")]
409    Serialization { message: String },
410
411    #[error("Storage backend not available")]
412    BackendUnavailable,
413}
414
415/// MFA-specific errors
416#[derive(Error, Debug)]
417pub enum MfaError {
418    #[error("MFA challenge expired")]
419    ChallengeExpired,
420
421    #[error("Invalid MFA code")]
422    InvalidCode,
423
424    #[error("MFA method not supported: {method}")]
425    MethodNotSupported { method: String },
426
427    #[error("MFA setup required")]
428    SetupRequired,
429
430    #[error("MFA verification failed: {message}")]
431    VerificationFailed { message: String },
432}
433
434/// Device flow specific errors
435#[derive(Error, Debug)]
436pub enum DeviceFlowError {
437    #[error("Authorization pending - user has not yet completed authorization")]
438    AuthorizationPending,
439
440    #[error("Slow down - polling too frequently")]
441    SlowDown,
442
443    #[error("Device code expired")]
444    ExpiredToken,
445
446    #[error("Access denied by user")]
447    AccessDenied,
448
449    #[error("Invalid device code")]
450    InvalidDeviceCode,
451
452    #[error("Unsupported grant type")]
453    UnsupportedGrantType,
454}
455
456/// OAuth provider specific errors
457#[derive(Error, Debug)]
458pub enum OAuthProviderError {
459    #[error("Invalid authorization code")]
460    InvalidAuthorizationCode,
461
462    #[error("Invalid redirect URI")]
463    InvalidRedirectUri,
464
465    #[error("Invalid client credentials")]
466    InvalidClientCredentials,
467
468    #[error("Insufficient scope: required '{required}', granted '{granted}'")]
469    InsufficientScope { required: String, granted: String },
470
471    #[error("Provider '{provider}' does not support '{feature}'")]
472    UnsupportedFeature { provider: String, feature: String },
473
474    #[error("Rate limited by provider: {message}")]
475    RateLimited { message: String },
476}
477
478impl AuthError {
479    /// Create a new configuration error
480    pub fn config(message: impl Into<String>) -> Self {
481        Self::Configuration {
482            message: message.into(),
483            source: None,
484            help: None,
485            docs_url: None,
486            suggested_fix: None,
487        }
488    }
489
490    /// Create a configuration error with helpful context
491    pub fn config_with_help(
492        message: impl Into<String>,
493        help: impl Into<String>,
494        suggested_fix: Option<String>,
495    ) -> Self {
496        Self::Configuration {
497            message: message.into(),
498            source: None,
499            help: Some(help.into()),
500            docs_url: Some(
501                "https://docs.rs/auth-framework/latest/auth_framework/config/".to_string(),
502            ),
503            suggested_fix,
504        }
505    }
506
507    /// Create a JWT secret validation error with helpful guidance
508    pub fn jwt_secret_too_short(current_length: usize) -> Self {
509        Self::Configuration {
510            message: format!(
511                "JWT secret too short (got {} characters, need 32+ for security)",
512                current_length
513            ),
514            source: None,
515            help: Some("Use a cryptographically secure random string of at least 32 characters".to_string()),
516            docs_url: Some("https://docs.rs/auth-framework/latest/auth_framework/config/struct.SecurityConfig.html".to_string()),
517            suggested_fix: Some("Generate a secure secret: `openssl rand -hex 32`".to_string()),
518        }
519    }
520
521    /// Create a production environment error with guidance
522    pub fn production_memory_storage() -> Self {
523        Self::Configuration {
524            message: "Memory storage is not suitable for production environments".to_string(),
525            source: None,
526            help: Some("Use a persistent storage backend like PostgreSQL or Redis".to_string()),
527            docs_url: Some("https://docs.rs/auth-framework/latest/auth_framework/storage/".to_string()),
528            suggested_fix: Some("Configure PostgreSQL: .with_postgres(\"postgresql://...\") or Redis: .with_redis(\"redis://...\")".to_string()),
529        }
530    }
531
532    /// Create a new auth method error
533    pub fn auth_method(method: impl Into<String>, message: impl Into<String>) -> Self {
534        Self::AuthMethod {
535            method: method.into(),
536            message: message.into(),
537            help: None,
538            docs_url: None,
539            suggested_fix: None,
540        }
541    }
542
543    /// Create an auth method error with helpful context
544    pub fn auth_method_with_help(
545        method: impl Into<String>,
546        message: impl Into<String>,
547        help: impl Into<String>,
548        suggested_fix: Option<String>,
549    ) -> Self {
550        Self::AuthMethod {
551            method: method.into(),
552            message: message.into(),
553            help: Some(help.into()),
554            docs_url: Some(
555                "https://docs.rs/auth-framework/latest/auth_framework/methods/".to_string(),
556            ),
557            suggested_fix,
558        }
559    }
560
561    /// Create a new rate limit error
562    pub fn rate_limit(message: impl Into<String>) -> Self {
563        Self::RateLimit {
564            message: message.into(),
565        }
566    }
567
568    /// Create a new crypto error
569    pub fn crypto(message: impl Into<String>) -> Self {
570        Self::Crypto {
571            message: message.into(),
572        }
573    }
574
575    /// Create a new validation error
576    pub fn validation(message: impl Into<String>) -> Self {
577        Self::Validation {
578            message: message.into(),
579        }
580    }
581
582    /// Create a new internal error
583    pub fn internal(message: impl Into<String>) -> Self {
584        Self::Internal {
585            message: message.into(),
586        }
587    }
588
589    /// Create an authorization error
590    pub fn authorization(message: impl Into<String>) -> Self {
591        Self::Permission(PermissionError::Denied {
592            action: "authorize".to_string(),
593            resource: "resource".to_string(),
594            message: message.into(),
595        })
596    }
597
598    /// Create an access denied error
599    pub fn access_denied(message: impl Into<String>) -> Self {
600        Self::Permission(PermissionError::Denied {
601            action: "access".to_string(),
602            resource: "resource".to_string(),
603            message: message.into(),
604        })
605    }
606
607    /// Create a token error
608    pub fn token(message: impl Into<String>) -> Self {
609        Self::Token(TokenError::Invalid {
610            message: message.into(),
611        })
612    }
613
614    /// Create a device flow error
615    pub fn device_flow(error: DeviceFlowError) -> Self {
616        Self::DeviceFlow(error)
617    }
618
619    /// Create an OAuth provider error
620    pub fn oauth_provider(error: OAuthProviderError) -> Self {
621        Self::OAuthProvider(error)
622    }
623
624    /// Create a user profile error
625    pub fn user_profile(message: impl Into<String>) -> Self {
626        Self::UserProfile {
627            message: message.into(),
628        }
629    }
630
631    /// Create an invalid credential error
632    pub fn invalid_credential(
633        credential_type: impl Into<String>,
634        message: impl Into<String>,
635    ) -> Self {
636        Self::InvalidCredential {
637            credential_type: credential_type.into(),
638            message: message.into(),
639        }
640    }
641
642    /// Create a timeout error
643    pub fn timeout(timeout_seconds: u64) -> Self {
644        Self::Timeout { timeout_seconds }
645    }
646
647    /// Create a provider not configured error
648    pub fn provider_not_configured(provider: impl Into<String>) -> Self {
649        Self::ProviderNotConfigured {
650            provider: provider.into(),
651        }
652    }
653
654    /// Create a rate limited error
655    pub fn rate_limited(message: impl Into<String>) -> Self {
656        Self::RateLimit {
657            message: message.into(),
658        }
659    }
660
661    /// Create a configuration error
662    pub fn configuration(message: impl Into<String>) -> Self {
663        Self::Configuration {
664            message: message.into(),
665            source: None,
666            help: None,
667            docs_url: None,
668            suggested_fix: None,
669        }
670    }
671}
672
673impl TokenError {
674    /// Create a new token creation failed error
675    pub fn creation_failed(message: impl Into<String>) -> Self {
676        Self::CreationFailed {
677            message: message.into(),
678        }
679    }
680
681    /// Create a new token refresh failed error
682    pub fn refresh_failed(message: impl Into<String>) -> Self {
683        Self::RefreshFailed {
684            message: message.into(),
685        }
686    }
687
688    /// Create a new token revocation failed error
689    pub fn revocation_failed(message: impl Into<String>) -> Self {
690        Self::RevocationFailed {
691            message: message.into(),
692        }
693    }
694}
695
696impl PermissionError {
697    /// Create a new access denied error
698    pub fn access_denied(permission: impl Into<String>, resource: impl Into<String>) -> Self {
699        Self::AccessDenied {
700            permission: permission.into(),
701            resource: resource.into(),
702        }
703    }
704
705    /// Create a new role not found error
706    pub fn role_not_found(role: impl Into<String>) -> Self {
707        Self::RoleNotFound { role: role.into() }
708    }
709
710    /// Create a new permission not found error
711    pub fn permission_not_found(permission: impl Into<String>) -> Self {
712        Self::PermissionNotFound {
713            permission: permission.into(),
714        }
715    }
716
717    /// Create a new invalid format error
718    pub fn invalid_format(message: impl Into<String>) -> Self {
719        Self::InvalidFormat {
720            message: message.into(),
721        }
722    }
723}
724
725impl StorageError {
726    /// Create a new connection failed error
727    pub fn connection_failed(message: impl Into<String>) -> Self {
728        Self::ConnectionFailed {
729            message: message.into(),
730        }
731    }
732
733    /// Create a new operation failed error
734    pub fn operation_failed(message: impl Into<String>) -> Self {
735        Self::OperationFailed {
736            message: message.into(),
737        }
738    }
739
740    /// Create a new serialization error
741    pub fn serialization(message: impl Into<String>) -> Self {
742        Self::Serialization {
743            message: message.into(),
744        }
745    }
746}
747
748impl MfaError {
749    /// Create a new method not supported error
750    pub fn method_not_supported(method: impl Into<String>) -> Self {
751        Self::MethodNotSupported {
752            method: method.into(),
753        }
754    }
755
756    /// Create a new verification failed error
757    pub fn verification_failed(message: impl Into<String>) -> Self {
758        Self::VerificationFailed {
759            message: message.into(),
760        }
761    }
762}
763
764// Actix-web ResponseError implementation
765#[cfg(feature = "actix-integration")]
766impl actix_web::ResponseError for AuthError {
767    fn error_response(&self) -> actix_web::HttpResponse {
768        match self {
769            AuthError::Token(_) => {
770                actix_web::HttpResponse::Unauthorized().json(serde_json::json!({
771                    "error": "invalid_token",
772                    "error_description": self.to_string()
773                }))
774            }
775            AuthError::Permission(_) => {
776                actix_web::HttpResponse::Forbidden().json(serde_json::json!({
777                    "error": "insufficient_permissions",
778                    "error_description": self.to_string()
779                }))
780            }
781            AuthError::RateLimit { .. } => {
782                actix_web::HttpResponse::TooManyRequests().json(serde_json::json!({
783                    "error": "rate_limit_exceeded",
784                    "error_description": self.to_string()
785                }))
786            }
787            AuthError::Configuration { .. }
788            | AuthError::Storage(_)
789            | AuthError::Internal { .. } => {
790                actix_web::HttpResponse::InternalServerError().json(serde_json::json!({
791                    "error": "internal_error",
792                    "error_description": "An internal error occurred"
793                }))
794            }
795            _ => actix_web::HttpResponse::BadRequest().json(serde_json::json!({
796                "error": "bad_request",
797                "error_description": self.to_string()
798            })),
799        }
800    }
801
802    fn status_code(&self) -> actix_web::http::StatusCode {
803        match self {
804            AuthError::Token(_) => actix_web::http::StatusCode::UNAUTHORIZED,
805            AuthError::Permission(_) => actix_web::http::StatusCode::FORBIDDEN,
806            AuthError::RateLimit { .. } => actix_web::http::StatusCode::TOO_MANY_REQUESTS,
807            AuthError::Internal { .. }
808            | AuthError::Configuration { .. }
809            | AuthError::Storage(_) => actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
810            _ => actix_web::http::StatusCode::BAD_REQUEST,
811        }
812    }
813}
814
815// Additional From implementations for admin tools
816impl From<Box<dyn std::error::Error + Send + Sync>> for AuthError {
817    fn from(error: Box<dyn std::error::Error + Send + Sync>) -> Self {
818        AuthError::Cli(format!("Admin tool error: {}", error))
819    }
820}
821
822impl From<Box<dyn std::error::Error>> for AuthError {
823    fn from(error: Box<dyn std::error::Error>) -> Self {
824        AuthError::Cli(format!("Admin tool error: {}", error))
825    }
826}
827
828#[cfg(test)]
829mod tests {
830    use super::*;
831    use std::error::Error;
832
833    #[test]
834    fn test_auth_error_creation() {
835        let token_error = AuthError::token("Invalid JWT signature");
836        assert!(matches!(token_error, AuthError::Token(_)));
837        assert!(token_error.to_string().contains("Invalid JWT signature"));
838
839        let permission_error = AuthError::access_denied("Access denied");
840        assert!(matches!(permission_error, AuthError::Permission(_)));
841        assert!(permission_error.to_string().contains("Access denied"));
842
843        let config_error = AuthError::config("Database connection failed");
844        assert!(matches!(config_error, AuthError::Configuration { .. }));
845        assert!(
846            config_error
847                .to_string()
848                .contains("Database connection failed")
849        );
850    }
851
852    #[test]
853    fn test_auth_error_categorization() {
854        // Test various error types maintain their category
855        let errors = vec![
856            (AuthError::token("test"), "Token"),
857            (AuthError::access_denied("test"), "Permission"),
858            (AuthError::config("test"), "Configuration"),
859            (AuthError::crypto("test"), "Crypto"),
860            (AuthError::validation("test"), "Validation"),
861        ];
862
863        for (error, expected_category) in errors {
864            let error_string = format!("{:?}", error);
865            assert!(
866                error_string.contains(expected_category),
867                "Error {:?} should contain category {}",
868                error,
869                expected_category
870            );
871        }
872    }
873
874    #[test]
875    fn test_rate_limit_error() {
876        let rate_limit_error = AuthError::rate_limit("Too many requests");
877
878        match rate_limit_error {
879            AuthError::RateLimit { message } => {
880                assert_eq!(message, "Too many requests");
881            }
882            _ => panic!("Expected RateLimit error"),
883        }
884    }
885
886    #[test]
887    fn test_validation_error() {
888        let validation_error = AuthError::validation("username must not be empty");
889
890        match validation_error {
891            AuthError::Validation { message } => {
892                assert_eq!(message, "username must not be empty");
893            }
894            _ => panic!("Expected Validation error"),
895        }
896    }
897
898    #[test]
899    fn test_configuration_error() {
900        let config_error = AuthError::config("jwt_secret is required");
901
902        match config_error {
903            AuthError::Configuration { message, .. } => {
904                assert_eq!(message, "jwt_secret is required");
905            }
906            _ => panic!("Expected Configuration error"),
907        }
908    }
909
910    #[test]
911    fn test_error_chain() {
912        let root_cause = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
913        let auth_error = AuthError::internal(format!("Config file error: {}", root_cause));
914
915        // Test that error information is preserved
916        assert!(auth_error.to_string().contains("File not found"));
917        assert!(auth_error.to_string().contains("Config file error"));
918    }
919
920    #[test]
921    fn test_error_source() {
922        let token_error = AuthError::token("JWT parsing failed");
923
924        // AuthError implements Error trait
925        // Token error wraps TokenError, so it should have a source
926        assert!(token_error.source().is_some());
927
928        // Test error display
929        let error_msg = format!("{}", token_error);
930        assert!(error_msg.contains("JWT parsing failed"));
931    }
932
933    #[test]
934    fn test_from_conversions() {
935        // Test conversion from std::io::Error
936        let io_error = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "Access denied");
937        let auth_error: AuthError = io_error.into();
938        assert!(matches!(auth_error, AuthError::Io(_)));
939
940        // Test conversion from serde_json::Error
941        let json_str = r#"{"invalid": json"#;
942        let json_error: serde_json::Error =
943            serde_json::from_str::<serde_json::Value>(json_str).unwrap_err();
944        let auth_error: AuthError = json_error.into();
945        assert!(matches!(auth_error, AuthError::Json(_)));
946    }
947
948    #[test]
949    fn test_error_equality() {
950        let error1 = AuthError::token("Same message");
951        let error2 = AuthError::token("Same message");
952        let error3 = AuthError::token("Different message");
953
954        // Test Debug representation for consistency
955        assert_eq!(format!("{:?}", error1), format!("{:?}", error2));
956        assert_ne!(format!("{:?}", error1), format!("{:?}", error3));
957    }
958
959    #[test]
960    fn test_actix_web_integration() {
961        #[cfg(feature = "actix-web")]
962        {
963            use actix_web::ResponseError;
964
965            // Test status codes
966            assert_eq!(
967                AuthError::token("test").status_code(),
968                actix_web::http::StatusCode::UNAUTHORIZED
969            );
970            assert_eq!(
971                AuthError::access_denied("test").status_code(),
972                actix_web::http::StatusCode::FORBIDDEN
973            );
974            assert_eq!(
975                AuthError::rate_limit("test").status_code(),
976                actix_web::http::StatusCode::TOO_MANY_REQUESTS
977            );
978            assert_eq!(
979                AuthError::internal("test").status_code(),
980                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
981            );
982        }
983    }
984
985    #[test]
986    fn test_error_message_safety() {
987        // Ensure error messages don't leak sensitive information
988        let sensitive_data = "password123";
989        let safe_error = AuthError::token("Invalid credentials");
990
991        // Error message should not contain sensitive data
992        assert!(!safe_error.to_string().contains(sensitive_data));
993
994        // Test that we can create errors without exposing internals
995        let config_error = AuthError::config("connection failed");
996        assert!(!config_error.to_string().contains("password"));
997        assert!(!config_error.to_string().contains("secret"));
998    }
999
1000    #[test]
1001    fn test_cli_error_conversion() {
1002        let boxed_error: Box<dyn std::error::Error + Send + Sync> = "CLI operation failed".into();
1003        let auth_error: AuthError = boxed_error.into();
1004
1005        assert!(matches!(auth_error, AuthError::Cli(_)));
1006        assert!(auth_error.to_string().contains("CLI operation failed"));
1007    }
1008
1009    #[test]
1010    fn test_error_variants_coverage() {
1011        // Ensure all error variants can be created and have proper messages
1012        let test_errors = vec![
1013            AuthError::token("token error"),
1014            AuthError::access_denied("permission error"),
1015            AuthError::internal("internal error"),
1016            AuthError::crypto("crypto error"),
1017            AuthError::Cli("cli error".to_string()),
1018            AuthError::validation("validation error"),
1019            AuthError::config("config error"),
1020            AuthError::rate_limit("rate limit error"),
1021        ];
1022
1023        for error in test_errors {
1024            // All errors should have non-empty messages
1025            assert!(
1026                !error.to_string().is_empty(),
1027                "Error should have message: {:?}",
1028                error
1029            );
1030
1031            // All errors should implement Debug
1032            let debug_repr = format!("{:?}", error);
1033            assert!(
1034                !debug_repr.is_empty(),
1035                "Error should have debug representation: {:?}",
1036                error
1037            );
1038        }
1039    }
1040
1041    #[test]
1042    fn test_oauth_specific_errors() {
1043        // Test OAuth-specific error creation using auth_method
1044        let invalid_client = AuthError::auth_method("oauth", "Client authentication failed");
1045        assert!(
1046            invalid_client
1047                .to_string()
1048                .contains("Client authentication failed")
1049        );
1050
1051        let invalid_grant = AuthError::auth_method("oauth", "Authorization code expired");
1052        assert!(
1053            invalid_grant
1054                .to_string()
1055                .contains("Authorization code expired")
1056        );
1057    }
1058
1059    #[test]
1060    fn test_error_context_preservation() {
1061        // Test that errors maintain context through transformations
1062        let original_msg = "Original error message";
1063        let context_msg = "Additional context";
1064
1065        let base_error = AuthError::internal(original_msg);
1066        let contextual_error = AuthError::internal(format!("{}: {}", context_msg, base_error));
1067
1068        assert!(contextual_error.to_string().contains(original_msg));
1069        assert!(contextual_error.to_string().contains(context_msg));
1070    }
1071
1072    #[test]
1073    fn test_error_serialization() {
1074        // Test that errors can be converted to JSON for API responses
1075        let error = AuthError::validation("email invalid format");
1076
1077        // Should be able to include in structured responses
1078        let error_response = serde_json::json!({
1079            "error": "validation_failed",
1080            "message": error.to_string(),
1081            "field": "email"
1082        });
1083
1084        assert!(
1085            error_response["message"]
1086                .as_str()
1087                .unwrap()
1088                .contains("invalid format")
1089        );
1090    }
1091
1092    #[test]
1093    fn test_concurrent_error_creation() {
1094        use std::thread;
1095
1096        let handles: Vec<_> = (0..10)
1097            .map(|i| {
1098                thread::spawn(move || {
1099                    let error = AuthError::token(format!("Concurrent error {}", i));
1100                    assert!(
1101                        error
1102                            .to_string()
1103                            .contains(&format!("Concurrent error {}", i))
1104                    );
1105                    error
1106                })
1107            })
1108            .collect();
1109
1110        // Wait for all threads and verify errors
1111        for handle in handles {
1112            let error = handle.join().unwrap();
1113            assert!(!error.to_string().is_empty());
1114        }
1115    }
1116}