From f62fb740d3db77e00eb69ee7b9f99793ba9693cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 25 Jul 2026 08:56:02 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=94=92=20cap=20the=20echoed=20ques?= =?UTF-8?q?tion=5Fid,=20and=20de-flake=20the=20exam-room=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cd6c1e4 started echoing `question_id` back in the per-question error frame, but the field was an unvalidated `String` and axum's default WebSocket message limit is 64 MiB, so a client could make the server echo ~64 MiB to itself. It is now length-checked against `MAX_QUESTION_ID_LEN` (64 — real values are 26-char ULID keys) before any lock or database work, and rejected *unattributed* so nothing of the oversized id is reflected. `exam_room_expires_mid_session` was flaky for a real reason, not a tight sleep: the fixture sampled `GET /time`, then made five more HTTP calls including a full argon2 login — costlier since 684f18b — and all of it had to fit inside the 2.6 s window it had just set. On a loaded run the setup outlived the exam and the attempt hit a closed window, 409. Setup now happens outside the window and the teacher shortens `ends_at` after the answer lands, which drives the same live-schedule path the extension test already covers, in the other direction. 20 runs, 20 passes. --- src/constant.rs | 9 +++++++++ src/web/exam_ws.rs | 8 +++++++- tests/e2e.rs | 48 +++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 61 insertions(+), 4 deletions(-) diff --git a/src/constant.rs b/src/constant.rs index 824f4c7..45047fc 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -207,6 +207,15 @@ pub const DB_CONNECT_BACKOFF_MAX_SECS: u64 = 5; /// (`GET /exams/{id}/attempt/ws`). pub const EXAM_WS_TICK_SECS: u64 = 2; +/// Ceiling on a `question_id` arriving on the exam-room WebSocket. The field is +/// a record key — a 26-char ULID in every real payload — not free text, so this +/// is generous by a factor of two and change. The cap exists because the +/// per-question error frame *echoes* the id back: axum's default WebSocket +/// frame limit is 64 MiB, so without it a client can make its own room reflect +/// that whole payload. Rejected before any database work, and unattributed — an +/// unusable id names no question, so nothing of it is sent back. +pub const MAX_QUESTION_ID_LEN: usize = 64; + /// The only accepted question kinds. `choice`: pick one of the listed /// choices, auto-scorable. `text`: free text, judged by the grader. pub const QUESTION_KINDS: [&str; 2] = ["choice", "text"]; diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index b27e00c..25bbca4 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -55,7 +55,7 @@ use axum::response::Response; use serde::Deserialize; use serde_json::{Value, json}; -use crate::constant::EXAM_WS_TICK_SECS; +use crate::constant::{EXAM_WS_TICK_SECS, MAX_QUESTION_ID_LEN}; use crate::database::Database; use crate::domain::exam::{Exam, ExamId}; use crate::domain::exam_answer::ExamAnswer; @@ -65,6 +65,7 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; use crate::state::AppState; +use crate::validate::validate_required; use crate::web::CurrentUser; use crate::web::exams::{ EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, save_answer_in, @@ -365,6 +366,11 @@ async fn handle_message( selected, text, } => { + // Cap the key before it can be echoed — see [`MAX_QUESTION_ID_LEN`]. + if let Err(err) = validate_required("question_id", &question_id, MAX_QUESTION_ID_LEN) { + let frame = error_frame(&AppError::Validation(err)); + return send(socket, frame).await; + } // Re-read the exam so the save is judged against the *current* // schedule, exactly like the REST path it shares — but write into // the room's own sitting, never whatever is latest. Reader lease diff --git a/tests/e2e.rs b/tests/e2e.rs index 903ed59..b6dd060 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -716,6 +716,21 @@ async fn exam_room_websocket_round_trip() { let error = ws_frame_of_type(&mut ws, "error").await; assert_eq!(error["question_id"], "nosuchquestion", "{error}"); + // An over-long `question_id` dies at the door and is *not* reflected. The + // error frame echoes the field it blames, and axum accepts frames up to + // 64 MiB, so an uncapped echo is a self-inflicted amplifier — uncapped, + // this arrives back with all 70 000 characters attached. + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": "x".repeat(70_000), "text": "x" }), + ) + .await; + let error = ws_frame_of_type(&mut ws, "error").await; + let message = error["message"].as_str().unwrap(); + assert!(message.contains("question_id"), "{error}"); + assert!(message.len() < 200, "the id itself is never quoted back"); + assert!(error.get("question_id").is_none(), "{error}"); + // Junk and unknown message types too — the room shrugs and stays up. // These are frame-level, not save-level: no question to blame, so the // client keeps failing everything in flight. @@ -982,9 +997,14 @@ async fn exam_room_deadline_moves_with_a_live_extension() { /// `expired`, closes, and everything saved in time survives for grading. #[tokio::test] async fn exam_room_expires_mid_session() { - // The window closes ~2.6 s in — enough to connect and save, gone by the - // second tick. Real time: expiry is judged by the server clock. - let room = exam_room_fixture(2_600).await; + // A generous window while the room is set up. Keying the deadline off + // *fixture* time (this used to ask for 2.6 s) made the whole fixture race + // it — five HTTP calls plus a `raw_session_cookie` login, and argon2 is + // deliberately expensive, so on a loaded run the setup alone outran the + // window and the attempt POST below hit an already-closed exam (409). + // Nothing here cares *when* the window closes, only that it closes with the + // room open — so close it deliberately, further down, once it is. + let room = exam_room_fixture(600_000).await; let res = room .student .post(format!("{}/exams/{}/attempt", room.base, room.exam_id)) @@ -1007,6 +1027,28 @@ async fn exam_room_expires_mid_session() { .await; ws_frame_of_type(&mut ws, "saved").await; + // Now bring the deadline in, from a *fresh* server clock — the room re-reads + // the schedule every tick, the same live-schedule path + // `exam_room_deadline_moves_with_a_live_extension` covers, in the other + // direction. Setup latency is behind us, so the only wait left is one tick. + let now: Value = room + .teacher + .get(format!("{}/time", room.base)) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let res = room + .teacher + .patch(format!("{}/exams/{}", room.base, room.exam_id)) + .json(&json!({ "ends_at": now["now"].as_i64().unwrap() + 1_000 })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + // A tick notices the deadline: `expired`, then the room closes. ws_frame_of_type(&mut ws, "expired").await; assert!(