Stop the review gate answering for an exam the caller cannot see
Browse files at this commit73eb272ce978b51ce849fea4088e498c4aa87baeParent: 37ee719- fix
- stop the review gate answering for an exam the caller cannot see
6 changed files +184 -12
- README.md +12 -0
- src/lib.rs +2 -2
- src/web/appointments.rs +10 -0
- src/web/exams/review.rs +18 -10
- tests/regress_appointments.rs +44 -0
- tests/regress_review.rs +98 -0
README.mdmodified+12 -0
| @@ -1541,6 +1541,14 @@ concurrent bookings can both read as free). The decisions: | ||
| 1541 | 1541 | `teacher` decides nothing on it any more — and nothing is left for anyone |
| 1542 | 1542 | else to decide either, since that demotion cancelled the bookings along with |
| 1543 | 1543 | the slots. Refused |
| 1544 | +Every slot carries its teacher's identity (id, username, display name), to a | |
| 1545 | +parent as much as to a student: **deliberate**, and not to be tightened. A | |
| 1546 | +parent's three direct routes to that identity are all shut (`GET | |
| 1547 | +/users/{id}/profile` is a `403`, `/users/search` is teacher+, `/users` is | |
| 1548 | +admin), but a conference cannot be booked off an anonymous calendar — this list | |
| 1549 | +*is* the staff directory for the booking flow, narrowed to whoever published | |
| 1550 | +bookable time. The same refs on a booking (`teacher`, `proposed_by`, | |
| 1551 | +`decided_by`) read the same way. | |
| 1544 | 1552 | (`409`) when the effective window has already started, and refused while a |
| 1545 | 1553 | counter-proposal stands: the proposal is the teacher's own, so approving it |
| 1546 | 1554 | here would let them confirm a time the requester never accepted. |
| @@ -2418,6 +2426,10 @@ construction): | ||
| 2418 | 2426 | staff never sit; enrolled; window open where one exists — `open` exams start |
| 2419 | 2427 | anytime). While the latest |
| 2420 | 2428 | sitting runs, re-posting returns it unchanged (`200`, not `201`): |
| 2429 | + The mark is checked **before** the flag, so a caller who has none reads `404` | |
| 2430 | + whichever way `allow_review` is set — an outsider (an unenrolled student, a | |
| 2431 | + parent) never learns from the status code whether review is on for an exam | |
| 2432 | + `GET /exams/{id}` would refuse them outright. | |
| 2421 | 2433 | reconnecting never resets the clock. Once it is submitted or expired, |
| 2422 | 2434 | re-posting mints the next sitting (`201`) **from a blank answer sheet** — |
| 2423 | 2435 | the previous sitting's answers are wiped — until `max_attempts` is spent |
src/lib.rsmodified+2 -2
| @@ -47,7 +47,7 @@ use crate::state::AppState; | ||
| 47 | 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`"), |
| 48 | 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 | 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"), | |
| 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 | 51 | (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), |
| 52 | 52 | (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), |
| 53 | 53 | (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry — unpaged, since the set is the şube one school runs at one grade — because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and `missing` only ever names courses that still exist: deleting a course takes its id out of every blueprint holding it, in the same cascade that detaches it from the sections, so no template is left naming a course that is gone (which used to be permanent at a grade with no sections, and made the re-`PATCH` below a `400`). Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached — they still carry that blueprint's tag, so dropping one from that template still detaches them — and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary, each route with its own set: a `409` from `POST /classes/{id}/courses` carries `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` or `course_full`, and one from `POST /classes/{id}/members` carries `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full` or `linked_course_missing`. The three *deleted* codes are a pump's alone — on a manual attach a deleted class or course is a `404`, never a `409` — and the ceiling pair differs by route because the ceilings do: a member add is refused by a full roster (`class_at_roster_ceiling`) or by a course list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both. `duplicate` (already attached / already a member) is a refusal on either route, and no skip for a pump, which asked for a row that is already in place; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"), |
| @@ -57,7 +57,7 @@ use crate::state::AppState; | ||
| 57 | 57 | (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), |
| 58 | 58 | (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise), and every one of those rights is re-checked against the caller's live role: `owner` is a historical column no demotion sweeps, so an account below `teacher` reads and edits nothing here, its own templates included; as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"), |
| 59 | 59 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| 60 | - (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). Those reads are refused (`409`) while the caller can still *write* a sitting at that exam — one in progress, or one still startable under `max_attempts` before the window closes — since a mark on an earlier sitting must never hand out the key to a retake, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` — and with no correctness flag and no `auto_score` contribution on the answer sheet — since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), | |
| 60 | + (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked; a caller with no mark reads `404` whether review is on or off, so the status code never discloses `allow_review` to someone `GET /exams/{id}` would refuse outright). Those reads are refused (`409`) while the caller can still *write* a sitting at that exam — one in progress, or one still startable under `max_attempts` before the window closes — since a mark on an earlier sitting must never hand out the key to a retake, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` — and with no correctness flag and no `auto_score` contribution on the answer sheet — since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), | |
| 61 | 61 | (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and must be a **real calendar day**, leap years included: a menu on a day that does not exist (`2026-02-29`) has no serving instant, so it carried no booking or cancel cutoff at all while being fully actionable otherwise, and a menu stored on such a day before that rule now refuses both (`409`) whenever a cutoff is configured — the deadline fails closed rather than never closing. `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`. The date is parsed by the same calendar library that computes the serving instant and compared back to the text it came from, so a signed component (`2026-+1-01`, which `\"+1\".parse()` once accepted) is a `400` rather than a **second** menu id for the 1st of January — one with its own capacity and seat counter, invisible to every `?from=&to=` read because `+` sorts below `0`. The day must also not already be over (`400`, measured against the end of the day, so today publishes all day long): a published menu is a bookable one and a booking is what charges, so a menu behind the calendar mints real debt for food nobody can be served. The day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat, and at most `meal.max_booking_attempts` (`GET /limits`) seats may be taken on it in all — the first booking plus the re-bookings after a cancel, past which it is a `409`, because every cycle appends a charge and its reversal permanently and nothing else bounded that growth; a menu whose **day has already passed** takes no booking at all (`409`), whatever the cutoff is set to and with no role able to bypass it — the booking is the charge, so a seat taken on a day already served bills a meal that cannot be eaten; *cancelling* a seat on such a menu stays open, since money already taken has to stay reversible. A full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. **Who is asking is decided before the seat is looked up**: an unauthorised caller gets the same `403` for a booking that exists and one that never did, and only a caller who may cancel it ever sees a `404` — booking ids are derivable (`{date}_{slot}_{student}`), so reading the row first made the status code hand out the manager-only per-menu list one student at a time. The flip releases **only the attempt the call read** (the same `attempt` fence the re-booking side carries), so a seat taken again while the cancel was in flight is a `409` rather than a silent cancellation of that brand-new seat — unfenced it freed a seat the API had just answered `201` for, refunded nothing (the money is keyed to the older attempt, already reversed) and burnt the new attempt's reversal id for good. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with **no `serving_minute` closes nothing at all** — there is no instant to count the deadline back from, and counting from midnight UTC (as it once did) put every same-day menu past its deadline the moment a school set the cutoff knob, since all three shipped slots ship without an hour: today's lunch could not be booked and the seats already held could not be cancelled by the families holding them. Setting the hour is what starts the deadline binding that slot, on menus already published too. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?, request_key?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. It takes the same optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters, no `_`) that `/payments/credits` does: the line is keyed `<student>_k_<key>`, so a client retry after a network timeout returns the line the first attempt wrote rather than crediting the money a second time — which nothing on this API could then edit or delete. The same key with a different `amount_minor` is a `409`; omit it and two identical posts are two credits. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"), |
| 62 | 62 | (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. One request is bounded by the charges it would raise rather than by the head count alone — `student_ids × installments` may not exceed 3 000 (200 students up to a 15-installment plan, 50 at a time on a 60-installment one) — and a bigger batch is a `400` naming the split, refused whole before anything is written, since a batch billed in part would leave the office guessing which families were charged. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. A reversed charge is no longer owed, so it takes no payment: `POST /payments/credits` against one is a `409` that says it was **reversed**, not that it was paid in full — a reversal fills the same room a payment does, and a bursar told \"paid in full\" about money that never arrived would go looking for it. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. That sum costs one query per line of the target's subtree, all of them under that lock, so a line carries **at most 20 applied lines** (the payments under a charge, the refunds under a payment, and the reversals among them): past that a further payment or refund against it is a `409`, an installment settled in more than twenty pieces being pathological. The ceiling binds new writes only — a line that already carries more still reads, still refunds through its own children, and is still reversible. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), |
| 63 | 63 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
src/web/appointments.rsmodified+10 -0
| @@ -363,6 +363,16 @@ async fn publish_slots( | ||
| 363 | 363 | /// already taken is not carried |
| 364 | 364 | /// here: booking a taken one answers `409`. Paged via `?limit=&offset=` (omit |
| 365 | 365 | /// `limit` for every slot); returns a `{items, total, limit, offset}` envelope. |
| 366 | +/// | |
| 367 | +/// Each slot carries its teacher's `PersonRef` (id, username, name) to *every* | |
| 368 | +/// authenticated caller, parents included — deliberate, and not to be | |
| 369 | +/// "tightened". A parent's three direct routes to that identity all refuse | |
| 370 | +/// (`GET /users/{id}/profile` 403, `/users/search` and `/users` teacher+/admin), | |
| 371 | +/// but you cannot pick whom to book a conference with from an anonymous | |
| 372 | +/// calendar: this list *is* the staff directory for the booking flow, scoped to | |
| 373 | +/// people who published bookable time. Same for the `teacher` / `proposed_by` / | |
| 374 | +/// `decided_by` refs on a booking. Pinned by | |
| 375 | +/// `tests/regress_appointments.rs::a_parent_reads_the_slot_teachers_identity`. | |
| 366 | 376 | // ponytail: occupancy would be one query per slot with today's domain API; a |
| 367 | 377 | // batch "live bookings for these slots" read would let the list carry it. |
| 368 | 378 | #[utoipa::path( |
src/web/exams/review.rsmodified+18 -10
| @@ -172,9 +172,17 @@ pub(crate) async fn student_marks_history( | ||
| 172 | 172 | // marked this student (an ExamResult row proves it). |
| 173 | 173 | |
| 174 | 174 | /// The exam plus the per-student review gate the three self-review reads share. |
| 175 | -/// 404 if the exam is missing or still a draft, 403 if review is off for it, | |
| 176 | -/// 404 until the caller has a mark on it (nothing to review yet), and 409 while | |
| 177 | -/// the caller could still write a sitting at it. | |
| 175 | +/// 404 if the exam is missing, still a draft, or the caller has no mark on it | |
| 176 | +/// (nothing to review yet), 403 if review is off for it, and 409 while the | |
| 177 | +/// caller could still write a sitting at it. | |
| 178 | +/// | |
| 179 | +/// The mark check runs *before* the `allow_review` one, and must stay there: a | |
| 180 | +/// caller with no mark is an outsider to this exam, and answering them 403-if- | |
| 181 | +/// off / 404-otherwise made the status code an oracle for a flag they cannot | |
| 182 | +/// read anywhere else (`GET /exams/{id}` refuses them at `can_view_course` | |
| 183 | +/// before it serves `allow_review` at all). With the mark first, an outsider's | |
| 184 | +/// answer is 404 whatever the flag says; only a caller who was marked — who | |
| 185 | +/// therefore sat the exam, enrolled or since dropped — ever sees the 403. | |
| 178 | 186 | /// |
| 179 | 187 | /// That last check is the one a mark alone can't make: the mark lookup reads the |
| 180 | 188 | /// *latest* sitting's mark, so a mark left at seq 1 satisfies it forever — a |
| @@ -196,12 +204,12 @@ pub(crate) async fn reviewable_exam( | ||
| 196 | 204 | if exam.is_draft() { |
| 197 | 205 | return Err(AppError::NotFound); |
| 198 | 206 | } |
| 199 | - if !exam.get_allow_review() { | |
| 200 | - return Err(AppError::Forbidden("review not enabled for this exam")); | |
| 201 | - } | |
| 202 | 207 | ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) |
| 203 | 208 | .await? |
| 204 | 209 | .ok_or(AppError::NotFound)?; |
| 210 | + if !exam.get_allow_review() { | |
| 211 | + return Err(AppError::Forbidden("review not enabled for this exam")); | |
| 212 | + } | |
| 205 | 213 | let attempts = ExamAttempt::list_for_user(exam.get_id(), user.get_id(), &st.db).await?; |
| 206 | 214 | let now = Timestamp::now(); |
| 207 | 215 | if attempts |
| @@ -278,7 +286,7 @@ async fn live_elsewhere( | ||
| 278 | 286 | responses( |
| 279 | 287 | (status = 200, description = "The caller's own sitting numbers, ascending", body = [i64]), |
| 280 | 288 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 281 | - (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), | |
| 289 | + (status = 403, description = "Review not enabled for this exam — only a caller who already has a mark on it ever reads this, everyone else gets the `404`", body = ErrorResponse), | |
| 282 | 290 | (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), |
| 283 | 291 | (status = 409, description = "The caller can still sit this exam (a sitting in progress, or an attempt left under `max_attempts` while the exam is open)", body = ErrorResponse), |
| 284 | 292 | ), |
| @@ -321,7 +329,7 @@ pub(crate) async fn review_attempts( | ||
| 321 | 329 | (status = 200, description = "A page of the exam's questions with `correct` (all of them when unpaged); `correct` is `null` on a question whose bank template the caller has live under an open sitting elsewhere", body = Page<QuestionResponse>), |
| 322 | 330 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 323 | 331 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 324 | - (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), | |
| 332 | + (status = 403, description = "Review not enabled for this exam — only a caller who already has a mark on it ever reads this, everyone else gets the `404`", body = ErrorResponse), | |
| 325 | 333 | (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), |
| 326 | 334 | (status = 409, description = "The caller can still sit this exam (a sitting in progress, or an attempt left under `max_attempts` while the exam is open)", body = ErrorResponse), |
| 327 | 335 | ), |
| @@ -360,7 +368,7 @@ pub(crate) async fn review_questions( | ||
| 360 | 368 | responses( |
| 361 | 369 | (status = 200, description = "That sitting's answers, judged", body = AttemptAnswersResponse), |
| 362 | 370 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 363 | - (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), | |
| 371 | + (status = 403, description = "Review not enabled for this exam — only a caller who already has a mark on it ever reads this, everyone else gets the `404`", body = ErrorResponse), | |
| 364 | 372 | (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), |
| 365 | 373 | (status = 409, description = "The caller can still sit this exam (a sitting in progress, or an attempt left under `max_attempts` while the exam is open)", body = ErrorResponse), |
| 366 | 374 | ), |
| @@ -393,7 +401,7 @@ pub(crate) async fn review_attempt_answers( | ||
| 393 | 401 | responses( |
| 394 | 402 | (status = 200, description = "The caller's drawing bytes", content_type = "image/*"), |
| 395 | 403 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 396 | - (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), | |
| 404 | + (status = 403, description = "Review not enabled for this exam — only a caller who already has a mark on it ever reads this, everyone else gets the `404`", body = ErrorResponse), | |
| 397 | 405 | (status = 404, description = "No such exam/question/drawing, a draft, or the caller has no mark on it", body = ErrorResponse), |
| 398 | 406 | (status = 409, description = "The caller can still sit this exam (a sitting in progress, or an attempt left under `max_attempts` while the exam is open)", body = ErrorResponse), |
| 399 | 407 | ), |
tests/regress_appointments.rsmodified+44 -0
| @@ -218,6 +218,50 @@ async fn accepting_a_superseded_proposal_is_refused() { | ||
| 218 | 218 | assert_eq!(res.body["ends_at"], swapped_ends_at); |
| 219 | 219 | } |
| 220 | 220 | |
| 221 | +/// Not a defect — a pin on a deliberate disclosure, so a future "tightening" | |
| 222 | +/// fails loudly instead of silently killing the booking flow. `GET | |
| 223 | +/// /appointments/slots` hands a parent the slot teacher's `PersonRef`, an | |
| 224 | +/// identity all three of a parent's direct routes refuse them (`/users/{id}/ | |
| 225 | +/// profile` 403, `/users/search` teacher+, `/users` admin). It has to: you | |
| 226 | +/// cannot choose whom to book a conference with from an anonymous calendar. | |
| 227 | +#[tokio::test] | |
| 228 | +async fn a_parent_reads_the_slot_teachers_identity() { | |
| 229 | + let (app, db) = app_and_db().await; | |
| 230 | + let ali = login_as(&app, &db, "ali", "teacher").await; | |
| 231 | + let ali_id = me_id(&app, &ali).await; | |
| 232 | + let veli = login_as(&app, &db, "veli", "parent").await; | |
| 233 | + let now = Timestamp::now().as_millis(); | |
| 234 | + | |
| 235 | + let res = send( | |
| 236 | + &app, | |
| 237 | + "POST", | |
| 238 | + "/appointments/slots", | |
| 239 | + Some(&ali), | |
| 240 | + Some(json!({ "starts_at": now + HOUR_MS, "ends_at": now + 2 * HOUR_MS })), | |
| 241 | + ) | |
| 242 | + .await; | |
| 243 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 244 | + | |
| 245 | + // The parent is refused that identity everywhere it is asked for directly. | |
| 246 | + for uri in [ | |
| 247 | + format!("/users/{ali_id}/profile"), | |
| 248 | + "/users/search?q=ali".to_string(), | |
| 249 | + "/users".to_string(), | |
| 250 | + ] { | |
| 251 | + let res = send(&app, "GET", &uri, Some(&veli), None).await; | |
| 252 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}: {}", res.body); | |
| 253 | + } | |
| 254 | + | |
| 255 | + // And gets it here anyway, on purpose: id, username, and the name they need | |
| 256 | + // to recognise the teacher they are booking. | |
| 257 | + let res = send(&app, "GET", "/appointments/slots", Some(&veli), None).await; | |
| 258 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 259 | + let teacher = &common::items(&res.body)[0]["teacher"]; | |
| 260 | + assert_eq!(teacher["id"], ali_id.as_str(), "{}", res.body); | |
| 261 | + assert_eq!(teacher["username"], "ali", "{}", res.body); | |
| 262 | + assert!(teacher.get("display_name").is_some(), "{}", res.body); | |
| 263 | +} | |
| 264 | + | |
| 221 | 265 | /// An answer belongs to the question of *its own* POST. Two POSTs on one thread |
| 222 | 266 | /// interleave across `append_user` / `append_pending_assistant`, so the rows |
| 223 | 267 | /// land `userA, userB, asstA, asstB` — and "the newest user row written before |
tests/regress_review.rsmodified+98 -0
| @@ -591,3 +591,101 @@ async fn review_stays_shut_while_another_sitting_is_still_available() { | ||
| 591 | 591 | res.body |
| 592 | 592 | ); |
| 593 | 593 | } |
| 594 | + | |
| 595 | +/// The review gate consulted `allow_review` before it had established the caller | |
| 596 | +/// has anything to review, so `GET /exams/{id}/review/attempts` answered 403 iff | |
| 597 | +/// (the exam exists ∧ is published ∧ review is off) and 404 otherwise — a | |
| 598 | +/// status-code oracle handing any authenticated caller, an unenrolled student or | |
| 599 | +/// a parent, a flag `GET /exams/{id}` refuses them outright (`can_view_course` | |
| 600 | +/// answers 403 there before `allow_review` is ever serialised). The mark check | |
| 601 | +/// runs first now, so an outsider reads 404 whichever way the flag is set, and | |
| 602 | +/// the flag-dependent answer is left to callers who were marked. | |
| 603 | +#[tokio::test] | |
| 604 | +async fn the_review_gate_does_not_leak_allow_review_to_outsiders() { | |
| 605 | + let (app, db) = app_and_db().await; | |
| 606 | + let teacher = login_as(&app, &db, "rev_flag_t", "teacher").await; | |
| 607 | + let student = login(&app, "rev_flag_s").await; | |
| 608 | + let student_id = me_id(&app, &student).await; | |
| 609 | + let outsider = login(&app, "rev_flag_out").await; | |
| 610 | + let parent = login_as(&app, &db, "rev_flag_p", "parent").await; | |
| 611 | + | |
| 612 | + let course = create_course(&app, &teacher, "physics").await; | |
| 613 | + enroll(&app, &teacher, &course, &student_id).await; | |
| 614 | + | |
| 615 | + // Two published exams, identical but for the flag under test. The student | |
| 616 | + // uses up their one sitting at each and is marked, so their read reaches the | |
| 617 | + // flag; nobody else has a mark at either. | |
| 618 | + let sat = async |title: &str, review: bool| { | |
| 619 | + let res = create_exam_with( | |
| 620 | + &app, | |
| 621 | + &teacher, | |
| 622 | + &course, | |
| 623 | + json!({ "title": title, "kind": "quiz", "mode": "open", | |
| 624 | + "max_attempts": 1, "allow_review": review }), | |
| 625 | + ) | |
| 626 | + .await; | |
| 627 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 628 | + let exam = id_of(&res.body); | |
| 629 | + let res = send( | |
| 630 | + &app, | |
| 631 | + "POST", | |
| 632 | + &format!("/exams/{exam}/attempt"), | |
| 633 | + Some(&student), | |
| 634 | + None, | |
| 635 | + ) | |
| 636 | + .await; | |
| 637 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 638 | + let res = send( | |
| 639 | + &app, | |
| 640 | + "POST", | |
| 641 | + &format!("/exams/{exam}/results"), | |
| 642 | + Some(&teacher), | |
| 643 | + Some(json!({ "mark": 50, "user_id": student_id.as_str() })), | |
| 644 | + ) | |
| 645 | + .await; | |
| 646 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 647 | + let res = send( | |
| 648 | + &app, | |
| 649 | + "POST", | |
| 650 | + &format!("/exams/{exam}/attempt/finish"), | |
| 651 | + Some(&student), | |
| 652 | + None, | |
| 653 | + ) | |
| 654 | + .await; | |
| 655 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 656 | + exam | |
| 657 | + }; | |
| 658 | + let open = sat("open review", true).await; | |
| 659 | + let shut = sat("shut review", false).await; | |
| 660 | + | |
| 661 | + let review_of = async |cookie: &str, exam: &str| { | |
| 662 | + send( | |
| 663 | + &app, | |
| 664 | + "GET", | |
| 665 | + &format!("/exams/{exam}/review/attempts"), | |
| 666 | + Some(cookie), | |
| 667 | + None, | |
| 668 | + ) | |
| 669 | + .await | |
| 670 | + .status | |
| 671 | + }; | |
| 672 | + | |
| 673 | + // The legitimate flow, untouched: marked, sittings used up, review on. | |
| 674 | + assert_eq!(review_of(&student, &open).await, StatusCode::OK); | |
| 675 | + // And the documented refusal still bites that same student when it is off. | |
| 676 | + assert_eq!(review_of(&student, &shut).await, StatusCode::FORBIDDEN); | |
| 677 | + | |
| 678 | + // The oracle: to a caller with no mark the two exams must be one answer — | |
| 679 | + // and the same answer an exam that does not exist gives. | |
| 680 | + let nowhere = review_of(&outsider, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await; | |
| 681 | + assert_eq!(nowhere, StatusCode::NOT_FOUND); | |
| 682 | + for (who, cookie) in [("unenrolled student", &outsider), ("parent", &parent)] { | |
| 683 | + let on_open = review_of(cookie, &open).await; | |
| 684 | + let on_shut = review_of(cookie, &shut).await; | |
| 685 | + assert_eq!(on_open, nowhere, "{who} reads the review-on exam apart"); | |
| 686 | + assert_eq!( | |
| 687 | + on_shut, on_open, | |
| 688 | + "{who}: the status code still reads the flag" | |
| 689 | + ); | |
| 690 | + } | |
| 691 | +} |