Error taxonomy, field validators, and limits
Browse files at this commit90effd19ff4e7088366a0c1ac95f25d6374f6baaParent: 25233e0- feat
- error taxonomy, field validators, and limits
3 changed files +329 -0
- src/constant.rs +28 -0
- src/error.rs +102 -0
- src/validate.rs +199 -0
src/constant.rsadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +//! Validation limits, in one place. | ||
| 2 | + | ||
| 3 | +pub const MIN_USERNAME_LEN: usize = 3; | ||
| 4 | +pub const MAX_USERNAME_LEN: usize = 32; | ||
| 5 | + | ||
| 6 | +pub const MIN_PASSWORD_LEN: usize = 6; | ||
| 7 | +pub const MAX_PASSWORD_LEN: usize = 128; | ||
| 8 | + | ||
| 9 | +pub const MAX_NOTE_TITLE_LEN: usize = 200; | ||
| 10 | +pub const MAX_NOTE_CONTENT_LEN: usize = 10_000; | ||
| 11 | + | ||
| 12 | +pub const MAX_EVENT_TITLE_LEN: usize = 200; | ||
| 13 | +pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; | ||
| 14 | + | ||
| 15 | +pub const MAX_EXAM_TITLE_LEN: usize = 200; | ||
| 16 | +pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; | ||
| 17 | + | ||
| 18 | +/// The only accepted attendance states. | ||
| 19 | +pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; | ||
| 20 | + | ||
| 21 | +/// The only accepted exam kinds — an exam is a homework or a quiz, nothing else. | ||
| 22 | +pub const EXAM_KINDS: [&str; 2] = ["homework", "quiz"]; | ||
| 23 | + | ||
| 24 | +/// Inclusive bounds for an exam mark. | ||
| 25 | +pub const MIN_MARK: i64 = 0; | ||
| 26 | +pub const MAX_MARK: i64 = 100; | ||
| 27 | + | ||
| 28 | +pub const SESSION_DURATION_DAYS: i64 = 7; | ||
src/error.rsadded+102 -0
| @@ -0,0 +1,102 @@ | |||
| 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 | +/// Uniform error body shape (`{ "error": "..." }`) used for OpenAPI docs. | ||
| 9 | +#[derive(Serialize, ToSchema)] | ||
| 10 | +pub struct ErrorResponse { | ||
| 11 | + /// Human-readable failure reason. | ||
| 12 | + pub error: String, | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +/// Why a newtype refused to be constructed from raw input. Always maps to `400`. | ||
| 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 | +/// The single error type every fallible operation returns. | ||
| 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 | + #[error("too many requests")] | ||
| 55 | + TooManyRequests { retry_after_secs: u64 }, | ||
| 56 | + #[error("database error")] | ||
| 57 | + Db(#[from] surrealdb::Error), | ||
| 58 | + #[error("internal error: {0}")] | ||
| 59 | + Internal(String), | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +impl From<argon2::password_hash::Error> for AppError { | ||
| 63 | + fn from(e: argon2::password_hash::Error) -> Self { | ||
| 64 | + AppError::Internal(format!("password hashing error: {e}")) | ||
| 65 | + } | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +impl IntoResponse for AppError { | ||
| 69 | + fn into_response(self) -> Response { | ||
| 70 | + let (status, message) = match &self { | ||
| 71 | + // The one arm with an extra header, so it builds its response here. | ||
| 72 | + AppError::TooManyRequests { retry_after_secs } => { | ||
| 73 | + return ( | ||
| 74 | + StatusCode::TOO_MANY_REQUESTS, | ||
| 75 | + [(header::RETRY_AFTER, retry_after_secs.to_string())], | ||
| 76 | + Json(json!({ "error": "too many requests" })), | ||
| 77 | + ) | ||
| 78 | + .into_response(); | ||
| 79 | + } | ||
| 80 | + AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()), | ||
| 81 | + AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), | ||
| 82 | + AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), | ||
| 83 | + AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()), | ||
| 84 | + AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()), | ||
| 85 | + AppError::Db(e) => { | ||
| 86 | + tracing::error!("database error: {e}"); | ||
| 87 | + ( | ||
| 88 | + StatusCode::INTERNAL_SERVER_ERROR, | ||
| 89 | + "database error".to_string(), | ||
| 90 | + ) | ||
| 91 | + } | ||
| 92 | + AppError::Internal(m) => { | ||
| 93 | + tracing::error!("internal error: {m}"); | ||
| 94 | + ( | ||
| 95 | + StatusCode::INTERNAL_SERVER_ERROR, | ||
| 96 | + "internal server error".to_string(), | ||
| 97 | + ) | ||
| 98 | + } | ||
| 99 | + }; | ||
| 100 | + (status, Json(json!({ "error": message }))).into_response() | ||
| 101 | + } | ||
| 102 | +} | ||
src/validate.rsadded+199 -0
| @@ -0,0 +1,199 @@ | |||
| 1 | +//! Field validators. Each newtype's `try_new` calls one of these before wrapping | ||
| 2 | +//! the value, so an existing newtype is always valid (parse, don't validate). | ||
| 3 | + | ||
| 4 | +use crate::constant::{ | ||
| 5 | + ATTENDANCE_STATUSES, EXAM_KINDS, MAX_MARK, MAX_PASSWORD_LEN, MAX_USERNAME_LEN, MIN_MARK, | ||
| 6 | + MIN_PASSWORD_LEN, MIN_USERNAME_LEN, | ||
| 7 | +}; | ||
| 8 | +use crate::error::ValidationError; | ||
| 9 | + | ||
| 10 | +pub fn validate_username(value: &str) -> Result<(), ValidationError> { | ||
| 11 | + // Length is measured on the trimmed value so padding can't defeat the | ||
| 12 | + // minimum (e.g. "a " is a one-character name, not a three-character one). | ||
| 13 | + let value = value.trim(); | ||
| 14 | + if value.is_empty() { | ||
| 15 | + return Err(ValidationError::Empty("username")); | ||
| 16 | + } | ||
| 17 | + if !value.is_ascii() { | ||
| 18 | + return Err(ValidationError::NotAscii("username")); | ||
| 19 | + } | ||
| 20 | + let len = value.chars().count(); | ||
| 21 | + if len < MIN_USERNAME_LEN { | ||
| 22 | + return Err(ValidationError::TooShort { | ||
| 23 | + field: "username", | ||
| 24 | + min: MIN_USERNAME_LEN, | ||
| 25 | + got: len, | ||
| 26 | + }); | ||
| 27 | + } | ||
| 28 | + if len > MAX_USERNAME_LEN { | ||
| 29 | + return Err(ValidationError::TooLong { | ||
| 30 | + field: "username", | ||
| 31 | + max: MAX_USERNAME_LEN, | ||
| 32 | + got: len, | ||
| 33 | + }); | ||
| 34 | + } | ||
| 35 | + Ok(()) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +pub fn validate_password(value: &str) -> Result<(), ValidationError> { | ||
| 39 | + // A password may contain anything, including whitespace, so it is not | ||
| 40 | + // trimmed — but length is still measured in characters, not UTF-8 bytes. | ||
| 41 | + let len = value.chars().count(); | ||
| 42 | + if len < MIN_PASSWORD_LEN { | ||
| 43 | + return Err(ValidationError::TooShort { | ||
| 44 | + field: "password", | ||
| 45 | + min: MIN_PASSWORD_LEN, | ||
| 46 | + got: len, | ||
| 47 | + }); | ||
| 48 | + } | ||
| 49 | + if len > MAX_PASSWORD_LEN { | ||
| 50 | + return Err(ValidationError::TooLong { | ||
| 51 | + field: "password", | ||
| 52 | + max: MAX_PASSWORD_LEN, | ||
| 53 | + got: len, | ||
| 54 | + }); | ||
| 55 | + } | ||
| 56 | + Ok(()) | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// A required free-text field: non-blank and within `max`. | ||
| 60 | +pub fn validate_required( | ||
| 61 | + field: &'static str, | ||
| 62 | + value: &str, | ||
| 63 | + max: usize, | ||
| 64 | +) -> Result<(), ValidationError> { | ||
| 65 | + if value.trim().is_empty() { | ||
| 66 | + return Err(ValidationError::Empty(field)); | ||
| 67 | + } | ||
| 68 | + if value.chars().count() > max { | ||
| 69 | + return Err(ValidationError::TooLong { | ||
| 70 | + field, | ||
| 71 | + max, | ||
| 72 | + got: value.chars().count(), | ||
| 73 | + }); | ||
| 74 | + } | ||
| 75 | + Ok(()) | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// An optional free-text field: may be empty, but within `max`. | ||
| 79 | +pub fn validate_optional( | ||
| 80 | + field: &'static str, | ||
| 81 | + value: &str, | ||
| 82 | + max: usize, | ||
| 83 | +) -> Result<(), ValidationError> { | ||
| 84 | + if value.chars().count() > max { | ||
| 85 | + return Err(ValidationError::TooLong { | ||
| 86 | + field, | ||
| 87 | + max, | ||
| 88 | + got: value.chars().count(), | ||
| 89 | + }); | ||
| 90 | + } | ||
| 91 | + Ok(()) | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +pub fn validate_status(value: &str) -> Result<(), ValidationError> { | ||
| 95 | + if ATTENDANCE_STATUSES.contains(&value) { | ||
| 96 | + Ok(()) | ||
| 97 | + } else { | ||
| 98 | + Err(ValidationError::Invalid { | ||
| 99 | + field: "status", | ||
| 100 | + reason: "must be one of: present, absent, late, excused", | ||
| 101 | + }) | ||
| 102 | + } | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +pub fn validate_exam_kind(value: &str) -> Result<(), ValidationError> { | ||
| 106 | + if EXAM_KINDS.contains(&value) { | ||
| 107 | + Ok(()) | ||
| 108 | + } else { | ||
| 109 | + Err(ValidationError::Invalid { | ||
| 110 | + field: "kind", | ||
| 111 | + reason: "must be one of: homework, quiz", | ||
| 112 | + }) | ||
| 113 | + } | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +pub fn validate_mark(value: i64) -> Result<(), ValidationError> { | ||
| 117 | + if (MIN_MARK..=MAX_MARK).contains(&value) { | ||
| 118 | + Ok(()) | ||
| 119 | + } else { | ||
| 120 | + Err(ValidationError::Invalid { | ||
| 121 | + field: "mark", | ||
| 122 | + reason: "must be between 0 and 100", | ||
| 123 | + }) | ||
| 124 | + } | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +#[cfg(test)] | ||
| 128 | +mod tests { | ||
| 129 | + use super::*; | ||
| 130 | + | ||
| 131 | + #[tokio::test] | ||
| 132 | + async fn username_rules() { | ||
| 133 | + assert!(validate_username("ali").is_ok()); | ||
| 134 | + assert!(validate_username("ab").is_err()); // too short | ||
| 135 | + assert!(validate_username(" ").is_err()); // blank | ||
| 136 | + assert!(validate_username(&"x".repeat(33)).is_err()); // too long | ||
| 137 | + assert!(validate_username("naïve").is_err()); // non-ascii | ||
| 138 | + assert!(validate_username("a ").is_err()); // padding can't defeat the minimum | ||
| 139 | + } | ||
| 140 | + | ||
| 141 | + #[tokio::test] | ||
| 142 | + async fn length_is_measured_in_characters_not_bytes() { | ||
| 143 | + // "é" is two UTF-8 bytes; a 4-char password of them is under the 6-char | ||
| 144 | + // minimum and must be rejected as too short, not accepted on byte count. | ||
| 145 | + assert!(validate_password("éééé").is_err()); | ||
| 146 | + // Exactly `max` multi-byte characters is allowed (bytes would overflow). | ||
| 147 | + assert!(validate_required("title", &"é".repeat(5), 5).is_ok()); | ||
| 148 | + assert!(validate_required("title", &"é".repeat(6), 5).is_err()); | ||
| 149 | + assert!(validate_optional("content", &"é".repeat(5), 5).is_ok()); | ||
| 150 | + assert!(validate_optional("content", &"é".repeat(6), 5).is_err()); | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + #[tokio::test] | ||
| 154 | + async fn password_rules() { | ||
| 155 | + assert!(validate_password("secret1").is_ok()); | ||
| 156 | + assert!(validate_password("12345").is_err()); | ||
| 157 | + assert!(validate_password(&"x".repeat(129)).is_err()); | ||
| 158 | + } | ||
| 159 | + | ||
| 160 | + #[tokio::test] | ||
| 161 | + async fn required_rules() { | ||
| 162 | + assert!(validate_required("title", "hi", 10).is_ok()); | ||
| 163 | + assert!(validate_required("title", " ", 10).is_err()); | ||
| 164 | + assert!(validate_required("title", "toolong", 3).is_err()); | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + #[tokio::test] | ||
| 168 | + async fn optional_rules() { | ||
| 169 | + assert!(validate_optional("content", "", 10).is_ok()); | ||
| 170 | + assert!(validate_optional("content", "toolong", 3).is_err()); | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + #[tokio::test] | ||
| 174 | + async fn status_rules() { | ||
| 175 | + for status in ["present", "absent", "late", "excused"] { | ||
| 176 | + assert!(validate_status(status).is_ok()); | ||
| 177 | + } | ||
| 178 | + assert!(validate_status("maybe").is_err()); | ||
| 179 | + assert!(validate_status("").is_err()); | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + #[tokio::test] | ||
| 183 | + async fn exam_kind_rules() { | ||
| 184 | + for kind in ["homework", "quiz"] { | ||
| 185 | + assert!(validate_exam_kind(kind).is_ok()); | ||
| 186 | + } | ||
| 187 | + assert!(validate_exam_kind("final").is_err()); | ||
| 188 | + assert!(validate_exam_kind("").is_err()); | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + #[tokio::test] | ||
| 192 | + async fn mark_rules() { | ||
| 193 | + for mark in [0, 1, 50, 99, 100] { | ||
| 194 | + assert!(validate_mark(mark).is_ok()); | ||
| 195 | + } | ||
| 196 | + assert!(validate_mark(-1).is_err()); | ||
| 197 | + assert!(validate_mark(101).is_err()); | ||
| 198 | + } | ||
| 199 | +} | ||