Six correctness holes from full-code audit
Browse files at this commitecbd55004d4a34f33c596115ff75a955f4b63956Parent: 9b09fd1- fix
- six correctness holes from full-code audit
8 changed files +205 -56
- README.md +4 -2
- src/domain/exam.rs +18 -13
- src/domain/exam_attempt.rs +10 -2
- src/domain/note_file.rs +20 -2
- src/domain/work_entry.rs +34 -20
- src/web/events.rs +24 -10
- src/web/notes.rs +3 -6
- tests/integration.rs +92 -1
README.mdmodified+4 -2
| @@ -13,7 +13,8 @@ present / absent / late / excused (students never self-mark), and a **roster | |||
| 13 | report** shows who was expected and who missed. Registration lists fill seat | 13 | report** shows who was expected and who missed. Registration lists fill seat |
| 14 | by seat: teachers register students (never the other way round), staff | 14 | by seat: teachers register students (never the other way round), staff |
| 15 | register only themselves, an optional `capacity` caps the seats, and the list | 15 | register only themselves, an optional `capacity` caps the seats, and the list |
| 16 | -closes the moment the event starts. Every event stays visible to everyone — | 16 | +closes the moment the event starts (or, for an event with only an end time — |
| 17 | +a pure signup deadline — the moment that end passes). Every event stays visible to everyone — | ||
| 17 | the audience is a roster, not a wall. Marks are course-shaped | 18 | the audience is a roster, not a wall. Marks are course-shaped |
| 18 | (Google Classroom style): a teacher creates a course — kind **`course`** (a | 19 | (Google Classroom style): a teacher creates a course — kind **`course`** (a |
| 19 | regular class) or **`study`** (a supervised study session — *etüt*; same | 20 | regular class) or **`study`** (a supervised study session — *etüt*; same |
| @@ -423,7 +424,8 @@ A registration list fills through `POST /events/{id}/register`: teachers place | |||
| 423 | students (a student never registers, not even themselves) and take seats only | 424 | students (a student never registers, not even themselves) and take seats only |
| 424 | for themselves — registering another staff member is refused. Re-registering | 425 | for themselves — registering another staff member is refused. Re-registering |
| 425 | someone is a no-op, a full list is a `409`, and the list freezes the moment | 426 | someone is a no-op, a full list is a `409`, and the list freezes the moment |
| 426 | -the event starts (register and unregister both). Signup rows survive an | 427 | +the event starts — or, when only `ends_at` is set (a pure signup deadline), |
| 428 | +the moment it passes (register and unregister both). Signup rows survive an | ||
| 427 | audience switch inertly and resurface if the event returns to the registration | 429 | audience switch inertly and resurface if the event returns to the registration |
| 428 | kind; deleting the event deletes them. Pre-existing hand-picked (`users`) | 430 | kind; deleting the event deletes them. Pre-existing hand-picked (`users`) |
| 429 | audiences convert on boot: each listed user becomes a signup row credited to | 431 | audiences convert on boot: each listed user becomes a signup row credited to |
src/domain/exam.rsmodified+18 -13
| @@ -429,20 +429,25 @@ impl Exam { | |||
| 429 | } | 429 | } |
| 430 | 430 | ||
| 431 | /// Delete the exam and cascade-remove its result, attempt, question, and | 431 | /// Delete the exam and cascade-remove its result, attempt, question, and |
| 432 | - /// answer rows. | 432 | + /// answer rows — all in one transaction, so a failure can't leave an |
| 433 | + /// emptied-out exam shell behind. | ||
| 433 | pub async fn delete(self, db: &Database) -> Result<Exam, AppError> { | 434 | pub async fn delete(self, db: &Database) -> Result<Exam, AppError> { |
| 434 | - db.query( | 435 | + let mut result = db |
| 435 | - "BEGIN TRANSACTION; | 436 | + .query( |
| 436 | - DELETE exam_result WHERE exam = $ex; | 437 | + "BEGIN TRANSACTION; |
| 437 | - DELETE exam_attempt WHERE exam = $ex; | 438 | + DELETE exam_result WHERE exam = $ex; |
| 438 | - DELETE exam_answer WHERE exam = $ex; | 439 | + DELETE exam_attempt WHERE exam = $ex; |
| 439 | - DELETE exam_question WHERE exam = $ex; | 440 | + DELETE exam_answer WHERE exam = $ex; |
| 440 | - COMMIT TRANSACTION;", | 441 | + DELETE exam_question WHERE exam = $ex; |
| 441 | - ) | 442 | + DELETE $ex RETURN BEFORE; |
| 442 | - .bind(("ex", self.id.record())) | 443 | + COMMIT TRANSACTION;", |
| 443 | - .await? | 444 | + ) |
| 444 | - .check()?; | 445 | + .bind(("ex", self.id.record())) |
| 445 | - let deleted: Option<Exam> = db.delete(self.id.record()).await?; | 446 | + .await? |
| 447 | + .check()?; | ||
| 448 | + // Statement slots count BEGIN and the child deletes: the exam's own | ||
| 449 | + // DELETE is slot 5. | ||
| 450 | + let deleted: Option<Exam> = result.take::<Vec<Exam>>(5)?.into_iter().next(); | ||
| 446 | deleted.ok_or(AppError::NotFound) | 451 | deleted.ok_or(AppError::NotFound) |
| 447 | } | 452 | } |
| 448 | } | 453 | } |
src/domain/exam_attempt.rsmodified+10 -2
| @@ -197,9 +197,17 @@ impl ExamAttempt { | |||
| 197 | match created { | 197 | match created { |
| 198 | Ok(Some(created)) => Ok((created, true)), | 198 | Ok(Some(created)) => Ok((created, true)), |
| 199 | Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())), | 199 | Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())), |
| 200 | + // Only a still-running row proves the loss was a double-start | ||
| 201 | + // collision (the winner's fresh sitting); a terminal or missing | ||
| 202 | + // latest means the create genuinely failed — surface that instead | ||
| 203 | + // of passing a finished sitting off as a resume. | ||
| 200 | Err(err) => match Self::read_latest_for_user(exam.get_id(), user, db).await? { | 204 | Err(err) => match Self::read_latest_for_user(exam.get_id(), user, db).await? { |
| 201 | - Some(existing) => Ok((existing, false)), | 205 | + Some(existing) |
| 202 | - None => Err(err.into()), | 206 | + if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress => |
| 207 | + { | ||
| 208 | + Ok((existing, false)) | ||
| 209 | + } | ||
| 210 | + _ => Err(err.into()), | ||
| 203 | }, | 211 | }, |
| 204 | } | 212 | } |
| 205 | } | 213 | } |
src/domain/note_file.rsmodified+20 -2
| @@ -6,13 +6,20 @@ | |||
| 6 | //! before blob on delete); this module owns the rows. | 6 | //! before blob on delete); this module owns the rows. |
| 7 | 7 | ||
| 8 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 8 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 9 | +use tokio::sync::Mutex; | ||
| 9 | use ulid::Ulid; | 10 | use ulid::Ulid; |
| 10 | 11 | ||
| 11 | -use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN}; | 12 | +use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, MAX_NOTE_FILES}; |
| 12 | use crate::database::{Database, NOTE_FILE_TABLE}; | 13 | use crate::database::{Database, NOTE_FILE_TABLE}; |
| 13 | use crate::domain::note::NoteId; | 14 | use crate::domain::note::NoteId; |
| 14 | use crate::error::{AppError, ValidationError}; | 15 | use crate::error::{AppError, ValidationError}; |
| 15 | 16 | ||
| 17 | +/// Serializes the files-per-note cap check against the insert (see | ||
| 18 | +/// [`NoteFile::insert`]). The database is embedded — this process is the only | ||
| 19 | +/// writer — so one process-wide lock is sufficient. | ||
| 20 | +// ponytail: global lock, per-note locks if uploads ever see real contention. | ||
| 21 | +static FILE_CAP_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 22 | + | ||
| 16 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 23 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 17 | pub struct NoteFileId(RecordId); | 24 | pub struct NoteFileId(RecordId); |
| 18 | 25 | ||
| @@ -148,8 +155,19 @@ impl NoteFile { | |||
| 148 | self.size | 155 | self.size |
| 149 | } | 156 | } |
| 150 | 157 | ||
| 151 | - /// Persist the row assembled by [`Self::new`]. | 158 | + /// Persist the row assembled by [`Self::new`], refusing once its note |
| 159 | + /// already holds [`MAX_NOTE_FILES`]. The count-then-create runs under | ||
| 160 | + /// [`FILE_CAP_LOCK`] — a `BEGIN…COMMIT` can't enforce the cap because | ||
| 161 | + /// SurrealDB doesn't conflict-check a cross-record count against a | ||
| 162 | + /// concurrent insert (write-skew), the same story as | ||
| 163 | + /// `Registration::register`. | ||
| 152 | pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> { | 164 | pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> { |
| 165 | + let _guard = FILE_CAP_LOCK.lock().await; | ||
| 166 | + if Self::list_for(&self.note, db).await?.len() >= MAX_NOTE_FILES { | ||
| 167 | + return Err(AppError::Conflict( | ||
| 168 | + "the note already holds the maximum of 10 files — delete one first", | ||
| 169 | + )); | ||
| 170 | + } | ||
| 153 | let created: Option<NoteFile> = db.create(self.id.record()).content(self).await?; | 171 | let created: Option<NoteFile> = db.create(self.id.record()).content(self).await?; |
| 154 | created.ok_or_else(|| AppError::Internal("failed to create note file".into())) | 172 | created.ok_or_else(|| AppError::Internal("failed to create note file".into())) |
| 155 | } | 173 | } |
src/domain/work_entry.rsmodified+34 -20
| @@ -99,29 +99,43 @@ impl WorkEntry { | |||
| 99 | .ok_or(AppError::Conflict("already checked in — check out first")) | 99 | .ok_or(AppError::Conflict("already checked in — check out first")) |
| 100 | } | 100 | } |
| 101 | 101 | ||
| 102 | - /// Close `user`'s open stint. The `DELETE .. RETURN BEFORE` is an atomic | 102 | + /// Close `user`'s open stint: atomically take the open row and re-file it |
| 103 | - /// take: of two racing check-outs exactly one receives the row (the other | 103 | + /// under a ULID id, freeing the open slot for the next check-in. Take and |
| 104 | - /// gets the conflict). The closed stint is then re-filed under a ULID id, | 104 | + /// re-file share one transaction — a failed re-file rolls the take back, |
| 105 | - /// freeing the open slot for the next check-in. | 105 | + /// so a stint can never vanish half-closed. Of two racing check-outs |
| 106 | + /// exactly one receives the row (the other gets the conflict). | ||
| 106 | pub async fn check_out(user: &UserId, db: &Database) -> Result<WorkEntry, AppError> { | 107 | pub async fn check_out(user: &UserId, db: &Database) -> Result<WorkEntry, AppError> { |
| 107 | let mut result = db | 108 | let mut result = db |
| 108 | - .query("DELETE $open RETURN BEFORE") | 109 | + .query( |
| 110 | + "BEGIN TRANSACTION; | ||
| 111 | + LET $before = (DELETE $open RETURN BEFORE); | ||
| 112 | + IF array::len($before) = 0 { THROW 'not_checked_in' }; | ||
| 113 | + CREATE $closed CONTENT { | ||
| 114 | + user: $before[0].user, | ||
| 115 | + check_in: $before[0].check_in, | ||
| 116 | + check_out: $out, | ||
| 117 | + }; | ||
| 118 | + COMMIT TRANSACTION;", | ||
| 119 | + ) | ||
| 109 | .bind(("open", WorkEntryId::open_for(user).record())) | 120 | .bind(("open", WorkEntryId::open_for(user).record())) |
| 110 | - .await? | 121 | + .bind(("closed", WorkEntryId::generate().record())) |
| 111 | - .check()?; | 122 | + .bind(("out", Timestamp::now())) |
| 112 | - let open = result | 123 | + .await?; |
| 113 | - .take::<Vec<WorkEntry>>(0)? | 124 | + // An aborted transaction errors *every* slot, most with a generic |
| 114 | - .into_iter() | 125 | + // "not executed" — only the THROW's own slot names the reason, so scan |
| 115 | - .next() | 126 | + // them all for the marker instead of trusting the first. |
| 116 | - .ok_or(AppError::Conflict("not checked in"))?; | 127 | + let mut errors = result.take_errors(); |
| 117 | - | 128 | + if errors |
| 118 | - let closed = WorkEntry { | 129 | + .values() |
| 119 | - id: WorkEntryId::generate(), | 130 | + .any(|error| error.to_string().contains("not_checked_in")) |
| 120 | - user: open.user, | 131 | + { |
| 121 | - check_in: open.check_in, | 132 | + return Err(AppError::Conflict("not checked in")); |
| 122 | - check_out: Some(Timestamp::now()), | 133 | + } |
| 123 | - }; | 134 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { |
| 124 | - let saved: Option<WorkEntry> = db.create(closed.id.record()).content(closed).await?; | 135 | + return Err(error.into()); |
| 136 | + } | ||
| 137 | + // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3. | ||
| 138 | + let saved: Option<WorkEntry> = result.take::<Vec<WorkEntry>>(3)?.into_iter().next(); | ||
| 125 | saved.ok_or_else(|| AppError::Internal("failed to close work entry".into())) | 139 | saved.ok_or_else(|| AppError::Internal("failed to close work entry".into())) |
| 126 | } | 140 | } |
| 127 | 141 | ||
src/web/events.rsmodified+24 -10
| @@ -656,8 +656,9 @@ struct RegistrationResponse { | |||
| 656 | 656 | ||
| 657 | /// The shared gate for touching a signup list: the event must carry the | 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 | 658 | /// registration audience, and the list must still be open — it closes the |
| 659 | -/// moment the event starts (a timeless event never closes). Returns the seat | 659 | +/// moment the event starts, or, for an ends_at-only event (a pure signup |
| 660 | -/// cap for the register path. | 660 | +/// deadline), the moment that end passes (a truly timeless event never |
| 661 | +/// closes). Returns the seat cap for the register path. | ||
| 661 | fn check_registration_open(event: &Event) -> Result<Option<i64>, AppError> { | 662 | fn check_registration_open(event: &Event) -> Result<Option<i64>, AppError> { |
| 662 | let EventAudience::Registration { capacity } = event.get_audience() else { | 663 | let EventAudience::Registration { capacity } = event.get_audience() else { |
| 663 | return Err(AppError::Validation(ValidationError::Invalid { | 664 | return Err(AppError::Validation(ValidationError::Invalid { |
| @@ -665,11 +666,12 @@ fn check_registration_open(event: &Event) -> Result<Option<i64>, AppError> { | |||
| 665 | reason: "this event does not take registrations", | 666 | reason: "this event does not take registrations", |
| 666 | })); | 667 | })); |
| 667 | }; | 668 | }; |
| 668 | - if let Some(starts_at) = event.get_starts_at() | 669 | + // ends_at can't precede starts_at, so when both exist starts_at governs. |
| 669 | - && Timestamp::now().as_millis() >= starts_at.as_millis() | 670 | + if let Some(closes_at) = event.get_starts_at().or(event.get_ends_at()) |
| 671 | + && Timestamp::now().as_millis() >= closes_at.as_millis() | ||
| 670 | { | 672 | { |
| 671 | return Err(AppError::Conflict( | 673 | return Err(AppError::Conflict( |
| 672 | - "registration closed when the event started", | 674 | + "registration closed — the event has started or ended", |
| 673 | )); | 675 | )); |
| 674 | } | 676 | } |
| 675 | Ok(*capacity) | 677 | Ok(*capacity) |
| @@ -680,7 +682,8 @@ fn check_registration_open(event: &Event) -> Result<Option<i64>, AppError> { | |||
| 680 | /// never register themselves; omit it to take a seat yourself (staff | 682 | /// never register themselves; omit it to take a seat yourself (staff |
| 681 | /// self-serve, so registering another teacher/manager is refused). Registering | 683 | /// self-serve, so registering another teacher/manager is refused). Registering |
| 682 | /// the same person twice is a no-op returning the existing seat. The list | 684 | /// the same person twice is a no-op returning the existing seat. The list |
| 683 | -/// closes when the event starts and refuses to grow past `capacity`. | 685 | +/// closes when the event starts (or its ends_at-only deadline passes) and |
| 686 | +/// refuses to grow past `capacity`. | ||
| 684 | #[utoipa::path( | 687 | #[utoipa::path( |
| 685 | post, | 688 | post, |
| 686 | path = "/{id}/register", | 689 | path = "/{id}/register", |
| @@ -694,7 +697,7 @@ fn check_registration_open(event: &Event) -> Result<Option<i64>, AppError> { | |||
| 694 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 697 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 695 | (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), | 698 | (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), |
| 696 | (status = 404, description = "Event not found", body = ErrorResponse), | 699 | (status = 404, description = "Event not found", body = ErrorResponse), |
| 697 | - (status = 409, description = "The event is full, or it already started", body = ErrorResponse), | 700 | + (status = 409, description = "The event is full, or it already started or ended", body = ErrorResponse), |
| 698 | ), | 701 | ), |
| 699 | )] | 702 | )] |
| 700 | async fn register( | 703 | async fn register( |
| @@ -728,7 +731,17 @@ async fn register( | |||
| 728 | 731 | ||
| 729 | let registration = | 732 | let registration = |
| 730 | Registration::register(&event_id, &target, user.get_id(), capacity, &st.db).await?; | 733 | Registration::register(&event_id, &target, user.get_id(), capacity, &st.db).await?; |
| 731 | - let people = PersonRef::map_of(&[&target_user, &user]); | 734 | + // Resolve from the row, not the request: a re-register returns the |
| 735 | + // existing seat, whose registered_by is the *original* placer — someone | ||
| 736 | + // the {target, caller} pair may not contain. | ||
| 737 | + let people = person_map( | ||
| 738 | + [ | ||
| 739 | + registration.get_user().clone(), | ||
| 740 | + registration.get_registered_by().clone(), | ||
| 741 | + ], | ||
| 742 | + &st.db, | ||
| 743 | + ) | ||
| 744 | + .await?; | ||
| 732 | Ok(Json(RegistrationResponse { | 745 | Ok(Json(RegistrationResponse { |
| 733 | event: registration.get_event().key().to_string(), | 746 | event: registration.get_event().key().to_string(), |
| 734 | user: PersonRef::resolve(&people, registration.get_user()), | 747 | user: PersonRef::resolve(&people, registration.get_user()), |
| @@ -739,7 +752,8 @@ async fn register( | |||
| 739 | /// Take a user off the signup list — the register rules mirrored: teacher+, | 752 | /// Take a user off the signup list — the register rules mirrored: teacher+, |
| 740 | /// students' seats or your own (another staff member's seat only if their | 753 | /// students' seats or your own (another staff member's seat only if their |
| 741 | /// account no longer exists), and only while the list is open (the event | 754 | /// account no longer exists), and only while the list is open (the event |
| 742 | -/// hasn't started). Attendance already marked stays recorded. | 755 | +/// hasn't started or, ends_at-only, passed). Attendance already marked stays |
| 756 | +/// recorded. | ||
| 743 | #[utoipa::path( | 757 | #[utoipa::path( |
| 744 | delete, | 758 | delete, |
| 745 | path = "/{id}/register/{user}", | 759 | path = "/{id}/register/{user}", |
| @@ -755,7 +769,7 @@ async fn register( | |||
| 755 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 769 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 756 | (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), | 770 | (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), |
| 757 | (status = 404, description = "Event not found, or the user holds no seat", body = ErrorResponse), | 771 | (status = 404, description = "Event not found, or the user holds no seat", body = ErrorResponse), |
| 758 | - (status = 409, description = "The event already started", body = ErrorResponse), | 772 | + (status = 409, description = "The event already started or ended", body = ErrorResponse), |
| 759 | ), | 773 | ), |
| 760 | )] | 774 | )] |
| 761 | async fn unregister( | 775 | async fn unregister( |
src/web/notes.rsmodified+3 -6
| @@ -11,7 +11,7 @@ use utoipa::ToSchema; | |||
| 11 | use utoipa_axum::router::OpenApiRouter; | 11 | use utoipa_axum::router::OpenApiRouter; |
| 12 | use utoipa_axum::routes; | 12 | use utoipa_axum::routes; |
| 13 | 13 | ||
| 14 | -use crate::constant::{MAX_MAX_FILE_BYTES, MAX_NOTE_FILES, UPLOAD_BODY_OVERHEAD_BYTES}; | 14 | +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 15 | use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; | 15 | use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; |
| 16 | use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; | 16 | use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; |
| 17 | use crate::domain::settings::Settings; | 17 | use crate::domain::settings::Settings; |
| @@ -283,11 +283,8 @@ async fn upload_file( | |||
| 283 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | 283 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| 284 | .await? | 284 | .await? |
| 285 | .ok_or(AppError::NotFound)?; | 285 | .ok_or(AppError::NotFound)?; |
| 286 | - if NoteFile::list_for(note.get_id(), &st.db).await?.len() >= MAX_NOTE_FILES { | 286 | + // The 10-file cap is enforced inside `NoteFile::insert` (count and create |
| 287 | - return Err(AppError::Conflict( | 287 | + // under one lock) — checking it here too would just race. |
| 288 | - "the note already holds the maximum of 10 files — delete one first", | ||
| 289 | - )); | ||
| 290 | - } | ||
| 291 | let limit = Settings::load(&st.db).await?.get_max_file_bytes(); | 288 | let limit = Settings::load(&st.db).await?.get_max_file_bytes(); |
| 292 | 289 | ||
| 293 | let mut field = loop { | 290 | let mut field = loop { |
tests/integration.rsmodified+92 -1
| @@ -717,6 +717,59 @@ async fn note_file_count_is_capped() { | |||
| 717 | assert_eq!(retry.status, StatusCode::CREATED); | 717 | assert_eq!(retry.status, StatusCode::CREATED); |
| 718 | } | 718 | } |
| 719 | 719 | ||
| 720 | +/// Regression: the 10-file cap was a bare count-then-write — concurrent | ||
| 721 | +/// uploads all read the same pre-count and pushed a note past the cap (the | ||
| 722 | +/// same write-skew as the event-capacity over-admit; SurrealDB transactions | ||
| 723 | +/// don't conflict-check a cross-record count against an insert). The insert | ||
| 724 | +/// now recounts under a lock, so the outcome is race-order independent: | ||
| 725 | +/// exactly enough uploads win to land on the cap, the rest get the same 409 | ||
| 726 | +/// as a sequential over-fill. | ||
| 727 | +#[tokio::test] | ||
| 728 | +async fn concurrent_uploads_never_exceed_the_file_cap() { | ||
| 729 | + let app = mem_app().await; | ||
| 730 | + let ali = login(&app, "ali").await; | ||
| 731 | + let note = create_note(&app, &ali, "contested").await; | ||
| 732 | + | ||
| 733 | + for i in 0..8 { | ||
| 734 | + let up = common::upload_file(&app, &ali, ¬e, &format!("f{i}.txt"), "", b"x").await; | ||
| 735 | + assert_eq!(up.status, StatusCode::CREATED, "seed file {i}"); | ||
| 736 | + } | ||
| 737 | + | ||
| 738 | + // Four racers for the two remaining slots. | ||
| 739 | + let results = tokio::join!( | ||
| 740 | + common::upload_file(&app, &ali, ¬e, "r0.txt", "", b"x"), | ||
| 741 | + common::upload_file(&app, &ali, ¬e, "r1.txt", "", b"x"), | ||
| 742 | + common::upload_file(&app, &ali, ¬e, "r2.txt", "", b"x"), | ||
| 743 | + common::upload_file(&app, &ali, ¬e, "r3.txt", "", b"x"), | ||
| 744 | + ); | ||
| 745 | + let statuses = [ | ||
| 746 | + results.0.status, | ||
| 747 | + results.1.status, | ||
| 748 | + results.2.status, | ||
| 749 | + results.3.status, | ||
| 750 | + ]; | ||
| 751 | + for status in statuses { | ||
| 752 | + assert!( | ||
| 753 | + status == StatusCode::CREATED || status == StatusCode::CONFLICT, | ||
| 754 | + "a lost cap race must be a 409, got {status}" | ||
| 755 | + ); | ||
| 756 | + } | ||
| 757 | + | ||
| 758 | + let list = send( | ||
| 759 | + &app, | ||
| 760 | + "GET", | ||
| 761 | + &format!("/notes/{note}/files"), | ||
| 762 | + Some(&ali), | ||
| 763 | + None, | ||
| 764 | + ) | ||
| 765 | + .await; | ||
| 766 | + assert_eq!( | ||
| 767 | + common::total(&list.body), | ||
| 768 | + 10, | ||
| 769 | + "the cap must hold exactly under concurrency, statuses={statuses:?}" | ||
| 770 | + ); | ||
| 771 | +} | ||
| 772 | + | ||
| 720 | #[tokio::test] | 773 | #[tokio::test] |
| 721 | async fn note_file_upload_validation() { | 774 | async fn note_file_upload_validation() { |
| 722 | let app = mem_app().await; | 775 | let app = mem_app().await; |
| @@ -3467,6 +3520,13 @@ async fn re_registering_returns_the_seat_untouched() { | |||
| 3467 | second.body["registered_by"]["id"], ali_id, | 3520 | second.body["registered_by"]["id"], ali_id, |
| 3468 | "re-registering must not rewrite who placed the student" | 3521 | "re-registering must not rewrite who placed the student" |
| 3469 | ); | 3522 | ); |
| 3523 | + // Regression: the response used to resolve people only from {target, | ||
| 3524 | + // caller}, so the original registrar degraded to a bare ULID username. | ||
| 3525 | + assert_eq!( | ||
| 3526 | + second.body["registered_by"]["username"], "ali", | ||
| 3527 | + "the original registrar must resolve to a person, not a bare id" | ||
| 3528 | + ); | ||
| 3529 | + assert_eq!(second.body["user"]["username"], "veli"); | ||
| 3470 | } | 3530 | } |
| 3471 | 3531 | ||
| 3472 | /// Regression: the capacity check used to run inside a `BEGIN…COMMIT` whose | 3532 | /// Regression: the capacity check used to run inside a `BEGIN…COMMIT` whose |
| @@ -3580,10 +3640,41 @@ async fn event_registration_closes_at_start() { | |||
| 3580 | .await; | 3640 | .await; |
| 3581 | assert_eq!(res.status, StatusCode::CONFLICT, "unregister freezes too"); | 3641 | assert_eq!(res.status, StatusCode::CONFLICT, "unregister freezes too"); |
| 3582 | 3642 | ||
| 3583 | - // A future or timeless event keeps its list open. | 3643 | + // Regression: an ends_at-only event (a pure signup deadline) used to stay |
| 3644 | + // open forever — the gate read starts_at alone. Ended 30s ago: inside the | ||
| 3645 | + // creation grace, but the list is closed. | ||
| 3646 | + let res = send( | ||
| 3647 | + &app, | ||
| 3648 | + "POST", | ||
| 3649 | + "/events", | ||
| 3650 | + Some(&ali), | ||
| 3651 | + Some(json!({ "title": "deadline passed", "ends_at": now - 30_000, | ||
| 3652 | + "audience": { "kind": "registration" } })), | ||
| 3653 | + ) | ||
| 3654 | + .await; | ||
| 3655 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 3656 | + let ev = id_of(&res.body); | ||
| 3657 | + let res = send( | ||
| 3658 | + &app, | ||
| 3659 | + "POST", | ||
| 3660 | + &format!("/events/{ev}/register"), | ||
| 3661 | + Some(&ali), | ||
| 3662 | + Some(json!({ "user_id": veli_id })), | ||
| 3663 | + ) | ||
| 3664 | + .await; | ||
| 3665 | + assert_eq!( | ||
| 3666 | + res.status, | ||
| 3667 | + StatusCode::CONFLICT, | ||
| 3668 | + "an event whose end has passed takes no signups" | ||
| 3669 | + ); | ||
| 3670 | + | ||
| 3671 | + // A future or timeless event keeps its list open — a future signup | ||
| 3672 | + // deadline (ends_at only) included. | ||
| 3584 | for body in [ | 3673 | for body in [ |
| 3585 | json!({ "title": "later", "starts_at": now + 3_600_000, | 3674 | json!({ "title": "later", "starts_at": now + 3_600_000, |
| 3586 | "audience": { "kind": "registration" } }), | 3675 | "audience": { "kind": "registration" } }), |
| 3676 | + json!({ "title": "deadline ahead", "ends_at": now + 3_600_000, | ||
| 3677 | + "audience": { "kind": "registration" } }), | ||
| 3587 | json!({ "title": "whenever", "audience": { "kind": "registration" } }), | 3678 | json!({ "title": "whenever", "audience": { "kind": "registration" } }), |
| 3588 | ] { | 3679 | ] { |
| 3589 | let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await; | 3680 | let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await; |