diff --git a/src/domain/user.rs b/src/domain/user.rs index 19c19f6..a02ed98 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -335,17 +335,36 @@ impl User { } /// Overwrite this user's role. The caller is responsible for authorizing it. - pub async fn set_role(mut self, role: Role, db: &Database) -> Result { - self.role = role; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + /// + /// Writes *only* the `role` field (never the whole row): the row mixes + /// admin-owned (role) and self-service (profile, preferences) fields, and + /// each writer starts from a snapshot read at request start. A whole-row + /// write would carry the snapshot's copy of the *other* group back over a + /// concurrent edit — an in-flight profile save silently reverting an + /// admin's demotion, or this write erasing a profile edit that raced it. + /// [`User::set_profile`] and [`User::set_preferences`] are scoped for the + /// same reason. + pub async fn set_role(self, role: Role, db: &Database) -> Result { + let mut result = db + .query("UPDATE $id SET role = $role RETURN AFTER") + .bind(("id", self.id.record())) + .bind(("role", role)) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } /// Overwrite the personal-info fields wholesale. Each argument is the final /// value (`None` clears); merging "keep what wasn't sent" against the - /// current row is the HTTP layer's job. The caller authorizes. + /// current row is the HTTP layer's job. The caller authorizes. Writes only + /// the five profile fields — see [`User::set_role`] for why the writers + /// are field-scoped. pub async fn set_profile( - mut self, + self, name: Option, surname: Option, email: Option, @@ -353,29 +372,49 @@ impl User { birth_date: Option, db: &Database, ) -> Result { - self.name = name; - self.surname = surname; - self.email = email; - self.phone = phone; - self.birth_date = birth_date; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query( + "UPDATE $id SET name = $name, surname = $surname, email = $email, \ + phone = $phone, birth_date = $birth_date RETURN AFTER", + ) + .bind(("id", self.id.record())) + .bind(("name", name)) + .bind(("surname", surname)) + .bind(("email", email)) + .bind(("phone", phone)) + .bind(("birth_date", birth_date)) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } /// Overwrite the UI-preference fields wholesale. Same contract as /// [`User::set_profile`]: each argument is the final value (`None` clears /// back to "never chose"), merging is the HTTP layer's job, the caller - /// authorizes. + /// authorizes. Writes only `theme` and `language` — see [`User::set_role`] + /// for why the writers are field-scoped. pub async fn set_preferences( - mut self, + self, theme: Option, language: Option, db: &Database, ) -> Result { - self.theme = theme; - self.language = language; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query("UPDATE $id SET theme = $theme, language = $language RETURN AFTER") + .bind(("id", self.id.record())) + .bind(("theme", theme)) + .bind(("language", language)) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } pub async fn find_by_username(username: &str, db: &Database) -> Result, AppError> { @@ -391,6 +430,48 @@ impl User { #[cfg(test)] mod tests { use super::*; + use crate::database::init_mem; + + #[tokio::test] + async fn a_stale_profile_write_cannot_revert_a_role_change() { + let db = init_mem().await.unwrap(); + let user = User::create( + Username::try_new("aysenur").unwrap(), + Password::try_new("secret1").unwrap().hash().unwrap(), + &db, + ) + .await + .unwrap(); + + // A PATCH /users/me handler reads its snapshot (role = student)... + let stale = User::read(user.get_id(), &db).await.unwrap().unwrap(); + + // ...then an admin's role change commits before the profile save runs. + User::read(user.get_id(), &db) + .await + .unwrap() + .unwrap() + .set_role(Role::Teacher, &db) + .await + .unwrap(); + + // The in-flight save lands from the stale snapshot. It must write only + // the profile fields — not carry the snapshot's old role back over the + // admin's change. + let name = PersonName::try_new("name", "Ayşenur").unwrap(); + stale + .set_profile(Some(name.clone()), None, None, None, None, &db) + .await + .unwrap(); + + let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); + assert_eq!( + after.get_role(), + Role::Teacher, + "the role change must survive the racing profile write" + ); + assert_eq!(after.get_name(), Some(&name), "the profile edit itself lands"); + } #[tokio::test] async fn username_newtype_validates() { diff --git a/src/lib.rs b/src/lib.rs index 0855471..162ba97 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -154,7 +154,10 @@ pub fn cors_layer(allowlist: Vec) -> CorsLayer { Method::DELETE, Method::OPTIONS, ]) - .allow_headers([header::CONTENT_TYPE]); + .allow_headers([header::CONTENT_TYPE]) + // Contract headers cross-origin JS must be able to read: `Retry-After` + // on 429s and `Content-Disposition` (original filename) on downloads. + .expose_headers([header::RETRY_AFTER, header::CONTENT_DISPOSITION]); if allowlist.is_empty() { layer diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index f91305c..1a65561 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -63,7 +63,7 @@ use crate::error::AppError; use crate::state::AppState; use crate::web::CurrentUser; use crate::web::exams::{ - check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt, + EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt, }; /// Serializes every presence transition with its matching `left_at` write: @@ -364,7 +364,11 @@ async fn handle_message( } => { // 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. + // the room's own sitting, never whatever is latest. Reader lease + // of [`EXAM_LOCK`] from the gates through the upsert, exactly + // like `save_answer_checked` — and dropped before the socket + // sends, so a slow client never stalls a writer. + let guard = EXAM_LOCK.read().await; let saved = match Exam::read(exam_id, db).await { Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { Ok(attempt) => { @@ -375,6 +379,7 @@ async fn handle_message( Ok(None) => Err(AppError::NotFound), Err(err) => Err(err), }; + drop(guard); match saved { Ok(answer) => { send( diff --git a/src/web/exams.rs b/src/web/exams.rs index ceee1b6..b28de58 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -40,6 +40,19 @@ use super::{ paginate, person_map, set_or_clear, }; +/// Serializes the exam subsystem's cross-record check-then-writes, which +/// `BEGIN…COMMIT` cannot (write skew) — same reasoning as `REGISTER_LOCK`. +/// Read side: the answer saves (REST and the exam room), holding the sheet +/// open from the writable-attempt gate through the upsert; saves stay +/// concurrent with each other. Write side: attempt starts (the max-attempts +/// count and the retake's answer wipe) and the structural teacher writes +/// whose 409 guards read attempt or question rows first — exam mode/schedule +/// updates, question create/update/delete, subject delete. So a save can +/// never land on a sheet a retake just wiped, and a first attempt can never +/// slip between a freeze-gate read and the write it was meant to freeze. +// ponytail: global RwLock, shard per-exam if save latency ever matters. +pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); + pub fn routes() -> OpenApiRouter { OpenApiRouter::new() // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so @@ -328,7 +341,10 @@ async fn update_exam( // Switching sync <-> async <-> open (or back to a draft) would silently // rewrite the deadline rules under students who already sat down; // extending times, the attempt limit, and the rejoin door are the - // supported live adjustments instead. + // supported live adjustments instead. Gate read and write share one + // writer lease of [`EXAM_LOCK`], so a first attempt can't land in the + // gap and leave a sat exam's mode flipped under it. + let _guard = EXAM_LOCK.write().await; let mode_changed = schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str); if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? { @@ -780,6 +796,15 @@ async fn start_attempt( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result<(StatusCode, Json), AppError> { + // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the + // sittable/window gates must be judged against the same exam row the + // attempt lands under (the mirror of `update_exam`'s re-derive — without + // it, a mode change at legally-zero attempts could slip between this + // gate and the insert, leaving an attempt on a draft exam). The lease + // also keeps the max-attempts count and the retake's wipe-and-create + // from interleaving with an in-flight answer save (a reader). Dropped + // before the response reads — they only describe the row. + let guard = EXAM_LOCK.write().await; let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; @@ -799,6 +824,7 @@ async fn start_attempt( } let (attempt, created) = ExamAttempt::start(&exam, user.get_id(), &st.db).await?; + drop(guard); let mark = ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) .await? .map(|r| r.get_mark()); @@ -1342,6 +1368,10 @@ async fn create_question( "only the course creator or a manager/admin can author questions", )); } + // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and + // the create are one unit — no first attempt can slip past the gate, and + // no subject delete can invalidate a subject this just validated. + let _guard = EXAM_LOCK.write().await; ensure_questions_editable(exam.get_id(), &st.db).await?; let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; @@ -1435,6 +1465,9 @@ async fn update_question( "only the course creator or a manager/admin can edit questions", )); } + // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and + // the update are one unit — 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?; @@ -1505,6 +1538,10 @@ async fn delete_question( "only the course creator or a manager/admin can delete questions", )); } + // Writer lease of [`EXAM_LOCK`]: freeze gate + delete are one unit — a + // first attempt slipping past the gate would sit an exam whose question + // list forks from what `auto_score` later judges. + 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?; question.delete(&st.db).await?; @@ -1618,6 +1655,10 @@ pub(crate) async fn save_answer_checked( text: Option, db: &Database, ) -> Result { + // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are + // one unit, or a retake's wipe-and-create (a writer) slips in between + // and this stale save lands on the fresh blank sheet. + let _guard = EXAM_LOCK.read().await; let attempt = writable_attempt(exam, user, db).await?; save_answer_in(exam, &attempt, question_id, selected, text, db).await } diff --git a/src/web/subjects.rs b/src/web/subjects.rs index ac8191b..48c8933 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -14,6 +14,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::courses::{can_manage_course, can_view_course}; +use super::exams::EXAM_LOCK; use super::{CurrentUser, RequireTeacher, SubjectResponse}; pub fn routes() -> OpenApiRouter { @@ -164,6 +165,10 @@ async fn delete_subject( "only the course creator or a manager/admin can delete this subject", )); } + // Writer lease of [`EXAM_LOCK`]: the no-questions check and the delete + // are one unit, so a question create/update that just validated this + // subject can't land its row on a subject that vanished mid-flight. + let _guard = EXAM_LOCK.write().await; if ExamQuestion::any_for_subject(subject.get_id(), &st.db).await? { return Err(AppError::Conflict( "exam questions still reference this subject — re-tag or delete them first", diff --git a/tests/integration.rs b/tests/integration.rs index c587189..96b51da 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -5042,6 +5042,26 @@ async fn cors_allowlist_mode_credits_only_listed_origins() { ); } +/// Both CORS modes share one layer base, so a single probe proves the exposed +/// headers: without them, cross-origin JS reads `null` for the documented +/// `Retry-After` (429s) and `Content-Disposition` (download filename) headers. +#[tokio::test] +async fn cors_exposes_retry_after_and_content_disposition() { + let app = mem_app().await; + let req = Request::builder() + .method("GET") + .uri("/health") + .header("origin", "https://app.example") + .body(Body::empty()) + .unwrap(); + let res = app.oneshot(req).await.unwrap(); + assert_eq!( + res.headers().get("access-control-expose-headers").unwrap(), + "retry-after,content-disposition", + "contract headers must be readable by cross-origin JS" + ); +} + // --- admin seed (ADMIN_USERNAME / ADMIN_PASSWORD bootstrap) ---------------- /// The seed creates a ready-to-use admin: login works with the configured