forge
Explore
Log in

Don't you dare go Hollow

Authz holes and stale-read races from the bug hunt

Browse files at this commit

de938d85f98b4ea12632b42b346ce4794fa7db8fAhmet Kaan GümüşParent: f4b3828
  • fix
    • authz holes and stale-read races from the bug hunt
Show full message
🐛 fix: authz holes and stale-read races from the bug hunt

- messages: a PATCH rejected on the folder no longer half-applies the
  read flag; the whole body validates before any write
- messages: the delete-from-trash gate rides in the UPDATE's WHERE
  instead of a check-then-act window
- notes: all nine handlers now require the student role — the read-only
  parent role could create notes and upload files (new RequireStudent)
- reports: a parent link whose student side changed role is inert;
  ensure_can_observe re-reads the target's live role like enrollments
- exams: update_exam takes the EXAM_LOCK writer lease before reading
  the row its merge defaults and draft/mode gates judge

Re-link keeping one tie while linked_by moves to the latest linker is
deliberate (matches re-enroll); doc reworded to say so.
src/domain/message.rsmodified+25 -4
@@ -267,11 +267,32 @@ impl Message {
267267 .ok_or(AppError::NotFound)
268268 }
269269
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.
273276 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+ };
275296 if after.sender_folder == DELETED_FOLDER && after.recipient_folder == DELETED_FOLDER {
276297 let _: Option<Message> = db.delete(after.id.record()).await?;
277298 }
src/web/exams.rsmodified+8 -4
@@ -324,6 +324,11 @@ async fn update_exam(
324324 Path(id): Path<String>,
325325 Json(req): Json<UpdateExam>,
326326 ) -> 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;
327332 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
328333 .await?
329334 .ok_or(AppError::NotFound)?;
@@ -393,10 +398,9 @@ async fn update_exam(
393398 // Switching sync <-> async <-> open (or back to unscheduled) would
394399 // silently rewrite the deadline rules under students who already sat
395400 // 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.
400404 let mode_changed =
401405 schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);
402406 if mode_changed && ExamAttempt::any_for_exam(exam.get_id(), &st.db).await? {
src/web/extractor.rsmodified+20 -0
@@ -54,6 +54,26 @@ where
5454 }
5555 }
5656
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+
5777 /// Like [`CurrentUser`], but also requires at least the `teacher` role.
5878 /// Authenticated-but-under-privileged callers get `403`.
5979 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
110110 let mut seen = HashSet::new();
111111 let ids: Vec<UserId> = messages
112112 .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+ })
114119 .filter(|id| seen.insert(id.key().to_string()))
115120 .collect();
116121 let users = User::list_by_ids(&ids, db).await?;
@@ -274,13 +279,12 @@ async fn update_message(
274279 .await?
275280 .ok_or(AppError::NotFound)?;
276281
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+ ));
284288 }
285289 if let Some(ref folder) = req.folder {
286290 let allowed: &[&str] = if message.is_sender(user.get_id()) {
@@ -294,6 +298,11 @@ async fn update_message(
294298 reason: "not a folder this side of the message can move to",
295299 }));
296300 }
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 {
297306 message = message.move_to(user.get_id(), folder, &st.db).await?;
298307 }
299308
@@ -325,11 +334,6 @@ async fn delete_message(
325334 let message = Message::read_for(&MessageId::from_key(&id), user.get_id(), &st.db)
326335 .await?
327336 .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- }
333337 message.delete_for(user.get_id(), &st.db).await?;
334338 Ok(StatusCode::NO_CONTENT)
335339 }
src/web/mod.rsmodified+14 -4
@@ -28,7 +28,7 @@ pub use dto::{
2828 CourseResponse, ExamResponse, PersonRef, SessionResponse, SubjectResponse, UserResponse,
2929 person_map,
3030 };
31-pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher};
31+pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher};
3232 pub use page::{Page, PageParams, paginate};
3333
3434 use std::path::{Path as FsPath, PathBuf};
@@ -50,8 +50,8 @@ use crate::error::{AppError, ValidationError};
5050 /// May `caller` read `target`'s per-student reports (marks, attendance,
5151 /// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's
5252 /// 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).
5555 pub(crate) async fn ensure_can_observe(
5656 caller: &User,
5757 target: &UserId,
@@ -60,7 +60,17 @@ pub(crate) async fn ensure_can_observe(
6060 if caller.get_role().at_least(Role::Teacher) {
6161 return Ok(());
6262 }
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+ {
6474 return Ok(());
6575 }
6676 Err(AppError::Forbidden(
src/web/notes.rsmodified+19 -10
@@ -16,7 +16,7 @@ use crate::error::{AppError, ErrorResponse};
1616 use crate::state::AppState;
1717
1818 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,
2020 };
2121
2222 pub fn routes() -> OpenApiRouter<AppState> {
@@ -78,11 +78,12 @@ impl NoteResponse {
7878 (status = 201, description = "Note created", body = NoteResponse),
7979 (status = 400, description = "Invalid title or content", body = ErrorResponse),
8080 (status = 401, description = "Not authenticated", body = ErrorResponse),
81+ (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
8182 ),
8283 )]
8384 async fn create(
8485 State(st): State<AppState>,
85- CurrentUser(user): CurrentUser,
86+ RequireStudent(user): RequireStudent,
8687 Json(req): Json<CreateNote>,
8788 ) -> Result<(StatusCode, Json<NoteResponse>), AppError> {
8889 let title = NoteTitle::try_new(&req.title)?;
@@ -104,11 +105,12 @@ async fn create(
104105 (status = 200, description = "A page of the user's notes (all of them when unpaged)", body = Page<NoteResponse>),
105106 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
106107 (status = 401, description = "Not authenticated", body = ErrorResponse),
108+ (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
107109 ),
108110 )]
109111 async fn list(
110112 State(st): State<AppState>,
111- CurrentUser(user): CurrentUser,
113+ RequireStudent(user): RequireStudent,
112114 Query(page): Query<PageParams>,
113115 ) -> Result<Json<Page<NoteResponse>>, AppError> {
114116 let (limit, offset) = page.resolve()?;
@@ -131,12 +133,13 @@ async fn list(
131133 responses(
132134 (status = 200, description = "The note", body = NoteResponse),
133135 (status = 401, description = "Not authenticated", body = ErrorResponse),
136+ (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
134137 (status = 404, description = "Not found", body = ErrorResponse),
135138 ),
136139 )]
137140 async fn get_one(
138141 State(st): State<AppState>,
139- CurrentUser(user): CurrentUser,
142+ RequireStudent(user): RequireStudent,
140143 Path(id): Path<String>,
141144 ) -> Result<Json<NoteResponse>, AppError> {
142145 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
@@ -157,12 +160,13 @@ async fn get_one(
157160 (status = 200, description = "Updated note", body = NoteResponse),
158161 (status = 400, description = "Invalid title or content", body = ErrorResponse),
159162 (status = 401, description = "Not authenticated", body = ErrorResponse),
163+ (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
160164 (status = 404, description = "Not found", body = ErrorResponse),
161165 ),
162166 )]
163167 async fn update(
164168 State(st): State<AppState>,
165- CurrentUser(user): CurrentUser,
169+ RequireStudent(user): RequireStudent,
166170 Path(id): Path<String>,
167171 Json(req): Json<UpdateNote>,
168172 ) -> Result<Json<NoteResponse>, AppError> {
@@ -193,12 +197,13 @@ async fn update(
193197 responses(
194198 (status = 204, description = "Deleted"),
195199 (status = 401, description = "Not authenticated", body = ErrorResponse),
200+ (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
196201 (status = 404, description = "Not found", body = ErrorResponse),
197202 ),
198203 )]
199204 async fn delete_one(
200205 State(st): State<AppState>,
201- CurrentUser(user): CurrentUser,
206+ RequireStudent(user): RequireStudent,
202207 Path(id): Path<String>,
203208 ) -> Result<StatusCode, AppError> {
204209 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
@@ -257,6 +262,7 @@ impl NoteFileResponse {
257262 (status = 201, description = "File stored", body = NoteFileResponse),
258263 (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse),
259264 (status = 401, description = "Not authenticated", body = ErrorResponse),
265+ (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
260266 (status = 404, description = "Note not found", body = ErrorResponse),
261267 (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse),
262268 (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse),
@@ -264,7 +270,7 @@ impl NoteFileResponse {
264270 )]
265271 async fn upload_file(
266272 State(st): State<AppState>,
267- CurrentUser(user): CurrentUser,
273+ RequireStudent(user): RequireStudent,
268274 Path(id): Path<String>,
269275 mut multipart: Multipart,
270276 ) -> Result<(StatusCode, Json<NoteFileResponse>), AppError> {
@@ -307,12 +313,13 @@ async fn upload_file(
307313 (status = 200, description = "A page of the note's files", body = Page<NoteFileResponse>),
308314 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
309315 (status = 401, description = "Not authenticated", body = ErrorResponse),
316+ (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
310317 (status = 404, description = "Note not found", body = ErrorResponse),
311318 ),
312319 )]
313320 async fn list_files(
314321 State(st): State<AppState>,
315- CurrentUser(user): CurrentUser,
322+ RequireStudent(user): RequireStudent,
316323 Path(id): Path<String>,
317324 Query(page): Query<PageParams>,
318325 ) -> Result<Json<Page<NoteFileResponse>>, AppError> {
@@ -343,12 +350,13 @@ async fn list_files(
343350 responses(
344351 (status = 200, description = "The file bytes", content_type = "application/octet-stream"),
345352 (status = 401, description = "Not authenticated", body = ErrorResponse),
353+ (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
346354 (status = 404, description = "Note or file not found", body = ErrorResponse),
347355 ),
348356 )]
349357 async fn download_file(
350358 State(st): State<AppState>,
351- CurrentUser(user): CurrentUser,
359+ RequireStudent(user): RequireStudent,
352360 Path((id, file_id)): Path<(String, String)>,
353361 ) -> Result<Response, AppError> {
354362 let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
@@ -396,12 +404,13 @@ async fn download_file(
396404 responses(
397405 (status = 204, description = "Deleted"),
398406 (status = 401, description = "Not authenticated", body = ErrorResponse),
407+ (status = 403, description = "Requires the student role or higher", body = ErrorResponse),
399408 (status = 404, description = "Note or file not found", body = ErrorResponse),
400409 ),
401410 )]
402411 async fn delete_file(
403412 State(st): State<AppState>,
404- CurrentUser(user): CurrentUser,
413+ RequireStudent(user): RequireStudent,
405414 Path((id, file_id)): Path<(String, String)>,
406415 ) -> Result<StatusCode, AppError> {
407416 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(
454454 /// Tie a student to a parent account. Admin only — family ties are school-office
455455 /// records, like roles. `{id}` must hold the `parent` role and `user_id` the
456456 /// `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
458459 /// parent read access to the student's marks, attendance, and pomodoro reports
459460 /// — nothing else, and never any write.
460461 #[utoipa::path(
tests/integration.rsmodified+188 -7
@@ -11088,7 +11088,14 @@ async fn messages_flow_through_folders_per_side() {
1108811088 .await;
1108911089 assert_eq!(res.status, StatusCode::FORBIDDEN);
1109011090 // `?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;
1109211099 assert_eq!(unread.body["total"], 1);
1109311100 let res = send(
1109411101 &app,
@@ -11099,7 +11106,14 @@ async fn messages_flow_through_folders_per_side() {
1109911106 )
1110011107 .await;
1110111108 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;
1110311117 assert_eq!(unread.body["total"], 0);
1110411118 let sent = send(&app, "GET", "/messages?folder=sent", Some(&ali), None).await;
1110511119 assert_eq!(common::items(&sent.body)[0]["read"], true);
@@ -11129,7 +11143,14 @@ async fn messages_flow_through_folders_per_side() {
1112911143 assert_eq!(common::items(&archive.body).len(), 1);
1113011144
1113111145 // 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;
1113311154 assert_eq!(res.status, StatusCode::CONFLICT);
1113411155 send(
1113511156 &app,
@@ -11141,7 +11162,14 @@ async fn messages_flow_through_folders_per_side() {
1114111162 .await;
1114211163 let trash = send(&app, "GET", "/messages?folder=trash", Some(&hoca), None).await;
1114311164 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;
1114511173 assert_eq!(res.status, StatusCode::NO_CONTENT);
1114611174 let trash = send(&app, "GET", "/messages?folder=trash", Some(&hoca), None).await;
1114711175 assert_eq!(common::items(&trash.body).len(), 0);
@@ -11168,7 +11196,14 @@ async fn messages_flow_through_folders_per_side() {
1116811196 Some(json!({ "folder": "trash" })),
1116911197 )
1117011198 .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;
1117211207 assert_eq!(res.status, StatusCode::NO_CONTENT);
1117311208 let mut result = db
1117411209 .query("SELECT VALUE id FROM message")
@@ -11219,7 +11254,11 @@ async fn messages_guard_parties_recipients_and_folders() {
1121911254 .await;
1122011255 assert_eq!(res.status, StatusCode::CREATED);
1122111256 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+ );
1122311262 let msg_id = id_of(&res.body);
1122411263
1122511264 // A third user is not a party: sees nothing, touches nothing.
@@ -11234,7 +11273,14 @@ async fn messages_guard_parties_recipients_and_folders() {
1123411273 )
1123511274 .await;
1123611275 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;
1123811284 assert_eq!(res.status, StatusCode::NOT_FOUND);
1123911285
1124011286 // Unknown folder names and oversized labels are refused.
@@ -11251,3 +11297,138 @@ async fn messages_guard_parties_recipients_and_folders() {
1125111297 .await;
1125211298 assert_eq!(res.status, StatusCode::BAD_REQUEST);
1125311299 }
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+}