Skip to main content

fastauth_core/
error.rs

1use std::borrow::Cow;
2use std::fmt;
3
4use bytes::Bytes;
5use http::{HeaderValue, StatusCode, header};
6use serde::Serialize;
7
8/// Error codes shared with Better Auth's client, so its `error.code` checks keep working.
9pub mod codes {
10    pub const UNAUTHORIZED: &str = "UNAUTHORIZED";
11    pub const FORBIDDEN: &str = "FORBIDDEN";
12    pub const NOT_FOUND: &str = "NOT_FOUND";
13    pub const METHOD_NOT_ALLOWED: &str = "METHOD_NOT_ALLOWED";
14    pub const INTERNAL: &str = "INTERNAL_SERVER_ERROR";
15    pub const INVALID_BODY: &str = "INVALID_REQUEST_BODY";
16    pub const TOO_MANY_REQUESTS: &str = "TOO_MANY_REQUESTS";
17    pub const INVALID_ORIGIN: &str = "INVALID_ORIGIN";
18    pub const MISSING_OR_NULL_ORIGIN: &str = "MISSING_OR_NULL_ORIGIN";
19    pub const INVALID_CALLBACK_URL: &str = "INVALID_CALLBACK_URL";
20    pub const SESSION_NOT_FRESH: &str = "SESSION_NOT_FRESH";
21    pub const INVALID_EMAIL: &str = "INVALID_EMAIL";
22    pub const INVALID_EMAIL_OR_PASSWORD: &str = "INVALID_EMAIL_OR_PASSWORD";
23    pub const INVALID_PASSWORD: &str = "INVALID_PASSWORD";
24    pub const PASSWORD_TOO_SHORT: &str = "PASSWORD_TOO_SHORT";
25    pub const PASSWORD_TOO_LONG: &str = "PASSWORD_TOO_LONG";
26    pub const PASSWORD_TOO_WEAK: &str = "PASSWORD_TOO_WEAK";
27    pub const USER_ALREADY_EXISTS: &str = "USER_ALREADY_EXISTS";
28    pub const USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: &str = "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL";
29    pub const USER_NOT_FOUND: &str = "USER_NOT_FOUND";
30    pub const EMAIL_NOT_VERIFIED: &str = "EMAIL_NOT_VERIFIED";
31    pub const EMAIL_ALREADY_VERIFIED: &str = "EMAIL_ALREADY_VERIFIED";
32    pub const INVALID_TOKEN: &str = "INVALID_TOKEN";
33    pub const CREDENTIAL_ACCOUNT_NOT_FOUND: &str = "CREDENTIAL_ACCOUNT_NOT_FOUND";
34    pub const SOCIAL_ACCOUNT_ALREADY_LINKED: &str = "SOCIAL_ACCOUNT_ALREADY_LINKED";
35    pub const SESSION_NOT_FOUND: &str = "SESSION_NOT_FOUND";
36    pub const INVALID_FIELD: &str = "INVALID_FIELD";
37    pub const FEATURE_DISABLED: &str = "FEATURE_DISABLED";
38    /// A user can't be deleted while it has accounts of a provider fastauth doesn't own.
39    pub const USER_HAS_FOREIGN_ACCOUNTS: &str = "USER_HAS_FOREIGN_ACCOUNTS";
40}
41
42/// The one error type every endpoint, hook and extractor returns. It leaves the server as
43/// `{ "code": "...", "message": "..." }` with `status`.
44#[derive(Clone, PartialEq, Eq)]
45pub struct AuthError {
46    status: StatusCode,
47    code: Cow<'static, str>,
48    message: Cow<'static, str>,
49}
50
51#[derive(Serialize)]
52struct ErrorBody<'a> {
53    code: &'a str,
54    message: &'a str,
55}
56
57impl AuthError {
58    pub const fn new(status: StatusCode, code: &'static str, message: &'static str) -> Self {
59        Self {
60            status,
61            code: Cow::Borrowed(code),
62            message: Cow::Borrowed(message),
63        }
64    }
65
66    pub fn with_message(
67        status: StatusCode,
68        code: impl Into<Cow<'static, str>>,
69        message: impl Into<Cow<'static, str>>,
70    ) -> Self {
71        Self {
72            status,
73            code: code.into(),
74            message: message.into(),
75        }
76    }
77
78    pub fn bad_request(
79        code: impl Into<Cow<'static, str>>,
80        message: impl Into<Cow<'static, str>>,
81    ) -> Self {
82        Self::with_message(StatusCode::BAD_REQUEST, code, message)
83    }
84
85    pub const fn unauthorized() -> Self {
86        Self::new(
87            StatusCode::UNAUTHORIZED,
88            codes::UNAUTHORIZED,
89            "a valid session is required",
90        )
91    }
92
93    pub const fn forbidden() -> Self {
94        Self::new(StatusCode::FORBIDDEN, codes::FORBIDDEN, "not allowed")
95    }
96
97    pub const fn not_found() -> Self {
98        Self::new(StatusCode::NOT_FOUND, codes::NOT_FOUND, "not found")
99    }
100
101    /// 403 `SESSION_NOT_FRESH`: the session is older than `fresh_age`.
102    pub const fn not_fresh() -> Self {
103        Self::new(
104            StatusCode::FORBIDDEN,
105            codes::SESSION_NOT_FRESH,
106            "sign in again to continue",
107        )
108    }
109
110    pub const fn too_many_requests() -> Self {
111        Self::new(
112            StatusCode::TOO_MANY_REQUESTS,
113            codes::TOO_MANY_REQUESTS,
114            "too many requests, try again later",
115        )
116    }
117
118    /// Logs `detail` server-side and returns a generic 500, so internals never reach clients.
119    pub fn internal(detail: impl fmt::Display) -> Self {
120        tracing::error!(error = %detail, "fastauth internal error");
121        Self::new(
122            StatusCode::INTERNAL_SERVER_ERROR,
123            codes::INTERNAL,
124            "internal server error",
125        )
126    }
127
128    pub fn status(&self) -> StatusCode {
129        self.status
130    }
131
132    pub fn code(&self) -> &str {
133        &self.code
134    }
135
136    pub fn message(&self) -> &str {
137        &self.message
138    }
139
140    pub fn to_json(&self) -> Bytes {
141        let body = ErrorBody {
142            code: &self.code,
143            message: &self.message,
144        };
145        Bytes::from(serde_json::to_vec(&body).expect("error body serializes"))
146    }
147
148    pub fn into_response(self) -> http::Response<Bytes> {
149        let mut response = http::Response::new(self.to_json());
150        *response.status_mut() = self.status;
151        response.headers_mut().insert(
152            header::CONTENT_TYPE,
153            HeaderValue::from_static("application/json"),
154        );
155        if self.status == StatusCode::TOO_MANY_REQUESTS {
156            response
157                .headers_mut()
158                .insert(header::RETRY_AFTER, HeaderValue::from_static("10"));
159        }
160        response
161    }
162}
163
164/// Lets axum handlers return `Result<T, AuthError>`: the same JSON body the auth routes use.
165#[cfg(feature = "axum")]
166impl axum_core::response::IntoResponse for AuthError {
167    fn into_response(self) -> axum_core::response::Response {
168        AuthError::into_response(self).map(axum_core::body::Body::from)
169    }
170}
171
172/// Lets actix-web handlers and extractors return `AuthError`: the same JSON body the auth
173/// routes use.
174#[cfg(feature = "actix")]
175impl actix_web::ResponseError for AuthError {
176    fn status_code(&self) -> actix_web::http::StatusCode {
177        actix_web::http::StatusCode::from_u16(self.status.as_u16())
178            .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR)
179    }
180
181    fn error_response(&self) -> actix_web::HttpResponse {
182        to_actix(self.clone().into_response())
183    }
184}
185
186/// An `http` 1.x response as an actix-web response, which is built on `http` 0.2.
187#[cfg(feature = "actix")]
188pub(crate) fn to_actix(response: http::Response<Bytes>) -> actix_web::HttpResponse {
189    let (parts, body) = response.into_parts();
190    let status = actix_web::http::StatusCode::from_u16(parts.status.as_u16())
191        .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);
192    let mut builder = actix_web::HttpResponse::build(status);
193    for (name, value) in &parts.headers {
194        builder.append_header((name.as_str(), value.as_bytes()));
195    }
196    builder.body(body)
197}
198
199impl fmt::Debug for AuthError {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        write!(
202            f,
203            "AuthError({} {}: {})",
204            self.status.as_u16(),
205            self.code,
206            self.message
207        )
208    }
209}
210
211impl fmt::Display for AuthError {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        write!(f, "{}: {}", self.code, self.message)
214    }
215}
216
217impl std::error::Error for AuthError {}
218
219/// Lets a plugin register its error codes at build time, so two plugins can't claim one code.
220pub trait ErrorCodes: Into<AuthError> {
221    const CODES: &'static [&'static str];
222}
223
224/// Configuration problems found by `.build()`, all reported at once.
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub struct BuildError {
227    pub problems: Vec<String>,
228}
229
230impl BuildError {
231    pub fn new(problem: impl Into<String>) -> Self {
232        Self {
233            problems: vec![problem.into()],
234        }
235    }
236}
237
238impl fmt::Display for BuildError {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        write!(f, "invalid fastauth configuration")?;
241        for problem in &self.problems {
242            write!(f, "\n  - {problem}")?;
243        }
244        Ok(())
245    }
246}
247
248impl std::error::Error for BuildError {}