From 32949bd584bca5bfd193fc4bee9d27cc5be1de08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 15 Jul 2026 16:28:33 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(web)!:=20gate=20enrollment,=20?= =?UTF-8?q?exams,=20grading,=20roll=20call=20to=20students?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Only Role::Student may enroll, sit exams, be graded, or appear on a class roster; teachers and above run those, they never take part. The manager+ teacher-presence roll call is unchanged. Two enforcement layers: - Enroll-time: `enroll` rejects a non-student target (400). Enrollment is student membership -- the choke point the rest ride on. - Action-time: `ensure_student` guards the exam sit paths (start, room WS door, answer save; 403) and the grade + roll-call targets (400), checked against the live role -- a post-enroll promotion can't smuggle staff in, and a stale enrollment goes inert instead of active. The answer tail re-judges the role per save (`ensure_student_now`, beside the enrollment wall on the path REST and the exam room share), so a promotion mid-exam also cuts an already-open room socket -- the door check is never the last word for a connection that outlives the role. Passive reads (own attempt/result, question view, finish) stay ungated: a non-student has no attempt to read and finish only submits saved work. Event attendance stays open -- events are school-wide, not classes. Behavior change: a user can be both course creator and enrollee only across a demotion now (staff create, students enroll), so the catalog-dedup regression drives that overlap via set_role. Docs updated per the surfaces checklist (utoipa 400/403 + endpoint docs, lib.rs exams/courses tags + intro, README matrix/route table/prose). Adds regression tests: only_students_can_be_enrolled, promotion_out_of_student_freezes_the_seat, and (e2e, over a live socket) exam_room_promotion_mid_exam_closes_the_sheet. --- README.md | 44 ++++++----- src/lib.rs | 6 +- src/web/courses.rs | 16 +++- src/web/exam_ws.rs | 18 +++-- src/web/exams.rs | 65 +++++++++++++--- src/web/sessions.rs | 37 +++++---- tests/e2e.rs | 85 +++++++++++++++++++++ tests/integration.rs | 178 +++++++++++++++++++++++++++++++++++++++---- 8 files changed, 378 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index e6e66a3..98d0ee1 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,8 @@ Session-cookie auth with four hierarchical roles (`student < teacher < manager < admin`). Notes are per-user. Attendance is event + attendees: create an event, then mark users present / absent / late / excused. Marks are course-shaped (Google Classroom style): a teacher creates a course, enrolls students, adds -exams inside it, and grades; students read a per-course weighted average and +exams inside it, and grades — enrolling, sitting exams, roll call, and marks are +all student-only, staff never take part; students read a per-course weighted average and an overall average from their mark report — each exam weighted by its **kind** (midterms can count double, orals once: weights are set per kind in settings, not per exam). Exams run **sync** (one @@ -162,23 +163,23 @@ effect on the user's very next call (no re-login). | View a course's sessions | student | Only inside **visible** courses: enrolled, creator, or `manager`+ | | List a session's roll call | teacher | The **session's teacher**, or anyone with course-management rights | | Create / edit / delete a course session | teacher | Course-management rights (course creator, or `manager`+) | -| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights | +| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights; only students sit on a roster | | Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call — the teacher can't self-mark | | Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | | Read **own** attendance report | student | | | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | | View **visible** courses/exams; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) | -| Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | Must be enrolled; window (where one exists) and `max_attempts` enforced by the server | -| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | Attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off | +| Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server | +| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off | | Author an exam's questions (add/edit/delete) | teacher | Course-management rights; frozen once anyone has an attempt | | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key | | Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights | | Create courses | teacher | The creator manages the course | -| Manage inside a course: edit/delete it, enroll/unenroll, add/edit/delete its exams, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course | +| Manage inside a course: edit/delete it, enroll/unenroll **students**, add/edit/delete its exams, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course; only students can be enrolled | | View a course's roster, an exam's result list / statistics | teacher | Course-management rights | | Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | -| Grade students | teacher | Target must be **enrolled**; grading never targets oneself | +| Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | | Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands) and the academic calendar are management's call | @@ -277,7 +278,7 @@ their existing shapes: the student exam-room reads | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) | | PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) | | DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments (creator, or manager+) | -| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a user (idempotent upsert; course manager) | +| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled) | | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | @@ -285,7 +286,7 @@ their existing shapes: the student exam-room reads | GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) | | PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) | | DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) | -| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled** students; the teacher's own row needs manager+ | +| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ | | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged | | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) | | POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?}` — add an exam (course manager); its weight comes from the kind | @@ -294,12 +295,12 @@ their existing shapes: the student exam-room reads | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) | | PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) | | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) | -| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) | +| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only) | | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged | | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) | | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) | | GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) | -| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt — enrolled; window open where one exists; `409` once `max_attempts` is spent | +| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt — students only; enrolled; window open where one exists; `409` once `max_attempts` is spent | | GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` | | POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room | | POST | `/exams/{id}/questions` | teacher | `{text, kind, points, choices?, correct?}` — add a question (course manager; frozen once attempted) | @@ -307,9 +308,9 @@ their existing shapes: the student exam-room reads | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | | GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires enrollment + an attempt) | -| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while enrolled and `in_progress` (and not locked out by a closed rejoin door) | +| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) | | GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) | -| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room: state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | +| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager) | | GET | `/exams/{id}/live/stream` | teacher | The same snapshot as SSE `snapshot` events every ~2s (course manager) | | GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) | @@ -459,8 +460,9 @@ A student **sits** an exam through attempts (sitting 1, 2, … — each row id i the composite `exam_user[_seq]` key, so a sitting exists at most once by construction): -- `POST /exams/{id}/attempt` starts, resumes, or retakes (enrolled; window - open where one exists — `open` exams start anytime). While the latest +- `POST /exams/{id}/attempt` starts, resumes, or retakes (students only — + staff never sit; enrolled; window open where one exists — `open` exams start + anytime). While the latest sitting runs, re-posting returns it unchanged (`200`, not `201`): reconnecting never resets the clock. Once it is submitted or expired, re-posting mints the next sitting (`201`) **from a blank answer sheet** — @@ -558,8 +560,9 @@ clock on every save): upsert: one row per question+user, re-answering overwrites. The payload must match the question's kind (`selected` indexing a choice, or `text` ≤ 10 000 chars — empty clears the draft); mismatches are `400`s. Requires - enrollment (`403`): an unenrollment mid-exam closes the sheet (the exam - room's door check, applied to every save — finishing stays open). Once the + the student role and enrollment (`403`): a promotion out of `student` or an + unenrollment mid-exam closes the sheet (the exam room's door checks, + re-applied to every save — finishing stays open). Once the attempt is submitted or past its deadline every save is a `409` — likewise while the student has left the exam room with `allow_rejoin` off; answers saved in time survive untouched for grading (until a retake wipes the sheet @@ -573,9 +576,9 @@ suggestion to read while grading, never written anywhere. **The exam room (WebSocket)** — `GET /exams/{id}/attempt/ws`, cookie-authed like everything else; REST above remains the full fallback. Gates run before -the upgrade: unknown exam `404`, draft with no mode `409`, not enrolled `403`, -no attempt yet `404` (start it first), submitted/expired `409`, left while -rejoin is closed `409`. Then JSON text frames: +the upgrade: unknown exam `404`, draft with no mode `409`, not a student `403`, +not enrolled `403`, no attempt yet `404` (start it first), submitted/expired +`409`, left while rejoin is closed `409`. Then JSON text frames: | direction | frame | |-----------|-------| @@ -639,7 +642,8 @@ are ordered by `starts_at` (a timetable, not a creation log). **Roll call** (`/sessions/{id}/attendance`) deliberately differs from event attendance: students never mark themselves. The session's teacher or a course -manager marks **enrolled** students (an unenrolled target is a `400`), and the +manager marks **enrolled** students — only students attend classes, so a +non-student or unenrolled target is a `400` — and the **session teacher's own** presence row can only be written or removed by manager+ — staff presence is management's call, so a teacher can't declare themselves present. Listing the roll call follows the same rights as taking diff --git a/src/lib.rs b/src/lib.rs index 843e3a7..a8f2549 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands) lives in an editable settings singleton, and courses may link to academic terms. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands) lives in an editable settings singleton, and courses may link to academic terms. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", ), modifiers(&SecurityAddon), tags( @@ -41,11 +41,11 @@ use crate::state::AppState; (name = "users", description = "User info: self-service profile, name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile administration (admin only)"), (name = "notes", description = "Per-user notes CRUD"), (name = "events", description = "Events and attendance"), - (name = "courses", description = "Courses, enrollment, course exams, and course sessions"), + (name = "courses", description = "Courses, enrollment (students only), course exams, and course sessions"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), - (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts 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). A modeless exam is an offline-graded draft — attempts on it are a 409. 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"), + (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). A modeless exam is an offline-graded draft — attempts on it are a 409. 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"), (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)"), (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands. Read: any authenticated user; edit: manager+"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), diff --git a/src/web/courses.rs b/src/web/courses.rs index cda8141..4a26e1b 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -376,7 +376,9 @@ async fn delete_course( // ---- enrollments ---------------------------------------------------------- /// Enroll a user into a course (idempotent upsert). Requires teacher+ and -/// course management rights. +/// course management rights. Only students can be enrolled — enrollment is +/// student membership, and it gates sitting exams, being graded, and the class +/// roster, all student-only. #[utoipa::path( post, path = "/{id}/enrollments", @@ -386,7 +388,7 @@ async fn delete_course( request_body = EnrollUser, responses( (status = 200, description = "Enrolled (or already enrolled)", body = EnrollmentResponse), - (status = 400, description = "Unknown user", body = ErrorResponse), + (status = 400, description = "Unknown user, or user is not a student", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), @@ -415,6 +417,16 @@ async fn enroll( })); }; + // Enrollment is student membership: it gates sitting exams, being graded, + // and appearing on a lesson roster — all student-only. Staff run courses, + // they don't enroll in them. + if target_user.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be enrolled in a course", + })); + } + let enrollment = Enrollment::enroll(course.get_id(), &target, user.get_id(), &st.db).await?; let people = PersonRef::map_of(&[&target_user, &user]); Ok(Json(EnrollmentResponse::new(&enrollment, &people))) diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 329c5b6..31eb898 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -24,7 +24,9 @@ //! Every save and every tick re-reads the exam and attempt, so the deadline //! stays server-authoritative: a teacher extending `ends_at` (or `duration_ms`) //! mid-exam moves this room's clock on the next tick, and a stale client can -//! never write past its real deadline. +//! never write past its real deadline. Every save also re-judges the sitter — +//! live role and enrollment — so a promotion out of `student` or an +//! unenrollment mid-exam closes the sheet with no reconnect needed. //! //! The room is also the presence signal behind the rejoin policy: connecting //! clears the attempt's `left_at`, and the *last* socket of the sitting to @@ -60,7 +62,9 @@ use crate::domain::user::UserId; use crate::error::AppError; use crate::state::AppState; use crate::web::CurrentUser; -use crate::web::exams::{check_rejoin, ensure_enrolled, save_answer_in, writable_attempt}; +use crate::web::exams::{ + check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt, +}; /// What the client asked for, tagged by `type`. #[derive(Deserialize)] @@ -79,10 +83,11 @@ enum ClientMessage { /// Upgrade into the caller's exam room. All gates run *before* the upgrade so /// a rejected client gets a proper HTTP status instead of an instant close: -/// unknown exam (404), draft with no mode (409), not enrolled (403), no -/// attempt yet (404 — `POST /exams/{id}/attempt` first), submitted or expired -/// (409), left the room while rejoin is closed (409). Entering the room -/// clears the attempt's `left_at` — the student is back inside. +/// unknown exam (404), draft with no mode (409), not a student (403), not +/// enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` first), +/// submitted or expired (409), left the room while rejoin is closed (409). +/// Entering the room clears the attempt's `left_at` — the student is back +/// inside. pub async fn attempt_ws( State(st): State, CurrentUser(user): CurrentUser, @@ -97,6 +102,7 @@ pub async fn attempt_ws( "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", )); } + ensure_student(&user)?; ensure_enrolled(&exam, user.get_id(), &st.db).await?; let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; check_rejoin(&exam, &attempt)?; diff --git a/src/web/exams.rs b/src/web/exams.rs index a7554fa..1ceef31 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -387,8 +387,9 @@ async fn delete_exam( // ---- results ------------------------------------------------------------ /// Record (or overwrite) a student's mark for an exam. Requires teacher+ and -/// management rights over the exam's course; the target must be enrolled. -/// Students never grade — and nobody grades themselves. +/// management rights over the exam's course; the target must be a student and +/// enrolled. Only students carry marks; students never grade — and nobody +/// grades themselves. #[utoipa::path( post, path = "/{id}/results", @@ -398,7 +399,7 @@ async fn delete_exam( request_body = GradeResult, responses( (status = 200, description = "Result recorded", body = ExamResultResponse), - (status = 400, description = "Invalid mark, unknown user, or user not enrolled", body = ErrorResponse), + (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), @@ -439,6 +440,15 @@ async fn grade( })); }; + // Only students carry marks — the grade system is theirs alone. A stale + // enrollment left behind by a promotion can't reopen grading for staff. + if target_user.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be graded", + })); + } + // ... and be enrolled in the exam's course. if Enrollment::read_for_user(exam.get_course(), &target, &st.db) .await? @@ -741,9 +751,10 @@ async fn attempts_used(exam: &ExamId, user: &UserId, db: &Database) -> Result Result, db: &Database, ) -> Result { + ensure_student_now(attempt.get_user(), db).await?; ensure_enrolled(exam, attempt.get_user(), db).await?; check_rejoin(exam, attempt)?; let question = question_of_exam(exam.get_id(), question_id, db).await?; ExamAnswer::save(&question, attempt.get_user(), selected, text, db).await } +/// A 403 unless `user` is a student. Sitting an exam is a student action — +/// teachers and above run exams, they never take them — so the sit paths +/// (start, room, save) enforce it on the *current* role. Checking the live +/// role, not just enrollment, closes the gap a mid-exam promotion would open +/// and neutralizes any stale non-student enrollment. Reading one's own attempt +/// and finishing stay ungated: a non-student has no attempt to read, and +/// finishing only submits work already saved. +pub(crate) fn ensure_student(user: &User) -> Result<(), AppError> { + if user.get_role() != Role::Student { + return Err(AppError::Forbidden("only students can sit exams")); + } + Ok(()) +} + +/// The answer path's live edition of [`ensure_student`]: re-read the row and +/// judge the *current* role, exactly like the enrollment wall beside it. Both +/// save paths run through here (REST per request, the exam room per message), +/// so a promotion out of `student` mid-exam closes the sheet on the very next +/// save — the room's door check is not the last word for a socket that +/// outlives the role. +pub(crate) async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> { + let user = User::read(user, db).await?.ok_or(AppError::Unauthorized)?; + ensure_student(&user) +} + /// A 403 unless `user` is enrolled in the exam's course — the same wall the /// exam room checks at its door, re-applied to the sitting's content paths so /// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the @@ -1688,8 +1727,9 @@ async fn attempt_questions( /// Save (or overwrite) one answer in the caller's in-progress attempt. /// `choice` questions take `selected`; `text` questions take `text`. Requires -/// enrollment in the exam's course — an unenrollment mid-exam closes the -/// sheet. Rejected once the attempt is submitted or its deadline has passed — +/// the student role and enrollment in the exam's course — an unenrollment (or a +/// promotion out of `student`) mid-exam closes the sheet. Rejected once the +/// attempt is submitted or its deadline has passed — /// the server clock, not the client's, is the judge — and rejected while the /// student has left the exam room with the exam's rejoin door closed. #[utoipa::path( @@ -1703,7 +1743,7 @@ async fn attempt_questions( (status = 200, description = "Answer saved", body = AnswerSavedResponse), (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), + (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), ), @@ -1717,6 +1757,7 @@ async fn save_answer( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + ensure_student(&user)?; let answer = save_answer_checked( &exam, user.get_id(), diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 8df7aa8..ec09663 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -266,9 +266,10 @@ async fn delete_session( // ---- roll call -------------------------------------------------------------- /// Record a user's roll-call state for a session. The session's teacher or a -/// course manager marks **enrolled students**; marking the **session's -/// teacher** requires manager+ (staff presence is management's call, so a -/// teacher can't mark themselves present). Students never self-mark a lesson. +/// course manager marks **enrolled students** (only students attend classes); +/// marking the **session's teacher** requires manager+ (staff presence is +/// management's call, so a teacher can't mark themselves present). Students +/// never self-mark a lesson. #[utoipa::path( post, path = "/{id}/attendance", @@ -278,7 +279,7 @@ async fn delete_session( request_body = MarkRollCall, responses( (status = 200, description = "Roll-call state recorded", body = SessionAttendanceResponse), - (status = 400, description = "Invalid status, unknown user, or target not on the roster", body = ErrorResponse), + (status = 400, description = "Invalid status, unknown user, target not a student, or not on the roster", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the session teacher or a course manager; or marking the teacher without manager+", body = ErrorResponse), (status = 404, description = "Session not found", body = ErrorResponse), @@ -316,15 +317,25 @@ async fn mark_roll_call( "marking the session's teacher requires manager role or higher", )); } - } else if Enrollment::read_for_user(session.get_course(), &target, &st.db) - .await? - .is_none() - { - // Everyone else on a lesson's roster comes from the enrollment list. - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user is not enrolled in this course", - })); + } else { + // Everyone else on a lesson's roster is an enrolled student. Only + // students attend classes; checking the live role keeps a stale + // enrollment (left by a promotion) from putting staff on the roll. + if target_user.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be marked present in a lesson", + })); + } + if Enrollment::read_for_user(session.get_course(), &target, &st.db) + .await? + .is_none() + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user is not enrolled in this course", + })); + } } let attendance = diff --git a/tests/e2e.rs b/tests/e2e.rs index 020d788..37491c3 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -758,6 +758,7 @@ async fn ws_frame_of_type(ws: &mut WsStream, kind: &str) -> Value { /// `window_ms` from now. struct ExamRoom { base: String, + db: Database, teacher: Client, student: Client, student_id: String, @@ -840,6 +841,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { let cookie = raw_session_cookie(&base, "veli").await; ExamRoom { base, + db, teacher, student, student_id, @@ -1060,6 +1062,89 @@ async fn exam_room_rejects_bad_handshakes() { ); } +/// A promotion out of `student` mid-exam closes the open room's answer sheet +/// on the very next save: the role wall is re-judged per save against the +/// live row — like the enrollment wall — so the door check is never the last +/// word for a socket that outlives the role. A demotion back reopens the +/// sheet on the same socket: it is a live check, not a latch. +#[tokio::test] +async fn exam_room_promotion_mid_exam_closes_the_sheet() { + let room = exam_room_fixture(600_000).await; + let ExamRoom { + base, + db, + teacher, + student, + student_id, + cookie, + exam_id, + question_id, + .. + } = &room; + let res = student + .post(format!("{base}/exams/{exam_id}/attempt")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let mut ws = ws_open(base, exam_id, Some(cookie)).await.expect("upgrade"); + + // While the sitter is a student the sheet is open — save one answer. + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": question_id, "selected": 1 }), + ) + .await; + ws_frame_of_type(&mut ws, "saved").await; + + // Mid-exam, with the socket still open, the sitter stops being a student. + promote(db, "veli", "teacher").await; + + // The very next save is refused over the same socket... + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": question_id, "selected": 0 }), + ) + .await; + let error = ws_frame_of_type(&mut ws, "error").await; + assert!( + error["message"].as_str().unwrap().contains("only students"), + "{error}" + ); + + // ... and over REST — the two paths share the wall. + let res = student + .post(format!("{base}/exams/{exam_id}/attempt/answers")) + .json(&json!({ "question_id": question_id, "selected": 0 })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::FORBIDDEN); + + // The refused writes left no trace: the sheet still holds the original. + let sheet: Value = teacher + .get(format!( + "{base}/exams/{exam_id}/attempts/{student_id}/answers" + )) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(sheet["answers"].as_array().unwrap().len(), 1); + assert_eq!(sheet["answers"][0]["selected"], 1); + + // Demoted back, the same socket writes again — no reconnect required. + promote(db, "veli", "student").await; + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": question_id, "selected": 0 }), + ) + .await; + ws_frame_of_type(&mut ws, "saved").await; +} + /// A teacher extending `ends_at` mid-exam moves the open room's countdown on /// the next tick — the deadline is re-read, never cached in the socket. #[tokio::test] diff --git a/tests/integration.rs b/tests/integration.rs index f4fca06..9fb3715 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -7,7 +7,7 @@ use axum::body::Body; use axum::http::{Request, StatusCode}; use common::{ app_and_db, create_course, create_exam, create_exam_with, create_session, enroll, id_of, login, - login_as, me_id, mem_app, send, + login_as, me_id, mem_app, send, set_role, }; use hezarfen_backend::domain::exam::ExamId; use hezarfen_backend::domain::exam_attempt::ExamAttempt; @@ -2989,7 +2989,10 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { /// Regression: the grade endpoint verified the exam, the mark, and that the /// target exists — but never that the grader isn't the target, so any teacher -/// could write their own mark. "Grading never targets oneself" (README). +/// could write their own mark. "Grading never targets oneself" (README). The +/// self-check precedes the target-role and enrollment checks, so it holds even +/// though staff — the only ones who can grade — are never enrolled or +/// gradeable themselves. #[tokio::test] async fn graders_cannot_grade_themselves() { let (app, db) = app_and_db().await; @@ -2997,10 +3000,11 @@ async fn graders_cannot_grade_themselves() { let boss = login_as(&app, &db, "boss", "manager").await; let teacher_id = me_id(&app, &teacher).await; let boss_id = me_id(&app, &boss).await; + let student = login(&app, "veli").await; + let student_id = me_id(&app, &student).await; let course_id = create_course(&app, &teacher, "algebra").await; - enroll(&app, &teacher, &course_id, &teacher_id).await; - enroll(&app, &teacher, &course_id, &boss_id).await; + enroll(&app, &teacher, &course_id, &student_id).await; let exam_id = create_exam(&app, &teacher, &course_id, "t", "quiz").await; // Self-grading is forbidden at every privilege level, not just for teachers. @@ -3036,18 +3040,154 @@ async fn graders_cannot_grade_themselves() { 0 ); - // Grading someone *else* still works (boss grades teacher). + // Grading someone *else* still works (boss grades the enrolled student). let res = send( &app, "POST", &format!("/exams/{exam_id}/results"), Some(&boss), - Some(json!({ "mark": 90, "user_id": teacher_id })), + Some(json!({ "mark": 90, "user_id": student_id })), ) .await; assert_eq!(res.status, StatusCode::OK); } +/// Enrollment is student membership: staff (teacher/manager/admin) can't be +/// enrolled, so they never gain the seat that gates sitting exams, being +/// graded, and the class roster. A plain student enrolls fine. +#[tokio::test] +async fn only_students_can_be_enrolled() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let colleague = login_as(&app, &db, "colleague", "teacher").await; + let manager = login_as(&app, &db, "boss", "manager").await; + let colleague_id = me_id(&app, &colleague).await; + let manager_id = me_id(&app, &manager).await; + + let course = create_course(&app, &teacher, "algebra").await; + + // A fellow teacher and a manager are both refused — staff don't enroll. + for staff_id in [&colleague_id, &manager_id] { + let res = send( + &app, + "POST", + &format!("/courses/{course}/enrollments"), + Some(&teacher), + Some(json!({ "user_id": staff_id })), + ) + .await; + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "enrolling staff must be rejected" + ); + } + + // A student enrolls without complaint (the helper asserts 200). + let student = login(&app, "veli").await; + let student_id = me_id(&app, &student).await; + enroll(&app, &teacher, &course, &student_id).await; +} + +/// The student-only rule is enforced on the *live* role, not merely at enroll +/// time. A student enrolled mid-course, then promoted to staff, keeps the +/// enrollment row — but it goes inert: they can no longer sit the exam, save +/// answers, be graded, or be marked present. This is the "stale rows stay +/// inert" decision, made airtight by the action-time checks. +#[tokio::test] +async fn promotion_out_of_student_freezes_the_seat() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let student = login(&app, "veli").await; + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course, &student_id).await; + let future = Timestamp::now().as_millis() + 3_600_000; + let session = create_session(&app, &teacher, &course, future).await; + let exam = scheduled_exam( + &app, + &teacher, + &course, + json!({ "title": "essay", "kind": "quiz", "mode": "open" }), + ) + .await; + + // While still a student, the seat works: they can start a sitting. + let res = send( + &app, + "POST", + &format!("/exams/{exam}/attempt"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "student sits: {}", res.body); + + // Promote the enrolled student to teacher; the enrollment row survives. + set_role(&db, "veli", "teacher").await; + + // Sitting is now refused — the live role, not the stale seat, decides. + let res = send( + &app, + "POST", + &format!("/exams/{exam}/attempt"), + Some(&student), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "promoted user can't start a sitting" + ); + + // Nor can they save into the attempt they opened while still a student. + let res = send( + &app, + "POST", + &format!("/exams/{exam}/attempt/answers"), + Some(&student), + Some(json!({ "question_id": "nope", "selected": 0 })), + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "promoted user can't save answers" + ); + + // Grading the promoted user is refused — only students carry marks. + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(json!({ "mark": 80, "user_id": student_id })), + ) + .await; + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "promoted user can't be graded" + ); + + // Roll call is refused too — only students attend classes. + let res = send( + &app, + "POST", + &format!("/sessions/{session}/attendance"), + Some(&teacher), + Some(json!({ "status": "present", "user_id": student_id })), + ) + .await; + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "promoted user can't be rolled" + ); +} + /// Regression: `User::create` pre-checks the username and then inserts, so two /// concurrent registrations of the same name could both pass the check; the /// loser then hit the unique index and surfaced as a raw 500. A lost race must @@ -7158,18 +7298,27 @@ async fn search_rejects_a_blank_query() { // --- courses: catalog dedup ------------------------------------------------- -/// A teacher who is also enrolled in their own course sees it once in the -/// catalog, not twice — the created and enrolled sources are deduplicated. +/// A user who both created a course (while staff) and is enrolled in it (after +/// a demotion to student) sees it once in the catalog, not twice — the created +/// and enrolled sources are deduplicated. Enrollment is student-only now, so +/// that overlap can only arise across a role change; the dedup must still hold. #[tokio::test] async fn course_catalog_lists_a_creator_enrolled_course_once() { let (app, db) = app_and_db().await; - let teacher = login_as(&app, &db, "teacher", "teacher").await; - let teacher_id = me_id(&app, &teacher).await; + let creator = login_as(&app, &db, "teacher", "teacher").await; + let boss = login_as(&app, &db, "boss", "manager").await; + let creator_id = me_id(&app, &creator).await; - let course = create_course(&app, &teacher, "algebra").await; - enroll(&app, &teacher, &course, &teacher_id).await; + let course = create_course(&app, &creator, "algebra").await; + // Author the exam while still staff, before the demotion below. + let exam = create_exam(&app, &creator, &course, "mt", "quiz").await; + + // Demote the creator to student, then have a manager enroll them into their + // own course: they now show up in both the created and enrolled sources. + set_role(&db, "teacher", "student").await; + enroll(&app, &boss, &course, &creator_id).await; - let res = send(&app, "GET", "/courses", Some(&teacher), None).await; + let res = send(&app, "GET", "/courses", Some(&creator), None).await; assert_eq!(res.status, StatusCode::OK); let courses = common::items(&res.body); assert_eq!(courses.len(), 1, "created+enrolled must dedup: {courses:?}"); @@ -7177,8 +7326,7 @@ async fn course_catalog_lists_a_creator_enrolled_course_once() { // The exam catalog derives from the same visible set and must not double // the course's exams either. - let exam = create_exam(&app, &teacher, &course, "mt", "quiz").await; - let res = send(&app, "GET", "/exams", Some(&teacher), None).await; + let res = send(&app, "GET", "/exams", Some(&creator), None).await; let exams = common::items(&res.body); assert_eq!(exams.len(), 1, "one exam listed once: {exams:?}"); assert_eq!(exams[0]["id"], json!(exam));