forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

user.rs497 lines, 18.9 KiBHistoryRawDownload
1//! Pure user shapes: the typed id, the credential newtypes (username,
2//! password, argon2 hash — with their blocking-pool discipline), and the row
3//! itself. Persistence lives in [`crate::db::user`]; the admin seed and the
4//! role change in [`crate::service::user`].
5
6use std::sync::OnceLock;
7
8use argon2::password_hash::phc::PasswordHash as PhcHash;
9use argon2::{Argon2, PasswordHasher, PasswordVerifier};
10use uuid::Uuid;
11
12use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD, MAX_STUDENT_NUMBER_LEN};
13use crate::domain::monotonic_id::next_uuid;
14use crate::domain::note_file::FileContentType;
15use crate::domain::person::PersonId;
16use crate::domain::preferences::{Language, PaletteColor, Theme};
17use crate::domain::profile::{
18 Address, Bio, BirthDate, DisplayName, Email, Gender, PersonName, Phone,
19};
20use crate::domain::role::Role;
21use crate::error::{AppError, ValidationError};
22use crate::validate::{validate_password, validate_required, validate_username};
23
24/// Typed user row id. A UUIDv7 minted by the process-wide monotonic
25/// generator, so `id` order is mint order.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
27#[sqlx(transparent)]
28pub struct UserId(Uuid);
29
30impl UserId {
31 /// Minted from the process-wide monotonic generator, not a random v4:
32 /// users list `id DESC` (newest first, [`crate::db::user::list_all`]) and
33 /// page by offset over that order, and a random low half scrambles rows
34 /// minted in the same millisecond. Not a secret: the session token is
35 /// separate (32-byte CSPRNG, `web::auth`), so id order carries no
36 /// authority.
37 pub fn generate() -> Self {
38 Self(next_uuid())
39 }
40
41 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
42 /// cannot take the newtype. Static `query!` binds take `self` directly.
43 pub fn uuid(&self) -> Uuid {
44 self.0
45 }
46
47 /// Parse a wire key. A key that parses as no UUID — a malformed path
48 /// segment — reads as the nil id, which matches no row: exactly the 404 a
49 /// dangling record key produced under the old store, without turning a
50 /// typo into a panic.
51 pub fn from_key(key: &str) -> Self {
52 Self(Uuid::parse_str(key).unwrap_or(Uuid::nil()))
53 }
54
55 /// The hyphenated wire form.
56 pub fn key(&self) -> String {
57 self.0.to_string()
58 }
59}
60
61/// A validated username. Construction guarantees the restrictions hold and
62/// canonicalizes the value: the stored string is trimmed, since the unique
63/// index and the login lookup key on it — `"ali "` must be `"ali"`, not a
64/// second, visually identical account.
65#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
66#[sqlx(transparent)]
67pub struct Username(String);
68
69impl Username {
70 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
71 validate_username(value)?;
72 Ok(Self(value.trim().to_string()))
73 }
74
75 pub fn as_str(&self) -> &str {
76 &self.0
77 }
78}
79
80/// A validated student number. Construction canonicalizes the value the way
81/// [`Username`] does — the stored string is trimmed, because the partial unique
82/// index keys on it and `"1234 "` must collide with `"1234"`, not sit beside it
83/// as a second number the school never issued.
84///
85/// Shape only: non-blank and within [`MAX_STUDENT_NUMBER_LEN`]. Uniqueness is
86/// the index's, and *so is the role rule* — whether the holding account is a
87/// student is the write path's check (it holds the row), never this type's,
88/// which never sees a role.
89#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
90#[sqlx(transparent)]
91pub struct StudentNumber(String);
92
93impl StudentNumber {
94 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
95 let trimmed = value.trim();
96 validate_required("student_number", trimmed, MAX_STUDENT_NUMBER_LEN)?;
97 Ok(Self(trimmed.to_string()))
98 }
99
100 pub fn as_str(&self) -> &str {
101 &self.0
102 }
103
104 /// The refusal every write path answers when a number would land on a row
105 /// that is not a student. Spelled once because two layers must say the
106 /// same thing: the web layer's pre-check (against the role it read) and
107 /// the database's own `CHECK` on the row (against the role at write time,
108 /// which is what closes the read-then-write race) both answer a 400, and a
109 /// client must not have to tell two sentences apart for one rule.
110 pub fn non_student_refusal() -> ValidationError {
111 ValidationError::Invalid {
112 field: "student_number",
113 reason: "only a student account may hold a student number",
114 }
115 }
116}
117
118/// Bounds how many argon2 hashes run at once. `spawn_blocking` is unbounded —
119/// tokio grows the blocking pool to 512 threads — and argon2's default `m_cost`
120/// is 19 MiB, so an un-capped login flood claims gigabytes (measured: ~17 MB
121/// per in-flight hash) and gets the whole process OOM-killed. A permit turns
122/// that into queueing: latency instead of memory. `nproc * 2` keeps every core
123/// busy while a hash waits on memory bandwidth, with a floor of 2 permits so a
124/// single-core box still makes progress.
125fn argon2_permits() -> &'static tokio::sync::Semaphore {
126 static PERMITS: OnceLock<tokio::sync::Semaphore> = OnceLock::new();
127 PERMITS.get_or_init(|| {
128 let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
129 tokio::sync::Semaphore::new(cores * 2)
130 })
131}
132
133/// A validated plaintext password. Never stored — only hashed or verified.
134pub struct Password(String);
135
136impl Password {
137 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
138 validate_password(value)?;
139 Ok(Self(value.to_string()))
140 }
141
142 /// Private on purpose: argon2 must never run on an async worker. Callers
143 /// outside this module go through [`Password::hash_async`].
144 fn hash(&self) -> Result<PasswordHash, AppError> {
145 // password-hash 0.6 generates the salt internally (its own CSPRNG);
146 // the explicit SaltString step is gone.
147 let hash = Argon2::default()
148 .hash_password(self.0.as_bytes())?
149 .to_string();
150 Ok(PasswordHash(hash))
151 }
152
153 /// [`Password::hash`] moved onto the blocking pool. argon2 is deliberately
154 /// CPU-expensive, so hashing on an async worker starves the runtime: under
155 /// load a registration burst pushes requests past `REQUEST_TIMEOUT_SECS`
156 /// and they come back as 503. Every request path must use this, not `hash`.
157 pub async fn hash_async(&self) -> Result<PasswordHash, AppError> {
158 let plain = self.0.clone();
159 let _permit = argon2_permits()
160 .acquire()
161 .await
162 .map_err(|e| AppError::Internal(format!("hash permit: {e}")))?;
163 tokio::task::spawn_blocking(move || Password(plain).hash())
164 .await
165 .map_err(|e| AppError::Internal(format!("hash task: {e}")))?
166 }
167}
168
169/// An argon2 PHC hash, safe to persist.
170#[derive(Debug, Clone, sqlx::Type)]
171#[sqlx(transparent)]
172pub struct PasswordHash(String);
173
174/// A process-wide decoy hash, computed once on first use. Verifying against it
175/// performs the full argon2 work while matching no real account.
176fn decoy_hash() -> &'static PasswordHash {
177 static DECOY: OnceLock<PasswordHash> = OnceLock::new();
178 DECOY.get_or_init(|| {
179 Password::try_new(DECOY_PASSWORD)
180 .expect("decoy password satisfies the password rules")
181 .hash()
182 .expect("decoy password hashes")
183 })
184}
185
186impl PasswordHash {
187 pub fn as_str(&self) -> &str {
188 &self.0
189 }
190
191 /// Private on purpose — see [`Password::hash`]. Use [`PasswordHash::verify_async`].
192 fn verify(&self, password: &Password) -> bool {
193 match PhcHash::new(&self.0) {
194 Ok(parsed) => Argon2::default()
195 .verify_password(password.0.as_bytes(), &parsed)
196 .is_ok(),
197 Err(_) => false,
198 }
199 }
200
201 /// [`PasswordHash::verify`] on the blocking pool — see [`Password::hash_async`].
202 pub async fn verify_async(&self, password: &Password) -> bool {
203 let hash = self.0.clone();
204 let plain = password.0.clone();
205 // A closed semaphore can't happen (it is `'static` and never closed), but
206 // if it ever did this must fail like a pool panic does — 401, never a
207 // status an attacker could tell apart from the unknown-user branch.
208 let Ok(_permit) = argon2_permits().acquire().await else {
209 return false;
210 };
211 tokio::task::spawn_blocking(move || PasswordHash(hash).verify(&Password(plain)))
212 .await
213 .unwrap_or(false)
214 }
215
216 /// Run a throwaway verification against the decoy hash, on the blocking pool
217 /// (see [`Password::hash_async`]; the one-time decoy hash happens there too).
218 /// Login calls this when the username is unknown, so a missing user costs the
219 /// same argon2 time as a real (wrong-password) check — otherwise the faster
220 /// reply would let an attacker enumerate valid usernames by timing.
221 pub async fn verify_decoy_async(password: &Password) {
222 let plain = password.0.clone();
223 // Same permit as the real check, so both login branches queue alike.
224 let Ok(_permit) = argon2_permits().acquire().await else {
225 return;
226 };
227 let _ = tokio::task::spawn_blocking(move || decoy_hash().verify(&Password(plain))).await;
228 }
229
230 /// Compute the decoy hash at startup, off the async runtime. Without this the
231 /// process's first unknown-username login pays hash + verify while a
232 /// wrong-password login pays only verify — a one-shot timing tell. The
233 /// `OnceLock` still initialises inside a blocking context, just earlier, and
234 /// the task is detached so boot never waits on it.
235 pub fn prewarm_decoy() {
236 // No permit: one hash at boot, and taking one here could only delay the
237 // seed's own hash.
238 tokio::task::spawn_blocking(|| {
239 decoy_hash();
240 });
241 }
242}
243
244#[derive(Debug, Clone, sqlx::FromRow)]
245/// Fields are crate-visible: [`crate::db::user`] mints rows and the role
246/// cascade reads the id, exactly as the other split domains do.
247pub struct User {
248 pub(crate) id: UserId,
249 pub(crate) username: Username,
250 /// The control-plane person this school row belongs to — the join key to
251 /// the credential. No FK: the two halves are separate databases. `None`
252 /// on rows minted before their person was known (boot seed order, tests).
253 pub(crate) person: Option<PersonId>,
254 pub(crate) role: Role,
255 /// The school-issued student number, unique inside the school. `None` on
256 /// every account that holds none — every staff account, and every student
257 /// its school has not numbered yet. Only a student row may carry one:
258 /// the write paths refuse a non-student, and the role cascade clears it in
259 /// the same transaction that leaves the student role.
260 pub(crate) student_number: Option<StudentNumber>,
261 // Personal info, identical for every role. All optional: accounts are
262 // created from bare credentials and filled in later, and rows from before
263 // these fields existed simply read back as `None`.
264 pub(crate) name: Option<PersonName>,
265 pub(crate) surname: Option<PersonName>,
266 pub(crate) email: Option<Email>,
267 pub(crate) phone: Option<Phone>,
268 pub(crate) birth_date: Option<BirthDate>,
269 /// Self-declared gender, a postal address, and who to call when this
270 /// person is unreachable. Optional like everything above — the same
271 /// "filled in later, `None` = never chose" contract.
272 pub(crate) gender: Option<Gender>,
273 pub(crate) address: Option<Address>,
274 pub(crate) emergency_contact_name: Option<PersonName>,
275 pub(crate) emergency_contact_phone: Option<Phone>,
276 // Frontend UI preferences. Optional like the personal info: `None` means
277 // "never chose", which the frontend renders as the device preference.
278 pub(crate) theme: Option<Theme>,
279 pub(crate) language: Option<Language>,
280 pub(crate) palette_color: Option<PaletteColor>,
281 // The public profile: what other people see instead of the credentials.
282 // Optional like everything above — a profile is written after the account
283 // exists, so rows from before these fields existed read back as `None`,
284 // which is exactly a fresh account that never filled one in. The avatar is
285 // a blob on disk (`FILES_PATH`) like every other upload; only its name,
286 // type and size live on the row.
287 pub(crate) display_name: Option<DisplayName>,
288 pub(crate) bio: Option<Bio>,
289 /// The staff member's branch (subject area), free text validated against
290 /// the school's own `Settings::get_branches()` list at the web layer —
291 /// optional like every other profile field, and clearable.
292 pub(crate) branch: Option<String>,
293 pub(crate) avatar_file: Option<String>,
294 pub(crate) avatar_content_type: Option<FileContentType>,
295 pub(crate) avatar_size: Option<i64>,
296}
297
298impl User {
299 /// The in-memory principal an AI service acts as over the QUIC bridge.
300 ///
301 /// Never written to the database, and never read back from one: the id is
302 /// the nil UUID, which no minted id (always a v7) can ever equal. Every
303 /// other field is inert — `person` is `None`, and [`Role::Ai`] clears no
304 /// `at_least` bar and fails every exact `== Role::Student` /
305 /// `== Role::Parent` gate.
306 pub(crate) fn ai_principal() -> User {
307 User {
308 id: UserId(Uuid::nil()),
309 username: Username(AI_PRINCIPAL_KEY.to_string()),
310 person: None,
311 role: Role::Ai,
312 student_number: None,
313 name: None,
314 surname: None,
315 email: None,
316 phone: None,
317 birth_date: None,
318 gender: None,
319 address: None,
320 emergency_contact_name: None,
321 emergency_contact_phone: None,
322 theme: None,
323 language: None,
324 palette_color: None,
325 display_name: None,
326 bio: None,
327 branch: None,
328 avatar_file: None,
329 avatar_content_type: None,
330 avatar_size: None,
331 }
332 }
333
334 pub fn get_id(&self) -> &UserId {
335 &self.id
336 }
337
338 pub fn get_username(&self) -> &Username {
339 &self.username
340 }
341 pub fn get_person(&self) -> Option<&PersonId> {
342 self.person.as_ref()
343 }
344
345 pub fn get_role(&self) -> Role {
346 self.role
347 }
348
349 /// The school-issued student number, as stored. Never non-`None` on a
350 /// non-student row — the writes that could spell that are refused at the
351 /// web layer, and the role cascade clears it on the way out of the student
352 /// role.
353 pub fn get_student_number(&self) -> Option<&StudentNumber> {
354 self.student_number.as_ref()
355 }
356
357 pub fn get_name(&self) -> Option<&PersonName> {
358 self.name.as_ref()
359 }
360
361 pub fn get_surname(&self) -> Option<&PersonName> {
362 self.surname.as_ref()
363 }
364
365 pub fn get_email(&self) -> Option<&Email> {
366 self.email.as_ref()
367 }
368
369 pub fn get_phone(&self) -> Option<&Phone> {
370 self.phone.as_ref()
371 }
372
373 pub fn get_birth_date(&self) -> Option<&BirthDate> {
374 self.birth_date.as_ref()
375 }
376
377 pub fn get_gender(&self) -> Option<Gender> {
378 self.gender
379 }
380
381 pub fn get_address(&self) -> Option<&Address> {
382 self.address.as_ref()
383 }
384
385 pub fn get_emergency_contact_name(&self) -> Option<&PersonName> {
386 self.emergency_contact_name.as_ref()
387 }
388
389 pub fn get_emergency_contact_phone(&self) -> Option<&Phone> {
390 self.emergency_contact_phone.as_ref()
391 }
392
393 pub fn get_theme(&self) -> Option<Theme> {
394 self.theme
395 }
396
397 pub fn get_language(&self) -> Option<Language> {
398 self.language
399 }
400
401 pub fn get_palette_color(&self) -> Option<&PaletteColor> {
402 self.palette_color.as_ref()
403 }
404
405 pub fn get_display_name(&self) -> Option<&DisplayName> {
406 self.display_name.as_ref()
407 }
408
409 pub fn get_bio(&self) -> Option<&Bio> {
410 self.bio.as_ref()
411 }
412
413 /// The staff member's branch, as stored (free text; membership in the
414 /// school's list is the write path's check, not this read's).
415 pub fn get_branch(&self) -> Option<&str> {
416 self.branch.as_deref()
417 }
418
419 pub fn get_avatar_file(&self) -> Option<&str> {
420 self.avatar_file.as_deref()
421 }
422
423 pub fn get_avatar_content_type(&self) -> Option<&FileContentType> {
424 self.avatar_content_type.as_ref()
425 }
426
427 pub fn get_avatar_size(&self) -> Option<i64> {
428 self.avatar_size
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435
436 #[tokio::test]
437 async fn username_newtype_validates() {
438 assert_eq!(Username::try_new("ali").unwrap().as_str(), "ali");
439 assert!(Username::try_new("").is_err());
440 assert!(Username::try_new("ab").is_err());
441 assert!(Username::try_new("Ali").is_err());
442 assert!(Username::try_new("-ali").is_err());
443 assert!(Username::try_new("ali-").is_err());
444 }
445
446 #[tokio::test]
447 async fn username_is_stored_trimmed() {
448 // The unique index and the login lookup key on the *stored* string, so
449 // padding must not survive construction — otherwise "ali " and "ali"
450 // become two distinct, visually identical accounts.
451 assert_eq!(Username::try_new(" ali ").unwrap().as_str(), "ali");
452 }
453
454 #[tokio::test]
455 async fn student_number_newtype_validates_and_trims() {
456 // Trimmed like the username, because the unique index keys on the
457 // stored string: "1234 " and "1234" must be one number, not two.
458 assert_eq!(StudentNumber::try_new(" 1234 ").unwrap().as_str(), "1234");
459 assert!(StudentNumber::try_new("").is_err());
460 assert!(StudentNumber::try_new(" ").is_err());
461 assert!(StudentNumber::try_new(&"9".repeat(MAX_STUDENT_NUMBER_LEN)).is_ok());
462 assert!(StudentNumber::try_new(&"9".repeat(MAX_STUDENT_NUMBER_LEN + 1)).is_err());
463 }
464
465 #[tokio::test]
466 async fn short_password_rejected() {
467 assert!(Password::try_new("123").is_err());
468 assert!(Password::try_new("secret1").is_ok());
469 }
470
471 #[tokio::test]
472 async fn password_hash_roundtrips() {
473 let hash = Password::try_new("secret1").unwrap().hash().unwrap();
474 assert!(hash.verify(&Password::try_new("secret1").unwrap()));
475 assert!(!hash.verify(&Password::try_new("wrongpw").unwrap()));
476 }
477
478 #[tokio::test]
479 async fn decoy_hash_is_valid_and_nonmatching() {
480 // The decoy must be a real, parseable argon2 hash. If it ever became
481 // malformed, verify() would early-return without doing the hashing work
482 // and the login timing-equalization would silently disappear.
483 assert!(
484 decoy_hash().verify(&Password::try_new(DECOY_PASSWORD).unwrap()),
485 "decoy hash must verify its own password"
486 );
487 assert!(!decoy_hash().verify(&Password::try_new("some-other-pw").unwrap()));
488 }
489
490 #[tokio::test]
491 async fn user_id_key_roundtrips() {
492 let id = UserId::generate();
493 let key = id.key();
494 assert!(!key.is_empty());
495 assert_eq!(UserId::from_key(&key).key(), key);
496 }
497}