forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

mod.rs532 lines, 19.8 KiBHistoryRawDownload
1//! HTTP layer: axum routers, request/response DTOs (serde), and the auth
2//! extractors. DTOs are plain strings on the wire; handlers parse them into
3//! validated domain newtypes before doing anything. Role-gated endpoints take a
4//! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`.
5
6pub mod ai;
7pub mod appointments;
8pub mod attendance;
9pub mod auth;
10pub mod bank_questions;
11pub mod board_ws;
12pub mod boards;
13pub mod builder;
14pub mod chatbot;
15pub mod classes;
16pub mod course_notes;
17pub mod courses;
18pub mod etag;
19pub mod events;
20pub mod exam_ws;
21pub mod exams;
22pub mod homework;
23pub mod limits;
24pub mod marks;
25pub mod meals;
26pub mod messages;
27pub mod module_gate;
28pub mod modules;
29pub mod notes;
30pub mod payments;
31pub mod pomodoro;
32pub mod questions;
33pub mod room;
34pub mod sessions;
35pub mod settings;
36pub mod subjects;
37pub mod terms;
38pub mod users;
39pub mod work;
40
41pub mod tenant_state;
42
43mod dto;
44// `pub(crate)` for `AiPrincipal`: the AI bridge injects it as an extension on
45// the requests it dispatches into the router (see `ai::server`).
46pub(crate) mod extractor;
47mod image;
48mod page;
49
50pub use dto::{
51 CourseResponse, ExamResponse, HomeworkResponse, PersonRef, SessionResponse, SubjectResponse,
52 UserResponse, course_people, person_map,
53};
54pub use extractor::{
55 BUILDER_COOKIE_PREFIX, CurrentUser, RequireAdmin, RequireBuilder, RequireManager,
56 RequireStudent, RequireTeacher,
57};
58pub(crate) use image::{ImageUpload, read_image_upload, store_blob};
59pub use page::{Page, PageParams, Scheduled, WindowParams, paginate};
60
61use std::path::{Path as FsPath, PathBuf};
62
63use axum::extract::Multipart;
64use axum::extract::multipart::MultipartError;
65use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
66use axum::http::{HeaderValue, StatusCode};
67use axum::response::{IntoResponse, Response};
68use serde::{Deserialize, Deserializer};
69use utoipa::ToSchema;
70
71use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS};
72use crate::database::Database;
73use crate::domain::exam_question::{Choice, ChoiceInput};
74use crate::domain::note_file::FileContentType;
75use crate::domain::role::Role;
76use crate::domain::timestamp::Timestamp;
77use crate::domain::user::UserId;
78use crate::error::{AppError, ValidationError};
79
80/// Close the window between "this account is teacher+" and the write that
81/// records a teacher-only assignment (a class's homeroom teacher, a course's
82/// teacher list). Call it *after* the write, with the account it named.
83///
84/// WHY: the demotion sweeps in `set_role` run **once**, over the rows that
85/// exist at that moment. A `PATCH /users/{id}/role` interleaving between a
86/// handler's role check and its write sweeps nothing — and nothing ever
87/// re-sweeps — so the assignment stands forever, naming an account that may no
88/// longer be a teacher at all. Re-reading the live role after the write is what
89/// makes the pair ordered: either the sweep sees the row, or this read sees the
90/// demotion.
91///
92/// The undo is the very sweep `set_role` owed, and both halves of it are
93/// conditional writes scoped to *this* user (`teacher = $usr`,
94/// `$usr IN teachers`), so a legitimate concurrent assignment of somebody else
95/// is untouched — no lock, the repo's existing idiom. Both are run, not just
96/// the caller's own: a demoted account may hold neither, and the row this
97/// request did not write is exactly the one a lost sweep left behind.
98///
99/// A missing user counts as demoted. The ordinary path is one extra read and no
100/// write at all.
101pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<(), AppError> {
102 if crate::service::user::read(db, target)
103 .await?
104 .is_some_and(|user| user.get_role().at_least(Role::Teacher))
105 {
106 return Ok(());
107 }
108 crate::service::class_group::unassign_everywhere(db, target).await?;
109 crate::service::course::unassign_everywhere(db, target).await?;
110 Err(AppError::Conflict(
111 "that user was demoted below teacher while this request ran — the assignment was undone; re-read their role and retry",
112 ))
113}
114
115/// If both ends are present, `ends_at` must not precede `starts_at`. Shared by
116/// everything that carries a time range (events, course sessions). The PATCH
117/// paths re-check this at write time via
118/// [`crate::db::field_update::FieldUpdate::ordered`], which answers with the
119/// same error — this is the pre-flight, that is the race closer.
120pub(crate) fn check_time_range(
121 starts_at: Option<Timestamp>,
122 ends_at: Option<Timestamp>,
123) -> Result<(), AppError> {
124 if let (Some(starts), Some(ends)) = (starts_at, ends_at)
125 && ends < starts
126 {
127 return Err(crate::domain::timestamp::range_error());
128 }
129 Ok(())
130}
131
132/// A schedule instant a request explicitly sets must not lie in the past —
133/// nothing can be scheduled to start (or end) before now. Applies only to
134/// values the request itself carries: stored values merged into a PATCH are
135/// exempt, because a running exam's `starts_at` is legitimately past and a
136/// title-only edit must not trip over it. `SCHEDULE_PAST_GRACE_MS` keeps
137/// "starts now" from failing by the width of its own round trip.
138pub(crate) fn check_not_past(
139 field: &'static str,
140 value: Option<Timestamp>,
141) -> Result<(), AppError> {
142 if let Some(value) = value
143 && value.as_millis() < Timestamp::now().as_millis() - SCHEDULE_PAST_GRACE_MS
144 {
145 return Err(AppError::Validation(ValidationError::Invalid {
146 field,
147 reason: "must not be in the past",
148 }));
149 }
150 Ok(())
151}
152
153// ---- uploaded blobs ---------------------------------------------------------
154// Note files and question images share one story: bytes on disk under the
155// configured directory in a file named by a server-generated ULID (user input
156// never shapes a path), metadata in a row. Upload writes the blob before the
157// row; delete removes the row before the blob — so a stored row always points
158// at a real blob and a crash strands at worst an unreachable file.
159
160/// Where a stored row's blob lives: one file under the configured directory,
161/// named by the row's server-generated key.
162pub(crate) fn blob_path(files_path: &FsPath, key: &str) -> PathBuf {
163 files_path.join(key)
164}
165
166/// Make sure a school's blob directory exists before writing into it.
167///
168/// `FILES_PATH` is the deployment root and `main` creates only that; each
169/// school's subdirectory appears the first time that school stores a file, so
170/// nothing has to be provisioned when a school is created.
171pub(crate) async fn ensure_files_dir(files_path: &FsPath) -> Result<(), AppError> {
172 tokio::fs::create_dir_all(files_path).await.map_err(|err| {
173 AppError::Internal(format!(
174 "failed to create the files directory {}: {err}",
175 files_path.display()
176 ))
177 })
178}
179
180/// Best-effort blob removal after its row is gone. Failure only strands an
181/// unreachable file on disk, so it is logged rather than surfaced.
182pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) {
183 let path = blob_path(files_path, key);
184 if let Err(err) = tokio::fs::remove_file(&path).await
185 && err.kind() != std::io::ErrorKind::NotFound
186 {
187 tracing::warn!("failed to remove blob {}: {err}", path.display());
188 }
189}
190
191/// The declared content type of an inline-displayed image upload, held to the
192/// raster allowlist — SVG stays out (it can script) since these bytes are
193/// rendered inline to whole classes. Shared by exam question images and pool
194/// question photos.
195pub(crate) fn image_content_type(raw: &str) -> Result<FileContentType, AppError> {
196 let content_type = FileContentType::try_new(raw)?;
197 if !QUESTION_IMAGE_CONTENT_TYPES.contains(&content_type.as_str()) {
198 return Err(AppError::Validation(ValidationError::Invalid {
199 field: "content_type",
200 reason: "must be image/png, image/jpeg, image/webp, or image/gif",
201 }));
202 }
203 Ok(content_type)
204}
205
206/// A stored blob as an inline-displayable response: the declared (and
207/// allowlisted) content type, `nosniff`, and `no-store` — moderated/exam
208/// content has no business in shared caches, and a replaced image must not
209/// linger.
210pub(crate) async fn serve_inline_blob(
211 files_path: &FsPath,
212 file: &str,
213 content_type: &FileContentType,
214) -> Result<Response, AppError> {
215 let bytes = tokio::fs::read(blob_path(files_path, file))
216 .await
217 .map_err(|err| {
218 // The row exists but its blob doesn't — server-side damage (a lost
219 // volume path), not a client 404.
220 AppError::Internal(format!("missing blob for image {file}: {err}"))
221 })?;
222 let content_type = HeaderValue::from_str(content_type.as_str())
223 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
224 Ok((
225 [
226 (CONTENT_TYPE, content_type),
227 (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
228 (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
229 ],
230 bytes,
231 )
232 .into_response())
233}
234
235/// Multipart read failures: the route-level body cap maps to 413 like the
236/// school-limit check; anything else is a malformed body.
237pub(crate) fn multipart_error(err: MultipartError) -> AppError {
238 if err.status() == StatusCode::PAYLOAD_TOO_LARGE {
239 AppError::PayloadTooLarge("the upload exceeds the server's absolute body cap".to_string())
240 } else {
241 AppError::Validation(ValidationError::Invalid {
242 field: "file",
243 reason: "malformed multipart body",
244 })
245 }
246}
247
248/// Schema-only mirror of an upload form; the handlers read the multipart
249/// stream directly.
250#[derive(ToSchema)]
251#[allow(dead_code)]
252pub(crate) struct UploadFileForm {
253 /// The file part. Its `Content-Type` (and, where required, `filename`)
254 /// are stored alongside the bytes.
255 #[schema(value_type = String, format = Binary)]
256 file: String,
257}
258
259/// One uploaded file's raw parts, as the client sent them — the caller
260/// validates what it cares about (notes need a filename, images an
261/// allowlisted content type).
262pub(crate) struct UploadedFile {
263 pub name: Option<String>,
264 pub content_type: Option<String>,
265 pub data: Vec<u8>,
266}
267
268/// Pull the `file` field out of a multipart body, reading it chunkwise so an
269/// oversized upload dies at `limit`, not after buffering whole — the check is
270/// on real bytes received, so a lying `Content-Length` can't sneak past it.
271/// Empty files are refused; stray extra fields are ignored.
272pub(crate) async fn read_upload(
273 multipart: &mut Multipart,
274 limit: i64,
275) -> Result<UploadedFile, AppError> {
276 let mut field = loop {
277 match multipart.next_field().await.map_err(multipart_error)? {
278 Some(field) if field.name() == Some("file") => break field,
279 Some(_) => continue,
280 None => {
281 return Err(AppError::Validation(ValidationError::Invalid {
282 field: "file",
283 reason: "the multipart body must carry a 'file' field",
284 }));
285 }
286 }
287 };
288 let name = field.file_name().map(str::to_string);
289 let content_type = field.content_type().map(str::to_string);
290
291 let mut data = Vec::new();
292 while let Some(chunk) = field.chunk().await.map_err(multipart_error)? {
293 if data.len() + chunk.len() > limit as usize {
294 return Err(AppError::PayloadTooLarge(format!(
295 "the file exceeds the school's limit of {limit} bytes"
296 )));
297 }
298 data.extend_from_slice(&chunk);
299 }
300 if data.is_empty() {
301 return Err(AppError::Validation(ValidationError::Empty("file")));
302 }
303 Ok(UploadedFile {
304 name,
305 content_type,
306 data,
307 })
308}
309
310/// One option of a choice question as a client sends it — the wire form of
311/// [`crate::domain::exam_question::ChoiceInput`], shared by the exam-question
312/// and bank-template routes.
313///
314/// `id` is the option's key within the payload: send back the `id` the server
315/// returned to keep that option (and its picture) across an edit, or any fresh
316/// string to introduce a new one. The server mints the stored id either way, so
317/// nothing a client sends here ever reaches storage.
318#[derive(Debug, Clone, Deserialize, ToSchema)]
319pub(crate) struct ChoiceBody {
320 #[serde(default)]
321 pub id: Option<String>,
322 #[schema(example = "42", max_length = 500)]
323 pub text: String,
324}
325
326impl ChoiceBody {
327 pub(crate) fn into_input(self) -> ChoiceInput {
328 ChoiceInput {
329 id: self.id,
330 text: self.text,
331 }
332 }
333
334 /// The whole submitted list, or `None` when the field was omitted/cleared.
335 pub(crate) fn into_inputs(choices: Option<Vec<Self>>) -> Option<Vec<ChoiceInput>> {
336 choices.map(|list| list.into_iter().map(Self::into_input).collect())
337 }
338
339 /// The stored choices as a payload that re-submits them unchanged — how a
340 /// PATCH that omits `choices` keeps every option's identity.
341 pub(crate) fn from_stored(choices: Option<&[Choice]>) -> Option<Vec<ChoiceInput>> {
342 choices.map(|list| {
343 list.iter()
344 .map(|choice| ChoiceInput {
345 id: Some(choice.get_id().as_str().to_string()),
346 text: choice.get_text().as_str().to_string(),
347 })
348 .collect()
349 })
350 }
351}
352
353/// Distinguishes an *absent* PATCH field from an explicit `null`: absent never
354/// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the
355/// stored value); `null` or a value lands here as `Some(inner)` (clear or set).
356pub(crate) fn set_or_clear<'de, D, T>(de: D) -> Result<Option<Option<T>>, D::Error>
357where
358 D: Deserializer<'de>,
359 T: Deserialize<'de>,
360{
361 Option::<T>::deserialize(de).map(Some)
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367
368 /// The demotion-vs-assign race, driven in the order the race produces it:
369 /// both assignments are already written (the handler's role check has
370 /// passed), *then* the account drops below `teacher` with no sweep — which
371 /// is exactly what `set_role`'s one-shot sweep leaves behind when it runs
372 /// before the write. The post-write re-read must undo both columns and
373 /// refuse; with the account still staff it must undo nothing at all.
374 ///
375 /// Asserted on stored state, never on a return value: the in-memory engine
376 /// forges those (see [`crate::db::cap`]).
377 #[tokio::test]
378 async fn undo_if_demoted_repairs_both_assignments_or_neither() {
379 use crate::domain::class_group::ClassName;
380 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
381 use crate::domain::user::{Password, Username};
382
383 let db = crate::database::init_mem().await.unwrap();
384 let office = UserId::from_key("office");
385 let teacher = crate::service::user::create(
386 &db,
387 Username::try_new("ada").unwrap(),
388 Password::try_new("secret1")
389 .unwrap()
390 .hash_async()
391 .await
392 .unwrap(),
393 )
394 .await
395 .unwrap();
396 crate::service::user::set_role(&db, teacher.get_id(), Role::Teacher)
397 .await
398 .unwrap();
399 let assigned = async |db: &Database| {
400 let class = crate::service::class_group::create(
401 db,
402 &office,
403 ClassName::try_new("9-A").unwrap(),
404 None,
405 None,
406 Some(teacher.get_id().clone()),
407 )
408 .await
409 .unwrap();
410 let course = crate::service::course::assign_teacher(
411 db,
412 &crate::service::course::create(
413 db,
414 &office,
415 CourseTitle::try_new("algebra").unwrap(),
416 CourseDescription::try_new("").unwrap(),
417 CourseKind::course(),
418 None,
419 None,
420 )
421 .await
422 .unwrap(),
423 teacher.get_id(),
424 )
425 .await
426 .unwrap();
427 (class, course)
428 };
429 /// `(the class's stored teacher, the course's stored teacher list)`.
430 async fn stored(
431 class: &crate::domain::class_group::ClassGroupId,
432 course: &crate::domain::course::CourseId,
433 db: &Database,
434 ) -> (Option<UserId>, Vec<UserId>) {
435 (
436 crate::service::class_group::read(db, class)
437 .await
438 .unwrap()
439 .unwrap()
440 .get_teacher()
441 .cloned(),
442 crate::service::course::read(db, course)
443 .await
444 .unwrap()
445 .unwrap()
446 .get_teachers()
447 .to_vec(),
448 )
449 }
450
451 // Still staff: one read, and not a single write.
452 let (class, course) = assigned(&db).await;
453 undo_if_demoted(teacher.get_id(), &db)
454 .await
455 .expect("an account that is still teacher+ keeps what it was given");
456 assert_eq!(
457 stored(class.get_id(), course.get_id(), &db).await,
458 (
459 Some(teacher.get_id().clone()),
460 vec![teacher.get_id().clone()]
461 ),
462 "nothing may be undone while the bar still holds"
463 );
464
465 // Demoted with no sweep — the state a lost race leaves.
466 db.query("UPDATE $usr SET role = 'student'")
467 .bind(("usr", teacher.get_id().record()))
468 .await
469 .unwrap()
470 .check()
471 .unwrap();
472 let refused = undo_if_demoted(teacher.get_id(), &db).await;
473 assert!(
474 matches!(refused, Err(AppError::Conflict(message)) if message.contains("demoted")),
475 "a demotion mid-request must be a 409 naming it: {refused:?}"
476 );
477 assert_eq!(
478 stored(class.get_id(), course.get_id(), &db).await,
479 (None, Vec::new()),
480 "…with both assignments taken back, not just the caller's own"
481 );
482
483 // A user that is gone counts as demoted, and the repair is idempotent.
484 assert!(
485 undo_if_demoted(&UserId::from_key("ghost"), &db)
486 .await
487 .is_err()
488 );
489 assert!(undo_if_demoted(teacher.get_id(), &db).await.is_err());
490 assert_eq!(
491 stored(class.get_id(), course.get_id(), &db).await,
492 (None, Vec::new())
493 );
494 }
495
496 #[tokio::test]
497 async fn check_time_range_orders_the_ends() {
498 let at = |ms| Some(Timestamp::from_millis(ms));
499 assert!(check_time_range(at(1), at(2)).is_ok());
500 assert!(check_time_range(at(1), at(1)).is_ok());
501 assert!(check_time_range(at(2), at(1)).is_err());
502 // A missing end never fails the range check.
503 assert!(check_time_range(None, at(1)).is_ok());
504 assert!(check_time_range(at(1), None).is_ok());
505 assert!(check_time_range(None, None).is_ok());
506 }
507
508 #[tokio::test]
509 async fn check_not_past_rejects_backdating_but_keeps_the_grace() {
510 let now = Timestamp::now().as_millis();
511 // Absent and future values pass.
512 assert!(check_not_past("starts_at", None).is_ok());
513 assert!(check_not_past("starts_at", Some(Timestamp::from_millis(now + 60_000))).is_ok());
514 // Inside the grace passes — "starts now" survives its round trip.
515 assert!(
516 check_not_past(
517 "starts_at",
518 Some(Timestamp::from_millis(now - SCHEDULE_PAST_GRACE_MS / 2)),
519 )
520 .is_ok()
521 );
522 // Beyond the grace is a validation error naming the field.
523 let past = Timestamp::from_millis(now - SCHEDULE_PAST_GRACE_MS - 60_000);
524 assert!(matches!(
525 check_not_past("ends_at", Some(past)),
526 Err(AppError::Validation(ValidationError::Invalid {
527 field: "ends_at",
528 ..
529 }))
530 ));
531 }
532}