From dbeb12287aee26a27d5f0b4bfd55fb1f91fd4898 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 19 Jul 2026 16:49:07 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(exams):=20images=20on=20questi?= =?UTF-8?q?ons=20and=20choice=20options?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Teachers pin one illustration to any question (the map above the prompt) and one picture per option on choice questions — the options themselves can be images. Multipart upload per slot, replace by re-upload, frozen with the question once attempts exist. - rows in question_image (deterministic id per slot, UPSERT = replace); blobs beside note files under FILES_PATH, capped by max_file_bytes - raster allowlist png/jpeg/webp/gif — SVG can script and these bytes render inline to students; served with nosniff + private, no-store - students fetch bytes behind the sitting wall (enrollment + started attempt, no early peek); course managers anytime - replacing a question's choices drops its option pictures (the illustration stays) — old pictures belong to the old options - blob cleanup wired into image replace/delete and question, exam, and course deletes (exam cascade result slot shifted 5 -> 6) --- README.md | 56 +++- src/constant.rs | 6 + src/database.rs | 11 + src/domain/course.rs | 11 +- src/domain/exam.rs | 12 +- src/domain/exam_question.rs | 16 +- src/domain/mod.rs | 1 + src/domain/question_image.rs | 291 ++++++++++++++++++ src/domain/user.rs | 6 +- src/lib.rs | 6 +- src/web/courses.rs | 14 +- src/web/exams.rs | 558 +++++++++++++++++++++++++++++++++-- src/web/mod.rs | 105 +++++++ src/web/notes.rs | 95 +----- tests/integration.rs | 364 +++++++++++++++++++++++ 15 files changed, 1413 insertions(+), 139 deletions(-) create mode 100644 src/domain/question_image.rs diff --git a/README.md b/README.md index 52f4c4f..177acfd 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,11 @@ fixed window), **async** (start anytime inside the window, with a personal time budget), or **open** (sit anytime, optionally timed per attempt); students *sit* them via attempts — retakes metered by a per-exam limit (`0` = unlimited), leaving the exam room governed by a teacher-controlled -rejoin door — and teachers watch attendance, per-student remaining time, +rejoin door. Questions can carry **images**: any question may hold one +illustration (a map above the prompt), and each option of a choice question +may be a picture of its own (pick the right city off the map) — raster +uploads capped by the same `max_file_bytes` policy as note files. Teachers +watch attendance, per-student remaining time, sittings, walk-outs, no-shows (`absent` once the window closes), submissions, and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also carry **lesson sessions** with teacher-taken roll call (students never self-mark a lesson), @@ -197,7 +201,7 @@ effect on the user's very next call (no re-login). | View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) | | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server | | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off | -| Author an exam's questions (add/edit/delete) | teacher | Course-management rights; frozen once anyone has an attempt | +| Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt | | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key | | Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights | | Create courses | teacher | The creator manages the course | @@ -340,7 +344,7 @@ their existing shapes: the student exam-room reads | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) · paged | | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) | | PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) | -| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) | +| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question images (course manager) | | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only) | | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged | | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) | @@ -353,7 +357,13 @@ their existing shapes: the student exam-room reads | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | -| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires enrollment + an attempt) | +| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) | +| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part — raster images only (`png`/`jpeg`/`webp`/`gif`), ≤ `max_file_bytes` (course manager; frozen once attempted) | +| GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) | +| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove the illustration (course manager; frozen once attempted) | +| POST | `/exams/{id}/questions/{qid}/choices/{index}/image` | teacher | Attach/replace option `index`'s picture (`choice` questions; same form and limits as above) | +| GET | `/exams/{id}/questions/{qid}/choices/{index}/image` | student | The option picture's bytes (same access as the illustration) | +| DELETE | `/exams/{id}/questions/{qid}/choices/{index}/image` | teacher | Remove one option picture (course manager; frozen once attempted) | | POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) | | GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | @@ -487,10 +497,10 @@ editable `settings` singleton (`GET /settings` for any signed-in user, averaging stay `0`–`100` forever — bands only add `grade`, `average_grade`, and `overall_grade` labels to the mark report, so a school can switch display scales without touching a single stored mark. -- **`max_file_bytes`** — the per-file size cap for note uploads, in bytes: - `1024` (1 KiB) to `26214400` (25 MiB; a server hard cap — uploads buffer in - memory), default `5242880` (5 MiB). Checked at upload time only: - lowering it never touches already-stored files. +- **`max_file_bytes`** — the per-file size cap for uploads (note files and + exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB; + a server hard cap — uploads buffer in memory), default `5242880` (5 MiB). + Checked at upload time only: lowering it never touches already-stored files. A `PATCH` replaces only the fields it carries, each wholesale, and validation is all-or-nothing. Concurrent edits are safe: each save applies only if the @@ -590,9 +600,10 @@ const es = new EventSource(`${BASE}/exams/${id}/live/stream`, { withCredentials: es.addEventListener("snapshot", (e) => render(JSON.parse(e.data))); ``` -Deleting an exam (or its course) cascades attempts, questions, and answers -along with results; unenrolling mid-exam hides the student from the monitor -roster but keeps the attempt and mark rows, mirroring the marks report. +Deleting an exam (or its course) cascades attempts, questions, answers, and +question images (blobs included) along with results; unenrolling mid-exam +hides the student from the monitor roster but keeps the attempt and mark +rows, mirroring the marks report. > **Upgrading a pre-course database**: `exam` rows created before courses > existed lack the now-required `course` field and will fail to deserialize. @@ -635,7 +646,28 @@ switching a question to `text` needs explicit `"choices": null, "correct": null`, switching to `choice` must bring both along. Presentation order is creation order. The whole list **freezes once anyone has started an attempt** (`409` on create/edit/delete) — editing questions under a sitting student -would fork what "the exam" means. Deleting a question cascades its answers. +would fork what "the exam" means. Deleting a question cascades its answers +and images. + +**Question images**: any question may carry one **illustration** (`POST +/exams/{id}/questions/{qid}/image` — the map the prompt asks about, on +`choice` and `text` questions alike), and each option of a `choice` question +may carry a **picture** of its own (`POST .../choices/{index}/image` — so +the options themselves can be images: four map crops, pick the right one). +Uploads are `multipart/form-data` with a single `file` part, capped by the +school's `max_file_bytes`; the declared content type must be `image/png`, +`image/jpeg`, `image/webp`, or `image/gif` (rasters only — SVG can script, +and these bytes render inline for the whole class). One image per slot: +re-uploading replaces, `DELETE` on the same paths removes, and replacing a +question's `choices` list drops all its option pictures (the illustration +stays — re-upload against the new list). Image writes follow question +authoring exactly: course-management rights, frozen once attempts exist. +Both question views (`GET /exams/{id}/questions` and the sitting view) +embed the metadata as `image: {content_type, size} | null` and +`choice_images: [...|null]` aligned with `choices`; the bytes come from the +`GET` endpoints above — course managers anytime, students through the same +enrollment + started-attempt wall as the sitting view (no early peek at the +pictures either), served with `Cache-Control: private, no-store`. **Answering** (student, attempt `in_progress`, deadline judged by the server clock on every save): diff --git a/src/constant.rs b/src/constant.rs index 80b211f..423ecb7 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -55,6 +55,12 @@ pub const MAX_MAX_FILE_BYTES: i64 = 25 * 1024 * 1024; /// the file bytes themselves. pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024; +/// The content types a question image may declare — raster formats only. SVG +/// is deliberately out: it can carry scripts, and these bytes are served for +/// inline display to everyone sitting the exam. +pub const QUESTION_IMAGE_CONTENT_TYPES: [&str; 4] = + ["image/png", "image/jpeg", "image/webp", "image/gif"]; + pub const MAX_EVENT_TITLE_LEN: usize = 200; pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; diff --git a/src/database.rs b/src/database.rs index 07925a5..70eae92 100644 --- a/src/database.rs +++ b/src/database.rs @@ -19,6 +19,7 @@ pub const EXAM_TABLE: &str = "exam"; pub const EXAM_RESULT_TABLE: &str = "exam_result"; pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt"; pub const EXAM_QUESTION_TABLE: &str = "exam_question"; +pub const QUESTION_IMAGE_TABLE: &str = "question_image"; pub const EXAM_ANSWER_TABLE: &str = "exam_answer"; pub const COURSE_TABLE: &str = "course"; pub const ENROLLMENT_TABLE: &str = "enrollment"; @@ -184,6 +185,16 @@ const MIGRATION: &str = " DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; + DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record; + DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record; + DEFINE FIELD IF NOT EXISTS slot ON question_image TYPE option; + DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string; + DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string; + DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int; + DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam; + DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question; + DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record; DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record; diff --git a/src/domain/course.rs b/src/domain/course.rs index 9c488f6..079a085 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -213,16 +213,19 @@ impl Course { updated.ok_or(AppError::NotFound) } - /// Delete the course and cascade-remove everything inside it: results and - /// attempts of its exams, its enrollments, its sessions with their roll - /// call, its subjects, and the exams themselves. The children go in one - /// transaction so a crash can't leave an exam pointing at a deleted course. + /// Delete the course and cascade-remove everything inside it: results, + /// attempts, and question images of its exams, its enrollments, its + /// sessions with their roll call, its subjects, and the exams themselves. + /// The children go in one transaction so a crash can't leave an exam + /// pointing at a deleted course. The image *blobs* are the web layer's to + /// remove — it collects their names before calling this. pub async fn delete(self, db: &Database) -> Result { db.query( "BEGIN TRANSACTION; DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE session_attendance WHERE course = $course; DELETE course_session WHERE course = $course; diff --git a/src/domain/exam.rs b/src/domain/exam.rs index e176959..20c75dd 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -428,9 +428,10 @@ impl Exam { updated.ok_or(AppError::NotFound) } - /// Delete the exam and cascade-remove its result, attempt, question, and - /// answer rows — all in one transaction, so a failure can't leave an - /// emptied-out exam shell behind. + /// Delete the exam and cascade-remove its result, attempt, question, + /// answer, and question-image rows — all in one transaction, so a failure + /// can't leave an emptied-out exam shell behind. The image *blobs* are the + /// web layer's to remove — it collects their names before calling this. pub async fn delete(self, db: &Database) -> Result { let mut result = db .query( @@ -438,6 +439,7 @@ impl Exam { DELETE exam_result WHERE exam = $ex; DELETE exam_attempt WHERE exam = $ex; DELETE exam_answer WHERE exam = $ex; + DELETE question_image WHERE exam = $ex; DELETE exam_question WHERE exam = $ex; DELETE $ex RETURN BEFORE; COMMIT TRANSACTION;", @@ -446,8 +448,8 @@ impl Exam { .await? .check()?; // Statement slots count BEGIN and the child deletes: the exam's own - // DELETE is slot 5. - let deleted: Option = result.take::>(5)?.into_iter().next(); + // DELETE is slot 6. + let deleted: Option = result.take::>(6)?.into_iter().next(); deleted.ok_or(AppError::NotFound) } } diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 75fabd0..2734660 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -293,13 +293,17 @@ impl ExamQuestion { updated.ok_or(AppError::NotFound) } - /// Delete the question and cascade-remove its answers, so no answer row - /// can point at a missing question. + /// Delete the question and cascade-remove its answers and image rows, so + /// neither can point at a missing question. The image *blobs* are the web + /// layer's to remove — it collects their names before calling this. pub async fn delete(self, db: &Database) -> Result { - db.query("DELETE exam_answer WHERE question = $q") - .bind(("q", self.id.record())) - .await? - .check()?; + db.query( + "DELETE exam_answer WHERE question = $q; + DELETE question_image WHERE question = $q;", + ) + .bind(("q", self.id.record())) + .await? + .check()?; let deleted: Option = db.delete(self.id.record()).await?; deleted.ok_or(AppError::NotFound) } diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 4d0b021..5102962 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -16,6 +16,7 @@ pub mod note; pub mod note_file; pub mod preferences; pub mod profile; +pub mod question_image; pub mod registration; pub mod role; pub mod session; diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs new file mode 100644 index 0000000..921697b --- /dev/null +++ b/src/domain/question_image.rs @@ -0,0 +1,291 @@ +//! An image pinned to an exam question — the question's own illustration +//! (`slot = NONE`, any kind: a map above the prompt) or one choice's picture +//! (`slot = i`, choice questions only). The row carries metadata; the bytes +//! live on disk under [`crate::config::Config::files_path`] in a file named by +//! `file` — a fresh server-generated ULID per upload, so no user input ever +//! shapes a disk path and a replace never overwrites bytes in place. The row +//! id is *deterministic* per (question, slot), so "one image per slot" holds +//! by construction and a replace is a plain UPSERT. The web layer owns the +//! blob I/O and its ordering (new blob before row, row before old blob); +//! this module owns the rows. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::database::{Database, QUESTION_IMAGE_TABLE}; +use crate::domain::course::CourseId; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::ExamQuestionId; +use crate::domain::note_file::FileContentType; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct QuestionImageId(RecordId); + +impl QuestionImageId { + /// The one id a (question, slot) pair can have: `{qid}_q` for the + /// question's own image, `{qid}_{i}` for choice `i` — uniqueness per slot + /// needs no index this way. + pub fn for_slot(question: &ExamQuestionId, slot: Option) -> Self { + let suffix = match slot { + None => "q".to_string(), + Some(index) => index.to_string(), + }; + Self(RecordId::new( + QUESTION_IMAGE_TABLE, + format!("{}_{suffix}", question.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct QuestionImage { + id: QuestionImageId, + exam: ExamId, + question: ExamQuestionId, + /// `NONE` = the question's illustration; `i` = the picture of choice `i`. + slot: Option, + /// The blob's on-disk name — a fresh ULID every upload. + file: String, + content_type: FileContentType, + size: i64, +} + +impl QuestionImage { + /// Assemble a row (fresh blob name generated here) without persisting it. + /// The caller writes the blob under [`Self::get_file`] first, then calls + /// [`Self::upsert`] — so a stored row always points at a real blob. + pub fn new( + exam: &ExamId, + question: &ExamQuestionId, + slot: Option, + content_type: FileContentType, + size: i64, + ) -> Self { + Self { + id: QuestionImageId::for_slot(question, slot), + exam: exam.clone(), + question: question.clone(), + slot, + file: Ulid::new().to_string(), + content_type, + size, + } + } + + pub fn get_question(&self) -> &ExamQuestionId { + &self.question + } + + pub fn get_slot(&self) -> Option { + self.slot + } + + pub fn get_file(&self) -> &str { + &self.file + } + + pub fn get_content_type(&self) -> &FileContentType { + &self.content_type + } + + pub fn get_size(&self) -> i64 { + self.size + } + + /// Create or replace the slot's image row — the deterministic id makes + /// this the whole "one image per slot" story. + pub async fn upsert(self, db: &Database) -> Result { + let written: Option = db.upsert(self.id.record()).content(self).await?; + written.ok_or_else(|| AppError::Internal("failed to store question image".into())) + } + + pub async fn read_slot( + question: &ExamQuestionId, + slot: Option, + db: &Database, + ) -> Result, AppError> { + Ok(db + .select(QuestionImageId::for_slot(question, slot).record()) + .await?) + } + + /// Every image of the exam's questions — one query for the list views. + pub async fn list_for_exam( + exam: &ExamId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM question_image WHERE exam = $ex") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn list_for_question( + question: &ExamQuestionId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM question_image WHERE question = $q") + .bind(("q", question.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Drop every *choice* image of the question (the question's own + /// illustration stays), returning the removed rows so the caller can take + /// their blobs off disk. Runs when a PATCH replaces the choice list — the + /// old pictures belong to the old options. + pub async fn delete_choices_for( + question: &ExamQuestionId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("DELETE question_image WHERE question = $q AND slot != NONE RETURN BEFORE") + .bind(("q", question.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// The blob names behind every image of every exam of `course` — collected + /// *before* the course-delete cascade wipes the rows. + pub async fn file_keys_for_course( + course: &CourseId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE file FROM question_image \ + WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)", + ) + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn delete(self, db: &Database) -> Result { + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png() -> FileContentType { + FileContentType::try_new("image/png").unwrap() + } + + #[tokio::test] + async fn upsert_replaces_per_slot() { + let db = crate::database::init_mem().await.unwrap(); + let exam = ExamId::generate(); + let question = ExamQuestionId::generate(); + + let first = QuestionImage::new(&exam, &question, None, png(), 3) + .upsert(&db) + .await + .unwrap(); + let second = QuestionImage::new(&exam, &question, None, png(), 5) + .upsert(&db) + .await + .unwrap(); + // Same slot, same row — the replace swapped the blob pointer. + assert_ne!(first.get_file(), second.get_file()); + let rows = QuestionImage::list_for_question(&question, &db) + .await + .unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get_size(), 5); + + // A choice slot is its own row. + QuestionImage::new(&exam, &question, Some(0), png(), 7) + .upsert(&db) + .await + .unwrap(); + assert_eq!( + QuestionImage::list_for_question(&question, &db) + .await + .unwrap() + .len(), + 2 + ); + let choice = QuestionImage::read_slot(&question, Some(0), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(choice.get_slot(), Some(0)); + assert!( + QuestionImage::read_slot(&question, Some(1), &db) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn choice_wipe_spares_the_question_image() { + let db = crate::database::init_mem().await.unwrap(); + let exam = ExamId::generate(); + let question = ExamQuestionId::generate(); + for slot in [None, Some(0), Some(1)] { + QuestionImage::new(&exam, &question, slot, png(), 1) + .upsert(&db) + .await + .unwrap(); + } + + let dropped = QuestionImage::delete_choices_for(&question, &db) + .await + .unwrap(); + assert_eq!(dropped.len(), 2); + assert!(dropped.iter().all(|image| image.get_slot().is_some())); + + let left = QuestionImage::list_for_question(&question, &db) + .await + .unwrap(); + assert_eq!(left.len(), 1); + assert_eq!(left[0].get_slot(), None); + } + + #[tokio::test] + async fn exam_listing_scopes_by_exam() { + let db = crate::database::init_mem().await.unwrap(); + let exam_a = ExamId::generate(); + let exam_b = ExamId::generate(); + QuestionImage::new(&exam_a, &ExamQuestionId::generate(), None, png(), 1) + .upsert(&db) + .await + .unwrap(); + assert_eq!( + QuestionImage::list_for_exam(&exam_a, &db) + .await + .unwrap() + .len(), + 1 + ); + assert!( + QuestionImage::list_for_exam(&exam_b, &db) + .await + .unwrap() + .is_empty() + ); + } +} diff --git a/src/domain/user.rs b/src/domain/user.rs index a02ed98..7321201 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -470,7 +470,11 @@ mod tests { Role::Teacher, "the role change must survive the racing profile write" ); - assert_eq!(after.get_name(), Some(&name), "the profile edit itself lands"); + assert_eq!( + after.get_name(), + Some(&name), + "the profile edit itself lands" + ); } #[tokio::test] diff --git a/src/lib.rs b/src/lib.rs index 162ba97..464ce7a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in two behaviorally identical kinds — `course` (a regular class) and `study` (a supervised study session — etüt) — and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in two behaviorally identical kinds — `course` (a regular class) and `study` (a supervised study session — etüt) — and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", ), modifiers(&SecurityAddon), tags( @@ -45,9 +45,9 @@ use crate::state::AppState; (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), - (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), + (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"), - (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file note-upload size limit (`max_file_bytes`). Read: any authenticated user; edit: manager+"), + (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, manager+); edit follows course management rights"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), ), diff --git a/src/web/courses.rs b/src/web/courses.rs index b297ba7..55bfb1d 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -16,6 +16,7 @@ use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; +use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; use crate::domain::settings::Settings; use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; @@ -29,7 +30,7 @@ use super::terms::resolve_term; use super::{ CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate, person_map, - set_or_clear, + remove_blob, set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -362,8 +363,9 @@ async fn update_course( } /// Delete a course. Requires teacher+; the creator may delete their own course -/// and managers/admins may delete anyone's. Cascades the course's exams, their -/// results, and all enrollments. +/// and managers/admins may delete anyone's. Cascades the course's exams (with +/// their results, questions, answers, and question images), its sessions and +/// roll call, its subjects, and all enrollments. #[utoipa::path( delete, path = "/{id}", @@ -390,7 +392,13 @@ async fn delete_course( "only the course creator or a manager/admin can delete this course", )); } + // Rows go first (the delete cascades them), blobs after — a crash in + // between strands at worst an unreachable blob. + let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?; course.delete(&st.db).await?; + for file in &image_files { + remove_blob(&st.files_path, file).await; + } Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/exams.rs b/src/web/exams.rs index b28de58..0fc1186 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -2,9 +2,11 @@ use std::collections::HashMap; use std::time::Duration; use axum::Json; -use axum::extract::{Path, Query, State}; -use axum::http::StatusCode; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; +use axum::http::{HeaderValue, StatusCode}; use axum::response::sse::{Event, KeepAlive, Sse}; +use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; use tokio_stream::wrappers::IntervalStream; use tokio_stream::{Stream, StreamExt}; @@ -12,7 +14,10 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::EXAM_LIVE_STREAM_INTERVAL_SECS; +use crate::constant::{ + EXAM_LIVE_STREAM_INTERVAL_SECS, MAX_MAX_FILE_BYTES, QUESTION_IMAGE_CONTENT_TYPES, + UPLOAD_BODY_OVERHEAD_BYTES, +}; use crate::database::Database; use crate::domain::course::Course; use crate::domain::enrollment::Enrollment; @@ -26,6 +31,8 @@ use crate::domain::exam_question::{ ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; use crate::domain::exam_result::{ExamResult, Mark}; +use crate::domain::note_file::FileContentType; +use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; @@ -36,8 +43,8 @@ use crate::state::AppState; use super::courses::{can_manage_course, can_view_course, visible_courses}; use super::subjects::subject_in_course; use super::{ - CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, check_not_past, - paginate, person_map, set_or_clear, + CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, UploadFileForm, + blob_path, check_not_past, paginate, person_map, read_upload, remove_blob, set_or_clear, }; /// Serializes the exam subsystem's cross-record check-then-writes, which @@ -77,6 +84,24 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(attempt_questions)) .routes(routes!(save_answer)) .routes(routes!(attempt_answers)) + // The image routes get their own HTTP body cap, like the note-file + // ones: the server-wide hard ceiling plus multipart framing headroom. + .merge( + OpenApiRouter::new() + .routes(routes!( + upload_question_image, + get_question_image, + delete_question_image + )) + .routes(routes!( + upload_choice_image, + get_choice_image, + delete_choice_image + )) + .layer(DefaultBodyLimit::max( + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, + )), + ) } #[derive(Deserialize, ToSchema)] @@ -368,8 +393,8 @@ async fn update_exam( } /// Delete an exam. Requires teacher+ and management rights over the exam's -/// course (its creator, or manager/admin). Cascades the exam's result and -/// attempt rows. +/// course (its creator, or manager/admin). Cascades the exam's results, +/// attempts, questions, answers, and question images (blobs included). #[utoipa::path( delete, path = "/{id}", @@ -397,7 +422,13 @@ async fn delete_exam( "only the course creator or a manager/admin can delete this exam", )); } + // Rows go first (the delete cascades them), blobs after — a crash in + // between strands at worst an unreachable blob. + let images = QuestionImage::list_for_exam(exam.get_id(), &st.db).await?; exam.delete(&st.db).await?; + for image in &images { + remove_blob(&st.files_path, image.get_file()).await; + } Ok(StatusCode::NO_CONTENT) } @@ -1260,7 +1291,8 @@ struct UpdateQuestion { /// when moving to `text`. kind: Option, /// Omit to keep the stored options; send `null` to drop them (text - /// questions only). + /// questions only). Replacing or clearing the list also drops every + /// option picture — the old images belong to the old options. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option>)] choices: Option>>, @@ -1270,6 +1302,64 @@ struct UpdateQuestion { correct: Option>, } +/// A stored question image's metadata; the bytes come from the image +/// endpoints (`GET .../image`, `GET .../choices/{index}/image`). +#[derive(Serialize, ToSchema)] +struct ImageMetaResponse { + /// MIME type as declared on upload (always one of the raster allowlist). + #[schema(example = "image/png")] + content_type: String, + /// Image size in bytes. + #[schema(example = 24_576)] + size: i64, +} + +impl ImageMetaResponse { + fn new(image: &QuestionImage) -> Self { + Self { + content_type: image.get_content_type().as_str().to_string(), + size: image.get_size(), + } + } +} + +/// The question's slot out of its image rows. +fn image_meta(images: &[QuestionImage], slot: Option) -> Option { + images + .iter() + .find(|image| image.get_slot() == slot) + .map(ImageMetaResponse::new) +} + +/// The per-choice metas, aligned index-for-index with `choices` (`None` +/// entries = that option has no picture); `None` whole for text questions. +fn choice_image_metas( + question: &ExamQuestion, + images: &[QuestionImage], +) -> Option>> { + question.get_choices().map(|choices| { + (0..choices.len() as i64) + .map(|index| image_meta(images, Some(index))) + .collect() + }) +} + +/// `exam`'s image rows bucketed by question key — one query feeding a whole +/// question list. +async fn images_by_question( + exam: &ExamId, + db: &Database, +) -> Result>, AppError> { + let mut buckets: HashMap> = HashMap::new(); + for image in QuestionImage::list_for_exam(exam, db).await? { + buckets + .entry(image.get_question().key().to_string()) + .or_default() + .push(image); + } + Ok(buckets) +} + /// A question as its author sees it — including the `correct` index. Never /// serialized to students; they get [`AttemptQuestionResponse`]. #[derive(Serialize, ToSchema)] @@ -1286,10 +1376,14 @@ struct QuestionResponse { choices: Option>, /// Zero-based index of the right option (`choice` questions only). correct: Option, + /// The question's illustration, if one was uploaded (any kind). + image: Option, + /// Per-option pictures, aligned with `choices` (`choice` questions only). + choice_images: Option>>, } impl QuestionResponse { - fn new(question: &ExamQuestion) -> Self { + fn new(question: &ExamQuestion, images: &[QuestionImage]) -> Self { Self { id: question.get_id().key().to_string(), exam: question.get_exam().key().to_string(), @@ -1301,6 +1395,8 @@ impl QuestionResponse { .get_choices() .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), correct: question.get_correct(), + image: image_meta(images, None), + choice_images: choice_image_metas(question, images), } } } @@ -1379,7 +1475,11 @@ async fn create_question( let points = QuestionPoints::try_new(req.points)?; let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?; let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?; - Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question)))) + // A question is born imageless — uploads come after, against its id. + Ok(( + StatusCode::CREATED, + Json(QuestionResponse::new(&question, &[])), + )) } /// The exam's question list, `correct` indexes included — the answer key, @@ -1418,10 +1518,18 @@ async fn list_questions( )); } let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?; + let images = images_by_question(exam.get_id(), &st.db).await?; let total = questions.len() as i64; let items = paginate(&questions, limit, offset) .iter() - .map(QuestionResponse::new) + .map(|question| { + QuestionResponse::new( + question, + images + .get(question.get_id().key()) + .map_or(&[][..], Vec::as_slice), + ) + }) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -1489,6 +1597,7 @@ async fn update_question( Some(ref kind) => QuestionKind::try_new(kind)?, None => question.get_kind().clone(), }; + let choices_replaced = req.choices.is_some(); let choices = match req.choices { Some(update) => update, None => question @@ -1502,7 +1611,16 @@ async fn update_question( let spec = QuestionSpec::try_new(kind, choices, correct)?; let updated = question.update(subject, text, points, spec, &st.db).await?; - Ok(Json(QuestionResponse::new(&updated))) + // A replaced (or cleared) choice list orphans the old options' pictures — + // drop them all; the question's own illustration stays. Uploads re-attach + // against the new list. + if choices_replaced { + for image in QuestionImage::delete_choices_for(updated.get_id(), &st.db).await? { + remove_blob(&st.files_path, image.get_file()).await; + } + } + let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; + Ok(Json(QuestionResponse::new(&updated, &images))) } /// Remove a question (and every answer to it). Requires teacher+ and @@ -1544,7 +1662,387 @@ async fn delete_question( let _guard = EXAM_LOCK.write().await; ensure_questions_editable(exam.get_id(), &st.db).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + // Rows go first (the delete cascades them), blobs after — a crash in + // between strands at worst an unreachable blob. + let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; question.delete(&st.db).await?; + for image in &images { + remove_blob(&st.files_path, image.get_file()).await; + } + Ok(StatusCode::NO_CONTENT) +} + +// ---- question images ---------------------------------------------------------- +// A question may carry one illustration (any kind — the map above the prompt) +// and, on choice questions, one picture per option (pick the right city off +// the map). Uploads are teacher authoring and freeze with the rest of the +// question once attempts exist; metadata rides on the question DTOs, bytes +// flow through the GET endpoints below, whose access follows the question's +// own visibility (author side and sitting side alike). + +/// The exam, provided the caller may author its questions — the shared front +/// half of every image write. +async fn image_managed_exam(st: &AppState, user: &User, id: &str) -> Result { + let exam = Exam::read(&ExamId::from_key(id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can manage question images", + )); + } + Ok(exam) +} + +/// A 403/404 unless the caller may see the exam's question content: course +/// managers always, students through the same wall as +/// `GET /exams/{id}/attempt/questions` — enrollment plus a started attempt, +/// so there is no early peek at the pictures either. +async fn ensure_question_content_visible( + st: &AppState, + exam: &Exam, + user: &User, +) -> Result<(), AppError> { + let course = course_of(exam, &st.db).await?; + if can_manage_course(&course, user) { + return Ok(()); + } + ensure_enrolled(exam, user.get_id(), &st.db).await?; + ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(()) +} + +/// The declared content type, held to the raster allowlist — SVG stays out +/// (it can script) since these bytes are rendered inline to whole classes. +fn image_content_type(raw: &str) -> Result { + let content_type = FileContentType::try_new(raw)?; + if !QUESTION_IMAGE_CONTENT_TYPES.contains(&content_type.as_str()) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "content_type", + reason: "must be image/png, image/jpeg, image/webp, or image/gif", + })); + } + Ok(content_type) +} + +/// The whole image write tail, shared by both upload endpoints: new blob to +/// disk, row UPSERT (the deterministic per-slot id makes it a replace), then +/// the replaced blob off disk. A failed row write takes the fresh blob back +/// out; a stored row always points at a real blob. +async fn store_image( + st: &AppState, + exam: &Exam, + question: &ExamQuestion, + slot: Option, + content_type: FileContentType, + data: &[u8], +) -> Result { + let replaced = QuestionImage::read_slot(question.get_id(), slot, &st.db).await?; + let image = QuestionImage::new( + exam.get_id(), + question.get_id(), + slot, + content_type, + data.len() as i64, + ); + let path = blob_path(&st.files_path, image.get_file()); + tokio::fs::write(&path, data) + .await + .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; + match image.upsert(&st.db).await { + Ok(stored) => { + if let Some(replaced) = replaced { + remove_blob(&st.files_path, replaced.get_file()).await; + } + Ok(stored) + } + Err(err) => { + let _ = tokio::fs::remove_file(&path).await; + Err(err) + } + } +} + +/// The stored bytes as an inline-displayable response: the declared (and +/// allowlisted) content type, `nosniff`, and `no-store` — exam content has no +/// business in shared caches, and a replaced image must not linger. +async fn serve_image(st: &AppState, image: &QuestionImage) -> Result { + let bytes = tokio::fs::read(blob_path(&st.files_path, image.get_file())) + .await + .map_err(|err| { + // The row exists but its blob doesn't — server-side damage (a + // lost volume path), not a client 404. + AppError::Internal(format!( + "missing blob for question image {}: {err}", + image.get_file() + )) + })?; + let content_type = HeaderValue::from_str(image.get_content_type().as_str()) + .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")); + Ok(( + [ + (CONTENT_TYPE, content_type), + (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")), + (CACHE_CONTROL, HeaderValue::from_static("private, no-store")), + ], + bytes, + ) + .into_response()) +} + +/// Attach (or replace) a question's illustration — any question kind may +/// carry one, e.g. the map the prompt asks about. `multipart/form-data` with +/// the image under a `file` field; the declared content type must be +/// `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — +/// no SVG), the bytes at most the school's `max_file_bytes` (settings). +/// Requires teacher+ and management rights over the exam's course; frozen +/// once attempts exist, like every other question edit. +#[utoipa::path( + post, + path = "/{id}/questions/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Image stored", body = ImageMetaResponse), + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +async fn upload_question_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let exam = image_managed_exam(&st, &user, &id).await?; + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + // The body is consumed before the lock — a client's slow upload must not + // stall the exam subsystem. + let upload = read_upload(&mut multipart, limit).await?; + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; + // Writer lease of [`EXAM_LOCK`]: freeze gate + write are one unit, like + // every other question edit — see `create_question`. + let _guard = EXAM_LOCK.write().await; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let stored = store_image(&st, &exam, &question, None, content_type, &upload.data).await?; + Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored)))) +} + +/// The question's illustration bytes. Course managers read anytime; students +/// through the same wall as the sitting view — enrollment plus a started +/// attempt (404 before that, like the question list itself). +#[utoipa::path( + get, + path = "/{id}/questions/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse), + ), +)] +async fn get_question_image( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, qid)): Path<(String, String)>, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_question_content_visible(&st, &exam, &user).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let image = QuestionImage::read_slot(question.get_id(), None, &st.db) + .await? + .ok_or(AppError::NotFound)?; + serve_image(&st, &image).await +} + +/// Remove a question's illustration. Requires teacher+ and management rights +/// over the exam's course; frozen once attempts exist. +#[utoipa::path( + delete, + path = "/{id}/questions/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, question, or image", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +async fn delete_question_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, +) -> Result { + let exam = image_managed_exam(&st, &user, &id).await?; + let _guard = EXAM_LOCK.write().await; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let image = QuestionImage::read_slot(question.get_id(), None, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let image = image.delete(&st.db).await?; + remove_blob(&st.files_path, image.get_file()).await; + Ok(StatusCode::NO_CONTENT) +} + +/// Attach (or replace) one option's picture on a `choice` question — so the +/// options themselves can be images (four map crops, pick the right one). +/// Same form, limits, and rights as the question-image upload; `index` is the +/// option's zero-based position. Replacing the question's `choices` list +/// drops all its option pictures — re-upload against the new list. +#[utoipa::path( + post, + path = "/{id}/questions/{qid}/choices/{index}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ("index" = i64, Path, description = "Zero-based choice index"), + ), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Image stored", body = ImageMetaResponse), + (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text question, or an index past the choices", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +async fn upload_choice_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid, index)): Path<(String, String, i64)>, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let exam = image_managed_exam(&st, &user, &id).await?; + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let upload = read_upload(&mut multipart, limit).await?; + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; + let _guard = EXAM_LOCK.write().await; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let Some(choices) = question.get_choices() else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "index", + reason: "only choice questions take option pictures", + })); + }; + if !(0..choices.len() as i64).contains(&index) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "index", + reason: "must index one of the choices", + })); + } + let stored = store_image( + &st, + &exam, + &question, + Some(index), + content_type, + &upload.data, + ) + .await?; + Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored)))) +} + +/// One option's picture bytes. Same access wall as the question-image read. +#[utoipa::path( + get, + path = "/{id}/questions/{qid}/choices/{index}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ("index" = i64, Path, description = "Zero-based choice index"), + ), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), + (status = 404, description = "No such exam, question, or image — or no attempt yet", body = ErrorResponse), + ), +)] +async fn get_choice_image( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, qid, index)): Path<(String, String, i64)>, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + ensure_question_content_visible(&st, &exam, &user).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let image = QuestionImage::read_slot(question.get_id(), Some(index), &st.db) + .await? + .ok_or(AppError::NotFound)?; + serve_image(&st, &image).await +} + +/// Remove one option's picture. Requires teacher+ and management rights over +/// the exam's course; frozen once attempts exist. +#[utoipa::path( + delete, + path = "/{id}/questions/{qid}/choices/{index}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ("index" = i64, Path, description = "Zero-based choice index"), + ), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, question, or image", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +async fn delete_choice_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid, index)): Path<(String, String, i64)>, +) -> Result { + let exam = image_managed_exam(&st, &user, &id).await?; + let _guard = EXAM_LOCK.write().await; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let image = QuestionImage::read_slot(question.get_id(), Some(index), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let image = image.delete(&st.db).await?; + remove_blob(&st.files_path, image.get_file()).await; Ok(StatusCode::NO_CONTENT) } @@ -1587,6 +2085,12 @@ struct AttemptQuestionResponse { kind: String, points: i64, choices: Option>, + /// The question's illustration, if any — bytes at + /// `GET /exams/{id}/questions/{qid}/image`. + image: Option, + /// Per-option pictures aligned with `choices`, if any — bytes at + /// `GET /exams/{id}/questions/{qid}/choices/{index}/image`. + choice_images: Option>>, /// The caller's saved answer; `null` while unanswered. answer: Option, } @@ -1763,6 +2267,7 @@ async fn attempt_questions( .ok_or(AppError::NotFound)?; let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?; + let images = images_by_question(exam.get_id(), &st.db).await?; let answers: HashMap = ExamAnswer::list_for_exam_user(exam.get_id(), user.get_id(), &st.db) .await? @@ -1772,18 +2277,25 @@ async fn attempt_questions( Ok(Json( questions .iter() - .map(|question| AttemptQuestionResponse { - id: question.get_id().key().to_string(), - subject: question.get_subject().key().to_string(), - text: question.get_text().as_str().to_string(), - kind: question.get_kind().as_str().to_string(), - points: question.get_points().as_i64(), - choices: question - .get_choices() - .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), - answer: answers + .map(|question| { + let question_images = images .get(question.get_id().key()) - .map(AnswerStateResponse::new), + .map_or(&[][..], Vec::as_slice); + AttemptQuestionResponse { + id: question.get_id().key().to_string(), + subject: question.get_subject().key().to_string(), + text: question.get_text().as_str().to_string(), + kind: question.get_kind().as_str().to_string(), + points: question.get_points().as_i64(), + choices: question + .get_choices() + .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), + image: image_meta(question_images, None), + choice_images: choice_image_metas(question, question_images), + answer: answers + .get(question.get_id().key()) + .map(AnswerStateResponse::new), + } }) .collect(), )) diff --git a/src/web/mod.rs b/src/web/mod.rs index a15a136..a832c6b 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -29,7 +29,13 @@ pub use dto::{ pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher}; pub use page::{Page, PageParams, paginate}; +use std::path::{Path as FsPath, PathBuf}; + +use axum::extract::Multipart; +use axum::extract::multipart::MultipartError; +use axum::http::StatusCode; use serde::{Deserialize, Deserializer}; +use utoipa::ToSchema; use crate::constant::SCHEDULE_PAST_GRACE_MS; use crate::domain::timestamp::Timestamp; @@ -73,6 +79,105 @@ pub(crate) fn check_not_past( Ok(()) } +// ---- uploaded blobs --------------------------------------------------------- +// Note files and question images share one story: bytes on disk under the +// configured directory in a file named by a server-generated ULID (user input +// never shapes a path), metadata in a row. Upload writes the blob before the +// row; delete removes the row before the blob — so a stored row always points +// at a real blob and a crash strands at worst an unreachable file. + +/// Where a stored row's blob lives: one file under the configured directory, +/// named by the row's server-generated key. +pub(crate) fn blob_path(files_path: &FsPath, key: &str) -> PathBuf { + files_path.join(key) +} + +/// Best-effort blob removal after its row is gone. Failure only strands an +/// unreachable file on disk, so it is logged rather than surfaced. +pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) { + let path = blob_path(files_path, key); + if let Err(err) = tokio::fs::remove_file(&path).await + && err.kind() != std::io::ErrorKind::NotFound + { + tracing::warn!("failed to remove blob {}: {err}", path.display()); + } +} + +/// Multipart read failures: the route-level body cap maps to 413 like the +/// school-limit check; anything else is a malformed body. +pub(crate) fn multipart_error(err: MultipartError) -> AppError { + if err.status() == StatusCode::PAYLOAD_TOO_LARGE { + AppError::PayloadTooLarge("the upload exceeds the server's absolute body cap".to_string()) + } else { + AppError::Validation(ValidationError::Invalid { + field: "file", + reason: "malformed multipart body", + }) + } +} + +/// Schema-only mirror of an upload form; the handlers read the multipart +/// stream directly. +#[derive(ToSchema)] +#[allow(dead_code)] +pub(crate) struct UploadFileForm { + /// The file part. Its `Content-Type` (and, where required, `filename`) + /// are stored alongside the bytes. + #[schema(value_type = String, format = Binary)] + file: String, +} + +/// One uploaded file's raw parts, as the client sent them — the caller +/// validates what it cares about (notes need a filename, images an +/// allowlisted content type). +pub(crate) struct UploadedFile { + pub name: Option, + pub content_type: Option, + pub data: Vec, +} + +/// Pull the `file` field out of a multipart body, reading it chunkwise so an +/// oversized upload dies at `limit`, not after buffering whole — the check is +/// on real bytes received, so a lying `Content-Length` can't sneak past it. +/// Empty files are refused; stray extra fields are ignored. +pub(crate) async fn read_upload( + multipart: &mut Multipart, + limit: i64, +) -> Result { + let mut field = loop { + match multipart.next_field().await.map_err(multipart_error)? { + Some(field) if field.name() == Some("file") => break field, + Some(_) => continue, + None => { + return Err(AppError::Validation(ValidationError::Invalid { + field: "file", + reason: "the multipart body must carry a 'file' field", + })); + } + } + }; + let name = field.file_name().map(str::to_string); + let content_type = field.content_type().map(str::to_string); + + let mut data = Vec::new(); + while let Some(chunk) = field.chunk().await.map_err(multipart_error)? { + if data.len() + chunk.len() > limit as usize { + return Err(AppError::PayloadTooLarge(format!( + "the file exceeds the school's limit of {limit} bytes" + ))); + } + data.extend_from_slice(&chunk); + } + if data.is_empty() { + return Err(AppError::Validation(ValidationError::Empty("file"))); + } + Ok(UploadedFile { + name, + content_type, + data, + }) +} + /// Distinguishes an *absent* PATCH field from an explicit `null`: absent never /// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the /// stored value); `null` or a value lands here as `Some(inner)` (clear or set). diff --git a/src/web/notes.rs b/src/web/notes.rs index 738ae0c..58377dc 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -1,7 +1,4 @@ -use std::path::{Path as FsPath, PathBuf}; - use axum::Json; -use axum::extract::multipart::MultipartError; use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; use axum::http::{HeaderValue, StatusCode}; @@ -15,10 +12,12 @@ use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; use crate::domain::settings::Settings; -use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; -use super::{CurrentUser, Page, PageParams, paginate}; +use super::{ + CurrentUser, Page, PageParams, UploadFileForm, blob_path, paginate, read_upload, remove_blob, +}; pub fn routes() -> OpenApiRouter { // The file routes get their own HTTP body cap: the server-wide hard @@ -211,7 +210,7 @@ async fn delete_one( let files = NoteFile::list_for(note.get_id(), &st.db).await?; note.delete(&st.db).await?; for file in &files { - remove_blob(&st.files_path, file.get_id()).await; + remove_blob(&st.files_path, file.get_id().key()).await; } Ok(StatusCode::NO_CONTENT) } @@ -243,17 +242,6 @@ impl NoteFileResponse { } } -/// Schema-only mirror of the upload form; the handler reads the multipart -/// stream directly. -#[derive(ToSchema)] -#[allow(dead_code)] -struct UploadFileForm { - /// The file part. Its `filename` (required) and `Content-Type` are stored - /// alongside the bytes. - #[schema(value_type = String, format = Binary)] - file: String, -} - /// Attach a file to a note owned by the current user. `multipart/form-data` /// with the file under a `file` field; its `filename` is required. At most /// 10 files per note; each file at most the school's `max_file_bytes` @@ -287,42 +275,15 @@ async fn upload_file( // under one lock) — checking it here too would just race. let limit = Settings::load(&st.db).await?.get_max_file_bytes(); - let mut field = loop { - match multipart.next_field().await.map_err(multipart_error)? { - Some(field) if field.name() == Some("file") => break field, - Some(_) => continue, // ignore stray extra fields - None => { - return Err(AppError::Validation(ValidationError::Invalid { - field: "file", - reason: "the multipart body must carry a 'file' field", - })); - } - } - }; - let name = FileName::try_new(field.file_name().unwrap_or_default())?; - let content_type = FileContentType::try_new(field.content_type().unwrap_or_default())?; - - // Read the part chunkwise so an oversized upload dies at the limit, not - // after buffering whole. The check is on real bytes received — a lying - // Content-Length can't sneak past it. - let mut data = Vec::new(); - while let Some(chunk) = field.chunk().await.map_err(multipart_error)? { - if data.len() + chunk.len() > limit as usize { - return Err(AppError::PayloadTooLarge(format!( - "the file exceeds the school's limit of {limit} bytes" - ))); - } - data.extend_from_slice(&chunk); - } - if data.is_empty() { - return Err(AppError::Validation(ValidationError::Empty("file"))); - } + let upload = read_upload(&mut multipart, limit).await?; + let name = FileName::try_new(&upload.name.unwrap_or_default())?; + let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?; // Blob first, row second — a stored row always points at a real blob. If // the row insert fails, take the fresh blob back out. - let file = NoteFile::new(note.get_id(), name, content_type, data.len() as i64); - let path = blob_path(&st.files_path, file.get_id()); - tokio::fs::write(&path, &data) + let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); + let path = blob_path(&st.files_path, file.get_id().key()); + tokio::fs::write(&path, &upload.data) .await .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; match file.insert(&st.db).await { @@ -396,7 +357,7 @@ async fn download_file( let file = NoteFile::read_for(&NoteFileId::from_key(&file_id), note.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; - let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id())) + let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_id().key())) .await .map_err(|err| { // The row exists but its blob doesn't — that's server-side damage @@ -450,40 +411,10 @@ async fn delete_file( .await? .ok_or(AppError::NotFound)?; let file = file.delete(&st.db).await?; - remove_blob(&st.files_path, file.get_id()).await; + remove_blob(&st.files_path, file.get_id().key()).await; Ok(StatusCode::NO_CONTENT) } -/// Where a file row's blob lives: one file under the configured directory, -/// named by the row's server-generated key — user input never shapes a path. -fn blob_path(files_path: &FsPath, id: &NoteFileId) -> PathBuf { - files_path.join(id.key()) -} - -/// Best-effort blob removal after its row is gone. Failure only strands an -/// unreachable file on disk, so it is logged rather than surfaced. -async fn remove_blob(files_path: &FsPath, id: &NoteFileId) { - let path = blob_path(files_path, id); - if let Err(err) = tokio::fs::remove_file(&path).await - && err.kind() != std::io::ErrorKind::NotFound - { - tracing::warn!("failed to remove blob {}: {err}", path.display()); - } -} - -/// Multipart read failures: the route-level body cap maps to 413 like the -/// school-limit check; anything else is a malformed body. -fn multipart_error(err: MultipartError) -> AppError { - if err.status() == StatusCode::PAYLOAD_TOO_LARGE { - AppError::PayloadTooLarge("the upload exceeds the server's absolute body cap".to_string()) - } else { - AppError::Validation(ValidationError::Invalid { - field: "file", - reason: "malformed multipart body", - }) - } -} - /// `Content-Disposition` for a download: an ASCII-safe `filename` fallback /// plus the RFC 5987 `filename*` form so non-ASCII names (`ödev.pdf`) survive. fn content_disposition(name: &str) -> String { diff --git a/tests/integration.rs b/tests/integration.rs index 96b51da..486f0e9 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -209,6 +209,12 @@ async fn protected_routes_require_session() { ("GET", "/exams/x/attempt/questions"), ("POST", "/exams/x/attempt/answers"), ("GET", "/exams/x/attempts/u/answers"), + ("POST", "/exams/x/questions/y/image"), + ("GET", "/exams/x/questions/y/image"), + ("DELETE", "/exams/x/questions/y/image"), + ("POST", "/exams/x/questions/y/choices/0/image"), + ("GET", "/exams/x/questions/y/choices/0/image"), + ("DELETE", "/exams/x/questions/y/choices/0/image"), // The WebSocket room authenticates before it upgrades. ("GET", "/exams/x/attempt/ws"), ("POST", "/courses/x/sessions"), @@ -10058,3 +10064,361 @@ async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() { ]) ); } + +// --- question images --------------------------------------------------------- + +/// POST `bytes` as a multipart image upload to `path`; returns (status, json). +async fn post_image( + app: &axum::Router, + cookie: &str, + path: &str, + content_type: &str, + bytes: &[u8], +) -> (StatusCode, serde_json::Value) { + let (status, _, body) = common::send_raw( + app, + "POST", + path, + Some(cookie), + Some("multipart/form-data; boundary=hezarfen-test-boundary"), + common::multipart_file("pic.png", content_type, bytes), + ) + .await; + let body = if body.is_empty() { + serde_json::Value::Null + } else { + serde_json::from_slice(&body).unwrap_or(serde_json::Value::Null) + }; + (status, body) +} + +/// Every stored question-image blob name, straight from the table. +async fn image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec { + let mut result = db + .query("SELECT VALUE file FROM question_image") + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap() +} + +/// The full life of question images: teacher uploads (question + choice slots, +/// rasters only, choice slots bounded), metadata on both question views, +/// bytes behind the sitting wall, replace swaps the blob, a choices PATCH +/// drops the option pictures, and every delete path takes the blobs with it. +#[tokio::test] +async fn question_images_author_serve_and_cascade() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "img_t", "teacher").await; + let student = login(&app, "img_s").await; + let student_id = me_id(&app, &student).await; + let outsider = login(&app, "img_o").await; + + let course = create_course(&app, &teacher, "geography").await; + let subject = create_subject(&app, &teacher, &course, "maps").await; + enroll(&app, &teacher, &course, &student_id).await; + let exam = scheduled_exam( + &app, + &teacher, + &course, + json!({ "title": "map quiz", "kind": "quiz", "mode": "open" }), + ) + .await; + let question = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "Which city is marked?", "kind": "choice", "points": 10, + "choices": ["Ankara", "İzmir"], "correct": 0 }), + ) + .await; + let essay = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "Describe the marked region.", "kind": "text", "points": 10 }), + ) + .await; + + let q_image = format!("/exams/{exam}/questions/{question}/image"); + let png = b"png-bytes-question".as_slice(); + + // SVG is out (script risk); unknown types are out; rasters land. + let (status, body) = post_image(&app, &teacher, &q_image, "image/svg+xml", b"").await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + let (status, body) = post_image(&app, &teacher, &q_image, "application/pdf", b"%PDF").await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + let (status, body) = post_image(&app, &teacher, &q_image, "image/png", png).await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + assert_eq!(body["content_type"], "image/png"); + assert_eq!(body["size"], png.len() as i64); + + // A classical (text) question takes an illustration too — but no option + // pictures, and no out-of-range slot anywhere. + let (status, body) = post_image( + &app, + &teacher, + &format!("/exams/{exam}/questions/{essay}/image"), + "image/jpeg", + b"jpeg-essay", + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + let (status, _) = post_image( + &app, + &teacher, + &format!("/exams/{exam}/questions/{essay}/choices/0/image"), + "image/png", + b"x", + ) + .await; + assert_eq!( + status, + StatusCode::BAD_REQUEST, + "text questions take no option pictures" + ); + let (status, _) = post_image( + &app, + &teacher, + &format!("/exams/{exam}/questions/{question}/choices/2/image"), + "image/png", + b"x", + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "slot must index a choice"); + + // Option picture on choice 1, and the author view carries all the metas. + let choice_image = format!("/exams/{exam}/questions/{question}/choices/1/image"); + let (status, _) = post_image(&app, &teacher, &choice_image, "image/webp", b"webp-choice").await; + assert_eq!(status, StatusCode::CREATED); + let res = send( + &app, + "GET", + &format!("/exams/{exam}/questions"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + let listed = &common::items(&res.body)[0]; + assert_eq!(listed["image"]["content_type"], "image/png"); + assert!(listed["choice_images"][0].is_null()); + assert_eq!(listed["choice_images"][1]["content_type"], "image/webp"); + + // Replace swaps the blob under the same slot: one row, fresh bytes. + let keys_before = image_blob_keys(&db).await; + let png2 = b"png-bytes-question-v2".as_slice(); + let (status, body) = post_image(&app, &teacher, &q_image, "image/png", png2).await; + assert_eq!(status, StatusCode::CREATED); + assert_eq!(body["size"], png2.len() as i64); + let keys_after = image_blob_keys(&db).await; + assert_eq!(keys_before.len(), keys_after.len(), "replace adds no row"); + for stale in keys_before.iter().filter(|k| !keys_after.contains(k)) { + assert!( + !common::files_dir().join(stale).exists(), + "replaced blob lingers on disk" + ); + } + + // The bytes sit behind the sitting wall: outsiders 403, enrolled students + // 404 until an attempt exists, then 200 with the guard headers on. + let (status, _, _) = + common::send_raw(&app, "GET", &q_image, Some(&outsider), None, Vec::new()).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _, _) = + common::send_raw(&app, "GET", &q_image, Some(&student), None, Vec::new()).await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "no early peek before the attempt" + ); + let res = send( + &app, + "POST", + &format!("/exams/{exam}/attempt"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let (status, headers, bytes) = + common::send_raw(&app, "GET", &q_image, Some(&student), None, Vec::new()).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, png2); + assert_eq!(headers["content-type"], "image/png"); + assert_eq!(headers["x-content-type-options"], "nosniff"); + assert_eq!(headers["cache-control"], "private, no-store"); + let (status, _, bytes) = + common::send_raw(&app, "GET", &choice_image, Some(&student), None, Vec::new()).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, b"webp-choice"); + + // The sitting view embeds the same metadata the author sees (sans key). + let res = send( + &app, + "GET", + &format!("/exams/{exam}/attempt/questions"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body[0]["image"]["content_type"], "image/png"); + assert_eq!( + res.body[0]["choice_images"][1]["content_type"], + "image/webp" + ); + assert_eq!(res.body[1]["image"]["content_type"], "image/jpeg"); + assert!(res.body[1]["choice_images"].is_null()); + + // Images freeze with the rest of the question once attempts exist. + let (status, body) = post_image(&app, &teacher, &q_image, "image/png", b"late").await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + let res = send(&app, "DELETE", &q_image, Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CONFLICT); + + // Deleting the exam takes every image row and blob with it. + let keys = image_blob_keys(&db).await; + assert_eq!(keys.len(), 3); + let res = send( + &app, + "DELETE", + &format!("/exams/{exam}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + assert!( + image_blob_keys(&db).await.is_empty(), + "rows survived the cascade" + ); + for key in &keys { + assert!( + !common::files_dir().join(key).exists(), + "blob {key} survived the exam delete" + ); + } +} + +/// The authoring edits that reshape a question also groom its images: a +/// replaced `choices` list drops the option pictures (the illustration +/// stays), an explicit image DELETE removes row + blob, and deleting the +/// question sweeps the rest. +#[tokio::test] +async fn question_image_edits_follow_the_choices() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "imge_t", "teacher").await; + let course = create_course(&app, &teacher, "history").await; + let subject = create_subject(&app, &teacher, &course, "eras").await; + let exam = scheduled_exam( + &app, + &teacher, + &course, + json!({ "title": "eras", "kind": "quiz", "mode": "open" }), + ) + .await; + let question = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "Pick the era.", "kind": "choice", "points": 5, + "choices": ["Bronze", "Iron"], "correct": 1 }), + ) + .await; + let base = format!("/exams/{exam}/questions/{question}"); + for (path, bytes) in [ + (format!("{base}/image"), b"illustration".as_slice()), + (format!("{base}/choices/0/image"), b"bronze".as_slice()), + (format!("{base}/choices/1/image"), b"iron".as_slice()), + ] { + let (status, body) = post_image(&app, &teacher, &path, "image/png", bytes).await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + } + + // A points-only PATCH touches no images. + let res = send( + &app, + "PATCH", + &base, + Some(&teacher), + Some(json!({ "points": 7 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert!(res.body["image"].is_object()); + assert!(res.body["choice_images"][0].is_object()); + assert!(res.body["choice_images"][1].is_object()); + + // Replacing the choices drops the option pictures, keeps the illustration. + let keys_before = image_blob_keys(&db).await; + let res = send( + &app, + "PATCH", + &base, + Some(&teacher), + Some(json!({ "choices": ["Stone", "Bronze", "Iron"], "correct": 2 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert!(res.body["image"].is_object(), "illustration must survive"); + assert_eq!( + res.body["choice_images"], + json!([null, null, null]), + "option pictures must not follow a replaced list" + ); + let keys_after = image_blob_keys(&db).await; + assert_eq!(keys_after.len(), 1); + for dropped in keys_before.iter().filter(|k| !keys_after.contains(k)) { + assert!( + !common::files_dir().join(dropped).exists(), + "dropped option blob lingers" + ); + } + + // Explicit image DELETE: 204 once, 404 after, blob gone. + let (status, _) = post_image( + &app, + &teacher, + &format!("{base}/choices/0/image"), + "image/gif", + b"gif", + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let res = send( + &app, + "DELETE", + &format!("{base}/choices/0/image"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let res = send( + &app, + "DELETE", + &format!("{base}/choices/0/image"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND); + + // Deleting the question sweeps its remaining image rows and blobs. + let keys = image_blob_keys(&db).await; + assert_eq!(keys.len(), 1); + let res = send(&app, "DELETE", &base, Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + assert!(image_blob_keys(&db).await.is_empty()); + for key in &keys { + assert!( + !common::files_dir().join(key).exists(), + "blob {key} survived the question delete" + ); + } +}