forge
Explore
Log in

Don't you dare go Hollow

Re-derive registration gate under the lock

Browse files at this commit

05cfa93778f6d99cb8b27a303ff7e6fd007b8cf7Ahmet Kaan GümüşParent: ecbd550
  • fix
    • re-derive registration gate under the lock
Show full message
🐛 fix(events): re-derive registration gate under the lock

The register handler read the event (capacity, audience kind, schedule)
before Registration::register took REGISTER_LOCK, so a concurrent PATCH
landing in that gap admitted against stale data. The gate moved into
Event::registration_capacity and register re-reads the event fresh
under the lock; the handler's early call remains as fast-fail only.
src/domain/event.rsmodified+72 -0
@@ -192,6 +192,29 @@ impl Event {
192 &self.creator == user192 &self.creator == user
193 }193 }
194 194
195+ /// The shared gate for touching a signup list: the event must carry the
196+ /// registration audience, and the list must still be open — it closes the
197+ /// moment the event starts, or, for an ends_at-only event (a pure signup
198+ /// deadline), the moment that end passes (a truly timeless event never
199+ /// closes). Returns the seat cap for the register path.
200+ pub fn registration_capacity(&self) -> Result<Option<i64>, AppError> {
201+ let EventAudience::Registration { capacity } = &self.audience else {
202+ return Err(AppError::Validation(ValidationError::Invalid {
203+ field: "audience",
204+ reason: "this event does not take registrations",
205+ }));
206+ };
207+ // ends_at can't precede starts_at, so when both exist starts_at governs.
208+ if let Some(closes_at) = self.starts_at.or(self.ends_at)
209+ && Timestamp::now().as_millis() >= closes_at.as_millis()
210+ {
211+ return Err(AppError::Conflict(
212+ "registration closed — the event has started or ended",
213+ ));
214+ }
215+ Ok(*capacity)
216+ }
217+
195 pub async fn create(218 pub async fn create(
196 creator: &UserId,219 creator: &UserId,
197 title: EventTitle,220 title: EventTitle,
@@ -316,6 +339,55 @@ mod tests {
316 }339 }
317 }340 }
318 341
342+ fn event_with(
343+ audience: EventAudience,
344+ starts_at: Option<Timestamp>,
345+ ends_at: Option<Timestamp>,
346+ ) -> Event {
347+ Event {
348+ id: EventId::generate(),
349+ creator: UserId::from_key("u1"),
350+ title: EventTitle::try_new("signup").unwrap(),
351+ description: EventDescription::try_new("").unwrap(),
352+ audience,
353+ starts_at,
354+ ends_at,
355+ }
356+ }
357+
358+ #[tokio::test]
359+ async fn registration_capacity_gates_and_echoes_cap() {
360+ let open = |capacity| EventAudience::Registration { capacity };
361+ let past = Some(Timestamp::from_millis(Timestamp::now().as_millis() - 1));
362+
363+ assert!(matches!(
364+ event_with(EventAudience::School, None, None).registration_capacity(),
365+ Err(AppError::Validation(_))
366+ ));
367+ assert_eq!(
368+ event_with(open(None), None, None)
369+ .registration_capacity()
370+ .unwrap(),
371+ None
372+ );
373+ assert_eq!(
374+ event_with(open(Some(30)), None, None)
375+ .registration_capacity()
376+ .unwrap(),
377+ Some(30)
378+ );
379+ // Started events close the list; an ends_at-only deadline in the past
380+ // does too.
381+ assert!(matches!(
382+ event_with(open(Some(30)), past, None).registration_capacity(),
383+ Err(AppError::Conflict(_))
384+ ));
385+ assert!(matches!(
386+ event_with(open(None), None, past).registration_capacity(),
387+ Err(AppError::Conflict(_))
388+ ));
389+ }
390+
319 /// The database strips `NONE`-valued optional columns and the boot391 /// The database strips `NONE`-valued optional columns and the boot
320 /// conversion writes a bare `{kind: 'registration'}` — an object with no392 /// conversion writes a bare `{kind: 'registration'}` — an object with no
321 /// `capacity` key at all must decode as an uncapped registration.393 /// `capacity` key at all must decode as an uncapped registration.
src/domain/registration.rsmodified+9 -4
@@ -2,7 +2,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 use tokio::sync::Mutex;2 use tokio::sync::Mutex;
3 3
4 use crate::database::{Database, REGISTRATION_TABLE};4 use crate::database::{Database, REGISTRATION_TABLE};
5-use crate::domain::event::EventId;5+use crate::domain::event::{Event, EventId};
6 use crate::domain::user::UserId;6 use crate::domain::user::UserId;
7 use crate::error::AppError;7 use crate::error::AppError;
8 8
@@ -71,22 +71,27 @@ impl Registration {
71 &self.registered_by71 &self.registered_by
72 }72 }
73 73
74- /// Register (idempotently) `user` onto `event`, refusing when a `capacity`74+ /// Register (idempotently) `user` onto `event`, refusing when a capacity
75 /// cap is set and every seat is taken. Someone already listed gets their75 /// cap is set and every seat is taken. Someone already listed gets their
76 /// existing row back untouched — a true no-op that never counts against76 /// existing row back untouched — a true no-op that never counts against
77 /// the cap and never rewrites who placed them. The whole check-then-write77 /// the cap and never rewrites who placed them. The whole check-then-write
78- /// runs under [`REGISTER_LOCK`], so a full event never over-admits.78+ /// runs under [`REGISTER_LOCK`], and the gate + cap are re-derived from a
79+ /// fresh event read under that lock, so neither a racing registration nor
80+ /// a concurrent capacity/audience/schedule PATCH can over-admit.
79 pub async fn register(81 pub async fn register(
80 event: &EventId,82 event: &EventId,
81 user: &UserId,83 user: &UserId,
82 registered_by: &UserId,84 registered_by: &UserId,
83- capacity: Option<i64>,
84 db: &Database,85 db: &Database,
85 ) -> Result<Registration, AppError> {86 ) -> Result<Registration, AppError> {
86 let _guard = REGISTER_LOCK.lock().await;87 let _guard = REGISTER_LOCK.lock().await;
87 if let Some(existing) = Self::read_for_user(event, user, db).await? {88 if let Some(existing) = Self::read_for_user(event, user, db).await? {
88 return Ok(existing);89 return Ok(existing);
89 }90 }
91+ let capacity = Event::read(event, db)
92+ .await?
93+ .ok_or(AppError::NotFound)?
94+ .registration_capacity()?;
90 if let Some(capacity) = capacity95 if let Some(capacity) = capacity
91 && Self::list_for_event(event, db).await?.len() as i64 >= capacity96 && Self::list_for_event(event, db).await?.len() as i64 >= capacity
92 {97 {
src/web/events.rsmodified+5 -27
@@ -654,29 +654,6 @@ struct RegistrationResponse {
654 registered_by: PersonRef,654 registered_by: PersonRef,
655 }655 }
656 656
657-/// The shared gate for touching a signup list: the event must carry the
658-/// registration audience, and the list must still be open — it closes the
659-/// moment the event starts, or, for an ends_at-only event (a pure signup
660-/// deadline), the moment that end passes (a truly timeless event never
661-/// closes). Returns the seat cap for the register path.
662-fn check_registration_open(event: &Event) -> Result<Option<i64>, AppError> {
663- let EventAudience::Registration { capacity } = event.get_audience() else {
664- return Err(AppError::Validation(ValidationError::Invalid {
665- field: "audience",
666- reason: "this event does not take registrations",
667- }));
668- };
669- // ends_at can't precede starts_at, so when both exist starts_at governs.
670- if let Some(closes_at) = event.get_starts_at().or(event.get_ends_at())
671- && Timestamp::now().as_millis() >= closes_at.as_millis()
672- {
673- return Err(AppError::Conflict(
674- "registration closed — the event has started or ended",
675- ));
676- }
677- Ok(*capacity)
678-}
679-
680 /// Put a user on a registration-audience event's signup list. Requires657 /// Put a user on a registration-audience event's signup list. Requires
681 /// teacher+. `user_id` must name a student — students are placed by staff and658 /// teacher+. `user_id` must name a student — students are placed by staff and
682 /// never register themselves; omit it to take a seat yourself (staff659 /// never register themselves; omit it to take a seat yourself (staff
@@ -710,7 +687,9 @@ async fn register(
710 let event = Event::read(&event_id, &st.db)687 let event = Event::read(&event_id, &st.db)
711 .await?688 .await?
712 .ok_or(AppError::NotFound)?;689 .ok_or(AppError::NotFound)?;
713- let capacity = check_registration_open(&event)?;690+ // Fast-fail gate; the authoritative re-check runs inside
691+ // `Registration::register` under its lock.
692+ event.registration_capacity()?;
714 693
715 let target = match req.user_id {694 let target = match req.user_id {
716 Some(ref key) => UserId::from_key(key),695 Some(ref key) => UserId::from_key(key),
@@ -729,8 +708,7 @@ async fn register(
729 ));708 ));
730 }709 }
731 710
732- let registration =711+ let registration = Registration::register(&event_id, &target, user.get_id(), &st.db).await?;
733- Registration::register(&event_id, &target, user.get_id(), capacity, &st.db).await?;
734 // Resolve from the row, not the request: a re-register returns the712 // Resolve from the row, not the request: a re-register returns the
735 // existing seat, whose registered_by is the *original* placer — someone713 // existing seat, whose registered_by is the *original* placer — someone
736 // the {target, caller} pair may not contain.714 // the {target, caller} pair may not contain.
@@ -781,7 +759,7 @@ async fn unregister(
781 let event = Event::read(&event_id, &st.db)759 let event = Event::read(&event_id, &st.db)
782 .await?760 .await?
783 .ok_or(AppError::NotFound)?;761 .ok_or(AppError::NotFound)?;
784- check_registration_open(&event)?;762+ event.registration_capacity()?;
785 763
786 let target = UserId::from_key(&target);764 let target = UserId::from_key(&target);
787 // A deleted account's leftover seat is fair game for any teacher+; a765 // A deleted account's leftover seat is fair game for any teacher+; a