forge
Explore
Log in

Don't you dare go Hollow

Five holes from fan-out audit

Browse files at this commit

7d8df3170cd2420e4a9460f4c2643afa40643c02Ahmet Kaan GümüşParent: 2aed950
  • fix
    • five holes from fan-out audit
Show full message
🐛 fix: five holes from fan-out audit

- serialize exam-subsystem check-then-writes with EXAM_LOCK RwLock
  (answer saves read, structural writes write): freeze gate vs first
  attempt, subject delete vs question write, retake wipe vs in-flight
  save; start_attempt re-derives the sittable gate under the lock
- field-scope User::set_role/set_profile/set_preferences: whole-row
  content() writes let a stale PATCH /users/me carry the snapshot role
  back over a concurrent admin demotion (exploitable by hammering the
  endpoint); each writer now updates only the fields it owns
- CORS: expose Retry-After and Content-Disposition so cross-origin JS
  can read the documented 429 backoff and download filename
src/domain/user.rsmodified+100 -19
@@ -335,17 +335,36 @@ impl User {
335 }335 }
336 336
337 /// Overwrite this user's role. The caller is responsible for authorizing it.337 /// Overwrite this user's role. The caller is responsible for authorizing it.
338- pub async fn set_role(mut self, role: Role, db: &Database) -> Result<User, AppError> {338+ ///
339- self.role = role;339+ /// Writes *only* the `role` field (never the whole row): the row mixes
340- let updated: Option<User> = db.update(self.id.record()).content(self).await?;340+ /// admin-owned (role) and self-service (profile, preferences) fields, and
341- updated.ok_or(AppError::NotFound)341+ /// each writer starts from a snapshot read at request start. A whole-row
342+ /// write would carry the snapshot's copy of the *other* group back over a
343+ /// concurrent edit — an in-flight profile save silently reverting an
344+ /// admin's demotion, or this write erasing a profile edit that raced it.
345+ /// [`User::set_profile`] and [`User::set_preferences`] are scoped for the
346+ /// same reason.
347+ pub async fn set_role(self, role: Role, db: &Database) -> Result<User, AppError> {
348+ let mut result = db
349+ .query("UPDATE $id SET role = $role RETURN AFTER")
350+ .bind(("id", self.id.record()))
351+ .bind(("role", role))
352+ .await?
353+ .check()?;
354+ result
355+ .take::<Vec<User>>(0)?
356+ .into_iter()
357+ .next()
358+ .ok_or(AppError::NotFound)
342 }359 }
343 360
344 /// Overwrite the personal-info fields wholesale. Each argument is the final361 /// Overwrite the personal-info fields wholesale. Each argument is the final
345 /// value (`None` clears); merging "keep what wasn't sent" against the362 /// value (`None` clears); merging "keep what wasn't sent" against the
346- /// current row is the HTTP layer's job. The caller authorizes.363+ /// current row is the HTTP layer's job. The caller authorizes. Writes only
364+ /// the five profile fields — see [`User::set_role`] for why the writers
365+ /// are field-scoped.
347 pub async fn set_profile(366 pub async fn set_profile(
348- mut self,367+ self,
349 name: Option<PersonName>,368 name: Option<PersonName>,
350 surname: Option<PersonName>,369 surname: Option<PersonName>,
351 email: Option<Email>,370 email: Option<Email>,
@@ -353,29 +372,49 @@ impl User {
353 birth_date: Option<BirthDate>,372 birth_date: Option<BirthDate>,
354 db: &Database,373 db: &Database,
355 ) -> Result<User, AppError> {374 ) -> Result<User, AppError> {
356- self.name = name;375+ let mut result = db
357- self.surname = surname;376+ .query(
358- self.email = email;377+ "UPDATE $id SET name = $name, surname = $surname, email = $email, \
359- self.phone = phone;378+ phone = $phone, birth_date = $birth_date RETURN AFTER",
360- self.birth_date = birth_date;379+ )
361- let updated: Option<User> = db.update(self.id.record()).content(self).await?;380+ .bind(("id", self.id.record()))
362- updated.ok_or(AppError::NotFound)381+ .bind(("name", name))
382+ .bind(("surname", surname))
383+ .bind(("email", email))
384+ .bind(("phone", phone))
385+ .bind(("birth_date", birth_date))
386+ .await?
387+ .check()?;
388+ result
389+ .take::<Vec<User>>(0)?
390+ .into_iter()
391+ .next()
392+ .ok_or(AppError::NotFound)
363 }393 }
364 394
365 /// Overwrite the UI-preference fields wholesale. Same contract as395 /// Overwrite the UI-preference fields wholesale. Same contract as
366 /// [`User::set_profile`]: each argument is the final value (`None` clears396 /// [`User::set_profile`]: each argument is the final value (`None` clears
367 /// back to "never chose"), merging is the HTTP layer's job, the caller397 /// back to "never chose"), merging is the HTTP layer's job, the caller
368- /// authorizes.398+ /// authorizes. Writes only `theme` and `language` — see [`User::set_role`]
399+ /// for why the writers are field-scoped.
369 pub async fn set_preferences(400 pub async fn set_preferences(
370- mut self,401+ self,
371 theme: Option<Theme>,402 theme: Option<Theme>,
372 language: Option<Language>,403 language: Option<Language>,
373 db: &Database,404 db: &Database,
374 ) -> Result<User, AppError> {405 ) -> Result<User, AppError> {
375- self.theme = theme;406+ let mut result = db
376- self.language = language;407+ .query("UPDATE $id SET theme = $theme, language = $language RETURN AFTER")
377- let updated: Option<User> = db.update(self.id.record()).content(self).await?;408+ .bind(("id", self.id.record()))
378- updated.ok_or(AppError::NotFound)409+ .bind(("theme", theme))
410+ .bind(("language", language))
411+ .await?
412+ .check()?;
413+ result
414+ .take::<Vec<User>>(0)?
415+ .into_iter()
416+ .next()
417+ .ok_or(AppError::NotFound)
379 }418 }
380 419
381 pub async fn find_by_username(username: &str, db: &Database) -> Result<Option<User>, AppError> {420 pub async fn find_by_username(username: &str, db: &Database) -> Result<Option<User>, AppError> {
@@ -391,6 +430,48 @@ impl User {
391 #[cfg(test)]430 #[cfg(test)]
392 mod tests {431 mod tests {
393 use super::*;432 use super::*;
433+ use crate::database::init_mem;
434+
435+ #[tokio::test]
436+ async fn a_stale_profile_write_cannot_revert_a_role_change() {
437+ let db = init_mem().await.unwrap();
438+ let user = User::create(
439+ Username::try_new("aysenur").unwrap(),
440+ Password::try_new("secret1").unwrap().hash().unwrap(),
441+ &db,
442+ )
443+ .await
444+ .unwrap();
445+
446+ // A PATCH /users/me handler reads its snapshot (role = student)...
447+ let stale = User::read(user.get_id(), &db).await.unwrap().unwrap();
448+
449+ // ...then an admin's role change commits before the profile save runs.
450+ User::read(user.get_id(), &db)
451+ .await
452+ .unwrap()
453+ .unwrap()
454+ .set_role(Role::Teacher, &db)
455+ .await
456+ .unwrap();
457+
458+ // The in-flight save lands from the stale snapshot. It must write only
459+ // the profile fields — not carry the snapshot's old role back over the
460+ // admin's change.
461+ let name = PersonName::try_new("name", "Ayşenur").unwrap();
462+ stale
463+ .set_profile(Some(name.clone()), None, None, None, None, &db)
464+ .await
465+ .unwrap();
466+
467+ let after = User::read(user.get_id(), &db).await.unwrap().unwrap();
468+ assert_eq!(
469+ after.get_role(),
470+ Role::Teacher,
471+ "the role change must survive the racing profile write"
472+ );
473+ assert_eq!(after.get_name(), Some(&name), "the profile edit itself lands");
474+ }
394 475
395 #[tokio::test]476 #[tokio::test]
396 async fn username_newtype_validates() {477 async fn username_newtype_validates() {
src/lib.rsmodified+4 -1
@@ -154,7 +154,10 @@ pub fn cors_layer(allowlist: Vec<HeaderValue>) -> CorsLayer {
154 Method::DELETE,154 Method::DELETE,
155 Method::OPTIONS,155 Method::OPTIONS,
156 ])156 ])
157- .allow_headers([header::CONTENT_TYPE]);157+ .allow_headers([header::CONTENT_TYPE])
158+ // Contract headers cross-origin JS must be able to read: `Retry-After`
159+ // on 429s and `Content-Disposition` (original filename) on downloads.
160+ .expose_headers([header::RETRY_AFTER, header::CONTENT_DISPOSITION]);
158 161
159 if allowlist.is_empty() {162 if allowlist.is_empty() {
160 layer163 layer
src/web/exam_ws.rsmodified+7 -2
@@ -63,7 +63,7 @@ use crate::error::AppError;
63 use crate::state::AppState;63 use crate::state::AppState;
64 use crate::web::CurrentUser;64 use crate::web::CurrentUser;
65 use crate::web::exams::{65 use crate::web::exams::{
66- check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt,66+ EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt,
67 };67 };
68 68
69 /// Serializes every presence transition with its matching `left_at` write:69 /// Serializes every presence transition with its matching `left_at` write:
@@ -364,7 +364,11 @@ async fn handle_message(
364 } => {364 } => {
365 // Re-read the exam so the save is judged against the *current*365 // Re-read the exam so the save is judged against the *current*
366 // schedule, exactly like the REST path it shares — but write into366 // schedule, exactly like the REST path it shares — but write into
367- // the room's own sitting, never whatever is latest.367+ // the room's own sitting, never whatever is latest. Reader lease
368+ // of [`EXAM_LOCK`] from the gates through the upsert, exactly
369+ // like `save_answer_checked` — and dropped before the socket
370+ // sends, so a slow client never stalls a writer.
371+ let guard = EXAM_LOCK.read().await;
368 let saved = match Exam::read(exam_id, db).await {372 let saved = match Exam::read(exam_id, db).await {
369 Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await {373 Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await {
370 Ok(attempt) => {374 Ok(attempt) => {
@@ -375,6 +379,7 @@ async fn handle_message(
375 Ok(None) => Err(AppError::NotFound),379 Ok(None) => Err(AppError::NotFound),
376 Err(err) => Err(err),380 Err(err) => Err(err),
377 };381 };
382+ drop(guard);
378 match saved {383 match saved {
379 Ok(answer) => {384 Ok(answer) => {
380 send(385 send(
src/web/exams.rsmodified+42 -1
@@ -40,6 +40,19 @@ use super::{
40 paginate, person_map, set_or_clear,40 paginate, person_map, set_or_clear,
41 };41 };
42 42
43+/// Serializes the exam subsystem's cross-record check-then-writes, which
44+/// `BEGIN…COMMIT` cannot (write skew) — same reasoning as `REGISTER_LOCK`.
45+/// Read side: the answer saves (REST and the exam room), holding the sheet
46+/// open from the writable-attempt gate through the upsert; saves stay
47+/// concurrent with each other. Write side: attempt starts (the max-attempts
48+/// count and the retake's answer wipe) and the structural teacher writes
49+/// whose 409 guards read attempt or question rows first — exam mode/schedule
50+/// updates, question create/update/delete, subject delete. So a save can
51+/// never land on a sheet a retake just wiped, and a first attempt can never
52+/// slip between a freeze-gate read and the write it was meant to freeze.
53+// ponytail: global RwLock, shard per-exam if save latency ever matters.
54+pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
55+
43 pub fn routes() -> OpenApiRouter<AppState> {56 pub fn routes() -> OpenApiRouter<AppState> {
44 OpenApiRouter::new()57 OpenApiRouter::new()
45 // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so58 // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so
@@ -328,7 +341,10 @@ async fn update_exam(
328 // Switching sync <-> async <-> open (or back to a draft) would silently341 // Switching sync <-> async <-> open (or back to a draft) would silently
329 // rewrite the deadline rules under students who already sat down;342 // rewrite the deadline rules under students who already sat down;
330 // extending times, the attempt limit, and the rejoin door are the343 // extending times, the attempt limit, and the rejoin door are the
331- // supported live adjustments instead.344+ // supported live adjustments instead. Gate read and write share one
345+ // writer lease of [`EXAM_LOCK`], so a first attempt can't land in the
346+ // gap and leave a sat exam's mode flipped under it.
347+ let _guard = EXAM_LOCK.write().await;
332 let mode_changed =348 let mode_changed =
333 schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);349 schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);
334 if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? {350 if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? {
@@ -780,6 +796,15 @@ async fn start_attempt(
780 CurrentUser(user): CurrentUser,796 CurrentUser(user): CurrentUser,
781 Path(id): Path<String>,797 Path(id): Path<String>,
782 ) -> Result<(StatusCode, Json<AttemptResponse>), AppError> {798 ) -> Result<(StatusCode, Json<AttemptResponse>), AppError> {
799+ // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the
800+ // sittable/window gates must be judged against the same exam row the
801+ // attempt lands under (the mirror of `update_exam`'s re-derive — without
802+ // it, a mode change at legally-zero attempts could slip between this
803+ // gate and the insert, leaving an attempt on a draft exam). The lease
804+ // also keeps the max-attempts count and the retake's wipe-and-create
805+ // from interleaving with an in-flight answer save (a reader). Dropped
806+ // before the response reads — they only describe the row.
807+ let guard = EXAM_LOCK.write().await;
783 let exam = Exam::read(&ExamId::from_key(&id), &st.db)808 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
784 .await?809 .await?
785 .ok_or(AppError::NotFound)?;810 .ok_or(AppError::NotFound)?;
@@ -799,6 +824,7 @@ async fn start_attempt(
799 }824 }
800 825
801 let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?;826 let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?;
827+ drop(guard);
802 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)828 let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
803 .await?829 .await?
804 .map(|r| r.get_mark());830 .map(|r| r.get_mark());
@@ -1342,6 +1368,10 @@ async fn create_question(
1342 "only the course creator or a manager/admin can author questions",1368 "only the course creator or a manager/admin can author questions",
1343 ));1369 ));
1344 }1370 }
1371+ // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and
1372+ // the create are one unit — no first attempt can slip past the gate, and
1373+ // no subject delete can invalidate a subject this just validated.
1374+ let _guard = EXAM_LOCK.write().await;
1345 ensure_questions_editable(exam.get_id(), &st.db).await?;1375 ensure_questions_editable(exam.get_id(), &st.db).await?;
1346 1376
1347 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;1377 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
@@ -1435,6 +1465,9 @@ async fn update_question(
1435 "only the course creator or a manager/admin can edit questions",1465 "only the course creator or a manager/admin can edit questions",
1436 ));1466 ));
1437 }1467 }
1468+ // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and
1469+ // the update are one unit — see `create_question`.
1470+ let _guard = EXAM_LOCK.write().await;
1438 ensure_questions_editable(exam.get_id(), &st.db).await?;1471 ensure_questions_editable(exam.get_id(), &st.db).await?;
1439 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;1472 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1440 1473
@@ -1505,6 +1538,10 @@ async fn delete_question(
1505 "only the course creator or a manager/admin can delete questions",1538 "only the course creator or a manager/admin can delete questions",
1506 ));1539 ));
1507 }1540 }
1541+ // Writer lease of [`EXAM_LOCK`]: freeze gate + delete are one unit — a
1542+ // first attempt slipping past the gate would sit an exam whose question
1543+ // list forks from what `auto_score` later judges.
1544+ let _guard = EXAM_LOCK.write().await;
1508 ensure_questions_editable(exam.get_id(), &st.db).await?;1545 ensure_questions_editable(exam.get_id(), &st.db).await?;
1509 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;1546 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1510 question.delete(&st.db).await?;1547 question.delete(&st.db).await?;
@@ -1618,6 +1655,10 @@ pub(crate) async fn save_answer_checked(
1618 text: Option<String>,1655 text: Option<String>,
1619 db: &Database,1656 db: &Database,
1620 ) -> Result<ExamAnswer, AppError> {1657 ) -> Result<ExamAnswer, AppError> {
1658+ // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are
1659+ // one unit, or a retake's wipe-and-create (a writer) slips in between
1660+ // and this stale save lands on the fresh blank sheet.
1661+ let _guard = EXAM_LOCK.read().await;
1621 let attempt = writable_attempt(exam, user, db).await?;1662 let attempt = writable_attempt(exam, user, db).await?;
1622 save_answer_in(exam, &attempt, question_id, selected, text, db).await1663 save_answer_in(exam, &attempt, question_id, selected, text, db).await
1623 }1664 }
src/web/subjects.rsmodified+5 -0
@@ -14,6 +14,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
14 use crate::state::AppState;14 use crate::state::AppState;
15 15
16 use super::courses::{can_manage_course, can_view_course};16 use super::courses::{can_manage_course, can_view_course};
17+use super::exams::EXAM_LOCK;
17 use super::{CurrentUser, RequireTeacher, SubjectResponse};18 use super::{CurrentUser, RequireTeacher, SubjectResponse};
18 19
19 pub fn routes() -> OpenApiRouter<AppState> {20 pub fn routes() -> OpenApiRouter<AppState> {
@@ -164,6 +165,10 @@ async fn delete_subject(
164 "only the course creator or a manager/admin can delete this subject",165 "only the course creator or a manager/admin can delete this subject",
165 ));166 ));
166 }167 }
168+ // Writer lease of [`EXAM_LOCK`]: the no-questions check and the delete
169+ // are one unit, so a question create/update that just validated this
170+ // subject can't land its row on a subject that vanished mid-flight.
171+ let _guard = EXAM_LOCK.write().await;
167 if ExamQuestion::any_for_subject(subject.get_id(), &st.db).await? {172 if ExamQuestion::any_for_subject(subject.get_id(), &st.db).await? {
168 return Err(AppError::Conflict(173 return Err(AppError::Conflict(
169 "exam questions still reference this subject — re-tag or delete them first",174 "exam questions still reference this subject — re-tag or delete them first",
tests/integration.rsmodified+20 -0
@@ -5042,6 +5042,26 @@ async fn cors_allowlist_mode_credits_only_listed_origins() {
5042 );5042 );
5043 }5043 }
5044 5044
5045+/// Both CORS modes share one layer base, so a single probe proves the exposed
5046+/// headers: without them, cross-origin JS reads `null` for the documented
5047+/// `Retry-After` (429s) and `Content-Disposition` (download filename) headers.
5048+#[tokio::test]
5049+async fn cors_exposes_retry_after_and_content_disposition() {
5050+ let app = mem_app().await;
5051+ let req = Request::builder()
5052+ .method("GET")
5053+ .uri("/health")
5054+ .header("origin", "https://app.example")
5055+ .body(Body::empty())
5056+ .unwrap();
5057+ let res = app.oneshot(req).await.unwrap();
5058+ assert_eq!(
5059+ res.headers().get("access-control-expose-headers").unwrap(),
5060+ "retry-after,content-disposition",
5061+ "contract headers must be readable by cross-origin JS"
5062+ );
5063+}
5064+
5045 // --- admin seed (ADMIN_USERNAME / ADMIN_PASSWORD bootstrap) ----------------5065 // --- admin seed (ADMIN_USERNAME / ADMIN_PASSWORD bootstrap) ----------------
5046 5066
5047 /// The seed creates a ready-to-use admin: login works with the configured5067 /// The seed creates a ready-to-use admin: login works with the configured