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