forge
Explore
Log in

Don't you dare go Hollow

🔒 cap the echoed question_id, and de-flake the exam-room test

Browse files at this commit

f62fb740d3db77e00eb69ee7b9f99793ba9693cbAhmet Kaan GümüşParent: 788229d
  • fix
    • 🔒 cap the echoed question_id, and de-flake the exam-room test
Show full message
fix: 🔒 cap the echoed question_id, and de-flake the exam-room test

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.rsmodified+9 -0
@@ -207,6 +207,15 @@ pub const DB_CONNECT_BACKOFF_MAX_SECS: u64 = 5;
207 /// (`GET /exams/{id}/attempt/ws`).207 /// (`GET /exams/{id}/attempt/ws`).
208 pub const EXAM_WS_TICK_SECS: u64 = 2;208 pub const EXAM_WS_TICK_SECS: u64 = 2;
209 209
210+/// Ceiling on a `question_id` arriving on the exam-room WebSocket. The field is
211+/// a record key — a 26-char ULID in every real payload — not free text, so this
212+/// is generous by a factor of two and change. The cap exists because the
213+/// per-question error frame *echoes* the id back: axum's default WebSocket
214+/// frame limit is 64 MiB, so without it a client can make its own room reflect
215+/// that whole payload. Rejected before any database work, and unattributed — an
216+/// unusable id names no question, so nothing of it is sent back.
217+pub const MAX_QUESTION_ID_LEN: usize = 64;
218+
210 /// The only accepted question kinds. `choice`: pick one of the listed219 /// The only accepted question kinds. `choice`: pick one of the listed
211 /// choices, auto-scorable. `text`: free text, judged by the grader.220 /// choices, auto-scorable. `text`: free text, judged by the grader.
212 pub const QUESTION_KINDS: [&str; 2] = ["choice", "text"];221 pub const QUESTION_KINDS: [&str; 2] = ["choice", "text"];
src/web/exam_ws.rsmodified+7 -1
@@ -55,7 +55,7 @@ use axum::response::Response;
55 use serde::Deserialize;55 use serde::Deserialize;
56 use serde_json::{Value, json};56 use serde_json::{Value, json};
57 57
58-use crate::constant::EXAM_WS_TICK_SECS;58+use crate::constant::{EXAM_WS_TICK_SECS, MAX_QUESTION_ID_LEN};
59 use crate::database::Database;59 use crate::database::Database;
60 use crate::domain::exam::{Exam, ExamId};60 use crate::domain::exam::{Exam, ExamId};
61 use crate::domain::exam_answer::ExamAnswer;61 use crate::domain::exam_answer::ExamAnswer;
@@ -65,6 +65,7 @@ use crate::domain::timestamp::Timestamp;
65 use crate::domain::user::UserId;65 use crate::domain::user::UserId;
66 use crate::error::AppError;66 use crate::error::AppError;
67 use crate::state::AppState;67 use crate::state::AppState;
68+use crate::validate::validate_required;
68 use crate::web::CurrentUser;69 use crate::web::CurrentUser;
69 use crate::web::exams::{70 use crate::web::exams::{
70 EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, save_answer_in,71 EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, save_answer_in,
@@ -365,6 +366,11 @@ async fn handle_message(
365 selected,366 selected,
366 text,367 text,
367 } => {368 } => {
369+ // Cap the key before it can be echoed — see [`MAX_QUESTION_ID_LEN`].
370+ if let Err(err) = validate_required("question_id", &question_id, MAX_QUESTION_ID_LEN) {
371+ let frame = error_frame(&AppError::Validation(err));
372+ return send(socket, frame).await;
373+ }
368 // Re-read the exam so the save is judged against the *current*374 // Re-read the exam so the save is judged against the *current*
369 // schedule, exactly like the REST path it shares — but write into375 // schedule, exactly like the REST path it shares — but write into
370 // the room's own sitting, never whatever is latest. Reader lease376 // the room's own sitting, never whatever is latest. Reader lease
tests/e2e.rsmodified+45 -3
@@ -716,6 +716,21 @@ async fn exam_room_websocket_round_trip() {
716 let error = ws_frame_of_type(&mut ws, "error").await;716 let error = ws_frame_of_type(&mut ws, "error").await;
717 assert_eq!(error["question_id"], "nosuchquestion", "{error}");717 assert_eq!(error["question_id"], "nosuchquestion", "{error}");
718 718
719+ // An over-long `question_id` dies at the door and is *not* reflected. The
720+ // error frame echoes the field it blames, and axum accepts frames up to
721+ // 64 MiB, so an uncapped echo is a self-inflicted amplifier — uncapped,
722+ // this arrives back with all 70 000 characters attached.
723+ ws_send(
724+ &mut ws,
725+ json!({ "type": "answer", "question_id": "x".repeat(70_000), "text": "x" }),
726+ )
727+ .await;
728+ let error = ws_frame_of_type(&mut ws, "error").await;
729+ let message = error["message"].as_str().unwrap();
730+ assert!(message.contains("question_id"), "{error}");
731+ assert!(message.len() < 200, "the id itself is never quoted back");
732+ assert!(error.get("question_id").is_none(), "{error}");
733+
719 // Junk and unknown message types too — the room shrugs and stays up.734 // Junk and unknown message types too — the room shrugs and stays up.
720 // These are frame-level, not save-level: no question to blame, so the735 // These are frame-level, not save-level: no question to blame, so the
721 // client keeps failing everything in flight.736 // client keeps failing everything in flight.
@@ -982,9 +997,14 @@ async fn exam_room_deadline_moves_with_a_live_extension() {
982 /// `expired`, closes, and everything saved in time survives for grading.997 /// `expired`, closes, and everything saved in time survives for grading.
983 #[tokio::test]998 #[tokio::test]
984 async fn exam_room_expires_mid_session() {999 async fn exam_room_expires_mid_session() {
985- // The window closes ~2.6 s in — enough to connect and save, gone by the1000+ // A generous window while the room is set up. Keying the deadline off
986- // second tick. Real time: expiry is judged by the server clock.1001+ // *fixture* time (this used to ask for 2.6 s) made the whole fixture race
987- let room = exam_room_fixture(2_600).await;1002+ // it — five HTTP calls plus a `raw_session_cookie` login, and argon2 is
1003+ // deliberately expensive, so on a loaded run the setup alone outran the
1004+ // window and the attempt POST below hit an already-closed exam (409).
1005+ // Nothing here cares *when* the window closes, only that it closes with the
1006+ // room open — so close it deliberately, further down, once it is.
1007+ let room = exam_room_fixture(600_000).await;
988 let res = room1008 let res = room
989 .student1009 .student
990 .post(format!("{}/exams/{}/attempt", room.base, room.exam_id))1010 .post(format!("{}/exams/{}/attempt", room.base, room.exam_id))
@@ -1007,6 +1027,28 @@ async fn exam_room_expires_mid_session() {
1007 .await;1027 .await;
1008 ws_frame_of_type(&mut ws, "saved").await;1028 ws_frame_of_type(&mut ws, "saved").await;
1009 1029
1030+ // Now bring the deadline in, from a *fresh* server clock — the room re-reads
1031+ // the schedule every tick, the same live-schedule path
1032+ // `exam_room_deadline_moves_with_a_live_extension` covers, in the other
1033+ // direction. Setup latency is behind us, so the only wait left is one tick.
1034+ let now: Value = room
1035+ .teacher
1036+ .get(format!("{}/time", room.base))
1037+ .send()
1038+ .await
1039+ .unwrap()
1040+ .json()
1041+ .await
1042+ .unwrap();
1043+ let res = room
1044+ .teacher
1045+ .patch(format!("{}/exams/{}", room.base, room.exam_id))
1046+ .json(&json!({ "ends_at": now["now"].as_i64().unwrap() + 1_000 }))
1047+ .send()
1048+ .await
1049+ .unwrap();
1050+ assert_eq!(res.status(), StatusCode::OK);
1051+
1010 // A tick notices the deadline: `expired`, then the room closes.1052 // A tick notices the deadline: `expired`, then the room closes.
1011 ws_frame_of_type(&mut ws, "expired").await;1053 ws_frame_of_type(&mut ws, "expired").await;
1012 assert!(1054 assert!(