diff --git a/README.md b/README.md index c1b832d..31537b0 100644 --- a/README.md +++ b/README.md @@ -611,6 +611,17 @@ own seats by hand. Seats on lists that have already closed (the event started, or its `ends_at`-only deadline passed) are never touched — that roster is history, and re-registering is refused. +A demotion to `parent` also **closes every whiteboard that account created**, +on top of taking it off the rosters it was invited to. The whiteboard is shut to +parents outright, so the creator is answered `404` on their own board; clear, +lock, close and delete are the creator's alone, so every other participant is +answered `403`; and no route lists a board the caller is not on, so not even an +admin can find its id. Left open it is a room nobody can end while its +participants keep drawing on it. Closed and not deleted, because the marks are +their work too: the board, its history and its epochs stay readable, only writes +are refused (`board_closed`), and the creator's board seat stays taken — a +closed board is still a stored board. + A demotion below `teacher` additionally **withdraws the published appointment calendar** and cancels the live bookings on it. Nothing else could: a slot is 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. The role write and every sweep it implies — class memberships and their counters, all enrollments and their seats, parent ties on both sides, a -demoted parent's still-freeable event seats, whiteboard rosters, course -staffing and homeroom-teacher columns, the appointment calendar and the -bookings on it — commit as **one transaction**. It +demoted parent's still-freeable event seats, whiteboard rosters and the boards +that account created, course staffing and homeroom-teacher columns, the +appointment calendar and the bookings on it — commit as **one transaction**. It either all lands or none of it does: a failure answers `500` with the account still holding its old role and every grant of it still standing, and the same `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 fields it changed, never the whole board object back. **Roster repair.** A roster only ever holds users of at least the `student` -role. A demotion sweeps the user off every board they were on, and the first +role. A demotion sweeps the user off every board they were on — and **closes +every board they created**, in the same write. A creator demoted to `parent` is +an outsider on their own board (`404`), while clearing, locking, closing and +deleting it are theirs alone and nothing lists a board the caller is not on: the +room would be commandable by nobody at all, and its participants would keep +drawing on it until the lifetime cap closed it. So the demotion closes it — +permanently read-only, nothing deleted, every mark and every epoch still +readable to the people who drew them, and the creator's `board_count` seat still +taken, because the row it counts is still there. The first boot of this version repaired the rosters an older binary left behind — parents, and ids of users deleted since. On top of that, a `PATCH` may always send back the roster it was just served: an id already on the board that has diff --git a/src/domain/user.rs b/src/domain/user.rs index d3071b9..c0b266e 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -570,8 +570,11 @@ impl User { /// still are: released apart, an enrollment row could be left tagged with /// a class whose counters had been given back, so the class passed its /// zero-zero delete guard and no sweep could ever reach the row again. - /// * **Parent** additionally frees event seats and comes off every - /// whiteboard roster. The seat is the one thing on a signup list nothing + /// * **Parent** additionally frees event seats, comes off every whiteboard + /// roster and has the boards they *created* closed — permanently + /// read-only, rows kept, because a room whose creator is demoted is + /// commandable by nobody at all (see the statement's own note). The seat + /// is the one thing on a signup list nothing /// else could remove: staff free their own by hand (`unregister` allows /// the self case) but a parent can reach no such door, so a promotion /// strands nothing and only this demotion does. A list that has already @@ -599,9 +602,10 @@ impl User { /// defined end available — and the alternative, deleting it, would make a /// confirmed meeting vanish with no trace at all. /// - /// The returned boards are the rooms whose roster this changed (plus those - /// the user created, which cannot be changed and are returned so their room - /// is prompted too). Publishing to them is the caller's job: an in-process + /// The returned boards are the rooms whose roster this changed, plus those + /// the user created — whose roster is untouched but which are now closed, + /// and they carry that stamp because the close is written first. Publishing + /// to them is the caller's job: an in-process /// fan-out cannot sit inside a database transaction, and a room told before /// the commit would re-read the pre-commit state. /// @@ -669,6 +673,24 @@ impl User { math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \ }}; }}" )); + // A room whose *creator* is demoted can never be ended by anyone: + // the whiteboard is closed to parents outright, so the creator is + // 404'd off their own board, `clear`/`lock`/`close`/`delete` are + // creator-only for everyone else, and `Board::list_for_user` is the + // crate's only enumeration — no manager or admin can so much as find + // the id. Its participants meanwhile keep 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. So the demotion + // retires it, with the same compare-and-set [`Board::close`] uses: an + // already-closed board keeps its first stamp. Closed and not deleted + // because the marks are the participants' work too — they keep reading + // the board and its whole history, and the creator's `board_count` + // seat stays taken, which is correct while the row it counts exists. + // Stamped *before* the roster strip so the strip's `RETURN AFTER` + // carries the closed row the caller fans out. + batch.push(format!( + "UPDATE {BOARD_TABLE} SET closed_at = $now WHERE creator = $usr AND closed_at = NONE" + )); board_slot = Some(batch.len()); batch.push(format!( "UPDATE {BOARD_TABLE} SET participants -= $usr \ @@ -911,6 +933,78 @@ mod tests { ); } + /// The half the roster strip cannot reach: the board's **creator**. Demoted, + /// they are 404'd off their own room, every command on it is creator-only + /// for everyone else, and nothing in the crate lists a board a caller is not + /// on — so the room could be cleared, locked, closed and deleted by nobody + /// while its participants kept drawing on it. The demotion closes it, and + /// closing is *all* it does: the roster, the row and every mark stay + /// readable. + #[tokio::test] + async fn a_demoted_creator_s_board_is_closed_and_still_readable() { + use crate::domain::board::{Board, BoardTitle}; + use crate::domain::board_stroke::{BOARD_CLOSED, BoardStroke}; + + let db = init_mem().await.unwrap(); + let creator = a_user("ogretmen", &db).await; + let guest = a_user("ogrenci", &db).await; + let board = Board::create( + creator.get_id(), + BoardTitle::try_new("Geometri").unwrap(), + vec![guest.get_id().clone()], + &db, + ) + .await + .unwrap(); + let mark = |epoch| { + let (id, author, db) = (board.get_id().clone(), guest.get_id().clone(), db.clone()); + async move { BoardStroke::append(&id, &author, "{\"p\":[1]}", epoch, &db).await } + }; + mark(0).await.unwrap(); + + let (creator, boards) = creator.set_role(Role::Parent, &db).await.unwrap(); + assert_eq!(boards.len(), 1, "the room must be reported back"); + let stamp = boards[0] + .get_closed_at() + .expect("and carry the closing stamp the room is told about"); + + // Stored, not merely reported — and nothing else moved. + let stored = Board::read(board.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(stored.get_closed_at(), Some(stamp)); + assert_eq!( + stored.get_participants(), + [guest.get_id().clone()], + "closing must not empty the roster it did not touch" + ); + assert_eq!( + BoardStroke::history(board.get_id(), None, false, None, 0, &db) + .await + .unwrap() + .1, + 1, + "the marks the participants drew stay on disk" + ); + + // Read-only for the participants who are still on it. + assert!( + matches!(mark(0).await, Err(AppError::Conflict(BOARD_CLOSED))), + "a closed board must refuse every write with the terminal answer" + ); + + // The stamp is the record: a re-run of the sweep must not move it. + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + creator.set_role(Role::Parent, &db).await.unwrap(); + assert_eq!( + Board::read(board.get_id(), &db) + .await + .unwrap() + .unwrap() + .get_closed_at(), + Some(stamp), + "the close is a compare-and-set, not a re-stamp" + ); + } + /// A demotion below `teacher` must take the published calendar with it and /// settle the bookings on it. Nothing else can: a slot is listed only on its /// own teacher's calendar (and hidden from every other reader once its owner diff --git a/src/lib.rs b/src/lib.rs index f00ceaf..4a87fe9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -64,7 +64,7 @@ use crate::state::AppState; (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+"), (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"), (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"), - (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"), + (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"), (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+"), ), )] diff --git a/src/web/users.rs b/src/web/users.rs index 50f216c..a03c327 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -420,7 +420,13 @@ async fn update_user_preferences( /// Demoting to `parent` additionally gives back the seats they hold on /// still-open event signup lists: a parent can no longer free them, and nobody /// else may. Seats on lists that have already closed stay as they are — that -/// roster is history. +/// roster is history. It also takes the account off every whiteboard roster and +/// **closes every board it created** — permanently read-only, nothing deleted. +/// A demoted creator is a `404` on their own board, the four commands that could +/// end it are the creator's alone, and no route lists a board the caller is not +/// on, so the room would otherwise be commandable by nobody while its +/// participants kept drawing on it. Closed, they keep reading the board, its +/// history and its epochs; only writes are refused. #[utoipa::path( patch, path = "/{id}/role", @@ -459,9 +465,12 @@ async fn set_role( // ([`super::undo_if_demoted`]), so a demotion racing an assignment is caught // by whichever side is second. let (updated, boards) = user.set_role(role, &st.db).await?; - // Whiteboard rooms whose roster the commit above changed, prompted with the - // same `participants` frame the roster PATCH publishes — after the commit, - // because the room re-reads the database before it acts on the frame. + // Whiteboard rooms the commit above changed, prompted with the same frames + // their own routes publish — after the commit, because the room re-reads the + // database before it acts on a frame. A room whose creator was demoted is + // now closed, and its `closed` frame is what turns the open sockets + // read-only; told only about the roster, they would draw on until each + // stroke came back refused. for board in boards { st.board_hub.publish( board.get_id().key(), @@ -476,6 +485,12 @@ async fn set_role( }) .to_string(), ); + if let Some(closed_at) = board.get_closed_at() { + st.board_hub.publish( + board.get_id().key(), + json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(), + ); + } } Ok(Json(UserResponse::new(&updated))) } diff --git a/tests/integration.rs b/tests/integration.rs index 38bd2e4..4015e28 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -25418,6 +25418,78 @@ async fn the_lifetime_cap_closes_the_board_and_it_stays_readable() { ); } +/// Demoting a board's **creator** to `parent` closes the room, and closes it +/// through the ordinary role route. Without that the board is commandable by +/// nobody: the ex-creator is 404'd off their own board (the whiteboard is shut +/// to parents), clear/lock/close/delete are creator-only for everyone else, and +/// no route lists a board the caller is not on — so not even an admin can find +/// the id, while the participants keep drawing on it. Closed and not deleted: +/// every read the board ever served, it still serves. +#[tokio::test] +async fn demoting_a_board_s_creator_closes_the_room_and_keeps_it_readable() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "yonetici", "admin").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + let veli = login(&app, "veli").await; + let veli_id = me_id(&app, &veli).await; + let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await; + draw(&db, &board, &veli_id, 0, "{\"p\":[1]}").await.unwrap(); + + let res = send( + &app, + "PATCH", + &format!("/users/{ali_id}/role"), + Some(&admin), + Some(json!({ "role": "parent" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let stamp = stored_board(&db, &board) + .await + .unwrap() + .get_closed_at() + .expect("the demotion must close the room its creator can no longer command"); + // The seat stays taken: the row it counts still exists. + assert_eq!(stored_board_count(&db, &ali_id).await, 1); + + // The participant still reads everything, and their marks are still there. + let res = send(&app, "GET", &format!("/boards/{board}"), Some(&veli), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["closed_at"], stamp.as_millis()); + let res = send( + &app, + "GET", + &format!("/boards/{board}/history"), + Some(&veli), + None, + ) + .await; + assert_eq!(common::total(&res.body), 1, "the whole log is still served"); + assert_eq!(stroke_rows(&db, &board).await.len(), 1); + let res = send(&app, "GET", "/boards", Some(&veli), None).await; + assert_eq!(common::total(&res.body), 1, "and it is still listed"); + + // But every write answers the terminal refusal, not the recoverable one. + let refused = draw(&db, &board, &veli_id, 0, "{\"p\":[2]}").await; + assert!( + matches!( + refused, + Err(hezarfen_backend::error::AppError::Conflict( + hezarfen_backend::domain::board_stroke::BOARD_CLOSED + )) + ), + "a closed board must refuse a stroke as closed, got {refused:?}" + ); + assert_eq!(stroke_rows(&db, &board).await.len(), 1, "nothing written"); + + // The ex-creator is out of their own room, which is the shape that made + // this uncommandable in the first place. + let res = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); +} + /// The per-creator cap, asserted on the stored counter — and a delete really /// hands the seat back, or a busy teacher's limit ratchets shut forever. #[tokio::test]