forge
Explore
Log in

Don't you dare go Hollow

Messages go upward only

Browse files at this commit

1d423c070152c3eba763a910400b261fc9e40b2aAhmet Kaan GümüşParent: 6b1748c
  • feat
    • messages go upward only
    • students and parents can search staff
Show full message
✉️ feat: messages go upward only; students and parents can search staff

A student or parent may only write to a teacher, manager or admin
(`Role::may_message`); staff still write to anyone. `POST /messages`
answers 403 below that bar, and only new sends are gated — stored
student↔student rows stay readable and filable.

`GET /users/search` opens to every signed-in role: a caller below
teacher sees only the staff they may message (the restriction sits in
the query, so `total` stays right), and asking for `role=student` or
`role=parent` from there is a 403. This is the recipient picker the
messaging rule needs.

Closes #23, closes #24.
README.mdmodified+18 -10
@@ -590,8 +590,9 @@ the tie is the parent's whole power — they list their students
590 and homework reports in full. Student-only checks are exact (`role == student`), so a590 and homework reports in full. Student-only checks are exact (`role == student`), so a
591 parent can never enroll, sit an exam, be graded, or land on a roll call; and591 parent can never enroll, sit an exam, be graded, or land on a roll call; and
592 sitting below every staff bar, they can't touch anything else either — except592 sitting below every staff bar, they can't touch anything else either — except
593-messages, which any role sends and receives (that's how a parent reaches a593+messages, which they send *upward* only — to a teacher, manager or admin,
594-teacher), and their own **notes**, which carry no role bar at all: a note is594+never to a student or another parent (the same bar a student holds, issue
595+#23) — and their own **notes**, which carry no role bar at all: a note is
595 private to one person, so a role change must not confiscate it. It used to.596 private to one person, so a role change must not confiscate it. It used to.
596 While the note routes required `student`, a demotion locked the owner out of597 While the note routes required `student`, a demotion locked the owner out of
597 their own notes permanently — and since nothing else in the crate reads a note598 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.
1021 | 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. |1022 | 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. |
1022 | 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. |1023 | 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. |
1023 | 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=`. |1024 | 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=`. |
1024-| 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. |1025+| 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. |
1025 | 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. |1026 | 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. |
1026 | 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. |1027 | 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. |
1027 | 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. |1028 | 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.
1093 | 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`. |1094 | 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`. |
1094 | GET | `/users/me/profile` | student | The caller's own public profile — what everyone else sees of them. |1095 | GET | `/users/me/profile` | student | The caller's own public profile — what everyone else sees of them. |
1095 | 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=`. |1096 | 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=`. |
1096-| 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. |1097+| 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. |
1097 | GET | `/users/{id}` | admin | Fetch one user with their role and personal info. Admin only. |1098 | GET | `/users/{id}` | admin | Fetch one user with their role and personal info. Admin only. |
1098 | 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'. |1099 | 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'. |
1099 | 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. |1100 | 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`.
1581 Every slot carries its teacher's identity (id, username, display name), to a1582 Every slot carries its teacher's identity (id, username, display name), to a
1582 parent as much as to a student: **deliberate**, and not to be tightened. A1583 parent as much as to a student: **deliberate**, and not to be tightened. A
1583 parent's three direct routes to that identity are all shut (`GET1584 parent's three direct routes to that identity are all shut (`GET
1584-/users/{id}/profile` is a `403`, `/users/search` is teacher+, `/users` is1585+/users/{id}/profile` is a `403`, `/users` is admin, and `/users/search` names
1585-admin), but a conference cannot be booked off an anonymous calendar — this list1586+staff but not *which* of them holds office hours), but a conference cannot be
1587+booked off an anonymous calendar — this list
1586 *is* the staff directory for the booking flow, narrowed to whoever published1588 *is* the staff directory for the booking flow, narrowed to whoever published
1587 bookable time. The same refs on a booking (`teacher`, `proposed_by`,1589 bookable time. The same refs on a booking (`teacher`, `proposed_by`,
1588 `decided_by`) read the same way.1590 `decided_by`) read the same way.
@@ -1701,9 +1703,14 @@ too — they may still decide any booking by id.
1701 ## Messaging1703 ## Messaging
1702 1704
1703 One-to-one, mail-style (subject + body + an optional free-text `label` the UI1705 One-to-one, mail-style (subject + body + an optional free-text `label` the UI
1704-renders as a badge — "Etüt", "Sınav"; no threads): any user writes to any1706+renders as a badge — "Etüt", "Sınav"; no threads). Writing is **upward only
1705-user — student to teacher, parent to teacher, teacher to student; only1707+below staff**: a student or parent may write to a teacher, manager or admin
1706-messaging yourself is refused. A single stored message serves both parties,1708+(student to teacher, parent to teacher), never to another student or parent —
1709+that is a `403`. Staff write to anyone, in any direction (teacher to student).
1710+Messaging yourself is refused, and only new sends are gated: student↔student
1711+rows sent before the rule stay readable and filable. `GET /users/search` is
1712+how a student or parent finds the staff member to write to — it shows them
1713+staff and nobody else (issue #24). A single stored message serves both parties,
1707 but each **owns their copy independently**: the recipient's moves through1714 but each **owns their copy independently**: the recipient's moves through
1708 `inbox` → `archive`/`trash` and carries the `read` flag (the sender sees it1715 `inbox` → `archive`/`trash` and carries the `read` flag (the sender sees it
1709 as a read receipt); the sender's moves through `sent` → `archive`/`trash`. Filing or1716 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.
3125 Both of them hide one field: **`creator` is `null` below teacher+**. A class is3132 Both of them hide one field: **`creator` is `null` below teacher+**. A class is
3126 created by manager+ only, so shipping the creator to a student (or to their3133 created by manager+ only, so shipping the creator to a student (or to their
3127 linked parent) would hand out an office account's username and real name — an3134 linked parent) would hand out an office account's username and real name — an
3128-identity `GET /users` (admin-only) and `/users/search` (teacher+) both withhold.3135+identity `GET /users` (admin-only) withholds outright, and one `/users/search`
3136+hands a student only as the messaging directory — never as class metadata.
3129 The homeroom teacher is *not* hidden: naming them is the point of the read. On3137 The homeroom teacher is *not* hidden: naming them is the point of the read. On
3130 every staff-facing route (`GET /classes`, `/classes/{id}`, and the create/edit3138 every staff-facing route (`GET /classes`, `/classes/{id}`, and the create/edit
3131 responses) `creator` is populated exactly as before.3139 responses) `creator` is populated exactly as before.
src/domain/role.rsmodified+47 -0
@@ -65,6 +65,28 @@ impl Role {
65 pub fn at_least(self, min: Role) -> bool {65 pub fn at_least(self, min: Role) -> bool {
66 self >= min66 self >= min
67 }67 }
68+
69+ /// May `self` open a message thread with `recipient`? Messaging is upward
70+ /// only for the two roles below staff: a `Student` or `Parent` writes to
71+ /// teachers and above, never sideways or down (issue #23). Staff
72+ /// (`Teacher`+) write to anyone. [`Role::Ai`] is a service principal with
73+ /// no mailbox, so it neither sends nor receives.
74+ pub fn may_message(self, recipient: Role) -> bool {
75+ if self == Role::Ai || recipient == Role::Ai {
76+ return false;
77+ }
78+ self.at_least(Role::Teacher) || recipient.at_least(Role::Teacher)
79+ }
80+
81+ /// The roles `self` is allowed to write to, when that set is narrower than
82+ /// "everyone" — `None` means unrestricted. Backs the `/users/search`
83+ /// restriction, which must land in the query so `total` stays right.
84+ pub fn messageable_roles(self) -> Option<&'static [Role]> {
85+ match self.at_least(Role::Teacher) {
86+ true => None,
87+ false => Some(&[Role::Teacher, Role::Manager, Role::Admin]),
88+ }
89+ }
68 }90 }
69 91
70 #[cfg(test)]92 #[cfg(test)]
@@ -111,6 +133,31 @@ mod tests {
111 assert_eq!(Role::Ai.as_str(), "ai");133 assert_eq!(Role::Ai.as_str(), "ai");
112 }134 }
113 135
136+ #[tokio::test]
137+ async fn messaging_is_upward_only_below_staff() {
138+ // Sideways and downward writes from the two non-staff roles: refused.
139+ for sender in [Role::Student, Role::Parent] {
140+ for recipient in [Role::Student, Role::Parent] {
141+ assert!(!sender.may_message(recipient));
142+ }
143+ for staff in [Role::Teacher, Role::Manager, Role::Admin] {
144+ assert!(sender.may_message(staff));
145+ }
146+ assert_eq!(
147+ sender.messageable_roles(),
148+ Some(&[Role::Teacher, Role::Manager, Role::Admin][..])
149+ );
150+ }
151+ // Staff write to anyone, in any direction, and are unrestricted in search.
152+ for sender in [Role::Teacher, Role::Manager, Role::Admin] {
153+ assert!(ROLES.iter().all(|&r| sender.may_message(r)));
154+ assert_eq!(sender.messageable_roles(), None);
155+ }
156+ // The service principal has no mailbox in either direction.
157+ assert!(ROLES.iter().all(|&r| !Role::Ai.may_message(r)));
158+ assert!(ROLES.iter().all(|&r| !r.may_message(Role::Ai)));
159+ }
160+
114 #[tokio::test]161 #[tokio::test]
115 async fn str_round_trips() {162 async fn str_round_trips() {
116 for role in ROLES {163 for role in ROLES {
src/domain/user.rsmodified+12 -1
@@ -527,7 +527,11 @@ impl User {
527 /// and surname. Needle and columns both go through527 /// and surname. Needle and columns both go through
528 /// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back —528 /// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back —
529 /// backs the user pickers. `role` narrows to one role (e.g. only students529 /// backs the user pickers. `role` narrows to one role (e.g. only students
530- /// for an enroll picker); `None` searches everyone. A blank `query`530+ /// for an enroll picker); `None` searches everyone. `allowed_roles`
531+ /// narrows the *visible* set (the roles a non-staff caller may message —
532+ /// see [`Role::messageable_roles`]); it is part of the query, not a
533+ /// post-filter, so `total` counts only what the caller may see. A blank
534+ /// `query`
531 /// matches everyone, so blank + `role` is a role-scoped listing. Returns535 /// matches everyone, so blank + `role` is a role-scoped listing. Returns
532 /// every match, ordered by username; the HTTP layer pages the result like536 /// every match, ordered by username; the HTTP layer pages the result like
533 /// any other list (no built-in cap — an over-broad fragment is windowed537 /// any other list (no built-in cap — an over-broad fragment is windowed
@@ -535,6 +539,7 @@ impl User {
535 pub async fn search(539 pub async fn search(
536 query: &str,540 query: &str,
537 role: Option<Role>,541 role: Option<Role>,
542+ allowed_roles: Option<&[Role]>,
538 limit: Option<i64>,543 limit: Option<i64>,
539 offset: i64,544 offset: i64,
540 db: &Database,545 db: &Database,
@@ -553,6 +558,9 @@ impl User {
553 if role.is_some() {558 if role.is_some() {
554 clauses.push("role = $role");559 clauses.push("role = $role");
555 }560 }
561+ if allowed_roles.is_some() {
562+ clauses.push("role IN $allowed");
563+ }
556 let where_clause = if clauses.is_empty() {564 let where_clause = if clauses.is_empty() {
557 "true".to_string()565 "true".to_string()
558 } else {566 } else {
@@ -563,6 +571,9 @@ impl User {
563 if let Some(role) = role {571 if let Some(role) = role {
564 list = list.bind("role", role);572 list = list.bind("role", role);
565 }573 }
574+ if let Some(allowed) = allowed_roles {
575+ list = list.bind("allowed", allowed.to_vec());
576+ }
566 list.run(limit, offset, db).await577 list.run(limit, offset, db).await
567 }578 }
568 579
src/lib.rsmodified+2 -2
@@ -44,9 +44,9 @@ use crate::state::AppState;
44 (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"),44 (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"),
45 (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`"),45 (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`"),
46 (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"),46 (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"),
47- (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`"),47+ (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`"),
48 (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"),48 (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"),
49- (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"),49+ (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"),
50 (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"),50 (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"),
51 (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"),51 (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"),
52 (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"),52 (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"),
src/web/messages.rsmodified+11 -4
@@ -157,10 +157,11 @@ impl MessageResponse {
157 }157 }
158 }158 }
159 159
160-/// Send a message to another user. Any authenticated user may write to any160+/// Send a message to another user. Messaging is upward only below staff: a
161-/// existing user (parents included — messaging is the one place a parent161+/// student or parent may write to a teacher, manager or admin (parents
162-/// acts); only messaging yourself is refused. The send is server-stamped and162+/// included — messaging is the one place a parent acts), never to another
163-/// lands in the recipient's inbox unread.163+/// student or parent; staff write to anyone. Messaging yourself is refused.
164+/// The send is server-stamped and lands in the recipient's inbox unread.
164 #[utoipa::path(165 #[utoipa::path(
165 post,166 post,
166 path = "/",167 path = "/",
@@ -171,6 +172,7 @@ impl MessageResponse {
171 (status = 201, description = "Message sent", body = MessageResponse),172 (status = 201, description = "Message sent", body = MessageResponse),
172 (status = 400, description = "Invalid subject or body, or the recipient is yourself", body = ErrorResponse),173 (status = 400, description = "Invalid subject or body, or the recipient is yourself", body = ErrorResponse),
173 (status = 401, description = "Not authenticated", body = ErrorResponse),174 (status = 401, description = "Not authenticated", body = ErrorResponse),
175+ (status = 403, description = "A student or parent wrote to someone who is not staff", body = ErrorResponse),
174 (status = 404, description = "No such recipient", body = ErrorResponse),176 (status = 404, description = "No such recipient", body = ErrorResponse),
175 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),177 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
176 ),178 ),
@@ -197,6 +199,11 @@ async fn send_message(
197 let recipient = User::read(&UserId::from_key(&req.recipient_id), &st.db)199 let recipient = User::read(&UserId::from_key(&req.recipient_id), &st.db)
198 .await?200 .await?
199 .ok_or(AppError::NotFound)?;201 .ok_or(AppError::NotFound)?;
202+ if !user.get_role().may_message(recipient.get_role()) {
203+ return Err(AppError::Forbidden(
204+ "students and parents may only message staff (teacher or higher)",
205+ ));
206+ }
200 207
201 let message = Message::send(208 let message = Message::send(
202 user.get_id(),209 user.get_id(),
src/web/users.rsmodified+21 -8
@@ -28,9 +28,8 @@ use super::courses::visible_courses;
28 use super::dto::AssignableRole;28 use super::dto::AssignableRole;
29 use super::dto::Role as RoleSchema;29 use super::dto::Role as RoleSchema;
30 use super::{30 use super::{
31- CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UploadFileForm,31+ CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse,
32- UserResponse, ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob,32+ ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, store_blob,
33- store_blob,
34 };33 };
35 34
36 pub fn routes() -> OpenApiRouter<AppState> {35 pub fn routes() -> OpenApiRouter<AppState> {
@@ -197,8 +196,12 @@ struct SearchUsers {
197 }196 }
198 197
199 /// Find users by username or name — backs the pickers (enroll, grade, mark198 /// Find users by username or name — backs the pickers (enroll, grade, mark
200-/// attendance). Requires teacher+. `role` narrows to one role (e.g.199+/// attendance) and, for a student or parent, the one way to find the staff
201-/// `role=student` for an enroll picker); a blank `q` with a `role` lists200+/// member they are allowed to message. Any authenticated user may ask; a
201+/// caller below teacher only ever sees the roles they may message (teacher,
202+/// manager, admin), in the items *and* in `total`. `role` narrows to one role
203+/// (e.g. `role=student` for an enroll picker) — a student or parent naming a
204+/// role they may not message is refused; a blank `q` with a `role` lists
202 /// everyone in that role. Paged via `?limit=&offset=` like the other lists205 /// everyone in that role. Paged via `?limit=&offset=` like the other lists
203 /// (omit `limit` for every match); returns a `{items, total, limit, offset}`206 /// (omit `limit` for every match); returns a `{items, total, limit, offset}`
204 /// envelope carrying only id/username/display name — no contact details.207 /// envelope carrying only id/username/display name — no contact details.
@@ -212,12 +215,12 @@ struct SearchUsers {
212 (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),215 (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),
213 (status = 400, description = "Blank query without a role, unknown role, or invalid limit/offset", body = ErrorResponse),216 (status = 400, description = "Blank query without a role, unknown role, or invalid limit/offset", body = ErrorResponse),
214 (status = 401, description = "Not authenticated", body = ErrorResponse),217 (status = 401, description = "Not authenticated", body = ErrorResponse),
215- (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),218+ (status = 403, description = "A student or parent asked for a role they may not message", body = ErrorResponse),
216 ),219 ),
217 )]220 )]
218 async fn search_users(221 async fn search_users(
219 State(st): State<AppState>,222 State(st): State<AppState>,
220- _teacher: RequireTeacher,223+ CurrentUser(user): CurrentUser,
221 Query(req): Query<SearchUsers>,224 Query(req): Query<SearchUsers>,
222 ) -> Result<Json<Page<PersonRef>>, AppError> {225 ) -> Result<Json<Page<PersonRef>>, AppError> {
223 if req.q.trim().is_empty() && req.role.is_none() {226 if req.q.trim().is_empty() && req.role.is_none() {
@@ -232,7 +235,17 @@ async fn search_users(
232 }235 }
233 .resolve()?;236 .resolve()?;
234 let role = req.role.as_deref().map(Role::try_from_str).transpose()?;237 let role = req.role.as_deref().map(Role::try_from_str).transpose()?;
235- let (users, total) = User::search(&req.q, role, limit, offset, &st.db).await?;238+ // Below staff the caller may only see whom they may write to. Asking for a
239+ // role outside that set is a refusal, not a silently empty page.
240+ let allowed = user.get_role().messageable_roles();
241+ if let (Some(allowed), Some(role)) = (allowed, role)
242+ && !allowed.contains(&role)
243+ {
244+ return Err(AppError::Forbidden(
245+ "students and parents may only search staff (teacher or higher)",
246+ ));
247+ }
248+ let (users, total) = User::search(&req.q, role, allowed, limit, offset, &st.db).await?;
236 let items = users.iter().map(PersonRef::new).collect();249 let items = users.iter().map(PersonRef::new).collect();
237 Ok(Json(Page::new(items, total, limit, offset)))250 Ok(Json(Page::new(items, total, limit, offset)))
238 }251 }
tests/e2e.rsmodified+13 -1
@@ -284,10 +284,22 @@ async fn full_user_journey() {
284 .unwrap();284 .unwrap();
285 assert!(found["items"].as_array().unwrap().is_empty());285 assert!(found["items"].as_array().unwrap().is_empty());
286 286
287- let res = veli287+ // A student may search since #24 — and sees staff only: ali the teacher
288+ // comes back, another student never would.
289+ let found: Value = veli
288 .get(format!("{base}/users/search?q=ali"))290 .get(format!("{base}/users/search?q=ali"))
289 .send()291 .send()
290 .await292 .await
293+ .unwrap()
294+ .json()
295+ .await
296+ .unwrap();
297+ assert_eq!(found["items"].as_array().unwrap().len(), 1);
298+ assert_eq!(found["items"][0]["username"], "ali");
299+ let res = veli
300+ .get(format!("{base}/users/search?q=vel&role=student"))
301+ .send()
302+ .await
291 .unwrap();303 .unwrap();
292 assert_eq!(res.status(), StatusCode::FORBIDDEN);304 assert_eq!(res.status(), StatusCode::FORBIDDEN);
293 305
tests/integration.rsmodified+139 -2
@@ -11059,6 +11059,76 @@ async fn attendance_report_tallies_events_and_sessions_per_course() {
11059 assert_eq!(res.status, StatusCode::NOT_FOUND);11059 assert_eq!(res.status, StatusCode::NOT_FOUND);
11060 }11060 }
11061 11061
11062+/// Issue #24: a student or parent needs a way to find the teacher they are
11063+/// allowed to write to, so `/users/search` is no longer teacher+ — but below
11064+/// staff it shows staff *only*, in the items and in `total` alike (the
11065+/// restriction is in the query, not a post-filter over one page).
11066+#[tokio::test]
11067+async fn search_below_staff_sees_only_staff() {
11068+ let (app, db) = app_and_db().await;
11069+ // Both match `q=ay`: one student, one teacher.
11070+ let ayse = login(&app, "ayse").await;
11071+ let _ayhan = login_as(&app, &db, "ayhan", "teacher").await;
11072+ let anne = login_as(&app, &db, "anne", "parent").await;
11073+ let mudur = login_as(&app, &db, "mudur", "manager").await;
11074+
11075+ for (who, cookie) in [("student", &ayse), ("parent", &anne)] {
11076+ let res = send(&app, "GET", "/users/search?q=ay", Some(cookie), None).await;
11077+ assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body);
11078+ let items = common::items(&res.body);
11079+ assert_eq!(
11080+ items.len(),
11081+ 1,
11082+ "{who} must see only the teacher: {}",
11083+ res.body
11084+ );
11085+ assert_eq!(items[0]["username"], "ayhan", "{who}");
11086+ assert_eq!(
11087+ res.body["total"], 1,
11088+ "{who}: total counts the visible set only"
11089+ );
11090+ // Only the picker fields, as before — never contact details.
11091+ assert!(items[0].get("email").is_none(), "{who}");
11092+
11093+ // Naming a role they may not message is a refusal, not an empty page.
11094+ let res = send(
11095+ &app,
11096+ "GET",
11097+ "/users/search?q=ay&role=student",
11098+ Some(cookie),
11099+ None,
11100+ )
11101+ .await;
11102+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{who}: {}", res.body);
11103+ // A staff role they may message filters as usual.
11104+ let res = send(
11105+ &app,
11106+ "GET",
11107+ "/users/search?q=ay&role=teacher",
11108+ Some(cookie),
11109+ None,
11110+ )
11111+ .await;
11112+ assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body);
11113+ assert_eq!(common::items(&res.body).len(), 1, "{who}");
11114+ }
11115+
11116+ // Staff keep the unrestricted picker: the student is back in the results.
11117+ let res = send(&app, "GET", "/users/search?q=ay", Some(&mudur), None).await;
11118+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11119+ assert_eq!(res.body["total"], 2, "{}", res.body);
11120+ let res = send(
11121+ &app,
11122+ "GET",
11123+ "/users/search?q=ay&role=student",
11124+ Some(&mudur),
11125+ None,
11126+ )
11127+ .await;
11128+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11129+ assert_eq!(common::items(&res.body)[0]["username"], "ayse");
11130+}
11131+
11062 // --- users: search matching semantics --------------------------------------11132 // --- users: search matching semantics --------------------------------------
11063 11133
11064 /// The search fragment is matched with literal `CONTAINS` semantics — never11134 /// The search fragment is matched with literal `CONTAINS` semantics — never
@@ -13333,8 +13403,12 @@ async fn parent_observes_linked_students_and_nothing_else() {
13333 )13403 )
13334 .await;13404 .await;
13335 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);13405 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
13406+ // Search is open to a parent since #24, but only onto staff: the linked
13407+ // student is a match by name and still must not come back.
13336 let res = send(&app, "GET", "/users/search?q=ali", Some(&parent), None).await;13408 let res = send(&app, "GET", "/users/search?q=ali", Some(&parent), None).await;
13337- assert_eq!(res.status, StatusCode::FORBIDDEN);13409+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
13410+ assert_eq!(common::items(&res.body).len(), 0, "{}", res.body);
13411+ assert_eq!(res.body["total"], 0);
13338 }13412 }
13339 13413
13340 /// A role change off either end of a tie sweeps it, exactly like promotion13414 /// 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() {
13671 assert_eq!(origins, vec![None], "the deleted side keeps no origin");13745 assert_eq!(origins, vec![None], "the deleted side keeps no origin");
13672 }13746 }
13673 13747
13748+/// Issue #23: messaging is upward only below staff. A student or parent writes
13749+/// to teacher+ and to nobody else; staff write in any direction.
13750+#[tokio::test]
13751+async fn messages_from_below_staff_go_upward_only() {
13752+ let (app, db) = app_and_db().await;
13753+ let ali = login(&app, "ali").await; // student
13754+ let ali_id = me_id(&app, &ali).await;
13755+ let veli = login(&app, "veli").await; // student
13756+ let veli_id = me_id(&app, &veli).await;
13757+ let anne = login_as(&app, &db, "anne", "parent").await;
13758+ let hoca = login_as(&app, &db, "hoca", "teacher").await;
13759+ let hoca_id = me_id(&app, &hoca).await;
13760+ let mudur = login_as(&app, &db, "mudur", "manager").await;
13761+
13762+ let write = async |from: &str, to: &str| {
13763+ send(
13764+ &app,
13765+ "POST",
13766+ "/messages",
13767+ Some(from),
13768+ Some(json!({ "recipient_id": to, "subject": "selam" })),
13769+ )
13770+ .await
13771+ };
13772+
13773+ // Sideways and downward from below staff: refused, with the rule spelled out.
13774+ let res = write(&ali, &veli_id).await;
13775+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
13776+ assert!(
13777+ res.body["error"]
13778+ .as_str()
13779+ .unwrap_or_default()
13780+ .contains("staff"),
13781+ "{}",
13782+ res.body
13783+ );
13784+ assert_eq!(write(&anne, &ali_id).await.status, StatusCode::FORBIDDEN);
13785+
13786+ // Upward: allowed for both.
13787+ assert_eq!(write(&ali, &hoca_id).await.status, StatusCode::CREATED);
13788+ assert_eq!(write(&anne, &hoca_id).await.status, StatusCode::CREATED);
13789+
13790+ // Staff write anywhere — down to a student, sideways to a colleague.
13791+ assert_eq!(write(&hoca, &ali_id).await.status, StatusCode::CREATED);
13792+ assert_eq!(write(&mudur, &hoca_id).await.status, StatusCode::CREATED);
13793+
13794+ // The refused sends left nothing behind.
13795+ let inbox = send(&app, "GET", "/messages", Some(&veli), None).await;
13796+ assert_eq!(common::items(&inbox.body).len(), 0, "{}", inbox.body);
13797+}
13798+
13674 #[tokio::test]13799 #[tokio::test]
13675 async fn messages_guard_parties_recipients_and_folders() {13800 async fn messages_guard_parties_recipients_and_folders() {
13676 let (app, db) = app_and_db().await;13801 let (app, db) = app_and_db().await;
@@ -13678,6 +13803,8 @@ async fn messages_guard_parties_recipients_and_folders() {
13678 let ali_id = me_id(&app, &ali).await;13803 let ali_id = me_id(&app, &ali).await;
13679 let veli = login(&app, "veli").await;13804 let veli = login(&app, "veli").await;
13680 let parent = login_as(&app, &db, "anne", "parent").await;13805 let parent = login_as(&app, &db, "anne", "parent").await;
13806+ let hoca = login_as(&app, &db, "hoca", "teacher").await;
13807+ let hoca_id = me_id(&app, &hoca).await;
13681 13808
13682 // Sending to yourself or to nobody fails.13809 // Sending to yourself or to nobody fails.
13683 let res = send(13810 let res = send(
@@ -13699,7 +13826,8 @@ async fn messages_guard_parties_recipients_and_folders() {
13699 .await;13826 .await;
13700 assert_eq!(res.status, StatusCode::NOT_FOUND);13827 assert_eq!(res.status, StatusCode::NOT_FOUND);
13701 13828
13702- // A parent writes like anyone else — messaging is the role's one pen.13829+ // A parent writes — messaging is the role's one pen — but upward only: to
13830+ // the teacher, not to the student.
13703 let res = send(13831 let res = send(
13704 &app,13832 &app,
13705 "POST",13833 "POST",
@@ -13708,6 +13836,15 @@ async fn messages_guard_parties_recipients_and_folders() {
13708 Some(json!({ "recipient_id": ali_id, "subject": "görüşme", "body": "uygun mu?" })),13836 Some(json!({ "recipient_id": ali_id, "subject": "görüşme", "body": "uygun mu?" })),
13709 )13837 )
13710 .await;13838 .await;
13839+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
13840+ let res = send(
13841+ &app,
13842+ "POST",
13843+ "/messages",
13844+ Some(&parent),
13845+ Some(json!({ "recipient_id": hoca_id, "subject": "görüşme", "body": "uygun mu?" })),
13846+ )
13847+ .await;
13711 assert_eq!(res.status, StatusCode::CREATED);13848 assert_eq!(res.status, StatusCode::CREATED);
13712 assert_eq!(res.body["sender_role"], "parent");13849 assert_eq!(res.body["sender_role"], "parent");
13713 assert_eq!(13850 assert_eq!(
tests/regress_appointments.rsmodified+5 -8
@@ -221,9 +221,10 @@ async fn accepting_a_superseded_proposal_is_refused() {
221 /// Not a defect — a pin on a deliberate disclosure, so a future "tightening"221 /// Not a defect — a pin on a deliberate disclosure, so a future "tightening"
222 /// fails loudly instead of silently killing the booking flow. `GET222 /// fails loudly instead of silently killing the booking flow. `GET
223 /// /appointments/slots` hands a parent the slot teacher's `PersonRef`, an223 /// /appointments/slots` hands a parent the slot teacher's `PersonRef`, an
224-/// identity all three of a parent's direct routes refuse them (`/users/{id}/224+/// identity a parent's direct routes still refuse them (`/users/{id}/profile`
225-/// profile` 403, `/users/search` teacher+, `/users` admin). It has to: you225+/// 403, `/users` admin) — `/users/search` names staff since #24, but never says
226-/// cannot choose whom to book a conference with from an anonymous calendar.226+/// which of them published bookable time. It has to: you cannot choose whom to
227+/// book a conference with from an anonymous calendar.
227 #[tokio::test]228 #[tokio::test]
228 async fn a_parent_reads_the_slot_teachers_identity() {229 async fn a_parent_reads_the_slot_teachers_identity() {
229 let (app, db) = app_and_db().await;230 let (app, db) = app_and_db().await;
@@ -243,11 +244,7 @@ async fn a_parent_reads_the_slot_teachers_identity() {
243 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);244 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
244 245
245 // The parent is refused that identity everywhere it is asked for directly.246 // The parent is refused that identity everywhere it is asked for directly.
246- for uri in [247+ for uri in [format!("/users/{ali_id}/profile"), "/users".to_string()] {
247- format!("/users/{ali_id}/profile"),
248- "/users/search?q=ali".to_string(),
249- "/users".to_string(),
250- ] {
251 let res = send(&app, "GET", &uri, Some(&veli), None).await;248 let res = send(&app, "GET", &uri, Some(&veli), None).await;
252 assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}: {}", res.body);249 assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}: {}", res.body);
253 }250 }
tests/regress_profile.rsmodified+4 -2
@@ -254,8 +254,10 @@ async fn display_name_falls_back_to_the_legal_name_then_null() {
254 /// their legal name by every list that embeds a person.254 /// their legal name by every list that embeds a person.
255 #[tokio::test]255 #[tokio::test]
256 async fn embedded_person_refs_show_the_chosen_name_like_the_profile() {256 async fn embedded_person_refs_show_the_chosen_name_like_the_profile() {
257- let (app, _db) = app_and_db().await;257+ let (app, db) = app_and_db().await;
258- let ali = login(&app, "ali").await;258+ // The sender is staff: messaging is upward-only below teacher, and this
259+ // test needs a send that lands, not the role rule.
260+ let ali = login_as(&app, &db, "ali", "teacher").await;
259 let ayse = login(&app, "ayse").await;261 let ayse = login(&app, "ayse").await;
260 let ayse_id = me_id(&app, &ayse).await;262 let ayse_id = me_id(&app, &ayse).await;
261 263