diff --git a/README.md b/README.md index fbcc1d8..abb6d5b 100644 --- a/README.md +++ b/README.md @@ -290,8 +290,8 @@ marks/attendance reports narrow to the courses the caller manages. | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) | | 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 an attempt) | -| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while `in_progress` (and not locked out by a closed rejoin door) | +| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires enrollment + an attempt) | +| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while 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: state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts (course manager) | @@ -307,7 +307,7 @@ marks/attendance reports narrow to the courses the caller manages. | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) | | GET | `/settings` | student | The school's policy: `exam_kinds`, `attendance_statuses`, `grade_bands` | -| PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale (see "Per-school policy") | +| PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | | GET | `/terms` | student | List terms, newest first | | GET | `/terms/{id}` | student | Get one term | @@ -381,9 +381,12 @@ editable `settings` singleton (`GET /settings` for any signed-in user, can switch display scales without touching a single stored mark. A `PATCH` replaces only the fields it carries, each wholesale, and validation -is all-or-nothing. Editing a list never rewrites history: an exam keeps its -retired kind, a roll-call row keeps its retired status — only **new writes** -are held to the current lists. +is all-or-nothing. Concurrent edits are safe: each save applies only if the +policy still matches the snapshot it merged from (retrying over the fresh row +otherwise), so two managers patching different fields both land instead of +the later write silently reverting the earlier one. Editing a list never +rewrites history: an exam keeps its retired kind, a roll-call row keeps its +retired status — only **new writes** are held to the current lists. Academic structure is data too. **Terms** (`/terms`) model whatever calendar the school runs — semester, trimester, quarter systems are just rows with a @@ -512,15 +515,18 @@ would fork what "the exam" means. Deleting a question cascades its answers. **Answering** (student, attempt `in_progress`, deadline judged by the server clock on every save): -- `GET /exams/{id}/attempt/questions` — the sitting view. Requires an attempt - (`404` before `POST /exams/{id}/attempt`; also the anti-peek gate), never - contains `correct`, and embeds the caller's own saved answer per question - (`{selected, text, updated_at}` or `null`). Still readable after - submitting/expiry, for review. +- `GET /exams/{id}/attempt/questions` — the sitting view. Requires + enrollment (`403` — the questions are course content, so leaving the course + closes them) and an attempt (`404` before `POST /exams/{id}/attempt`; also + the anti-peek gate), never contains `correct`, and embeds the caller's own + saved answer per question (`{selected, text, updated_at}` or `null`). Still + readable after submitting/expiry, for review. - `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` — an upsert: one row per question+user, re-answering overwrites. The payload must match the question's kind (`selected` indexing a choice, or `text` - ≤ 10 000 chars — empty clears the draft); mismatches are `400`s. Once the + ≤ 10 000 chars — empty clears the draft); mismatches are `400`s. Requires + enrollment (`403`): an unenrollment mid-exam closes the sheet (the exam + room's door check, applied to every save — finishing stays open). Once the attempt is submitted or past its deadline every save is a `409` — likewise while the student has left the exam room with `allow_rejoin` off; answers saved in time survive untouched for grading (until a retake wipes the sheet @@ -551,7 +557,10 @@ rejoin is closed `409`. Then JSON text frames: Every tick and every save re-read the exam, so a mid-exam `ends_at` extension moves the room's countdown on the next tick, and no stale socket can write -past its real deadline — the socket shares the exact REST write path. +past its real deadline — the socket shares the exact REST write path. Each +room acts only on the sitting it was opened for: once that sitting is over, +its `answer`/`finish` are `error` frames, so a lingering socket can never +scribble on (or instantly submit) a retake started elsewhere. The room is also the presence signal behind the **rejoin door**: connecting clears the attempt's `left_at`, and the *last* socket of the sitting to close diff --git a/src/constant.rs b/src/constant.rs index 321df28..15fa3b5 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -65,6 +65,10 @@ pub const MAX_SETTINGS_ITEM_LEN: usize = 50; pub const MAX_GRADE_BANDS: usize = 20; pub const MAX_GRADE_LABEL_LEN: usize = 20; +/// How many times `PATCH /settings` re-merges and retries when a concurrent +/// edit lands between its snapshot and its compare-and-set save. +pub const SETTINGS_UPDATE_RETRIES: usize = 3; + pub const MAX_TERM_NAME_LEN: usize = 100; /// The only accepted exam modes. `sync`: everyone sits the exam inside one diff --git a/src/domain/settings.rs b/src/domain/settings.rs index 7e1a34c..0a74e50 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -167,11 +167,53 @@ impl Settings { Ok(found.unwrap_or_else(Self::defaults)) } - /// Persist the policy (single UPSERT on the fixed singleton id). + /// Persist the policy (single UPSERT on the fixed singleton id), + /// unconditionally — last write wins. Prefer [`Self::save_if_unchanged`] + /// wherever the new policy was merged from a loaded snapshot. pub async fn save(self, db: &Database) -> Result { let saved: Option = db.upsert(Self::record_id()).content(self).await?; saved.ok_or_else(|| AppError::Internal("failed to save settings".into())) } + + /// Persist the policy only while the stored row still matches `expected` + /// — the snapshot the caller merged omitted fields from. `None` means a + /// concurrent edit landed in between and nothing was written: reload, + /// re-merge, retry. Without this compare-and-set, two managers patching + /// *different* fields silently revert each other (both merge from the + /// same snapshot; the later whole-row write restores its stale copy of + /// the other's field). + /// + /// One transaction: the seed insert materializes the defaults-as-loaded + /// state when no row exists yet (`load` reported the defaults, so the + /// defaults are what the caller merged over), then the guarded update + /// applies `self` only if the row (still) equals `expected`. + pub async fn save_if_unchanged( + self, + expected: &Settings, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "BEGIN TRANSACTION; + INSERT IGNORE INTO settings $expected; + UPDATE $id CONTENT $new + WHERE exam_kinds = $ek + AND attendance_statuses = $st + AND grade_bands = $gb; + COMMIT TRANSACTION;", + ) + .bind(("expected", expected.clone())) + .bind(("id", Self::record_id())) + .bind(("new", self)) + .bind(("ek", expected.exam_kinds.clone())) + .bind(("st", expected.attendance_statuses.clone())) + .bind(("gb", expected.grade_bands.clone())) + .await? + .check()?; + // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An + // empty slot means the row no longer matched `expected`. + Ok(result.take::>(2)?.into_iter().next()) + } } /// Shared rules for the editable string lists: 1–20 trimmed, non-empty, @@ -337,6 +379,81 @@ mod tests { assert_eq!(rows[0].get_exam_kinds(), ["quiz"]); } + #[tokio::test] + async fn a_stale_snapshot_cannot_revert_a_newer_policy() { + let db = crate::database::init_mem().await.unwrap(); + let statuses = Settings::defaults().get_attendance_statuses().to_vec(); + + // Editor A snapshots the policy (the defaults — no row yet)... + let stale = Settings::load(&db).await.unwrap(); + // ...then editor B lands a new exam-kind list first. + Settings::try_new(kinds(&["lab"]), statuses.clone(), vec![]) + .unwrap() + .save(&db) + .await + .unwrap(); + + // A's merge over the stale snapshot (kinds kept "as loaded", bands + // changed) — exactly what a concurrent PATCH /settings computes — + // must be refused, not applied. + let refused = Settings::try_new( + stale.get_exam_kinds().to_vec(), + stale.get_attendance_statuses().to_vec(), + bands(&[(0, "F"), (50, "P")]), + ) + .unwrap() + .save_if_unchanged(&stale, &db) + .await + .unwrap(); + assert!(refused.is_none(), "a stale snapshot's save must not apply"); + + // B's edit must survive A's stale write attempt. + let after = Settings::load(&db).await.unwrap(); + assert_eq!( + after.get_exam_kinds(), + ["lab"], + "a concurrent editor's exam kinds must not be silently reverted" + ); + assert!(after.get_grade_bands().is_empty()); + + // A's retry — reload, re-merge, save again — lands both edits. + let fresh = Settings::load(&db).await.unwrap(); + let saved = Settings::try_new( + fresh.get_exam_kinds().to_vec(), + fresh.get_attendance_statuses().to_vec(), + bands(&[(0, "F"), (50, "P")]), + ) + .unwrap() + .save_if_unchanged(&fresh, &db) + .await + .unwrap() + .expect("a merge over the current row applies"); + assert_eq!(saved.get_exam_kinds(), ["lab"]); + assert_eq!(saved.get_grade_bands().len(), 2); + } + + #[tokio::test] + async fn save_if_unchanged_seeds_the_first_row() { + let db = crate::database::init_mem().await.unwrap(); + // No row yet: `load` reports the defaults, and a save conditioned on + // that snapshot must apply (seeding the singleton on the way). + let current = Settings::load(&db).await.unwrap(); + let saved = Settings::try_new( + kinds(&["lab"]), + current.get_attendance_statuses().to_vec(), + vec![], + ) + .unwrap() + .save_if_unchanged(¤t, &db) + .await + .unwrap() + .expect("the first save applies"); + assert_eq!(saved.get_exam_kinds(), ["lab"]); + let mut result = db.query("SELECT * FROM settings").await.unwrap(); + let rows: Vec = result.take(0).unwrap(); + assert_eq!(rows.len(), 1, "still one singleton row"); + } + #[tokio::test] async fn grade_label_picks_the_greatest_min_at_or_below() { let defaults = Settings::defaults(); diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 53f5ea9..329c5b6 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -36,8 +36,10 @@ //! finishing stays allowed. //! //! Each room is bound to the sitting it was opened for: state frames track -//! that attempt (not whatever is latest), so a room whose sitting ends — -//! submitted or expired anywhere — announces it and closes. +//! that attempt (not whatever is latest), a room whose sitting ends — +//! submitted or expired anywhere — announces it and closes, and `answer` / +//! `finish` refuse to touch any other sitting, so a lingering socket can +//! never write into (or submit) a retake it never hosted. use std::time::Duration; @@ -49,7 +51,6 @@ use serde_json::{Value, json}; use crate::constant::EXAM_WS_TICK_SECS; use crate::database::Database; -use crate::domain::enrollment::Enrollment; use crate::domain::exam::{Exam, ExamId}; use crate::domain::exam_answer::ExamAnswer; use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt, ExamAttemptId}; @@ -59,7 +60,7 @@ use crate::domain::user::UserId; use crate::error::AppError; use crate::state::AppState; use crate::web::CurrentUser; -use crate::web::exams::{check_rejoin, save_answer_checked, writable_attempt}; +use crate::web::exams::{check_rejoin, ensure_enrolled, save_answer_in, writable_attempt}; /// What the client asked for, tagged by `type`. #[derive(Deserialize)] @@ -96,14 +97,7 @@ pub async fn attempt_ws( "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", )); } - if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db) - .await? - .is_none() - { - return Err(AppError::Forbidden( - "you are not enrolled in this exam's course", - )); - } + ensure_enrolled(&exam, user.get_id(), &st.db).await?; let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; check_rejoin(&exam, &attempt)?; let attempt = if attempt.get_left_at().is_some() { @@ -198,6 +192,27 @@ async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) /// terminal state and the close frame was sent. struct RoomClosed; +/// The room's own sitting, provided it is still the student's current one and +/// writable. Messages act on the sitting the room was opened for — never on a +/// retake started elsewhere while this socket lingered, which a stale tab +/// could otherwise scribble on or instantly submit (burning a limited +/// sitting). The latest-attempt read also keeps the deadline gates on the +/// exam's current schedule, exactly like the REST path. +async fn writable_room_attempt( + exam: &Exam, + attempt_id: &ExamAttemptId, + user: &UserId, + db: &Database, +) -> Result { + let attempt = writable_attempt(exam, user, db).await?; + if attempt.get_id() != attempt_id { + return Err(AppError::Conflict( + "this room's sitting is over — reconnect to continue in the new attempt", + )); + } + Ok(attempt) +} + async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { socket .send(Message::Text(frame.to_string().into())) @@ -310,11 +325,15 @@ async fn handle_message( text, } => { // Re-read the exam so the save is judged against the *current* - // schedule, exactly like the REST path it shares. + // schedule, exactly like the REST path it shares — but write into + // the room's own sitting, never whatever is latest. let saved = match Exam::read(exam_id, db).await { - Ok(Some(exam)) => { - save_answer_checked(&exam, user, &question_id, selected, text, db).await - } + Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { + Ok(attempt) => { + save_answer_in(&exam, &attempt, &question_id, selected, text, db).await + } + Err(err) => Err(err), + }, Ok(None) => Err(AppError::NotFound), Err(err) => Err(err), }; @@ -337,8 +356,10 @@ async fn handle_message( } } ClientMessage::Finish => { + // Submit the room's own sitting — a stale room must not submit a + // retake it never hosted. let finished = match Exam::read(exam_id, db).await { - Ok(Some(exam)) => match writable_attempt(&exam, user, db).await { + Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { Ok(attempt) => attempt.finish(db).await, Err(err) => Err(err), }, diff --git a/src/web/exams.rs b/src/web/exams.rs index 795c779..45edb1b 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -758,14 +758,7 @@ async fn start_attempt( .await? .ok_or(AppError::NotFound)?; ensure_sittable(&exam)?; - if Enrollment::read_for_user(exam.get_course(), user.get_id(), &st.db) - .await? - .is_none() - { - return Err(AppError::Forbidden( - "you are not enrolled in this exam's course", - )); - } + ensure_enrolled(&exam, user.get_id(), &st.db).await?; let now = Timestamp::now(); if let Some(starts_at) = exam.get_starts_at() && now < starts_at @@ -1539,9 +1532,10 @@ pub(crate) fn check_rejoin(exam: &Exam, attempt: &ExamAttempt) -> Result<(), App } /// Save one answer inside the caller's in-progress attempt — the whole write -/// path (attempt gate, rejoin gate, question lookup, kind check, upsert), -/// shared verbatim by the REST handler and the WebSocket room so the two can -/// never drift. +/// path (attempt gate, rejoin gate, question lookup, kind check, upsert). The +/// REST handler saves into the latest sitting via this; the WebSocket room +/// resolves its own sitting first and shares [`save_answer_in`], so the two +/// can never drift. pub(crate) async fn save_answer_checked( exam: &Exam, user: &UserId, @@ -1551,16 +1545,53 @@ pub(crate) async fn save_answer_checked( db: &Database, ) -> Result { let attempt = writable_attempt(exam, user, db).await?; - check_rejoin(exam, &attempt)?; + save_answer_in(exam, &attempt, question_id, selected, text, db).await +} + +/// The tail of the answer write path, given the sitting to write in: the +/// enrollment wall (leaving the course closes the sheet, mid-exam included), +/// the rejoin gate, the question lookup, and the upsert. +pub(crate) async fn save_answer_in( + exam: &Exam, + attempt: &ExamAttempt, + question_id: &str, + selected: Option, + text: Option, + db: &Database, +) -> Result { + ensure_enrolled(exam, attempt.get_user(), db).await?; + check_rejoin(exam, attempt)?; let question = question_of_exam(exam.get_id(), question_id, db).await?; - ExamAnswer::save(&question, user, selected, text, db).await + ExamAnswer::save(&question, attempt.get_user(), selected, text, db).await +} + +/// A 403 unless `user` is enrolled in the exam's course — the same wall the +/// exam room checks at its door, re-applied to the sitting's content paths so +/// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the +/// rejoin lock, submitting what's already saved writes nothing new. +pub(crate) async fn ensure_enrolled( + exam: &Exam, + user: &UserId, + db: &Database, +) -> Result<(), AppError> { + if Enrollment::read_for_user(exam.get_course(), user, db) + .await? + .is_none() + { + return Err(AppError::Forbidden( + "you are not enrolled in this exam's course", + )); + } + Ok(()) } /// The exam's questions as the sitting student sees them: `correct` stripped, /// their own saved answers embedded — the latest sitting's, since a retake -/// starts from a blank sheet. Requires an attempt — start one with -/// `POST /exams/{id}/attempt` first (404 until then). Readable in every -/// attempt state, so a submitted student can still review what they wrote. +/// starts from a blank sheet. Requires enrollment in the exam's course (the +/// questions are course content — leaving the course closes them) and an +/// attempt — start one with `POST /exams/{id}/attempt` first (404 until +/// then). Readable in every attempt state, so a submitted student can still +/// review what they wrote. #[utoipa::path( get, path = "/{id}/attempt/questions", @@ -1570,6 +1601,7 @@ pub(crate) async fn save_answer_checked( responses( (status = 200, description = "Questions with the caller's answers embedded", body = [AttemptQuestionResponse]), (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, or no attempt yet — start the attempt first", body = ErrorResponse), ), )] @@ -1581,6 +1613,7 @@ async fn attempt_questions( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + ensure_enrolled(&exam, user.get_id(), &st.db).await?; // The question list is for sitting students; without an attempt there is // nothing to sit behind — and no early peek at the questions. ExamAttempt::read_latest_for_user(exam.get_id(), user.get_id(), &st.db) @@ -1614,10 +1647,11 @@ async fn attempt_questions( } /// Save (or overwrite) one answer in the caller's in-progress attempt. -/// `choice` questions take `selected`; `text` questions take `text`. Rejected -/// once the attempt is submitted or its deadline has passed — the server -/// clock, not the client's, is the judge — and rejected while the student has -/// left the exam room with the exam's rejoin door closed. +/// `choice` questions take `selected`; `text` questions take `text`. Requires +/// enrollment in the exam's course — an unenrollment mid-exam closes the +/// sheet. Rejected once the attempt is submitted or its deadline has passed — +/// the server clock, not the client's, is the judge — and rejected while the +/// student has left the exam room with the exam's rejoin door closed. #[utoipa::path( post, path = "/{id}/attempt/answers", @@ -1629,6 +1663,7 @@ async fn attempt_questions( (status = 200, description = "Answer saved", body = AnswerSavedResponse), (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse), (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 attempt", body = ErrorResponse), (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), ), diff --git a/src/web/settings.rs b/src/web/settings.rs index 632650a..37281c1 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -5,6 +5,7 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use crate::constant::SETTINGS_UPDATE_RETRIES; use crate::domain::settings::{GradeBand, Settings}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; @@ -108,6 +109,7 @@ async fn get_settings( (status = 400, description = "Invalid lists or bands", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 409, description = "Concurrent edits kept changing the settings mid-save", body = ErrorResponse), ), )] async fn update_settings( @@ -115,23 +117,35 @@ async fn update_settings( RequireManager(_user): RequireManager, Json(req): Json, ) -> Result, AppError> { - let current = Settings::load(&st.db).await?; + // Merge over a snapshot, then save only while the row still matches it — + // otherwise a concurrent PATCH of a *different* field would be silently + // reverted by whichever whole-row write lands second. A refused save + // reloads and re-merges, so both edits land. + for _ in 0..SETTINGS_UPDATE_RETRIES { + let current = Settings::load(&st.db).await?; - let exam_kinds = req - .exam_kinds - .unwrap_or_else(|| current.get_exam_kinds().to_vec()); - let attendance_statuses = req - .attendance_statuses - .unwrap_or_else(|| current.get_attendance_statuses().to_vec()); - let grade_bands = match req.grade_bands { - Some(bands) => bands - .into_iter() - .map(|band| GradeBand::try_new(band.min, &band.label)) - .collect::, _>>()?, - None => current.get_grade_bands().to_vec(), - }; + let exam_kinds = req + .exam_kinds + .clone() + .unwrap_or_else(|| current.get_exam_kinds().to_vec()); + let attendance_statuses = req + .attendance_statuses + .clone() + .unwrap_or_else(|| current.get_attendance_statuses().to_vec()); + let grade_bands = match &req.grade_bands { + Some(bands) => bands + .iter() + .map(|band| GradeBand::try_new(band.min, &band.label)) + .collect::, _>>()?, + None => current.get_grade_bands().to_vec(), + }; - let settings = Settings::try_new(exam_kinds, attendance_statuses, grade_bands)?; - let saved = settings.save(&st.db).await?; - Ok(Json(SettingsResponse::new(&saved))) + let settings = Settings::try_new(exam_kinds, attendance_statuses, grade_bands)?; + if let Some(saved) = settings.save_if_unchanged(¤t, &st.db).await? { + return Ok(Json(SettingsResponse::new(&saved))); + } + } + Err(AppError::Conflict( + "the settings kept changing underneath this update — try again", + )) } diff --git a/src/web/work.rs b/src/web/work.rs index 948741e..008b55d 100644 --- a/src/web/work.rs +++ b/src/web/work.rs @@ -53,7 +53,9 @@ impl WorkEntryResponse { user: entry.get_user().key().to_string(), check_in, check_out, - duration_ms: check_out.map(|out| out - check_in), + // Saturating: manager-corrected instants are arbitrary i64s, and + // an absurdly wide pair must cap the duration, not overflow it. + duration_ms: check_out.map(|out| out.saturating_sub(check_in)), } } } diff --git a/tests/e2e.rs b/tests/e2e.rs index cc6e37c..406b8ae 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -1266,6 +1266,118 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() { ); } +/// Messages through a stale room act on that room's own sitting — never on a +/// retake started while the old socket lingered. An `answer` or `finish` sent +/// through the old room after sitting #1 ended must be refused, not silently +/// applied to sitting #2 (which would scribble on — or instantly submit — a +/// fresh attempt the student opened elsewhere, burning a limited sitting). +#[tokio::test] +async fn exam_room_messages_bind_to_their_own_sitting() { + let room = exam_room_fixture(600_000).await; + + // An open exam with two sittings and one choice question. + let exam: Value = room + .teacher + .post(format!("{}/courses/{}/exams", room.base, room.course_id)) + .json(&json!({ + "title": "practice", "kind": "quiz", "weight": 1, + "mode": "open", "max_attempts": 2, + })) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let exam_id = exam["id"].as_str().unwrap().to_string(); + let question: Value = room + .teacher + .post(format!("{}/exams/{exam_id}/questions", room.base)) + .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5, + "choices": ["5", "6"], "correct": 1 })) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let question_id = question["id"].as_str().unwrap().to_string(); + + // Sit sitting #1 and open its room. + let res = room + .student + .post(format!("{}/exams/{exam_id}/attempt", room.base)) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let mut ws = ws_open(&room.base, &exam_id, Some(&room.cookie)) + .await + .expect("room for sitting #1"); + let state = ws_next_frame(&mut ws).await.expect("connect state"); + assert_eq!(state["attempt"], 1, "{state}"); + + // Finish sitting #1 and start sitting #2 over REST — the old socket is + // still open while the retake begins. + let res = room + .student + .post(format!("{}/exams/{exam_id}/attempt/finish", room.base)) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + let res = room + .student + .post(format!("{}/exams/{exam_id}/attempt", room.base)) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let body: Value = res.json().await.unwrap(); + assert_eq!(body["attempt"], 2); + + // An answer through the stale room must be refused — not saved into the + // blank sheet of sitting #2. + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": question_id, "selected": 1 }), + ) + .await; + let error = ws_frame_of_type(&mut ws, "error").await; + assert!( + error["message"].as_str().unwrap().contains("sitting"), + "{error}" + ); + + // A finish through the stale room must be refused — not submit sitting #2. + ws_send(&mut ws, json!({ "type": "finish" })).await; + let error = ws_frame_of_type(&mut ws, "error").await; + assert!( + error["message"].as_str().unwrap().contains("sitting"), + "{error}" + ); + + // Sitting #2 is untouched: still running, sheet still blank. + let attempt: Value = room + .student + .get(format!("{}/exams/{exam_id}/attempt", room.base)) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(attempt["attempt"], 2, "{attempt}"); + assert_eq!( + attempt["status"], "in_progress", + "a stale room must not submit the new sitting: {attempt}" + ); + assert_eq!( + attempt["answered"], 0, + "a stale room must not write into the new sitting's sheet: {attempt}" + ); +} + /// Two sockets on the same sitting (a second tab): closing one must not count /// as leaving the exam room while the other is still connected — only the last /// socket out stamps `left_at` and (with the door closed) locks answering. diff --git a/tests/integration.rs b/tests/integration.rs index cb25ce1..65d5abb 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -5247,6 +5247,122 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { assert_eq!(res.body[1]["answer"]["text"], "because"); } +#[tokio::test] +async fn unenrollment_cuts_the_sittings_reads_and_writes() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "cut_t", "teacher").await; + let student = login(&app, "cansu").await; + let student_id = me_id(&app, &student).await; + let (course, exam) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; + let question = create_question( + &app, + &teacher, + &exam, + json!({ "text": "2 + 2?", "kind": "choice", "points": 10, + "choices": ["3", "4"], "correct": 1 }), + ) + .await; + + // Enrolled: start the attempt, read the questions, save an answer. + let res = send( + &app, + "POST", + &format!("/exams/{exam}/attempt"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/exams/{exam}/attempt/questions"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam}/attempt/answers"), + Some(&student), + Some(json!({ "question_id": question, "selected": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Unenrolled mid-exam: the course wall closes over the sitting too. The + // question list is course content (`GET /exams/{id}` is already walled), + // and answering from outside the course would dodge the same wall the + // exam room enforces on entry. + let res = send( + &app, + "DELETE", + &format!("/courses/{course}/enrollments/{student_id}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/exams/{exam}/attempt/questions"), + Some(&student), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "question list after unenrollment: {}", + res.body + ); + let res = send( + &app, + "POST", + &format!("/exams/{exam}/attempt/answers"), + Some(&student), + Some(json!({ "question_id": question, "selected": 0 })), + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "answer save after unenrollment: {}", + res.body + ); + + // Their own status and submission stay theirs: like the rejoin lock, + // finishing submits what's already saved and writes nothing new. + let res = send( + &app, + "GET", + &format!("/exams/{exam}/attempt"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam}/attempt/finish"), + Some(&student), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::OK, + "finish stays open: {}", + res.body + ); + assert_eq!(res.body["status"], "submitted"); + assert_eq!(res.body["answered"], 1, "the enrolled-time answer survives"); +} + #[tokio::test] async fn answer_saves_stop_at_the_deadline() { let (app, db) = app_and_db().await; @@ -6591,6 +6707,38 @@ async fn work_log_manager_reads_and_corrections() { assert_eq!(res.status, StatusCode::CREATED); } +#[tokio::test] +async fn work_duration_survives_absurd_corrected_instants() { + let (app, db) = app_and_db().await; + let hoca = login_as(&app, &db, "wid_t", "teacher").await; + let boss = login_as(&app, &db, "wid_m", "manager").await; + send(&app, "POST", "/work/check-in", Some(&hoca), None).await; + let closed = send(&app, "POST", "/work/check-out", Some(&hoca), None).await; + let closed_id = id_of(&closed.body); + + // Corrected instants are arbitrary i64 millis; the widest legal pair must + // not overflow the `check_out - check_in` duration (a wrapped negative in + // release, a panicking 500 in debug) — it saturates instead. + let res = send( + &app, + "PATCH", + &format!("/work/entries/{closed_id}"), + Some(&boss), + Some(json!({ "check_in": i64::MIN, "check_out": i64::MAX })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + res.body["duration_ms"].as_i64(), + Some(i64::MAX), + "the over-wide stint saturates: {}", + res.body + ); + // The stored row must stay readable, not a permanent 500. + let res = send(&app, "GET", "/work/me", Some(&hoca), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); +} + // --- attendance reports ------------------------------------------------------- #[tokio::test]