diff --git a/README.md b/README.md index 297ef0c..f9f37c0 100644 --- a/README.md +++ b/README.md @@ -430,7 +430,7 @@ drift from it**, which is enforced rather than asked for: and fails unless each one is either referenced by `src/web/limits.rs` or listed as a deliberate exclusion *with a reason*. A new constant breaks the suite until someone decides, consciously, whether clients need it. -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 176 published +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 194 published bounds back out of the emitted JSON, and asserts each equals its constant. This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal only** — a `const` there does not compile — so the annotations are @@ -741,7 +741,9 @@ against the SurrealDB server — e.g. ## Endpoints `Auth` is the minimum role; `no` means no session required, `student` means any -logged-in user. +logged-in user. `builder` is not a school role: it means the deployment's +vendor account (see the `builder` tag), whose cookie is refused on every other +endpoint here exactly as a school's cookie is refused on its. A course is a regular taught course (kind `course`, the default), an *etüt* (kind `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. | 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. | | 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. | | 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") | +| POST | `/builder/login` | no | Log in as the deployment's builder. Sets a `session` cookie (`builder.`) that works on this surface and nowhere else. | +| POST | `/builder/logout` | no | Log out a builder: revoke the session (if any) and clear the cookie. Idempotent — answers `204` either way. | +| GET | `/builder/me` | builder | The current builder. | | 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. | | 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). | | 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. | 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. | | 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). | | DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo. Author only, anytime — solutions are never frozen. | +| GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). | +| POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. | +| GET | `/schools/{slug}` | builder | One school by slug. | +| 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. | +| DELETE | `/schools/{slug}` | builder | Delete a school: its database, its registry row, and its uploaded files. Irreversible — suspension is the reversible door. | +| 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. | +| POST | `/schools/{slug}/enter` | builder | Enter a school as one of its admins — support access, with the school's own session cookie (`.`) and no builder power inside it. | | 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. | | PATCH | `/sessions/{id}` | teacher | Update a session. Requires teacher+ with course-management rights. Omitted fields keep their value; an explicit `null` clears `ends_at`. | | DELETE | `/sessions/{id}` | teacher | Delete a session and its roll-call rows. Requires teacher+ with course-management rights. | diff --git a/src/constant.rs b/src/constant.rs index bcb8081..f58afe2 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -11,6 +11,9 @@ use crate::domain::role::Role; pub const MIN_SLUG_LEN: usize = 2; pub const MAX_SLUG_LEN: usize = 32; +/// A school's display name — free text, unlike its slug. +pub const MAX_SCHOOL_NAME_LEN: usize = 120; + pub const MIN_USERNAME_LEN: usize = 3; pub const MAX_USERNAME_LEN: usize = 32; diff --git a/src/domain/session.rs b/src/domain/session.rs index d44bd0d..dc2ba08 100644 --- a/src/domain/session.rs +++ b/src/domain/session.rs @@ -93,6 +93,17 @@ impl Session { Ok(()) } + /// Revoke every session a user holds. The other half of a password reset: + /// the new credential means nothing while a cookie minted under the old one + /// still authenticates. + pub async fn delete_by_user(user: &UserId, db: &Database) -> Result<(), AppError> { + db.query("DELETE session WHERE user = $usr") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(()) + } + /// Delete every session whose expiry is in the past, returning how many were /// removed. Expired sessions are already rejected at auth, but nothing else /// deletes their rows — without this sweep the `session` table grows forever. diff --git a/src/domain/user.rs b/src/domain/user.rs index 4dabec9..15ee0c1 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -370,7 +370,7 @@ impl User { /// or a cancelled future), and the row left behind is an ordinary student /// account that [`User::ensure_admin`] must then refuse to touch — a /// deployment with no admin and no way for a later boot to repair it. - async fn create_with_role( + pub async fn create_with_role( username: Username, password_hash: PasswordHash, role: Role, @@ -892,6 +892,29 @@ impl User { Ok(rows.into_iter().next()) } + /// Replace a user's password hash — the builder's admin-password reset + /// (`POST /schools/{slug}/admin-password`). Only the credential is + /// rewritten; revoking the sessions minted under the old one is the + /// caller's second half + /// ([`crate::domain::session::Session::delete_by_user`]), because a reset + /// that leaves a stolen cookie working resets nothing. + pub async fn set_password_hash( + id: &UserId, + password_hash: PasswordHash, + db: &Database, + ) -> Result, AppError> { + let rows: Vec = write_with_retry( + db, + "UPDATE $u SET password_hash = $hash RETURN AFTER", + &[ + ("u".into(), id.record().into_value()), + ("hash".into(), password_hash.into_value()), + ], + ) + .await?; + Ok(rows.into_iter().next()) + } + /// Write the UI-preference fields the request actually carried. Same /// contract as [`User::set_profile`]: `None` = omitted (not written), /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. diff --git a/src/lib.rs b/src/lib.rs index cb756f9..682a7cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,6 +43,7 @@ use crate::state::AppState; tags( (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"), (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"), + (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."), (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`"), (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"), (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 { .merge(web::limits::routes()) .nest("/ai", web::ai::routes()) .nest("/auth", web::auth::routes(&state)) + .merge(web::builder::routes(&state)) .nest("/chatbot", web::chatbot::routes()) .nest("/users", web::users::routes()) .nest("/notes", web::notes::routes()) diff --git a/src/web/auth.rs b/src/web/auth.rs index 4982d36..5ca561f 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -199,18 +199,29 @@ async fn login( let session = Session::create(user.get_id(), &db).await?; // `.`: the cookie carries the school, so every later request // finds its database without a second lookup path that could disagree. - let cookie = Cookie::build(("session", format!("{school}.{}", session.token().as_str()))) + let cookie = session_cookie( + format!("{school}.{}", session.token().as_str()), + st.cookie_secure, + ); + + Ok((jar.add(cookie), Json(UserResponse::new(&user)))) +} + +/// The `session` cookie, however it was earned. Shared by school login and the +/// builder surface (`web::builder`) so the two can never drift apart on path, +/// flags or lifetime — the value is the only difference between them +/// (`.` against `builder.`). +pub(crate) fn session_cookie(value: String, secure: bool) -> Cookie<'static> { + Cookie::build(("session", value)) .path("/") .http_only(true) - .secure(st.cookie_secure) + .secure(secure) // Lax is part of the CORS defense: it keeps this cookie off cross-site // requests. Before relaxing toward SameSite=None, first make sure // `cors_layer` (lib.rs) can never mirror origins with credentials on. .same_site(SameSite::Lax) .max_age(time::Duration::days(SESSION_DURATION_DAYS)) - .build(); - - Ok((jar.add(cookie), Json(UserResponse::new(&user)))) + .build() } /// Log out: revoke the current session (if any) and clear the cookie. diff --git a/src/web/builder.rs b/src/web/builder.rs new file mode 100644 index 0000000..0e12738 --- /dev/null +++ b/src/web/builder.rs @@ -0,0 +1,535 @@ +//! The vendor's surface: the operator who owns the deployment, not anybody's +//! school. Every handler here takes `axum::extract::State` (the **control** +//! database) rather than `web::tenant_state::State`, because these routes are +//! *about* schools instead of inside one — the school a request touches is +//! named in its path and resolved through [`crate::tenant::Tenants`]. +//! +//! The two principals never mix: [`RequireBuilder`] takes only a +//! `builder.` cookie, and that cookie is `401` on every school surface +//! (see `web::tenant_state::resolve_tenant`). `POST /schools/{slug}/enter` is +//! the one bridge, and it does not blur the line — it mints an ordinary school +//! session for an admin account that already exists there. +//! +//! A suspended school is closed to *its users*, not to its vendor: every route +//! here keeps working on one (that is how it gets un-suspended) except `enter`, +//! so "suspended blocks everything" stays true of the school's own doors. + +use axum::Json; +use axum::extract::{Path, Query, Request, State}; +use axum::http::StatusCode; +use axum::middleware::{self, Next}; +use axum_extra::extract::CookieJar; +use axum_extra::extract::cookie::Cookie; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::constant::MAX_SCHOOL_NAME_LEN; +use crate::domain::builder::{Builder, BuilderSession}; +use crate::domain::role::Role; +use crate::domain::session::Session; +use crate::domain::user::{Password, PasswordHash, User, Username}; +use crate::error::{AppError, ErrorResponse}; +use crate::rate_limit::{RateLimitConfig, RateLimiter}; +use crate::state::AppState; +use crate::tenant::{School, SchoolStatus, Slug}; +use crate::validate::validate_required; +use crate::web::tenant_state::school_files_path; + +use super::auth::session_cookie; +use super::{BUILDER_COOKIE_PREFIX, Page, PageParams, RequireBuilder, UserResponse}; + +pub fn routes(state: &AppState) -> OpenApiRouter { + // The builder credential is the most valuable one in the deployment, so its + // login sits behind the same strict per-IP tier `/auth/login` uses — its own + // budget, since a school's brute-forcer must not spend the vendor's. + let rate_limit: &RateLimitConfig = &state.rate_limit; + let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); + limiter.share("builder", state.db.clone(), state.db_up.clone()); + OpenApiRouter::new() + .routes(routes!(builder_login)) + .route_layer(middleware::from_fn(move |req: Request, next: Next| { + let limiter = limiter.clone(); + async move { limiter.enforce(req, next).await } + })) + .routes(routes!(builder_logout)) + .routes(routes!(builder_me)) + .routes(routes!(create_school, list_schools)) + .routes(routes!(get_school, update_school, delete_school)) + .routes(routes!(reset_admin_password)) + .routes(routes!(enter_school)) +} + +#[derive(Deserialize, ToSchema)] +struct BuilderCredentials { + #[schema(example = "operator", min_length = 3, max_length = 32)] + username: String, + #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] + password: String, +} + +/// The operator behind the cookie. Deliberately not [`UserResponse`]: a builder +/// has no role, no profile and no school. +#[derive(Serialize, ToSchema)] +struct BuilderResponse { + id: String, + #[schema(example = "operator")] + username: String, +} + +impl BuilderResponse { + fn new(builder: &Builder) -> Self { + Self { + id: builder.get_id().key().to_string(), + username: builder.get_username().as_str().to_string(), + } + } +} + +#[derive(Serialize, ToSchema)] +struct SchoolResponse { + #[schema(example = "ata-koleji")] + slug: String, + #[schema(example = "Ata Koleji")] + name: String, + /// `active` or `suspended`. A suspended school refuses every one of its own + /// users, login included. + #[schema(example = "active")] + status: String, + /// Registered at, UTC unix-milliseconds. + created_at: i64, +} + +impl SchoolResponse { + fn new(school: &School) -> Self { + Self { + slug: school.slug().as_str().to_string(), + name: school.name().to_string(), + status: school.status().as_str().to_string(), + created_at: school.created_at().as_millis(), + } + } +} + +#[derive(Deserialize, ToSchema)] +struct CreateSchool { + /// Lowercase `a-z`, `0-9` and `-`, starting with a letter or digit. Names + /// the school's database, its blob directory and its cookie prefix, so it + /// is immutable once taken. + #[schema(example = "ata-koleji", min_length = 2, max_length = 32)] + slug: String, + #[schema(example = "Ata Koleji", max_length = 120)] + name: String, + /// The school's first admin, created inside the new school's database. + #[schema(example = "admin", min_length = 3, max_length = 32)] + admin_username: String, + #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] + admin_password: String, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateSchool { + #[schema(example = "Ata Koleji", max_length = 120)] + name: Option, + /// `active` or `suspended`. + #[schema(example = "suspended")] + status: Option, +} + +#[derive(Deserialize, ToSchema)] +struct AdminPassword { + /// The admin account in that school whose password is being reset. + #[schema(example = "admin", min_length = 3, max_length = 32)] + username: String, + #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] + password: String, +} + +#[derive(Deserialize, ToSchema)] +struct EnterSchool { + /// The admin account to enter as. It must already exist in that school. + #[schema(example = "admin", min_length = 3, max_length = 32)] + username: String, +} + +/// A school's display name: free text, unlike its slug. +fn school_name(value: &str) -> Result { + validate_required("name", value, MAX_SCHOOL_NAME_LEN)?; + Ok(value.trim().to_string()) +} + +/// The slug in a path. Anything that is not a slug names no school, so it is +/// the same `404` an unknown one gets — and it never reaches +/// [`school_files_path`], which is exactly why that path is built from a +/// validated [`Slug`] and never from the raw segment. +fn path_slug(raw: &str) -> Result { + Slug::try_new(raw).map_err(|_| AppError::NotFound) +} + +/// The named account in `db`, which must be an admin of that school: unknown → +/// `404` (a builder is authenticated, there is nothing to hide), present but +/// below admin → `409`, the repo's verdict for "the row exists, its state +/// refuses this". +async fn school_admin(username: &str, db: &crate::database::Database) -> Result { + let user = User::find_by_username(username.trim(), db) + .await? + .ok_or(AppError::NotFound)?; + if user.get_role() != Role::Admin { + return Err(AppError::Conflict( + "that account is not an admin of this school", + )); + } + Ok(user) +} + +/// Log in as the deployment's builder. Sets a `session` cookie +/// (`builder.`) that works on this surface and nowhere else. +#[utoipa::path( + post, + path = "/builder/login", + tag = "builder", + request_body = BuilderCredentials, + responses( + (status = 200, description = "Logged in; builder session cookie set", body = BuilderResponse), + (status = 401, description = "Bad credentials", body = ErrorResponse), + (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn builder_login( + State(st): State, + jar: CookieJar, + Json(req): Json, +) -> Result<(CookieJar, Json), AppError> { + let control = st.tenants.control(); + let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; + let builder = match Builder::find_by_username(req.username.trim(), control).await? { + Some(builder) => { + if !builder + .get_password_hash() + .verify_async(&password) + .await + { + return Err(AppError::Unauthorized); + } + builder + } + None => { + // The same decoy hash `/auth/login` runs: a wrong name and a wrong + // password must cost the same, or the reply time enumerates the + // operator accounts. + PasswordHash::verify_decoy_async(&password).await; + return Err(AppError::Unauthorized); + } + }; + + let session = BuilderSession::create(builder.get_id(), control).await?; + let cookie = session_cookie( + format!("{BUILDER_COOKIE_PREFIX}.{}", session.token().as_str()), + st.cookie_secure, + ); + Ok((jar.add(cookie), Json(BuilderResponse::new(&builder)))) +} + +/// Log out a builder: revoke the session (if any) and clear the cookie. +/// Idempotent — answers `204` either way. +#[utoipa::path( + post, + path = "/builder/logout", + tag = "builder", + responses((status = 204, description = "Logged out (no-op without a builder session)")), +)] +async fn builder_logout( + State(st): State, + jar: CookieJar, +) -> Result<(CookieJar, StatusCode), AppError> { + if let Some((BUILDER_COOKIE_PREFIX, token)) = jar + .get("session") + .and_then(|cookie| super::tenant_state::split_cookie(cookie.value())) + { + BuilderSession::delete_by_token(token, st.tenants.control()).await?; + } + let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); + Ok((jar, StatusCode::NO_CONTENT)) +} + +/// The current builder. +#[utoipa::path( + get, + path = "/builder/me", + tag = "builder", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The current builder", body = BuilderResponse), + (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), + ), +)] +async fn builder_me(RequireBuilder(builder): RequireBuilder) -> Json { + Json(BuilderResponse::new(&builder)) +} + +/// Create a school: its registry row, its database, its schema, and its first +/// admin account — one call, or none of it. +#[utoipa::path( + post, + path = "/schools", + tag = "builder", + security(("session_cookie" = [])), + request_body = CreateSchool, + responses( + (status = 201, description = "School created, with its first admin", body = SchoolResponse), + (status = 400, description = "Invalid slug, name, or admin credentials", body = ErrorResponse), + (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), + (status = 409, description = "That slug is already taken", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn create_school( + State(st): State, + RequireBuilder(_builder): RequireBuilder, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + // Everything the request must get right is checked (and the admin password + // hashed) *before* a database is defined, so the ordinary rejection never + // creates anything to clean up. + let slug = Slug::try_new(&req.slug)?; + let name = school_name(&req.name)?; + let username = Username::try_new(&req.admin_username)?; + let password_hash = Password::try_new(&req.admin_password)?.hash_async().await?; + + let db = st.tenants.create(&slug, &name).await?; + if let Err(err) = User::create_with_role(username, password_hash, Role::Admin, &db).await { + // A school nobody can log into is worse than no school: take the + // database back so the very same request can simply be retried. + if let Err(cleanup) = st.tenants.drop(&slug).await { + tracing::error!("failed to drop {slug} after its admin seed failed: {cleanup}"); + } + return Err(err); + } + + let school = School::read(&slug, st.tenants.control()) + .await? + .ok_or_else(|| AppError::Internal("the school vanished as it was created".into()))?; + Ok((StatusCode::CREATED, Json(SchoolResponse::new(&school)))) +} + +/// Every school this deployment serves, newest first. Paged via +/// `?limit=&offset=` (omit `limit` for the full list). +#[utoipa::path( + get, + path = "/schools", + tag = "builder", + security(("session_cookie" = [])), + params(PageParams), + responses( + (status = 200, description = "A page of schools (the full list when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), + ), +)] +async fn list_schools( + State(st): State, + RequireBuilder(_builder): RequireBuilder, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let (schools, total) = School::list(limit, offset, st.tenants.control()).await?; + let items = schools.iter().map(SchoolResponse::new).collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// One school by slug. +#[utoipa::path( + get, + path = "/schools/{slug}", + tag = "builder", + security(("session_cookie" = [])), + params(("slug" = String, Path, description = "School slug")), + responses( + (status = 200, description = "The school", body = SchoolResponse), + (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), + (status = 404, description = "No such school", body = ErrorResponse), + ), +)] +async fn get_school( + State(st): State, + RequireBuilder(_builder): RequireBuilder, + Path(slug): Path, +) -> Result, AppError> { + let school = School::read(&path_slug(&slug)?, st.tenants.control()) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(SchoolResponse::new(&school))) +} + +/// 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. +/// +/// Suspending is immediate and total for the school's own users: their next +/// request is a `403`, live session or not. +#[utoipa::path( + patch, + path = "/schools/{slug}", + tag = "builder", + security(("session_cookie" = [])), + params(("slug" = String, Path, description = "School slug")), + request_body = UpdateSchool, + responses( + (status = 200, description = "The updated school", body = SchoolResponse), + (status = 400, description = "Invalid name or status", body = ErrorResponse), + (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), + (status = 404, description = "No such school", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn update_school( + State(st): State, + RequireBuilder(_builder): RequireBuilder, + Path(slug): Path, + Json(req): Json, +) -> Result, AppError> { + let slug = path_slug(&slug)?; + let name = req.name.as_deref().map(school_name).transpose()?; + let status = req + .status + .as_deref() + .map(SchoolStatus::try_from_str) + .transpose()?; + + let control = st.tenants.control(); + // An empty patch on an unknown school is still a 404, so the existence + // check is not left to whichever field happened to be present. + School::read(&slug, control).await?.ok_or(AppError::NotFound)?; + if let Some(name) = name { + School::update_name(&slug, &name, control).await?; + } + if let Some(status) = status { + st.tenants.set_status(&slug, status).await?; + } + let school = School::read(&slug, control).await?.ok_or(AppError::NotFound)?; + Ok(Json(SchoolResponse::new(&school))) +} + +/// Delete a school: its database, its registry row, and its uploaded files. +/// Irreversible — suspension is the reversible door. +#[utoipa::path( + delete, + path = "/schools/{slug}", + tag = "builder", + security(("session_cookie" = [])), + params(("slug" = String, Path, description = "School slug")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), + (status = 404, description = "No such school", body = ErrorResponse), + ), +)] +async fn delete_school( + State(st): State, + RequireBuilder(_builder): RequireBuilder, + Path(slug): Path, +) -> Result { + let slug = path_slug(&slug)?; + School::read(&slug, st.tenants.control()) + .await? + .ok_or(AppError::NotFound)?; + st.tenants.drop(&slug).await?; + + // Rows first, bytes second — the same order every blob delete here keeps, so + // a crash between them strands unreachable files rather than rows pointing + // at nothing. The directory is built from the validated `Slug`, never from + // the raw path segment. + let dir = school_files_path(&st.files_path, &slug); + if let Err(err) = tokio::fs::remove_dir_all(&dir).await + && err.kind() != std::io::ErrorKind::NotFound + { + tracing::warn!("failed to remove the files of {slug} at {}: {err}", dir.display()); + } + Ok(StatusCode::NO_CONTENT) +} + +/// 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. +#[utoipa::path( + post, + path = "/schools/{slug}/admin-password", + tag = "builder", + security(("session_cookie" = [])), + params(("slug" = String, Path, description = "School slug")), + request_body = AdminPassword, + responses( + (status = 204, description = "Password reset; that account's sessions are revoked"), + (status = 400, description = "Invalid password", body = ErrorResponse), + (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), + (status = 404, description = "No such school, or no such account in it", body = ErrorResponse), + (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn reset_admin_password( + State(st): State, + RequireBuilder(_builder): RequireBuilder, + Path(slug): Path, + Json(req): Json, +) -> Result { + let slug = path_slug(&slug)?; + // `get_any_status`, not `get`: a lockout is exactly the situation a school + // may be suspended in, and the vendor must still be able to fix it. + let (db, _status) = st.tenants.get_any_status(&slug).await?; + let user = school_admin(&req.username, &db).await?; + let password_hash = Password::try_new(&req.password)?.hash_async().await?; + + User::set_password_hash(user.get_id(), password_hash, &db) + .await? + .ok_or(AppError::NotFound)?; + // The other half: the new password means nothing while a cookie minted + // under the old one still authenticates. + Session::delete_by_user(user.get_id(), &db).await?; + Ok(StatusCode::NO_CONTENT) +} + +/// Enter a school as one of its admins — support access, with the school's own +/// session cookie (`.`) and no builder power inside it. +/// +/// Refused on a suspended school (`403`): a suspension closes the school's +/// doors, and this is one of them. Un-suspend it first. +#[utoipa::path( + post, + path = "/schools/{slug}/enter", + tag = "builder", + security(("session_cookie" = [])), + params(("slug" = String, Path, description = "School slug")), + request_body = EnterSchool, + responses( + (status = 200, description = "Entered; that school's session cookie is set", body = UserResponse), + (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), + (status = 403, description = "The school is suspended", body = ErrorResponse), + (status = 404, description = "No such school, or no such account in it", body = ErrorResponse), + (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn enter_school( + State(st): State, + RequireBuilder(_builder): RequireBuilder, + jar: CookieJar, + Path(slug): Path, + Json(req): Json, +) -> Result<(CookieJar, Json), AppError> { + let slug = path_slug(&slug)?; + let (db, status) = st.tenants.get_any_status(&slug).await?; + if status == SchoolStatus::Suspended { + return Err(AppError::Forbidden("school is suspended")); + } + let user = school_admin(&req.username, &db).await?; + + let session = Session::create(user.get_id(), &db).await?; + let cookie = session_cookie( + format!("{slug}.{}", session.token().as_str()), + st.cookie_secure, + ); + Ok((jar.add(cookie), Json(UserResponse::new(&user)))) +} diff --git a/src/web/limits.rs b/src/web/limits.rs index d71acb4..b91a0a4 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -37,6 +37,8 @@ struct UserLimits { /// Slugs no school may take — they name the builder cookie prefix and the /// control database. reserved_slugs: Vec<&'static str>, + /// A school's display name, set by the vendor when the school is created. + max_school_name_len: usize, min_username_len: usize, max_username_len: usize, /// Separators allowed inside a username — never at the edges, never doubled. @@ -473,6 +475,7 @@ impl LimitsResponse { min_slug_len: MIN_SLUG_LEN, max_slug_len: MAX_SLUG_LEN, reserved_slugs: crate::tenant::RESERVED_SLUGS.to_vec(), + max_school_name_len: MAX_SCHOOL_NAME_LEN, min_username_len: MIN_USERNAME_LEN, max_username_len: MAX_USERNAME_LEN, username_separators: USERNAME_SEPARATORS.iter().map(char::to_string).collect(), diff --git a/src/web/mod.rs b/src/web/mod.rs index 788714f..6e20ef2 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -10,6 +10,7 @@ pub mod auth; pub mod bank_questions; pub mod board_ws; pub mod boards; +pub mod builder; pub mod chatbot; pub mod classes; pub mod course_notes; diff --git a/tests/builder_api.rs b/tests/builder_api.rs new file mode 100644 index 0000000..504f4b6 --- /dev/null +++ b/tests/builder_api.rs @@ -0,0 +1,592 @@ +//! The vendor surface (`web::builder`): the one principal that is not a user of +//! any school. Everything here is about the line between the two — a builder +//! cookie must never act inside a school, a school cookie must never manage +//! schools, and a session minted by `enter` must act in exactly one school. + +mod common; + +use axum::Router; +use axum::http::StatusCode; +use common::*; +use hezarfen_backend::domain::builder::Builder; +use hezarfen_backend::domain::user::{Password, Username}; +use hezarfen_backend::tenant::{DEMO_SLUG, Tenants}; +use serde_json::{Value, json}; + +const BUILDER_USER: &str = "operator"; +const BUILDER_PASS: &str = "secret1"; + +/// A deployment with the demo school, plus a builder account to drive it — +/// production's `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed, by the same path. +async fn deployment() -> (Router, hezarfen_backend::database::Database, Tenants) { + let (app, db, tenants) = app_and_tenants().await; + Builder::ensure( + Username::try_new(BUILDER_USER).unwrap(), + Password::try_new(BUILDER_PASS).unwrap(), + tenants.control(), + ) + .await + .expect("seed the builder"); + (app, db, tenants) +} + +async fn builder_login(app: &Router) -> String { + let res = send( + app, + "POST", + "/builder/login", + None, + Some(json!({ "username": BUILDER_USER, "password": BUILDER_PASS })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "builder login: {:?}", res.body); + res.cookie.expect("builder cookie set on login") +} + +/// Create a school as the builder (no assertion) — slug, name, first admin. +async fn create_school(app: &Router, cookie: &str, slug: &str, admin_pass: &str) -> Res { + send( + app, + "POST", + "/schools", + Some(cookie), + Some(json!({ + "slug": slug, + "name": format!("{slug} school"), + "admin_username": "admin", + "admin_password": admin_pass, + })), + ) + .await +} + +async fn school_login(app: &Router, slug: &str, username: &str, password: &str) -> Res { + send( + app, + "POST", + "/auth/login", + None, + Some(json!({ "school": slug, "username": username, "password": password })), + ) + .await +} + +fn slugs(body: &Value) -> Vec { + items(body) + .iter() + .map(|item| item["slug"].as_str().expect("slug").to_string()) + .collect() +} + +/// The two cookies share a name and nothing else. This is the whole point of +/// the split: neither principal may ever be accepted where the other belongs. +#[tokio::test] +async fn a_builder_logs_in_and_its_cookie_works_here_and_nowhere_else() { + let (app, _db, _tenants) = deployment().await; + let builder = builder_login(&app).await; + + let me = send(&app, "GET", "/builder/me", Some(&builder), None).await; + assert_eq!(me.status, StatusCode::OK); + assert_eq!(me.body["username"], BUILDER_USER); + assert!(me.body["id"].as_str().is_some_and(|id| !id.is_empty())); + + // A school user's cookie is not a builder's… + let student = login(&app, "ali").await; + assert_eq!( + send(&app, "GET", "/builder/me", Some(&student), None) + .await + .status, + StatusCode::UNAUTHORIZED, + "a school cookie reached the builder surface" + ); + assert_eq!( + send(&app, "GET", "/schools", Some(&student), None) + .await + .status, + StatusCode::UNAUTHORIZED + ); + // …and a builder's is not a school user's. + assert_eq!( + send(&app, "GET", "/auth/me", Some(&builder), None) + .await + .status, + StatusCode::UNAUTHORIZED, + "a builder cookie reached a school surface" + ); + + // Bad credentials, both shapes. + for bad in [ + json!({ "username": BUILDER_USER, "password": "wrongpass" }), + json!({ "username": "ghost", "password": BUILDER_PASS }), + ] { + assert_eq!( + send(&app, "POST", "/builder/login", None, Some(bad)) + .await + .status, + StatusCode::UNAUTHORIZED + ); + } + + let out = send(&app, "POST", "/builder/logout", Some(&builder), None).await; + assert_eq!(out.status, StatusCode::NO_CONTENT); + assert_eq!( + send(&app, "GET", "/builder/me", Some(&builder), None) + .await + .status, + StatusCode::UNAUTHORIZED, + "logout must revoke the session, not just clear the cookie" + ); +} + +/// One call brings a whole school into being: registry row, database, schema, +/// and an admin who can actually log into it. +#[tokio::test] +async fn creating_a_school_seeds_an_admin_who_can_log_in() { + let (app, _db, _tenants) = deployment().await; + let builder = builder_login(&app).await; + + let created = create_school(&app, &builder, "ata-koleji", "secret1").await; + assert_eq!( + created.status, + StatusCode::CREATED, + "create school: {:?}", + created.body + ); + assert_eq!(created.body["slug"], "ata-koleji"); + assert_eq!(created.body["status"], "active"); + + let login = school_login(&app, "ata-koleji", "admin", "secret1").await; + assert_eq!(login.status, StatusCode::OK, "seeded admin logs in"); + let cookie = login.cookie.expect("school cookie"); + assert!( + cookie.starts_with("session=ata-koleji."), + "the cookie names its school: {cookie}" + ); + let me = send(&app, "GET", "/auth/me", Some(&cookie), None).await; + assert_eq!(me.status, StatusCode::OK); + assert_eq!(me.body["role"], "admin", "the seed is an admin, not a student"); + + // The slug is the identity: a second school may not take it. + assert_eq!( + create_school(&app, &builder, "ata-koleji", "secret1") + .await + .status, + StatusCode::CONFLICT + ); + + // Anything that is not a slug is refused before a database exists — the + // reserved words most of all, since they name the builder cookie prefix and + // the control database itself. + for bad in ["control", "builder", "Ab", "a", &"x".repeat(33), "../x"] { + let res = create_school(&app, &builder, bad, "secret1").await; + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "slug {bad:?} was not refused: {:?}", + res.body + ); + // …and nothing was left behind by the refusal. + assert_eq!( + send(&app, "GET", &format!("/schools/{bad}"), Some(&builder), None) + .await + .status, + StatusCode::NOT_FOUND, + "slug {bad:?} left a school behind" + ); + } + // A blank name and a too-short admin password are refused the same way. + for body in [ + json!({ "slug": "yeni", "name": " ", "admin_username": "admin", "admin_password": "secret1" }), + json!({ "slug": "yeni", "name": "Yeni", "admin_username": "admin", "admin_password": "x" }), + ] { + assert_eq!( + send(&app, "POST", "/schools", Some(&builder), Some(body)) + .await + .status, + StatusCode::BAD_REQUEST + ); + } + assert_eq!( + school_login(&app, "yeni", "admin", "secret1").await.status, + StatusCode::UNAUTHORIZED, + "a refused create must not have made a school" + ); +} + +/// Listing, reading and patching the registry — and the suspension that closes +/// a school to its own users while the builder keeps managing it. +#[tokio::test] +async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { + let (app, _db, _tenants) = deployment().await; + let builder = builder_login(&app).await; + assert_eq!( + create_school(&app, &builder, "beta", "secret1").await.status, + StatusCode::CREATED + ); + + let list = send(&app, "GET", "/schools", Some(&builder), None).await; + assert_eq!(list.status, StatusCode::OK); + let listed = slugs(&list.body); + assert!(listed.contains(&DEMO_SLUG.to_string()) && listed.contains(&"beta".to_string())); + assert_eq!(total(&list.body), 2); + // The envelope pages like every other list. + let page = send(&app, "GET", "/schools?limit=1", Some(&builder), None).await; + assert_eq!(items(&page.body).len(), 1); + assert_eq!(total(&page.body), 2); + + assert_eq!( + send(&app, "GET", "/schools/ghost", Some(&builder), None) + .await + .status, + StatusCode::NOT_FOUND + ); + + // A partial patch touches only what it names: the name moves, the status + // and the created stamp stay. + let before = send(&app, "GET", "/schools/beta", Some(&builder), None).await; + let renamed = send( + &app, + "PATCH", + "/schools/beta", + Some(&builder), + Some(json!({ "name": "Beta Koleji" })), + ) + .await; + assert_eq!(renamed.status, StatusCode::OK); + assert_eq!(renamed.body["name"], "Beta Koleji"); + assert_eq!(renamed.body["status"], "active"); + assert_eq!(renamed.body["slug"], "beta"); + assert_eq!(renamed.body["created_at"], before.body["created_at"]); + // An empty patch is a no-op read, and a bad status is a 400. + let untouched = send( + &app, + "PATCH", + "/schools/beta", + Some(&builder), + Some(json!({})), + ) + .await; + assert_eq!(untouched.body["name"], "Beta Koleji"); + assert_eq!( + send( + &app, + "PATCH", + "/schools/beta", + Some(&builder), + Some(json!({ "status": "closed" })), + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // A live cookie, taken out before the suspension. + let live = school_login(&app, "beta", "admin", "secret1") + .await + .cookie + .expect("school cookie"); + let suspended = send( + &app, + "PATCH", + "/schools/beta", + Some(&builder), + Some(json!({ "status": "suspended" })), + ) + .await; + assert_eq!(suspended.status, StatusCode::OK); + assert_eq!(suspended.body["status"], "suspended"); + + assert_eq!( + school_login(&app, "beta", "admin", "secret1").await.status, + StatusCode::FORBIDDEN, + "a suspended school refuses login" + ); + assert_eq!( + send(&app, "GET", "/auth/me", Some(&live), None).await.status, + StatusCode::FORBIDDEN, + "…and the cookie it had already issued, on its very next call" + ); + // The builder still manages it — that is how it gets un-suspended. + assert_eq!( + send(&app, "GET", "/schools/beta", Some(&builder), None) + .await + .status, + StatusCode::OK + ); + // …except entering it, the one door a suspension must also close. + assert_eq!( + send( + &app, + "POST", + "/schools/beta/enter", + Some(&builder), + Some(json!({ "username": "admin" })), + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + send( + &app, + "PATCH", + "/schools/beta", + Some(&builder), + Some(json!({ "status": "active" })), + ) + .await; + assert_eq!( + send(&app, "GET", "/auth/me", Some(&live), None).await.status, + StatusCode::OK, + "resuming restores the very same session" + ); +} + +/// The lockout fix: re-key an admin, and take every session minted under the +/// old password with it. +#[tokio::test] +async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions() { + let (app, _db, _tenants) = deployment().await; + let builder = builder_login(&app).await; + create_school(&app, &builder, "gamma", "secret1").await; + let old_cookie = school_login(&app, "gamma", "admin", "secret1") + .await + .cookie + .expect("school cookie"); + + // An account that is not an admin of that school, and one that is not there + // at all, are told apart. + assert_eq!( + send( + &app, + "POST", + "/schools/gamma/admin-password", + Some(&builder), + Some(json!({ "username": "ghost", "password": "secret2" })), + ) + .await + .status, + StatusCode::NOT_FOUND + ); + let gamma_db = _tenants + .get(&hezarfen_backend::tenant::Slug::try_new("gamma").unwrap()) + .await + .unwrap(); + hezarfen_backend::domain::user::User::create( + Username::try_new("veli").unwrap(), + Password::try_new("secret1").unwrap().hash_async().await.unwrap(), + &gamma_db, + ) + .await + .unwrap(); + assert_eq!( + send( + &app, + "POST", + "/schools/gamma/admin-password", + Some(&builder), + Some(json!({ "username": "veli", "password": "secret2" })), + ) + .await + .status, + StatusCode::CONFLICT, + "a student is not the school's admin" + ); + + let reset = send( + &app, + "POST", + "/schools/gamma/admin-password", + Some(&builder), + Some(json!({ "username": "admin", "password": "secret2" })), + ) + .await; + assert_eq!(reset.status, StatusCode::NO_CONTENT); + + assert_eq!( + school_login(&app, "gamma", "admin", "secret1").await.status, + StatusCode::UNAUTHORIZED, + "the old password must be dead" + ); + assert_eq!( + school_login(&app, "gamma", "admin", "secret2").await.status, + StatusCode::OK + ); + assert_eq!( + send(&app, "GET", "/auth/me", Some(&old_cookie), None) + .await + .status, + StatusCode::UNAUTHORIZED, + "a reset that leaves the old cookie working resets nothing" + ); +} + +/// `enter` mints an ordinary school session: full admin power inside that +/// school, none at all in the school next door. +#[tokio::test] +async fn entering_a_school_acts_in_that_school_and_no_other() { + let (app, _db, _tenants) = deployment().await; + let builder = builder_login(&app).await; + create_school(&app, &builder, "alpha", "secret1").await; + create_school(&app, &builder, "beta", "secret1").await; + + let entered = send( + &app, + "POST", + "/schools/alpha/enter", + Some(&builder), + Some(json!({ "username": "admin" })), + ) + .await; + assert_eq!(entered.status, StatusCode::OK, "enter: {:?}", entered.body); + assert_eq!(entered.body["username"], "admin"); + assert_eq!(entered.body["role"], "admin"); + let alpha = entered.cookie.expect("a school cookie"); + assert!(alpha.starts_with("session=alpha."), "{alpha}"); + + // It is an ordinary school session — and only a school session. + let me = send(&app, "GET", "/auth/me", Some(&alpha), None).await; + assert_eq!(me.status, StatusCode::OK); + assert_eq!(me.body["role"], "admin"); + assert_eq!( + send(&app, "GET", "/builder/me", Some(&alpha), None) + .await + .status, + StatusCode::UNAUTHORIZED, + "entering a school must not hand back builder power" + ); + + // A row written in alpha is invisible from beta — the isolation the whole + // per-school database exists for. + let note = send( + &app, + "POST", + "/notes", + Some(&alpha), + Some(json!({ "title": "alpha only", "content": "mine" })), + ) + .await; + assert_eq!(note.status, StatusCode::CREATED); + let note_id = id_of(¬e.body); + let beta = send( + &app, + "POST", + "/schools/beta/enter", + Some(&builder), + Some(json!({ "username": "admin" })), + ) + .await + .cookie + .expect("beta cookie"); + assert_eq!( + send(&app, "GET", &format!("/notes/{note_id}"), Some(&beta), None) + .await + .status, + StatusCode::NOT_FOUND, + "a note written in alpha was reachable under beta's cookie" + ); + + // Unknown school, unknown account, non-admin account. + assert_eq!( + send( + &app, + "POST", + "/schools/ghost/enter", + Some(&builder), + Some(json!({ "username": "admin" })), + ) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send( + &app, + "POST", + "/schools/alpha/enter", + Some(&builder), + Some(json!({ "username": "nobody" })), + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +/// Deleting a school takes its rows *and* its bytes — and only its own. +#[tokio::test] +async fn deleting_a_school_takes_its_data_and_its_files() { + let (app, _db, _tenants) = deployment().await; + let builder = builder_login(&app).await; + create_school(&app, &builder, "delta", "secret1").await; + create_school(&app, &builder, "epsilon", "secret1").await; + + // A note with a file in each school, so the delete has bytes to take. + let mut blobs = Vec::new(); + for slug in ["delta", "epsilon"] { + let cookie = school_login(&app, slug, "admin", "secret1") + .await + .cookie + .expect("school cookie"); + let note = send( + &app, + "POST", + "/notes", + Some(&cookie), + Some(json!({ "title": "with a file", "content": "x" })), + ) + .await; + assert_eq!(note.status, StatusCode::CREATED); + let up = upload_file( + &app, + &cookie, + &id_of(¬e.body), + "plan.pdf", + "application/pdf", + b"bytes", + ) + .await; + assert_eq!(up.status, StatusCode::CREATED, "upload: {:?}", up.body); + // One directory per school under `FILES_PATH`, named by the slug. + let blob = files_dir().join(slug).join(id_of(&up.body)); + assert!(blob.exists(), "{} should exist", blob.display()); + blobs.push(blob); + } + + let deleted = send(&app, "DELETE", "/schools/delta", Some(&builder), None).await; + assert_eq!(deleted.status, StatusCode::NO_CONTENT); + + assert_eq!( + send(&app, "GET", "/schools/delta", Some(&builder), None) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + school_login(&app, "delta", "admin", "secret1").await.status, + StatusCode::UNAUTHORIZED, + "a deleted school is an unknown school, never a 403" + ); + assert!( + !files_dir().join("delta").exists(), + "the school's files subtree must be gone" + ); + assert!( + blobs[1].exists(), + "the school next door must keep every byte it owns" + ); + // Its neighbour is untouched all the way through the API. + assert_eq!( + school_login(&app, "epsilon", "admin", "secret1") + .await + .status, + StatusCode::OK + ); + // Deleting it again is a 404, not a second destruction. + assert_eq!( + send(&app, "DELETE", "/schools/delta", Some(&builder), None) + .await + .status, + StatusCode::NOT_FOUND + ); +} diff --git a/tests/doc_sync.rs b/tests/doc_sync.rs index 20d551b..fe4f7e4 100644 --- a/tests/doc_sync.rs +++ b/tests/doc_sync.rs @@ -96,6 +96,9 @@ fn attr_str<'a>(attr: &'a str, key: &str) -> Option<&'a str> { /// ("any logged-in user"). fn extractor_floor(params: &str) -> &'static str { for (ty, role) in [ + // Not a school role at all: the deployment's vendor, whose cookie is + // `401` on every school surface (see `web::builder`). + ("RequireBuilder", "builder"), ("RequireAdmin", "admin"), ("RequireManager", "manager"), ("RequireTeacher", "teacher"), diff --git a/tests/e2e.rs b/tests/e2e.rs index a4d3a87..38bd37c 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -25,6 +25,16 @@ async fn spawn_server_with_ai(ai: Option) -> (St .get(&Slug::try_new(DEMO_SLUG).unwrap()) .await .expect("the demo school"); + // The deployment's operator, seeded exactly as `main` does from + // `BUILDER_USERNAME`/`BUILDER_PASSWORD`, so the vendor surface is drivable + // over real TCP here too. + hezarfen_backend::domain::builder::Builder::ensure( + hezarfen_backend::domain::user::Username::try_new("operator").unwrap(), + hezarfen_backend::domain::user::Password::try_new("secret1").unwrap(), + tenants.control(), + ) + .await + .expect("seed the builder"); let app = build_router(AppState { db: tenants.control().clone(), tenants, @@ -3689,3 +3699,69 @@ async fn a_manager_archived_year_refuses_every_write_and_answers_every_read() { ); } } + +/// The vendor surface over real TCP, with a browser's cookie jar: the builder +/// logs in, brings a school into being, and the admin that call seeded logs +/// into it — the whole onboarding path, end to end. +#[tokio::test] +async fn a_builder_creates_a_school_over_tcp_and_its_admin_logs_in() { + let (base, _db) = spawn_server().await; + let vendor = client(); + + let res = vendor + .post(format!("{base}/builder/login")) + .json(&json!({ "username": "operator", "password": "secret1" })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + assert_eq!(res.json::().await.unwrap()["username"], "operator"); + + let res = vendor + .post(format!("{base}/schools")) + .json(&json!({ + "slug": "tcp-koleji", + "name": "TCP Koleji", + "admin_username": "admin", + "admin_password": "secret1", + })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let school = res.json::().await.unwrap(); + assert_eq!(school["slug"], "tcp-koleji"); + assert_eq!(school["status"], "active"); + + // A separate jar: the school admin is a different principal on the wire. + let admin = client(); + let res = admin + .post(format!("{base}/auth/login")) + .json(&json!({ "school": "tcp-koleji", "username": "admin", "password": "secret1" })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK, "the seeded admin logs in"); + + let me = admin + .get(format!("{base}/auth/me")) + .send() + .await + .unwrap() + .json::() + .await + .unwrap(); + assert_eq!(me["username"], "admin"); + assert_eq!(me["role"], "admin"); + + // The builder's own cookie is not a school cookie, over TCP either. + assert_eq!( + vendor + .get(format!("{base}/auth/me")) + .send() + .await + .unwrap() + .status(), + StatusCode::UNAUTHORIZED + ); +} diff --git a/tests/integration.rs b/tests/integration.rs index 3cb21d1..b6adf0d 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -355,6 +355,12 @@ const PUBLIC: &[(&str, &str)] = &[ // A server certificate is handed to every peer in the TLS handshake, so // publishing it discloses nothing (see the module doc in `web/ai.rs`). ("GET", "/ai/certificate"), + // The vendor's own credential endpoint: the door a builder session comes + // out of, behind the same strict per-IP tier `/auth/login` sits behind. + ("POST", "/builder/login"), + // Idempotent, like `/auth/logout`: revokes the builder session if there is + // one, `204` either way. + ("POST", "/builder/logout"), ]; /// Router paths that carry no OpenAPI operation, so the derived sweep below @@ -376,7 +382,7 @@ async fn protected_routes_require_session() { /// Floor on the number of protected operations swept. It only ever goes /// up: raise it when routes are added. Without it, deleting a route family /// would delete its own coverage and still pass. - const MIN_PROTECTED: usize = 255; + const MIN_PROTECTED: usize = 263; let app = mem_app().await; let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index 615dc48..6c93a77 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -681,9 +681,12 @@ async fn every_route_enforces_the_shipped_limit_plus_one() { for (i, (method, path)) in routes.iter().enumerate() { // One unique client per route (203.0.x.x is TEST-NET-3). let ip = format!("203.0.{}.{}", i / 200, (i % 200) + 1); - // The strict tier owns the two credential endpoints; everything else - // runs into the catch-all api tier. - let limit = if path == "/auth/login" || path == "/auth/register" { + // The strict tier owns the credential endpoints — the school's two and + // the vendor's own login, which has a budget of its own so a school's + // brute-forcer cannot spend it; everything else runs into the catch-all + // api tier. + let limit = if ["/auth/login", "/auth/register", "/builder/login"].contains(&path.as_str()) + { DEFAULT_AUTH_RATE_LIMIT } else { DEFAULT_API_RATE_LIMIT diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 0075c9a..74d0b2a 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -61,6 +61,95 @@ async fn spec() -> Value { /// a request DTO — the annotation is the promise, this row is the proof. fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { vec![ + // --- builder (the vendor surface) --- + ("CreateSchool", "slug", "minLength", MIN_SLUG_LEN as i64), + ("CreateSchool", "slug", "maxLength", MAX_SLUG_LEN as i64), + ("CreateSchool", "name", "maxLength", MAX_SCHOOL_NAME_LEN as i64), + ("UpdateSchool", "name", "maxLength", MAX_SCHOOL_NAME_LEN as i64), + ( + "CreateSchool", + "admin_username", + "minLength", + MIN_USERNAME_LEN as i64, + ), + ( + "CreateSchool", + "admin_username", + "maxLength", + MAX_USERNAME_LEN as i64, + ), + ( + "CreateSchool", + "admin_password", + "minLength", + MIN_PASSWORD_LEN as i64, + ), + ( + "CreateSchool", + "admin_password", + "maxLength", + MAX_PASSWORD_LEN as i64, + ), + ( + "BuilderCredentials", + "username", + "minLength", + MIN_USERNAME_LEN as i64, + ), + ( + "BuilderCredentials", + "username", + "maxLength", + MAX_USERNAME_LEN as i64, + ), + ( + "BuilderCredentials", + "password", + "minLength", + MIN_PASSWORD_LEN as i64, + ), + ( + "BuilderCredentials", + "password", + "maxLength", + MAX_PASSWORD_LEN as i64, + ), + ( + "AdminPassword", + "username", + "minLength", + MIN_USERNAME_LEN as i64, + ), + ( + "AdminPassword", + "username", + "maxLength", + MAX_USERNAME_LEN as i64, + ), + ( + "EnterSchool", + "username", + "minLength", + MIN_USERNAME_LEN as i64, + ), + ( + "EnterSchool", + "username", + "maxLength", + MAX_USERNAME_LEN as i64, + ), + ( + "AdminPassword", + "password", + "minLength", + MIN_PASSWORD_LEN as i64, + ), + ( + "AdminPassword", + "password", + "maxLength", + MAX_PASSWORD_LEN as i64, + ), // --- auth / users / notes / messages --- ("Credentials", "school", "minLength", MIN_SLUG_LEN as i64), ("Credentials", "school", "maxLength", MAX_SLUG_LEN as i64),