diff --git a/src/domain/message.rs b/src/domain/message.rs index 9e5238e..dc149b2 100644 --- a/src/domain/message.rs +++ b/src/domain/message.rs @@ -267,11 +267,32 @@ impl Message { .ok_or(AppError::NotFound) } - /// Permanently drop `user`'s side. The row itself is removed once both - /// sides are gone — judged on the post-write row, so two concurrent - /// deletes can't leak an all-deleted row. + /// Permanently drop `user`'s side — only if that side currently sits in + /// the trash; the gate rides in the `UPDATE`'s `WHERE` so a concurrent + /// move back to the inbox can't slip past a check-then-act window. The + /// row itself is removed once both sides are gone — judged on the + /// post-write row, so two concurrent deletes can't leak an all-deleted + /// row. pub async fn delete_for(self, user: &UserId, db: &Database) -> Result<(), AppError> { - let after = self.move_to(user, DELETED_FOLDER, db).await?; + let field = if self.is_sender(user) { + "sender_folder" + } else { + "recipient_folder" + }; + let mut result = db + .query(format!( + "UPDATE $id SET {field} = $deleted WHERE {field} = $trash RETURN AFTER" + )) + .bind(("id", self.id.record())) + .bind(("deleted", DELETED_FOLDER.to_string())) + .bind(("trash", "trash".to_string())) + .await? + .check()?; + let Some(after) = result.take::>(0)?.into_iter().next() else { + return Err(AppError::Conflict( + "only messages in the trash can be permanently deleted", + )); + }; if after.sender_folder == DELETED_FOLDER && after.recipient_folder == DELETED_FOLDER { let _: Option = db.delete(after.id.record()).await?; } diff --git a/src/web/exams.rs b/src/web/exams.rs index 98419f4..8795240 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -324,6 +324,11 @@ async fn update_exam( Path(id): Path, Json(req): Json, ) -> Result, AppError> { + // Take the writer lease before the row read: the merge defaults and the + // mode/draft gates below all judge this snapshot, so a publish or mode + // change landing between an unlocked read and the gates would be silently + // written back over. + let _guard = EXAM_LOCK.write().await; let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; @@ -393,10 +398,9 @@ async fn update_exam( // Switching sync <-> async <-> open (or back to unscheduled) 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. 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; + // supported live adjustments instead. Gate read and write share the + // handler-wide 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 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? { diff --git a/src/web/extractor.rs b/src/web/extractor.rs index b1e2b05..62d8d33 100644 --- a/src/web/extractor.rs +++ b/src/web/extractor.rs @@ -54,6 +54,26 @@ where } } +/// Like [`CurrentUser`], but also requires at least the `student` role — +/// keeps the read-only `parent` role out of write-capable surfaces. +pub struct RequireStudent(pub User); + +impl FromRequestParts for RequireStudent +where + S: Send + Sync, + AppState: FromRef, +{ + type Rejection = AppError; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + let user = authed_user(parts, state).await?; + if !user.get_role().at_least(Role::Student) { + return Err(AppError::Forbidden("requires student role or higher")); + } + Ok(RequireStudent(user)) + } +} + /// Like [`CurrentUser`], but also requires at least the `teacher` role. /// Authenticated-but-under-privileged callers get `403`. pub struct RequireTeacher(pub User); diff --git a/src/web/messages.rs b/src/web/messages.rs index 104f8b7..476d29b 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -110,7 +110,12 @@ async fn load_people(messages: &[Message], db: &Database) -> Result = messages .iter() - .flat_map(|message| [message.get_sender().clone(), message.get_recipient().clone()]) + .flat_map(|message| { + [ + message.get_sender().clone(), + message.get_recipient().clone(), + ] + }) .filter(|id| seen.insert(id.key().to_string())) .collect(); let users = User::list_by_ids(&ids, db).await?; @@ -274,13 +279,12 @@ async fn update_message( .await? .ok_or(AppError::NotFound)?; - if let Some(read) = req.read { - if message.is_sender(user.get_id()) { - return Err(AppError::Forbidden( - "only the recipient can change the read flag", - )); - } - message = message.set_read(read, &st.db).await?; + // Validate the whole patch before touching the row: a rejected folder + // must not leave a half-applied read flag behind. + if req.read.is_some() && message.is_sender(user.get_id()) { + return Err(AppError::Forbidden( + "only the recipient can change the read flag", + )); } if let Some(ref folder) = req.folder { let allowed: &[&str] = if message.is_sender(user.get_id()) { @@ -294,6 +298,11 @@ async fn update_message( reason: "not a folder this side of the message can move to", })); } + } + if let Some(read) = req.read { + message = message.set_read(read, &st.db).await?; + } + if let Some(ref folder) = req.folder { message = message.move_to(user.get_id(), folder, &st.db).await?; } @@ -325,11 +334,6 @@ async fn delete_message( let message = Message::read_for(&MessageId::from_key(&id), user.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; - if message.folder_of(user.get_id()) != "trash" { - return Err(AppError::Conflict( - "only messages in the trash can be permanently deleted", - )); - } message.delete_for(user.get_id(), &st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/mod.rs b/src/web/mod.rs index c73771d..6f040f2 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -28,7 +28,7 @@ pub use dto::{ CourseResponse, ExamResponse, PersonRef, SessionResponse, SubjectResponse, UserResponse, person_map, }; -pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher}; +pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher}; pub use page::{Page, PageParams, paginate}; use std::path::{Path as FsPath, PathBuf}; @@ -50,8 +50,8 @@ use crate::error::{AppError, ValidationError}; /// May `caller` read `target`'s per-student reports (marks, attendance, /// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's /// business); a parent may exactly when a `parent_link` row ties them to the -/// target. Everyone else — students included — gets a 403 (self-reads go -/// through the `/me` endpoints). +/// target *and* the target still holds the student role. Everyone else — +/// students included — gets a 403 (self-reads go through the `/me` endpoints). pub(crate) async fn ensure_can_observe( caller: &User, target: &UserId, @@ -60,7 +60,17 @@ pub(crate) async fn ensure_can_observe( if caller.get_role().at_least(Role::Teacher) { return Ok(()); } - if caller.get_role() == Role::Parent && ParentLink::exists(caller.get_id(), target, db).await? { + // The link row alone is not the grant: like stale enrollments, a link + // whose student side changed role (a sweep lost a race with link_student) + // must be inert, so the target's live role is re-read here. Missing or + // non-student targets fall through to the same 403 — a parent never gets + // an existence oracle. + if caller.get_role() == Role::Parent + && ParentLink::exists(caller.get_id(), target, db).await? + && User::read(target, db) + .await? + .is_some_and(|target| target.get_role() == Role::Student) + { return Ok(()); } Err(AppError::Forbidden( diff --git a/src/web/notes.rs b/src/web/notes.rs index 58377dc..62713aa 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -16,7 +16,7 @@ use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; use super::{ - CurrentUser, Page, PageParams, UploadFileForm, blob_path, paginate, read_upload, remove_blob, + Page, PageParams, RequireStudent, UploadFileForm, blob_path, paginate, read_upload, remove_blob, }; pub fn routes() -> OpenApiRouter { @@ -78,11 +78,12 @@ impl NoteResponse { (status = 201, description = "Note created", body = NoteResponse), (status = 400, description = "Invalid title or content", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), ), )] async fn create( State(st): State, - CurrentUser(user): CurrentUser, + RequireStudent(user): RequireStudent, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let title = NoteTitle::try_new(&req.title)?; @@ -104,11 +105,12 @@ async fn create( (status = 200, description = "A page of the user's notes (all of them when unpaged)", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), ), )] async fn list( State(st): State, - CurrentUser(user): CurrentUser, + RequireStudent(user): RequireStudent, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; @@ -131,12 +133,13 @@ async fn list( responses( (status = 200, description = "The note", body = NoteResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] async fn get_one( State(st): State, - CurrentUser(user): CurrentUser, + RequireStudent(user): RequireStudent, Path(id): Path, ) -> Result, AppError> { let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) @@ -157,12 +160,13 @@ async fn get_one( (status = 200, description = "Updated note", body = NoteResponse), (status = 400, description = "Invalid title or content", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] async fn update( State(st): State, - CurrentUser(user): CurrentUser, + RequireStudent(user): RequireStudent, Path(id): Path, Json(req): Json, ) -> Result, AppError> { @@ -193,12 +197,13 @@ async fn update( responses( (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] async fn delete_one( State(st): State, - CurrentUser(user): CurrentUser, + RequireStudent(user): RequireStudent, Path(id): Path, ) -> Result { let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) @@ -257,6 +262,7 @@ impl NoteFileResponse { (status = 201, description = "File stored", body = NoteFileResponse), (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), (status = 404, description = "Note not found", body = ErrorResponse), (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse), (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), @@ -264,7 +270,7 @@ impl NoteFileResponse { )] async fn upload_file( State(st): State, - CurrentUser(user): CurrentUser, + RequireStudent(user): RequireStudent, Path(id): Path, mut multipart: Multipart, ) -> Result<(StatusCode, Json), AppError> { @@ -307,12 +313,13 @@ async fn upload_file( (status = 200, description = "A page of the note's files", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), (status = 404, description = "Note not found", body = ErrorResponse), ), )] async fn list_files( State(st): State, - CurrentUser(user): CurrentUser, + RequireStudent(user): RequireStudent, Path(id): Path, Query(page): Query, ) -> Result>, AppError> { @@ -343,12 +350,13 @@ async fn list_files( responses( (status = 200, description = "The file bytes", content_type = "application/octet-stream"), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), (status = 404, description = "Note or file not found", body = ErrorResponse), ), )] async fn download_file( State(st): State, - CurrentUser(user): CurrentUser, + RequireStudent(user): RequireStudent, Path((id, file_id)): Path<(String, String)>, ) -> Result { let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) @@ -396,12 +404,13 @@ async fn download_file( responses( (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role or higher", body = ErrorResponse), (status = 404, description = "Note or file not found", body = ErrorResponse), ), )] async fn delete_file( State(st): State, - CurrentUser(user): CurrentUser, + RequireStudent(user): RequireStudent, Path((id, file_id)): Path<(String, String)>, ) -> Result { let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) diff --git a/src/web/users.rs b/src/web/users.rs index 79c38e1..3cbc502 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -454,7 +454,8 @@ async fn students_page( /// Tie a student to a parent account. Admin only — family ties are school-office /// records, like roles. `{id}` must hold the `parent` role and `user_id` the /// `student` role; a parent may observe any number of students. Idempotent: -/// linking the same pair again returns the existing tie. The tie grants the +/// linking the same pair again keeps the one tie (the `linked_by` stamp moves +/// to the latest linker, like re-enrolling). The tie grants the /// parent read access to the student's marks, attendance, and pomodoro reports /// — nothing else, and never any write. #[utoipa::path( diff --git a/tests/integration.rs b/tests/integration.rs index 783fc6b..4de2954 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -11088,7 +11088,14 @@ async fn messages_flow_through_folders_per_side() { .await; assert_eq!(res.status, StatusCode::FORBIDDEN); // `?read=` narrows; `total` on the filtered view is the unread badge. - let unread = send(&app, "GET", "/messages?folder=inbox&read=false&limit=1", Some(&hoca), None).await; + let unread = send( + &app, + "GET", + "/messages?folder=inbox&read=false&limit=1", + Some(&hoca), + None, + ) + .await; assert_eq!(unread.body["total"], 1); let res = send( &app, @@ -11099,7 +11106,14 @@ async fn messages_flow_through_folders_per_side() { ) .await; assert_eq!(res.status, StatusCode::OK); - let unread = send(&app, "GET", "/messages?folder=inbox&read=false&limit=1", Some(&hoca), None).await; + let unread = send( + &app, + "GET", + "/messages?folder=inbox&read=false&limit=1", + Some(&hoca), + None, + ) + .await; assert_eq!(unread.body["total"], 0); let sent = send(&app, "GET", "/messages?folder=sent", Some(&ali), None).await; assert_eq!(common::items(&sent.body)[0]["read"], true); @@ -11129,7 +11143,14 @@ async fn messages_flow_through_folders_per_side() { assert_eq!(common::items(&archive.body).len(), 1); // Permanent delete only from the trash; it never touches the other copy. - let res = send(&app, "DELETE", &format!("/messages/{msg_id}"), Some(&hoca), None).await; + let res = send( + &app, + "DELETE", + &format!("/messages/{msg_id}"), + Some(&hoca), + None, + ) + .await; assert_eq!(res.status, StatusCode::CONFLICT); send( &app, @@ -11141,7 +11162,14 @@ async fn messages_flow_through_folders_per_side() { .await; let trash = send(&app, "GET", "/messages?folder=trash", Some(&hoca), None).await; assert_eq!(common::items(&trash.body).len(), 1); - let res = send(&app, "DELETE", &format!("/messages/{msg_id}"), Some(&hoca), None).await; + let res = send( + &app, + "DELETE", + &format!("/messages/{msg_id}"), + Some(&hoca), + None, + ) + .await; assert_eq!(res.status, StatusCode::NO_CONTENT); let trash = send(&app, "GET", "/messages?folder=trash", Some(&hoca), None).await; assert_eq!(common::items(&trash.body).len(), 0); @@ -11168,7 +11196,14 @@ async fn messages_flow_through_folders_per_side() { Some(json!({ "folder": "trash" })), ) .await; - let res = send(&app, "DELETE", &format!("/messages/{msg_id}"), Some(&ali), None).await; + let res = send( + &app, + "DELETE", + &format!("/messages/{msg_id}"), + Some(&ali), + None, + ) + .await; assert_eq!(res.status, StatusCode::NO_CONTENT); let mut result = db .query("SELECT VALUE id FROM message") @@ -11219,7 +11254,11 @@ async fn messages_guard_parties_recipients_and_folders() { .await; assert_eq!(res.status, StatusCode::CREATED); assert_eq!(res.body["sender_role"], "parent"); - assert_eq!(res.body["label"], serde_json::Value::Null, "no label sent, none stored"); + assert_eq!( + res.body["label"], + serde_json::Value::Null, + "no label sent, none stored" + ); let msg_id = id_of(&res.body); // A third user is not a party: sees nothing, touches nothing. @@ -11234,7 +11273,14 @@ async fn messages_guard_parties_recipients_and_folders() { ) .await; assert_eq!(res.status, StatusCode::NOT_FOUND); - let res = send(&app, "DELETE", &format!("/messages/{msg_id}"), Some(&veli), None).await; + let res = send( + &app, + "DELETE", + &format!("/messages/{msg_id}"), + Some(&veli), + None, + ) + .await; assert_eq!(res.status, StatusCode::NOT_FOUND); // Unknown folder names and oversized labels are refused. @@ -11251,3 +11297,138 @@ async fn messages_guard_parties_recipients_and_folders() { .await; assert_eq!(res.status, StatusCode::BAD_REQUEST); } + +/// A patch that fails validation must not half-apply: the read flag stays +/// untouched when the folder part of the same body is rejected. +#[tokio::test] +async fn messages_rejected_patch_leaves_no_side_effects() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let hoca_id = me_id(&app, &hoca).await; + + let res = send( + &app, + "POST", + "/messages", + Some(&ali), + Some(json!({ "recipient_id": hoca_id, "subject": "s", "body": "b" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + let msg_id = id_of(&res.body); + let res = send( + &app, + "PATCH", + &format!("/messages/{msg_id}"), + Some(&hoca), + Some(json!({ "read": true })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + + // Recipient can't move to `sent`; the bundled read flip must not land. + let res = send( + &app, + "PATCH", + &format!("/messages/{msg_id}"), + Some(&hoca), + Some(json!({ "read": false, "folder": "sent" })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + let unread = send( + &app, + "GET", + "/messages?folder=inbox&read=false", + Some(&hoca), + None, + ) + .await; + assert_eq!( + common::items(&unread.body).len(), + 0, + "rejected patch must not flip the read flag" + ); +} + +/// The read-only parent role must bounce off every notes surface — they were +/// gated on bare authentication before the parent role existed. +#[tokio::test] +async fn parent_role_cannot_touch_notes() { + let (app, db) = app_and_db().await; + let parent = login_as(&app, &db, "baba", "parent").await; + + let res = send( + &app, + "POST", + "/notes", + Some(&parent), + Some(json!({ "title": "not" })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send(&app, "GET", "/notes", Some(&parent), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // Student and up keep the pen. + let ali = login(&app, "ali").await; + let res = send( + &app, + "POST", + "/notes", + Some(&ali), + Some(json!({ "title": "ok" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); +} + +/// A parent link whose student side stopped being a student (a role sweep +/// losing a race with link creation) must be inert, exactly like a stale +/// enrollment: the report reads re-check the live role. +#[tokio::test] +async fn stale_parent_link_is_inert_after_role_change() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + let parent = login_as(&app, &db, "anne", "parent").await; + let parent_id = me_id(&app, &parent).await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + + let res = send( + &app, + "POST", + &format!("/users/{parent_id}/students"), + Some(&admin), + Some(json!({ "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/marks/{ali_id}"), + Some(&parent), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Promote the student straight in the DB — the endpoint's sweep never + // fires, leaving the link row behind like a lost race would. + common::set_role(&db, "ali", "teacher").await; + + for path in [ + format!("/marks/{ali_id}"), + format!("/attendance/{ali_id}"), + format!("/pomodoro/{ali_id}"), + ] { + let res = send(&app, "GET", &path, Some(&parent), None).await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "stale link must not grant {path}" + ); + } +}