forge
Explore
Log in

Don't you dare go Hollow

Builder API — the vendor creates, suspends, enters and deletes schools

Browse files at this commit

1ab298d2b98122216eee9765421f4e2d46463768Ahmet Kaan GümüşParent: b7dfc0c
  • feat
    • builder API — the vendor creates, suspends, enters and deletes schools
Show full message
✨ feat: builder API — the vendor creates, suspends, enters and deletes schools

`POST /builder/login|logout`, `GET /builder/me`; `POST|GET /schools`,
`GET|PATCH|DELETE /schools/{slug}`, `POST /schools/{slug}/admin-password`,
`POST /schools/{slug}/enter`. Builder sessions live in the control database
behind their own strict per-IP login tier; deleting a school drops its
database and its files subtree.
README.mdmodified+14 -2
@@ -430,7 +430,7 @@ drift from it**, which is enforced rather than asked for:
430430 and fails unless each one is either referenced by `src/web/limits.rs` or
431431 listed as a deliberate exclusion *with a reason*. A new constant breaks the
432432 suite until someone decides, consciously, whether clients need it.
433-- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 176 published
433+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 194 published
434434 bounds back out of the emitted JSON, and asserts each equals its constant.
435435 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
436436 only** — a `const` there does not compile — so the annotations are
@@ -741,7 +741,9 @@ against the SurrealDB server — e.g.
741741 ## Endpoints
742742
743743 `Auth` is the minimum role; `no` means no session required, `student` means any
744-logged-in user.
744+logged-in user. `builder` is not a school role: it means the deployment's
745+vendor account (see the `builder` tag), whose cookie is refused on every other
746+endpoint here exactly as a school's cookie is refused on its.
745747
746748 A course is a regular taught course (kind `course`, the default), an *etüt* (kind
747749 `study` — a supervised study session), or a *kulüp* (kind `club` — a student
@@ -871,6 +873,9 @@ window filtering, before paging; negative values are a `400` naming the field.
871873 | POST | `/boards/{id}/invite` | student | 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. |
872874 | GET | `/boards/{id}/strokes` | student | The live canvas: the current epoch's strokes, oldest first, paged via `?limit=&offset=`. This is what a client draws to catch up — earlier epochs are still stored, and read through `/history`. Drawn marks only: a `clear` marker never appears here, exactly as it never appears on the board room's socket. Read `/history` or `/epochs` for the markers. |
873875 | GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see "Collaborative whiteboard") |
876+| POST | `/builder/login` | no | Log in as the deployment's builder. Sets a `session` cookie (`builder.<token>`) that works on this surface and nowhere else. |
877+| POST | `/builder/logout` | no | Log out a builder: revoke the session (if any) and clear the cookie. Idempotent — answers `204` either way. |
878+| GET | `/builder/me` | builder | The current builder. |
874879 | GET | `/chatbot/threads` | student | The caller's own threads, most recently active first. Paged via `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's. |
875880 | POST | `/chatbot/threads` | student | Start a new chatbot thread, optionally named. Every authenticated role may chat, parents included. A user may keep up to the school's `max_chatbot_threads` threads; at the cap the request is refused (409) until an old thread is deleted — the cap is storage protection, not a usage quota (that is the per-minute message limit). |
876881 | PATCH | `/chatbot/threads/{id}` | student | Rename a thread, or clear its name (`title: null`). Owner only; someone else's thread is a `404`, never a `403`. The edit counts as activity, so the thread moves to the top of the list — renaming is how a user files a thread, and a rename that left it buried would be useless. |
@@ -1070,6 +1075,13 @@ window filtering, before paging; negative values are a `400` naming the field.
10701075 | GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes. Access follows the question the solution hangs on — in practice school-wide, since solutions exist only on approved questions. |
10711076 | POST | `/questions/{id}/solutions/{sid}/image` | student | Attach (or replace) the solution's photo. Author only — and at any time, since solutions are never frozen. `multipart/form-data` with the image under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes` (settings). |
10721077 | DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo. Author only, anytime — solutions are never frozen. |
1078+| GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). |
1079+| POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. |
1080+| GET | `/schools/{slug}` | builder | One school by slug. |
1081+| PATCH | `/schools/{slug}` | builder | Rename a school and/or flip it between `active` and `suspended`. Omitted fields keep their value. The slug itself is immutable — it names a database and a directory. |
1082+| DELETE | `/schools/{slug}` | builder | Delete a school: its database, its registry row, and its uploaded files. Irreversible — suspension is the reversible door. |
1083+| POST | `/schools/{slug}/admin-password` | builder | Reset an admin's password inside a school — the "we are locked out" call. Every session that account held is revoked with it, so a stolen cookie does not survive the reset. Works on a suspended school. |
1084+| POST | `/schools/{slug}/enter` | builder | Enter a school as one of its admins — support access, with the school's own session cookie (`<slug>.<token>`) and no builder power inside it. |
10731085 | GET | `/sessions/{id}` | student | Fetch a single session by id. Visible to its course's enrolled users, the session's teacher, the course's own teachers, and managers/admins. |
10741086 | PATCH | `/sessions/{id}` | teacher | Update a session. Requires teacher+ with course-management rights. Omitted fields keep their value; an explicit `null` clears `ends_at`. |
10751087 | DELETE | `/sessions/{id}` | teacher | Delete a session and its roll-call rows. Requires teacher+ with course-management rights. |
src/constant.rsmodified+3 -0
@@ -11,6 +11,9 @@ use crate::domain::role::Role;
1111 pub const MIN_SLUG_LEN: usize = 2;
1212 pub const MAX_SLUG_LEN: usize = 32;
1313
14+/// A school's display name — free text, unlike its slug.
15+pub const MAX_SCHOOL_NAME_LEN: usize = 120;
16+
1417 pub const MIN_USERNAME_LEN: usize = 3;
1518 pub const MAX_USERNAME_LEN: usize = 32;
1619
src/domain/session.rsmodified+11 -0
@@ -93,6 +93,17 @@ impl Session {
9393 Ok(())
9494 }
9595
96+ /// Revoke every session a user holds. The other half of a password reset:
97+ /// the new credential means nothing while a cookie minted under the old one
98+ /// still authenticates.
99+ pub async fn delete_by_user(user: &UserId, db: &Database) -> Result<(), AppError> {
100+ db.query("DELETE session WHERE user = $usr")
101+ .bind(("usr", user.record()))
102+ .await?
103+ .check()?;
104+ Ok(())
105+ }
106+
96107 /// Delete every session whose expiry is in the past, returning how many were
97108 /// removed. Expired sessions are already rejected at auth, but nothing else
98109 /// deletes their rows — without this sweep the `session` table grows forever.
src/domain/user.rsmodified+24 -1
@@ -370,7 +370,7 @@ impl User {
370370 /// or a cancelled future), and the row left behind is an ordinary student
371371 /// account that [`User::ensure_admin`] must then refuse to touch — a
372372 /// deployment with no admin and no way for a later boot to repair it.
373- async fn create_with_role(
373+ pub async fn create_with_role(
374374 username: Username,
375375 password_hash: PasswordHash,
376376 role: Role,
@@ -892,6 +892,29 @@ impl User {
892892 Ok(rows.into_iter().next())
893893 }
894894
895+ /// Replace a user's password hash — the builder's admin-password reset
896+ /// (`POST /schools/{slug}/admin-password`). Only the credential is
897+ /// rewritten; revoking the sessions minted under the old one is the
898+ /// caller's second half
899+ /// ([`crate::domain::session::Session::delete_by_user`]), because a reset
900+ /// that leaves a stolen cookie working resets nothing.
901+ pub async fn set_password_hash(
902+ id: &UserId,
903+ password_hash: PasswordHash,
904+ db: &Database,
905+ ) -> Result<Option<User>, AppError> {
906+ let rows: Vec<User> = write_with_retry(
907+ db,
908+ "UPDATE $u SET password_hash = $hash RETURN AFTER",
909+ &[
910+ ("u".into(), id.record().into_value()),
911+ ("hash".into(), password_hash.into_value()),
912+ ],
913+ )
914+ .await?;
915+ Ok(rows.into_iter().next())
916+ }
917+
895918 /// Write the UI-preference fields the request actually carried. Same
896919 /// contract as [`User::set_profile`]: `None` = omitted (not written),
897920 /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set.
src/lib.rsmodified+2 -0
@@ -43,6 +43,7 @@ use crate::state::AppState;
4343 tags(
4444 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),
4545 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
46+ (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it."),
4647 (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"),
4748 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
4849 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
@@ -99,6 +100,7 @@ pub fn build_router(state: AppState) -> Router {
99100 .merge(web::limits::routes())
100101 .nest("/ai", web::ai::routes())
101102 .nest("/auth", web::auth::routes(&state))
103+ .merge(web::builder::routes(&state))
102104 .nest("/chatbot", web::chatbot::routes())
103105 .nest("/users", web::users::routes())
104106 .nest("/notes", web::notes::routes())
src/web/auth.rsmodified+16 -5
@@ -199,18 +199,29 @@ async fn login(
199199 let session = Session::create(user.get_id(), &db).await?;
200200 // `<slug>.<token>`: the cookie carries the school, so every later request
201201 // finds its database without a second lookup path that could disagree.
202- let cookie = Cookie::build(("session", format!("{school}.{}", session.token().as_str())))
202+ let cookie = session_cookie(
203+ format!("{school}.{}", session.token().as_str()),
204+ st.cookie_secure,
205+ );
206+
207+ Ok((jar.add(cookie), Json(UserResponse::new(&user))))
208+}
209+
210+/// The `session` cookie, however it was earned. Shared by school login and the
211+/// builder surface (`web::builder`) so the two can never drift apart on path,
212+/// flags or lifetime — the value is the only difference between them
213+/// (`<slug>.<token>` against `builder.<token>`).
214+pub(crate) fn session_cookie(value: String, secure: bool) -> Cookie<'static> {
215+ Cookie::build(("session", value))
203216 .path("/")
204217 .http_only(true)
205- .secure(st.cookie_secure)
218+ .secure(secure)
206219 // Lax is part of the CORS defense: it keeps this cookie off cross-site
207220 // requests. Before relaxing toward SameSite=None, first make sure
208221 // `cors_layer` (lib.rs) can never mirror origins with credentials on.
209222 .same_site(SameSite::Lax)
210223 .max_age(time::Duration::days(SESSION_DURATION_DAYS))
211- .build();
212-
213- Ok((jar.add(cookie), Json(UserResponse::new(&user))))
224+ .build()
214225 }
215226
216227 /// Log out: revoke the current session (if any) and clear the cookie.
src/web/builder.rsadded+535 -0
@@ -0,0 +1,535 @@
1+//! The vendor's surface: the operator who owns the deployment, not anybody's
2+//! school. Every handler here takes `axum::extract::State` (the **control**
3+//! database) rather than `web::tenant_state::State`, because these routes are
4+//! *about* schools instead of inside one — the school a request touches is
5+//! named in its path and resolved through [`crate::tenant::Tenants`].
6+//!
7+//! The two principals never mix: [`RequireBuilder`] takes only a
8+//! `builder.<token>` cookie, and that cookie is `401` on every school surface
9+//! (see `web::tenant_state::resolve_tenant`). `POST /schools/{slug}/enter` is
10+//! the one bridge, and it does not blur the line — it mints an ordinary school
11+//! session for an admin account that already exists there.
12+//!
13+//! A suspended school is closed to *its users*, not to its vendor: every route
14+//! here keeps working on one (that is how it gets un-suspended) except `enter`,
15+//! so "suspended blocks everything" stays true of the school's own doors.
16+
17+use axum::Json;
18+use axum::extract::{Path, Query, Request, State};
19+use axum::http::StatusCode;
20+use axum::middleware::{self, Next};
21+use axum_extra::extract::CookieJar;
22+use axum_extra::extract::cookie::Cookie;
23+use serde::{Deserialize, Serialize};
24+use utoipa::ToSchema;
25+use utoipa_axum::router::OpenApiRouter;
26+use utoipa_axum::routes;
27+
28+use crate::constant::MAX_SCHOOL_NAME_LEN;
29+use crate::domain::builder::{Builder, BuilderSession};
30+use crate::domain::role::Role;
31+use crate::domain::session::Session;
32+use crate::domain::user::{Password, PasswordHash, User, Username};
33+use crate::error::{AppError, ErrorResponse};
34+use crate::rate_limit::{RateLimitConfig, RateLimiter};
35+use crate::state::AppState;
36+use crate::tenant::{School, SchoolStatus, Slug};
37+use crate::validate::validate_required;
38+use crate::web::tenant_state::school_files_path;
39+
40+use super::auth::session_cookie;
41+use super::{BUILDER_COOKIE_PREFIX, Page, PageParams, RequireBuilder, UserResponse};
42+
43+pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
44+ // The builder credential is the most valuable one in the deployment, so its
45+ // login sits behind the same strict per-IP tier `/auth/login` uses — its own
46+ // budget, since a school's brute-forcer must not spend the vendor's.
47+ let rate_limit: &RateLimitConfig = &state.rate_limit;
48+ let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy);
49+ limiter.share("builder", state.db.clone(), state.db_up.clone());
50+ OpenApiRouter::new()
51+ .routes(routes!(builder_login))
52+ .route_layer(middleware::from_fn(move |req: Request, next: Next| {
53+ let limiter = limiter.clone();
54+ async move { limiter.enforce(req, next).await }
55+ }))
56+ .routes(routes!(builder_logout))
57+ .routes(routes!(builder_me))
58+ .routes(routes!(create_school, list_schools))
59+ .routes(routes!(get_school, update_school, delete_school))
60+ .routes(routes!(reset_admin_password))
61+ .routes(routes!(enter_school))
62+}
63+
64+#[derive(Deserialize, ToSchema)]
65+struct BuilderCredentials {
66+ #[schema(example = "operator", min_length = 3, max_length = 32)]
67+ username: String,
68+ #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
69+ password: String,
70+}
71+
72+/// The operator behind the cookie. Deliberately not [`UserResponse`]: a builder
73+/// has no role, no profile and no school.
74+#[derive(Serialize, ToSchema)]
75+struct BuilderResponse {
76+ id: String,
77+ #[schema(example = "operator")]
78+ username: String,
79+}
80+
81+impl BuilderResponse {
82+ fn new(builder: &Builder) -> Self {
83+ Self {
84+ id: builder.get_id().key().to_string(),
85+ username: builder.get_username().as_str().to_string(),
86+ }
87+ }
88+}
89+
90+#[derive(Serialize, ToSchema)]
91+struct SchoolResponse {
92+ #[schema(example = "ata-koleji")]
93+ slug: String,
94+ #[schema(example = "Ata Koleji")]
95+ name: String,
96+ /// `active` or `suspended`. A suspended school refuses every one of its own
97+ /// users, login included.
98+ #[schema(example = "active")]
99+ status: String,
100+ /// Registered at, UTC unix-milliseconds.
101+ created_at: i64,
102+}
103+
104+impl SchoolResponse {
105+ fn new(school: &School) -> Self {
106+ Self {
107+ slug: school.slug().as_str().to_string(),
108+ name: school.name().to_string(),
109+ status: school.status().as_str().to_string(),
110+ created_at: school.created_at().as_millis(),
111+ }
112+ }
113+}
114+
115+#[derive(Deserialize, ToSchema)]
116+struct CreateSchool {
117+ /// Lowercase `a-z`, `0-9` and `-`, starting with a letter or digit. Names
118+ /// the school's database, its blob directory and its cookie prefix, so it
119+ /// is immutable once taken.
120+ #[schema(example = "ata-koleji", min_length = 2, max_length = 32)]
121+ slug: String,
122+ #[schema(example = "Ata Koleji", max_length = 120)]
123+ name: String,
124+ /// The school's first admin, created inside the new school's database.
125+ #[schema(example = "admin", min_length = 3, max_length = 32)]
126+ admin_username: String,
127+ #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
128+ admin_password: String,
129+}
130+
131+#[derive(Deserialize, ToSchema)]
132+struct UpdateSchool {
133+ #[schema(example = "Ata Koleji", max_length = 120)]
134+ name: Option<String>,
135+ /// `active` or `suspended`.
136+ #[schema(example = "suspended")]
137+ status: Option<String>,
138+}
139+
140+#[derive(Deserialize, ToSchema)]
141+struct AdminPassword {
142+ /// The admin account in that school whose password is being reset.
143+ #[schema(example = "admin", min_length = 3, max_length = 32)]
144+ username: String,
145+ #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
146+ password: String,
147+}
148+
149+#[derive(Deserialize, ToSchema)]
150+struct EnterSchool {
151+ /// The admin account to enter as. It must already exist in that school.
152+ #[schema(example = "admin", min_length = 3, max_length = 32)]
153+ username: String,
154+}
155+
156+/// A school's display name: free text, unlike its slug.
157+fn school_name(value: &str) -> Result<String, AppError> {
158+ validate_required("name", value, MAX_SCHOOL_NAME_LEN)?;
159+ Ok(value.trim().to_string())
160+}
161+
162+/// The slug in a path. Anything that is not a slug names no school, so it is
163+/// the same `404` an unknown one gets — and it never reaches
164+/// [`school_files_path`], which is exactly why that path is built from a
165+/// validated [`Slug`] and never from the raw segment.
166+fn path_slug(raw: &str) -> Result<Slug, AppError> {
167+ Slug::try_new(raw).map_err(|_| AppError::NotFound)
168+}
169+
170+/// The named account in `db`, which must be an admin of that school: unknown →
171+/// `404` (a builder is authenticated, there is nothing to hide), present but
172+/// below admin → `409`, the repo's verdict for "the row exists, its state
173+/// refuses this".
174+async fn school_admin(username: &str, db: &crate::database::Database) -> Result<User, AppError> {
175+ let user = User::find_by_username(username.trim(), db)
176+ .await?
177+ .ok_or(AppError::NotFound)?;
178+ if user.get_role() != Role::Admin {
179+ return Err(AppError::Conflict(
180+ "that account is not an admin of this school",
181+ ));
182+ }
183+ Ok(user)
184+}
185+
186+/// Log in as the deployment's builder. Sets a `session` cookie
187+/// (`builder.<token>`) that works on this surface and nowhere else.
188+#[utoipa::path(
189+ post,
190+ path = "/builder/login",
191+ tag = "builder",
192+ request_body = BuilderCredentials,
193+ responses(
194+ (status = 200, description = "Logged in; builder session cookie set", body = BuilderResponse),
195+ (status = 401, description = "Bad credentials", body = ErrorResponse),
196+ (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
197+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
198+ ),
199+)]
200+async fn builder_login(
201+ State(st): State<AppState>,
202+ jar: CookieJar,
203+ Json(req): Json<BuilderCredentials>,
204+) -> Result<(CookieJar, Json<BuilderResponse>), AppError> {
205+ let control = st.tenants.control();
206+ let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?;
207+ let builder = match Builder::find_by_username(req.username.trim(), control).await? {
208+ Some(builder) => {
209+ if !builder
210+ .get_password_hash()
211+ .verify_async(&password)
212+ .await
213+ {
214+ return Err(AppError::Unauthorized);
215+ }
216+ builder
217+ }
218+ None => {
219+ // The same decoy hash `/auth/login` runs: a wrong name and a wrong
220+ // password must cost the same, or the reply time enumerates the
221+ // operator accounts.
222+ PasswordHash::verify_decoy_async(&password).await;
223+ return Err(AppError::Unauthorized);
224+ }
225+ };
226+
227+ let session = BuilderSession::create(builder.get_id(), control).await?;
228+ let cookie = session_cookie(
229+ format!("{BUILDER_COOKIE_PREFIX}.{}", session.token().as_str()),
230+ st.cookie_secure,
231+ );
232+ Ok((jar.add(cookie), Json(BuilderResponse::new(&builder))))
233+}
234+
235+/// Log out a builder: revoke the session (if any) and clear the cookie.
236+/// Idempotent — answers `204` either way.
237+#[utoipa::path(
238+ post,
239+ path = "/builder/logout",
240+ tag = "builder",
241+ responses((status = 204, description = "Logged out (no-op without a builder session)")),
242+)]
243+async fn builder_logout(
244+ State(st): State<AppState>,
245+ jar: CookieJar,
246+) -> Result<(CookieJar, StatusCode), AppError> {
247+ if let Some((BUILDER_COOKIE_PREFIX, token)) = jar
248+ .get("session")
249+ .and_then(|cookie| super::tenant_state::split_cookie(cookie.value()))
250+ {
251+ BuilderSession::delete_by_token(token, st.tenants.control()).await?;
252+ }
253+ let jar = jar.remove(Cookie::build(("session", "")).path("/").build());
254+ Ok((jar, StatusCode::NO_CONTENT))
255+}
256+
257+/// The current builder.
258+#[utoipa::path(
259+ get,
260+ path = "/builder/me",
261+ tag = "builder",
262+ security(("session_cookie" = [])),
263+ responses(
264+ (status = 200, description = "The current builder", body = BuilderResponse),
265+ (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
266+ ),
267+)]
268+async fn builder_me(RequireBuilder(builder): RequireBuilder) -> Json<BuilderResponse> {
269+ Json(BuilderResponse::new(&builder))
270+}
271+
272+/// Create a school: its registry row, its database, its schema, and its first
273+/// admin account — one call, or none of it.
274+#[utoipa::path(
275+ post,
276+ path = "/schools",
277+ tag = "builder",
278+ security(("session_cookie" = [])),
279+ request_body = CreateSchool,
280+ responses(
281+ (status = 201, description = "School created, with its first admin", body = SchoolResponse),
282+ (status = 400, description = "Invalid slug, name, or admin credentials", body = ErrorResponse),
283+ (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
284+ (status = 409, description = "That slug is already taken", body = ErrorResponse),
285+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
286+ ),
287+)]
288+async fn create_school(
289+ State(st): State<AppState>,
290+ RequireBuilder(_builder): RequireBuilder,
291+ Json(req): Json<CreateSchool>,
292+) -> Result<(StatusCode, Json<SchoolResponse>), AppError> {
293+ // Everything the request must get right is checked (and the admin password
294+ // hashed) *before* a database is defined, so the ordinary rejection never
295+ // creates anything to clean up.
296+ let slug = Slug::try_new(&req.slug)?;
297+ let name = school_name(&req.name)?;
298+ let username = Username::try_new(&req.admin_username)?;
299+ let password_hash = Password::try_new(&req.admin_password)?.hash_async().await?;
300+
301+ let db = st.tenants.create(&slug, &name).await?;
302+ if let Err(err) = User::create_with_role(username, password_hash, Role::Admin, &db).await {
303+ // A school nobody can log into is worse than no school: take the
304+ // database back so the very same request can simply be retried.
305+ if let Err(cleanup) = st.tenants.drop(&slug).await {
306+ tracing::error!("failed to drop {slug} after its admin seed failed: {cleanup}");
307+ }
308+ return Err(err);
309+ }
310+
311+ let school = School::read(&slug, st.tenants.control())
312+ .await?
313+ .ok_or_else(|| AppError::Internal("the school vanished as it was created".into()))?;
314+ Ok((StatusCode::CREATED, Json(SchoolResponse::new(&school))))
315+}
316+
317+/// Every school this deployment serves, newest first. Paged via
318+/// `?limit=&offset=` (omit `limit` for the full list).
319+#[utoipa::path(
320+ get,
321+ path = "/schools",
322+ tag = "builder",
323+ security(("session_cookie" = [])),
324+ params(PageParams),
325+ responses(
326+ (status = 200, description = "A page of schools (the full list when unpaged)", body = Page<SchoolResponse>),
327+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
328+ (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
329+ ),
330+)]
331+async fn list_schools(
332+ State(st): State<AppState>,
333+ RequireBuilder(_builder): RequireBuilder,
334+ Query(page): Query<PageParams>,
335+) -> Result<Json<Page<SchoolResponse>>, AppError> {
336+ let (limit, offset) = page.resolve()?;
337+ let (schools, total) = School::list(limit, offset, st.tenants.control()).await?;
338+ let items = schools.iter().map(SchoolResponse::new).collect();
339+ Ok(Json(Page::new(items, total, limit, offset)))
340+}
341+
342+/// One school by slug.
343+#[utoipa::path(
344+ get,
345+ path = "/schools/{slug}",
346+ tag = "builder",
347+ security(("session_cookie" = [])),
348+ params(("slug" = String, Path, description = "School slug")),
349+ responses(
350+ (status = 200, description = "The school", body = SchoolResponse),
351+ (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
352+ (status = 404, description = "No such school", body = ErrorResponse),
353+ ),
354+)]
355+async fn get_school(
356+ State(st): State<AppState>,
357+ RequireBuilder(_builder): RequireBuilder,
358+ Path(slug): Path<String>,
359+) -> Result<Json<SchoolResponse>, AppError> {
360+ let school = School::read(&path_slug(&slug)?, st.tenants.control())
361+ .await?
362+ .ok_or(AppError::NotFound)?;
363+ Ok(Json(SchoolResponse::new(&school)))
364+}
365+
366+/// Rename a school and/or flip it between `active` and `suspended`. Omitted
367+/// fields keep their value. The slug itself is immutable — it names a database
368+/// and a directory.
369+///
370+/// Suspending is immediate and total for the school's own users: their next
371+/// request is a `403`, live session or not.
372+#[utoipa::path(
373+ patch,
374+ path = "/schools/{slug}",
375+ tag = "builder",
376+ security(("session_cookie" = [])),
377+ params(("slug" = String, Path, description = "School slug")),
378+ request_body = UpdateSchool,
379+ responses(
380+ (status = 200, description = "The updated school", body = SchoolResponse),
381+ (status = 400, description = "Invalid name or status", body = ErrorResponse),
382+ (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
383+ (status = 404, description = "No such school", body = ErrorResponse),
384+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
385+ ),
386+)]
387+async fn update_school(
388+ State(st): State<AppState>,
389+ RequireBuilder(_builder): RequireBuilder,
390+ Path(slug): Path<String>,
391+ Json(req): Json<UpdateSchool>,
392+) -> Result<Json<SchoolResponse>, AppError> {
393+ let slug = path_slug(&slug)?;
394+ let name = req.name.as_deref().map(school_name).transpose()?;
395+ let status = req
396+ .status
397+ .as_deref()
398+ .map(SchoolStatus::try_from_str)
399+ .transpose()?;
400+
401+ let control = st.tenants.control();
402+ // An empty patch on an unknown school is still a 404, so the existence
403+ // check is not left to whichever field happened to be present.
404+ School::read(&slug, control).await?.ok_or(AppError::NotFound)?;
405+ if let Some(name) = name {
406+ School::update_name(&slug, &name, control).await?;
407+ }
408+ if let Some(status) = status {
409+ st.tenants.set_status(&slug, status).await?;
410+ }
411+ let school = School::read(&slug, control).await?.ok_or(AppError::NotFound)?;
412+ Ok(Json(SchoolResponse::new(&school)))
413+}
414+
415+/// Delete a school: its database, its registry row, and its uploaded files.
416+/// Irreversible — suspension is the reversible door.
417+#[utoipa::path(
418+ delete,
419+ path = "/schools/{slug}",
420+ tag = "builder",
421+ security(("session_cookie" = [])),
422+ params(("slug" = String, Path, description = "School slug")),
423+ responses(
424+ (status = 204, description = "Deleted"),
425+ (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
426+ (status = 404, description = "No such school", body = ErrorResponse),
427+ ),
428+)]
429+async fn delete_school(
430+ State(st): State<AppState>,
431+ RequireBuilder(_builder): RequireBuilder,
432+ Path(slug): Path<String>,
433+) -> Result<StatusCode, AppError> {
434+ let slug = path_slug(&slug)?;
435+ School::read(&slug, st.tenants.control())
436+ .await?
437+ .ok_or(AppError::NotFound)?;
438+ st.tenants.drop(&slug).await?;
439+
440+ // Rows first, bytes second — the same order every blob delete here keeps, so
441+ // a crash between them strands unreachable files rather than rows pointing
442+ // at nothing. The directory is built from the validated `Slug`, never from
443+ // the raw path segment.
444+ let dir = school_files_path(&st.files_path, &slug);
445+ if let Err(err) = tokio::fs::remove_dir_all(&dir).await
446+ && err.kind() != std::io::ErrorKind::NotFound
447+ {
448+ tracing::warn!("failed to remove the files of {slug} at {}: {err}", dir.display());
449+ }
450+ Ok(StatusCode::NO_CONTENT)
451+}
452+
453+/// Reset an admin's password inside a school — the "we are locked out" call.
454+/// Every session that account held is revoked with it, so a stolen cookie does
455+/// not survive the reset. Works on a suspended school.
456+#[utoipa::path(
457+ post,
458+ path = "/schools/{slug}/admin-password",
459+ tag = "builder",
460+ security(("session_cookie" = [])),
461+ params(("slug" = String, Path, description = "School slug")),
462+ request_body = AdminPassword,
463+ responses(
464+ (status = 204, description = "Password reset; that account's sessions are revoked"),
465+ (status = 400, description = "Invalid password", body = ErrorResponse),
466+ (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
467+ (status = 404, description = "No such school, or no such account in it", body = ErrorResponse),
468+ (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse),
469+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
470+ ),
471+)]
472+async fn reset_admin_password(
473+ State(st): State<AppState>,
474+ RequireBuilder(_builder): RequireBuilder,
475+ Path(slug): Path<String>,
476+ Json(req): Json<AdminPassword>,
477+) -> Result<StatusCode, AppError> {
478+ let slug = path_slug(&slug)?;
479+ // `get_any_status`, not `get`: a lockout is exactly the situation a school
480+ // may be suspended in, and the vendor must still be able to fix it.
481+ let (db, _status) = st.tenants.get_any_status(&slug).await?;
482+ let user = school_admin(&req.username, &db).await?;
483+ let password_hash = Password::try_new(&req.password)?.hash_async().await?;
484+
485+ User::set_password_hash(user.get_id(), password_hash, &db)
486+ .await?
487+ .ok_or(AppError::NotFound)?;
488+ // The other half: the new password means nothing while a cookie minted
489+ // under the old one still authenticates.
490+ Session::delete_by_user(user.get_id(), &db).await?;
491+ Ok(StatusCode::NO_CONTENT)
492+}
493+
494+/// Enter a school as one of its admins — support access, with the school's own
495+/// session cookie (`<slug>.<token>`) and no builder power inside it.
496+///
497+/// Refused on a suspended school (`403`): a suspension closes the school's
498+/// doors, and this is one of them. Un-suspend it first.
499+#[utoipa::path(
500+ post,
501+ path = "/schools/{slug}/enter",
502+ tag = "builder",
503+ security(("session_cookie" = [])),
504+ params(("slug" = String, Path, description = "School slug")),
505+ request_body = EnterSchool,
506+ responses(
507+ (status = 200, description = "Entered; that school's session cookie is set", body = UserResponse),
508+ (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
509+ (status = 403, description = "The school is suspended", body = ErrorResponse),
510+ (status = 404, description = "No such school, or no such account in it", body = ErrorResponse),
511+ (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse),
512+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
513+ ),
514+)]
515+async fn enter_school(
516+ State(st): State<AppState>,
517+ RequireBuilder(_builder): RequireBuilder,
518+ jar: CookieJar,
519+ Path(slug): Path<String>,
520+ Json(req): Json<EnterSchool>,
521+) -> Result<(CookieJar, Json<UserResponse>), AppError> {
522+ let slug = path_slug(&slug)?;
523+ let (db, status) = st.tenants.get_any_status(&slug).await?;
524+ if status == SchoolStatus::Suspended {
525+ return Err(AppError::Forbidden("school is suspended"));
526+ }
527+ let user = school_admin(&req.username, &db).await?;
528+
529+ let session = Session::create(user.get_id(), &db).await?;
530+ let cookie = session_cookie(
531+ format!("{slug}.{}", session.token().as_str()),
532+ st.cookie_secure,
533+ );
534+ Ok((jar.add(cookie), Json(UserResponse::new(&user))))
535+}
src/web/limits.rsmodified+3 -0
@@ -37,6 +37,8 @@ struct UserLimits {
3737 /// Slugs no school may take — they name the builder cookie prefix and the
3838 /// control database.
3939 reserved_slugs: Vec<&'static str>,
40+ /// A school's display name, set by the vendor when the school is created.
41+ max_school_name_len: usize,
4042 min_username_len: usize,
4143 max_username_len: usize,
4244 /// Separators allowed inside a username — never at the edges, never doubled.
@@ -473,6 +475,7 @@ impl LimitsResponse {
473475 min_slug_len: MIN_SLUG_LEN,
474476 max_slug_len: MAX_SLUG_LEN,
475477 reserved_slugs: crate::tenant::RESERVED_SLUGS.to_vec(),
478+ max_school_name_len: MAX_SCHOOL_NAME_LEN,
476479 min_username_len: MIN_USERNAME_LEN,
477480 max_username_len: MAX_USERNAME_LEN,
478481 username_separators: USERNAME_SEPARATORS.iter().map(char::to_string).collect(),
src/web/mod.rsmodified+1 -0
@@ -10,6 +10,7 @@ pub mod auth;
1010 pub mod bank_questions;
1111 pub mod board_ws;
1212 pub mod boards;
13+pub mod builder;
1314 pub mod chatbot;
1415 pub mod classes;
1516 pub mod course_notes;
tests/builder_api.rsadded+592 -0
@@ -0,0 +1,592 @@
1+//! The vendor surface (`web::builder`): the one principal that is not a user of
2+//! any school. Everything here is about the line between the two — a builder
3+//! cookie must never act inside a school, a school cookie must never manage
4+//! schools, and a session minted by `enter` must act in exactly one school.
5+
6+mod common;
7+
8+use axum::Router;
9+use axum::http::StatusCode;
10+use common::*;
11+use hezarfen_backend::domain::builder::Builder;
12+use hezarfen_backend::domain::user::{Password, Username};
13+use hezarfen_backend::tenant::{DEMO_SLUG, Tenants};
14+use serde_json::{Value, json};
15+
16+const BUILDER_USER: &str = "operator";
17+const BUILDER_PASS: &str = "secret1";
18+
19+/// A deployment with the demo school, plus a builder account to drive it —
20+/// production's `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed, by the same path.
21+async fn deployment() -> (Router, hezarfen_backend::database::Database, Tenants) {
22+ let (app, db, tenants) = app_and_tenants().await;
23+ Builder::ensure(
24+ Username::try_new(BUILDER_USER).unwrap(),
25+ Password::try_new(BUILDER_PASS).unwrap(),
26+ tenants.control(),
27+ )
28+ .await
29+ .expect("seed the builder");
30+ (app, db, tenants)
31+}
32+
33+async fn builder_login(app: &Router) -> String {
34+ let res = send(
35+ app,
36+ "POST",
37+ "/builder/login",
38+ None,
39+ Some(json!({ "username": BUILDER_USER, "password": BUILDER_PASS })),
40+ )
41+ .await;
42+ assert_eq!(res.status, StatusCode::OK, "builder login: {:?}", res.body);
43+ res.cookie.expect("builder cookie set on login")
44+}
45+
46+/// Create a school as the builder (no assertion) — slug, name, first admin.
47+async fn create_school(app: &Router, cookie: &str, slug: &str, admin_pass: &str) -> Res {
48+ send(
49+ app,
50+ "POST",
51+ "/schools",
52+ Some(cookie),
53+ Some(json!({
54+ "slug": slug,
55+ "name": format!("{slug} school"),
56+ "admin_username": "admin",
57+ "admin_password": admin_pass,
58+ })),
59+ )
60+ .await
61+}
62+
63+async fn school_login(app: &Router, slug: &str, username: &str, password: &str) -> Res {
64+ send(
65+ app,
66+ "POST",
67+ "/auth/login",
68+ None,
69+ Some(json!({ "school": slug, "username": username, "password": password })),
70+ )
71+ .await
72+}
73+
74+fn slugs(body: &Value) -> Vec<String> {
75+ items(body)
76+ .iter()
77+ .map(|item| item["slug"].as_str().expect("slug").to_string())
78+ .collect()
79+}
80+
81+/// The two cookies share a name and nothing else. This is the whole point of
82+/// the split: neither principal may ever be accepted where the other belongs.
83+#[tokio::test]
84+async fn a_builder_logs_in_and_its_cookie_works_here_and_nowhere_else() {
85+ let (app, _db, _tenants) = deployment().await;
86+ let builder = builder_login(&app).await;
87+
88+ let me = send(&app, "GET", "/builder/me", Some(&builder), None).await;
89+ assert_eq!(me.status, StatusCode::OK);
90+ assert_eq!(me.body["username"], BUILDER_USER);
91+ assert!(me.body["id"].as_str().is_some_and(|id| !id.is_empty()));
92+
93+ // A school user's cookie is not a builder's…
94+ let student = login(&app, "ali").await;
95+ assert_eq!(
96+ send(&app, "GET", "/builder/me", Some(&student), None)
97+ .await
98+ .status,
99+ StatusCode::UNAUTHORIZED,
100+ "a school cookie reached the builder surface"
101+ );
102+ assert_eq!(
103+ send(&app, "GET", "/schools", Some(&student), None)
104+ .await
105+ .status,
106+ StatusCode::UNAUTHORIZED
107+ );
108+ // …and a builder's is not a school user's.
109+ assert_eq!(
110+ send(&app, "GET", "/auth/me", Some(&builder), None)
111+ .await
112+ .status,
113+ StatusCode::UNAUTHORIZED,
114+ "a builder cookie reached a school surface"
115+ );
116+
117+ // Bad credentials, both shapes.
118+ for bad in [
119+ json!({ "username": BUILDER_USER, "password": "wrongpass" }),
120+ json!({ "username": "ghost", "password": BUILDER_PASS }),
121+ ] {
122+ assert_eq!(
123+ send(&app, "POST", "/builder/login", None, Some(bad))
124+ .await
125+ .status,
126+ StatusCode::UNAUTHORIZED
127+ );
128+ }
129+
130+ let out = send(&app, "POST", "/builder/logout", Some(&builder), None).await;
131+ assert_eq!(out.status, StatusCode::NO_CONTENT);
132+ assert_eq!(
133+ send(&app, "GET", "/builder/me", Some(&builder), None)
134+ .await
135+ .status,
136+ StatusCode::UNAUTHORIZED,
137+ "logout must revoke the session, not just clear the cookie"
138+ );
139+}
140+
141+/// One call brings a whole school into being: registry row, database, schema,
142+/// and an admin who can actually log into it.
143+#[tokio::test]
144+async fn creating_a_school_seeds_an_admin_who_can_log_in() {
145+ let (app, _db, _tenants) = deployment().await;
146+ let builder = builder_login(&app).await;
147+
148+ let created = create_school(&app, &builder, "ata-koleji", "secret1").await;
149+ assert_eq!(
150+ created.status,
151+ StatusCode::CREATED,
152+ "create school: {:?}",
153+ created.body
154+ );
155+ assert_eq!(created.body["slug"], "ata-koleji");
156+ assert_eq!(created.body["status"], "active");
157+
158+ let login = school_login(&app, "ata-koleji", "admin", "secret1").await;
159+ assert_eq!(login.status, StatusCode::OK, "seeded admin logs in");
160+ let cookie = login.cookie.expect("school cookie");
161+ assert!(
162+ cookie.starts_with("session=ata-koleji."),
163+ "the cookie names its school: {cookie}"
164+ );
165+ let me = send(&app, "GET", "/auth/me", Some(&cookie), None).await;
166+ assert_eq!(me.status, StatusCode::OK);
167+ assert_eq!(me.body["role"], "admin", "the seed is an admin, not a student");
168+
169+ // The slug is the identity: a second school may not take it.
170+ assert_eq!(
171+ create_school(&app, &builder, "ata-koleji", "secret1")
172+ .await
173+ .status,
174+ StatusCode::CONFLICT
175+ );
176+
177+ // Anything that is not a slug is refused before a database exists — the
178+ // reserved words most of all, since they name the builder cookie prefix and
179+ // the control database itself.
180+ for bad in ["control", "builder", "Ab", "a", &"x".repeat(33), "../x"] {
181+ let res = create_school(&app, &builder, bad, "secret1").await;
182+ assert_eq!(
183+ res.status,
184+ StatusCode::BAD_REQUEST,
185+ "slug {bad:?} was not refused: {:?}",
186+ res.body
187+ );
188+ // …and nothing was left behind by the refusal.
189+ assert_eq!(
190+ send(&app, "GET", &format!("/schools/{bad}"), Some(&builder), None)
191+ .await
192+ .status,
193+ StatusCode::NOT_FOUND,
194+ "slug {bad:?} left a school behind"
195+ );
196+ }
197+ // A blank name and a too-short admin password are refused the same way.
198+ for body in [
199+ json!({ "slug": "yeni", "name": " ", "admin_username": "admin", "admin_password": "secret1" }),
200+ json!({ "slug": "yeni", "name": "Yeni", "admin_username": "admin", "admin_password": "x" }),
201+ ] {
202+ assert_eq!(
203+ send(&app, "POST", "/schools", Some(&builder), Some(body))
204+ .await
205+ .status,
206+ StatusCode::BAD_REQUEST
207+ );
208+ }
209+ assert_eq!(
210+ school_login(&app, "yeni", "admin", "secret1").await.status,
211+ StatusCode::UNAUTHORIZED,
212+ "a refused create must not have made a school"
213+ );
214+}
215+
216+/// Listing, reading and patching the registry — and the suspension that closes
217+/// a school to its own users while the builder keeps managing it.
218+#[tokio::test]
219+async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
220+ let (app, _db, _tenants) = deployment().await;
221+ let builder = builder_login(&app).await;
222+ assert_eq!(
223+ create_school(&app, &builder, "beta", "secret1").await.status,
224+ StatusCode::CREATED
225+ );
226+
227+ let list = send(&app, "GET", "/schools", Some(&builder), None).await;
228+ assert_eq!(list.status, StatusCode::OK);
229+ let listed = slugs(&list.body);
230+ assert!(listed.contains(&DEMO_SLUG.to_string()) && listed.contains(&"beta".to_string()));
231+ assert_eq!(total(&list.body), 2);
232+ // The envelope pages like every other list.
233+ let page = send(&app, "GET", "/schools?limit=1", Some(&builder), None).await;
234+ assert_eq!(items(&page.body).len(), 1);
235+ assert_eq!(total(&page.body), 2);
236+
237+ assert_eq!(
238+ send(&app, "GET", "/schools/ghost", Some(&builder), None)
239+ .await
240+ .status,
241+ StatusCode::NOT_FOUND
242+ );
243+
244+ // A partial patch touches only what it names: the name moves, the status
245+ // and the created stamp stay.
246+ let before = send(&app, "GET", "/schools/beta", Some(&builder), None).await;
247+ let renamed = send(
248+ &app,
249+ "PATCH",
250+ "/schools/beta",
251+ Some(&builder),
252+ Some(json!({ "name": "Beta Koleji" })),
253+ )
254+ .await;
255+ assert_eq!(renamed.status, StatusCode::OK);
256+ assert_eq!(renamed.body["name"], "Beta Koleji");
257+ assert_eq!(renamed.body["status"], "active");
258+ assert_eq!(renamed.body["slug"], "beta");
259+ assert_eq!(renamed.body["created_at"], before.body["created_at"]);
260+ // An empty patch is a no-op read, and a bad status is a 400.
261+ let untouched = send(
262+ &app,
263+ "PATCH",
264+ "/schools/beta",
265+ Some(&builder),
266+ Some(json!({})),
267+ )
268+ .await;
269+ assert_eq!(untouched.body["name"], "Beta Koleji");
270+ assert_eq!(
271+ send(
272+ &app,
273+ "PATCH",
274+ "/schools/beta",
275+ Some(&builder),
276+ Some(json!({ "status": "closed" })),
277+ )
278+ .await
279+ .status,
280+ StatusCode::BAD_REQUEST
281+ );
282+
283+ // A live cookie, taken out before the suspension.
284+ let live = school_login(&app, "beta", "admin", "secret1")
285+ .await
286+ .cookie
287+ .expect("school cookie");
288+ let suspended = send(
289+ &app,
290+ "PATCH",
291+ "/schools/beta",
292+ Some(&builder),
293+ Some(json!({ "status": "suspended" })),
294+ )
295+ .await;
296+ assert_eq!(suspended.status, StatusCode::OK);
297+ assert_eq!(suspended.body["status"], "suspended");
298+
299+ assert_eq!(
300+ school_login(&app, "beta", "admin", "secret1").await.status,
301+ StatusCode::FORBIDDEN,
302+ "a suspended school refuses login"
303+ );
304+ assert_eq!(
305+ send(&app, "GET", "/auth/me", Some(&live), None).await.status,
306+ StatusCode::FORBIDDEN,
307+ "…and the cookie it had already issued, on its very next call"
308+ );
309+ // The builder still manages it — that is how it gets un-suspended.
310+ assert_eq!(
311+ send(&app, "GET", "/schools/beta", Some(&builder), None)
312+ .await
313+ .status,
314+ StatusCode::OK
315+ );
316+ // …except entering it, the one door a suspension must also close.
317+ assert_eq!(
318+ send(
319+ &app,
320+ "POST",
321+ "/schools/beta/enter",
322+ Some(&builder),
323+ Some(json!({ "username": "admin" })),
324+ )
325+ .await
326+ .status,
327+ StatusCode::FORBIDDEN
328+ );
329+
330+ send(
331+ &app,
332+ "PATCH",
333+ "/schools/beta",
334+ Some(&builder),
335+ Some(json!({ "status": "active" })),
336+ )
337+ .await;
338+ assert_eq!(
339+ send(&app, "GET", "/auth/me", Some(&live), None).await.status,
340+ StatusCode::OK,
341+ "resuming restores the very same session"
342+ );
343+}
344+
345+/// The lockout fix: re-key an admin, and take every session minted under the
346+/// old password with it.
347+#[tokio::test]
348+async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions() {
349+ let (app, _db, _tenants) = deployment().await;
350+ let builder = builder_login(&app).await;
351+ create_school(&app, &builder, "gamma", "secret1").await;
352+ let old_cookie = school_login(&app, "gamma", "admin", "secret1")
353+ .await
354+ .cookie
355+ .expect("school cookie");
356+
357+ // An account that is not an admin of that school, and one that is not there
358+ // at all, are told apart.
359+ assert_eq!(
360+ send(
361+ &app,
362+ "POST",
363+ "/schools/gamma/admin-password",
364+ Some(&builder),
365+ Some(json!({ "username": "ghost", "password": "secret2" })),
366+ )
367+ .await
368+ .status,
369+ StatusCode::NOT_FOUND
370+ );
371+ let gamma_db = _tenants
372+ .get(&hezarfen_backend::tenant::Slug::try_new("gamma").unwrap())
373+ .await
374+ .unwrap();
375+ hezarfen_backend::domain::user::User::create(
376+ Username::try_new("veli").unwrap(),
377+ Password::try_new("secret1").unwrap().hash_async().await.unwrap(),
378+ &gamma_db,
379+ )
380+ .await
381+ .unwrap();
382+ assert_eq!(
383+ send(
384+ &app,
385+ "POST",
386+ "/schools/gamma/admin-password",
387+ Some(&builder),
388+ Some(json!({ "username": "veli", "password": "secret2" })),
389+ )
390+ .await
391+ .status,
392+ StatusCode::CONFLICT,
393+ "a student is not the school's admin"
394+ );
395+
396+ let reset = send(
397+ &app,
398+ "POST",
399+ "/schools/gamma/admin-password",
400+ Some(&builder),
401+ Some(json!({ "username": "admin", "password": "secret2" })),
402+ )
403+ .await;
404+ assert_eq!(reset.status, StatusCode::NO_CONTENT);
405+
406+ assert_eq!(
407+ school_login(&app, "gamma", "admin", "secret1").await.status,
408+ StatusCode::UNAUTHORIZED,
409+ "the old password must be dead"
410+ );
411+ assert_eq!(
412+ school_login(&app, "gamma", "admin", "secret2").await.status,
413+ StatusCode::OK
414+ );
415+ assert_eq!(
416+ send(&app, "GET", "/auth/me", Some(&old_cookie), None)
417+ .await
418+ .status,
419+ StatusCode::UNAUTHORIZED,
420+ "a reset that leaves the old cookie working resets nothing"
421+ );
422+}
423+
424+/// `enter` mints an ordinary school session: full admin power inside that
425+/// school, none at all in the school next door.
426+#[tokio::test]
427+async fn entering_a_school_acts_in_that_school_and_no_other() {
428+ let (app, _db, _tenants) = deployment().await;
429+ let builder = builder_login(&app).await;
430+ create_school(&app, &builder, "alpha", "secret1").await;
431+ create_school(&app, &builder, "beta", "secret1").await;
432+
433+ let entered = send(
434+ &app,
435+ "POST",
436+ "/schools/alpha/enter",
437+ Some(&builder),
438+ Some(json!({ "username": "admin" })),
439+ )
440+ .await;
441+ assert_eq!(entered.status, StatusCode::OK, "enter: {:?}", entered.body);
442+ assert_eq!(entered.body["username"], "admin");
443+ assert_eq!(entered.body["role"], "admin");
444+ let alpha = entered.cookie.expect("a school cookie");
445+ assert!(alpha.starts_with("session=alpha."), "{alpha}");
446+
447+ // It is an ordinary school session — and only a school session.
448+ let me = send(&app, "GET", "/auth/me", Some(&alpha), None).await;
449+ assert_eq!(me.status, StatusCode::OK);
450+ assert_eq!(me.body["role"], "admin");
451+ assert_eq!(
452+ send(&app, "GET", "/builder/me", Some(&alpha), None)
453+ .await
454+ .status,
455+ StatusCode::UNAUTHORIZED,
456+ "entering a school must not hand back builder power"
457+ );
458+
459+ // A row written in alpha is invisible from beta — the isolation the whole
460+ // per-school database exists for.
461+ let note = send(
462+ &app,
463+ "POST",
464+ "/notes",
465+ Some(&alpha),
466+ Some(json!({ "title": "alpha only", "content": "mine" })),
467+ )
468+ .await;
469+ assert_eq!(note.status, StatusCode::CREATED);
470+ let note_id = id_of(&note.body);
471+ let beta = send(
472+ &app,
473+ "POST",
474+ "/schools/beta/enter",
475+ Some(&builder),
476+ Some(json!({ "username": "admin" })),
477+ )
478+ .await
479+ .cookie
480+ .expect("beta cookie");
481+ assert_eq!(
482+ send(&app, "GET", &format!("/notes/{note_id}"), Some(&beta), None)
483+ .await
484+ .status,
485+ StatusCode::NOT_FOUND,
486+ "a note written in alpha was reachable under beta's cookie"
487+ );
488+
489+ // Unknown school, unknown account, non-admin account.
490+ assert_eq!(
491+ send(
492+ &app,
493+ "POST",
494+ "/schools/ghost/enter",
495+ Some(&builder),
496+ Some(json!({ "username": "admin" })),
497+ )
498+ .await
499+ .status,
500+ StatusCode::NOT_FOUND
501+ );
502+ assert_eq!(
503+ send(
504+ &app,
505+ "POST",
506+ "/schools/alpha/enter",
507+ Some(&builder),
508+ Some(json!({ "username": "nobody" })),
509+ )
510+ .await
511+ .status,
512+ StatusCode::NOT_FOUND
513+ );
514+}
515+
516+/// Deleting a school takes its rows *and* its bytes — and only its own.
517+#[tokio::test]
518+async fn deleting_a_school_takes_its_data_and_its_files() {
519+ let (app, _db, _tenants) = deployment().await;
520+ let builder = builder_login(&app).await;
521+ create_school(&app, &builder, "delta", "secret1").await;
522+ create_school(&app, &builder, "epsilon", "secret1").await;
523+
524+ // A note with a file in each school, so the delete has bytes to take.
525+ let mut blobs = Vec::new();
526+ for slug in ["delta", "epsilon"] {
527+ let cookie = school_login(&app, slug, "admin", "secret1")
528+ .await
529+ .cookie
530+ .expect("school cookie");
531+ let note = send(
532+ &app,
533+ "POST",
534+ "/notes",
535+ Some(&cookie),
536+ Some(json!({ "title": "with a file", "content": "x" })),
537+ )
538+ .await;
539+ assert_eq!(note.status, StatusCode::CREATED);
540+ let up = upload_file(
541+ &app,
542+ &cookie,
543+ &id_of(&note.body),
544+ "plan.pdf",
545+ "application/pdf",
546+ b"bytes",
547+ )
548+ .await;
549+ assert_eq!(up.status, StatusCode::CREATED, "upload: {:?}", up.body);
550+ // One directory per school under `FILES_PATH`, named by the slug.
551+ let blob = files_dir().join(slug).join(id_of(&up.body));
552+ assert!(blob.exists(), "{} should exist", blob.display());
553+ blobs.push(blob);
554+ }
555+
556+ let deleted = send(&app, "DELETE", "/schools/delta", Some(&builder), None).await;
557+ assert_eq!(deleted.status, StatusCode::NO_CONTENT);
558+
559+ assert_eq!(
560+ send(&app, "GET", "/schools/delta", Some(&builder), None)
561+ .await
562+ .status,
563+ StatusCode::NOT_FOUND
564+ );
565+ assert_eq!(
566+ school_login(&app, "delta", "admin", "secret1").await.status,
567+ StatusCode::UNAUTHORIZED,
568+ "a deleted school is an unknown school, never a 403"
569+ );
570+ assert!(
571+ !files_dir().join("delta").exists(),
572+ "the school's files subtree must be gone"
573+ );
574+ assert!(
575+ blobs[1].exists(),
576+ "the school next door must keep every byte it owns"
577+ );
578+ // Its neighbour is untouched all the way through the API.
579+ assert_eq!(
580+ school_login(&app, "epsilon", "admin", "secret1")
581+ .await
582+ .status,
583+ StatusCode::OK
584+ );
585+ // Deleting it again is a 404, not a second destruction.
586+ assert_eq!(
587+ send(&app, "DELETE", "/schools/delta", Some(&builder), None)
588+ .await
589+ .status,
590+ StatusCode::NOT_FOUND
591+ );
592+}
tests/doc_sync.rsmodified+3 -0
@@ -96,6 +96,9 @@ fn attr_str<'a>(attr: &'a str, key: &str) -> Option<&'a str> {
9696 /// ("any logged-in user").
9797 fn extractor_floor(params: &str) -> &'static str {
9898 for (ty, role) in [
99+ // Not a school role at all: the deployment's vendor, whose cookie is
100+ // `401` on every school surface (see `web::builder`).
101+ ("RequireBuilder", "builder"),
99102 ("RequireAdmin", "admin"),
100103 ("RequireManager", "manager"),
101104 ("RequireTeacher", "teacher"),
tests/e2e.rsmodified+76 -0
@@ -25,6 +25,16 @@ async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (St
2525 .get(&Slug::try_new(DEMO_SLUG).unwrap())
2626 .await
2727 .expect("the demo school");
28+ // The deployment's operator, seeded exactly as `main` does from
29+ // `BUILDER_USERNAME`/`BUILDER_PASSWORD`, so the vendor surface is drivable
30+ // over real TCP here too.
31+ hezarfen_backend::domain::builder::Builder::ensure(
32+ hezarfen_backend::domain::user::Username::try_new("operator").unwrap(),
33+ hezarfen_backend::domain::user::Password::try_new("secret1").unwrap(),
34+ tenants.control(),
35+ )
36+ .await
37+ .expect("seed the builder");
2838 let app = build_router(AppState {
2939 db: tenants.control().clone(),
3040 tenants,
@@ -3689,3 +3699,69 @@ async fn a_manager_archived_year_refuses_every_write_and_answers_every_read() {
36893699 );
36903700 }
36913701 }
3702+
3703+/// The vendor surface over real TCP, with a browser's cookie jar: the builder
3704+/// logs in, brings a school into being, and the admin that call seeded logs
3705+/// into it — the whole onboarding path, end to end.
3706+#[tokio::test]
3707+async fn a_builder_creates_a_school_over_tcp_and_its_admin_logs_in() {
3708+ let (base, _db) = spawn_server().await;
3709+ let vendor = client();
3710+
3711+ let res = vendor
3712+ .post(format!("{base}/builder/login"))
3713+ .json(&json!({ "username": "operator", "password": "secret1" }))
3714+ .send()
3715+ .await
3716+ .unwrap();
3717+ assert_eq!(res.status(), StatusCode::OK);
3718+ assert_eq!(res.json::<Value>().await.unwrap()["username"], "operator");
3719+
3720+ let res = vendor
3721+ .post(format!("{base}/schools"))
3722+ .json(&json!({
3723+ "slug": "tcp-koleji",
3724+ "name": "TCP Koleji",
3725+ "admin_username": "admin",
3726+ "admin_password": "secret1",
3727+ }))
3728+ .send()
3729+ .await
3730+ .unwrap();
3731+ assert_eq!(res.status(), StatusCode::CREATED);
3732+ let school = res.json::<Value>().await.unwrap();
3733+ assert_eq!(school["slug"], "tcp-koleji");
3734+ assert_eq!(school["status"], "active");
3735+
3736+ // A separate jar: the school admin is a different principal on the wire.
3737+ let admin = client();
3738+ let res = admin
3739+ .post(format!("{base}/auth/login"))
3740+ .json(&json!({ "school": "tcp-koleji", "username": "admin", "password": "secret1" }))
3741+ .send()
3742+ .await
3743+ .unwrap();
3744+ assert_eq!(res.status(), StatusCode::OK, "the seeded admin logs in");
3745+
3746+ let me = admin
3747+ .get(format!("{base}/auth/me"))
3748+ .send()
3749+ .await
3750+ .unwrap()
3751+ .json::<Value>()
3752+ .await
3753+ .unwrap();
3754+ assert_eq!(me["username"], "admin");
3755+ assert_eq!(me["role"], "admin");
3756+
3757+ // The builder's own cookie is not a school cookie, over TCP either.
3758+ assert_eq!(
3759+ vendor
3760+ .get(format!("{base}/auth/me"))
3761+ .send()
3762+ .await
3763+ .unwrap()
3764+ .status(),
3765+ StatusCode::UNAUTHORIZED
3766+ );
3767+}
tests/integration.rsmodified+7 -1
@@ -355,6 +355,12 @@ const PUBLIC: &[(&str, &str)] = &[
355355 // A server certificate is handed to every peer in the TLS handshake, so
356356 // publishing it discloses nothing (see the module doc in `web/ai.rs`).
357357 ("GET", "/ai/certificate"),
358+ // The vendor's own credential endpoint: the door a builder session comes
359+ // out of, behind the same strict per-IP tier `/auth/login` sits behind.
360+ ("POST", "/builder/login"),
361+ // Idempotent, like `/auth/logout`: revokes the builder session if there is
362+ // one, `204` either way.
363+ ("POST", "/builder/logout"),
358364 ];
359365
360366 /// Router paths that carry no OpenAPI operation, so the derived sweep below
@@ -376,7 +382,7 @@ async fn protected_routes_require_session() {
376382 /// Floor on the number of protected operations swept. It only ever goes
377383 /// up: raise it when routes are added. Without it, deleting a route family
378384 /// would delete its own coverage and still pass.
379- const MIN_PROTECTED: usize = 255;
385+ const MIN_PROTECTED: usize = 263;
380386
381387 let app = mem_app().await;
382388 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
tests/rate_limit.rsmodified+6 -3
@@ -681,9 +681,12 @@ async fn every_route_enforces_the_shipped_limit_plus_one() {
681681 for (i, (method, path)) in routes.iter().enumerate() {
682682 // One unique client per route (203.0.x.x is TEST-NET-3).
683683 let ip = format!("203.0.{}.{}", i / 200, (i % 200) + 1);
684- // The strict tier owns the two credential endpoints; everything else
685- // runs into the catch-all api tier.
686- let limit = if path == "/auth/login" || path == "/auth/register" {
684+ // The strict tier owns the credential endpoints — the school's two and
685+ // the vendor's own login, which has a budget of its own so a school's
686+ // brute-forcer cannot spend it; everything else runs into the catch-all
687+ // api tier.
688+ let limit = if ["/auth/login", "/auth/register", "/builder/login"].contains(&path.as_str())
689+ {
687690 DEFAULT_AUTH_RATE_LIMIT
688691 } else {
689692 DEFAULT_API_RATE_LIMIT
tests/spec_bounds.rsmodified+89 -0
@@ -61,6 +61,95 @@ async fn spec() -> Value {
6161 /// a request DTO — the annotation is the promise, this row is the proof.
6262 fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
6363 vec![
64+ // --- builder (the vendor surface) ---
65+ ("CreateSchool", "slug", "minLength", MIN_SLUG_LEN as i64),
66+ ("CreateSchool", "slug", "maxLength", MAX_SLUG_LEN as i64),
67+ ("CreateSchool", "name", "maxLength", MAX_SCHOOL_NAME_LEN as i64),
68+ ("UpdateSchool", "name", "maxLength", MAX_SCHOOL_NAME_LEN as i64),
69+ (
70+ "CreateSchool",
71+ "admin_username",
72+ "minLength",
73+ MIN_USERNAME_LEN as i64,
74+ ),
75+ (
76+ "CreateSchool",
77+ "admin_username",
78+ "maxLength",
79+ MAX_USERNAME_LEN as i64,
80+ ),
81+ (
82+ "CreateSchool",
83+ "admin_password",
84+ "minLength",
85+ MIN_PASSWORD_LEN as i64,
86+ ),
87+ (
88+ "CreateSchool",
89+ "admin_password",
90+ "maxLength",
91+ MAX_PASSWORD_LEN as i64,
92+ ),
93+ (
94+ "BuilderCredentials",
95+ "username",
96+ "minLength",
97+ MIN_USERNAME_LEN as i64,
98+ ),
99+ (
100+ "BuilderCredentials",
101+ "username",
102+ "maxLength",
103+ MAX_USERNAME_LEN as i64,
104+ ),
105+ (
106+ "BuilderCredentials",
107+ "password",
108+ "minLength",
109+ MIN_PASSWORD_LEN as i64,
110+ ),
111+ (
112+ "BuilderCredentials",
113+ "password",
114+ "maxLength",
115+ MAX_PASSWORD_LEN as i64,
116+ ),
117+ (
118+ "AdminPassword",
119+ "username",
120+ "minLength",
121+ MIN_USERNAME_LEN as i64,
122+ ),
123+ (
124+ "AdminPassword",
125+ "username",
126+ "maxLength",
127+ MAX_USERNAME_LEN as i64,
128+ ),
129+ (
130+ "EnterSchool",
131+ "username",
132+ "minLength",
133+ MIN_USERNAME_LEN as i64,
134+ ),
135+ (
136+ "EnterSchool",
137+ "username",
138+ "maxLength",
139+ MAX_USERNAME_LEN as i64,
140+ ),
141+ (
142+ "AdminPassword",
143+ "password",
144+ "minLength",
145+ MIN_PASSWORD_LEN as i64,
146+ ),
147+ (
148+ "AdminPassword",
149+ "password",
150+ "maxLength",
151+ MAX_PASSWORD_LEN as i64,
152+ ),
64153 // --- auth / users / notes / messages ---
65154 ("Credentials", "school", "minLength", MIN_SLUG_LEN as i64),
66155 ("Credentials", "school", "maxLength", MAX_SLUG_LEN as i64),