diff --git a/README.md b/README.md index 4fd378a..7fd7c85 100644 --- a/README.md +++ b/README.md @@ -590,8 +590,9 @@ the tie is the parent's whole power — they list their students and homework reports in full. Student-only checks are exact (`role == student`), so a parent can never enroll, sit an exam, be graded, or land on a roll call; and sitting below every staff bar, they can't touch anything else either — except -messages, which any role sends and receives (that's how a parent reaches a -teacher), and their own **notes**, which carry no role bar at all: a note is +messages, which they send *upward* only — to a teacher, manager or admin, +never to a student or another parent (the same bar a student holds, issue +#23) — and their own **notes**, which carry no role bar at all: a note is private to one person, so a role change must not confiscate it. It used to. While the note routes required `student`, a demotion locked the owner out of their own notes permanently — and since nothing else in the crate reads a note @@ -1021,7 +1022,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/meals/profiles/{user}` | teacher | One student's dietary profile. Requires teacher+, or a parent link to them — the caller's own id always passes. | | PATCH | `/meals/profiles/{user}` | manager | Record what a student may not eat. **Manager+**, deliberately: an allergen list is a safety record the school keeps on the student's behalf, not a self-service preference — a student editing their own would let a mistyped (or removed) allergy reach the kitchen with the school's authority behind it. Omitted fields keep their value; `tags` replaces the whole list, and `"note": null` clears the note. First write creates the row. | | GET | `/messages` | student | List one of the caller's folders, newest first: `inbox` (default), `sent`, `archive`, or `trash` (`?folder=`). `?read=` narrows by the read flag; `total` counts the filtered folder, so `?folder=inbox&read=false&limit=1` is a cheap unread badge. Paged via `?limit=&offset=`. | -| POST | `/messages` | student | Send a message to another user. Any authenticated user may write to any existing user (parents included — messaging is the one place a parent acts); only messaging yourself is refused. The send is server-stamped and lands in the recipient's inbox unread. | +| POST | `/messages` | student | Send a message to another user. Messaging is upward only below staff: a student or parent may write to a teacher, manager or admin (parents included — messaging is the one place a parent acts), never to another student or parent; staff write to anyone. Messaging yourself is refused. The send is server-stamped and lands in the recipient's inbox unread. | | PATCH | `/messages/{id}` | student | Update the caller's view of a message: flip the read flag (recipient only) and/or move the caller's copy between folders. Each side files independently — archiving or trashing never touches the other party's copy. Filing into `archive`/`trash` records the folder left behind as the copy's `previous_folder`, so restoring is a move back to that value (`inbox`, or `sent` for the sender's copy, when it is `null`). Omitted fields change nothing. | | DELETE | `/messages/{id}` | student | Permanently delete the caller's copy — allowed only from the trash (`PATCH` it to `folder: "trash"` first). The other party's copy lives on; the row disappears for good once both sides have deleted theirs. | | GET | `/notes` | student | List the notes owned by the current user, newest first. Paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. | @@ -1093,7 +1094,7 @@ window filtering, before paging; negative values are a `400` naming the field. | PATCH | `/users/me/preferences` | student | Update the caller's own UI preferences: `theme` (`light`/`dark`), `language` (`tr`/`en`), and `palette_color` (accent color as `#rrggbb`). Any authenticated role. Omitted fields stay as they are; an empty string clears one back to "never chose" (the client then follows the device preference). Read them back on any user response, e.g. `GET /auth/me`. | | GET | `/users/me/profile` | student | The caller's own public profile — what everyone else sees of them. | | GET | `/users/me/students` | parent | The students the calling parent observes, sorted by username. Requires the `parent` role. Each entry's reports live at `GET /marks/{user}`, `GET /attendance/{user}`, and `GET /pomodoro/{user}`. Paged via `?limit=&offset=`. | -| GET | `/users/search` | teacher | Find users by username or name — backs the pickers (enroll, grade, mark attendance). Requires teacher+. `role` narrows to one role (e.g. `role=student` for an enroll picker); a blank `q` with a `role` lists everyone in that role. Paged via `?limit=&offset=` like the other lists (omit `limit` for every match); returns a `{items, total, limit, offset}` envelope carrying only id/username/display name — no contact details. | +| GET | `/users/search` | student | Find users by username or name — backs the pickers (enroll, grade, mark attendance) and, for a student or parent, the one way to find the staff member they are allowed to message. Any authenticated user may ask; a caller below teacher only ever sees the roles they may message (teacher, manager, admin), in the items *and* in `total`. `role` narrows to one role (e.g. `role=student` for an enroll picker) — a student or parent naming a role they may not message is refused; a blank `q` with a `role` lists everyone in that role. Paged via `?limit=&offset=` like the other lists (omit `limit` for every match); returns a `{items, total, limit, offset}` envelope carrying only id/username/display name — no contact details. | | GET | `/users/{id}` | admin | Fetch one user with their role and personal info. Admin only. | | GET | `/users/{id}/avatar` | student | The avatar bytes. Same reach as the profile itself: every authenticated account, except a parent, who is limited to their own and their linked students'. | | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar. Admin only — the moderation path: an offensive picture is a school problem, and no route deletes the account it hangs on. | @@ -1581,8 +1582,9 @@ answers `409`. Every slot carries its teacher's identity (id, username, display name), to a parent as much as to a student: **deliberate**, and not to be tightened. A parent's three direct routes to that identity are all shut (`GET -/users/{id}/profile` is a `403`, `/users/search` is teacher+, `/users` is -admin), but a conference cannot be booked off an anonymous calendar — this list +/users/{id}/profile` is a `403`, `/users` is admin, and `/users/search` names +staff but not *which* of them holds office hours), but a conference cannot be +booked off an anonymous calendar — this list *is* the staff directory for the booking flow, narrowed to whoever published bookable time. The same refs on a booking (`teacher`, `proposed_by`, `decided_by`) read the same way. @@ -1701,9 +1703,14 @@ too — they may still decide any booking by id. ## Messaging One-to-one, mail-style (subject + body + an optional free-text `label` the UI -renders as a badge — "Etüt", "Sınav"; no threads): any user writes to any -user — student to teacher, parent to teacher, teacher to student; only -messaging yourself is refused. A single stored message serves both parties, +renders as a badge — "Etüt", "Sınav"; no threads). Writing is **upward only +below staff**: a student or parent may write to a teacher, manager or admin +(student to teacher, parent to teacher), never to another student or parent — +that is a `403`. Staff write to anyone, in any direction (teacher to student). +Messaging yourself is refused, and only new sends are gated: student↔student +rows sent before the rule stay readable and filable. `GET /users/search` is +how a student or parent finds the staff member to write to — it shows them +staff and nobody else (issue #24). A single stored message serves both parties, but each **owns their copy independently**: the recipient's moves through `inbox` → `archive`/`trash` and carries the `read` flag (the sender sees it as a read receipt); the sender's moves through `sent` → `archive`/`trash`. Filing or @@ -3125,7 +3132,8 @@ newest first, and `total` counts the memberships the window was cut from. Both of them hide one field: **`creator` is `null` below teacher+**. A class is created by manager+ only, so shipping the creator to a student (or to their linked parent) would hand out an office account's username and real name — an -identity `GET /users` (admin-only) and `/users/search` (teacher+) both withhold. +identity `GET /users` (admin-only) withholds outright, and one `/users/search` +hands a student only as the messaging directory — never as class metadata. The homeroom teacher is *not* hidden: naming them is the point of the read. On every staff-facing route (`GET /classes`, `/classes/{id}`, and the create/edit responses) `creator` is populated exactly as before. diff --git a/src/domain/role.rs b/src/domain/role.rs index 9a6c612..0e7a512 100644 --- a/src/domain/role.rs +++ b/src/domain/role.rs @@ -65,6 +65,28 @@ impl Role { pub fn at_least(self, min: Role) -> bool { self >= min } + + /// May `self` open a message thread with `recipient`? Messaging is upward + /// only for the two roles below staff: a `Student` or `Parent` writes to + /// teachers and above, never sideways or down (issue #23). Staff + /// (`Teacher`+) write to anyone. [`Role::Ai`] is a service principal with + /// no mailbox, so it neither sends nor receives. + pub fn may_message(self, recipient: Role) -> bool { + if self == Role::Ai || recipient == Role::Ai { + return false; + } + self.at_least(Role::Teacher) || recipient.at_least(Role::Teacher) + } + + /// The roles `self` is allowed to write to, when that set is narrower than + /// "everyone" — `None` means unrestricted. Backs the `/users/search` + /// restriction, which must land in the query so `total` stays right. + pub fn messageable_roles(self) -> Option<&'static [Role]> { + match self.at_least(Role::Teacher) { + true => None, + false => Some(&[Role::Teacher, Role::Manager, Role::Admin]), + } + } } #[cfg(test)] @@ -111,6 +133,31 @@ mod tests { assert_eq!(Role::Ai.as_str(), "ai"); } + #[tokio::test] + async fn messaging_is_upward_only_below_staff() { + // Sideways and downward writes from the two non-staff roles: refused. + for sender in [Role::Student, Role::Parent] { + for recipient in [Role::Student, Role::Parent] { + assert!(!sender.may_message(recipient)); + } + for staff in [Role::Teacher, Role::Manager, Role::Admin] { + assert!(sender.may_message(staff)); + } + assert_eq!( + sender.messageable_roles(), + Some(&[Role::Teacher, Role::Manager, Role::Admin][..]) + ); + } + // Staff write to anyone, in any direction, and are unrestricted in search. + for sender in [Role::Teacher, Role::Manager, Role::Admin] { + assert!(ROLES.iter().all(|&r| sender.may_message(r))); + assert_eq!(sender.messageable_roles(), None); + } + // The service principal has no mailbox in either direction. + assert!(ROLES.iter().all(|&r| !Role::Ai.may_message(r))); + assert!(ROLES.iter().all(|&r| !r.may_message(Role::Ai))); + } + #[tokio::test] async fn str_round_trips() { for role in ROLES { diff --git a/src/domain/user.rs b/src/domain/user.rs index 0e325d3..4dabec9 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -527,7 +527,11 @@ impl User { /// and surname. Needle and columns both go through /// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back — /// backs the user pickers. `role` narrows to one role (e.g. only students - /// for an enroll picker); `None` searches everyone. A blank `query` + /// for an enroll picker); `None` searches everyone. `allowed_roles` + /// narrows the *visible* set (the roles a non-staff caller may message — + /// see [`Role::messageable_roles`]); it is part of the query, not a + /// post-filter, so `total` counts only what the caller may see. A blank + /// `query` /// matches everyone, so blank + `role` is a role-scoped listing. Returns /// every match, ordered by username; the HTTP layer pages the result like /// any other list (no built-in cap — an over-broad fragment is windowed @@ -535,6 +539,7 @@ impl User { pub async fn search( query: &str, role: Option, + allowed_roles: Option<&[Role]>, limit: Option, offset: i64, db: &Database, @@ -553,6 +558,9 @@ impl User { if role.is_some() { clauses.push("role = $role"); } + if allowed_roles.is_some() { + clauses.push("role IN $allowed"); + } let where_clause = if clauses.is_empty() { "true".to_string() } else { @@ -563,6 +571,9 @@ impl User { if let Some(role) = role { list = list.bind("role", role); } + if let Some(allowed) = allowed_roles { + list = list.bind("allowed", allowed.to_vec()); + } list.run(limit, offset, db).await } diff --git a/src/lib.rs b/src/lib.rs index af8ad13..4439633 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,9 +44,9 @@ use crate::state::AppState; (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), - (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), + (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"), - (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), + (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused. The bookable list carries each slot's teacher identity (id, username, display name) to every caller, parents included — deliberate, since a conference cannot be booked from an anonymous calendar; it is the staff directory for booking, narrowed to whoever published bookable time, and the direct people routes stay closed to a parent"), (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), diff --git a/src/web/messages.rs b/src/web/messages.rs index 2342de0..c1c8642 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -157,10 +157,11 @@ impl MessageResponse { } } -/// Send a message to another user. Any authenticated user may write to any -/// existing user (parents included — messaging is the one place a parent -/// acts); only messaging yourself is refused. The send is server-stamped and -/// lands in the recipient's inbox unread. +/// Send a message to another user. Messaging is upward only below staff: a +/// student or parent may write to a teacher, manager or admin (parents +/// included — messaging is the one place a parent acts), never to another +/// student or parent; staff write to anyone. Messaging yourself is refused. +/// The send is server-stamped and lands in the recipient's inbox unread. #[utoipa::path( post, path = "/", @@ -171,6 +172,7 @@ impl MessageResponse { (status = 201, description = "Message sent", body = MessageResponse), (status = 400, description = "Invalid subject or body, or the recipient is yourself", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "A student or parent wrote to someone who is not staff", body = ErrorResponse), (status = 404, description = "No such recipient", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), @@ -197,6 +199,11 @@ async fn send_message( let recipient = User::read(&UserId::from_key(&req.recipient_id), &st.db) .await? .ok_or(AppError::NotFound)?; + if !user.get_role().may_message(recipient.get_role()) { + return Err(AppError::Forbidden( + "students and parents may only message staff (teacher or higher)", + )); + } let message = Message::send( user.get_id(), diff --git a/src/web/users.rs b/src/web/users.rs index 6c6a50d..07d43e5 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -28,9 +28,8 @@ use super::courses::visible_courses; use super::dto::AssignableRole; use super::dto::Role as RoleSchema; use super::{ - CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UploadFileForm, - UserResponse, ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, - store_blob, + CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse, + ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, store_blob, }; pub fn routes() -> OpenApiRouter { @@ -197,8 +196,12 @@ struct SearchUsers { } /// Find users by username or name — backs the pickers (enroll, grade, mark -/// attendance). Requires teacher+. `role` narrows to one role (e.g. -/// `role=student` for an enroll picker); a blank `q` with a `role` lists +/// attendance) and, for a student or parent, the one way to find the staff +/// member they are allowed to message. Any authenticated user may ask; a +/// caller below teacher only ever sees the roles they may message (teacher, +/// manager, admin), in the items *and* in `total`. `role` narrows to one role +/// (e.g. `role=student` for an enroll picker) — a student or parent naming a +/// role they may not message is refused; a blank `q` with a `role` lists /// everyone in that role. Paged via `?limit=&offset=` like the other lists /// (omit `limit` for every match); returns a `{items, total, limit, offset}` /// envelope carrying only id/username/display name — no contact details. @@ -212,12 +215,12 @@ struct SearchUsers { (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page), (status = 400, description = "Blank query without a role, unknown role, or invalid limit/offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "A student or parent asked for a role they may not message", body = ErrorResponse), ), )] async fn search_users( State(st): State, - _teacher: RequireTeacher, + CurrentUser(user): CurrentUser, Query(req): Query, ) -> Result>, AppError> { if req.q.trim().is_empty() && req.role.is_none() { @@ -232,7 +235,17 @@ async fn search_users( } .resolve()?; let role = req.role.as_deref().map(Role::try_from_str).transpose()?; - let (users, total) = User::search(&req.q, role, limit, offset, &st.db).await?; + // Below staff the caller may only see whom they may write to. Asking for a + // role outside that set is a refusal, not a silently empty page. + let allowed = user.get_role().messageable_roles(); + if let (Some(allowed), Some(role)) = (allowed, role) + && !allowed.contains(&role) + { + return Err(AppError::Forbidden( + "students and parents may only search staff (teacher or higher)", + )); + } + let (users, total) = User::search(&req.q, role, allowed, limit, offset, &st.db).await?; let items = users.iter().map(PersonRef::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/tests/e2e.rs b/tests/e2e.rs index 407fbe0..2510b3a 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -284,10 +284,22 @@ async fn full_user_journey() { .unwrap(); assert!(found["items"].as_array().unwrap().is_empty()); - let res = veli + // A student may search since #24 — and sees staff only: ali the teacher + // comes back, another student never would. + let found: Value = veli .get(format!("{base}/users/search?q=ali")) .send() .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(found["items"].as_array().unwrap().len(), 1); + assert_eq!(found["items"][0]["username"], "ali"); + let res = veli + .get(format!("{base}/users/search?q=vel&role=student")) + .send() + .await .unwrap(); assert_eq!(res.status(), StatusCode::FORBIDDEN); diff --git a/tests/integration.rs b/tests/integration.rs index 19c1759..1b74695 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -11059,6 +11059,76 @@ async fn attendance_report_tallies_events_and_sessions_per_course() { assert_eq!(res.status, StatusCode::NOT_FOUND); } +/// Issue #24: a student or parent needs a way to find the teacher they are +/// allowed to write to, so `/users/search` is no longer teacher+ — but below +/// staff it shows staff *only*, in the items and in `total` alike (the +/// restriction is in the query, not a post-filter over one page). +#[tokio::test] +async fn search_below_staff_sees_only_staff() { + let (app, db) = app_and_db().await; + // Both match `q=ay`: one student, one teacher. + let ayse = login(&app, "ayse").await; + let _ayhan = login_as(&app, &db, "ayhan", "teacher").await; + let anne = login_as(&app, &db, "anne", "parent").await; + let mudur = login_as(&app, &db, "mudur", "manager").await; + + for (who, cookie) in [("student", &ayse), ("parent", &anne)] { + let res = send(&app, "GET", "/users/search?q=ay", Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body); + let items = common::items(&res.body); + assert_eq!( + items.len(), + 1, + "{who} must see only the teacher: {}", + res.body + ); + assert_eq!(items[0]["username"], "ayhan", "{who}"); + assert_eq!( + res.body["total"], 1, + "{who}: total counts the visible set only" + ); + // Only the picker fields, as before — never contact details. + assert!(items[0].get("email").is_none(), "{who}"); + + // Naming a role they may not message is a refusal, not an empty page. + let res = send( + &app, + "GET", + "/users/search?q=ay&role=student", + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{who}: {}", res.body); + // A staff role they may message filters as usual. + let res = send( + &app, + "GET", + "/users/search?q=ay&role=teacher", + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body); + assert_eq!(common::items(&res.body).len(), 1, "{who}"); + } + + // Staff keep the unrestricted picker: the student is back in the results. + let res = send(&app, "GET", "/users/search?q=ay", Some(&mudur), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["total"], 2, "{}", res.body); + let res = send( + &app, + "GET", + "/users/search?q=ay&role=student", + Some(&mudur), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::items(&res.body)[0]["username"], "ayse"); +} + // --- users: search matching semantics -------------------------------------- /// The search fragment is matched with literal `CONTAINS` semantics — never @@ -13333,8 +13403,12 @@ async fn parent_observes_linked_students_and_nothing_else() { ) .await; assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + // Search is open to a parent since #24, but only onto staff: the linked + // student is a match by name and still must not come back. let res = send(&app, "GET", "/users/search?q=ali", Some(&parent), None).await; - assert_eq!(res.status, StatusCode::FORBIDDEN); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::items(&res.body).len(), 0, "{}", res.body); + assert_eq!(res.body["total"], 0); } /// A role change off either end of a tie sweeps it, exactly like promotion @@ -13671,6 +13745,57 @@ async fn messages_remember_the_folder_a_filed_copy_came_from() { assert_eq!(origins, vec![None], "the deleted side keeps no origin"); } +/// Issue #23: messaging is upward only below staff. A student or parent writes +/// to teacher+ and to nobody else; staff write in any direction. +#[tokio::test] +async fn messages_from_below_staff_go_upward_only() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; // student + let ali_id = me_id(&app, &ali).await; + let veli = login(&app, "veli").await; // student + let veli_id = me_id(&app, &veli).await; + let anne = login_as(&app, &db, "anne", "parent").await; + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let hoca_id = me_id(&app, &hoca).await; + let mudur = login_as(&app, &db, "mudur", "manager").await; + + let write = async |from: &str, to: &str| { + send( + &app, + "POST", + "/messages", + Some(from), + Some(json!({ "recipient_id": to, "subject": "selam" })), + ) + .await + }; + + // Sideways and downward from below staff: refused, with the rule spelled out. + let res = write(&ali, &veli_id).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + assert!( + res.body["error"] + .as_str() + .unwrap_or_default() + .contains("staff"), + "{}", + res.body + ); + assert_eq!(write(&anne, &ali_id).await.status, StatusCode::FORBIDDEN); + + // Upward: allowed for both. + assert_eq!(write(&ali, &hoca_id).await.status, StatusCode::CREATED); + assert_eq!(write(&anne, &hoca_id).await.status, StatusCode::CREATED); + + // Staff write anywhere — down to a student, sideways to a colleague. + assert_eq!(write(&hoca, &ali_id).await.status, StatusCode::CREATED); + assert_eq!(write(&mudur, &hoca_id).await.status, StatusCode::CREATED); + + // The refused sends left nothing behind. + let inbox = send(&app, "GET", "/messages", Some(&veli), None).await; + assert_eq!(common::items(&inbox.body).len(), 0, "{}", inbox.body); +} + #[tokio::test] async fn messages_guard_parties_recipients_and_folders() { let (app, db) = app_and_db().await; @@ -13678,6 +13803,8 @@ async fn messages_guard_parties_recipients_and_folders() { let ali_id = me_id(&app, &ali).await; let veli = login(&app, "veli").await; let parent = login_as(&app, &db, "anne", "parent").await; + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let hoca_id = me_id(&app, &hoca).await; // Sending to yourself or to nobody fails. let res = send( @@ -13699,7 +13826,8 @@ async fn messages_guard_parties_recipients_and_folders() { .await; assert_eq!(res.status, StatusCode::NOT_FOUND); - // A parent writes like anyone else — messaging is the role's one pen. + // A parent writes — messaging is the role's one pen — but upward only: to + // the teacher, not to the student. let res = send( &app, "POST", @@ -13708,6 +13836,15 @@ async fn messages_guard_parties_recipients_and_folders() { Some(json!({ "recipient_id": ali_id, "subject": "görüşme", "body": "uygun mu?" })), ) .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "POST", + "/messages", + Some(&parent), + Some(json!({ "recipient_id": hoca_id, "subject": "görüşme", "body": "uygun mu?" })), + ) + .await; assert_eq!(res.status, StatusCode::CREATED); assert_eq!(res.body["sender_role"], "parent"); assert_eq!( diff --git a/tests/regress_appointments.rs b/tests/regress_appointments.rs index fa1828e..31b49f5 100644 --- a/tests/regress_appointments.rs +++ b/tests/regress_appointments.rs @@ -221,9 +221,10 @@ async fn accepting_a_superseded_proposal_is_refused() { /// Not a defect — a pin on a deliberate disclosure, so a future "tightening" /// fails loudly instead of silently killing the booking flow. `GET /// /appointments/slots` hands a parent the slot teacher's `PersonRef`, an -/// identity all three of a parent's direct routes refuse them (`/users/{id}/ -/// profile` 403, `/users/search` teacher+, `/users` admin). It has to: you -/// cannot choose whom to book a conference with from an anonymous calendar. +/// identity a parent's direct routes still refuse them (`/users/{id}/profile` +/// 403, `/users` admin) — `/users/search` names staff since #24, but never says +/// which of them published bookable time. It has to: you cannot choose whom to +/// book a conference with from an anonymous calendar. #[tokio::test] async fn a_parent_reads_the_slot_teachers_identity() { let (app, db) = app_and_db().await; @@ -243,11 +244,7 @@ async fn a_parent_reads_the_slot_teachers_identity() { assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); // The parent is refused that identity everywhere it is asked for directly. - for uri in [ - format!("/users/{ali_id}/profile"), - "/users/search?q=ali".to_string(), - "/users".to_string(), - ] { + for uri in [format!("/users/{ali_id}/profile"), "/users".to_string()] { let res = send(&app, "GET", &uri, Some(&veli), None).await; assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}: {}", res.body); } diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs index 4d9c606..0f029ff 100644 --- a/tests/regress_profile.rs +++ b/tests/regress_profile.rs @@ -254,8 +254,10 @@ async fn display_name_falls_back_to_the_legal_name_then_null() { /// their legal name by every list that embeds a person. #[tokio::test] async fn embedded_person_refs_show_the_chosen_name_like_the_profile() { - let (app, _db) = app_and_db().await; - let ali = login(&app, "ali").await; + let (app, db) = app_and_db().await; + // The sender is staff: messaging is upward-only below teacher, and this + // test needs a send that lands, not the role rule. + let ali = login_as(&app, &db, "ali", "teacher").await; let ayse = login(&app, "ayse").await; let ayse_id = me_id(&app, &ayse).await;