forge
Explore
Log in

Don't you dare go Hollow

🚫 keep parents off the whiteboard entirely

Browse files at this commit

860b4ce03ebce7e5ea09a9f19db570596ccd0ba5Ahmet Kaan GümüşParent: a05b319
  • fix
    • 🚫 keep parents off the whiteboard entirely
Show full message
fix: 🚫 keep parents off the whiteboard entirely

A parent is the school's read-only observer, but every board route was
`CurrentUser` only β€” so a parent could open a board and draw on it.

The cut that does the work is in `resolve_participants`: a parent id is
refused as a participant, so a parent is never on a roster. That alone
makes `board_for` and the room's door answer the outsider's 404 on every
id-scoped route. `POST /boards` and `GET /boards` take `RequireStudent`
(a 403 there leaks nothing β€” no board exists to hide), while the read
path and the socket door re-check the role and answer 404, never 403,
which would confirm the board is there. Refusing the door is also what
stops a parent drawing: no socket, no `stroke` frame, and no per-stroke
role read on the hot path.

A board row written earlier that still lists a parent is inert β€” that
parent now sees a 404 for it like any stranger.
README.mdmodified+20 -6
@@ -10,8 +10,8 @@ attendance, pomodoro, and homework reports β€” that's the whole role. Notes are
10 per-file size cap is school policy in settings (`max_file_bytes`, default10 per-file size cap is school policy in settings (`max_file_bytes`, default
11 5 MiB). Any two users can **message** each other, mail-style β€” subject +11 5 MiB). Any two users can **message** each other, mail-style β€” subject +
12 body into the recipient's inbox, each side filing its own copy through12 body into the recipient's inbox, each side filing its own copy through
13-archive/trash with a read flag the sender sees as a receipt (one of the two13+archive/trash with a read flag the sender sees as a receipt (the only place a
14-places a `parent` writes β€” whiteboards below are the other). Attendance is event + attendees: create an event with an **audience**14+`parent` writes). Attendance is event + attendees: create an event with an **audience**
15 (the whole school, one role, a course's enrollment, or a **registration**15 (the whole school, one role, a course's enrollment, or a **registration**
16 signup list β€” omit for school-wide), then teachers mark the expected attendees16 signup list β€” omit for school-wide), then teachers mark the expected attendees
17 present / absent / late / excused (students never self-mark), and a **roster17 present / absent / late / excused (students never self-mark), and a **roster
@@ -111,8 +111,10 @@ inference outlives a request: the turn plus an empty `pending` answer are
111 written *first*, the call goes out after, so a reload never loses an answer;111 written *first*, the call goes out after, so a reload never loses an answer;
112 the client then polls the message or reads it off an SSE stream (see112 the client then polls the message or reads it off an SSE stream (see
113 "Chatbot").113 "Chatbot").
114-Any signed-in account (a `parent` included) can also open a **collaborative114+Any account from `student` upwards can also open a **collaborative
115-whiteboard**: a titled board whose membership is an **ad-hoc invite list** β€”115+whiteboard** (a `parent` gets no whiteboard access at all β€” it can neither open
116+one nor be invited onto one): a titled board whose membership is an **ad-hoc
117+invite list** β€”
116 the creator names participant user ids, and no course, session or appointment118 the creator names participant user ids, and no course, session or appointment
117 is involved. Every participant draws over a WebSocket, the creator alone119 is involved. Every participant draws over a WebSocket, the creator alone
118 clears, locks, closes or deletes, and someone who is not on a board gets a120 clears, locks, closes or deletes, and someone who is not on a board gets a
@@ -2503,10 +2505,22 @@ context without either end having to be redeployed in lockstep.
2503 2505
2504 A board is a shared canvas whose membership is an **ad-hoc invite list**: the2506 A board is a shared canvas whose membership is an **ad-hoc invite list**: the
2505 creator names participant user ids at `POST /boards` and that is the whole2507 creator names participant user ids at `POST /boards` and that is the whole
2506-model β€” no course, no lesson session, no appointment. Any signed-in account2508+model β€” no course, no lesson session, no appointment. Any account from
2507-(a `parent` included) may open one. **Every participant draws; the creator2509+`student` upwards may open one. **Every participant draws; the creator
2508 alone clears, locks, closes or deletes.**2510 alone clears, locks, closes or deletes.**
2509 2511
2512+**No parents, anywhere.** The `parent` role is the school's read-only observer,
2513+and it has no whiteboard access at all β€” not a view-only tier, none. It is
2514+refused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named*
2515+in an invite list either: `resolve_participants` rejects a parent id with a
2516+`400`, so a parent is never on a roster in the first place. That one cut is
2517+what closes the rest β€” never on a roster means the id-scoped routes and the
2518+room's door already answer the outsider's `404` (never a `403`, which would
2519+confirm the board is there), and no socket opens, so no `stroke` frame can be
2520+sent. The role bar is re-checked on the read path and at the door as well, so a
2521+board row written before this rule that still lists a parent is inert: that
2522+parent sees a `404` for it like any stranger.
2523+
2510 **Two doors, two statuses.** A caller who is not on a board gets a `404` on2524 **Two doors, two statuses.** A caller who is not on a board gets a `404` on
2511 every route, its existence included β€” an outsider must never learn a board is2525 every route, its existence included β€” an outsider must never learn a board is
2512 there. A participant who is not the creator has already been told it exists, so2526 there. A participant who is not the creator has already been told it exists, so
src/lib.rsmodified+1 -1
@@ -63,7 +63,7 @@ use crate::state::AppState;
63 (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β€” note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β€” those marks would silently re-weight. Also the food program: the meal slots menus are published for β€” each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) β€” the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β€” one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"),63 (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β€” note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β€” those marks would silently re-weight. Also the food program: the meal slots menus are published for β€” each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) β€” the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β€” one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"),
64 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β€” re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),64 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β€” re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),
65 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course β€” whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files β€” any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored β€” the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),65 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course β€” whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files β€” any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored β€” the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),
66- (name = "boards", description = "Collaborative whiteboards. Anyone opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids β€” no course, session or appointment is involved β€” and every participant draws on it; the creator alone clears, locks, closes or deletes it. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored β€” `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers, each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage and stamps `closed_at` on the way past β€” a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks β€” it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens β€” JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"),66+ (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids β€” no course, session or appointment is involved β€” and every participant draws on it; the creator alone clears, locks, closes or deletes it. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) β€” so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored β€” `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers, each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage and stamps `closed_at` on the way past β€” a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks β€” it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens β€” JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"),
67 (name = "terms", description = "Academic terms (semester/trimester/quarter β€” whatever the school runs); courses may link to one. A term still linked by any course cannot be deleted (409) β€” unlink those courses first. Read: any authenticated user; edit: manager+"),67 (name = "terms", description = "Academic terms (semester/trimester/quarter β€” whatever the school runs); courses may link to one. A term still linked by any course cannot be deleted (409) β€” unlink those courses first. Read: any authenticated user; edit: manager+"),
68 ),68 ),
69 )]69 )]
src/web/board_ws.rsmodified+7 -3
@@ -69,6 +69,7 @@ use crate::constant::{BOARD_REPLAY_CHUNK, BOARD_WS_TICK_SECS, MAX_BOARD_ID_LEN};
69 use crate::database::Database;69 use crate::database::Database;
70 use crate::domain::board::{Board, BoardId};70 use crate::domain::board::{Board, BoardId};
71 use crate::domain::board_stroke::BoardStroke;71 use crate::domain::board_stroke::BoardStroke;
72+use crate::domain::role::Role;
72 use crate::domain::timestamp::Timestamp;73 use crate::domain::timestamp::Timestamp;
73 use crate::domain::user::UserId;74 use crate::domain::user::UserId;
74 use crate::error::AppError;75 use crate::error::AppError;
@@ -108,9 +109,12 @@ enum ClientMessage {
108 109
109 /// Enter the caller's board room. Every gate runs *before* the upgrade so a110 /// Enter the caller's board room. Every gate runs *before* the upgrade so a
110 /// rejection is an HTTP status rather than an instant close: no session (401),111 /// rejection is an HTTP status rather than an instant close: no session (401),
111-/// and a board that does not exist β€” or that the caller is not on β€” is the112+/// and a board that does not exist β€” or that the caller is not on, or that the
113+/// caller is a `parent` and so barred from the whiteboard outright β€” is the
112 /// same **404**, because a non-participant must not learn a board exists (the114 /// same **404**, because a non-participant must not learn a board exists (the
113-/// rationale at `src/lib.rs`).115+/// rationale at `src/lib.rs`). Refusing the door is also what stops a parent
116+/// drawing: no socket, no `stroke` frame, and no per-stroke role read on the
117+/// hot path.
114 pub async fn board_ws(118 pub async fn board_ws(
115 State(st): State<AppState>,119 State(st): State<AppState>,
116 CurrentUser(user): CurrentUser,120 CurrentUser(user): CurrentUser,
@@ -120,7 +124,7 @@ pub async fn board_ws(
120 // Length-capped before the key is read back or echoed in a `state` frame.124 // Length-capped before the key is read back or echoed in a `state` frame.
121 // A key this long names no board, so it answers like any other stranger's125 // A key this long names no board, so it answers like any other stranger's
122 // board: 404.126 // board: 404.
123- if id.len() > MAX_BOARD_ID_LEN {127+ if id.len() > MAX_BOARD_ID_LEN || !user.get_role().at_least(Role::Student) {
124 return Err(AppError::NotFound);128 return Err(AppError::NotFound);
125 }129 }
126 let board = Board::read(&BoardId::from_key(&id), &st.db)130 let board = Board::read(&BoardId::from_key(&id), &st.db)
src/web/boards.rsmodified+28 -12
@@ -3,8 +3,9 @@
3 //! lock, close, delete). Live drawing itself rides the board-room WebSocket3 //! lock, close, delete). Live drawing itself rides the board-room WebSocket
4 //! next door; everything here is the REST half it sits beside.4 //! next door; everything here is the REST half it sits beside.
5 //!5 //!
6-//! The permission model is two predicates and nothing else6+//! The permission model is a role bar plus two predicates
7-//! ([`Board::is_participant`], [`Board::is_creator`]), applied in one order on7+//! (student-and-above, then [`Board::is_participant`], [`Board::is_creator`]),
8+//! applied in one order on
8 //! every route: a non-participant gets a **404** even for a board that plainly9 //! every route: a non-participant gets a **404** even for a board that plainly
9 //! exists (a 403 would confirm it β€” see the rationale at `src/lib.rs`), while a10 //! exists (a 403 would confirm it β€” see the rationale at `src/lib.rs`), while a
10 //! participant who is not the creator gets a **403** on the four commands. They11 //! participant who is not the creator gets a **403** on the four commands. They
@@ -30,11 +31,12 @@ use crate::constant::MAX_BOARD_PARTICIPANTS;
30 use crate::database::Database;31 use crate::database::Database;
31 use crate::domain::board::{Board, BoardId, BoardTitle};32 use crate::domain::board::{Board, BoardId, BoardTitle};
32 use crate::domain::board_stroke::BoardStroke;33 use crate::domain::board_stroke::BoardStroke;
34+use crate::domain::role::Role;
33 use crate::domain::user::{User, UserId};35 use crate::domain::user::{User, UserId};
34 use crate::error::{AppError, ErrorResponse, ValidationError};36 use crate::error::{AppError, ErrorResponse, ValidationError};
35 use crate::state::AppState;37 use crate::state::AppState;
36 38
37-use super::{CurrentUser, Page, PageParams, paginate, set_or_clear};39+use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear};
38 40
39 pub fn routes() -> OpenApiRouter<AppState> {41 pub fn routes() -> OpenApiRouter<AppState> {
40 OpenApiRouter::new()42 OpenApiRouter::new()
@@ -53,11 +55,16 @@ pub fn routes() -> OpenApiRouter<AppState> {
53 55
54 /// The board, or a 404 β€” including the deliberate 404 for a caller who is not56 /// The board, or a 404 β€” including the deliberate 404 for a caller who is not
55 /// on it. Every route starts here, so existence never leaks.57 /// on it. Every route starts here, so existence never leaks.
58+///
59+/// A `parent` is treated as an outsider rather than refused with a 403: the
60+/// role is barred from the whiteboard entirely, and a 403 would confirm the
61+/// board exists. [`resolve_participants`] keeps parents off every roster, so
62+/// this arm only ever fires for a row written before that rule.
56 async fn board_for(id: &str, user: &User, db: &Database) -> Result<Board, AppError> {63 async fn board_for(id: &str, user: &User, db: &Database) -> Result<Board, AppError> {
57 let board = Board::read(&BoardId::from_key(id), db)64 let board = Board::read(&BoardId::from_key(id), db)
58 .await?65 .await?
59 .ok_or(AppError::NotFound)?;66 .ok_or(AppError::NotFound)?;
60- if !board.is_participant(user.get_id()) {67+ if !user.get_role().at_least(Role::Student) || !board.is_participant(user.get_id()) {
61 return Err(AppError::NotFound);68 return Err(AppError::NotFound);
62 }69 }
63 Ok(board)70 Ok(board)
@@ -80,6 +87,10 @@ fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> {
80 /// but only after this loop would have run one read per id), and an unknown id87 /// but only after this loop would have run one read per id), and an unknown id
81 /// is a 400 rather than a silently dropped invitation.88 /// is a 400 rather than a silently dropped invitation.
82 ///89 ///
90+/// A `parent` is refused here, and that is the cut that keeps the role off the
91+/// whiteboard: never on a roster means [`board_for`] and the room's door already
92+/// answer 404 on every id-scoped route, and no socket can ever open.
93+///
83 /// The creator is a participant by construction, so they are neither injected94 /// The creator is a participant by construction, so they are neither injected
84 /// into the list nor rejected from it.95 /// into the list nor rejected from it.
85 async fn resolve_participants(96 async fn resolve_participants(
@@ -101,10 +112,11 @@ async fn resolve_participants(
101 let mut users = Vec::with_capacity(ids.len());112 let mut users = Vec::with_capacity(ids.len());
102 for id in ids {113 for id in ids {
103 let user = UserId::from_key(&id);114 let user = UserId::from_key(&id);
104- if User::read(&user, db).await?.is_none() {115+ let found = User::read(&user, db).await?;
116+ if !found.is_some_and(|found| found.get_role().at_least(Role::Student)) {
105 return Err(AppError::Validation(ValidationError::Invalid {117 return Err(AppError::Validation(ValidationError::Invalid {
106 field: "participants",118 field: "participants",
107- reason: "every participant must be an existing user",119+ reason: "every participant must be an existing user of at least the student role",
108 }));120 }));
109 }121 }
110 users.push(user);122 users.push(user);
@@ -205,8 +217,10 @@ struct CreateBoard {
205 217
206 /// Open a whiteboard. The caller becomes its creator β€” the only one who may218 /// Open a whiteboard. The caller becomes its creator β€” the only one who may
207 /// clear, lock, close or delete it β€” and everyone named in `participant_ids`219 /// clear, lock, close or delete it β€” and everyone named in `participant_ids`
208-/// may draw on it. `409` once the caller holds `max_boards_per_creator` boards220+/// may draw on it. Student and above: the `parent` role has no whiteboard
209-/// (`GET /limits`); delete one to free a seat.221+/// access at all, neither as a creator nor as a participant. `409` once the
222+/// caller holds `max_boards_per_creator` boards (`GET /limits`); delete one to
223+/// free a seat.
210 #[utoipa::path(224 #[utoipa::path(
211 post,225 post,
212 path = "/",226 path = "/",
@@ -215,14 +229,15 @@ struct CreateBoard {
215 request_body = CreateBoard,229 request_body = CreateBoard,
216 responses(230 responses(
217 (status = 201, description = "The new board", body = BoardResponse),231 (status = 201, description = "The new board", body = BoardResponse),
218- (status = 400, description = "Invalid title, or a participant list that is too long or names an unknown user", body = ErrorResponse),232+ (status = 400, description = "Invalid title, or a participant list that is too long, names an unknown user, or names a parent", body = ErrorResponse),
219 (status = 401, description = "Not authenticated", body = ErrorResponse),233 (status = 401, description = "Not authenticated", body = ErrorResponse),
234+ (status = 403, description = "The caller is a parent", body = ErrorResponse),
220 (status = 409, description = "The caller already holds the maximum number of boards", body = ErrorResponse),235 (status = 409, description = "The caller already holds the maximum number of boards", body = ErrorResponse),
221 ),236 ),
222 )]237 )]
223 async fn create_board(238 async fn create_board(
224 State(st): State<AppState>,239 State(st): State<AppState>,
225- CurrentUser(user): CurrentUser,240+ RequireStudent(user): RequireStudent,
226 Json(req): Json<CreateBoard>,241 Json(req): Json<CreateBoard>,
227 ) -> Result<(StatusCode, Json<BoardResponse>), AppError> {242 ) -> Result<(StatusCode, Json<BoardResponse>), AppError> {
228 let title = BoardTitle::try_new(&req.title)?;243 let title = BoardTitle::try_new(&req.title)?;
@@ -244,11 +259,12 @@ async fn create_board(
244 (status = 200, description = "A page of the caller's boards", body = Page<BoardResponse>),259 (status = 200, description = "A page of the caller's boards", body = Page<BoardResponse>),
245 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),260 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
246 (status = 401, description = "Not authenticated", body = ErrorResponse),261 (status = 401, description = "Not authenticated", body = ErrorResponse),
262+ (status = 403, description = "The caller is a parent", body = ErrorResponse),
247 ),263 ),
248 )]264 )]
249 async fn list_boards(265 async fn list_boards(
250 State(st): State<AppState>,266 State(st): State<AppState>,
251- CurrentUser(user): CurrentUser,267+ RequireStudent(user): RequireStudent,
252 Query(page): Query<PageParams>,268 Query(page): Query<PageParams>,
253 ) -> Result<Json<Page<BoardResponse>>, AppError> {269 ) -> Result<Json<Page<BoardResponse>>, AppError> {
254 let (limit, offset) = page.resolve()?;270 let (limit, offset) = page.resolve()?;
@@ -426,7 +442,7 @@ struct UpdateBoard {
426 request_body = UpdateBoard,442 request_body = UpdateBoard,
427 responses(443 responses(
428 (status = 200, description = "The updated board", body = BoardResponse),444 (status = 200, description = "The updated board", body = BoardResponse),
429- (status = 400, description = "Invalid title, or a participant list that is too long or names an unknown user", body = ErrorResponse),445+ (status = 400, description = "Invalid title, or a participant list that is too long, names an unknown user, or names a parent", body = ErrorResponse),
430 (status = 401, description = "Not authenticated", body = ErrorResponse),446 (status = 401, description = "Not authenticated", body = ErrorResponse),
431 (status = 403, description = "Only the creator may change the participants or the lock", body = ErrorResponse),447 (status = 403, description = "Only the creator may change the participants or the lock", body = ErrorResponse),
432 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),448 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
tests/e2e.rsmodified+66 -0
@@ -2552,6 +2552,72 @@ async fn the_door_is_a_404_for_an_outsider_and_an_unknown_board() {
2552 .expect("a participant is let in");2552 .expect("a participant is let in");
2553 }2553 }
2554 2554
2555+/// Test 6b β€” the door is shut on a `parent` too, and shut the same way: a 404,
2556+/// never a 403. Proved against the hardest case β€” the parent is forced onto the
2557+/// roster in the database first, so the roster gate would let them in and only
2558+/// the role bar refuses. No socket is the whole point: a parent that cannot
2559+/// upgrade can never send a `stroke` frame, and the store proves nothing landed.
2560+#[tokio::test]
2561+async fn a_parent_cannot_enter_the_room_or_draw() {
2562+ let room = board_room_fixture().await;
2563+ let (base, board) = (&room.base, &room.board_id);
2564+ let anne = client();
2565+ register(&anne, base, "anne").await;
2566+ promote(&room.db, "anne", "parent").await;
2567+ login(&anne, base, "anne").await;
2568+ let cookie = raw_session_cookie(base, "anne").await;
2569+
2570+ // On the roster by force β€” the stale row this rule leaves behind.
2571+ let me: Value = anne
2572+ .get(format!("{base}/auth/me"))
2573+ .send()
2574+ .await
2575+ .unwrap()
2576+ .json()
2577+ .await
2578+ .unwrap();
2579+ // Beside `veli`, who stays: the two differ only by role, so the refusal
2580+ // below cannot be blamed on the roster.
2581+ room.db
2582+ .query("UPDATE $b SET participants = [$v, $u]")
2583+ .bind(("b", board_record(board)))
2584+ .bind((
2585+ "v",
2586+ surrealdb::types::RecordId::new("user", room.veli_id.clone()),
2587+ ))
2588+ .bind((
2589+ "u",
2590+ surrealdb::types::RecordId::new("user", me["id"].as_str().unwrap().to_string()),
2591+ ))
2592+ .await
2593+ .unwrap()
2594+ .check()
2595+ .unwrap();
2596+
2597+ assert_eq!(
2598+ board_open(base, board, Some(&cookie)).await.err(),
2599+ Some(404),
2600+ "a parent on the roster must still be told the board does not exist"
2601+ );
2602+ // Not a 403 anywhere: identical to a board that was never minted.
2603+ assert_eq!(
2604+ board_open(base, "01JZZZZZZZZZZZZZZZZZZZZZZZ", Some(&cookie))
2605+ .await
2606+ .err(),
2607+ Some(404)
2608+ );
2609+ // No socket, so no stroke β€” asserted against the store, not the wire.
2610+ assert!(
2611+ stored_stroke_ids(&room.db, board, 0).await.is_empty(),
2612+ "a parent must not have drawn"
2613+ );
2614+ // And the bar is about the role, not the roster: `veli` sits on the same
2615+ // roster and is let straight in.
2616+ board_open(base, board, Some(&room.veli_cookie))
2617+ .await
2618+ .expect("a student participant is still let in");
2619+}
2620+
2555 /// Test 7 β€” a participant dropped mid-session stops drawing. Twice over: once2621 /// Test 7 β€” a participant dropped mid-session stops drawing. Twice over: once
2556 /// with the roster frame deliberately withheld (the socket's own gate is what2622 /// with the roster frame deliberately withheld (the socket's own gate is what
2557 /// actually protects the board), and once through the frame the REST route2623 /// actually protects the board), and once through the frame the REST route
tests/integration.rsmodified+89 -0
@@ -24249,6 +24249,95 @@ async fn every_board_route_is_a_404_for_an_outsider() {
24249 assert_ne!(mine, board);24249 assert_ne!(mine, board);
24250 }24250 }
24251 24251
24252+/// The `parent` role has no whiteboard at all. Three cuts in one test, because
24253+/// they only work together: a parent cannot open a board, cannot be *named* on
24254+/// one, and β€” the stale-row case, forced here by writing a parent straight into
24255+/// a roster β€” still gets the outsider's `404` rather than a `403` that would
24256+/// confirm the board is there.
24257+#[tokio::test]
24258+async fn a_parent_gets_no_whiteboard_at_all() {
24259+ let (app, db) = app_and_db().await;
24260+ let ali = login(&app, "ali").await;
24261+ let anne = login_as(&app, &db, "anne", "parent").await;
24262+ let anne_id = me_id(&app, &anne).await;
24263+
24264+ // 1. A parent cannot open one. A 403, not a 404: no board exists to hide.
24265+ let res = send(
24266+ &app,
24267+ "POST",
24268+ "/boards",
24269+ Some(&anne),
24270+ Some(json!({ "title": "Gizli", "participant_ids": [] })),
24271+ )
24272+ .await;
24273+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
24274+ // And nothing was written on the way to that refusal.
24275+ assert_eq!(stored_board_count(&db, &anne_id).await, 0);
24276+
24277+ // 2. A parent cannot be named on one either β€” refused whole, so the board
24278+ // is not created half-invited.
24279+ let res = send(
24280+ &app,
24281+ "POST",
24282+ "/boards",
24283+ Some(&ali),
24284+ Some(json!({ "title": "Geometri", "participant_ids": [&anne_id] })),
24285+ )
24286+ .await;
24287+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
24288+ assert_eq!(stored_board_count(&db, &me_id(&app, &ali).await).await, 0);
24289+
24290+ // The same refusal on the way in through PATCH, on a board that does exist.
24291+ let board = create_board(&app, &ali, "Geometri", &[]).await;
24292+ let res = send(
24293+ &app,
24294+ "PATCH",
24295+ &format!("/boards/{board}"),
24296+ Some(&ali),
24297+ Some(json!({ "participants": [&anne_id] })),
24298+ )
24299+ .await;
24300+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
24301+ assert!(
24302+ stored_board(&db, &board)
24303+ .await
24304+ .unwrap()
24305+ .get_participants()
24306+ .is_empty(),
24307+ "a refused roster change must leave the old roster"
24308+ );
24309+
24310+ // 3. The stale row: a parent already on a roster, written before this rule.
24311+ // Every id-scoped route must still answer exactly like a board that was
24312+ // never minted β€” a 403 anywhere here leaks the board's existence.
24313+ db.query("UPDATE $b SET participants = [$u]")
24314+ .bind(("b", BoardId::from_key(&board).record()))
24315+ .bind(("u", UserId::from_key(&anne_id).record()))
24316+ .await
24317+ .unwrap()
24318+ .check()
24319+ .unwrap();
24320+ let ghost = board_routes("nosuchboard");
24321+ for (n, (method, uri, body)) in board_routes(&board).into_iter().enumerate() {
24322+ let res = send(&app, method, &uri, Some(&anne), body).await;
24323+ assert_eq!(
24324+ res.status,
24325+ StatusCode::NOT_FOUND,
24326+ "{method} {uri} must 404 for a parent, got {}",
24327+ res.body
24328+ );
24329+ let (gm, gu, gb) = ghost[n].clone();
24330+ let gone = send(&app, gm, &gu, Some(&anne), gb).await;
24331+ assert_eq!(res.status, gone.status, "{method} {uri}");
24332+ assert_eq!(res.body, gone.body, "{method} {uri} bodies must match too");
24333+ }
24334+ // The list route is barred outright β€” nothing to hide, so a 403 is honest.
24335+ let res = send(&app, "GET", "/boards", Some(&anne), None).await;
24336+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
24337+ // None of it disturbed the board.
24338+ assert!(stored_board(&db, &board).await.is_some());
24339+}
24340+
24252 /// The other half of the two-tier line: a participant sees the board and may24341 /// The other half of the two-tier line: a participant sees the board and may
24253 /// re-title it, but the four commands and the roster/lock arms of `PATCH` are24342 /// re-title it, but the four commands and the roster/lock arms of `PATCH` are
24254 /// the creator's alone β€” a 403, because hiding a board they are already24343 /// the creator's alone β€” a 403, because hiding a board they are already