forge
Explore
Log in

Don't you dare go Hollow

🔐 a partial PATCH can no longer invert a range

Browse files at this commit

352b0b0cf6dcf4b40cba7d122e9ec97d307a9c26Ahmet Kaan GümüşParent: 85b408e
  • fix
    • 🔐 a partial PATCH can no longer invert a range
Show full message
fix: 🔐 a partial PATCH can no longer invert a range

- regression from the previous commit: writing only the field a
  request carried meant an event's schedule and a work stint's clock
  were each checked against a stored other end that a concurrent
  request had already changed, so two individually valid PATCHes
  committed starts_at > ends_at (or check_in > check_out), both 200
- the old snapshot refill hid this by always writing a consistent
  pair; the parent commit passes the same attack, this one did not
- add EVENT_LOCK and WORK_ENTRY_LOCK and hold them across
  read → range check → write, but only when a range field actually
  arrives, mirroring what terms already did correctly
- both locks are leaves: their only holders take no other lock and no
  other lock holder takes them, so the documented EXAM → BANK and
  EXAM → HOMEWORK orders are unaffected
- omitted fields are still never written; the lock guards the check,
  it does not license writing back what was only read
- regression tests race one end against the other and assert the
  stored pair is ordered whatever each request returns
src/domain/event.rsmodified+15 -0
@@ -1,6 +1,7 @@
1 // `Value` looks unused but is load-bearing: the `SurrealValue` derive on the1 // `Value` looks unused but is load-bearing: the `SurrealValue` derive on the
2 // tagged `EventAudience` enum expands to code that names `Value` unqualified.2 // tagged `EventAudience` enum expands to code that names `Value` unqualified.
3 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};3 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};
4+use tokio::sync::Mutex;
4 use ulid::Ulid;5 use ulid::Ulid;
5 6
6 use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};7 use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};
@@ -15,6 +16,20 @@ use crate::domain::user::{User, UserId};
15 use crate::error::{AppError, ValidationError};16 use crate::error::{AppError, ValidationError};
16 use crate::validate::{validate_optional, validate_required};17 use crate::validate::{validate_optional, validate_required};
17 18
19+/// Serializes the schedule-range check against the write it guards, exactly as
20+/// `TERM_LOCK` does for terms: `starts_at <= ends_at` is a cross-field check,
21+/// so a partial PATCH validates the end it carries against the *stored* other
22+/// end — two such PATCHes, each fine on its own snapshot, would otherwise
23+/// commit an inverted range between them. A PATCH that moves neither end
24+/// checks nothing cross-field and stays lock-free.
25+///
26+/// Lock order: this is a leaf — the only path that takes it (`PATCH
27+/// /events/{id}`) takes no other lock, and no path that holds `REGISTER_LOCK`,
28+/// `ENROLL_LOCK`, `TERM_LOCK`, `EXAM_LOCK` or any other takes this one, so it
29+/// cannot sit in a cycle. Should a future path need both, take the other lock
30+/// first and this one innermost.
31+pub(crate) static EVENT_LOCK: Mutex<()> = Mutex::const_new(());
32+
18 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]33 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
19 pub struct EventId(RecordId);34 pub struct EventId(RecordId);
20 35
src/domain/work_entry.rsmodified+15 -0
@@ -1,4 +1,5 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2+use tokio::sync::Mutex;
2 use ulid::Ulid;3 use ulid::Ulid;
3 4
4 use crate::database::{Database, WORK_ENTRY_TABLE};5 use crate::database::{Database, WORK_ENTRY_TABLE};
@@ -7,6 +8,20 @@ use crate::domain::timestamp::Timestamp;
7 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
8 use crate::error::AppError;9 use crate::error::AppError;
9 10
11+/// Serializes a stint correction's ordering check against the write it guards,
12+/// exactly as `TERM_LOCK` does for terms: `check_in <= check_out` is a
13+/// cross-field check, so a correction of one instant validates against the
14+/// *stored* other one — two such corrections, each fine on its own snapshot,
15+/// would otherwise commit an inverted stint between them. Check-in/check-out
16+/// themselves stay lock-free (they are atomic single-row writes), and a PATCH
17+/// carrying neither instant checks nothing cross-field.
18+///
19+/// Lock order: this is a leaf — the only path that takes it (`PATCH
20+/// /work/entries/{id}`) takes no other lock, and no path holding another lock
21+/// takes this one, so it cannot sit in a cycle. Should a future path need
22+/// both, take the other lock first and this one innermost.
23+pub(crate) static WORK_ENTRY_LOCK: Mutex<()> = Mutex::const_new(());
24+
10 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]25 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
11 pub struct WorkEntryId(RecordId);26 pub struct WorkEntryId(RecordId);
12 27
src/web/events.rsmodified+21 -9
@@ -11,7 +11,9 @@ use utoipa_axum::routes;
11 use crate::database::Database;11 use crate::database::Database;
12 use crate::domain::attendance::{Attendance, AttendanceStatus};12 use crate::domain::attendance::{Attendance, AttendanceStatus};
13 use crate::domain::course::{Course, CourseId};13 use crate::domain::course::{Course, CourseId};
14-use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};14+use crate::domain::event::{
15+ EVENT_LOCK, Event, EventAudience, EventDescription, EventId, EventTitle,
16+};
15 use crate::domain::registration::Registration;17 use crate::domain::registration::Registration;
16 use crate::domain::role::Role;18 use crate::domain::role::Role;
17 use crate::domain::settings::Settings;19 use crate::domain::settings::Settings;
@@ -335,6 +337,22 @@ async fn update_event(
335 Path(id): Path<String>,337 Path(id): Path<String>,
336 Json(req): Json<UpdateEvent>,338 Json(req): Json<UpdateEvent>,
337 ) -> Result<Json<EventResponse>, AppError> {339 ) -> Result<Json<EventResponse>, AppError> {
340+ // The schedule columns are nullable, so they keep the outer/inner
341+ // distinction: a provided value sets the field, an explicit `null` clears
342+ // it, and an omitted one is left alone.
343+ let starts_at = req
344+ .starts_at
345+ .map(|update| update.map(Timestamp::from_millis));
346+ let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis));
347+ // Only the range check needs the stored row, and only it can race: it
348+ // validates an arriving end against the other end as stored, so the read,
349+ // the check and the write are held together under [`EVENT_LOCK`]. A PATCH
350+ // that moves neither end pays nothing.
351+ let _guard = match (starts_at, ends_at) {
352+ (None, None) => None,
353+ _ => Some(EVENT_LOCK.lock().await),
354+ };
355+
338 let event = Event::read(&EventId::from_key(&id), &st.db)356 let event = Event::read(&EventId::from_key(&id), &st.db)
339 .await?357 .await?
340 .ok_or(AppError::NotFound)?;358 .ok_or(AppError::NotFound)?;
@@ -359,14 +377,8 @@ async fn update_event(
359 Some(audience) => Some(audience.into_domain(&st.db).await?),377 Some(audience) => Some(audience.into_domain(&st.db).await?),
360 None => None,378 None => None,
361 };379 };
362- // The schedule columns are nullable, so they keep the outer/inner380+ // Only set schedule values are held to the no-past rule — a kept time of
363- // distinction: a provided value sets the field, an explicit `null` clears381+ // an event already underway may be past.
364- // it, and an omitted one is left alone. Only set values are held to the
365- // no-past rule — a kept time of an event already underway may be past.
366- let starts_at = req
367- .starts_at
368- .map(|update| update.map(Timestamp::from_millis));
369- let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis));
370 if let Some(starts_at) = starts_at {382 if let Some(starts_at) = starts_at {
371 check_not_past("starts_at", starts_at)?;383 check_not_past("starts_at", starts_at)?;
372 }384 }
src/web/work.rsmodified+12 -3
@@ -8,7 +8,7 @@ use utoipa_axum::routes;
8 8
9 use crate::domain::timestamp::Timestamp;9 use crate::domain::timestamp::Timestamp;
10 use crate::domain::user::{User, UserId};10 use crate::domain::user::{User, UserId};
11-use crate::domain::work_entry::{WorkEntry, WorkEntryId};11+use crate::domain::work_entry::{WORK_ENTRY_LOCK, WorkEntry, WorkEntryId};
12 use crate::error::{AppError, ErrorResponse, ValidationError};12 use crate::error::{AppError, ErrorResponse, ValidationError};
13 use crate::state::AppState;13 use crate::state::AppState;
14 14
@@ -198,6 +198,17 @@ async fn update_entry(
198 Path(id): Path<String>,198 Path(id): Path<String>,
199 Json(req): Json<UpdateWorkEntry>,199 Json(req): Json<UpdateWorkEntry>,
200 ) -> Result<Json<WorkEntryResponse>, AppError> {200 ) -> Result<Json<WorkEntryResponse>, AppError> {
201+ let check_in = req.check_in.map(Timestamp::from_millis);
202+ let check_out = req.check_out.map(Timestamp::from_millis);
203+ // Only the ordering check needs the stored row, and only it can race: it
204+ // validates an arriving instant against the other one as stored, so the
205+ // read, the check and the write are held together under
206+ // [`WORK_ENTRY_LOCK`]. A PATCH carrying neither instant pays nothing.
207+ let _guard = match (check_in, check_out) {
208+ (None, None) => None,
209+ _ => Some(WORK_ENTRY_LOCK.lock().await),
210+ };
211+
201 let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db)212 let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db)
202 .await?213 .await?
203 .ok_or(AppError::NotFound)?;214 .ok_or(AppError::NotFound)?;
@@ -207,8 +218,6 @@ async fn update_entry(
207 ));218 ));
208 };219 };
209 220
210- let check_in = req.check_in.map(Timestamp::from_millis);
211- let check_out = req.check_out.map(Timestamp::from_millis);
212 // The side the correction left out is only *read* for the ordering check —221 // The side the correction left out is only *read* for the ordering check —
213 // it is never written back, so a concurrent correction of it survives.222 // it is never written back, so a concurrent correction of it survives.
214 if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) {223 if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) {
tests/partial_patch_events.rsmodified+55 -0
@@ -125,3 +125,58 @@ async fn range_check_still_sees_the_stored_other_side() {
125 "ends_at before stored starts_at"125 "ends_at before stored starts_at"
126 );126 );
127 }127 }
128+
129+/// Each end moved *just inside* the other is valid on its own snapshot, so two
130+/// concurrent one-ended PATCHes can each pass their check against the stored
131+/// row and still commit an inverted range between them. Whatever each request
132+/// returns (200/400/409 are all fine), the stored pair must stay ordered.
133+#[tokio::test]
134+async fn concurrent_range_patches_never_invert_the_stored_row() {
135+ let (app, db) = app_and_db().await;
136+ let who = login_as(&app, &db, "range", "teacher").await;
137+ let starts = 1_900_000_000_000_i64;
138+ let ends = starts + 3_600_000;
139+
140+ for round in 0..20 {
141+ let created = send(
142+ &app,
143+ "POST",
144+ "/events",
145+ Some(&who),
146+ Some(json!({ "title": "timed", "starts_at": starts, "ends_at": ends })),
147+ )
148+ .await;
149+ assert_eq!(created.status, StatusCode::CREATED, "round {round} create");
150+ let uri = format!("/events/{}", id_of(&created.body));
151+
152+ // Each alone is valid: starts_at lands before the stored ends_at, and
153+ // ends_at lands after the stored starts_at.
154+ let (a, b) = tokio::join!(
155+ send(
156+ &app,
157+ "PATCH",
158+ &uri,
159+ Some(&who),
160+ Some(json!({ "starts_at": ends - 1000 })),
161+ ),
162+ send(
163+ &app,
164+ "PATCH",
165+ &uri,
166+ Some(&who),
167+ Some(json!({ "ends_at": starts + 1000 })),
168+ ),
169+ );
170+
171+ let after = send(&app, "GET", &uri, Some(&who), None).await.body;
172+ let stored_starts = after["starts_at"].as_i64().expect("starts_at");
173+ let stored_ends = after["ends_at"].as_i64().expect("ends_at");
174+ assert!(
175+ stored_starts <= stored_ends,
176+ "round {round}: stored inverted range starts_at={stored_starts} \
177+ ends_at={stored_ends} (statuses {} {})",
178+ a.status,
179+ b.status
180+ );
181+ }
182+}
tests/partial_patch_work.rsmodified+60 -0
@@ -129,3 +129,63 @@ async fn range_check_still_sees_the_stored_other_side() {
129 "check_out before the stored check_in"129 "check_out before the stored check_in"
130 );130 );
131 }131 }
132+
133+/// Each instant moved *just inside* the other is valid on its own snapshot, so
134+/// two concurrent one-sided corrections can each pass their check against the
135+/// stored row and still commit an inverted stint between them. Whatever each
136+/// request returns (200/400/409 are all fine), the stored pair must stay
137+/// ordered.
138+#[tokio::test]
139+async fn concurrent_range_patches_never_invert_the_stored_stint() {
140+ let (app, db) = app_and_db().await;
141+ let who = login_as(&app, &db, "mudur5", "manager").await;
142+
143+ let base = 1_000_000_000_000_i64;
144+ let end = base + 3_600_000;
145+
146+ for round in 0..20 {
147+ let id = closed_entry(&app, &who).await;
148+ let uri = format!("/work/entries/{id}");
149+ // The server stamps both instants milliseconds apart; widen the stint
150+ // first so the racing corrections have room to invert it.
151+ let widened = send(
152+ &app,
153+ "PATCH",
154+ &uri,
155+ Some(&who),
156+ Some(json!({ "check_in": base, "check_out": end })),
157+ )
158+ .await;
159+ assert_eq!(widened.status, StatusCode::OK, "round {round} widen");
160+
161+ // Each alone is valid: check_in lands before the stored check_out, and
162+ // check_out after the stored check_in.
163+ let (a, b) = tokio::join!(
164+ send(
165+ &app,
166+ "PATCH",
167+ &uri,
168+ Some(&who),
169+ Some(json!({ "check_in": end - 1000 })),
170+ ),
171+ send(
172+ &app,
173+ "PATCH",
174+ &uri,
175+ Some(&who),
176+ Some(json!({ "check_out": base + 1000 })),
177+ ),
178+ );
179+
180+ let after = entry(&app, &who, &id).await;
181+ let final_in = after["check_in"].as_i64().expect("check_in");
182+ let final_out = after["check_out"].as_i64().expect("check_out");
183+ assert!(
184+ final_in <= final_out,
185+ "round {round}: stored inverted stint check_in={final_in} \
186+ check_out={final_out} (statuses {} {})",
187+ a.status,
188+ b.status
189+ );
190+ }
191+}