Authz holes and stale-read races from the bug hunt
Browse files at this commitde938d85f98b4ea12632b42b346ce4794fa7db8fParent: f4b3828- fix
- authz holes and stale-read races from the bug hunt
8 changed files +293 -43
- src/domain/message.rs +25 -4
- src/web/exams.rs +8 -4
- src/web/extractor.rs +20 -0
- src/web/messages.rs +17 -13
- src/web/mod.rs +14 -4
- src/web/notes.rs +19 -10
- src/web/users.rs +2 -1
- tests/integration.rs +188 -7
src/domain/message.rsmodified+25 -4
| @@ -267,11 +267,32 @@ impl Message { | ||
| 267 | 267 | .ok_or(AppError::NotFound) |
| 268 | 268 | } |
| 269 | 269 | |
| 270 | - /// Permanently drop `user`'s side. The row itself is removed once both | |
| 271 | - /// sides are gone — judged on the post-write row, so two concurrent | |
| 272 | - /// deletes can't leak an all-deleted row. | |
| 270 | + /// Permanently drop `user`'s side — only if that side currently sits in | |
| 271 | + /// the trash; the gate rides in the `UPDATE`'s `WHERE` so a concurrent | |
| 272 | + /// move back to the inbox can't slip past a check-then-act window. The | |
| 273 | + /// row itself is removed once both sides are gone — judged on the | |
| 274 | + /// post-write row, so two concurrent deletes can't leak an all-deleted | |
| 275 | + /// row. | |
| 273 | 276 | pub async fn delete_for(self, user: &UserId, db: &Database) -> Result<(), AppError> { |
| 274 | - let after = self.move_to(user, DELETED_FOLDER, db).await?; | |
| 277 | + let field = if self.is_sender(user) { | |
| 278 | + "sender_folder" | |
| 279 | + } else { | |
| 280 | + "recipient_folder" | |
| 281 | + }; | |
| 282 | + let mut result = db | |
| 283 | + .query(format!( | |
| 284 | + "UPDATE $id SET {field} = $deleted WHERE {field} = $trash RETURN AFTER" | |
| 285 | + )) | |
| 286 | + .bind(("id", self.id.record())) | |
| 287 | + .bind(("deleted", DELETED_FOLDER.to_string())) | |
| 288 | + .bind(("trash", "trash".to_string())) | |
| 289 | + .await? | |
| 290 | + .check()?; | |
| 291 | + let Some(after) = result.take::<Vec<Message>>(0)?.into_iter().next() else { | |
| 292 | + return Err(AppError::Conflict( | |
| 293 | + "only messages in the trash can be permanently deleted", | |
| 294 | + )); | |
| 295 | + }; | |
| 275 | 296 | if after.sender_folder == DELETED_FOLDER && after.recipient_folder == DELETED_FOLDER { |
| 276 | 297 | let _: Option<Message> = db.delete(after.id.record()).await?; |
| 277 | 298 | } |
src/web/exams.rsmodified+8 -4
| @@ -324,6 +324,11 @@ async fn update_exam( | ||
| 324 | 324 | Path(id): Path<String>, |
| 325 | 325 | Json(req): Json<UpdateExam>, |
| 326 | 326 | ) -> Result<Json<ExamResponse>, AppError> { |
| 327 | + // Take the writer lease before the row read: the merge defaults and the | |
| 328 | + // mode/draft gates below all judge this snapshot, so a publish or mode | |
| 329 | + // change landing between an unlocked read and the gates would be silently | |
| 330 | + // written back over. | |
| 331 | + let _guard = EXAM_LOCK.write().await; | |
| 327 | 332 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 328 | 333 | .await? |
| 329 | 334 | .ok_or(AppError::NotFound)?; |
| @@ -393,10 +398,9 @@ async fn update_exam( | ||
| 393 | 398 | // Switching sync <-> async <-> open (or back to unscheduled) would |
| 394 | 399 | // silently rewrite the deadline rules under students who already sat |
| 395 | 400 | // down; extending times, the attempt limit, and the rejoin door are the |
| 396 | - // supported live adjustments instead. Gate read and write share one | |
| 397 | - // writer lease of [`EXAM_LOCK`], so a first attempt can't land in the | |
| 398 | - // gap and leave a sat exam's mode flipped under it. | |
| 399 | - let _guard = EXAM_LOCK.write().await; | |
| 401 | + // supported live adjustments instead. Gate read and write share the | |
| 402 | + // handler-wide writer lease of [`EXAM_LOCK`], so a first attempt can't | |
| 403 | + // land in the gap and leave a sat exam's mode flipped under it. | |
| 400 | 404 | let mode_changed = |
| 401 | 405 | schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str); |
| 402 | 406 | if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? { |
src/web/extractor.rsmodified+20 -0
| @@ -54,6 +54,26 @@ where | ||
| 54 | 54 | } |
| 55 | 55 | } |
| 56 | 56 | |
| 57 | +/// Like [`CurrentUser`], but also requires at least the `student` role — | |
| 58 | +/// keeps the read-only `parent` role out of write-capable surfaces. | |
| 59 | +pub struct RequireStudent(pub User); | |
| 60 | + | |
| 61 | +impl<S> FromRequestParts<S> for RequireStudent | |
| 62 | +where | |
| 63 | + S: Send + Sync, | |
| 64 | + AppState: FromRef<S>, | |
| 65 | +{ | |
| 66 | + type Rejection = AppError; | |
| 67 | + | |
| 68 | + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | |
| 69 | + let user = authed_user(parts, state).await?; | |
| 70 | + if !user.get_role().at_least(Role::Student) { | |
| 71 | + return Err(AppError::Forbidden("requires student role or higher")); | |
| 72 | + } | |
| 73 | + Ok(RequireStudent(user)) | |
| 74 | + } | |
| 75 | +} | |
| 76 | + | |
| 57 | 77 | /// Like [`CurrentUser`], but also requires at least the `teacher` role. |
| 58 | 78 | /// Authenticated-but-under-privileged callers get `403`. |
| 59 | 79 | pub struct RequireTeacher(pub User); |
src/web/messages.rsmodified+17 -13
| @@ -110,7 +110,12 @@ async fn load_people(messages: &[Message], db: &Database) -> Result<People, AppE | ||
| 110 | 110 | let mut seen = HashSet::new(); |
| 111 | 111 | let ids: Vec<UserId> = messages |
| 112 | 112 | .iter() |
| 113 | - .flat_map(|message| [message.get_sender().clone(), message.get_recipient().clone()]) | |
| 113 | + .flat_map(|message| { | |
| 114 | + [ | |
| 115 | + message.get_sender().clone(), | |
| 116 | + message.get_recipient().clone(), | |
| 117 | + ] | |
| 118 | + }) | |
| 114 | 119 | .filter(|id| seen.insert(id.key().to_string())) |
| 115 | 120 | .collect(); |
| 116 | 121 | let users = User::list_by_ids(&ids, db).await?; |
| @@ -274,13 +279,12 @@ async fn update_message( | ||
| 274 | 279 | .await? |
| 275 | 280 | .ok_or(AppError::NotFound)?; |
| 276 | 281 | |
| 277 | - if let Some(read) = req.read { | |
| 278 | - if message.is_sender(user.get_id()) { | |
| 279 | - return Err(AppError::Forbidden( | |
| 280 | - "only the recipient can change the read flag", | |
| 281 | - )); | |
| 282 | - } | |
| 283 | - message = message.set_read(read, &st.db).await?; | |
| 282 | + // Validate the whole patch before touching the row: a rejected folder | |
| 283 | + // must not leave a half-applied read flag behind. | |
| 284 | + if req.read.is_some() && message.is_sender(user.get_id()) { | |
| 285 | + return Err(AppError::Forbidden( | |
| 286 | + "only the recipient can change the read flag", | |
| 287 | + )); | |
| 284 | 288 | } |
| 285 | 289 | if let Some(ref folder) = req.folder { |
| 286 | 290 | let allowed: &[&str] = if message.is_sender(user.get_id()) { |
| @@ -294,6 +298,11 @@ async fn update_message( | ||
| 294 | 298 | reason: "not a folder this side of the message can move to", |
| 295 | 299 | })); |
| 296 | 300 | } |
| 301 | + } | |
| 302 | + if let Some(read) = req.read { | |
| 303 | + message = message.set_read(read, &st.db).await?; | |
| 304 | + } | |
| 305 | + if let Some(ref folder) = req.folder { | |
| 297 | 306 | message = message.move_to(user.get_id(), folder, &st.db).await?; |
| 298 | 307 | } |
| 299 | 308 | |
| @@ -325,11 +334,6 @@ async fn delete_message( | ||
| 325 | 334 | let message = Message::read_for(&MessageId::from_key(&id), user.get_id(), &st.db) |
| 326 | 335 | .await? |
| 327 | 336 | .ok_or(AppError::NotFound)?; |
| 328 | - if message.folder_of(user.get_id()) != "trash" { | |
| 329 | - return Err(AppError::Conflict( | |
| 330 | - "only messages in the trash can be permanently deleted", | |
| 331 | - )); | |
| 332 | - } | |
| 333 | 337 | message.delete_for(user.get_id(), &st.db).await?; |
| 334 | 338 | Ok(StatusCode::NO_CONTENT) |
| 335 | 339 | } |
src/web/mod.rsmodified+14 -4
| @@ -28,7 +28,7 @@ pub use dto::{ | ||
| 28 | 28 | CourseResponse, ExamResponse, PersonRef, SessionResponse, SubjectResponse, UserResponse, |
| 29 | 29 | person_map, |
| 30 | 30 | }; |
| 31 | -pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher}; | |
| 31 | +pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher}; | |
| 32 | 32 | pub use page::{Page, PageParams, paginate}; |
| 33 | 33 | |
| 34 | 34 | use std::path::{Path as FsPath, PathBuf}; |
| @@ -50,8 +50,8 @@ use crate::error::{AppError, ValidationError}; | ||
| 50 | 50 | /// May `caller` read `target`'s per-student reports (marks, attendance, |
| 51 | 51 | /// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's |
| 52 | 52 | /// business); a parent may exactly when a `parent_link` row ties them to the |
| 53 | -/// target. Everyone else — students included — gets a 403 (self-reads go | |
| 54 | -/// through the `/me` endpoints). | |
| 53 | +/// target *and* the target still holds the student role. Everyone else — | |
| 54 | +/// students included — gets a 403 (self-reads go through the `/me` endpoints). | |
| 55 | 55 | pub(crate) async fn ensure_can_observe( |
| 56 | 56 | caller: &User, |
| 57 | 57 | target: &UserId, |
| @@ -60,7 +60,17 @@ pub(crate) async fn ensure_can_observe( | ||
| 60 | 60 | if caller.get_role().at_least(Role::Teacher) { |
| 61 | 61 | return Ok(()); |
| 62 | 62 | } |
| 63 | - if caller.get_role() == Role::Parent && ParentLink::exists(caller.get_id(), target, db).await? { | |
| 63 | + // The link row alone is not the grant: like stale enrollments, a link | |
| 64 | + // whose student side changed role (a sweep lost a race with link_student) | |
| 65 | + // must be inert, so the target's live role is re-read here. Missing or | |
| 66 | + // non-student targets fall through to the same 403 — a parent never gets | |
| 67 | + // an existence oracle. | |
| 68 | + if caller.get_role() == Role::Parent | |
| 69 | + && ParentLink::exists(caller.get_id(), target, db).await? | |
| 70 | + && User::read(target, db) | |
| 71 | + .await? | |
| 72 | + .is_some_and(|target| target.get_role() == Role::Student) | |
| 73 | + { | |
| 64 | 74 | return Ok(()); |
| 65 | 75 | } |
| 66 | 76 | Err(AppError::Forbidden( |
src/web/notes.rsmodified+19 -10
| @@ -16,7 +16,7 @@ use crate::error::{AppError, ErrorResponse}; | ||
| 16 | 16 | use crate::state::AppState; |
| 17 | 17 | |
| 18 | 18 | use super::{ |
| 19 | - CurrentUser, Page, PageParams, UploadFileForm, blob_path, paginate, read_upload, remove_blob, | |
| 19 | + Page, PageParams, RequireStudent, UploadFileForm, blob_path, paginate, read_upload, remove_blob, | |
| 20 | 20 | }; |
| 21 | 21 | |
| 22 | 22 | pub fn routes() -> OpenApiRouter<AppState> { |
| @@ -78,11 +78,12 @@ impl NoteResponse { | ||
| 78 | 78 | (status = 201, description = "Note created", body = NoteResponse), |
| 79 | 79 | (status = 400, description = "Invalid title or content", body = ErrorResponse), |
| 80 | 80 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 81 | + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | |
| 81 | 82 | ), |
| 82 | 83 | )] |
| 83 | 84 | async fn create( |
| 84 | 85 | State(st): State<AppState>, |
| 85 | - CurrentUser(user): CurrentUser, | |
| 86 | + RequireStudent(user): RequireStudent, | |
| 86 | 87 | Json(req): Json<CreateNote>, |
| 87 | 88 | ) -> Result<(StatusCode, Json<NoteResponse>), AppError> { |
| 88 | 89 | let title = NoteTitle::try_new(&req.title)?; |
| @@ -104,11 +105,12 @@ async fn create( | ||
| 104 | 105 | (status = 200, description = "A page of the user's notes (all of them when unpaged)", body = Page<NoteResponse>), |
| 105 | 106 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 106 | 107 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 108 | + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | |
| 107 | 109 | ), |
| 108 | 110 | )] |
| 109 | 111 | async fn list( |
| 110 | 112 | State(st): State<AppState>, |
| 111 | - CurrentUser(user): CurrentUser, | |
| 113 | + RequireStudent(user): RequireStudent, | |
| 112 | 114 | Query(page): Query<PageParams>, |
| 113 | 115 | ) -> Result<Json<Page<NoteResponse>>, AppError> { |
| 114 | 116 | let (limit, offset) = page.resolve()?; |
| @@ -131,12 +133,13 @@ async fn list( | ||
| 131 | 133 | responses( |
| 132 | 134 | (status = 200, description = "The note", body = NoteResponse), |
| 133 | 135 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 136 | + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | |
| 134 | 137 | (status = 404, description = "Not found", body = ErrorResponse), |
| 135 | 138 | ), |
| 136 | 139 | )] |
| 137 | 140 | async fn get_one( |
| 138 | 141 | State(st): State<AppState>, |
| 139 | - CurrentUser(user): CurrentUser, | |
| 142 | + RequireStudent(user): RequireStudent, | |
| 140 | 143 | Path(id): Path<String>, |
| 141 | 144 | ) -> Result<Json<NoteResponse>, AppError> { |
| 142 | 145 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| @@ -157,12 +160,13 @@ async fn get_one( | ||
| 157 | 160 | (status = 200, description = "Updated note", body = NoteResponse), |
| 158 | 161 | (status = 400, description = "Invalid title or content", body = ErrorResponse), |
| 159 | 162 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 163 | + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | |
| 160 | 164 | (status = 404, description = "Not found", body = ErrorResponse), |
| 161 | 165 | ), |
| 162 | 166 | )] |
| 163 | 167 | async fn update( |
| 164 | 168 | State(st): State<AppState>, |
| 165 | - CurrentUser(user): CurrentUser, | |
| 169 | + RequireStudent(user): RequireStudent, | |
| 166 | 170 | Path(id): Path<String>, |
| 167 | 171 | Json(req): Json<UpdateNote>, |
| 168 | 172 | ) -> Result<Json<NoteResponse>, AppError> { |
| @@ -193,12 +197,13 @@ async fn update( | ||
| 193 | 197 | responses( |
| 194 | 198 | (status = 204, description = "Deleted"), |
| 195 | 199 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 200 | + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | |
| 196 | 201 | (status = 404, description = "Not found", body = ErrorResponse), |
| 197 | 202 | ), |
| 198 | 203 | )] |
| 199 | 204 | async fn delete_one( |
| 200 | 205 | State(st): State<AppState>, |
| 201 | - CurrentUser(user): CurrentUser, | |
| 206 | + RequireStudent(user): RequireStudent, | |
| 202 | 207 | Path(id): Path<String>, |
| 203 | 208 | ) -> Result<StatusCode, AppError> { |
| 204 | 209 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| @@ -257,6 +262,7 @@ impl NoteFileResponse { | ||
| 257 | 262 | (status = 201, description = "File stored", body = NoteFileResponse), |
| 258 | 263 | (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse), |
| 259 | 264 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 265 | + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | |
| 260 | 266 | (status = 404, description = "Note not found", body = ErrorResponse), |
| 261 | 267 | (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse), |
| 262 | 268 | (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), |
| @@ -264,7 +270,7 @@ impl NoteFileResponse { | ||
| 264 | 270 | )] |
| 265 | 271 | async fn upload_file( |
| 266 | 272 | State(st): State<AppState>, |
| 267 | - CurrentUser(user): CurrentUser, | |
| 273 | + RequireStudent(user): RequireStudent, | |
| 268 | 274 | Path(id): Path<String>, |
| 269 | 275 | mut multipart: Multipart, |
| 270 | 276 | ) -> Result<(StatusCode, Json<NoteFileResponse>), AppError> { |
| @@ -307,12 +313,13 @@ async fn upload_file( | ||
| 307 | 313 | (status = 200, description = "A page of the note's files", body = Page<NoteFileResponse>), |
| 308 | 314 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 309 | 315 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 316 | + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | |
| 310 | 317 | (status = 404, description = "Note not found", body = ErrorResponse), |
| 311 | 318 | ), |
| 312 | 319 | )] |
| 313 | 320 | async fn list_files( |
| 314 | 321 | State(st): State<AppState>, |
| 315 | - CurrentUser(user): CurrentUser, | |
| 322 | + RequireStudent(user): RequireStudent, | |
| 316 | 323 | Path(id): Path<String>, |
| 317 | 324 | Query(page): Query<PageParams>, |
| 318 | 325 | ) -> Result<Json<Page<NoteFileResponse>>, AppError> { |
| @@ -343,12 +350,13 @@ async fn list_files( | ||
| 343 | 350 | responses( |
| 344 | 351 | (status = 200, description = "The file bytes", content_type = "application/octet-stream"), |
| 345 | 352 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 353 | + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | |
| 346 | 354 | (status = 404, description = "Note or file not found", body = ErrorResponse), |
| 347 | 355 | ), |
| 348 | 356 | )] |
| 349 | 357 | async fn download_file( |
| 350 | 358 | State(st): State<AppState>, |
| 351 | - CurrentUser(user): CurrentUser, | |
| 359 | + RequireStudent(user): RequireStudent, | |
| 352 | 360 | Path((id, file_id)): Path<(String, String)>, |
| 353 | 361 | ) -> Result<Response, AppError> { |
| 354 | 362 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| @@ -396,12 +404,13 @@ async fn download_file( | ||
| 396 | 404 | responses( |
| 397 | 405 | (status = 204, description = "Deleted"), |
| 398 | 406 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 407 | + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | |
| 399 | 408 | (status = 404, description = "Note or file not found", body = ErrorResponse), |
| 400 | 409 | ), |
| 401 | 410 | )] |
| 402 | 411 | async fn delete_file( |
| 403 | 412 | State(st): State<AppState>, |
| 404 | - CurrentUser(user): CurrentUser, | |
| 413 | + RequireStudent(user): RequireStudent, | |
| 405 | 414 | Path((id, file_id)): Path<(String, String)>, |
| 406 | 415 | ) -> Result<StatusCode, AppError> { |
| 407 | 416 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
src/web/users.rsmodified+2 -1
| @@ -454,7 +454,8 @@ async fn students_page( | ||
| 454 | 454 | /// Tie a student to a parent account. Admin only — family ties are school-office |
| 455 | 455 | /// records, like roles. `{id}` must hold the `parent` role and `user_id` the |
| 456 | 456 | /// `student` role; a parent may observe any number of students. Idempotent: |
| 457 | -/// linking the same pair again returns the existing tie. The tie grants the | |
| 457 | +/// linking the same pair again keeps the one tie (the `linked_by` stamp moves | |
| 458 | +/// to the latest linker, like re-enrolling). The tie grants the | |
| 458 | 459 | /// parent read access to the student's marks, attendance, and pomodoro reports |
| 459 | 460 | /// — nothing else, and never any write. |
| 460 | 461 | #[utoipa::path( |
tests/integration.rsmodified+188 -7
| @@ -11088,7 +11088,14 @@ async fn messages_flow_through_folders_per_side() { | ||
| 11088 | 11088 | .await; |
| 11089 | 11089 | assert_eq!(res.status, StatusCode::FORBIDDEN); |
| 11090 | 11090 | // `?read=` narrows; `total` on the filtered view is the unread badge. |
| 11091 | - let unread = send(&app, "GET", "/messages?folder=inbox&read=false&limit=1", Some(&hoca), None).await; | |
| 11091 | + let unread = send( | |
| 11092 | + &app, | |
| 11093 | + "GET", | |
| 11094 | + "/messages?folder=inbox&read=false&limit=1", | |
| 11095 | + Some(&hoca), | |
| 11096 | + None, | |
| 11097 | + ) | |
| 11098 | + .await; | |
| 11092 | 11099 | assert_eq!(unread.body["total"], 1); |
| 11093 | 11100 | let res = send( |
| 11094 | 11101 | &app, |
| @@ -11099,7 +11106,14 @@ async fn messages_flow_through_folders_per_side() { | ||
| 11099 | 11106 | ) |
| 11100 | 11107 | .await; |
| 11101 | 11108 | assert_eq!(res.status, StatusCode::OK); |
| 11102 | - let unread = send(&app, "GET", "/messages?folder=inbox&read=false&limit=1", Some(&hoca), None).await; | |
| 11109 | + let unread = send( | |
| 11110 | + &app, | |
| 11111 | + "GET", | |
| 11112 | + "/messages?folder=inbox&read=false&limit=1", | |
| 11113 | + Some(&hoca), | |
| 11114 | + None, | |
| 11115 | + ) | |
| 11116 | + .await; | |
| 11103 | 11117 | assert_eq!(unread.body["total"], 0); |
| 11104 | 11118 | let sent = send(&app, "GET", "/messages?folder=sent", Some(&ali), None).await; |
| 11105 | 11119 | assert_eq!(common::items(&sent.body)[0]["read"], true); |
| @@ -11129,7 +11143,14 @@ async fn messages_flow_through_folders_per_side() { | ||
| 11129 | 11143 | assert_eq!(common::items(&archive.body).len(), 1); |
| 11130 | 11144 | |
| 11131 | 11145 | // Permanent delete only from the trash; it never touches the other copy. |
| 11132 | - let res = send(&app, "DELETE", &format!("/messages/{msg_id}"), Some(&hoca), None).await; | |
| 11146 | + let res = send( | |
| 11147 | + &app, | |
| 11148 | + "DELETE", | |
| 11149 | + &format!("/messages/{msg_id}"), | |
| 11150 | + Some(&hoca), | |
| 11151 | + None, | |
| 11152 | + ) | |
| 11153 | + .await; | |
| 11133 | 11154 | assert_eq!(res.status, StatusCode::CONFLICT); |
| 11134 | 11155 | send( |
| 11135 | 11156 | &app, |
| @@ -11141,7 +11162,14 @@ async fn messages_flow_through_folders_per_side() { | ||
| 11141 | 11162 | .await; |
| 11142 | 11163 | let trash = send(&app, "GET", "/messages?folder=trash", Some(&hoca), None).await; |
| 11143 | 11164 | assert_eq!(common::items(&trash.body).len(), 1); |
| 11144 | - let res = send(&app, "DELETE", &format!("/messages/{msg_id}"), Some(&hoca), None).await; | |
| 11165 | + let res = send( | |
| 11166 | + &app, | |
| 11167 | + "DELETE", | |
| 11168 | + &format!("/messages/{msg_id}"), | |
| 11169 | + Some(&hoca), | |
| 11170 | + None, | |
| 11171 | + ) | |
| 11172 | + .await; | |
| 11145 | 11173 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 11146 | 11174 | let trash = send(&app, "GET", "/messages?folder=trash", Some(&hoca), None).await; |
| 11147 | 11175 | assert_eq!(common::items(&trash.body).len(), 0); |
| @@ -11168,7 +11196,14 @@ async fn messages_flow_through_folders_per_side() { | ||
| 11168 | 11196 | Some(json!({ "folder": "trash" })), |
| 11169 | 11197 | ) |
| 11170 | 11198 | .await; |
| 11171 | - let res = send(&app, "DELETE", &format!("/messages/{msg_id}"), Some(&ali), None).await; | |
| 11199 | + let res = send( | |
| 11200 | + &app, | |
| 11201 | + "DELETE", | |
| 11202 | + &format!("/messages/{msg_id}"), | |
| 11203 | + Some(&ali), | |
| 11204 | + None, | |
| 11205 | + ) | |
| 11206 | + .await; | |
| 11172 | 11207 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 11173 | 11208 | let mut result = db |
| 11174 | 11209 | .query("SELECT VALUE id FROM message") |
| @@ -11219,7 +11254,11 @@ async fn messages_guard_parties_recipients_and_folders() { | ||
| 11219 | 11254 | .await; |
| 11220 | 11255 | assert_eq!(res.status, StatusCode::CREATED); |
| 11221 | 11256 | assert_eq!(res.body["sender_role"], "parent"); |
| 11222 | - assert_eq!(res.body["label"], serde_json::Value::Null, "no label sent, none stored"); | |
| 11257 | + assert_eq!( | |
| 11258 | + res.body["label"], | |
| 11259 | + serde_json::Value::Null, | |
| 11260 | + "no label sent, none stored" | |
| 11261 | + ); | |
| 11223 | 11262 | let msg_id = id_of(&res.body); |
| 11224 | 11263 | |
| 11225 | 11264 | // A third user is not a party: sees nothing, touches nothing. |
| @@ -11234,7 +11273,14 @@ async fn messages_guard_parties_recipients_and_folders() { | ||
| 11234 | 11273 | ) |
| 11235 | 11274 | .await; |
| 11236 | 11275 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11237 | - let res = send(&app, "DELETE", &format!("/messages/{msg_id}"), Some(&veli), None).await; | |
| 11276 | + let res = send( | |
| 11277 | + &app, | |
| 11278 | + "DELETE", | |
| 11279 | + &format!("/messages/{msg_id}"), | |
| 11280 | + Some(&veli), | |
| 11281 | + None, | |
| 11282 | + ) | |
| 11283 | + .await; | |
| 11238 | 11284 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 11239 | 11285 | |
| 11240 | 11286 | // Unknown folder names and oversized labels are refused. |
| @@ -11251,3 +11297,138 @@ async fn messages_guard_parties_recipients_and_folders() { | ||
| 11251 | 11297 | .await; |
| 11252 | 11298 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 11253 | 11299 | } |
| 11300 | + | |
| 11301 | +/// A patch that fails validation must not half-apply: the read flag stays | |
| 11302 | +/// untouched when the folder part of the same body is rejected. | |
| 11303 | +#[tokio::test] | |
| 11304 | +async fn messages_rejected_patch_leaves_no_side_effects() { | |
| 11305 | + let (app, db) = app_and_db().await; | |
| 11306 | + let ali = login(&app, "ali").await; | |
| 11307 | + let hoca = login_as(&app, &db, "hoca", "teacher").await; | |
| 11308 | + let hoca_id = me_id(&app, &hoca).await; | |
| 11309 | + | |
| 11310 | + let res = send( | |
| 11311 | + &app, | |
| 11312 | + "POST", | |
| 11313 | + "/messages", | |
| 11314 | + Some(&ali), | |
| 11315 | + Some(json!({ "recipient_id": hoca_id, "subject": "s", "body": "b" })), | |
| 11316 | + ) | |
| 11317 | + .await; | |
| 11318 | + assert_eq!(res.status, StatusCode::CREATED); | |
| 11319 | + let msg_id = id_of(&res.body); | |
| 11320 | + let res = send( | |
| 11321 | + &app, | |
| 11322 | + "PATCH", | |
| 11323 | + &format!("/messages/{msg_id}"), | |
| 11324 | + Some(&hoca), | |
| 11325 | + Some(json!({ "read": true })), | |
| 11326 | + ) | |
| 11327 | + .await; | |
| 11328 | + assert_eq!(res.status, StatusCode::OK); | |
| 11329 | + | |
| 11330 | + // Recipient can't move to `sent`; the bundled read flip must not land. | |
| 11331 | + let res = send( | |
| 11332 | + &app, | |
| 11333 | + "PATCH", | |
| 11334 | + &format!("/messages/{msg_id}"), | |
| 11335 | + Some(&hoca), | |
| 11336 | + Some(json!({ "read": false, "folder": "sent" })), | |
| 11337 | + ) | |
| 11338 | + .await; | |
| 11339 | + assert_eq!(res.status, StatusCode::BAD_REQUEST); | |
| 11340 | + let unread = send( | |
| 11341 | + &app, | |
| 11342 | + "GET", | |
| 11343 | + "/messages?folder=inbox&read=false", | |
| 11344 | + Some(&hoca), | |
| 11345 | + None, | |
| 11346 | + ) | |
| 11347 | + .await; | |
| 11348 | + assert_eq!( | |
| 11349 | + common::items(&unread.body).len(), | |
| 11350 | + 0, | |
| 11351 | + "rejected patch must not flip the read flag" | |
| 11352 | + ); | |
| 11353 | +} | |
| 11354 | + | |
| 11355 | +/// The read-only parent role must bounce off every notes surface — they were | |
| 11356 | +/// gated on bare authentication before the parent role existed. | |
| 11357 | +#[tokio::test] | |
| 11358 | +async fn parent_role_cannot_touch_notes() { | |
| 11359 | + let (app, db) = app_and_db().await; | |
| 11360 | + let parent = login_as(&app, &db, "baba", "parent").await; | |
| 11361 | + | |
| 11362 | + let res = send( | |
| 11363 | + &app, | |
| 11364 | + "POST", | |
| 11365 | + "/notes", | |
| 11366 | + Some(&parent), | |
| 11367 | + Some(json!({ "title": "not" })), | |
| 11368 | + ) | |
| 11369 | + .await; | |
| 11370 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | |
| 11371 | + let res = send(&app, "GET", "/notes", Some(&parent), None).await; | |
| 11372 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | |
| 11373 | + | |
| 11374 | + // Student and up keep the pen. | |
| 11375 | + let ali = login(&app, "ali").await; | |
| 11376 | + let res = send( | |
| 11377 | + &app, | |
| 11378 | + "POST", | |
| 11379 | + "/notes", | |
| 11380 | + Some(&ali), | |
| 11381 | + Some(json!({ "title": "ok" })), | |
| 11382 | + ) | |
| 11383 | + .await; | |
| 11384 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 11385 | +} | |
| 11386 | + | |
| 11387 | +/// A parent link whose student side stopped being a student (a role sweep | |
| 11388 | +/// losing a race with link creation) must be inert, exactly like a stale | |
| 11389 | +/// enrollment: the report reads re-check the live role. | |
| 11390 | +#[tokio::test] | |
| 11391 | +async fn stale_parent_link_is_inert_after_role_change() { | |
| 11392 | + let (app, db) = app_and_db().await; | |
| 11393 | + let admin = login_as(&app, &db, "boss", "admin").await; | |
| 11394 | + let parent = login_as(&app, &db, "anne", "parent").await; | |
| 11395 | + let parent_id = me_id(&app, &parent).await; | |
| 11396 | + let ali = login(&app, "ali").await; | |
| 11397 | + let ali_id = me_id(&app, &ali).await; | |
| 11398 | + | |
| 11399 | + let res = send( | |
| 11400 | + &app, | |
| 11401 | + "POST", | |
| 11402 | + &format!("/users/{parent_id}/students"), | |
| 11403 | + Some(&admin), | |
| 11404 | + Some(json!({ "user_id": ali_id })), | |
| 11405 | + ) | |
| 11406 | + .await; | |
| 11407 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 11408 | + let res = send( | |
| 11409 | + &app, | |
| 11410 | + "GET", | |
| 11411 | + &format!("/marks/{ali_id}"), | |
| 11412 | + Some(&parent), | |
| 11413 | + None, | |
| 11414 | + ) | |
| 11415 | + .await; | |
| 11416 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 11417 | + | |
| 11418 | + // Promote the student straight in the DB — the endpoint's sweep never | |
| 11419 | + // fires, leaving the link row behind like a lost race would. | |
| 11420 | + common::set_role(&db, "ali", "teacher").await; | |
| 11421 | + | |
| 11422 | + for path in [ | |
| 11423 | + format!("/marks/{ali_id}"), | |
| 11424 | + format!("/attendance/{ali_id}"), | |
| 11425 | + format!("/pomodoro/{ali_id}"), | |
| 11426 | + ] { | |
| 11427 | + let res = send(&app, "GET", &path, Some(&parent), None).await; | |
| 11428 | + assert_eq!( | |
| 11429 | + res.status, | |
| 11430 | + StatusCode::FORBIDDEN, | |
| 11431 | + "stale link must not grant {path}" | |
| 11432 | + ); | |
| 11433 | + } | |
| 11434 | +} |