forge
Explore
Log in

Don't you dare go Hollow

Close a whiteboard whose creator was demoted

Browse files at this commit

26e7470c6b2df9d7eec2ecf045255f1f6d4cea2fAhmet Kaan GümüşParent: 528403a
  • fix
    • close a whiteboard whose creator was demoted
Show full message
🖍️ fix: close a whiteboard whose creator was demoted

A board's creator demoted to `parent` left a room nobody could command.
The whiteboard is shut to that role outright, so the creator was answered
404 on their own board; clear, lock, close and delete are the creator's
alone, so every other participant was answered 403; and
`Board::list_for_user` is the crate's only enumeration, so no manager or
admin could so much as find the id. Meanwhile the participants kept
drawing (the room re-derives membership per frame and they still pass)
into a board only the 50 000-stroke lifetime cap could ever retire — and
`Board::delete`, the sole releaser of `board_count` and the sole deleter
of `board_stroke`, was unreachable forever.

The demotion now stamps `closed_at` on every board the account created,
in `set_role`'s own transaction and with the same compare-and-set
`Board::close` uses, so an already-closed board keeps its first stamp.
Written before the roster strip, so the strip's `RETURN AFTER` carries
the closed row the caller fans out — as a `closed` frame beside the
`participants` one, which is what turns the open sockets read-only.

Closed and not deleted: the marks are the other participants' work too,
so the board, its history and its epochs stay readable and only writes
are refused (`board_closed`, terminal). The cost is accepted — the
creator's `board_count` seat stays taken, which is correct while the row
it counts still exists, and the strokes stay on disk.

