Skip to main content

scyph_auth/
error.rs

1//! Authentication and authorization error type definitions for `scyph-auth`.
2//!
3//! This module provides [`AuthError`], the unified error type for all authentication,
4//! RBAC, JWT, and password operations within `scyph-auth`. It implements `Into<AppError>`
5//! to integrate seamlessly with Scyph's RFC 7807 HTTP error response system.
6//!
7//! # Error Mapping
8//!
9//! | [`AuthError`] variant  | [`scyph_core::AppError`] / HTTP status |
10//! |------------------------|-----------------------------------|
11//! | `Unauthorized`         | `AppError::Unauthorized` / 401    |
12//! | `Forbidden`            | `AppError::Forbidden` / 403       |
13//! | `ValidationError`      | `AppError::ValidationError` / 422 |
14//! | `Password`             | `AppError::Unauthorized` / 401    |
15//! | `Jwt`                  | `AppError::Unauthorized` / 401    |
16//! | `Internal`             | `AppError::internal(...)` / 500   |
17//!
18//! # Examples
19//!
20//! Constructing a validation error with field details:
21//!
22//! ```rust
23//! use scyph_auth::AuthError;
24//! use scyph_core::ErrorDetails;
25//!
26//! let err = AuthError::validation(
27//!     "Password policy violation",
28//!     vec![
29//!         ErrorDetails {
30//!             code: "TOO_SHORT".into(),
31//!             message: "Password must be at least 12 characters".into(),
32//!             field: Some("password".into()),
33//!         },
34//!     ],
35//! );
36//!
37//! // Convert to AppError for HTTP response
38//! let app_error: scyph_core::AppError = err.into();
39//! assert_eq!(app_error.status(), axum::http::StatusCode::UNPROCESSABLE_ENTITY);
40//! ```
41//!
42//! Returning an `AuthError` from a handler (auto-converts via `Into<AppError>`):
43//!
44//! ```rust,ignore
45//! use scyph_auth::AuthError;
46//! use scyph_core::{AppError, ApiResponse};
47//!
48//! async fn login_handler(/* ... */) -> Result<ApiResponse<String>, AppError> {
49//!     // verify_password returns PasswordError which converts to AuthError then AppError
50//!     scyph_auth::verify_password_async(&input_password, &stored_hash).await
51//!         .map_err(|e| AppError::from(AuthError::from(e)))?;
52//!     Ok(ApiResponse::ok("token_string".into()))
53//! }
54//! ```
55
56use scyph_core::{AppError, ErrorDetails};
57
58/// Error type for authentication, RBAC, and JWT operations in `scyph-auth`.
59///
60/// All variants convert to [`AppError`] via the [`From<AuthError> for AppError`] implementation,
61/// making it straightforward to use `?` in handlers that return `Result<_, AppError>`.
62#[derive(Debug, thiserror::Error)]
63pub enum AuthError {
64    /// Missing, invalid, expired, or revoked authentication credentials (e.g. Bearer token).
65    ///
66    /// Maps to HTTP 401 Unauthorized.
67    #[error("Unauthorized: {0}")]
68    Unauthorized(String),
69
70    /// Authenticated user does not possess required role or permission.
71    ///
72    /// Maps to HTTP 403 Forbidden.
73    #[error("Forbidden: {0}")]
74    Forbidden(String),
75
76    /// Structured validation failure (e.g. password policy, invalid credential fields).
77    ///
78    /// Maps to HTTP 422 Unprocessable Entity with per-field [`ErrorDetails`].
79    #[error("Auth validation failed: {message}")]
80    ValidationError {
81        /// Summary message.
82        message: String,
83        /// Field-level validation error details.
84        details: Vec<ErrorDetails>,
85    },
86
87    /// Password hashing or verification failure.
88    ///
89    /// Wraps [`PasswordError`](crate::password::PasswordError). Maps to HTTP 401 Unauthorized
90    /// because a password failure indicates invalid credentials.
91    #[error("Password error: {0}")]
92    Password(#[from] crate::password::PasswordError),
93
94    /// JWT encoding, decoding, or verification failure.
95    ///
96    /// Wraps [`JwtError`](crate::jwt::JwtError). Maps to HTTP 401 Unauthorized.
97    #[error("JWT error: {0}")]
98    Jwt(#[from] crate::jwt::JwtError),
99
100    /// Internal or generic authentication processing error.
101    ///
102    /// Maps to HTTP 500 Internal Server Error.
103    #[error("Internal auth error: {0}")]
104    Internal(String),
105}
106
107impl AuthError {
108    /// Constructs an [`AuthError::ValidationError`] with a summary message and field-level details.
109    ///
110    /// # Arguments
111    ///
112    /// * `message` - A human-readable summary of why validation failed.
113    /// * `details` - A list of [`ErrorDetails`] describing per-field failures.
114    ///
115    /// # Examples
116    ///
117    /// ```rust
118    /// use scyph_auth::AuthError;
119    /// use scyph_core::ErrorDetails;
120    ///
121    /// let err = AuthError::validation(
122    ///     "Invalid credentials",
123    ///     vec![ErrorDetails {
124    ///         code: "REQUIRED".into(),
125    ///         message: "Email is required".into(),
126    ///         field: Some("email".into()),
127    ///     }],
128    /// );
129    /// ```
130    pub fn validation(message: impl Into<String>, details: Vec<ErrorDetails>) -> Self {
131        Self::ValidationError {
132            message: message.into(),
133            details,
134        }
135    }
136}
137
138impl From<AuthError> for AppError {
139    /// Converts an [`AuthError`] into an RFC 7807 [`AppError`] response (401 Unauthorized, 403 Forbidden, 422 Unprocessable, or 500 Internal).
140    fn from(err: AuthError) -> Self {
141        match err {
142            AuthError::Unauthorized(msg) => AppError::Unauthorized(msg),
143            AuthError::Forbidden(msg) => AppError::Forbidden(msg),
144            AuthError::ValidationError { message, details } => {
145                AppError::ValidationError { message, details }
146            }
147            AuthError::Password(e) => AppError::Unauthorized(e.to_string()),
148            AuthError::Jwt(e) => AppError::Unauthorized(e.to_string()),
149            AuthError::Internal(msg) => AppError::internal(msg),
150        }
151    }
152}