diff --git a/README.md b/README.md index 7acba11..61c8c8c 100644 --- a/README.md +++ b/README.md @@ -343,7 +343,7 @@ response in the same commit. "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 }, "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200, "min_max_message_len": 100, "…": 0 }, - "board": { "max_title_len": 200, "max_participants": 50, + "board": { "max_title_len": 200, "max_participants": 200, "max_stroke_payload_len": 4096, "max_epoch_strokes": 5000, "max_board_strokes": 50000, "max_boards_per_creator": 200, @@ -972,6 +972,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included · `?epoch=` for one epoch · paged | | GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) · paged | | PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` — re-title (any participant); the roster and the lock are the creator's alone (`403`) | +| POST | `/boards/{id}/invite` | teacher | **Creator only**, additive: fill the roster from a group — `{kind:"class", class}`, `{kind:"course", course}` (a club is a course), `{kind:"event", event}`. Resolved once, never live; `409` all-or-nothing at `max_participants` | | POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap — nothing is deleted; `409` on a closed board, on a **locked** board, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) | | POST | `/boards/{id}/close` | student | **Creator only**: retire the board — permanently read-only, still fully readable; idempotent, and there is no reopen | | DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats | @@ -2979,9 +2980,12 @@ context without either end having to be redeployed in lockstep. A board is a shared canvas whose membership is an **ad-hoc invite list**: the creator names participant user ids at `POST /boards` and that is the whole -model — no course, no lesson session, no appointment. Any account from -`student` upwards may open one. **Every participant draws; the creator -alone clears, locks, closes or deletes.** +model — no course, no lesson session, no appointment binds a board. Any account +from `student` upwards may open one. **Every participant draws; the creator +alone clears, locks, closes or deletes.** A teacher who does not want to type +thirty ids fills the same list in one call with `POST /boards/{id}/invite` +(below) — that is a bulk *write* into the ad-hoc list, not a binding: the board +still owns its roster afterwards. The roster is spelled `participants` everywhere — in the `POST` body, in the `PATCH` body and in every board response — so the field never changes name @@ -3005,6 +3009,62 @@ read-modify-write never wedges on a value the server itself handed over. Naming a *new* id that is unknown or a parent is still a `400`, and the whole call is refused — the roster is never half-applied. +**Bulk invite.** `POST /boards/{id}/invite` fills the roster from a group that +already exists instead of one id at a time. The body is tagged by `kind`, the +same wire shape an event audience uses: + +```json +{ "kind": "class", "class": "01J…" } // everyone in a class section (şube) +{ "kind": "course", "course": "01J…" } // everyone enrolled in a course +{ "kind": "event", "event": "01J…" } // the event's expected-attendee roster +``` + +A **club is a course** (`kind` `club`), so "invite the whole club" is the +`course` form; so is a study group (`study`). The `event` form resolves exactly +what `GET /events/{id}/roster` resolves, which is the signup list for a +registration event and the class or course roster for the others — a +school-wide or role-wide event will normally overflow the cap, and that is a +`409` rather than a truncation. + +It is the creator's call and **additive**: everyone the source names is *added*, +nobody is ever removed by it. Removal stays `PATCH /boards/{id}` — send the +roster you want. + +**The ids are resolved once, at the call — this is a snapshot, not a +subscription.** A board keeps 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 nothing the class does afterwards puts back a student the creator took off. +Re-inviting the same source is how a board is topped up after the class changed; +it adds only who is missing, so it is idempotent when nothing did — and it is +also the one thing that undoes a removal, because the source still names that +student. Removing someone from a board you intend to re-invite the class to is +therefore not a ban; there is no per-board exclusion list. Live resolution was the alternative and +was rejected here: it would turn the permission check behind every stroke, the +room's door and "which boards may I open" into cross-table queries, and it would +take the per-person removal away from the creator — which is most of what a +whiteboard roster is for. + +Three filters run before the ids land, and all three are **silent**, because one +ineligible member must not fail the invite for the other twenty-nine: ids that +no longer resolve to a user are dropped, anyone below `student` is dropped (the +same cut that keeps `parent` off a whiteboard), and anyone already on the board +— the creator included — is not added twice. + +The cap, though, is **all-or-nothing**: if the union would carry the board past +`max_participants` the whole invite is refused with a `409` naming both numbers +and the roster is left exactly as it was. A partial invite would silently pick +which half of a class gets to draw. + +**Inviting a group discloses that group.** A board's roster is visible to every +participant, so each source carries the gate its own listing route carries — +teacher+ for a class (`GET /classes/{id}/members`), the course's creator, an +assigned teacher or a manager+ for a course (`GET /courses/{id}/enrollments`), +teacher+ for an event (`GET /events/{id}/roster`). A student may still build a +board one id at a time; they cannot pour a class roster into one. A source that +does not exist is a `400` naming the field, never a `404` — on these routes a +`404` means "no such board, or not yours", and reusing it here would tell a +creator their own board had vanished. + **No parents, anywhere.** The `parent` role is the school's read-only observer, and it has no whiteboard access at all — not a view-only tier, none. It is refused `POST /boards` and `GET /boards` with a `403`, and it cannot be *named* diff --git a/src/constant.rs b/src/constant.rs index 104f78f..e6868da 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -299,10 +299,16 @@ pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200; pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64; /// Bounds on a whiteboard: its title, and how many people the creator may name -/// onto it. Fifty is a class and its teachers, not the school; every +/// onto it. Two hundred is a big club or a whole grade, not the school; every /// participant may draw, so this is also what bounds one board's writer count. +/// +/// It was fifty while a roster could only be typed one id at a time. Bulk +/// invite (`POST /boards/{id}/invite`) resolves a class section, a course or an +/// event's roster in one call, and fifty refused an ordinary club — so the +/// ceiling moved to the size of the largest group a school actually puts on one +/// canvas. Raising it can only widen what an existing row is allowed to hold. pub const MAX_BOARD_TITLE_LEN: usize = 200; -pub const MAX_BOARD_PARTICIPANTS: usize = 50; +pub const MAX_BOARD_PARTICIPANTS: usize = 200; /// Ceiling on one stroke's serialized payload. A stroke is a short path — a /// handful of points, a colour, a width — and it is stored verbatim and fanned diff --git a/src/lib.rs b/src/lib.rs index 25ebe38..dcf3449 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 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. 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); 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. `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"), + (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. `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/boards.rs b/src/web/boards.rs index 1b0c512..581bc0b 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -31,11 +31,17 @@ use crate::constant::MAX_BOARD_PARTICIPANTS; use crate::database::Database; use crate::domain::board::{Board, BoardId, BoardTitle}; use crate::domain::board_stroke::BoardStroke; +use crate::domain::class_group::{ClassGroup, ClassGroupId}; +use crate::domain::class_member::ClassMember; +use crate::domain::course::{Course, CourseId}; +use crate::domain::enrollment::Enrollment; +use crate::domain::event::{Event, EventId}; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; +use super::courses::can_manage_course; use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear}; pub fn routes() -> OpenApiRouter { @@ -51,6 +57,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(list_epochs)) .routes(routes!(clear_board)) .routes(routes!(close_board)) + .routes(routes!(invite_board)) } /// The board, or a 404 — including the deliberate 404 for a caller who is not @@ -83,9 +90,16 @@ fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> { } /// The invite list off the wire: deduped, capped, and every id resolved against -/// a real user. The cap is applied *before* the lookups (the domain caps too, -/// but only after this loop would have run one read per id), and an unknown id -/// is a 400 rather than a silently dropped invitation. +/// a real user. The cap is applied *before* the lookup (the domain caps too, but +/// only after the read would already have run), and an unknown id is a 400 +/// rather than a silently dropped invitation. +/// +/// The eligible set is fetched in **one** read, not one per id. That was a +/// per-id loop while a roster could only be typed by hand and so was a handful +/// of ids; bulk invite made a full board an ordinary thing to own, and a +/// read-modify-write PATCH of one — read the board, drop a name, send the rest +/// back — is the common client shape, so the loop had become +/// `max_participants` sequential round trips on a routine edit. /// /// A `parent` is refused here, and that is the cut that keeps the role off the /// whiteboard: never on a roster means [`board_for`] and the room's door already @@ -118,11 +132,19 @@ async fn resolve_participants( got: ids.len(), })); } - let mut users = Vec::with_capacity(ids.len()); - for id in ids { - let user = UserId::from_key(&id); - let found = User::read(&user, db).await?; - if !found.is_some_and(|found| found.get_role().at_least(Role::Student)) { + let wanted: Vec = ids.iter().map(|id| UserId::from_key(id)).collect(); + // Absent from this list means "no such user, or below `student`" — the two + // are one case here, and telling them apart is what the caller must not be + // able to do anyway. + let eligible: Vec = User::list_by_ids(&wanted, db) + .await? + .iter() + .filter(|found| found.get_role().at_least(Role::Student)) + .map(|found| found.get_id().clone()) + .collect(); + let mut users = Vec::with_capacity(wanted.len()); + for user in wanted { + if !eligible.contains(&user) { if current.contains(&user) { continue; } @@ -142,6 +164,22 @@ fn fan_out(st: &AppState, board: &BoardId, frame: serde_json::Value) { st.board_hub.publish(board.key(), frame.to_string()); } +/// The roster frame every path that changes the invite list must publish. A +/// participant dropped from the array keeps drawing over the socket they +/// already hold until the room hears this, so it is a permission fix rather +/// than a notification. +fn participants_frame(board: &Board) -> serde_json::Value { + json!({ + "type": "participants", + "creator": board.get_creator().key(), + "participants": board + .get_participants() + .iter() + .map(|user| user.key()) + .collect::>(), + }) +} + #[derive(Serialize, ToSchema)] struct BoardResponse { id: String, @@ -229,7 +267,7 @@ struct CreateBoard { title: String, /// Who may draw, besides the creator. Omit or send an empty list to open a /// board alone and invite later. - #[schema(max_items = 50)] + #[schema(max_items = 200)] participants: Option>, } @@ -462,7 +500,7 @@ struct UpdateBoard { /// Replace the invite list — **creator only**. Omit to keep; send `null` /// (or an empty list) to leave the creator alone on the board. #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option>, max_items = 50)] + #[schema(value_type = Option>, max_items = 200)] participants: Option>>, /// Pause (`true`) or resume (`false`) drawing — **creator only**. Omit to /// keep. @@ -514,19 +552,7 @@ async fn update_board( let participants = resolve_participants(participants, board.get_participants(), &st.db).await?; board = board.set_participants(participants, &st.db).await?; - fan_out( - &st, - board.get_id(), - json!({ - "type": "participants", - "creator": board.get_creator().key(), - "participants": board - .get_participants() - .iter() - .map(|user| user.key()) - .collect::>(), - }), - ); + fan_out(&st, board.get_id(), participants_frame(&board)); } if let Some(locked) = req.locked { board = board.set_locked(locked, user.get_id(), &st.db).await?; @@ -622,6 +648,198 @@ async fn close_board( Ok(Json(BoardResponse::new(&board))) } +/// A bulk invite's source: a roster that already exists somewhere else, named +/// on the wire and resolved to user ids **once**, at the moment of the call. +/// Tagged by `kind`, the same wire shape an event audience uses. +/// +/// The result is a **snapshot**, not a subscription. A board holds a flat list +/// of ids and nothing else — it does not remember it was filled from a class — +/// so a student who joins that class tomorrow is not on yesterday's board, and +/// nothing the class does afterwards puts back a student the creator took off. +/// That is the point of the shape: the roster is a list the creator owns and can +/// edit, and re-inviting the same source is how it is topped up (adding only who +/// is missing). Re-inviting *is* also what undoes a removal — the source still +/// names that student — so a removal is not a per-board ban; there is no +/// exclusion list. +/// +/// Live resolution was the alternative and is rejected for this feature: it +/// would make [`Board::is_participant`], the board room's door and +/// `list_for_user` cross-table queries — "which boards may I open" would stop +/// being one indexed read — and it would take the per-person removal away from +/// the creator, which is what a whiteboard is for. +#[derive(Deserialize, ToSchema)] +#[serde(tag = "kind", rename_all = "lowercase")] +enum InviteSource { + /// Everyone currently in this class section (şube). The homeroom teacher is + /// not implied — the field is a label and grants nothing. + Class { class: String }, + /// Everyone currently enrolled in this course. Clubs and study groups are + /// courses (`kind` `club` / `study`), so this is how a whole club is + /// invited. Staff running the course are not enrolled and so are not + /// included. + Course { course: String }, + /// The event's expected-attendee roster, exactly as `GET + /// /events/{id}/roster` resolves it — the signup list for a registration + /// event, the class or the course roster for the others. A school-wide or + /// role-wide event will normally overflow the board's participant cap; that + /// is a `409`, not a truncation. + Event { event: String }, +} + +impl InviteSource { + /// Resolve to raw user ids, refusing a caller who may not read this roster + /// in the first place. + /// + /// The gate is deliberately not a new permission: a board's roster is + /// visible to everyone on the board, so a bulk invite *discloses* the source + /// roster. Each arm therefore mirrors the gate on that roster's own listing + /// route — teacher+ for a class (`GET /classes/{id}/members`), + /// [`can_manage_course`] for a course (`GET /courses/{id}/enrollments`), + /// teacher+ for an event (`GET /events/{id}/roster`). A student can still + /// build a board one id at a time; they cannot dump a class roster into one. + /// + /// A source that does not exist is a `400` naming the field, never a `404`: + /// on these routes a 404 means "no such board, or not yours", and reusing it + /// here would tell a creator their own board had vanished. + async fn resolve(self, user: &User, db: &Database) -> Result, AppError> { + match self { + InviteSource::Class { class } => { + if !user.get_role().at_least(Role::Teacher) { + return Err(AppError::Forbidden( + "requires teacher role or higher to invite a whole class section", + )); + } + let class = ClassGroupId::from_key(&class); + if ClassGroup::read(&class, db).await?.is_none() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "class", + reason: "no such class section", + })); + } + Ok(ClassMember::list_for_class(&class, None, 0, db) + .await? + .0 + .iter() + .map(|member| member.get_user().clone()) + .collect()) + } + InviteSource::Course { course } => { + let course = Course::read(&CourseId::from_key(&course), db) + .await? + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "course", + reason: "no such course", + }))?; + if !can_manage_course(&course, user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can invite its roster", + )); + } + Ok(Enrollment::list_for_course(course.get_id(), None, 0, db) + .await? + .0 + .iter() + .map(|enrollment| enrollment.get_user().clone()) + .collect()) + } + InviteSource::Event { event } => { + if !user.get_role().at_least(Role::Teacher) { + return Err(AppError::Forbidden( + "requires teacher role or higher to invite an event's roster", + )); + } + let event = Event::read(&EventId::from_key(&event), db).await?.ok_or( + AppError::Validation(ValidationError::Invalid { + field: "event", + reason: "no such event", + }), + )?; + event.get_audience().members(event.get_id(), db).await + } + } + } +} + +/// Invite a whole roster at once — creator only, and additive: everyone the +/// source names is **added** to the invite list, nobody is ever removed by it. +/// Re-inviting the same source is therefore how a board is topped up after the +/// class gained a student, and it is idempotent when nothing changed. +/// +/// The ids are resolved once, here. The board keeps a flat list and no memory +/// of where it came from, so the roster does not track the source afterwards — +/// see [`InviteSource`] for why. Removal stays `PATCH /boards/{id}`: send the +/// roster you want. +/// +/// Three filters run on the resolved list before it lands, and all three are +/// silent — a source is a whole group, and one ineligible member must not fail +/// the invite for the other twenty-nine: +/// - ids that no longer resolve to a user row are dropped, +/// - anyone below the student role is dropped, which is what keeps `parent` off +/// the whiteboard by the same cut [`resolve_participants`] makes, +/// - anyone already on the board (the creator included) is not added twice. +/// +/// The cap is **all-or-nothing**: if the union would exceed +/// `max_participants` (`GET /limits`) the whole invite is refused with a `409` +/// naming the two numbers, and the roster is left exactly as it was. A partial +/// invite would silently pick which half of a class gets to draw. +#[utoipa::path( + post, + path = "/{id}/invite", + tag = "boards", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Board id")), + request_body = InviteSource, + responses( + (status = 200, description = "The board with the widened roster", body = BoardResponse), + (status = 400, description = "The named class, course or event does not exist", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the board's creator, or not allowed to read that roster", body = ErrorResponse), + (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse), + (status = 409, description = "The invite would put the board over its participant cap; nobody was added", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: an unknown or missing `kind`, or the field that `kind` requires is absent"), + ), +)] +async fn invite_board( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let board = board_for(&id, &user, &st.db).await?; + ensure_creator(&board, &user)?; + let invited = req.resolve(&user, &st.db).await?; + + // One read for the whole group. The filters below are silent on purpose — + // a source is a whole group, and one member who has left or was never + // eligible must not fail the invite for the other twenty-nine. + let mut roster = board.get_participants().to_vec(); + for candidate in User::list_by_ids(&invited, &st.db).await? { + if !candidate.get_role().at_least(Role::Student) { + continue; + } + // The creator is a participant by construction and never sits in the + // array; adding them there would spend a seat on someone who already + // has access. + if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) { + continue; + } + roster.push(candidate.get_id().clone()); + } + + if roster.len() > MAX_BOARD_PARTICIPANTS { + return Err(AppError::ConflictOwned(format!( + "this invite would put the board at {} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added", + roster.len() + ))); + } + // Unchanged rosters still write and still fan out: the alternative is a + // branch that has to prove the two lists are equal, and a re-invite that + // added nobody is the idempotent case, not the hot path. + let board = board.set_participants(roster, &st.db).await?; + fan_out(&st, board.get_id(), participants_frame(&board)); + Ok(Json(BoardResponse::new(&board))) +} + /// Delete the board and its whole stroke history — creator only, and the one /// operation in this system that really destroys marks (a clear never does). /// It also frees the creator's board seat. Use `/close` to retire a board while diff --git a/tests/board_invite.rs b/tests/board_invite.rs new file mode 100644 index 0000000..064c73a --- /dev/null +++ b/tests/board_invite.rs @@ -0,0 +1,548 @@ +//! `POST /boards/{id}/invite` — filling a whiteboard's roster from a group that +//! already exists (a class section, a course/club, an event's roster) instead of +//! one id at a time. +//! +//! The invariants pinned here are the ones the feature would be wrong without: +//! the expansion is a **snapshot** and not a subscription, it only ever **adds**, +//! the participant cap is **all-or-nothing**, ineligible members are dropped +//! **silently** while the whole call still succeeds, and — because a board's +//! roster is visible to everyone on the board — each source carries the gate its +//! own listing route carries, so bulk invite cannot become a roster-disclosure +//! oracle for a student. + +mod common; + +use axum::http::StatusCode; +use common::{Res, app_and_db, create_course, enroll, login, login_as, me_id, send}; +use hezarfen_backend::constant::MAX_BOARD_PARTICIPANTS; +use hezarfen_backend::domain::board::BoardId; +use hezarfen_backend::domain::user::UserId; +use serde_json::{Value, json}; + +/// Open a board as `cookie`; returns its id. +async fn a_board(app: &axum::Router, cookie: &str) -> String { + let res = send( + app, + "POST", + "/boards", + Some(cookie), + Some(json!({ "title": "Tahta" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + res.body["id"].as_str().unwrap().to_string() +} + +async fn invite(app: &axum::Router, cookie: &str, board: &str, source: Value) -> Res { + send( + app, + "POST", + &format!("/boards/{board}/invite"), + Some(cookie), + Some(source), + ) + .await +} + +/// The roster as the *server* holds it, read back off `GET /boards/{id}` rather +/// than trusted from the invite's own reply. +async fn roster(app: &axum::Router, cookie: &str, board: &str) -> Vec { + let res = send(app, "GET", &format!("/boards/{board}"), Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let mut ids: Vec = res.body["participants"] + .as_array() + .expect("participants array") + .iter() + .map(|id| id.as_str().unwrap().to_string()) + .collect(); + ids.sort(); + ids +} + +/// A class section with `members` in it, created by `manager`. +async fn a_class(app: &axum::Router, manager: &str, name: &str, members: &[&str]) -> String { + let res = send( + app, + "POST", + "/classes", + Some(manager), + Some(json!({ "name": name })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let class = res.body["id"].as_str().unwrap().to_string(); + for user in members { + let res = send( + app, + "POST", + &format!("/classes/{class}/members"), + Some(manager), + Some(json!({ "user_id": user })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + } + class +} + +/// The headline case: a teacher fills a board with a whole class in one call, +/// and the expansion is a snapshot — a student who joins the class *after* the +/// invite is not on the board until someone invites the class again, and that +/// re-invite adds only the person who was missing. +#[tokio::test] +async fn a_class_invite_fills_the_roster_and_re_inviting_tops_it_up() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager_a", "manager").await; + let teacher = login_as(&app, &db, "teacher_a", "teacher").await; + let ali = login(&app, "ali").await; + let ayse = login(&app, "ayse").await; + let deniz = login(&app, "deniz").await; + let (ali_id, ayse_id, deniz_id) = ( + me_id(&app, &ali).await, + me_id(&app, &ayse).await, + me_id(&app, &deniz).await, + ); + + let class = a_class(&app, &manager, "9-A", &[&ali_id, &ayse_id]).await; + let board = a_board(&app, &teacher).await; + + let res = invite( + &app, + &teacher, + &board, + json!({"kind": "class", "class": class}), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let mut expected = vec![ali_id.clone(), ayse_id.clone()]; + expected.sort(); + assert_eq!( + roster(&app, &teacher, &board).await, + expected, + "the whole class should be on the board" + ); + + // The class gains a student. The board is a snapshot, so nothing happens to + // it — this is the assertion that separates this design from a live roster. + let res = send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&manager), + Some(json!({ "user_id": deniz_id })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!( + roster(&app, &teacher, &board).await, + expected, + "a snapshot must not follow the class; the new member appeared on the board by itself" + ); + + // Re-inviting the same source tops it up, adding only who is missing. + let res = invite( + &app, + &teacher, + &board, + json!({"kind": "class", "class": class}), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let mut topped = vec![ali_id, ayse_id, deniz_id]; + topped.sort(); + assert_eq!( + roster(&app, &teacher, &board).await, + topped, + "a re-invite should add the missing member and duplicate nobody" + ); +} + +/// "Invite the whole club" is the course form — a club is a course whose `kind` +/// is `club`, so the club case needs no source of its own. The same call also +/// pins the two things an invite must never do: remove anybody, or spend a seat +/// on the creator (who is a participant by construction and never sits in the +/// array). +#[tokio::test] +async fn a_club_invite_adds_its_members_without_removing_a_hand_invited_one() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher_b", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let ali = login(&app, "ali").await; + let ayse = login(&app, "ayse").await; + let hakan = login(&app, "hakan").await; + let (ali_id, ayse_id, hakan_id) = ( + me_id(&app, &ali).await, + me_id(&app, &ayse).await, + me_id(&app, &hakan).await, + ); + + let res = send( + &app, + "POST", + "/courses", + Some(&teacher), + Some(json!({ "title": "Satranç Kulübü", "kind": "club" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let club = res.body["id"].as_str().unwrap().to_string(); + enroll(&app, &teacher, &club, &ali_id).await; + enroll(&app, &teacher, &club, &ayse_id).await; + + // Hakan is not in the club — he was invited by hand, and the club invite + // must leave him alone. + let res = send( + &app, + "POST", + "/boards", + Some(&teacher), + Some(json!({ "title": "Açılış", "participants": [hakan_id] })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let board = res.body["id"].as_str().unwrap().to_string(); + + let res = invite( + &app, + &teacher, + &board, + json!({"kind": "course", "course": club}), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let mut expected = vec![ali_id, ayse_id, hakan_id]; + expected.sort(); + let seen = roster(&app, &teacher, &board).await; + assert_eq!( + seen, expected, + "an invite adds; it must never drop the hand-invited participant" + ); + assert!( + !seen.contains(&teacher_id), + "the creator is a participant by construction and must not take a seat in the array: {seen:?}" + ); +} + +/// An event source resolves whatever `GET /events/{id}/roster` resolves, and the +/// role filter runs over the result: a `parent`-role event names only parents, +/// and the whiteboard admits none of them. The call still succeeds — a source is +/// a whole group, and dropping its ineligible members must not fail it. +#[tokio::test] +async fn parents_in_a_source_are_dropped_silently_and_the_invite_still_succeeds() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher_c", "teacher").await; + let _veli = login_as(&app, &db, "veli", "parent").await; + + let res = send( + &app, + "POST", + "/events", + Some(&teacher), + Some(json!({ "title": "Veli toplantısı", "audience": {"kind": "role", "role": "parent"} })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let event = res.body["id"].as_str().unwrap().to_string(); + + let board = a_board(&app, &teacher).await; + let res = invite( + &app, + &teacher, + &board, + json!({"kind": "event", "event": event}), + ) + .await; + assert_eq!( + res.status, + StatusCode::OK, + "an all-parent source must be a successful no-op, not an error: {}", + res.body + ); + assert!( + roster(&app, &teacher, &board).await.is_empty(), + "a parent reached a whiteboard roster through bulk invite" + ); +} + +/// A member the source still names but whose user row is gone is dropped the +/// same silent way — the batch lookup simply does not return them. +#[tokio::test] +async fn a_deleted_user_in_a_source_is_dropped() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher_d", "teacher").await; + let ali = login(&app, "ali").await; + let ghost = login(&app, "ghost").await; + let (ali_id, ghost_id) = (me_id(&app, &ali).await, me_id(&app, &ghost).await); + + let course = create_course(&app, &teacher, "Fizik").await; + enroll(&app, &teacher, &course, &ali_id).await; + enroll(&app, &teacher, &course, &ghost_id).await; + + // The row goes without the cascade a real DELETE runs, which is exactly the + // state a stale enrollment leaves behind. + db.query("DELETE type::record('user', $key)") + .bind(("key", ghost_id.clone())) + .await + .unwrap() + .check() + .unwrap(); + + let board = a_board(&app, &teacher).await; + let res = invite( + &app, + &teacher, + &board, + json!({"kind": "course", "course": course}), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + roster(&app, &teacher, &board).await, + vec![ali_id], + "a deleted user must not be written onto a roster" + ); +} + +/// The cap is all-or-nothing. A partial invite would silently pick which half of +/// a class gets to draw, so an invite that would carry the board past +/// `max_participants` is refused whole and leaves the roster untouched. +#[tokio::test] +async fn an_over_cap_invite_is_refused_whole_and_changes_nothing() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager_e", "manager").await; + let teacher = login_as(&app, &db, "teacher_e", "teacher").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + + let class = a_class(&app, &manager, "9-B", &[&ali_id]).await; + let board = a_board(&app, &teacher).await; + + // Fill the roster to the brim directly: reaching the cap through the API + // would mean registering two hundred accounts to prove an arithmetic guard. + // The ids need not resolve — the roster is only repaired at boot, and the + // guard under test counts entries. + let full: Vec<_> = (0..MAX_BOARD_PARTICIPANTS) + .map(|n| UserId::from_key(&format!("filler{n}")).record()) + .collect(); + db.query("UPDATE $b SET participants = $who") + .bind(("b", BoardId::from_key(&board).record())) + .bind(("who", full)) + .await + .unwrap() + .check() + .unwrap(); + let before = roster(&app, &teacher, &board).await; + assert_eq!(before.len(), MAX_BOARD_PARTICIPANTS); + + let res = invite( + &app, + &teacher, + &board, + json!({"kind": "class", "class": class}), + ) + .await; + assert_eq!( + res.status, + StatusCode::CONFLICT, + "one member over the cap must be a 409: {}", + res.body + ); + assert_eq!( + roster(&app, &teacher, &board).await, + before, + "a refused invite must leave the roster byte-identical" + ); +} + +/// The disclosure gate. A board's roster is visible to every participant, so +/// inviting a group hands that group's membership to everyone on the board — +/// which makes bulk invite a *read* of the source roster, and it must carry the +/// same gate that roster's own listing route carries. A student can still build +/// a board one id at a time; they cannot pour a class into one. +#[tokio::test] +async fn a_student_cannot_use_bulk_invite_as_a_class_roster_oracle() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager_f", "manager").await; + let ali = login(&app, "ali").await; + let ayse = login(&app, "ayse").await; + let (ali_id, ayse_id) = (me_id(&app, &ali).await, me_id(&app, &ayse).await); + + let class = a_class(&app, &manager, "9-C", &[&ali_id, &ayse_id]).await; + // Ali is *in* the class, and still may not dump it onto his own board. + let board = a_board(&app, &ali).await; + + let res = invite(&app, &ali, &board, json!({"kind": "class", "class": class})).await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "a student expanded a class roster: {}", + res.body + ); + assert!(roster(&app, &ali, &board).await.is_empty(), "{}", res.body); +} + +/// The course arm's gate is narrower than teacher+: a teacher who neither +/// created the course nor was assigned to it cannot read its roster, so they +/// cannot invite it either. The course's own teacher can. +#[tokio::test] +async fn a_teacher_who_does_not_run_the_course_cannot_invite_its_roster() { + let (app, db) = app_and_db().await; + let owner = login_as(&app, &db, "teacher_g", "teacher").await; + let outsider = login_as(&app, &db, "teacher_h", "teacher").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + + let course = create_course(&app, &owner, "Kimya").await; + enroll(&app, &owner, &course, &ali_id).await; + + let their_board = a_board(&app, &outsider).await; + let res = invite( + &app, + &outsider, + &their_board, + json!({"kind": "course", "course": course}), + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "an unrelated teacher read a course roster through an invite: {}", + res.body + ); + + let own_board = a_board(&app, &owner).await; + let res = invite( + &app, + &owner, + &own_board, + json!({"kind": "course", "course": course}), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(roster(&app, &owner, &own_board).await, vec![ali_id]); +} + +/// The board's own two-tier answer, unchanged by the new route: an outsider is +/// told the board does not exist, a participant who is not the creator is told +/// it is not theirs to command. +#[tokio::test] +async fn a_participant_gets_403_and_an_outsider_gets_404() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager_i", "manager").await; + let creator = login_as(&app, &db, "teacher_i", "teacher").await; + let other = login_as(&app, &db, "teacher_j", "teacher").await; + let stranger = login_as(&app, &db, "teacher_k", "teacher").await; + let other_id = me_id(&app, &other).await; + + let class = a_class(&app, &manager, "9-D", &[]).await; + let res = send( + &app, + "POST", + "/boards", + Some(&creator), + Some(json!({ "title": "Tahta", "participants": [other_id] })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let board = res.body["id"].as_str().unwrap().to_string(); + + let res = invite( + &app, + &other, + &board, + json!({"kind": "class", "class": class.clone()}), + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "a participant who is not the creator: {}", + res.body + ); + + let res = invite( + &app, + &stranger, + &board, + json!({"kind": "class", "class": class}), + ) + .await; + assert_eq!( + res.status, + StatusCode::NOT_FOUND, + "an outsider must not learn the board exists: {}", + res.body + ); +} + +/// A source that does not exist is a `400` naming the field it came in on — +/// never a `404`, which on these routes means "no such board, or not yours" and +/// would tell a creator their own board had vanished. +#[tokio::test] +async fn an_unknown_source_is_a_400_and_not_the_boards_404() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher_l", "teacher").await; + let board = a_board(&app, &teacher).await; + + for (source, field) in [ + ( + json!({"kind": "class", "class": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}), + "class", + ), + ( + json!({"kind": "course", "course": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}), + "course", + ), + ( + json!({"kind": "event", "event": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}), + "event", + ), + ] { + let res = invite(&app, &teacher, &board, source).await; + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "a missing {field} must not borrow the board's 404: {}", + res.body + ); + assert!( + res.body.to_string().contains(field), + "the 400 should name the field that was wrong: {}", + res.body + ); + } +} + +/// The reply is the board itself, so a client never has to re-fetch to learn who +/// it just added. (That the live room is *told* as well is an end-to-end matter +/// and is pinned over a real socket in `e2e.rs`.) +#[tokio::test] +async fn the_reply_carries_the_widened_roster() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "manager_m", "manager").await; + let teacher = login_as(&app, &db, "teacher_m", "teacher").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + + let class = a_class(&app, &manager, "9-E", &[&ali_id]).await; + let board = a_board(&app, &teacher).await; + let res = invite( + &app, + &teacher, + &board, + json!({"kind": "class", "class": class}), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The reply is the board, so the roster the room is told about and the + // roster the caller is shown are the same list. + assert_eq!( + res.body["participants"], + json!([ali_id]), + "the invite's own reply must carry the widened roster: {}", + res.body + ); +} diff --git a/tests/e2e.rs b/tests/e2e.rs index c67513e..37e9f7f 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -2709,6 +2709,82 @@ async fn a_removed_participant_can_no_longer_draw() { } } +/// A bulk invite (`POST /boards/{id}/invite`) must reach the live room like any +/// other roster change. The room authorizes every delivery against the roster it +/// is told about, so a path that widens the array and stays silent leaves the +/// new participant unrenderable to the people already drawing — and this one is +/// easy to forget precisely because it only ever *adds*, so it can never trip +/// the removal test above. +#[tokio::test] +async fn a_bulk_invite_announces_the_widened_roster_to_the_room() { + let room = board_room_fixture().await; + let (base, board) = (room.base.as_str(), room.board_id.as_str()); + // The invite gates are teacher+, and the fixture's creator is a student. + promote(&room.db, "ali", "teacher").await; + + let mut veli = board_open(base, board, Some(&room.veli_cookie)) + .await + .expect("invited"); + board_join(&mut veli, None, None).await; + + // A school-wide event resolves to every account, which here is the three the + // fixture registered — so the invite adds exactly the outsider, ayşe. + let res = room + .creator + .post(format!("{base}/events")) + .json(&json!({ "title": "Tüm okul" })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let event: Value = res.json().await.unwrap(); + let event_id = event["id"].as_str().unwrap().to_string(); + + let res = room + .creator + .post(format!("{base}/boards/{board}/invite")) + .json(&json!({ "kind": "event", "event": event_id })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + let widened: Value = res.json().await.unwrap(); + + let frame = board_frame_of_type(&mut veli, "participants").await; + let announced = frame["participants"].as_array().unwrap(); + assert!( + announced.iter().any(|id| id == &json!(room.veli_id)), + "the standing participant must still be on the announced roster: {frame}" + ); + assert_eq!( + announced.len(), + 2, + "the outsider should have been added and announced: {frame}" + ); + // The wire and the reply are the same list, and the creator is in neither + // array — they are a participant by construction. + let mut from_frame: Vec<&Value> = announced.iter().collect(); + let served = widened["participants"].as_array().unwrap(); + let mut from_body: Vec<&Value> = served.iter().collect(); + from_frame.sort_by_key(|id| id.as_str().unwrap()); + from_body.sort_by_key(|id| id.as_str().unwrap()); + assert_eq!(from_frame, from_body, "{frame} vs {widened}"); + assert_eq!(frame["creator"], widened["creator"], "{frame}"); + + // The stored row is the authority — the mem engine forges write wins, so a + // frame alone proves only that the server said something. + let stored: Value = room + .creator + .get(format!("{base}/boards/{board}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(stored["participants"], widened["participants"]); +} + /// Test 8 — `client_seq` is the client's correlation id and is echoed /// verbatim, including a value no `i32` holds; a message without one gets a /// reply without the key at all. Kills the "helpfully normalize it" bug that