Stop a demotion confiscating the owner's own notes
Browse files at this commit528403a9adcefc4ec037d02bba884df89bc62774Parent: b1ef594- fix
- stop a demotion confiscating the owner's own notes
4 changed files +216 -40
- README.md +21 -12
- src/lib.rs +1 -1
- src/web/notes.rs +10 -21
- tests/integration.rs +184 -6
README.mdmodified+21 -12
| @@ -5,7 +5,9 @@ Note, attendance, course + weighted exam mark backend. **Rust (edition 2024) · | |||
| 5 | Session-cookie auth with five hierarchical roles (`parent < student < teacher | 5 | Session-cookie auth with five hierarchical roles (`parent < student < teacher |
| 6 | < manager < admin`). A **`parent`** observes and changes nothing: admins tie | 6 | < manager < admin`). A **`parent`** observes and changes nothing: admins tie |
| 7 | students to a parent account, and the parent reads those students' mark, | 7 | students to a parent account, and the parent reads those students' mark, |
| 8 | -attendance, pomodoro, and homework reports — that's the whole role. Notes are per-user and carry **file attachments** (PDFs, documents, | 8 | +attendance, pomodoro, and homework reports — that's the whole role, bar the |
| 9 | +two things every account keeps whatever its role: **messages** and its own | ||
| 10 | +**notes**. Notes are per-user and carry **file attachments** (PDFs, documents, | ||
| 9 | …): blobs live on disk next to the database, metadata in the database, and the | 11 | …): blobs live on disk next to the database, metadata in the database, and the |
| 10 | per-file size cap is school policy in settings (`max_file_bytes`, default | 12 | per-file size cap is school policy in settings (`max_file_bytes`, default |
| 11 | 5 MiB). Any two users can **message** each other, mail-style — subject + | 13 | 5 MiB). Any two users can **message** each other, mail-style — subject + |
| @@ -585,7 +587,13 @@ and homework reports in full. Student-only checks are exact (`role == student`), | |||
| 585 | parent can never enroll, sit an exam, be graded, or land on a roll call; and | 587 | parent can never enroll, sit an exam, be graded, or land on a roll call; and |
| 586 | sitting below every staff bar, they can't touch anything else either — except | 588 | sitting below every staff bar, they can't touch anything else either — except |
| 587 | messages, which any role sends and receives (that's how a parent reaches a | 589 | messages, which any role sends and receives (that's how a parent reaches a |
| 588 | -teacher). A role | 590 | +teacher), and their own **notes**, which carry no role bar at all: a note is |
| 591 | +private to one person, so a role change must not confiscate it. It used to. | ||
| 592 | +While the note routes required `student`, a demotion locked the owner out of | ||
| 593 | +their own notes permanently — and since nothing else in the crate reads a note | ||
| 594 | +and no route cascades one, the rows and their on-disk blobs were left | ||
| 595 | +unreachable and undeletable by everybody, without even a per-user cap to bound | ||
| 596 | +the wreckage. Ownership is now the whole check there. A role | ||
| 589 | change off either end of a tie (the parent stops being a `parent`, the | 597 | change off either end of a tie (the parent stops being a `parent`, the |
| 590 | student stops being a `student`) drops the tie, exactly like promotion drops | 598 | student stops being a `student`) drops the tie, exactly like promotion drops |
| 591 | course enrollments. That sweep runs once, so a tie written in the same instant | 599 | course enrollments. That sweep runs once, so a tie written in the same instant |
| @@ -628,7 +636,8 @@ still left exactly as they stand. | |||
| 628 | | Action | Minimum role | Notes | | 636 | | Action | Minimum role | Notes | |
| 629 | |------------------------------------------|--------------|-----------------------------------------------| | 637 | |------------------------------------------|--------------|-----------------------------------------------| |
| 630 | | Register / login / view own account | (any) | Registration always creates a `student` | | 638 | | Register / login / view own account | (any) | Registration always creates a `student` | |
| 631 | -| View events, own notes; CRUD notes + their files | student | Everyone can read events and keep notes; note files (upload/download) are walled per owner like the notes themselves | | 639 | +| View events | student | Everyone from `student` up can read events | |
| 640 | +| CRUD own notes + their files | (any) | A note is private to its owner and has no other reader, so there is no role bar: ownership *is* the authorization, `parent` included. Note files (upload/download/delete) are walled per owner like the notes themselves — a file is only ever reached through its own note | | ||
| 632 | | Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included — the role's one write); each party only ever touches their own copy | | 641 | | Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included — the role's one write); each party only ever touches their own copy | |
| 633 | | Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark — a teacher+ may mark anyone expected, themselves included | | 642 | | Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark — a teacher+ may mark anyone expected, themselves included | |
| 634 | | Create events | teacher | The audience (school / role / course / class / registration) is set at creation and editable later | | 643 | | Create events | teacher | The audience (school / role / course / class / registration) is set at creation and editable later | |
| @@ -830,15 +839,15 @@ window filtering, before paging; negative values are a `400` naming the field. | |||
| 830 | | POST | `/users/{id}/students` | admin | `{user_id}` — tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant | | 839 | | POST | `/users/{id}/students` | admin | `{user_id}` — tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant | |
| 831 | | GET | `/users/{id}/students` | admin | List a parent's linked students (same live-role filter as `/users/me/students`) · paged | | 840 | | GET | `/users/{id}/students` | admin | List a parent's linked students (same live-role filter as `/users/me/students`) · paged | |
| 832 | | DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) | | 841 | | DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) | |
| 833 | -| POST | `/notes` | student | `{title, content?}` | | 842 | +| POST | `/notes` | (any) | `{title, content?}` | |
| 834 | -| GET | `/notes` | student | List own notes · paged | | 843 | +| GET | `/notes` | (any) | List own notes · paged | |
| 835 | -| GET | `/notes/{id}` | student | Get own note | | 844 | +| GET | `/notes/{id}` | (any) | Get own note | |
| 836 | -| PATCH | `/notes/{id}` | student | `{title?, content?}` | | 845 | +| PATCH | `/notes/{id}` | (any) | `{title?, content?}` | |
| 837 | -| DELETE | `/notes/{id}` | student | Delete own note (its files go with it) | | 846 | +| DELETE | `/notes/{id}` | (any) | Delete own note (its files go with it) | |
| 838 | -| POST | `/notes/{id}/files` | student | Attach a file: `multipart/form-data`, one `file` part (`filename` required) — ≤ the school's `max_file_bytes`, ≤ 10 files per note | | 847 | +| POST | `/notes/{id}/files` | (any) | Attach a file: `multipart/form-data`, one `file` part (`filename` required) — ≤ the school's `max_file_bytes`, ≤ 10 files per note | |
| 839 | -| GET | `/notes/{id}/files` | student | List a note's files (metadata: `{id, name, content_type, size}`) · paged | | 848 | +| GET | `/notes/{id}/files` | (any) | List a note's files (metadata: `{id, name, content_type, size}`) · paged | |
| 840 | -| GET | `/notes/{id}/files/{file_id}` | student | Download the bytes (original filename + content type in the headers) | | 849 | +| GET | `/notes/{id}/files/{file_id}` | (any) | Download the bytes (original filename + content type in the headers) | |
| 841 | -| DELETE | `/notes/{id}/files/{file_id}` | student | Delete one file | | 850 | +| DELETE | `/notes/{id}/files/{file_id}` | (any) | Delete one file | |
| 842 | | POST | `/messages` | student | `{recipient_id, subject, body?, label?}` — send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag | | 851 | | POST | `/messages` | student | `{recipient_id, subject, body?, label?}` — send to any user (every role incl. `parent`; not yourself); `label` is a free-text badge tag | |
| 843 | | GET | `/messages` | student | `?folder=inbox\|sent\|archive\|trash` (default `inbox`) `&read=` — the caller's folder, newest first; `?folder=inbox&read=false&limit=1` → `total` is the unread badge · paged | | 852 | | GET | `/messages` | student | `?folder=inbox\|sent\|archive\|trash` (default `inbox`) `&read=` — the caller's folder, newest first; `?folder=inbox&read=false&limit=1` → `total` is the unread badge · paged | |
| 844 | | PATCH | `/messages/{id}` | student | `{read?, folder?}` — read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) | | 853 | | PATCH | `/messages/{id}` | student | `{read?, folder?}` — read flag (recipient only) and/or move **own copy** (recipient: `inbox`/`archive`/`trash`; sender: `sent`/`archive`/`trash`) | |
src/lib.rsmodified+1 -1
| @@ -45,7 +45,7 @@ use crate::state::AppState; | |||
| 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 (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`). 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 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"), |
| 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"), |
src/web/notes.rsmodified+10 -21
| @@ -15,9 +15,7 @@ use crate::domain::settings::Settings; | |||
| 15 | use crate::error::{AppError, ErrorResponse}; | 15 | use crate::error::{AppError, ErrorResponse}; |
| 16 | use crate::state::AppState; | 16 | use crate::state::AppState; |
| 17 | 17 | ||
| 18 | -use super::{ | 18 | +use super::{CurrentUser, Page, PageParams, UploadFileForm, blob_path, read_upload, remove_blob}; |
| 19 | - Page, PageParams, RequireStudent, UploadFileForm, blob_path, read_upload, remove_blob, | ||
| 20 | -}; | ||
| 21 | 19 | ||
| 22 | pub fn routes() -> OpenApiRouter<AppState> { | 20 | pub fn routes() -> OpenApiRouter<AppState> { |
| 23 | // The file routes get their own HTTP body cap: the server-wide hard | 21 | // The file routes get their own HTTP body cap: the server-wide hard |
| @@ -80,13 +78,12 @@ impl NoteResponse { | |||
| 80 | (status = 201, description = "Note created", body = NoteResponse), | 78 | (status = 201, description = "Note created", body = NoteResponse), |
| 81 | (status = 400, description = "Invalid title or content", body = ErrorResponse), | 79 | (status = 400, description = "Invalid title or content", body = ErrorResponse), |
| 82 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 80 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 83 | - (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | ||
| 84 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | 81 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 85 | ), | 82 | ), |
| 86 | )] | 83 | )] |
| 87 | async fn create( | 84 | async fn create( |
| 88 | State(st): State<AppState>, | 85 | State(st): State<AppState>, |
| 89 | - RequireStudent(user): RequireStudent, | 86 | + CurrentUser(user): CurrentUser, |
| 90 | Json(req): Json<CreateNote>, | 87 | Json(req): Json<CreateNote>, |
| 91 | ) -> Result<(StatusCode, Json<NoteResponse>), AppError> { | 88 | ) -> Result<(StatusCode, Json<NoteResponse>), AppError> { |
| 92 | let title = NoteTitle::try_new(&req.title)?; | 89 | let title = NoteTitle::try_new(&req.title)?; |
| @@ -108,12 +105,11 @@ async fn create( | |||
| 108 | (status = 200, description = "A page of the user's notes (all of them when unpaged)", body = Page<NoteResponse>), | 105 | (status = 200, description = "A page of the user's notes (all of them when unpaged)", body = Page<NoteResponse>), |
| 109 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | 106 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 110 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 107 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 111 | - (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | ||
| 112 | ), | 108 | ), |
| 113 | )] | 109 | )] |
| 114 | async fn list( | 110 | async fn list( |
| 115 | State(st): State<AppState>, | 111 | State(st): State<AppState>, |
| 116 | - RequireStudent(user): RequireStudent, | 112 | + CurrentUser(user): CurrentUser, |
| 117 | Query(page): Query<PageParams>, | 113 | Query(page): Query<PageParams>, |
| 118 | ) -> Result<Json<Page<NoteResponse>>, AppError> { | 114 | ) -> Result<Json<Page<NoteResponse>>, AppError> { |
| 119 | let (limit, offset) = page.resolve()?; | 115 | let (limit, offset) = page.resolve()?; |
| @@ -132,13 +128,12 @@ async fn list( | |||
| 132 | responses( | 128 | responses( |
| 133 | (status = 200, description = "The note", body = NoteResponse), | 129 | (status = 200, description = "The note", body = NoteResponse), |
| 134 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 130 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 135 | - (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | ||
| 136 | (status = 404, description = "Not found", body = ErrorResponse), | 131 | (status = 404, description = "Not found", body = ErrorResponse), |
| 137 | ), | 132 | ), |
| 138 | )] | 133 | )] |
| 139 | async fn get_one( | 134 | async fn get_one( |
| 140 | State(st): State<AppState>, | 135 | State(st): State<AppState>, |
| 141 | - RequireStudent(user): RequireStudent, | 136 | + CurrentUser(user): CurrentUser, |
| 142 | Path(id): Path<String>, | 137 | Path(id): Path<String>, |
| 143 | ) -> Result<Json<NoteResponse>, AppError> { | 138 | ) -> Result<Json<NoteResponse>, AppError> { |
| 144 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | 139 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| @@ -159,14 +154,13 @@ async fn get_one( | |||
| 159 | (status = 200, description = "Updated note", body = NoteResponse), | 154 | (status = 200, description = "Updated note", body = NoteResponse), |
| 160 | (status = 400, description = "Invalid title or content", body = ErrorResponse), | 155 | (status = 400, description = "Invalid title or content", body = ErrorResponse), |
| 161 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 156 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 162 | - (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | ||
| 163 | (status = 404, description = "Not found", body = ErrorResponse), | 157 | (status = 404, description = "Not found", body = ErrorResponse), |
| 164 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | 158 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 165 | ), | 159 | ), |
| 166 | )] | 160 | )] |
| 167 | async fn update( | 161 | async fn update( |
| 168 | State(st): State<AppState>, | 162 | State(st): State<AppState>, |
| 169 | - RequireStudent(user): RequireStudent, | 163 | + CurrentUser(user): CurrentUser, |
| 170 | Path(id): Path<String>, | 164 | Path(id): Path<String>, |
| 171 | Json(req): Json<UpdateNote>, | 165 | Json(req): Json<UpdateNote>, |
| 172 | ) -> Result<Json<NoteResponse>, AppError> { | 166 | ) -> Result<Json<NoteResponse>, AppError> { |
| @@ -199,13 +193,12 @@ async fn update( | |||
| 199 | responses( | 193 | responses( |
| 200 | (status = 204, description = "Deleted"), | 194 | (status = 204, description = "Deleted"), |
| 201 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 195 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 202 | - (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | ||
| 203 | (status = 404, description = "Not found", body = ErrorResponse), | 196 | (status = 404, description = "Not found", body = ErrorResponse), |
| 204 | ), | 197 | ), |
| 205 | )] | 198 | )] |
| 206 | async fn delete_one( | 199 | async fn delete_one( |
| 207 | State(st): State<AppState>, | 200 | State(st): State<AppState>, |
| 208 | - RequireStudent(user): RequireStudent, | 201 | + CurrentUser(user): CurrentUser, |
| 209 | Path(id): Path<String>, | 202 | Path(id): Path<String>, |
| 210 | ) -> Result<StatusCode, AppError> { | 203 | ) -> Result<StatusCode, AppError> { |
| 211 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | 204 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| @@ -264,7 +257,6 @@ impl NoteFileResponse { | |||
| 264 | (status = 201, description = "File stored", body = NoteFileResponse), | 257 | (status = 201, description = "File stored", body = NoteFileResponse), |
| 265 | (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse), | 258 | (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse), |
| 266 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 259 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 267 | - (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | ||
| 268 | (status = 404, description = "Note not found", body = ErrorResponse), | 260 | (status = 404, description = "Note not found", body = ErrorResponse), |
| 269 | (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse), | 261 | (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse), |
| 270 | (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), | 262 | (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), |
| @@ -272,7 +264,7 @@ impl NoteFileResponse { | |||
| 272 | )] | 264 | )] |
| 273 | async fn upload_file( | 265 | async fn upload_file( |
| 274 | State(st): State<AppState>, | 266 | State(st): State<AppState>, |
| 275 | - RequireStudent(user): RequireStudent, | 267 | + CurrentUser(user): CurrentUser, |
| 276 | Path(id): Path<String>, | 268 | Path(id): Path<String>, |
| 277 | mut multipart: Multipart, | 269 | mut multipart: Multipart, |
| 278 | ) -> Result<(StatusCode, Json<NoteFileResponse>), AppError> { | 270 | ) -> Result<(StatusCode, Json<NoteFileResponse>), AppError> { |
| @@ -315,13 +307,12 @@ async fn upload_file( | |||
| 315 | (status = 200, description = "A page of the note's files", body = Page<NoteFileResponse>), | 307 | (status = 200, description = "A page of the note's files", body = Page<NoteFileResponse>), |
| 316 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | 308 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 317 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 309 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 318 | - (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | ||
| 319 | (status = 404, description = "Note not found", body = ErrorResponse), | 310 | (status = 404, description = "Note not found", body = ErrorResponse), |
| 320 | ), | 311 | ), |
| 321 | )] | 312 | )] |
| 322 | async fn list_files( | 313 | async fn list_files( |
| 323 | State(st): State<AppState>, | 314 | State(st): State<AppState>, |
| 324 | - RequireStudent(user): RequireStudent, | 315 | + CurrentUser(user): CurrentUser, |
| 325 | Path(id): Path<String>, | 316 | Path(id): Path<String>, |
| 326 | Query(page): Query<PageParams>, | 317 | Query(page): Query<PageParams>, |
| 327 | ) -> Result<Json<Page<NoteFileResponse>>, AppError> { | 318 | ) -> Result<Json<Page<NoteFileResponse>>, AppError> { |
| @@ -348,13 +339,12 @@ async fn list_files( | |||
| 348 | responses( | 339 | responses( |
| 349 | (status = 200, description = "The file bytes", content_type = "application/octet-stream"), | 340 | (status = 200, description = "The file bytes", content_type = "application/octet-stream"), |
| 350 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 341 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 351 | - (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | ||
| 352 | (status = 404, description = "Note or file not found", body = ErrorResponse), | 342 | (status = 404, description = "Note or file not found", body = ErrorResponse), |
| 353 | ), | 343 | ), |
| 354 | )] | 344 | )] |
| 355 | async fn download_file( | 345 | async fn download_file( |
| 356 | State(st): State<AppState>, | 346 | State(st): State<AppState>, |
| 357 | - RequireStudent(user): RequireStudent, | 347 | + CurrentUser(user): CurrentUser, |
| 358 | Path((id, file_id)): Path<(String, String)>, | 348 | Path((id, file_id)): Path<(String, String)>, |
| 359 | ) -> Result<Response, AppError> { | 349 | ) -> Result<Response, AppError> { |
| 360 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | 350 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
| @@ -402,13 +392,12 @@ async fn download_file( | |||
| 402 | responses( | 392 | responses( |
| 403 | (status = 204, description = "Deleted"), | 393 | (status = 204, description = "Deleted"), |
| 404 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 394 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 405 | - (status = 403, description = "Requires the student role or higher", body = ErrorResponse), | ||
| 406 | (status = 404, description = "Note or file not found", body = ErrorResponse), | 395 | (status = 404, description = "Note or file not found", body = ErrorResponse), |
| 407 | ), | 396 | ), |
| 408 | )] | 397 | )] |
| 409 | async fn delete_file( | 398 | async fn delete_file( |
| 410 | State(st): State<AppState>, | 399 | State(st): State<AppState>, |
| 411 | - RequireStudent(user): RequireStudent, | 400 | + CurrentUser(user): CurrentUser, |
| 412 | Path((id, file_id)): Path<(String, String)>, | 401 | Path((id, file_id)): Path<(String, String)>, |
| 413 | ) -> Result<StatusCode, AppError> { | 402 | ) -> Result<StatusCode, AppError> { |
| 414 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) | 403 | let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) |
tests/integration.rsmodified+184 -6
| @@ -561,6 +561,181 @@ async fn notes_crud_is_scoped_to_owner() { | |||
| 561 | ); | 561 | ); |
| 562 | } | 562 | } |
| 563 | 563 | ||
| 564 | +/// A demotion to `parent` must not confiscate the account's own notes. It used | ||
| 565 | +/// to: every note route required `student`, so after the demotion the owner | ||
| 566 | +/// could no longer list, read or **delete** their notes — and since nothing | ||
| 567 | +/// else in the crate reads a note and no route cascades one, the rows and their | ||
| 568 | +/// on-disk blobs were unreachable and undeletable by everybody, forever. The | ||
| 569 | +/// role bar is gone; the owner scoping that was always underneath it is now the | ||
| 570 | +/// whole authorization, so a `parent` reaches their own notes and nobody | ||
| 571 | +/// else's. | ||
| 572 | +#[tokio::test] | ||
| 573 | +async fn a_demotion_to_parent_strands_no_note_and_no_blob() { | ||
| 574 | + let (app, db) = app_and_db().await; | ||
| 575 | + let admin = login_as(&app, &db, "boss", "admin").await; | ||
| 576 | + let ali = login(&app, "ali").await; | ||
| 577 | + let ali_id = me_id(&app, &ali).await; | ||
| 578 | + | ||
| 579 | + // A student's note with a file on it. | ||
| 580 | + let res = send( | ||
| 581 | + &app, | ||
| 582 | + "POST", | ||
| 583 | + "/notes", | ||
| 584 | + Some(&ali), | ||
| 585 | + Some(json!({ "title": "kept", "content": "mine" })), | ||
| 586 | + ) | ||
| 587 | + .await; | ||
| 588 | + assert_eq!(res.status, StatusCode::CREATED); | ||
| 589 | + let note_id = id_of(&res.body); | ||
| 590 | + let up = common::upload_file( | ||
| 591 | + &app, | ||
| 592 | + &ali, | ||
| 593 | + ¬e_id, | ||
| 594 | + "plan.pdf", | ||
| 595 | + "application/pdf", | ||
| 596 | + b"bytes", | ||
| 597 | + ) | ||
| 598 | + .await; | ||
| 599 | + assert_eq!(up.status, StatusCode::CREATED); | ||
| 600 | + let file_id = id_of(&up.body); | ||
| 601 | + let blob = common::files_dir().join(&file_id); | ||
| 602 | + assert!(blob.exists(), "the upload must have written a blob"); | ||
| 603 | + | ||
| 604 | + // Demote through the real route, not a seeded role. | ||
| 605 | + let res = send( | ||
| 606 | + &app, | ||
| 607 | + "PATCH", | ||
| 608 | + &format!("/users/{ali_id}/role"), | ||
| 609 | + Some(&admin), | ||
| 610 | + Some(json!({ "role": "parent" })), | ||
| 611 | + ) | ||
| 612 | + .await; | ||
| 613 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 614 | + assert_eq!(res.body["role"], "parent"); | ||
| 615 | + | ||
| 616 | + // Every own-scoped read still answers the owner. | ||
| 617 | + let res = send(&app, "GET", "/notes", Some(&ali), None).await; | ||
| 618 | + assert_eq!(res.status, StatusCode::OK); | ||
| 619 | + assert_eq!(common::items(&res.body).len(), 1); | ||
| 620 | + assert_eq!( | ||
| 621 | + send(&app, "GET", &format!("/notes/{note_id}"), Some(&ali), None) | ||
| 622 | + .await | ||
| 623 | + .body["title"], | ||
| 624 | + "kept" | ||
| 625 | + ); | ||
| 626 | + let res = send( | ||
| 627 | + &app, | ||
| 628 | + "PATCH", | ||
| 629 | + &format!("/notes/{note_id}"), | ||
| 630 | + Some(&ali), | ||
| 631 | + Some(json!({ "content": "still mine" })), | ||
| 632 | + ) | ||
| 633 | + .await; | ||
| 634 | + assert_eq!(res.status, StatusCode::OK); | ||
| 635 | + assert_eq!(res.body["content"], "still mine"); | ||
| 636 | + | ||
| 637 | + // Files too: list, download the bytes, and attach another one. | ||
| 638 | + let res = send( | ||
| 639 | + &app, | ||
| 640 | + "GET", | ||
| 641 | + &format!("/notes/{note_id}/files"), | ||
| 642 | + Some(&ali), | ||
| 643 | + None, | ||
| 644 | + ) | ||
| 645 | + .await; | ||
| 646 | + assert_eq!(common::items(&res.body).len(), 1); | ||
| 647 | + let (status, _, bytes) = common::send_raw( | ||
| 648 | + &app, | ||
| 649 | + "GET", | ||
| 650 | + &format!("/notes/{note_id}/files/{file_id}"), | ||
| 651 | + Some(&ali), | ||
| 652 | + None, | ||
| 653 | + Vec::new(), | ||
| 654 | + ) | ||
| 655 | + .await; | ||
| 656 | + assert_eq!(status, StatusCode::OK); | ||
| 657 | + assert_eq!(bytes, b"bytes"); | ||
| 658 | + let extra = | ||
| 659 | + common::upload_file(&app, &ali, ¬e_id, "more.pdf", "application/pdf", b"x").await; | ||
| 660 | + assert_eq!(extra.status, StatusCode::CREATED); | ||
| 661 | + | ||
| 662 | + // A different parent reaches none of it — the owner check is all that | ||
| 663 | + // stands there now, so prove every route holds. `404`, the crate's answer | ||
| 664 | + // for someone else's row, never `403`. | ||
| 665 | + let veli = login_as(&app, &db, "veli", "parent").await; | ||
| 666 | + for (method, uri) in [ | ||
| 667 | + ("GET", format!("/notes/{note_id}")), | ||
| 668 | + ("PATCH", format!("/notes/{note_id}")), | ||
| 669 | + ("GET", format!("/notes/{note_id}/files")), | ||
| 670 | + ("GET", format!("/notes/{note_id}/files/{file_id}")), | ||
| 671 | + ("DELETE", format!("/notes/{note_id}/files/{file_id}")), | ||
| 672 | + ("DELETE", format!("/notes/{note_id}")), | ||
| 673 | + ] { | ||
| 674 | + let body = (method == "PATCH").then(|| json!({ "title": "stolen" })); | ||
| 675 | + assert_eq!( | ||
| 676 | + send(&app, method, &uri, Some(&veli), body).await.status, | ||
| 677 | + StatusCode::NOT_FOUND, | ||
| 678 | + "{method} {uri} must not reach another user's note" | ||
| 679 | + ); | ||
| 680 | + } | ||
| 681 | + assert_eq!( | ||
| 682 | + common::upload_file(&app, &veli, ¬e_id, "x.pdf", "application/pdf", b"x") | ||
| 683 | + .await | ||
| 684 | + .status, | ||
| 685 | + StatusCode::NOT_FOUND, | ||
| 686 | + "a stranger must not attach a file to someone else's note" | ||
| 687 | + ); | ||
| 688 | + assert!(common::items(&send(&app, "GET", "/notes", Some(&veli), None).await.body).is_empty()); | ||
| 689 | + // A parent's own notes work end to end, which is what makes the demoted | ||
| 690 | + // owner's access ownership and not leftover privilege. | ||
| 691 | + assert_eq!( | ||
| 692 | + send( | ||
| 693 | + &app, | ||
| 694 | + "POST", | ||
| 695 | + "/notes", | ||
| 696 | + Some(&veli), | ||
| 697 | + Some(json!({ "title": "veli's" })) | ||
| 698 | + ) | ||
| 699 | + .await | ||
| 700 | + .status, | ||
| 701 | + StatusCode::CREATED | ||
| 702 | + ); | ||
| 703 | + | ||
| 704 | + // And the demoted owner can still clear the whole thing out: one file by | ||
| 705 | + // hand, the rest through the note's cascade — blobs included. | ||
| 706 | + assert_eq!( | ||
| 707 | + send( | ||
| 708 | + &app, | ||
| 709 | + "DELETE", | ||
| 710 | + &format!("/notes/{note_id}/files/{file_id}"), | ||
| 711 | + Some(&ali), | ||
| 712 | + None | ||
| 713 | + ) | ||
| 714 | + .await | ||
| 715 | + .status, | ||
| 716 | + StatusCode::NO_CONTENT | ||
| 717 | + ); | ||
| 718 | + assert!(!blob.exists(), "deleting a file must unlink its blob"); | ||
| 719 | + let extra_blob = common::files_dir().join(id_of(&extra.body)); | ||
| 720 | + assert_eq!( | ||
| 721 | + send( | ||
| 722 | + &app, | ||
| 723 | + "DELETE", | ||
| 724 | + &format!("/notes/{note_id}"), | ||
| 725 | + Some(&ali), | ||
| 726 | + None | ||
| 727 | + ) | ||
| 728 | + .await | ||
| 729 | + .status, | ||
| 730 | + StatusCode::NO_CONTENT | ||
| 731 | + ); | ||
| 732 | + assert!( | ||
| 733 | + !extra_blob.exists(), | ||
| 734 | + "the note delete must take its remaining blobs with it" | ||
| 735 | + ); | ||
| 736 | + assert!(common::items(&send(&app, "GET", "/notes", Some(&ali), None).await.body).is_empty()); | ||
| 737 | +} | ||
| 738 | + | ||
| 564 | #[tokio::test] | 739 | #[tokio::test] |
| 565 | async fn note_content_defaults_to_empty() { | 740 | async fn note_content_defaults_to_empty() { |
| 566 | let app = mem_app().await; | 741 | let app = mem_app().await; |
| @@ -13482,10 +13657,12 @@ async fn messages_rejected_patch_leaves_no_side_effects() { | |||
| 13482 | ); | 13657 | ); |
| 13483 | } | 13658 | } |
| 13484 | 13659 | ||
| 13485 | -/// The read-only parent role must bounce off every notes surface — they were | 13660 | +/// Notes carry no role bar: they are own-scoped personal data with no other |
| 13486 | -/// gated on bare authentication before the parent role existed. | 13661 | +/// reader, so the read-only `parent` keeps theirs like everybody else. The |
| 13662 | +/// `student` bar this route family used to hold was a defect — see | ||
| 13663 | +/// `a_demotion_to_parent_strands_no_note_and_no_blob`. | ||
| 13487 | #[tokio::test] | 13664 | #[tokio::test] |
| 13488 | -async fn parent_role_cannot_touch_notes() { | 13665 | +async fn parent_role_keeps_its_own_notes() { |
| 13489 | let (app, db) = app_and_db().await; | 13666 | let (app, db) = app_and_db().await; |
| 13490 | let parent = login_as(&app, &db, "baba", "parent").await; | 13667 | let parent = login_as(&app, &db, "baba", "parent").await; |
| 13491 | 13668 | ||
| @@ -13494,12 +13671,13 @@ async fn parent_role_cannot_touch_notes() { | |||
| 13494 | "POST", | 13671 | "POST", |
| 13495 | "/notes", | 13672 | "/notes", |
| 13496 | Some(&parent), | 13673 | Some(&parent), |
| 13497 | - Some(json!({ "title": "not" })), | 13674 | + Some(json!({ "title": "mine" })), |
| 13498 | ) | 13675 | ) |
| 13499 | .await; | 13676 | .await; |
| 13500 | - assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | 13677 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 13501 | let res = send(&app, "GET", "/notes", Some(&parent), None).await; | 13678 | let res = send(&app, "GET", "/notes", Some(&parent), None).await; |
| 13502 | - assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | 13679 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 13680 | + assert_eq!(common::items(&res.body).len(), 1); | ||
| 13503 | 13681 | ||
| 13504 | // Student and up keep the pen. | 13682 | // Student and up keep the pen. |
| 13505 | let ali = login(&app, "ali").await; | 13683 | let ali = login(&app, "ali").await; |