forge
Explore
Log in

Don't you dare go Hollow

Show a person under the name they chose, everywhere

Browse files at this commit

4e4a80879b2337c9861e84ebcf1dafe8fa93fef8Ahmet Kaan GümüşParent: 73eb272
  • fix
    • show a person under the name they chose, everywhere
Show full message
👤 fix: show a person under the name they chose, everywhere

`PersonRef::new` built `display_name` from `name` + `surname` only and never
read the stored `display_name`, so anybody who chose one was still rendered
under their legal name by every route that embeds a person — messages,
`/users/search`, course creator/teachers, rosters, exam results, appointments,
meals, payments, the question pool. Meanwhile `GET /users/{id}/profile` served
the chosen name, and `GET /users/{id}` is admin-only, so the profile was the
one surface telling the truth.

The rule was written twice: `ProfileResponse` did the three documented steps
(stored, else the join, else null) and borrowed only the join half from
`PersonRef`, which had the other half missing. Two hand-kept copies of one
documented rule is how it drifted, so the resolve now lives once, in
`PersonRef::new`; the profile calls it whole. The test that was missing is the
one that fails on drift: a display name differing from the join, asserted on a
`PersonRef` route and against the profile's own answer, at all three steps.

Second, unrelated to the resolve but on the same doc: `profile_of` claimed only
`stats.courses` and `stats.classes` cross a gate the reader would fail. Eight
more do — `pomodoro_focus_ms`, `pomodoro_focus_ms_total`,
`lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`,
`exam_sat_total`, `high_mark_total` mirror data behind `ensure_can_observe`,
and for an exactly-teacher reader they are wider than the reports themselves.
The disclosure stays (motivational counters, no object named); the comment,
the schema description, the tag and the README now say so accurately.
README.mdmodified+23 -3
@@ -1223,7 +1223,11 @@ link *and* the target's live role — so unlinking a student, or promoting one
1223 out of `student`, stops the reads at once rather than at the next login.1223 out of `student`, stops the reads at once rather than at the next login.
1224 1224
1225 **`display_name`** resolves in three steps: the stored `display_name`, else the1225 **`display_name`** resolves in three steps: the stored `display_name`, else the
1226-`"name surname"` join, else `null`. It does **not** replace `name`/`surname` —1226+`"name surname"` join, else `null`. Those same three steps are what **every
1227+embedded person ref** (`{id, username, display_name}`) shows, everywhere one
1228+appears — a message's sender, a course's teachers, a roster row, an exam result:
1229+a person who chose a display name is shown under it school-wide, which is the
1230+point of choosing one. It does **not** replace `name`/`surname` —
1227 those stay the school-office record, and an admin still edits them — and it1231 those stay the school-office record, and an admin still edits them — and it
1228 deliberately does not enter the user search fold: `/users/search` finds people1232 deliberately does not enter the user search fold: `/users/search` finds people
1229 by the name the office knows them under, not by a nickname they picked this1233 by the name the office knows them under, not by a nickname they picked this
@@ -1256,8 +1260,9 @@ own profile and a manager's read are never cut, since both already see the
1256 whole list, and the 20-course truncation runs *after* the filter, so a reader1260 whole list, and the 20-course truncation runs *after* the filter, so a reader
1257 gets up to 20 courses they can actually open. `stats.courses` stays the1261 gets up to 20 courses they can actually open. `stats.courses` stays the
1258 owner's true total on purpose — it is the motivational counter, a per-reader1262 owner's true total on purpose — it is the motivational counter, a per-reader
1259-number would be meaningless, and a magnitude names no course. One consequence,1263+number would be meaningless, and a magnitude names no course (see "every
1260-by design: a teacher you share nothing with has an empty `courses` block.1264+number in `stats`" below). One consequence, by design: a teacher you share
1265+nothing with has an empty `courses` block.
1261 1266
1262 **The class block is cut the same way, at the same bar `GET /classes/user/{id}`1267 **The class block is cut the same way, at the same bar `GET /classes/user/{id}`
1263 holds**: teacher+, a parent linked to that student, or the owner reading their1268 holds**: teacher+, a parent linked to that student, or the owner reading their
@@ -1272,6 +1277,21 @@ either sees the owner's section list or sees none of it. `stats.classes`, like
1272 `stats.courses`, stays the owner's true total for every reader — a magnitude1277 `stats.courses`, stays the owner's true total for every reader — a magnitude
1273 names no class.1278 names no class.
1274 1279
1280+**Every number in `stats` is the owner's true total for every reader**, and
1281+that is a decision rather than an oversight. It is not only the two counters
1282+above: `pomodoro_focus_ms` and `pomodoro_focus_ms_total` are the same figure
1283+`GET /pomodoro/{id}` serves as `total_focus_ms` behind its observer gate, and
1284+`lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`,
1285+`exam_sat_total` and `high_mark_total` are magnitudes of the mark and
1286+attendance data that same gate holds — for a reader who is exactly a `teacher`
1287+they are in fact *wider* than `GET /marks/user/{id}` and
1288+`GET /attendance/user/{id}`, which narrow to the courses that teacher manages.
1289+They stay unnarrowed because they are motivational counters: a magnitude names
1290+no course, no class, no lesson and no exam, and a per-reader figure would make
1291+one profile read differently to different people, which is worse than useless
1292+on a number whose whole job is to say "this is how much you have done". The
1293+*named* things — the class and course blocks — keep their gates, above.
1294+
1275 **`stats` holds sixteen numbers of two different kinds, and the difference is1295 **`stats` holds sixteen numbers of two different kinds, and the difference is
1276 worth knowing.** `pomodoro_sessions`, `pomodoro_focus_ms`, `courses` and1296 worth knowing.** `pomodoro_sessions`, `pomodoro_focus_ms`, `courses` and
1277 `classes` are **computed at read**: they are recounted from the live rows on1297 `classes` are **computed at read**: they are recounted from the live rows on
src/lib.rsmodified+1 -1
@@ -44,7 +44,7 @@ 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. `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. `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` — 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+. `stats.courses` and `stats.classes` stay the owner's true totals either way — they are motivational counters, and a magnitude names no course and no class. `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 (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`"),
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`)"),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`)"),
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 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"),
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"),
src/web/dto.rsmodified+11 -2
@@ -52,12 +52,18 @@ pub struct PersonRef {
52 pub id: String,52 pub id: String,
53 #[schema(example = "ada")]53 #[schema(example = "ada")]
54 pub username: String,54 pub username: String,
55- /// `"Name Surname"` when the profile carries either; `null` otherwise.55+ /// The name to show this person under, resolved in the same three steps
56+ /// `GET /users/{id}/profile` uses: the stored `display_name`, else the
57+ /// `"Name Surname"` join, else `null`.
56 #[schema(example = "Ada Lovelace")]58 #[schema(example = "Ada Lovelace")]
57 pub display_name: Option<String>,59 pub display_name: Option<String>,
58 }60 }
59 61
60 impl PersonRef {62 impl PersonRef {
63+ /// The one spelling of the display-name resolve — `ProfileResponse` calls
64+ /// this too. It was two hand-kept copies once, and the copy here forgot the
65+ /// stored name, so a person who chose one was still shown their legal name
66+ /// by every list that embeds a person.
61 pub fn new(user: &User) -> Self {67 pub fn new(user: &User) -> Self {
62 let full: Vec<&str> = [user.get_name(), user.get_surname()]68 let full: Vec<&str> = [user.get_name(), user.get_surname()]
63 .into_iter()69 .into_iter()
@@ -67,7 +73,10 @@ impl PersonRef {
67 Self {73 Self {
68 id: user.get_id().key().to_string(),74 id: user.get_id().key().to_string(),
69 username: user.get_username().as_str().to_string(),75 username: user.get_username().as_str().to_string(),
70- display_name: (!full.is_empty()).then(|| full.join(" ")),76+ display_name: user
77+ .get_display_name()
78+ .map(|chosen| chosen.as_str().to_string())
79+ .or_else(|| (!full.is_empty()).then(|| full.join(" "))),
71 }80 }
72 }81 }
73 82
src/web/users.rsmodified+30 -11
@@ -777,6 +777,13 @@ struct ProfileCourseRef {
777 ///777 ///
778 /// Some are staff counters and some student ones; a role that never does the778 /// Some are staff counters and some student ones; a role that never does the
779 /// work simply reads zero, which is why no key is conditional.779 /// work simply reads zero, which is why no key is conditional.
780+///
781+/// Every number here is the **owner's** true total for every reader, never
782+/// narrowed per viewer — deliberately so even where the rows behind it sit
783+/// behind a gate this reader would fail (`GET /pomodoro/{id}`,
784+/// `GET /marks/user/{id}`, `GET /attendance/user/{id}`). A magnitude names no
785+/// course, class, lesson or exam, and a per-reader counter would make one
786+/// profile read differently to different people.
780 #[derive(Serialize, ToSchema)]787 #[derive(Serialize, ToSchema)]
781 struct ProfileStatsResponse {788 struct ProfileStatsResponse {
782 /// Finished pomodoro stints; an open one counts for nothing.789 /// Finished pomodoro stints; an open one counts for nothing.
@@ -846,10 +853,22 @@ struct ProfileStatsResponse {
846 /// rest of the profile is still public to them.853 /// rest of the profile is still public to them.
847 ///854 ///
848 /// So no *named* thing here crosses a gate the viewer would fail directly. The855 /// So no *named* thing here crosses a gate the viewer would fail directly. The
849-/// two magnitudes deliberately do: `stats.courses` and `stats.classes` stay the856+/// magnitudes deliberately do — **every** one of them, not just the two that
850-/// owner's true totals for every reader — they are the motivational counters, a857+/// count the gated blocks. `stats.courses` and `stats.classes` are the obvious
851-/// per-reader number would be meaningless, and a magnitude names no course and858+/// pair; `pomodoro_focus_ms` and `pomodoro_focus_ms_total` are byte-identical
852-/// no class.859+/// to the `total_focus_ms` that `GET /pomodoro/{id}` serves behind
860+/// [`ensure_can_observe`]; and `lessons_attended_total`,
861+/// `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and
862+/// `high_mark_total` are magnitudes of the same report data that gate holds —
863+/// for a reader who is exactly [`Role::Teacher`] they are in fact *wider* than
864+/// the reports themselves, which [`crate::web::marks`] and
865+/// [`crate::web::attendance`] narrow to the courses that teacher manages.
866+///
867+/// That is the decision, not an oversight: every magnitude in `stats` is the
868+/// owner's true total for every reader. They are the motivational counters, a
869+/// per-reader number would make one profile read differently to different
870+/// people, and a magnitude names no course, no class, no lesson and no exam —
871+/// the *named* things stay behind their own gates, above.
853 async fn profile_of(872 async fn profile_of(
854 st: &AppState,873 st: &AppState,
855 user: &User,874 user: &User,
@@ -903,11 +922,9 @@ async fn profile_of(
903 Ok(ProfileResponse {922 Ok(ProfileResponse {
904 id: id.key().to_string(),923 id: id.key().to_string(),
905 username: user.get_username().as_str().to_string(),924 username: user.get_username().as_str().to_string(),
906- display_name: user925+ // The whole three-step resolve lives in `PersonRef` — one spelling of
907- .get_display_name()926+ // it, so this profile and every embedded person ref cannot disagree.
908- .map(|name| name.as_str().to_string())927+ display_name: PersonRef::new(user).display_name,
909- // The legal-name join lives in `PersonRef` — one spelling of it.
910- .or_else(|| PersonRef::new(user).display_name),
911 role: user.get_role().into(),928 role: user.get_role().into(),
912 bio: user.get_bio().map(|bio| bio.as_str().to_string()),929 bio: user.get_bio().map(|bio| bio.as_str().to_string()),
913 avatar: user930 avatar: user
@@ -1047,8 +1064,10 @@ async fn my_profile(
1047 /// would pass `GET /courses/{id}` on. The class block holds the same bar as1064 /// would pass `GET /courses/{id}` on. The class block holds the same bar as
1048 /// `GET /classes/user/{id}` — teacher+, a parent linked to this student, or the1065 /// `GET /classes/user/{id}` — teacher+, a parent linked to this student, or the
1049 /// owner themselves; every other reader gets an empty `classes` array rather1066 /// owner themselves; every other reader gets an empty `classes` array rather
1050-/// than a 403. `stats.courses` and `stats.classes` stay the owner's true totals1067+/// than a 403. Every number in `stats` stays the owner's true total either way,
1051-/// either way.1068+/// including the ones whose underlying reports are gated (`/pomodoro/{id}`,
1069+/// `/marks/user/{id}`, `/attendance/user/{id}`): they are motivational
1070+/// counters, and a magnitude names no course, class, lesson or exam.
1052 #[utoipa::path(1071 #[utoipa::path(
1053 get,1072 get,
1054 path = "/{id}/profile",1073 path = "/{id}/profile",
tests/regress_profile.rsmodified+89 -0
@@ -246,6 +246,91 @@ async fn display_name_falls_back_to_the_legal_name_then_null() {
246 );246 );
247 }247 }
248 248
249+/// The embedded person refs resolve the display name in the *same* three steps
250+/// the profile does — the rule has one spelling, and this asserts the two
251+/// surfaces agree at every step. It shipped broken because no test had ever set
252+/// a `display_name` that differs from the legal-name join: the person ref
253+/// skipped the stored name outright, so anyone who chose one was still shown
254+/// their legal name by every list that embeds a person.
255+#[tokio::test]
256+async fn embedded_person_refs_show_the_chosen_name_like_the_profile() {
257+ let (app, _db) = app_and_db().await;
258+ let ali = login(&app, "ali").await;
259+ let ayse = login(&app, "ayse").await;
260+ let ayse_id = me_id(&app, &ayse).await;
261+
262+ // What `ali` sees of `ayse` in a person ref, and what her own profile says.
263+ let as_person_ref = async || {
264+ let sent = send(&app, "GET", "/messages?folder=sent", Some(&ali), None).await;
265+ assert_eq!(sent.status, StatusCode::OK, "{}", sent.body);
266+ items(&sent.body)[0]["recipient"]["display_name"].clone()
267+ };
268+ let as_profile = async || {
269+ let profile = send(
270+ &app,
271+ "GET",
272+ &format!("/users/{ayse_id}/profile"),
273+ Some(&ali),
274+ None,
275+ )
276+ .await;
277+ assert_eq!(profile.status, StatusCode::OK, "{}", profile.body);
278+ profile.body["display_name"].clone()
279+ };
280+
281+ let sent = send(
282+ &app,
283+ "POST",
284+ "/messages",
285+ Some(&ali),
286+ Some(json!({ "recipient_id": ayse_id, "subject": "ödev", "body": "yarın" })),
287+ )
288+ .await;
289+ assert_eq!(sent.status, StatusCode::CREATED, "{}", sent.body);
290+
291+ // Neither name: `null` on both surfaces, never the username.
292+ assert!(as_person_ref().await.is_null(), "nothing to show yet");
293+ assert_eq!(as_person_ref().await, as_profile().await);
294+
295+ // Legal name only: the join, on both.
296+ let res = send(
297+ &app,
298+ "PATCH",
299+ "/users/me",
300+ Some(&ayse),
301+ Some(json!({ "name": "Ayşe", "surname": "Yılmaz" })),
302+ )
303+ .await;
304+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
305+ assert_eq!(as_person_ref().await, "Ayşe Yılmaz");
306+ assert_eq!(as_person_ref().await, as_profile().await);
307+
308+ // A chosen name wins over the legal one — the whole point of choosing it.
309+ let res = send(
310+ &app,
311+ "PATCH",
312+ "/users/me",
313+ Some(&ayse),
314+ Some(json!({ "display_name": "Ada" })),
315+ )
316+ .await;
317+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
318+ assert_eq!(
319+ as_person_ref().await,
320+ "Ada",
321+ "the legal name must not leak back through a person ref"
322+ );
323+ assert_eq!(
324+ as_person_ref().await,
325+ as_profile().await,
326+ "the two surfaces resolve one rule and cannot disagree"
327+ );
328+ // The office record is untouched by any of this.
329+ let office = send(&app, "GET", "/auth/me", Some(&ayse), None).await;
330+ assert_eq!(office.body["name"], "Ayşe");
331+ assert_eq!(office.body["surname"], "Yılmaz");
332+}
333+
249 /// The read-time badge backstop, and the write it must not make.334 /// The read-time badge backstop, and the write it must not make.
250 ///335 ///
251 /// A counter is moved behind the API's back — exactly what a lost `badge::sync`336 /// A counter is moved behind the API's back — exactly what a lost `badge::sync`
@@ -355,6 +440,10 @@ async fn fresh_stats_read_zero_on_every_field() {
355 stats.get(field)440 stats.get(field)
356 );441 );
357 }442 }
443+ // A 17th key is a new disclosure decision, not just a new number: every
444+ // magnitude here is the owner's true total for *every* reader, gate or no
445+ // gate (see `profile_of`). Adding one means re-reading that paragraph and
446+ // saying so in the README before this list grows.
358 assert_eq!(stats.len(), 16, "an unlisted counter shipped: {stats:?}");447 assert_eq!(stats.len(), 16, "an unlisted counter shipped: {stats:?}");
359 assert!(mine.body["avatar"].is_null());448 assert!(mine.body["avatar"].is_null());
360 assert_eq!(mine.body["classes"], json!([]));449 assert_eq!(mine.body["classes"], json!([]));