forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB0346717Ahmet Kaan Gümüş3 months ago230 commits

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