| 1 | use axum::Json; |
| 2 | use axum::http::{StatusCode, header}; |
| 3 | use axum::response::{IntoResponse, Response}; |
| 4 | use serde::Serialize; |
| 5 | use serde_json::json; |
| 6 | use utoipa::ToSchema; |
| 7 | |
| 8 | |
| 9 | #[derive(Serialize, ToSchema)] |
| 10 | pub struct ErrorResponse { |
| 11 | |
| 12 | pub error: String, |
| 13 | } |
| 14 | |
| 15 | |
| 16 | #[derive(Debug, thiserror::Error)] |
| 17 | pub enum ValidationError { |
| 18 | #[error("{0} must not be empty")] |
| 19 | Empty(&'static str), |
| 20 | #[error("{field} must be at least {min} characters (got {got})")] |
| 21 | TooShort { |
| 22 | field: &'static str, |
| 23 | min: usize, |
| 24 | got: usize, |
| 25 | }, |
| 26 | #[error("{field} must be at most {max} characters (got {got})")] |
| 27 | TooLong { |
| 28 | field: &'static str, |
| 29 | max: usize, |
| 30 | got: usize, |
| 31 | }, |
| 32 | #[error("{0} must be ASCII")] |
| 33 | NotAscii(&'static str), |
| 34 | #[error("{field}: {reason}")] |
| 35 | Invalid { |
| 36 | field: &'static str, |
| 37 | reason: &'static str, |
| 38 | }, |
| 39 | } |
| 40 | |
| 41 | |
| 42 | #[derive(Debug, thiserror::Error)] |
| 43 | pub enum AppError { |
| 44 | #[error(transparent)] |
| 45 | Validation(#[from] ValidationError), |
| 46 | #[error("not found")] |
| 47 | NotFound, |
| 48 | #[error("unauthorized")] |
| 49 | Unauthorized, |
| 50 | #[error("forbidden: {0}")] |
| 51 | Forbidden(&'static str), |
| 52 | #[error("conflict: {0}")] |
| 53 | Conflict(&'static str), |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | #[error("conflict: {0}")] |
| 59 | ConflictOwned(String), |
| 60 | |
| 61 | |
| 62 | #[error("payload too large: {0}")] |
| 63 | PayloadTooLarge(String), |
| 64 | #[error("too many requests")] |
| 65 | TooManyRequests { retry_after_secs: u64 }, |
| 66 | #[error("database error")] |
| 67 | Db(#[source] surrealdb::Error), |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | #[error("database unavailable")] |
| 74 | DbUnavailable, |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | #[error("request timed out")] |
| 85 | DbTimeout, |
| 86 | #[error("internal error: {0}")] |
| 87 | Internal(String), |
| 88 | } |
| 89 | |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | pub(crate) fn is_session_replay_error(message: &str) -> bool { |
| 97 | message.contains("Specify a namespace") || message.contains("Anonymous access not allowed") |
| 98 | } |
| 99 | |
| 100 | impl From<surrealdb::Error> for AppError { |
| 101 | fn from(e: surrealdb::Error) -> Self { |
| 102 | |
| 103 | |
| 104 | |
| 105 | if e.is_connection() || is_session_replay_error(&e.to_string()) { |
| 106 | AppError::DbUnavailable |
| 107 | } else { |
| 108 | AppError::Db(e) |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | impl From<argon2::password_hash::Error> for AppError { |
| 114 | fn from(e: argon2::password_hash::Error) -> Self { |
| 115 | AppError::Internal(format!("password hashing error: {e}")) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | impl IntoResponse for AppError { |
| 120 | fn into_response(self) -> Response { |
| 121 | let (status, message) = match &self { |
| 122 | |
| 123 | AppError::TooManyRequests { retry_after_secs } => { |
| 124 | return ( |
| 125 | StatusCode::TOO_MANY_REQUESTS, |
| 126 | [(header::RETRY_AFTER, retry_after_secs.to_string())], |
| 127 | Json(json!({ "error": "too many requests" })), |
| 128 | ) |
| 129 | .into_response(); |
| 130 | } |
| 131 | |
| 132 | AppError::DbUnavailable => { |
| 133 | tracing::warn!("database reconnecting — refusing the query with 503"); |
| 134 | return ( |
| 135 | StatusCode::SERVICE_UNAVAILABLE, |
| 136 | [(header::RETRY_AFTER, "1")], |
| 137 | Json(json!({ "error": "database reconnecting — retry shortly" })), |
| 138 | ) |
| 139 | .into_response(); |
| 140 | } |
| 141 | |
| 142 | |
| 143 | AppError::DbTimeout => { |
| 144 | tracing::error!("request timed out waiting on the database"); |
| 145 | return ( |
| 146 | StatusCode::SERVICE_UNAVAILABLE, |
| 147 | Json(json!({ "error": "request timed out — the write may or may not have applied" })), |
| 148 | ) |
| 149 | .into_response(); |
| 150 | } |
| 151 | AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()), |
| 152 | AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), |
| 153 | AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), |
| 154 | AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()), |
| 155 | AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()), |
| 156 | AppError::ConflictOwned(m) => (StatusCode::CONFLICT, m.clone()), |
| 157 | AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()), |
| 158 | AppError::Db(e) => { |
| 159 | tracing::error!("database error: {e}"); |
| 160 | ( |
| 161 | StatusCode::INTERNAL_SERVER_ERROR, |
| 162 | "database error".to_string(), |
| 163 | ) |
| 164 | } |
| 165 | AppError::Internal(m) => { |
| 166 | tracing::error!("internal error: {m}"); |
| 167 | ( |
| 168 | StatusCode::INTERNAL_SERVER_ERROR, |
| 169 | "internal server error".to_string(), |
| 170 | ) |
| 171 | } |
| 172 | }; |
| 173 | (status, Json(json!({ "error": message }))).into_response() |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | #[cfg(test)] |
| 178 | mod tests { |
| 179 | use super::*; |
| 180 | |
| 181 | #[test] |
| 182 | fn replay_signatures_classify_as_unavailable() { |
| 183 | |
| 184 | |
| 185 | assert!(is_session_replay_error("Specify a namespace to use")); |
| 186 | assert!(is_session_replay_error( |
| 187 | "Anonymous access not allowed: Not enough permissions to perform this action" |
| 188 | )); |
| 189 | } |
| 190 | |
| 191 | #[test] |
| 192 | fn connection_errors_classify_as_unavailable() { |
| 193 | |
| 194 | |
| 195 | let e = surrealdb::Error::connection( |
| 196 | "Connection reset".to_string(), |
| 197 | surrealdb::types::ConnectionError::ConnectionFailed, |
| 198 | ); |
| 199 | assert!(matches!(AppError::from(e), AppError::DbUnavailable)); |
| 200 | } |
| 201 | |
| 202 | #[test] |
| 203 | fn real_errors_stay_db_errors() { |
| 204 | |
| 205 | assert!(!is_session_replay_error( |
| 206 | "Not enough permissions to perform this action" |
| 207 | )); |
| 208 | assert!(!is_session_replay_error("Parse error: unexpected token")); |
| 209 | assert!(!is_session_replay_error( |
| 210 | "Database index `user_username` already contains 'admin'" |
| 211 | )); |
| 212 | } |
| 213 | } |