The concurrent half needs nothing: `Board::create` claims the creator's
own user row (`cap::claim_and_create` on `board_count`), the very record
this transaction writes `role` on, so a board opened while the demotion
runs collides in the store and one side re-sends — it cannot slip past
the sweep.
README.mdmodified+23 -4
@@ -611,6 +611,17 @@ own seats by hand. Seats on lists that have already closed (the event started,
611 or its `ends_at`-only deadline passed) are never touched — that roster is611 or its `ends_at`-only deadline passed) are never touched — that roster is
612 history, and re-registering is refused.612 history, and re-registering is refused.
613 613
614+A demotion to `parent` also **closes every whiteboard that account created**,
615+on top of taking it off the rosters it was invited to. The whiteboard is shut to
616+parents outright, so the creator is answered `404` on their own board; clear,
617+lock, close and delete are the creator's alone, so every other participant is
618+answered `403`; and no route lists a board the caller is not on, so not even an
619+admin can find its id. Left open it is a room nobody can end while its
620+participants keep drawing on it. Closed and not deleted, because the marks are
621+their work too: the board, its history and its epochs stay readable, only writes
622+are refused (`board_closed`), and the creator's board seat stays taken — a
623+closed board is still a stored board.
624+
614 A demotion below `teacher` additionally **withdraws the published appointment625 A demotion below `teacher` additionally **withdraws the published appointment
615 calendar** and cancels the live bookings on it. Nothing else could: a slot is626 calendar** and cancels the live bookings on it. Nothing else could: a slot is
616 listed only on its own teacher's calendar and deleted only by a teacher+, so627 listed only on its own teacher's calendar and deleted only by a teacher+, so
@@ -625,9 +636,9 @@ booking racing it collides on the slot row the sweep deletes.
625 636
626 The role write and every sweep it implies — class memberships and their637 The role write and every sweep it implies — class memberships and their
627 counters, all enrollments and their seats, parent ties on both sides, a638 counters, all enrollments and their seats, parent ties on both sides, a
628-demoted parent's still-freeable event seats, whiteboard rosters, course639+demoted parent's still-freeable event seats, whiteboard rosters and the boards
629-staffing and homeroom-teacher columns, the appointment calendar and the640+that account created, course staffing and homeroom-teacher columns, the
630-bookings on it — commit as **one transaction**. It641+appointment calendar and the bookings on it — commit as **one transaction**. It
631 either all lands or none of it does: a failure answers `500` with the account642 either all lands or none of it does: a failure answers `500` with the account
632 still holding its old role and every grant of it still standing, and the same643 still holding its old role and every grant of it still standing, and the same
633 `PATCH` retried applies the lot. Signup lists that have already frozen are644 `PATCH` retried applies the lot. Signup lists that have already frozen are
@@ -3725,7 +3736,15 @@ unknown to `POST` and `PATCH`. A read-modify-write client sends the writable
3725 fields it changed, never the whole board object back.3736 fields it changed, never the whole board object back.
3726 3737
3727 **Roster repair.** A roster only ever holds users of at least the `student`3738 **Roster repair.** A roster only ever holds users of at least the `student`
3728-role. A demotion sweeps the user off every board they were on, and the first3739+role. A demotion sweeps the user off every board they were on — and **closes
3740+every board they created**, in the same write. A creator demoted to `parent` is
3741+an outsider on their own board (`404`), while clearing, locking, closing and
3742+deleting it are theirs alone and nothing lists a board the caller is not on: the
3743+room would be commandable by nobody at all, and its participants would keep
3744+drawing on it until the lifetime cap closed it. So the demotion closes it —
3745+permanently read-only, nothing deleted, every mark and every epoch still
3746+readable to the people who drew them, and the creator's `board_count` seat still
3747+taken, because the row it counts is still there. The first
3729 boot of this version repaired the rosters an older binary left behind —3748 boot of this version repaired the rosters an older binary left behind —
3730 parents, and ids of users deleted since. On top of that, a `PATCH` may always3749 parents, and ids of users deleted since. On top of that, a `PATCH` may always
3731 send back the roster it was just served: an id already on the board that has3750 send back the roster it was just served: an id already on the board that has
src/domain/user.rsmodified+99 -5
@@ -570,8 +570,11 @@ impl User {
570 /// still are: released apart, an enrollment row could be left tagged with570 /// still are: released apart, an enrollment row could be left tagged with
571 /// a class whose counters had been given back, so the class passed its571 /// a class whose counters had been given back, so the class passed its
572 /// zero-zero delete guard and no sweep could ever reach the row again.572 /// zero-zero delete guard and no sweep could ever reach the row again.
573- /// * **Parent** additionally frees event seats and comes off every573+ /// * **Parent** additionally frees event seats, comes off every whiteboard
574- /// whiteboard roster. The seat is the one thing on a signup list nothing574+ /// roster and has the boards they *created* closed — permanently
575+ /// read-only, rows kept, because a room whose creator is demoted is
576+ /// commandable by nobody at all (see the statement's own note). The seat
577+ /// is the one thing on a signup list nothing
575 /// else could remove: staff free their own by hand (`unregister` allows578 /// else could remove: staff free their own by hand (`unregister` allows
576 /// the self case) but a parent can reach no such door, so a promotion579 /// the self case) but a parent can reach no such door, so a promotion
577 /// strands nothing and only this demotion does. A list that has already580 /// strands nothing and only this demotion does. A list that has already
@@ -599,9 +602,10 @@ impl User {
599 /// defined end available — and the alternative, deleting it, would make a602 /// defined end available — and the alternative, deleting it, would make a
600 /// confirmed meeting vanish with no trace at all.603 /// confirmed meeting vanish with no trace at all.
601 ///604 ///
602- /// The returned boards are the rooms whose roster this changed (plus those605+ /// The returned boards are the rooms whose roster this changed, plus those
603- /// the user created, which cannot be changed and are returned so their room606+ /// the user created — whose roster is untouched but which are now closed,
604- /// is prompted too). Publishing to them is the caller's job: an in-process607+ /// and they carry that stamp because the close is written first. Publishing
608+ /// to them is the caller's job: an in-process
605 /// fan-out cannot sit inside a database transaction, and a room told before609 /// fan-out cannot sit inside a database transaction, and a room told before
606 /// the commit would re-read the pre-commit state.610 /// the commit would re-read the pre-commit state.
607 ///611 ///
@@ -669,6 +673,24 @@ impl User {
669 math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \673 math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \
670 }}; }}"674 }}; }}"
671 ));675 ));
676+ // A room whose *creator* is demoted can never be ended by anyone:
677+ // the whiteboard is closed to parents outright, so the creator is
678+ // 404'd off their own board, `clear`/`lock`/`close`/`delete` are
679+ // creator-only for everyone else, and `Board::list_for_user` is the
680+ // crate's only enumeration — no manager or admin can so much as find
681+ // the id. Its participants meanwhile keep drawing (the room re-derives
682+ // membership per frame and they still pass), into a board only the
683+ // 50 000-stroke lifetime cap could ever retire. So the demotion
684+ // retires it, with the same compare-and-set [`Board::close`] uses: an
685+ // already-closed board keeps its first stamp. Closed and not deleted
686+ // because the marks are the participants' work too — they keep reading
687+ // the board and its whole history, and the creator's `board_count`
688+ // seat stays taken, which is correct while the row it counts exists.
689+ // Stamped *before* the roster strip so the strip's `RETURN AFTER`
690+ // carries the closed row the caller fans out.
691+ batch.push(format!(
692+ "UPDATE {BOARD_TABLE} SET closed_at = $now WHERE creator = $usr AND closed_at = NONE"
693+ ));
672 board_slot = Some(batch.len());694 board_slot = Some(batch.len());
673 batch.push(format!(695 batch.push(format!(
674 "UPDATE {BOARD_TABLE} SET participants -= $usr \696 "UPDATE {BOARD_TABLE} SET participants -= $usr \
@@ -911,6 +933,78 @@ mod tests {
911 );933 );
912 }934 }
913 935
936+ /// The half the roster strip cannot reach: the board's **creator**. Demoted,
937+ /// they are 404'd off their own room, every command on it is creator-only
938+ /// for everyone else, and nothing in the crate lists a board a caller is not
939+ /// on — so the room could be cleared, locked, closed and deleted by nobody
940+ /// while its participants kept drawing on it. The demotion closes it, and
941+ /// closing is *all* it does: the roster, the row and every mark stay
942+ /// readable.
943+ #[tokio::test]
944+ async fn a_demoted_creator_s_board_is_closed_and_still_readable() {
945+ use crate::domain::board::{Board, BoardTitle};
946+ use crate::domain::board_stroke::{BOARD_CLOSED, BoardStroke};
947+
948+ let db = init_mem().await.unwrap();
949+ let creator = a_user("ogretmen", &db).await;
950+ let guest = a_user("ogrenci", &db).await;
951+ let board = Board::create(
952+ creator.get_id(),
953+ BoardTitle::try_new("Geometri").unwrap(),
954+ vec![guest.get_id().clone()],
955+ &db,
956+ )
957+ .await
958+ .unwrap();
959+ let mark = |epoch| {
960+ let (id, author, db) = (board.get_id().clone(), guest.get_id().clone(), db.clone());
961+ async move { BoardStroke::append(&id, &author, "{\"p\":[1]}", epoch, &db).await }
962+ };
963+ mark(0).await.unwrap();
964+
965+ let (creator, boards) = creator.set_role(Role::Parent, &db).await.unwrap();
966+ assert_eq!(boards.len(), 1, "the room must be reported back");
967+ let stamp = boards[0]
968+ .get_closed_at()
969+ .expect("and carry the closing stamp the room is told about");
970+
971+ // Stored, not merely reported — and nothing else moved.
972+ let stored = Board::read(board.get_id(), &db).await.unwrap().unwrap();
973+ assert_eq!(stored.get_closed_at(), Some(stamp));
974+ assert_eq!(
975+ stored.get_participants(),
976+ [guest.get_id().clone()],
977+ "closing must not empty the roster it did not touch"
978+ );
979+ assert_eq!(
980+ BoardStroke::history(board.get_id(), None, false, None, 0, &db)
981+ .await
982+ .unwrap()
983+ .1,
984+ 1,
985+ "the marks the participants drew stay on disk"
986+ );
987+
988+ // Read-only for the participants who are still on it.
989+ assert!(
990+ matches!(mark(0).await, Err(AppError::Conflict(BOARD_CLOSED))),
991+ "a closed board must refuse every write with the terminal answer"
992+ );
993+
994+ // The stamp is the record: a re-run of the sweep must not move it.
995+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;
996+ creator.set_role(Role::Parent, &db).await.unwrap();
997+ assert_eq!(
998+ Board::read(board.get_id(), &db)
999+ .await
1000+ .unwrap()
1001+ .unwrap()
1002+ .get_closed_at(),
1003+ Some(stamp),
1004+ "the close is a compare-and-set, not a re-stamp"
1005+ );
1006+ }
1007+
914 /// A demotion below `teacher` must take the published calendar with it and1008 /// A demotion below `teacher` must take the published calendar with it and
915 /// settle the bookings on it. Nothing else can: a slot is listed only on its1009 /// settle the bookings on it. Nothing else can: a slot is listed only on its
916 /// own teacher's calendar (and hidden from every other reader once its owner1010 /// own teacher's calendar (and hidden from every other reader once its owner
src/lib.rsmodified+1 -1
@@ -64,7 +64,7 @@ use crate::state::AppState;
64 (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 a slot with no serving minute carries **no cutoff at all** rather than one counted from midnight) — 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. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"),64 (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 a slot with no serving minute carries **no cutoff at all** rather than one counted from midnight) — 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. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"),
65 (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 = "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"),
66 (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), and the ones it does name get its `assigned` list narrowed to their own id — who else was assigned is roster information, and the roster is teacher+-only; a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"),66 (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), and the ones it does name get its `assigned` list narrowed to their own id — who else was assigned is roster information, and the roster is teacher+-only; a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"),
67- (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. `GET /boards` takes `?open=true|false` to narrow the list by the closing stamp (`total` counts the filtered list) — a closed board is never deleted, so this is how a creator holding many boards trims the retired ones out of sight. It filters `closed_at` and nothing else: a **locked** board, and one that has spent its lifetime stroke budget but was never drawn on again, are both still open, because the stamp is written only by `/close` or by the append the lifetime cap refuses. 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. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there — taken off the roster, or demoted below `student` — is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion below `student` also sweeps that account off every roster it was on, and the rosters an older binary left behind were repaired at boot: a board written before that sweep can name a parent, or a user since deleted, and every such id is stripped the first time this binary starts. A board whose *creator* was demoted is left standing — barred to them, unchanged for everyone else. 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 — drawn marks only, never a `clear` marker, exactly as the room's socket replays it, so the REST catch-up and the live canvas can never disagree, `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board and the **locked** one — the pause the creator set holds against their own clear too, so a locked board sitting at `max_epoch_strokes` is recovered by unlock, clear, relock — since the marker is a stored row charged to the lifetime cap), 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 — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — 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. Closing and locking are independent, and a board holding both flags answers **closed** everywhere — a stroke, a socket `clear` and `POST /boards/{id}/clear` all report the terminal state, never the pause, because the pause can never lift. `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). `POST /boards/{id}/invite` fills that roster from a group that already exists rather than one id at a time — `{kind:\"class\", class}` for a class section (şube), `{kind:\"course\", course}` for a course's enrolled students (clubs and study groups *are* courses, so this is how a whole club is invited), `{kind:\"event\", event}` for an event's expected-attendee roster exactly as `GET /events/{id}/roster` resolves it. It is the creator's alone and strictly **additive** — nothing is ever removed by it, removal stays `PATCH` — and it resolves **once**, at the call: a board holds a flat list of ids and no memory of where they came from, so a student who joins that class tomorrow is not on today's board, and re-inviting the same source is how a roster is topped up (idempotent when nothing changed). Ineligible members are dropped silently rather than failing the call for everyone else — ids that no longer resolve to a user, and anyone below `student`, which is the same cut that keeps `parent` off a whiteboard — but the participant cap is **all-or-nothing**: an invite that would carry the board past `max_participants` is refused with a `409` naming both numbers, and nobody is added. Since a board's roster is visible to every participant, inviting a group *discloses* that group's membership, so each source carries the gate its own listing route already carries: teacher+ for a class, the course's creator/assigned teacher/manager+ for a course, teacher+ for an event. A student may still build a board one id at a time; they cannot pour a class roster into one. 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 = "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. `GET /boards` takes `?open=true|false` to narrow the list by the closing stamp (`total` counts the filtered list) — a closed board is never deleted, so this is how a creator holding many boards trims the retired ones out of sight. It filters `closed_at` and nothing else: a **locked** board, and one that has spent its lifetime stroke budget but was never drawn on again, are both still open, because the stamp is written only by `/close` or by the append the lifetime cap refuses. 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. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there — taken off the roster, or demoted below `student` — is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion below `student` also sweeps that account off every roster it was on, and the rosters an older binary left behind were repaired at boot: a board written before that sweep can name a parent, or a user since deleted, and every such id is stripped the first time this binary starts. A board whose *creator* was demoted is **closed** by that same write: barred to them, still fully readable to everyone else, and refusing every write with the terminal `board_closed` — because clearing, locking, closing and deleting are the creator's alone and nothing lists a board the caller is not on, so a room whose creator was demoted could be ended by nobody at all while its participants kept drawing on it. Nothing is deleted (the marks are the participants' work too) and the seat it holds on `max_boards_per_creator` stays taken, exactly as a manually closed board's does. 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 — drawn marks only, never a `clear` marker, exactly as the room's socket replays it, so the REST catch-up and the live canvas can never disagree, `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board and the **locked** one — the pause the creator set holds against their own clear too, so a locked board sitting at `max_epoch_strokes` is recovered by unlock, clear, relock — since the marker is a stored row charged to the lifetime cap), 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 — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — 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. Closing and locking are independent, and a board holding both flags answers **closed** everywhere — a stroke, a socket `clear` and `POST /boards/{id}/clear` all report the terminal state, never the pause, because the pause can never lift. `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). `POST /boards/{id}/invite` fills that roster from a group that already exists rather than one id at a time — `{kind:\"class\", class}` for a class section (şube), `{kind:\"course\", course}` for a course's enrolled students (clubs and study groups *are* courses, so this is how a whole club is invited), `{kind:\"event\", event}` for an event's expected-attendee roster exactly as `GET /events/{id}/roster` resolves it. It is the creator's alone and strictly **additive** — nothing is ever removed by it, removal stays `PATCH` — and it resolves **once**, at the call: a board holds a flat list of ids and no memory of where they came from, so a student who joins that class tomorrow is not on today's board, and re-inviting the same source is how a roster is topped up (idempotent when nothing changed). Ineligible members are dropped silently rather than failing the call for everyone else — ids that no longer resolve to a user, and anyone below `student`, which is the same cut that keeps `parent` off a whiteboard — but the participant cap is **all-or-nothing**: an invite that would carry the board past `max_participants` is refused with a `409` naming both numbers, and nobody is added. Since a board's roster is visible to every participant, inviting a group *discloses* that group's membership, so each source carries the gate its own listing route already carries: teacher+ for a class, the course's creator/assigned teacher/manager+ for a course, teacher+ for an event. A student may still build a board one id at a time; they cannot pour a class roster into one. 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"),
68 (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) — unlink them first. Read: any authenticated user; edit: manager+"),68 (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) — unlink them first. Read: any authenticated user; edit: manager+"),
69 ),69 ),
70 )]70 )]
src/web/users.rsmodified+19 -4
@@ -420,7 +420,13 @@ async fn update_user_preferences(
420 /// Demoting to `parent` additionally gives back the seats they hold on420 /// Demoting to `parent` additionally gives back the seats they hold on
421 /// still-open event signup lists: a parent can no longer free them, and nobody421 /// still-open event signup lists: a parent can no longer free them, and nobody
422 /// else may. Seats on lists that have already closed stay as they are — that422 /// else may. Seats on lists that have already closed stay as they are — that
423-/// roster is history.423+/// roster is history. It also takes the account off every whiteboard roster and
424+/// **closes every board it created** — permanently read-only, nothing deleted.
425+/// A demoted creator is a `404` on their own board, the four commands that could
426+/// end it are the creator's alone, and no route lists a board the caller is not
427+/// on, so the room would otherwise be commandable by nobody while its
428+/// participants kept drawing on it. Closed, they keep reading the board, its
429+/// history and its epochs; only writes are refused.
424 #[utoipa::path(430 #[utoipa::path(
425 patch,431 patch,
426 path = "/{id}/role",432 path = "/{id}/role",
@@ -459,9 +465,12 @@ async fn set_role(
459 // ([`super::undo_if_demoted`]), so a demotion racing an assignment is caught465 // ([`super::undo_if_demoted`]), so a demotion racing an assignment is caught
460 // by whichever side is second.466 // by whichever side is second.
461 let (updated, boards) = user.set_role(role, &st.db).await?;467 let (updated, boards) = user.set_role(role, &st.db).await?;
462- // Whiteboard rooms whose roster the commit above changed, prompted with the468+ // Whiteboard rooms the commit above changed, prompted with the same frames
463- // same `participants` frame the roster PATCH publishes — after the commit,469+ // their own routes publish — after the commit, because the room re-reads the
464- // because the room re-reads the database before it acts on the frame.470+ // database before it acts on a frame. A room whose creator was demoted is
471+ // now closed, and its `closed` frame is what turns the open sockets
472+ // read-only; told only about the roster, they would draw on until each
473+ // stroke came back refused.
465 for board in boards {474 for board in boards {
466 st.board_hub.publish(475 st.board_hub.publish(
467 board.get_id().key(),476 board.get_id().key(),
@@ -476,6 +485,12 @@ async fn set_role(
476 })485 })
477 .to_string(),486 .to_string(),
478 );487 );
488+ if let Some(closed_at) = board.get_closed_at() {
489+ st.board_hub.publish(
490+ board.get_id().key(),
491+ json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(),
492+ );
493+ }
479 }494 }
480 Ok(Json(UserResponse::new(&updated)))495 Ok(Json(UserResponse::new(&updated)))
481 }496 }
tests/integration.rsmodified+72 -0
@@ -25418,6 +25418,78 @@ async fn the_lifetime_cap_closes_the_board_and_it_stays_readable() {
25418 );25418 );
25419 }25419 }
25420 25420
25421+/// Demoting a board's **creator** to `parent` closes the room, and closes it
25422+/// through the ordinary role route. Without that the board is commandable by
25423+/// nobody: the ex-creator is 404'd off their own board (the whiteboard is shut
25424+/// to parents), clear/lock/close/delete are creator-only for everyone else, and
25425+/// no route lists a board the caller is not on — so not even an admin can find
25426+/// the id, while the participants keep drawing on it. Closed and not deleted:
25427+/// every read the board ever served, it still serves.
25428+#[tokio::test]
25429+async fn demoting_a_board_s_creator_closes_the_room_and_keeps_it_readable() {
25430+ let (app, db) = app_and_db().await;
25431+ let admin = login_as(&app, &db, "yonetici", "admin").await;
25432+ let ali = login(&app, "ali").await;
25433+ let ali_id = me_id(&app, &ali).await;
25434+ let veli = login(&app, "veli").await;
25435+ let veli_id = me_id(&app, &veli).await;
25436+ let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await;
25437+ draw(&db, &board, &veli_id, 0, "{\"p\":[1]}").await.unwrap();
25438+
25439+ let res = send(
25440+ &app,
25441+ "PATCH",
25442+ &format!("/users/{ali_id}/role"),
25443+ Some(&admin),
25444+ Some(json!({ "role": "parent" })),
25445+ )
25446+ .await;
25447+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
25448+
25449+ let stamp = stored_board(&db, &board)
25450+ .await
25451+ .unwrap()
25452+ .get_closed_at()
25453+ .expect("the demotion must close the room its creator can no longer command");
25454+ // The seat stays taken: the row it counts still exists.
25455+ assert_eq!(stored_board_count(&db, &ali_id).await, 1);
25456+
25457+ // The participant still reads everything, and their marks are still there.
25458+ let res = send(&app, "GET", &format!("/boards/{board}"), Some(&veli), None).await;
25459+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
25460+ assert_eq!(res.body["closed_at"], stamp.as_millis());
25461+ let res = send(
25462+ &app,
25463+ "GET",
25464+ &format!("/boards/{board}/history"),
25465+ Some(&veli),
25466+ None,
25467+ )
25468+ .await;
25469+ assert_eq!(common::total(&res.body), 1, "the whole log is still served");
25470+ assert_eq!(stroke_rows(&db, &board).await.len(), 1);
25471+ let res = send(&app, "GET", "/boards", Some(&veli), None).await;
25472+ assert_eq!(common::total(&res.body), 1, "and it is still listed");
25473+
25474+ // But every write answers the terminal refusal, not the recoverable one.
25475+ let refused = draw(&db, &board, &veli_id, 0, "{\"p\":[2]}").await;
25476+ assert!(
25477+ matches!(
25478+ refused,
25479+ Err(hezarfen_backend::error::AppError::Conflict(
25480+ hezarfen_backend::domain::board_stroke::BOARD_CLOSED
25481+ ))
25482+ ),
25483+ "a closed board must refuse a stroke as closed, got {refused:?}"
25484+ );
25485+ assert_eq!(stroke_rows(&db, &board).await.len(), 1, "nothing written");
25486+
25487+ // The ex-creator is out of their own room, which is the shape that made
25488+ // this uncommandable in the first place.
25489+ let res = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await;
25490+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
25491+}
25492+
25421 /// The per-creator cap, asserted on the stored counter — and a delete really25493 /// The per-creator cap, asserted on the stored counter — and a delete really
25422 /// hands the seat back, or a busy teacher's limit ratchets shut forever.25494 /// hands the seat back, or a busy teacher's limit ratchets shut forever.
25423 #[tokio::test]25495 #[tokio::test]