forge
Explore
Log in

Don't you dare go Hollow

One database per school behind a control registry

Browse files at this commit

b7dfc0cbbafa37c46c15860077b0ce2a7b0e683bAhmet Kaan GümüşParent: b8069dc
  • feat
    • one database per school behind a control registry
    • login names the school
Show full message
✨ feat: one database per school behind a control registry; login names the school

Namespace `hezarfen` now holds one DATABASE per school (name = slug) plus a
`control` database with the school registry, builder accounts and builder
sessions. `Tenants` keeps one separately-connected handle per school; the
shadow `web::tenant_state::State` resolves the school from the
`<slug>.<token>` cookie so every handler's `st.db` is school-scoped by
construction. `POST /auth/login` / `register` carry `school`; a suspended
school answers 403 everywhere. `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed the
vendor account; the boot admin seed is gone. No customers, no compat shims.

59 changed files +1850 -235

.env.examplemodified+13 -8
@@ -8,9 +8,12 @@ DB_URL=ws://127.0.0.1:8000
88 DB_USER=root
99 DB_PASS=root
1010 DB_NAMESPACE=hezarfen
11-DB_DATABASE=hezarfen
11+# The CONTROL database: the school registry and the builder accounts. Each
12+# school gets a database of its own inside DB_NAMESPACE, named by its slug.
13+DB_DATABASE=control
1214
13-# Directory for uploaded note-file blobs (created at startup).
15+# Directory for uploaded note-file blobs (created at startup). Each school
16+# writes into a subdirectory of it named by its slug.
1417 FILES_PATH=./data/files
1518
1619 # Optional log filter.
@@ -43,12 +46,14 @@ RUST_LOG=info,hezarfen_backend=debug
4346 # trivially bypassed. When off (default), the peer address is used.
4447 # TRUST_PROXY=true
4548
46-# Seed an admin account at startup: if this username doesn't exist yet it is
47-# created with this password and the `admin` role. Both must be set together.
48-# If the username exists as a non-admin, nothing is changed (a warning is
49-# logged) — the seed never promotes or rewrites an existing account.
50-# ADMIN_USERNAME=admin
51-# ADMIN_PASSWORD=admin123
49+# Seed a BUILDER account at startup: the deployment operator who creates,
50+# suspends and drops schools. Not a user of any school and holds no role in
51+# one; its cookie is `builder.<token>` where a school user's is
52+# `<slug>.<token>`. Both must be set together. An existing account with this
53+# username is left exactly as it is — the seed never rewrites a credential, so
54+# changing the password here does not re-key a live builder.
55+# BUILDER_USERNAME=builder
56+# BUILDER_PASSWORD=builder123
5257
5358 # --- AI bridge (QUIC) -------------------------------------------------------
5459 # The AI features run as separate services that dial IN to this backend over
README.mdmodified+18 -6
@@ -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 174 published
433+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 176 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
@@ -844,10 +844,10 @@ window filtering, before paging; negative values are a `400` naming the field.
844844 | PATCH | `/appointments/{id}/reschedule/decline` | student | Refuse the teacher's counter-proposal. The requester's call alone, and it **cancels the booking**: the proposal replaced the time that was asked for, so there is nothing left to fall back to — book another slot instead. The slot frees up, and the original request stays readable as `cancelled` with the refused proposal still on it. Declining is a cancel, so it answers to the same deadline: `409` once the meeting's effective window has started. |
845845 | GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, and a per-course breakdown with attendance rates. |
846846 | GET | `/attendance/{user}` | teacher | Any user's attendance report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every course; a teacher sees the event tallies plus only the roll-call blocks of the target's courses they manage. |
847-| POST | `/auth/login` | no | Log in with username + password. Sets a `session` cookie on success. |
847+| POST | `/auth/login` | no | Log in with school + username + password. Sets a `session` cookie (`<school>.<token>`) on success. |
848848 | POST | `/auth/logout` | no | Log out: revoke the current session (if any) and clear the cookie. Idempotent — no session required; answers `204` either way. |
849849 | GET | `/auth/me` | student | Return the currently authenticated user. |
850-| POST | `/auth/register` | no | Register a new user account: `{username, password}` in, `{username, role}` back (no `id`; new accounts are `student`). Always `201`, even if the name was already taken — see "Auth model". |
850+| POST | `/auth/register` | no | Register a new user account: `{school, username, password}` in, `{username, role}` back (no `id`; new accounts are `student`). Always `201`, even if the name was already taken — see "Auth model". |
851851 | GET | `/bank-questions` | teacher | The bank the caller may see — their own templates plus the ones published to the school (admins see every one), **newest first**. `?subject=` narrows to one origin subject; `?owner=` to one owner (a user id, or `me` for the caller); `?q=` to a case-insensitive fragment of the question text; `?visibility=private\|school` to one shelf — it narrows what the caller may already see and never widens it, so `private` is "my drafts" and `school` the published library. Paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope, where `total` counts every match under the same filters, not just this page. Each item carries the resolved `subject_name`/`owner_name` so a client needn't look them up per row, plus `used_count` — how many exam questions were copied out of that template (one grouped query for the page, not one per row). |
852852 | POST | `/bank-questions` | teacher | Add a template to the bank. Requires teacher+. `subject_id` is origin metadata (any subject — the same-course rule lives at instantiate time), so it need only exist (an unknown subject is a `400`). `choice` templates carry 2–10 `choices` plus `correct` naming one of them by id; `text` templates carry neither. The caller becomes the owner. |
853853 | GET | `/bank-questions/{bid}` | teacher | One template by id. Visible ones only: a `private` template belonging to someone else is a 404, not a 403 — a 403 would confirm it exists. |
@@ -4376,11 +4376,16 @@ src/
43764376 constant.rs validation limits
43774377 validate.rs field validators (used by every newtype's try_new)
43784378 error.rs ValidationError + AppError -> HTTP responses
4379- database.rs SurrealDB server connect (ws) + SCHEMAFULL migration
4379+ database.rs SurrealDB server connect (ws) + SCHEMAFULL migration; init()
4380+ brings up the control database, migrate() a school's
4381+ tenant.rs Slug · SchoolStatus · School · Tenants: one database per
4382+ school inside one namespace, plus the control database that
4383+ registers them (DEMO_SLUG is the in-memory test school)
43804384 migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,
4381- MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them
4385+ MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them,
4386+ and CONTROL_MIGRATION_BATCHES for the control database
43824387 rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier
4383- state.rs AppState { db, files_path, cookie_secure, rate_limit,
4388+ state.rs AppState { db, tenants, files_path, cookie_secure, rate_limit,
43844389 chatbot_limit, exam_presence, board_hub, db_up, ai }
43854390 ai/ QUIC bridge to the out-of-process AI services
43864391 (see "AI bridge (QUIC)"; the HTTP half is web/ai.rs)
@@ -4409,6 +4414,8 @@ src/
44094414 text_fold.rs case- and diacritic-insensitive folding for search, shared by
44104415 the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…)
44114416 session.rs SessionId · SessionToken · Session (7-day expiry)
4417+ builder.rs BuilderId · Builder · BuilderSession: the deployment operator
4418+ who creates and suspends schools, in the control database
44124419 timestamp.rs Timestamp (unix-millisecond instant)
44134420 note.rs NoteId · NoteTitle · NoteContent · Note
44144421 note_file.rs NoteFileId · FileName · FileContentType · NoteFile (metadata row;
@@ -4524,7 +4531,12 @@ src/
45244531 row per homework+user — its existence freezes the submission)
45254532 web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +
45264533 auth extractors
4534+ tenant_state.rs State<AppState>: the shadow of axum's State that resolves the
4535+ caller's school from the `<slug>.<token>` cookie, so every
4536+ handler that imports it is school-scoped by construction
4537+ (TenantExt · SchoolSlug · split_cookie)
45274538 extractor.rs CurrentUser · RequireTeacher · RequireManager · RequireAdmin
4539+ · RequireBuilder (the control-database principal)
45284540 dto.rs shared UserResponse · CourseResponse · ExamResponse · SessionResponse schemas
45294541 exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)
45304542 board_ws.rs the collaborative board room WebSocket (join replay, strokes
src/ai/server.rsmodified+54 -13
@@ -29,9 +29,11 @@ use crate::domain::course_note::CourseNote;
2929 use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId};
3030 use crate::domain::user::{User, UserId};
3131 use crate::state::DbHealth;
32+use crate::tenant::{Slug, Tenants};
3233 use crate::web::blob_path;
3334 use crate::web::courses::can_view_course;
3435 use crate::web::extractor::AiPrincipal;
36+use crate::web::tenant_state::{TenantExt, school_files_path};
3537
3638 /// What the bridge needs to come up.
3739 #[derive(Clone, Debug)]
@@ -48,17 +50,43 @@ pub struct BridgeConfig {
4850 }
4951
5052 /// What an api read needs to be answered: the router to dispatch into, the
51-/// database the acting principal is loaded from, and the liveness flag that
53+/// school the acting principal is loaded from, and the liveness flag that
5254 /// stands in for the HTTP db guard this path bypasses.
5355 struct ApiHandle {
5456 router: axum::Router,
55- db: Database,
57+ tenants: Tenants,
58+ /// The one school this bridge serves.
59+ ///
60+ /// corner-cut: `hab/1` frames carry no school, so the reverse api-read path
61+ /// is pinned to [`crate::tenant::DEMO_SLUG`] — a deployment whose schools
62+ /// are named anything else answers `unavailable` to every service read.
63+ /// The upgrade is `hab/2`: put the school on `Hello`/`ApiRequest` and
64+ /// resolve it per request. Nothing else about the bridge is single-school —
65+ /// the outbound chatbot dispatch never touches a database.
66+ slug: Slug,
5667 db_up: DbHealth,
57- /// Where course-note blobs live, for the byte stream — the same directory
58- /// `GET /course-notes/{id}/files/{file_id}` serves from.
68+ /// Where uploaded blobs live — the deployment root; the school's own
69+ /// directory is [`school_files_path`] of it.
5970 files_path: std::path::PathBuf,
6071 }
6172
73+impl ApiHandle {
74+ /// The school database this bridge reads, or the refusal a service gets.
75+ async fn db(&self) -> Result<Database, (&'static str, String)> {
76+ self.tenants.get(&self.slug).await.map_err(|err| {
77+ (
78+ "unavailable",
79+ format!("the `{}` school is not reachable: {err}", self.slug),
80+ )
81+ })
82+ }
83+
84+ /// That school's blob directory.
85+ fn files_dir(&self) -> std::path::PathBuf {
86+ school_files_path(&self.files_path, &self.slug)
87+ }
88+}
89+
6290 struct Inner {
6391 registry: AiRegistry,
6492 /// Armed once per process by [`crate::build_router`] (see
@@ -240,7 +268,7 @@ impl AiBridge {
240268 pub(crate) fn arm_api(
241269 &self,
242270 router: axum::Router,
243- db: Database,
271+ tenants: Tenants,
244272 db_up: DbHealth,
245273 files_path: std::path::PathBuf,
246274 ) {
@@ -249,7 +277,8 @@ impl AiBridge {
249277 .api
250278 .set(ApiHandle {
251279 router,
252- db,
280+ tenants,
281+ slug: Slug::try_new(crate::tenant::DEMO_SLUG).expect("the demo slug is a slug"),
253282 db_up,
254283 files_path,
255284 })
@@ -468,6 +497,7 @@ async fn open_blob(
468497 "the database socket is down — retry".to_string(),
469498 ));
470499 }
500+ let db = api.db().await?;
471501 let user = principal(api, request.on_behalf_of.as_deref()).await?;
472502
473503 let missing = || {
@@ -477,19 +507,19 @@ async fn open_blob(
477507 )
478508 };
479509 let unavailable = |e: crate::error::AppError| ("unavailable", e.to_string());
480- let file = CourseNoteFile::read(&CourseNoteFileId::from_key(&request.file), &api.db)
510+ let file = CourseNoteFile::read(&CourseNoteFileId::from_key(&request.file), &db)
481511 .await
482512 .map_err(unavailable)?
483513 .ok_or_else(missing)?;
484- let note = CourseNote::read(file.get_course_note(), &api.db)
514+ let note = CourseNote::read(file.get_course_note(), &db)
485515 .await
486516 .map_err(unavailable)?
487517 .ok_or_else(missing)?;
488- let course = Course::read(note.get_course(), &api.db)
518+ let course = Course::read(note.get_course(), &db)
489519 .await
490520 .map_err(unavailable)?
491521 .ok_or_else(missing)?;
492- if !can_view_course(&course, &user, &api.db)
522+ if !can_view_course(&course, &user, &db)
493523 .await
494524 .map_err(unavailable)?
495525 {
@@ -504,7 +534,7 @@ async fn open_blob(
504534
505535 // The row exists but its blob does not: server-side damage (a lost volume
506536 // path), exactly as `download_file` reads it — not the service's `404`.
507- let path = blob_path(&api.files_path, file.get_id().key());
537+ let path = blob_path(&api.files_dir(), file.get_id().key());
508538 let handle = tokio::fs::File::open(&path).await.map_err(|e| {
509539 (
510540 "unavailable",
@@ -548,7 +578,7 @@ async fn principal(
548578 // Both the bare key (`abc`, as a REST path spells it) and the record form
549579 // (`user:abc`) are accepted.
550580 let key = who.strip_prefix("user:").unwrap_or(who);
551- User::read(&UserId::from_key(key), &api.db)
581+ User::read(&UserId::from_key(key), &api.db().await?)
552582 .await
553583 .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))?
554584 .ok_or_else(|| ("unknown_user", format!("no user `{who}`")))
@@ -627,6 +657,7 @@ async fn dispatch_api(
627657
628658 // The role itself is re-read again by the extractor on the dispatched
629659 // request; see [`principal`] for why it is never taken from the frame.
660+ let db = api.db().await?;
630661 let user = principal(api, on_behalf_of.as_deref()).await?;
631662
632663 let target = match query.as_deref() {
@@ -646,6 +677,12 @@ async fn dispatch_api(
646677 // An extension cannot be set from outside the process, which is what makes
647678 // this principal unforgeable over HTTP (see [`AiPrincipal`]).
648679 dispatched.extensions_mut().insert(AiPrincipal(user));
680+ // The dispatched request carries no cookie, so the school is handed over
681+ // in the extension the shadow `State` reads first.
682+ dispatched.extensions_mut().insert(TenantExt {
683+ slug: api.slug.clone(),
684+ db,
685+ });
649686
650687 let response = tokio::time::timeout(
651688 Duration::from_secs(REQUEST_TIMEOUT_SECS),
@@ -859,6 +896,7 @@ mod tests {
859896 refuse_before_dispatch,
860897 };
861898 use crate::ai::protocol::read_frame;
899+ use crate::tenant::Slug;
862900
863901 /// An armed handle serving `router`. The database is never touched by these
864902 /// reads (nobody is named, so the principal is synthetic), but the handle
@@ -866,7 +904,10 @@ mod tests {
866904 async fn armed(router: axum::Router) -> ApiHandle {
867905 ApiHandle {
868906 router,
869- db: crate::database::init_mem().await.expect("in-memory db"),
907+ tenants: crate::database::init_mem_tenants()
908+ .await
909+ .expect("in-memory deployment"),
910+ slug: Slug::try_new(crate::tenant::DEMO_SLUG).unwrap(),
870911 db_up: Default::default(),
871912 files_path: std::env::temp_dir(),
872913 }
src/config.rsmodified+13 -8
@@ -17,6 +17,9 @@ pub struct Config {
1717 pub db_user: String,
1818 pub db_pass: String,
1919 pub db_ns: String,
20+ /// The **control** database inside `db_ns` (`DB_DATABASE`): the school
21+ /// registry and the builder accounts. Every school gets a database of its
22+ /// own, named by its slug.
2023 pub db_name: String,
2124 /// Directory for uploaded note-file blobs (`FILES_PATH`).
2225 pub files_path: String,
@@ -31,11 +34,13 @@ pub struct Config {
3134 /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is
3235 /// keyed by user and is enforced inside the handler.
3336 pub chatbot_per_minute: u32,
34- /// Startup admin seed (`ADMIN_USERNAME` + `ADMIN_PASSWORD`). When both are
35- /// set, an admin account with these credentials is created at boot if the
36- /// username doesn't exist yet. Blank values count as unset.
37- pub admin_username: Option<String>,
38- pub admin_password: Option<String>,
37+ /// Startup builder seed (`BUILDER_USERNAME` + `BUILDER_PASSWORD`). When
38+ /// both are set, a builder account with these credentials is created in the
39+ /// control database at boot if the username doesn't exist yet. Blank values
40+ /// count as unset. A builder manages schools; it is not a user of any of
41+ /// them.
42+ pub builder_username: Option<String>,
43+ pub builder_password: Option<String>,
3944 /// AI bridge listen address (`AI_QUIC_ADDR`, e.g. `0.0.0.0:8090`). Unset
4045 /// leaves the bridge off entirely: the API runs exactly as before and any
4146 /// AI-backed feature reports that no service is connected.
@@ -62,7 +67,7 @@ impl Config {
6267 db_user: env::var("DB_USER").unwrap_or_else(|_| "root".into()),
6368 db_pass: env::var("DB_PASS").unwrap_or_else(|_| "root".into()),
6469 db_ns: env::var("DB_NAMESPACE").unwrap_or_else(|_| "hezarfen".into()),
65- db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "hezarfen".into()),
70+ db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "control".into()),
6671 files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()),
6772 cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()),
6873 rate_limit: RateLimitConfig {
@@ -80,8 +85,8 @@ impl Config {
8085 env::var("RATE_LIMIT_CHATBOT_PER_MINUTE").ok(),
8186 DEFAULT_CHATBOT_RATE_LIMIT,
8287 ),
83- admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()),
84- admin_password: parse_optional(env::var("ADMIN_PASSWORD").ok()),
88+ builder_username: parse_optional(env::var("BUILDER_USERNAME").ok()),
89+ builder_password: parse_optional(env::var("BUILDER_PASSWORD").ok()),
8590 ai_quic_addr: parse_optional(env::var("AI_QUIC_ADDR").ok()),
8691 ai_shared_token: parse_optional(env::var("AI_SHARED_TOKEN").ok()),
8792 ai_tls_cert: parse_optional(env::var("AI_TLS_CERT").ok()),
src/constant.rsmodified+6 -0
@@ -5,6 +5,12 @@ use crate::domain::message::Folder;
55 use crate::domain::preferences::{Language, Theme};
66 use crate::domain::role::Role;
77
8+/// A school slug's length bounds — the name in front of the dot in the session
9+/// cookie, which is also the school's database name and its blob directory
10+/// (see [`crate::tenant::Slug`]).
11+pub const MIN_SLUG_LEN: usize = 2;
12+pub const MAX_SLUG_LEN: usize = 32;
13+
814 pub const MIN_USERNAME_LEN: usize = 3;
915 pub const MAX_USERNAME_LEN: usize = 32;
1016
src/database.rsmodified+44 -19
@@ -6,10 +6,12 @@ use surrealdb::opt::auth::Root;
66
77 use crate::config::Config;
88 use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS};
9+use crate::domain::builder::Builder;
910 use crate::domain::timestamp::Timestamp;
10-use crate::domain::user::{Password, User, Username};
11+use crate::domain::user::{Password, Username};
1112 use crate::error::AppError;
12-use crate::migration_sql::{BACKFILL, MIGRATION_BATCHES};
13+use crate::migration_sql::{BACKFILL, CONTROL_MIGRATION_BATCHES, MIGRATION_BATCHES};
14+use crate::tenant::Tenants;
1315
1416 /// The shared database handle.
1517 ///
@@ -27,14 +29,14 @@ use crate::migration_sql::{BACKFILL, MIGRATION_BATCHES};
2729 /// Cloning the `Arc` shares the single session established at boot instead.
2830 pub type Database = std::sync::Arc<Surreal<Any>>;
2931
30-/// Connect to the SurrealDB server, sign in as root, apply the schema and seed
31-/// the admin. One process, one database, stop-the-world deploys — so all of it
32-/// runs unconditionally on every boot.
33-pub async fn init(cfg: &Config) -> Result<Database, AppError> {
32+/// Connect to the **control** database, sign in as root, apply the control
33+/// schema and seed the builder account. School databases are brought up
34+/// separately, one per school, by [`crate::tenant::Tenants`].
35+pub async fn init(cfg: &Config) -> Result<Tenants, AppError> {
3436 // Validated before the connection, not after: half a credential pair is a
3537 // deployment mistake, and reporting it only after a successful dial buries
3638 // it under an outage that isn't one.
37- let admin = admin_credentials(cfg)?;
39+ let builder = builder_credentials(cfg)?;
3840 let db = connect_with_retry(cfg).await;
3941 db.signin(Root {
4042 username: cfg.db_user.clone(),
@@ -45,27 +47,28 @@ pub async fn init(cfg: &Config) -> Result<Database, AppError> {
4547 .use_db(cfg.db_name.clone())
4648 .await?;
4749 let db = std::sync::Arc::new(db);
48- migrate(&db).await?;
49- if let Some((username, password)) = admin {
50- User::ensure_admin(username, password, &db).await?;
50+ migrate_control(&db).await?;
51+ if let Some((username, password)) = builder {
52+ Builder::ensure(username, password, &db).await?;
5153 }
52- Ok(db)
54+ Ok(Tenants::new_remote(db, cfg))
5355 }
5456
55-/// The `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap pair, if configured.
57+/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured.
5658 /// Both-or-neither: half a pair aborts startup rather than silently running
57-/// without the seed.
58-fn admin_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> {
59- match (&cfg.admin_username, &cfg.admin_password) {
59+/// without the seed — and without a builder, a fresh deployment has nobody who
60+/// can create the first school.
61+fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> {
62+ match (&cfg.builder_username, &cfg.builder_password) {
6063 (Some(username), Some(password)) => Ok(Some((
6164 Username::try_new(username)
62- .map_err(|err| AppError::Internal(format!("invalid ADMIN_USERNAME: {err}")))?,
65+ .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?,
6366 Password::try_new(password)
64- .map_err(|err| AppError::Internal(format!("invalid ADMIN_PASSWORD: {err}")))?,
67+ .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?,
6568 ))),
6669 (None, None) => Ok(None),
6770 _ => Err(AppError::Internal(
68- "ADMIN_USERNAME and ADMIN_PASSWORD must be set together".into(),
71+ "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(),
6972 )),
7073 }
7174 }
@@ -254,7 +257,9 @@ async fn connect_with_retry(cfg: &Config) -> Surreal<Any> {
254257 }
255258 }
256259
257-/// A fresh in-memory database with the schema applied. For tests.
260+/// A fresh in-memory **school** database with the school schema applied. For
261+/// the unit tests whose subject is one school's own rows; a test that needs the
262+/// whole app (control database included) wants [`init_mem_tenants`].
258263 pub async fn init_mem() -> Result<Database, AppError> {
259264 let db = surrealdb::engine::any::connect("memory").await?;
260265 db.use_ns("hezarfen").use_db("hezarfen").await?;
@@ -262,6 +267,16 @@ pub async fn init_mem() -> Result<Database, AppError> {
262267 Ok(std::sync::Arc::new(db))
263268 }
264269
270+/// A fresh in-memory deployment: an empty control database plus one school,
271+/// [`crate::tenant::DEMO_SLUG`]. The bootstrap every router-level test uses.
272+pub async fn init_mem_tenants() -> Result<Tenants, AppError> {
273+ let tenants = Tenants::new_mem().await?;
274+ let demo = crate::tenant::Slug::try_new(crate::tenant::DEMO_SLUG)
275+ .map_err(|err| AppError::Internal(format!("the demo slug is a slug: {err}")))?;
276+ tenants.create(&demo, "Demo School").await?;
277+ Ok(tenants)
278+}
279+
265280 /// A handle on a **real** SurrealDB server, in a scratch namespace of its own
266281 /// that is dropped and re-made on every call. For the tests whose subject is
267282 /// the store's own conflict detection, which [`init_mem`]'s embedded engine
@@ -326,6 +341,16 @@ pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> {
326341 Ok(())
327342 }
328343
344+/// Apply the **control** schema (schools, builders, the shared rate-limit
345+/// window). Idempotent, like [`migrate`], and takes no bound parameters —
346+/// nothing in the control batch is data-driven.
347+pub async fn migrate_control(db: &Surreal<Any>) -> Result<(), AppError> {
348+ for sql in CONTROL_MIGRATION_BATCHES {
349+ db.query(sql).await?.check()?;
350+ }
351+ Ok(())
352+}
353+
329354 /// Parameters the batches are executed with. Bound, not baked into the SQL
330355 /// string: a `const` cannot be interpolated into another `const`, and a
331356 /// hand-copied 300000 would drift silently. The one-time blocks' fingerprints
src/domain/builder.rsadded+253 -0
@@ -0,0 +1,253 @@
1+//! The deployment operator's account, in the control database.
2+//!
3+//! A builder creates, suspends and drops schools; it is **not** a user of any
4+//! school and holds no role there. The two principals are kept apart by
5+//! construction: a builder row lives in a different database and its cookie
6+//! carries a different prefix (`builder.<token>` against `<slug>.<token>`), so
7+//! neither extractor can be fed the other's cookie.
8+//!
9+//! The credential newtypes are [`crate::domain::user`]'s — same rules, same
10+//! argon2 discipline, deliberately not a second copy that could drift.
11+
12+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
13+use ulid::Ulid;
14+
15+use crate::constant::SESSION_DURATION_DAYS;
16+use crate::database::Database;
17+use crate::domain::session::SessionToken;
18+use crate::domain::timestamp::Timestamp;
19+use crate::domain::user::{Password, PasswordHash, Username};
20+use crate::error::AppError;
21+
22+pub const BUILDER_TABLE: &str = "builder";
23+pub const BUILDER_SESSION_TABLE: &str = "builder_session";
24+
25+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
26+pub struct BuilderId(RecordId);
27+
28+impl BuilderId {
29+ pub fn generate() -> Self {
30+ Self(RecordId::new(BUILDER_TABLE, Ulid::new().to_string()))
31+ }
32+
33+ pub fn from_key(key: &str) -> Self {
34+ Self(RecordId::new(BUILDER_TABLE, key))
35+ }
36+
37+ pub fn record(&self) -> RecordId {
38+ self.0.clone()
39+ }
40+
41+ pub fn key(&self) -> &str {
42+ match &self.0.key {
43+ RecordIdKey::String(key) => key,
44+ _ => "",
45+ }
46+ }
47+}
48+
49+#[derive(Debug, Clone, SurrealValue)]
50+pub struct Builder {
51+ id: BuilderId,
52+ username: Username,
53+ password_hash: PasswordHash,
54+}
55+
56+impl Builder {
57+ pub fn get_id(&self) -> &BuilderId {
58+ &self.id
59+ }
60+
61+ pub fn get_username(&self) -> &Username {
62+ &self.username
63+ }
64+
65+ pub fn get_password_hash(&self) -> &PasswordHash {
66+ &self.password_hash
67+ }
68+
69+ pub async fn find_by_username(
70+ username: &str,
71+ control: &Database,
72+ ) -> Result<Option<Builder>, AppError> {
73+ let mut result = control
74+ .query("SELECT * FROM builder WHERE username = $u LIMIT 1")
75+ .bind(("u", username.trim().to_string()))
76+ .await?
77+ .check()?;
78+ Ok(result.take::<Vec<Builder>>(0)?.into_iter().next())
79+ }
80+
81+ pub async fn read(id: &BuilderId, control: &Database) -> Result<Option<Builder>, AppError> {
82+ Ok(control.select(id.record()).await?)
83+ }
84+
85+ /// Idempotent startup seed. An existing row is left exactly as it is — the
86+ /// seed never rewrites a credential, so rotating `BUILDER_PASSWORD` in the
87+ /// environment does not silently re-key a live account (delete the row to
88+ /// re-seed). There is no role to promote here, so this cannot have
89+ /// `ensure_admin`'s create-then-promote hole.
90+ pub async fn ensure(
91+ username: Username,
92+ password: Password,
93+ control: &Database,
94+ ) -> Result<(), AppError> {
95+ if Self::find_by_username(username.as_str(), control)
96+ .await?
97+ .is_some()
98+ {
99+ return Ok(());
100+ }
101+ let builder = Builder {
102+ id: BuilderId::generate(),
103+ password_hash: password.hash_async().await?,
104+ username,
105+ };
106+ let created: Option<Builder> = control
107+ .create(builder.id.record())
108+ .content(builder.clone())
109+ .await?;
110+ created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?;
111+ tracing::info!(
112+ username = builder.username.as_str(),
113+ "seeded builder account"
114+ );
115+ Ok(())
116+ }
117+}
118+
119+/// A builder's login session. [`crate::domain::session::Session`]'s shape
120+/// against the control database, with the token type shared so both cookies
121+/// are the same 64 hex chars.
122+#[derive(Debug, Clone, SurrealValue)]
123+pub struct BuilderSession {
124+ id: RecordId,
125+ builder: BuilderId,
126+ token: SessionToken,
127+ created_at: Timestamp,
128+ expires_at: Timestamp,
129+}
130+
131+impl BuilderSession {
132+ pub async fn create(
133+ builder: &BuilderId,
134+ control: &Database,
135+ ) -> Result<BuilderSession, AppError> {
136+ let session = BuilderSession {
137+ id: RecordId::new(BUILDER_SESSION_TABLE, Ulid::new().to_string()),
138+ builder: builder.clone(),
139+ token: SessionToken::generate()?,
140+ created_at: Timestamp::now(),
141+ expires_at: Timestamp::in_days(SESSION_DURATION_DAYS),
142+ };
143+ let created: Option<BuilderSession> =
144+ control.create(session.id.clone()).content(session).await?;
145+ created.ok_or_else(|| AppError::Internal("failed to create the builder session".into()))
146+ }
147+
148+ pub fn token(&self) -> &SessionToken {
149+ &self.token
150+ }
151+
152+ pub fn builder(&self) -> &BuilderId {
153+ &self.builder
154+ }
155+
156+ pub fn is_expired(&self) -> bool {
157+ self.expires_at.is_past()
158+ }
159+
160+ pub async fn find_by_token(
161+ token: &str,
162+ control: &Database,
163+ ) -> Result<Option<BuilderSession>, AppError> {
164+ let mut result = control
165+ .query("SELECT * FROM builder_session WHERE token = $tok LIMIT 1")
166+ .bind(("tok", token.to_string()))
167+ .await?
168+ .check()?;
169+ Ok(result.take::<Vec<BuilderSession>>(0)?.into_iter().next())
170+ }
171+
172+ pub async fn delete_by_token(token: &str, control: &Database) -> Result<(), AppError> {
173+ control
174+ .query("DELETE builder_session WHERE token = $tok")
175+ .bind(("tok", token.to_string()))
176+ .await?
177+ .check()?;
178+ Ok(())
179+ }
180+}
181+
182+#[cfg(test)]
183+mod tests {
184+ use super::*;
185+ use crate::tenant::Tenants;
186+
187+ #[tokio::test]
188+ async fn the_seed_is_idempotent_and_never_rewrites_a_credential() {
189+ let tenants = Tenants::new_mem().await.unwrap();
190+ let control = tenants.control();
191+ let name = Username::try_new("builder1").unwrap();
192+ Builder::ensure(name.clone(), Password::try_new("secret1").unwrap(), control)
193+ .await
194+ .unwrap();
195+ let first = Builder::find_by_username("builder1", control)
196+ .await
197+ .unwrap()
198+ .expect("seeded");
199+
200+ // A second boot with a *different* password must leave the row alone:
201+ // an environment edit is not a password reset.
202+ Builder::ensure(name, Password::try_new("secret2").unwrap(), control)
203+ .await
204+ .unwrap();
205+ let again = Builder::find_by_username("builder1", control)
206+ .await
207+ .unwrap()
208+ .expect("still there");
209+ assert_eq!(again.get_id(), first.get_id());
210+ assert_eq!(
211+ again.get_password_hash().as_str(),
212+ first.get_password_hash().as_str()
213+ );
214+ }
215+
216+ #[tokio::test]
217+ async fn a_builder_session_round_trips_and_deletes() {
218+ let tenants = Tenants::new_mem().await.unwrap();
219+ let control = tenants.control();
220+ Builder::ensure(
221+ Username::try_new("builder1").unwrap(),
222+ Password::try_new("secret1").unwrap(),
223+ control,
224+ )
225+ .await
226+ .unwrap();
227+ let builder = Builder::find_by_username("builder1", control)
228+ .await
229+ .unwrap()
230+ .unwrap();
231+
232+ let session = BuilderSession::create(builder.get_id(), control)
233+ .await
234+ .unwrap();
235+ let token = session.token().as_str().to_string();
236+ let found = BuilderSession::find_by_token(&token, control)
237+ .await
238+ .unwrap()
239+ .expect("found by token");
240+ assert_eq!(found.builder(), builder.get_id());
241+ assert!(!found.is_expired());
242+
243+ BuilderSession::delete_by_token(&token, control)
244+ .await
245+ .unwrap();
246+ assert!(
247+ BuilderSession::find_by_token(&token, control)
248+ .await
249+ .unwrap()
250+ .is_none()
251+ );
252+ }
253+}
src/domain/mod.rsmodified+1 -0
@@ -11,6 +11,7 @@ pub mod bank_question;
1111 pub mod bank_question_image;
1212 pub mod board;
1313 pub mod board_stroke;
14+pub mod builder;
1415 pub mod cap;
1516 pub mod chatbot_message;
1617 pub mod chatbot_thread;
src/lib.rsmodified+2 -1
@@ -7,6 +7,7 @@ pub mod error;
77 pub mod migration_sql;
88 pub mod rate_limit;
99 pub mod state;
10+pub mod tenant;
1011 pub mod validate;
1112 pub mod web;
1213
@@ -161,7 +162,7 @@ pub fn build_router(state: AppState) -> Router {
161162 if let Some(ai) = &state.ai {
162163 ai.arm_api(
163164 service.clone(),
164- state.db.clone(),
165+ state.tenants.clone(),
165166 state.db_up.clone(),
166167 state.files_path.clone(),
167168 );
src/main.rsmodified+9 -5
@@ -19,17 +19,21 @@ async fn main() -> anyhow::Result<()> {
1919 // Hash the login decoy now, so the first unknown-username login is not the
2020 // one request that pays for it (see `PasswordHash::prewarm_decoy`).
2121 hezarfen_backend::domain::user::PasswordHash::prewarm_decoy();
22- // Connects, migrates the schema and seeds the admin — all of it idempotent
23- // and unconditional on every boot.
24- let db = database::init(&cfg).await?;
22+ // Connects to the control database, migrates it and seeds the builder —
23+ // all of it idempotent and unconditional on every boot. School databases
24+ // come up lazily, one connection each, on first use.
25+ let tenants = database::init(&cfg).await?;
2526 let db_up = DbHealth::default();
26- keepalive(db.clone(), db_up.clone());
27+ // The control connection is the one every request touches (the school
28+ // lookup rides it), so it is the socket worth watching.
29+ keepalive(tenants.control().clone(), db_up.clone());
2730 tokio::fs::create_dir_all(&cfg.files_path)
2831 .await
2932 .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?;
3033 let ai = hezarfen_backend::ai::start_bridge(&cfg).await?;
3134 let app = build_router(AppState {
32- db,
35+ db: tenants.control().clone(),
36+ tenants,
3337 files_path: cfg.files_path.clone().into(),
3438 cookie_secure: cfg.cookie_secure,
3539 rate_limit: cfg.rate_limit.clone(),
src/migration_sql.rsmodified+42 -0
@@ -1461,6 +1461,48 @@ pub const BACKFILL: &str = "
14611461 };
14621462 ";
14631463
1464+/// The **control** database's schema — the one database per deployment that
1465+/// knows which schools exist and who may create them. Everything else lives in
1466+/// a school database, whose schema is [`MIGRATION_BATCHES`] and is applied
1467+/// per school by [`crate::tenant::Tenants::create`].
1468+///
1469+/// The `rate_limit` copy is deliberate: the shared per-IP window
1470+/// (`crate::rate_limit::RateLimiter::share`) is billed against the control
1471+/// handle, because the limiter runs in front of the router — before any cookie
1472+/// has named a school. One budget per deployment is also the honest one for an
1473+/// unauthenticated brute-forcer, who has not picked a school yet either.
1474+pub const CONTROL_MIGRATION: &str = "
1475+ DEFINE TABLE IF NOT EXISTS school SCHEMAFULL;
1476+ DEFINE FIELD IF NOT EXISTS slug ON school TYPE string;
1477+ DEFINE FIELD IF NOT EXISTS name ON school TYPE string;
1478+ DEFINE FIELD IF NOT EXISTS status ON school TYPE string;
1479+ DEFINE FIELD IF NOT EXISTS created_at ON school TYPE int;
1480+ -- Redundant with the `school:<slug>` id, and kept anyway: the id is the
1481+ -- fast path, the index is what makes a second row on the same slug
1482+ -- impossible if a future write ever mints an id some other way.
1483+ DEFINE INDEX IF NOT EXISTS school_slug ON school FIELDS slug UNIQUE;
1484+
1485+ DEFINE TABLE IF NOT EXISTS builder SCHEMAFULL;
1486+ DEFINE FIELD IF NOT EXISTS username ON builder TYPE string;
1487+ DEFINE FIELD IF NOT EXISTS password_hash ON builder TYPE string;
1488+ DEFINE INDEX IF NOT EXISTS builder_username ON builder FIELDS username UNIQUE;
1489+
1490+ DEFINE TABLE IF NOT EXISTS builder_session SCHEMAFULL;
1491+ DEFINE FIELD IF NOT EXISTS builder ON builder_session TYPE record<builder>;
1492+ DEFINE FIELD IF NOT EXISTS token ON builder_session TYPE string;
1493+ DEFINE FIELD IF NOT EXISTS created_at ON builder_session TYPE int;
1494+ DEFINE FIELD IF NOT EXISTS expires_at ON builder_session TYPE int;
1495+ DEFINE INDEX IF NOT EXISTS builder_session_token ON builder_session FIELDS token UNIQUE;
1496+ DEFINE INDEX IF NOT EXISTS builder_session_expires ON builder_session FIELDS expires_at;
1497+
1498+ -- Verbatim from `MIGRATION`; see the note above this constant.
1499+ DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL;
1500+ DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0;
1501+ DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int;
1502+";
1503+
1504+pub const CONTROL_MIGRATION_BATCHES: [&str; 1] = [CONTROL_MIGRATION];
1505+
14641506 /// The migration batches, in the order a boot applies them — and the *only*
14651507 /// list of them. [`crate::database::migrate`] runs exactly these. They stay
14661508 /// three separate queries: statements in one batch see the schema as it stood
src/state.rsmodified+8 -0
@@ -8,11 +8,19 @@ use tokio::sync::broadcast;
88 use crate::ai::AiBridge;
99 use crate::database::Database;
1010 use crate::rate_limit::{RateLimitConfig, UserRateLimiter};
11+use crate::tenant::Tenants;
1112
1213 /// Shared application state handed to every handler.
1314 #[derive(Clone)]
1415 pub struct AppState {
16+ /// The database this request works in. At the router's root this is the
17+ /// **control** database; `crate::web::tenant_state::State` swaps in the
18+ /// caller's school before any handler that shadows `State` sees it.
1519 pub db: Database,
20+ /// The school registry and its connections. Always the deployment-wide
21+ /// one — it is never narrowed per request, so a handler can still reach
22+ /// another school's handle deliberately.
23+ pub tenants: Tenants,
1624 /// Directory holding uploaded note-file blobs, one file per
1725 /// `note_file` row, named by the row's key
1826 /// (from [`crate::config::Config::files_path`]).
src/tenant.rsadded+652 -0
@@ -0,0 +1,652 @@
1+//! Multi-school tenancy: one SurrealDB **database** per school inside one
2+//! namespace, plus a **control** database holding the school registry, the
3+//! builder accounts that manage it, and the deployment-wide rate-limit window.
4+//!
5+//! Isolation is the store's, not ours. A school database sees only its own
6+//! rows, so no handler needs a `WHERE school = …` it could forget: the school
7+//! is chosen once, at the edge (`crate::web::tenant_state::State`), and every
8+//! query underneath runs against that handle.
9+//!
10+//! # One connection per school, never a clone
11+//!
12+//! [`crate::database::Database`] is `Arc<Surreal<Any>>` for the reason spelled
13+//! out there — `Surreal::clone()` mints a racing server-side session — and the
14+//! same reasoning forbids the obvious shortcut here: switching `use_db` on the
15+//! control handle would repoint *every* in-flight query on it. So a cache miss
16+//! dials a **new** connection, signs it in, and pins it to the school's
17+//! database for its lifetime.
18+//!
19+//! In-memory mode (tests) has no server to define databases on: each
20+//! `connect("memory")` is an independent datastore, so a school *is* its own
21+//! store and the cache is the only thing that finds it again.
22+
23+use std::collections::HashMap;
24+use std::sync::{Arc, RwLock};
25+
26+use serde::Serialize;
27+use surrealdb::opt::auth::Root;
28+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
29+
30+use crate::config::Config;
31+use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN};
32+use crate::database::{Database, lost_the_race, migrate, migrate_control};
33+use crate::domain::page::PagedList;
34+use crate::domain::timestamp::Timestamp;
35+use crate::error::{AppError, ValidationError};
36+
37+pub(crate) const SCHOOL_TABLE: &str = "school";
38+
39+/// The school every in-memory test bootstrap gets. Not special to the code —
40+/// just the one name the test harness and the suites agree on.
41+pub const DEMO_SLUG: &str = "demo";
42+
43+/// Slugs that name something other than a school: the builder cookie prefix and
44+/// the control database itself. Refused at construction, so neither a login nor
45+/// a `DEFINE DATABASE` can ever be aimed at them.
46+pub const RESERVED_SLUGS: [&str; 2] = ["builder", "control"];
47+
48+/// A school's identity everywhere it is named: the cookie prefix, the database
49+/// name, and the files subdirectory. The character set is deliberately the
50+/// intersection of what all three accept — lowercase alphanumerics and `-`,
51+/// starting with an alphanumeric — which is also what makes it safe to
52+/// interpolate into `DEFINE DATABASE` / `REMOVE DATABASE`, the two statements
53+/// SurrealQL gives no way to bind a name into.
54+#[derive(Debug, Clone, PartialEq, Eq, Hash, SurrealValue, Serialize)]
55+#[serde(transparent)]
56+pub struct Slug(String);
57+
58+/// `^[a-z0-9][a-z0-9-]{1,31}$`, spelled out. `regex` is a dev-dependency here
59+/// and this is five lines of `char` predicates — a runtime dependency would
60+/// cost more than it saves.
61+fn is_slug(value: &str) -> bool {
62+ let ok_len = (MIN_SLUG_LEN..=MAX_SLUG_LEN).contains(&value.len());
63+ let ok_first = value
64+ .chars()
65+ .next()
66+ .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
67+ let ok_rest = value
68+ .chars()
69+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
70+ ok_len && ok_first && ok_rest
71+}
72+
73+impl Slug {
74+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
75+ if !is_slug(value) {
76+ return Err(ValidationError::Invalid {
77+ field: "school",
78+ reason: "must be 2-32 characters of a-z, 0-9 and -, starting with a letter or digit",
79+ });
80+ }
81+ if RESERVED_SLUGS.contains(&value) {
82+ return Err(ValidationError::Invalid {
83+ field: "school",
84+ reason: "this name is reserved",
85+ });
86+ }
87+ Ok(Self(value.to_string()))
88+ }
89+
90+ pub fn as_str(&self) -> &str {
91+ &self.0
92+ }
93+}
94+
95+impl std::fmt::Display for Slug {
96+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97+ f.write_str(&self.0)
98+ }
99+}
100+
101+/// Whether a school may be reached at all. Suspension is immediate and total:
102+/// [`Tenants::get`] refuses before any handler runs, and login is no exception.
103+///
104+/// Stored as a bare lowercase string, like [`crate::domain::role::Role`].
105+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue, Serialize)]
106+#[surreal(untagged, rename_all = "lowercase")]
107+#[serde(rename_all = "lowercase")]
108+pub enum SchoolStatus {
109+ Active,
110+ Suspended,
111+}
112+
113+impl SchoolStatus {
114+ pub fn as_str(self) -> &'static str {
115+ match self {
116+ SchoolStatus::Active => "active",
117+ SchoolStatus::Suspended => "suspended",
118+ }
119+ }
120+
121+ pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
122+ match value {
123+ "active" => Ok(SchoolStatus::Active),
124+ "suspended" => Ok(SchoolStatus::Suspended),
125+ _ => Err(ValidationError::Invalid {
126+ field: "status",
127+ reason: "must be one of: active, suspended",
128+ }),
129+ }
130+ }
131+}
132+
133+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
134+pub struct SchoolId(RecordId);
135+
136+impl SchoolId {
137+ /// The id **is** the slug, so the registry can never hold two rows for one
138+ /// school even if the unique index were dropped.
139+ pub fn from_slug(slug: &Slug) -> Self {
140+ Self(RecordId::new(SCHOOL_TABLE, slug.as_str()))
141+ }
142+
143+ pub fn record(&self) -> RecordId {
144+ self.0.clone()
145+ }
146+
147+ pub fn key(&self) -> &str {
148+ match &self.0.key {
149+ RecordIdKey::String(key) => key,
150+ _ => "",
151+ }
152+ }
153+}
154+
155+/// A row in the control database's school registry.
156+#[derive(Debug, Clone, SurrealValue)]
157+pub struct School {
158+ id: SchoolId,
159+ slug: Slug,
160+ name: String,
161+ status: SchoolStatus,
162+ created_at: Timestamp,
163+}
164+
165+impl School {
166+ pub fn get_id(&self) -> &SchoolId {
167+ &self.id
168+ }
169+
170+ pub fn slug(&self) -> &Slug {
171+ &self.slug
172+ }
173+
174+ pub fn name(&self) -> &str {
175+ &self.name
176+ }
177+
178+ pub fn status(&self) -> SchoolStatus {
179+ self.status
180+ }
181+
182+ pub fn created_at(&self) -> Timestamp {
183+ self.created_at
184+ }
185+
186+ pub async fn read(slug: &Slug, control: &Database) -> Result<Option<School>, AppError> {
187+ Ok(control.select(SchoolId::from_slug(slug).record()).await?)
188+ }
189+
190+ /// One page of the registry, newest first. Same `(rows, total)` shape every
191+ /// other list domain returns, so the builder API can wrap it in the usual
192+ /// [`crate::web::Page`] envelope.
193+ pub async fn list(
194+ limit: Option<i64>,
195+ offset: i64,
196+ control: &Database,
197+ ) -> Result<(Vec<School>, i64), AppError> {
198+ PagedList::new(SCHOOL_TABLE, "ORDER BY created_at DESC, id DESC")
199+ .run::<School>(limit, offset, control)
200+ .await
201+ }
202+
203+ /// Rename a school. The slug is immutable — it names a database and a
204+ /// directory, so it is the one field a rename must not touch.
205+ pub async fn update_name(
206+ slug: &Slug,
207+ name: &str,
208+ control: &Database,
209+ ) -> Result<School, AppError> {
210+ let updated: Option<School> = control
211+ .query("UPDATE $id SET name = $name RETURN AFTER")
212+ .bind(("id", SchoolId::from_slug(slug).record()))
213+ .bind(("name", name.to_string()))
214+ .await?
215+ .check()?
216+ .take::<Vec<School>>(0)?
217+ .into_iter()
218+ .next();
219+ updated.ok_or(AppError::NotFound)
220+ }
221+}
222+
223+/// How a school handle is minted. Remote dials the server the control handle
224+/// came from; `Mem` mints an independent embedded datastore per school.
225+#[derive(Debug)]
226+enum Mode {
227+ Remote {
228+ url: String,
229+ user: String,
230+ pass: String,
231+ ns: String,
232+ },
233+ Mem,
234+}
235+
236+/// The school registry plus its live connections.
237+#[derive(Clone)]
238+pub struct Tenants {
239+ control: Database,
240+ cache: Arc<RwLock<HashMap<String, Database>>>,
241+ mode: Arc<Mode>,
242+}
243+
244+impl Tenants {
245+ /// Wrap an already-connected, already-migrated control handle.
246+ pub fn new_remote(control: Database, cfg: &Config) -> Tenants {
247+ Tenants {
248+ control,
249+ cache: Arc::new(RwLock::new(HashMap::new())),
250+ mode: Arc::new(Mode::Remote {
251+ url: cfg.db_url.clone(),
252+ user: cfg.db_user.clone(),
253+ pass: cfg.db_pass.clone(),
254+ ns: cfg.db_ns.clone(),
255+ }),
256+ }
257+ }
258+
259+ /// A fresh in-memory control database with the control schema applied, and
260+ /// no schools. For tests.
261+ pub async fn new_mem() -> Result<Tenants, AppError> {
262+ let control = surrealdb::engine::any::connect("memory").await?;
263+ control.use_ns("hezarfen").use_db("control").await?;
264+ migrate_control(&control).await?;
265+ Ok(Tenants {
266+ control: Arc::new(control),
267+ cache: Arc::new(RwLock::new(HashMap::new())),
268+ mode: Arc::new(Mode::Mem),
269+ })
270+ }
271+
272+ /// A fresh in-memory registry that already knows `slug`, backed by a handle
273+ /// that already exists rather than a new store.
274+ ///
275+ /// This is how a suite simulates a reboot: the process (and so the registry,
276+ /// the connection cache and the control database) is new, while the school's
277+ /// data is the very data the previous process wrote.
278+ pub async fn new_mem_adopting(
279+ slug: &Slug,
280+ name: &str,
281+ db: Database,
282+ ) -> Result<Tenants, AppError> {
283+ let tenants = Tenants::new_mem().await?;
284+ let school = School {
285+ id: SchoolId::from_slug(slug),
286+ slug: slug.clone(),
287+ name: name.to_string(),
288+ status: SchoolStatus::Active,
289+ created_at: Timestamp::now(),
290+ };
291+ let _: Option<School> = tenants
292+ .control
293+ .create(school.id.record())
294+ .content(school)
295+ .await?;
296+ tenants
297+ .cache
298+ .write()
299+ .expect("tenant cache lock")
300+ .insert(slug.as_str().to_string(), db);
301+ Ok(tenants)
302+ }
303+
304+ /// The control database: schools, builders, the shared rate-limit window.
305+ /// Never `use_db`-switched — see this module's header.
306+ pub fn control(&self) -> &Database {
307+ &self.control
308+ }
309+
310+ /// The handle for a school a request may use, or the refusal a request
311+ /// gets: unknown → `401` (a wrong school is a wrong credential, and a `404`
312+ /// would enumerate the customer list), suspended → `403`.
313+ ///
314+ /// corner-cut: the registry row is read on every request, so a suspension
315+ /// takes effect on the next call with no invalidation protocol. That is one
316+ /// extra control-db round trip per request; cache the row with a short TTL
317+ /// if it ever shows up in a profile — the eviction in [`Tenants::set_status`]
318+ /// is already there to make a cached decision safe.
319+ pub async fn get(&self, slug: &Slug) -> Result<Database, AppError> {
320+ match School::read(slug, &self.control).await? {
321+ None => Err(AppError::Unauthorized),
322+ Some(school) if school.status == SchoolStatus::Suspended => {
323+ self.evict(slug);
324+ Err(AppError::Forbidden("school is suspended"))
325+ }
326+ Some(_) => self.handle(slug).await,
327+ }
328+ }
329+
330+ /// [`Tenants::get`] for builder tooling, which must still reach a suspended
331+ /// school to un-suspend or inspect it. Unknown → `404`, because a builder is
332+ /// authenticated and there is nothing to hide from them.
333+ pub async fn get_any_status(&self, slug: &Slug) -> Result<(Database, SchoolStatus), AppError> {
334+ let school = School::read(slug, &self.control)
335+ .await?
336+ .ok_or(AppError::NotFound)?;
337+ Ok((self.handle(slug).await?, school.status))
338+ }
339+
340+ /// Register a school and bring its database into being: registry row first
341+ /// (so a lost race is a `409` and not a half-made database), then
342+ /// `DEFINE DATABASE`, then the school schema.
343+ pub async fn create(&self, slug: &Slug, name: &str) -> Result<Database, AppError> {
344+ let school = School {
345+ id: SchoolId::from_slug(slug),
346+ slug: slug.clone(),
347+ name: name.to_string(),
348+ status: SchoolStatus::Active,
349+ created_at: Timestamp::now(),
350+ };
351+ let created: Result<Option<School>, surrealdb::Error> = self
352+ .control
353+ .create(school.id.record())
354+ .content(school.clone())
355+ .await;
356+ match created {
357+ Ok(Some(_)) => {}
358+ Ok(None) => return Err(AppError::Internal("failed to create the school".into())),
359+ // The id is the slug, so "already exists" is exactly "taken" — and
360+ // a lost transaction race is the same verdict reached differently.
361+ Err(err) if lost_the_race(&err) => {
362+ return Err(AppError::Conflict("school slug already taken"));
363+ }
364+ Err(err) => return Err(err.into()),
365+ }
366+
367+ let db = match &*self.mode {
368+ Mode::Remote { .. } => {
369+ // `slug` is `Slug`-validated, so this interpolation carries only
370+ // `[a-z0-9-]` — SurrealQL cannot bind a database name.
371+ self.control
372+ .query(format!("DEFINE DATABASE IF NOT EXISTS {slug}"))
373+ .await?
374+ .check()?;
375+ self.connect(slug).await?
376+ }
377+ Mode::Mem => self.connect(slug).await?,
378+ };
379+ migrate(&db).await?;
380+ self.cache
381+ .write()
382+ .expect("tenant cache lock")
383+ .insert(slug.as_str().to_string(), db.clone());
384+ Ok(db)
385+ }
386+
387+ /// Flip a school between active and suspended. Suspending also drops the
388+ /// cached handle, so nothing that already resolved keeps serving.
389+ pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> {
390+ let updated: Vec<School> = self
391+ .control
392+ .query("UPDATE $id SET status = $status RETURN AFTER")
393+ .bind(("id", SchoolId::from_slug(slug).record()))
394+ .bind(("status", status))
395+ .await?
396+ .check()?
397+ .take(0)?;
398+ if updated.is_empty() {
399+ return Err(AppError::NotFound);
400+ }
401+ if status == SchoolStatus::Suspended {
402+ self.evict(slug);
403+ }
404+ Ok(())
405+ }
406+
407+ /// Delete a school outright: its data, then its registry row, then its
408+ /// handle. Irreversible on purpose — there is no soft-delete state, that is
409+ /// what [`SchoolStatus::Suspended`] is for.
410+ pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> {
411+ if let Mode::Remote { .. } = &*self.mode {
412+ // Interpolation, not a bind: see `create`.
413+ self.control
414+ .query(format!("REMOVE DATABASE IF EXISTS {slug}"))
415+ .await?
416+ .check()?;
417+ }
418+ self.control
419+ .query("DELETE $id")
420+ .bind(("id", SchoolId::from_slug(slug).record()))
421+ .await?
422+ .check()?;
423+ self.forget(slug);
424+ Ok(())
425+ }
426+
427+ /// Forget a school's connection. The next request dials a fresh one.
428+ ///
429+ /// A no-op in memory mode, where the cached handle *is* the school's
430+ /// datastore and dropping it would delete the school's data rather than its
431+ /// connection. Nothing depends on eviction for correctness — [`Tenants::get`]
432+ /// re-reads the registry row on every request, so a suspension is refused
433+ /// whether or not a handle survived it. [`Tenants::drop`], which does mean to
434+ /// destroy the store, forgets it unconditionally.
435+ pub fn evict(&self, slug: &Slug) {
436+ if matches!(&*self.mode, Mode::Mem) {
437+ return;
438+ }
439+ self.forget(slug);
440+ }
441+
442+ fn forget(&self, slug: &Slug) {
443+ self.cache
444+ .write()
445+ .expect("tenant cache lock")
446+ .remove(slug.as_str());
447+ }
448+
449+ /// The cached handle, or a freshly dialled one.
450+ async fn handle(&self, slug: &Slug) -> Result<Database, AppError> {
451+ if let Some(db) = self
452+ .cache
453+ .read()
454+ .expect("tenant cache lock")
455+ .get(slug.as_str())
456+ {
457+ return Ok(db.clone());
458+ }
459+ let db = self.connect(slug).await?;
460+ // In-memory mode has nowhere for a school's rows to have survived a
461+ // cache miss, so a fresh store needs the schema. Remote already has it.
462+ if matches!(&*self.mode, Mode::Mem) {
463+ migrate(&db).await?;
464+ }
465+ // Losing the race here is harmless — both handles are equivalent — but
466+ // the winner is kept so two requests never diverge onto two sessions.
467+ Ok(self
468+ .cache
469+ .write()
470+ .expect("tenant cache lock")
471+ .entry(slug.as_str().to_string())
472+ .or_insert(db)
473+ .clone())
474+ }
475+
476+ /// One new connection, pinned to `slug`'s database for its lifetime.
477+ async fn connect(&self, slug: &Slug) -> Result<Database, AppError> {
478+ let db = match &*self.mode {
479+ Mode::Remote {
480+ url,
481+ user,
482+ pass,
483+ ns,
484+ } => {
485+ let db = surrealdb::engine::any::connect(url.clone()).await?;
486+ db.signin(Root {
487+ username: user.clone(),
488+ password: pass.clone(),
489+ })
490+ .await?;
491+ db.use_ns(ns.clone()).use_db(slug.as_str()).await?;
492+ db
493+ }
494+ Mode::Mem => {
495+ let db = surrealdb::engine::any::connect("memory").await?;
496+ db.use_ns("hezarfen").use_db(slug.as_str()).await?;
497+ db
498+ }
499+ };
500+ Ok(Arc::new(db))
501+ }
502+}
503+
504+#[cfg(test)]
505+mod tests {
506+ use super::*;
507+
508+ fn slug(value: &str) -> Slug {
509+ Slug::try_new(value).expect(value)
510+ }
511+
512+ async fn count(db: &Database, table: &str) -> usize {
513+ let mut rows = db
514+ .query(format!("SELECT id FROM {table}"))
515+ .await
516+ .unwrap()
517+ .check()
518+ .unwrap();
519+ rows.take::<Vec<surrealdb::types::RecordId>>(0)
520+ .unwrap()
521+ .len()
522+ }
523+
524+ #[tokio::test]
525+ async fn a_slug_names_a_school_and_nothing_reserved() {
526+ for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] {
527+ assert!(Slug::try_new(good).is_ok(), "{good:?} should be a slug");
528+ }
529+ // Reserved words would collide with the builder cookie prefix and the
530+ // control database itself — the two things a slug must never name.
531+ for bad in [
532+ "builder",
533+ "control",
534+ "Demo",
535+ "..",
536+ "",
537+ "x",
538+ "-lead",
539+ "has_underscore",
540+ "has.dot",
541+ &"x".repeat(33),
542+ ] {
543+ assert!(Slug::try_new(bad).is_err(), "{bad:?} must not be a slug");
544+ }
545+ }
546+
547+ #[tokio::test]
548+ async fn two_schools_do_not_see_each_others_rows() {
549+ let tenants = Tenants::new_mem().await.unwrap();
550+ let (a, b) = (slug("alpha"), slug("beta"));
551+ let one = tenants.create(&a, "Alpha").await.unwrap();
552+ let two = tenants.create(&b, "Beta").await.unwrap();
553+
554+ one.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'")
555+ .await
556+ .unwrap()
557+ .check()
558+ .unwrap();
559+ assert_eq!(count(&one, "user").await, 1);
560+ assert_eq!(
561+ count(&two, "user").await,
562+ 0,
563+ "a row written in one school must be invisible in the other"
564+ );
565+ // A second `create` on a taken slug is a conflict, not a second school.
566+ assert!(matches!(
567+ tenants.create(&a, "Alpha again").await,
568+ Err(AppError::Conflict(_))
569+ ));
570+ }
571+
572+ #[tokio::test]
573+ async fn suspending_refuses_the_school_and_the_handle_it_already_had() {
574+ let tenants = Tenants::new_mem().await.unwrap();
575+ let s = slug("alpha");
576+ tenants.create(&s, "Alpha").await.unwrap();
577+ // Cached by the first resolve; the suspension must beat the cache.
578+ tenants.get(&s).await.expect("active school resolves");
579+
580+ tenants
581+ .set_status(&s, SchoolStatus::Suspended)
582+ .await
583+ .unwrap();
584+ assert!(matches!(
585+ tenants.get(&s).await,
586+ Err(AppError::Forbidden("school is suspended"))
587+ ));
588+ // Builder tooling still reaches it, which is how it gets un-suspended.
589+ let (_, status) = tenants.get_any_status(&s).await.unwrap();
590+ assert_eq!(status, SchoolStatus::Suspended);
591+
592+ tenants.set_status(&s, SchoolStatus::Active).await.unwrap();
593+ assert!(tenants.get(&s).await.is_ok());
594+ // An unknown school is a bad credential, never a `404`.
595+ assert!(matches!(
596+ tenants.get(&slug("ghost")).await,
597+ Err(AppError::Unauthorized)
598+ ));
599+ assert!(matches!(
600+ tenants.get_any_status(&slug("ghost")).await,
601+ Err(AppError::NotFound)
602+ ));
603+ }
604+
605+ #[tokio::test]
606+ async fn dropping_a_school_takes_its_rows_with_it() {
607+ let tenants = Tenants::new_mem().await.unwrap();
608+ let s = slug("alpha");
609+ let db = tenants.create(&s, "Alpha").await.unwrap();
610+ db.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'")
611+ .await
612+ .unwrap()
613+ .check()
614+ .unwrap();
615+ assert_eq!(count(&db, "user").await, 1);
616+
617+ tenants.drop(&s).await.unwrap();
618+ assert!(matches!(tenants.get(&s).await, Err(AppError::Unauthorized)));
619+
620+ let fresh = tenants.create(&s, "Alpha reborn").await.unwrap();
621+ assert_eq!(
622+ count(&fresh, "user").await,
623+ 0,
624+ "a re-created school must not inherit the dropped one's rows"
625+ );
626+ }
627+
628+ #[tokio::test]
629+ async fn the_registry_lists_and_renames() {
630+ let tenants = Tenants::new_mem().await.unwrap();
631+ tenants.create(&slug("alpha"), "Alpha").await.unwrap();
632+ tenants.create(&slug("beta"), "Beta").await.unwrap();
633+
634+ let (rows, total) = School::list(None, 0, tenants.control()).await.unwrap();
635+ assert_eq!(total, 2);
636+ assert_eq!(rows.len(), 2);
637+
638+ let renamed = School::update_name(&slug("alpha"), "Alpha Koleji", tenants.control())
639+ .await
640+ .unwrap();
641+ assert_eq!(renamed.name(), "Alpha Koleji");
642+ assert_eq!(
643+ renamed.slug().as_str(),
644+ "alpha",
645+ "a rename never moves the slug"
646+ );
647+ assert!(matches!(
648+ School::update_name(&slug("ghost"), "Nope", tenants.control()).await,
649+ Err(AppError::NotFound)
650+ ));
651+ }
652+}
src/web/appointments.rsmodified+2 -1
@@ -1,7 +1,8 @@
11 use std::collections::{HashMap, HashSet};
22
3+use crate::web::tenant_state::State;
34 use axum::Json;
4-use axum::extract::{Path, Query, State};
5+use axum::extract::{Path, Query};
56 use axum::http::StatusCode;
67 use serde::{Deserialize, Serialize};
78 use utoipa::ToSchema;
src/web/attendance.rsmodified+2 -1
@@ -1,7 +1,8 @@
11 use std::collections::HashMap;
22
3+use crate::web::tenant_state::State;
34 use axum::Json;
4-use axum::extract::{Path, State};
5+use axum::extract::Path;
56 use serde::Serialize;
67 use utoipa::ToSchema;
78 use utoipa_axum::router::OpenApiRouter;
src/web/auth.rsmodified+47 -11
@@ -10,15 +10,18 @@ use utoipa_axum::router::OpenApiRouter;
1010 use utoipa_axum::routes;
1111
1212 use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS};
13+use crate::domain::builder::BuilderSession;
1314 use crate::domain::role::Role as DomainRole;
1415 use crate::domain::session::Session;
1516 use crate::domain::user::{Password, PasswordHash, User, Username};
1617 use crate::error::{AppError, ErrorResponse, ValidationError};
1718 use crate::rate_limit::{RateLimitConfig, RateLimiter};
1819 use crate::state::AppState;
20+use crate::tenant::Slug;
1921
2022 use super::dto::Role;
21-use super::{CurrentUser, UserResponse};
23+use super::tenant_state::split_cookie;
24+use super::{BUILDER_COOKIE_PREFIX, CurrentUser, UserResponse};
2225
2326 pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
2427 // Strict per-IP limit on the two credential endpoints only — the
@@ -44,6 +47,11 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
4447
4548 #[derive(Deserialize, ToSchema)]
4649 struct Credentials {
50+ /// The school's slug — the name in front of the dot in the session cookie.
51+ /// One backend serves many schools, so a username only identifies an
52+ /// account together with this.
53+ #[schema(example = "demo", min_length = 2, max_length = 32)]
54+ school: String,
4755 #[schema(example = "ada", min_length = 3, max_length = 32)]
4856 username: String,
4957 #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
@@ -63,7 +71,7 @@ struct RegisterResponse {
6371 role: Role,
6472 }
6573
66-/// Register a new user account: `{username, password}` in, `{username, role}`
74+/// Register a new user account: `{school, username, password}` in, `{username, role}`
6775 /// back (no `id`; new accounts are `student`). Always `201`, even if the name
6876 /// was already taken — see "Auth model".
6977 ///
@@ -83,6 +91,8 @@ struct RegisterResponse {
8391 responses(
8492 (status = 201, description = "Account created, or the username was already taken — deliberately indistinguishable. Carries no `id`: on the taken path there is no row to name, so log in to learn who you are", body = RegisterResponse),
8593 (status = 400, description = "Invalid username or password", body = ErrorResponse),
94+ (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse),
95+ (status = 403, description = "The school is suspended", body = ErrorResponse),
8696 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
8797 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
8898 ),
@@ -91,6 +101,12 @@ async fn register(
91101 State(st): State<AppState>,
92102 Json(req): Json<Credentials>,
93103 ) -> Result<(StatusCode, Json<RegisterResponse>), AppError> {
104+ // The school first: a registration into a school that does not exist, or
105+ // one that is suspended, must not reach the (expensive) hashing path — and
106+ // an unknown school answers `401` here for the same anti-enumeration reason
107+ // login does, rather than confirming which schools this deployment serves.
108+ let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?;
109+ let db = st.tenants.get(&school).await?;
94110 let username = Username::try_new(&req.username)?;
95111 // Registration-level policy, not a `Username` invariant: these names read
96112 // as staff and invite impersonation, but the `ADMIN_USERNAME` bootstrap
@@ -115,7 +131,7 @@ async fn register(
115131 username: username.as_str().to_string(),
116132 role: DomainRole::Student.into(),
117133 };
118- match User::create(username, password_hash, &st.db).await {
134+ match User::create(username, password_hash, &db).await {
119135 Ok(_) => {}
120136 // Taken. Log the real reason server-side; the caller gets the same 201
121137 // and the same body, because telling the two apart is the whole thing
@@ -128,7 +144,8 @@ async fn register(
128144 Ok((StatusCode::CREATED, Json(body)))
129145 }
130146
131-/// Log in with username + password. Sets a `session` cookie on success.
147+/// Log in with school + username + password. Sets a `session` cookie
148+/// (`<school>.<token>`) on success.
132149 #[utoipa::path(
133150 post,
134151 path = "/login",
@@ -136,7 +153,8 @@ async fn register(
136153 request_body = Credentials,
137154 responses(
138155 (status = 200, description = "Logged in; session cookie set", body = UserResponse),
139- (status = 401, description = "Bad credentials", body = ErrorResponse),
156+ (status = 401, description = "Bad credentials, or no such school — deliberately indistinguishable", body = ErrorResponse),
157+ (status = 403, description = "The school is suspended", body = ErrorResponse),
140158 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
141159 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
142160 ),
@@ -146,10 +164,17 @@ async fn login(
146164 jar: CookieJar,
147165 Json(req): Json<Credentials>,
148166 ) -> Result<(CookieJar, Json<UserResponse>), AppError> {
167+ // Resolved *before* the argon2 work: a login aimed at a school that does
168+ // not exist is a bad credential (`401`, indistinguishable from a bad
169+ // password — the school list is not public), and a suspended school is
170+ // `403` for every request including this one, so neither should buy an
171+ // attacker a hash.
172+ let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?;
173+ let db = st.tenants.get(&school).await?;
149174 let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?;
150175 // Usernames are stored trimmed (see `Username::try_new`); trim the lookup
151176 // the same way so a padded login attempt matches the canonical name.
152- let user = match User::find_by_username(req.username.trim(), &st.db).await? {
177+ let user = match User::find_by_username(req.username.trim(), &db).await? {
153178 // Verification is `.await`ed so argon2 runs on the blocking pool instead
154179 // of stalling an async worker; that rules out a match guard, which
155180 // cannot await.
@@ -169,10 +194,12 @@ async fn login(
169194 };
170195
171196 // The caller is genuine; opportunistically drop any expired session rows.
172- let _ = Session::purge_expired(&st.db).await;
197+ let _ = Session::purge_expired(&db).await;
173198
174- let session = Session::create(user.get_id(), &st.db).await?;
175- let cookie = Cookie::build(("session", session.token().as_str().to_string()))
199+ let session = Session::create(user.get_id(), &db).await?;
200+ // `<slug>.<token>`: the cookie carries the school, so every later request
201+ // finds its database without a second lookup path that could disagree.
202+ let cookie = Cookie::build(("session", format!("{school}.{}", session.token().as_str())))
176203 .path("/")
177204 .http_only(true)
178205 .secure(st.cookie_secure)
@@ -198,8 +225,17 @@ async fn logout(
198225 State(st): State<AppState>,
199226 jar: CookieJar,
200227 ) -> Result<(CookieJar, StatusCode), AppError> {
201- if let Some(cookie) = jar.get("session") {
202- Session::delete_by_token(cookie.value(), &st.db).await?;
228+ // Best-effort: the cookie names its own school, so a logout resolves that
229+ // school and deletes the row there. A cookie naming a school that is gone
230+ // or suspended still clears below — logging out must never fail.
231+ if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) {
232+ if prefix == BUILDER_COOKIE_PREFIX {
233+ BuilderSession::delete_by_token(token, &st.db).await?;
234+ } else if let Ok(slug) = Slug::try_new(prefix)
235+ && let Ok(db) = st.tenants.get(&slug).await
236+ {
237+ Session::delete_by_token(token, &db).await?;
238+ }
203239 }
204240 let jar = jar.remove(Cookie::build(("session", "")).path("/").build());
205241 Ok((jar, StatusCode::NO_CONTENT))
src/web/bank_questions.rsmodified+2 -1
@@ -15,8 +15,9 @@
1515
1616 use std::collections::HashMap;
1717
18+use crate::web::tenant_state::State;
1819 use axum::Json;
19-use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
20+use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
2021 use axum::http::StatusCode;
2122 use axum::response::Response;
2223 use serde::{Deserialize, Serialize};
src/web/board_ws.rsmodified+2 -1
@@ -58,8 +58,9 @@
5858 use std::collections::VecDeque;
5959 use std::time::Duration;
6060
61+use crate::web::tenant_state::State;
62+use axum::extract::Path;
6163 use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
62-use axum::extract::{Path, State};
6364 use axum::response::Response;
6465 use serde::Deserialize;
6566 use serde_json::{Value, json};
src/web/boards.rsmodified+2 -1
@@ -18,8 +18,9 @@
1818 //! mid-session keeps drawing over an already-open socket until the room hears
1919 //! about it, so a roster change *must* fan out.
2020
21+use crate::web::tenant_state::State;
2122 use axum::Json;
22-use axum::extract::{Path, Query, State};
23+use axum::extract::{Path, Query};
2324 use axum::http::StatusCode;
2425 use serde::{Deserialize, Serialize};
2526 use serde_json::json;
src/web/chatbot.rsmodified+2 -1
@@ -20,8 +20,9 @@
2020
2121 use std::time::Duration;
2222
23+use crate::web::tenant_state::State;
2324 use axum::Json;
24-use axum::extract::{Path, Query, State};
25+use axum::extract::{Path, Query};
2526 use axum::http::StatusCode;
2627 use axum::response::sse::{Event, KeepAlive, Sse};
2728 use axum::response::{IntoResponse, Response};
src/web/classes.rsmodified+2 -1
@@ -7,8 +7,9 @@
77 //! and its roster are the office's (manager+), while attaching a course writes
88 //! *that course's* roster and takes the same right enrolling into it does.
99
10+use crate::web::tenant_state::State;
1011 use axum::Json;
11-use axum::extract::{Path, Query, State};
12+use axum::extract::{Path, Query};
1213 use axum::http::StatusCode;
1314 use serde::{Deserialize, Serialize};
1415 use utoipa::{IntoParams, ToSchema};
src/web/course_notes.rsmodified+3 -1
@@ -5,8 +5,9 @@
55 //! teacher, or manager+), reads need [`super::courses::can_view_course`]
66 //! (management rights, or enrollment).
77
8+use crate::web::tenant_state::State;
89 use axum::Json;
9-use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
10+use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
1011 use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
1112 use axum::http::{HeaderValue, StatusCode};
1213 use axum::response::{IntoResponse, Response};
@@ -387,6 +388,7 @@ async fn upload_file(
387388 // the row insert fails, take the fresh blob back out.
388389 let file = CourseNoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64);
389390 let path = blob_path(&st.files_path, file.get_id().key());
391+ crate::web::ensure_files_dir(&st.files_path).await?;
390392 tokio::fs::write(&path, &upload.data)
391393 .await
392394 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
src/web/courses.rsmodified+3 -1
@@ -1,7 +1,8 @@
11 use std::collections::HashMap;
22
3+use crate::web::tenant_state::State;
34 use axum::Json;
4-use axum::extract::{Path, Query, State};
5+use axum::extract::{Path, Query};
56 use axum::http::StatusCode;
67 use serde::{Deserialize, Serialize};
78 use utoipa::ToSchema;
@@ -1415,6 +1416,7 @@ mod tests {
14151416 let course = course(&manager, &db).await;
14161417 let st = AppState {
14171418 db: db.clone(),
1419+ tenants: crate::database::init_mem_tenants().await.unwrap(),
14181420 files_path: std::env::temp_dir(),
14191421 cookie_secure: false,
14201422 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
src/web/events.rsmodified+2 -1
@@ -1,7 +1,8 @@
11 use std::collections::HashMap;
22
3+use crate::web::tenant_state::State;
34 use axum::Json;
4-use axum::extract::{Path, Query, State};
5+use axum::extract::{Path, Query};
56 use axum::http::StatusCode;
67 use serde::{Deserialize, Serialize};
78 use utoipa::ToSchema;
src/web/exam_ws.rsmodified+2 -1
@@ -56,8 +56,9 @@
5656
5757 use std::time::Duration;
5858
59+use crate::web::tenant_state::State;
60+use axum::extract::Path;
5961 use axum::extract::ws::{WebSocket, WebSocketUpgrade};
60-use axum::extract::{Path, State};
6162 use axum::response::Response;
6263 use serde::Deserialize;
6364 use serde_json::{Value, json};
src/web/exams/mod.rsmodified+2 -1
@@ -1,7 +1,8 @@
11 use std::collections::{HashMap, HashSet};
22
3+use crate::web::tenant_state::State;
34 use axum::Json;
4-use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
5+use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
56 use axum::http::StatusCode;
67 use axum::response::Response;
78 use serde::{Deserialize, Serialize};
src/web/extractor.rsmodified+56 -8
@@ -2,11 +2,14 @@ use axum::extract::{FromRef, FromRequestParts};
22 use axum::http::request::Parts;
33 use axum_extra::extract::CookieJar;
44
5+use crate::database::Database;
6+use crate::domain::builder::{Builder, BuilderSession};
57 use crate::domain::role::Role;
68 use crate::domain::session::Session;
79 use crate::domain::user::User;
810 use crate::error::AppError;
911 use crate::state::AppState;
12+use crate::web::tenant_state::{resolve_tenant, split_cookie};
1013
1114 /// A principal injected as a request extension by the AI bridge, for the
1215 /// synthetic requests it dispatches into the router. Extensions cannot be set
@@ -18,6 +21,11 @@ pub(crate) struct AiPrincipal(pub User);
1821 /// [`AiPrincipal`] extension wins over the cookie. The role is read fresh from
1922 /// the row on every request, so a role change takes effect on the user's next
2023 /// call — no re-login required.
24+///
25+/// The school is resolved by the very helper `State<AppState>` uses
26+/// ([`resolve_tenant`]), so the principal and the rows a handler then reads can
27+/// never come from two different databases. A `builder.<token>` cookie names no
28+/// school and so cannot reach here at all.
2129 async fn authed_user<S>(parts: &mut Parts, state: &S) -> Result<User, AppError>
2230 where
2331 S: Send + Sync,
@@ -27,24 +35,22 @@ where
2735 return Ok(principal.0.clone());
2836 }
2937
38+ let (_, db) = resolve_tenant(parts, state).await?;
39+
3040 let jar = CookieJar::from_request_parts(parts, state)
3141 .await
3242 .map_err(|_| AppError::Unauthorized)?;
33- let token = jar
34- .get("session")
35- .map(|cookie| cookie.value().to_owned())
36- .ok_or(AppError::Unauthorized)?;
37-
38- let app = AppState::from_ref(state);
43+ let cookie = jar.get("session").ok_or(AppError::Unauthorized)?;
44+ let (_, token) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?;
3945
40- let session = Session::find_by_token(&token, &app.db)
46+ let session = Session::find_by_token(token, &db)
4147 .await?
4248 .ok_or(AppError::Unauthorized)?;
4349 if session.is_expired() {
4450 return Err(AppError::Unauthorized);
4551 }
4652
47- User::read(session.user(), &app.db)
53+ User::read(session.user(), &db)
4854 .await?
4955 .ok_or(AppError::Unauthorized)
5056 }
@@ -144,3 +150,45 @@ where
144150 Ok(RequireAdmin(user))
145151 }
146152 }
153+
154+/// The deployment operator behind a `builder.<token>` cookie, resolved against
155+/// the **control** database. Any school cookie is `401` here, and this cookie
156+/// is `401` on every school surface (`resolve_tenant` refuses the `builder`
157+/// prefix as a slug) — the two principals share a cookie name and nothing else.
158+pub struct RequireBuilder(pub Builder);
159+
160+impl<S> FromRequestParts<S> for RequireBuilder
161+where
162+ S: Send + Sync,
163+ AppState: FromRef<S>,
164+{
165+ type Rejection = AppError;
166+
167+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
168+ let jar = CookieJar::from_request_parts(parts, state)
169+ .await
170+ .map_err(|_| AppError::Unauthorized)?;
171+ let cookie = jar.get("session").ok_or(AppError::Unauthorized)?;
172+ let (prefix, token) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?;
173+ if prefix != BUILDER_COOKIE_PREFIX {
174+ return Err(AppError::Unauthorized);
175+ }
176+
177+ let control: Database = AppState::from_ref(state).tenants.control().clone();
178+ let session = BuilderSession::find_by_token(token, &control)
179+ .await?
180+ .ok_or(AppError::Unauthorized)?;
181+ if session.is_expired() {
182+ return Err(AppError::Unauthorized);
183+ }
184+ Ok(RequireBuilder(
185+ Builder::read(session.builder(), &control)
186+ .await?
187+ .ok_or(AppError::Unauthorized)?,
188+ ))
189+ }
190+}
191+
192+/// The cookie prefix a builder session carries in place of a school slug.
193+/// `Slug::try_new` reserves this word, so it can never also name a school.
194+pub const BUILDER_COOKIE_PREFIX: &str = "builder";
src/web/homework.rsmodified+3 -1
@@ -5,8 +5,9 @@
55 //! [`super::courses`]); everything shares the visibility rule
66 //! ([`Homework::student_sees`]) and the [`HOMEWORK_LOCK`].
77
8+use crate::web::tenant_state::State;
89 use axum::Json;
9-use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
10+use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
1011 use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
1112 use axum::http::{HeaderValue, StatusCode};
1213 use axum::response::{IntoResponse, Response};
@@ -964,6 +965,7 @@ async fn upload_submission_file(
964965 upload.data.len() as i64,
965966 );
966967 let path = blob_path(&st.files_path, file.get_file());
968+ crate::web::ensure_files_dir(&st.files_path).await?;
967969 tokio::fs::write(&path, &upload.data)
968970 .await
969971 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
src/web/image.rsmodified+1 -0
@@ -62,6 +62,7 @@ pub(crate) async fn store_blob<T, Fut>(
6262 where
6363 Fut: Future<Output = Result<(T, Option<String>), AppError>>,
6464 {
65+ crate::web::ensure_files_dir(&st.files_path).await?;
6566 let path = blob_path(&st.files_path, file);
6667 tokio::fs::write(&path, data)
6768 .await
src/web/limits.rsmodified+11 -0
@@ -29,6 +29,14 @@ pub fn routes() -> OpenApiRouter<AppState> {
2929 /// Account fields: credentials, profile, and the closed role set.
3030 #[derive(Serialize, ToSchema)]
3131 struct UserLimits {
32+ /// The school slug the login and registration forms ask for, in front of
33+ /// the dot in the session cookie. Lowercase `a-z`, `0-9` and `-`, starting
34+ /// with a letter or digit.
35+ min_slug_len: usize,
36+ max_slug_len: usize,
37+ /// Slugs no school may take — they name the builder cookie prefix and the
38+ /// control database.
39+ reserved_slugs: Vec<&'static str>,
3240 min_username_len: usize,
3341 max_username_len: usize,
3442 /// Separators allowed inside a username — never at the edges, never doubled.
@@ -462,6 +470,9 @@ impl LimitsResponse {
462470 fn new(st: &AppState) -> Self {
463471 Self {
464472 user: UserLimits {
473+ min_slug_len: MIN_SLUG_LEN,
474+ max_slug_len: MAX_SLUG_LEN,
475+ reserved_slugs: crate::tenant::RESERVED_SLUGS.to_vec(),
465476 min_username_len: MIN_USERNAME_LEN,
466477 max_username_len: MAX_USERNAME_LEN,
467478 username_separators: USERNAME_SEPARATORS.iter().map(char::to_string).collect(),
src/web/marks.rsmodified+2 -1
@@ -1,7 +1,8 @@
11 use std::collections::HashMap;
22
3+use crate::web::tenant_state::State;
34 use axum::Json;
4-use axum::extract::{Path, State};
5+use axum::extract::Path;
56 use serde::Serialize;
67 use utoipa::ToSchema;
78 use utoipa_axum::router::OpenApiRouter;
src/web/meals.rsmodified+2 -1
@@ -9,8 +9,9 @@
99 //! Money only ever *appends* here (see [`MealLedger`]): booking charges a price
1010 //! snapshot, cancelling reverses it, and recording a payment is admin-only.
1111
12+use crate::web::tenant_state::State;
1213 use axum::Json;
13-use axum::extract::{Path, Query, State};
14+use axum::extract::{Path, Query};
1415 use axum::http::StatusCode;
1516 use serde::{Deserialize, Serialize};
1617 use utoipa::{IntoParams, ToSchema};
src/web/messages.rsmodified+2 -1
@@ -1,7 +1,8 @@
11 use std::collections::{HashMap, HashSet};
22
3+use crate::web::tenant_state::State;
34 use axum::Json;
4-use axum::extract::{Path, Query, State};
5+use axum::extract::{Path, Query};
56 use axum::http::StatusCode;
67 use serde::{Deserialize, Serialize};
78 use utoipa::{IntoParams, ToSchema};
src/web/mod.rsmodified+20 -1
@@ -35,6 +35,8 @@ pub mod terms;
3535 pub mod users;
3636 pub mod work;
3737
38+pub mod tenant_state;
39+
3840 mod dto;
3941 // `pub(crate)` for `AiPrincipal`: the AI bridge injects it as an extension on
4042 // the requests it dispatches into the router (see `ai::server`).
@@ -46,7 +48,10 @@ pub use dto::{
4648 CourseResponse, ExamResponse, HomeworkResponse, PersonRef, SessionResponse, SubjectResponse,
4749 UserResponse, course_people, person_map,
4850 };
49-pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher};
51+pub use extractor::{
52+ BUILDER_COOKIE_PREFIX, CurrentUser, RequireAdmin, RequireBuilder, RequireManager,
53+ RequireStudent, RequireTeacher,
54+};
5055 pub(crate) use image::{ImageUpload, read_image_upload, store_blob};
5156 pub use page::{Page, PageParams, Scheduled, WindowParams, paginate};
5257
@@ -187,6 +192,20 @@ pub(crate) fn blob_path(files_path: &FsPath, key: &str) -> PathBuf {
187192 files_path.join(key)
188193 }
189194
195+/// Make sure a school's blob directory exists before writing into it.
196+///
197+/// `FILES_PATH` is the deployment root and `main` creates only that; each
198+/// school's subdirectory appears the first time that school stores a file, so
199+/// nothing has to be provisioned when a school is created.
200+pub(crate) async fn ensure_files_dir(files_path: &FsPath) -> Result<(), AppError> {
201+ tokio::fs::create_dir_all(files_path).await.map_err(|err| {
202+ AppError::Internal(format!(
203+ "failed to create the files directory {}: {err}",
204+ files_path.display()
205+ ))
206+ })
207+}
208+
190209 /// Best-effort blob removal after its row is gone. Failure only strands an
191210 /// unreachable file on disk, so it is logged rather than surfaced.
192211 pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) {
src/web/notes.rsmodified+3 -1
@@ -1,5 +1,6 @@
1+use crate::web::tenant_state::State;
12 use axum::Json;
2-use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
3+use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
34 use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
45 use axum::http::{HeaderValue, StatusCode};
56 use axum::response::{IntoResponse, Response};
@@ -283,6 +284,7 @@ async fn upload_file(
283284 // the row insert fails, take the fresh blob back out.
284285 let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64);
285286 let path = blob_path(&st.files_path, file.get_id().key());
287+ crate::web::ensure_files_dir(&st.files_path).await?;
286288 tokio::fs::write(&path, &upload.data)
287289 .await
288290 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
src/web/payments.rsmodified+2 -1
@@ -13,8 +13,9 @@
1313
1414 use std::collections::HashMap;
1515
16+use crate::web::tenant_state::State;
1617 use axum::Json;
17-use axum::extract::{Path, Query, State};
18+use axum::extract::{Path, Query};
1819 use axum::http::StatusCode;
1920 use serde::{Deserialize, Serialize};
2021 use utoipa::ToSchema;
src/web/pomodoro.rsmodified+2 -1
@@ -1,5 +1,6 @@
1+use crate::web::tenant_state::State;
12 use axum::Json;
2-use axum::extract::{Path, Query, State};
3+use axum::extract::{Path, Query};
34 use axum::http::StatusCode;
45 use serde::Serialize;
56 use utoipa::ToSchema;
src/web/questions.rsmodified+2 -1
@@ -8,8 +8,9 @@
88 //! opposite: unmoderated, so their author may edit the body and attach,
99 //! replace, or drop one photo at any time — moderation there is delete-only.
1010
11+use crate::web::tenant_state::State;
1112 use axum::Json;
12-use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
13+use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
1314 use axum::http::StatusCode;
1415 use axum::response::Response;
1516 use serde::{Deserialize, Serialize};
src/web/sessions.rsmodified+2 -1
@@ -1,7 +1,8 @@
11 use std::collections::HashMap;
22
3+use crate::web::tenant_state::State;
34 use axum::Json;
4-use axum::extract::{Path, Query, State};
5+use axum::extract::{Path, Query};
56 use axum::http::StatusCode;
67 use serde::{Deserialize, Serialize};
78 use utoipa::ToSchema;
src/web/settings.rsmodified+1 -1
@@ -1,5 +1,5 @@
1+use crate::web::tenant_state::State;
12 use axum::Json;
2-use axum::extract::State;
33 use serde::{Deserialize, Serialize};
44 use utoipa::ToSchema;
55 use utoipa_axum::router::OpenApiRouter;
src/web/subjects.rsmodified+2 -1
@@ -1,5 +1,6 @@
1+use crate::web::tenant_state::State;
12 use axum::Json;
2-use axum::extract::{Path, State};
3+use axum::extract::Path;
34 use axum::http::StatusCode;
45 use serde::Deserialize;
56 use utoipa::ToSchema;
src/web/tenant_state.rsadded+305 -0
@@ -0,0 +1,305 @@
1+//! The school-scoped replacement for `axum::extract::State`.
2+//!
3+//! [`State`] is named to **shadow** `axum::extract::State` on purpose: a
4+//! handler file swaps one import and every `State(st)` in it starts working in
5+//! the caller's school instead of the control database, with no handler body
6+//! touched. That is the whole design — there is no `st.db` a handler could
7+//! forget to scope, because the only `st` it can name is already scoped.
8+//!
9+//! Three files keep the real `axum::extract::State` because they legitimately
10+//! see the control database: `web::auth` (it resolves the school itself, and
11+//! its rate limiter is deployment-wide), `web::limits` (constants, no rows) and
12+//! `web::ai` (bridge certificate, no rows).
13+
14+use std::path::PathBuf;
15+
16+use axum::extract::{FromRef, FromRequestParts};
17+use axum::http::request::Parts;
18+use axum_extra::extract::CookieJar;
19+
20+use crate::database::Database;
21+use crate::error::AppError;
22+use crate::state::AppState;
23+use crate::tenant::Slug;
24+
25+/// The school a request has already been resolved into, injected as a request
26+/// extension by an in-process caller that has no cookie — today only the AI
27+/// bridge. Extensions cannot be set from outside the process, so this is
28+/// unforgeable over HTTP, exactly like
29+/// [`crate::web::extractor::AiPrincipal`].
30+#[derive(Clone)]
31+pub struct TenantExt {
32+ pub slug: Slug,
33+ pub db: Database,
34+}
35+
36+/// Split a `session` cookie into its school part and its token. `builder` in
37+/// the first position is the deployment operator; anything else is a slug.
38+///
39+/// Splits at the **first** dot, so a token can never be mistaken for a slug no
40+/// matter what it contains (it is hex today, and this does not depend on that).
41+pub fn split_cookie(value: &str) -> Option<(&str, &str)> {
42+ let (prefix, token) = value.split_once('.')?;
43+ (!prefix.is_empty() && !token.is_empty()).then_some((prefix, token))
44+}
45+
46+/// The school behind this request: the `TenantExt` extension if one was
47+/// injected, else the `session` cookie's prefix.
48+///
49+/// Shared with [`crate::web::extractor`] so the two can never disagree about
50+/// which school a request belongs to — the authenticated user and the rows
51+/// they read must come from the same database.
52+pub(crate) async fn resolve_tenant<S>(
53+ parts: &mut Parts,
54+ state: &S,
55+) -> Result<(Slug, Database), AppError>
56+where
57+ S: Send + Sync,
58+ AppState: FromRef<S>,
59+{
60+ if let Some(tenant) = parts.extensions.get::<TenantExt>() {
61+ return Ok((tenant.slug.clone(), tenant.db.clone()));
62+ }
63+ let jar = CookieJar::from_request_parts(parts, state)
64+ .await
65+ .map_err(|_| AppError::Unauthorized)?;
66+ let cookie = jar.get("session").ok_or(AppError::Unauthorized)?;
67+ // A builder cookie names no school, and a cookie with no dot names nothing
68+ // at all. Both are `401` here: the builder surface is a different extractor
69+ // (`RequireBuilder`), and this one must never let it in.
70+ let (prefix, _) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?;
71+ let slug = Slug::try_new(prefix).map_err(|_| AppError::Unauthorized)?;
72+
73+ let app = AppState::from_ref(state);
74+ let db = app.tenants.get(&slug).await?;
75+ Ok((slug, db))
76+}
77+
78+/// The application state, narrowed to the caller's school. Drop-in for
79+/// `axum::extract::State<AppState>` in every handler that reads school data.
80+///
81+/// Unauthenticated callers are refused *here*, before the handler runs — which
82+/// is correct for every route that uses it, since all of them already require a
83+/// session to do anything.
84+pub struct State<T>(pub T);
85+
86+impl<S> FromRequestParts<S> for State<AppState>
87+where
88+ S: Send + Sync,
89+ AppState: FromRef<S>,
90+{
91+ type Rejection = AppError;
92+
93+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
94+ let (slug, db) = resolve_tenant(parts, state).await?;
95+ let app = AppState::from_ref(state);
96+ Ok(State(AppState {
97+ db,
98+ files_path: school_files_path(&app.files_path, &slug),
99+ ..app
100+ }))
101+ }
102+}
103+
104+/// Just the school, for the handlers that need it as a key prefix (the exam
105+/// presence map, the whiteboard hub) rather than as a database handle.
106+pub struct SchoolSlug(pub Slug);
107+
108+impl<S> FromRequestParts<S> for SchoolSlug
109+where
110+ S: Send + Sync,
111+ AppState: FromRef<S>,
112+{
113+ type Rejection = AppError;
114+
115+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
116+ Ok(SchoolSlug(resolve_tenant(parts, state).await?.0))
117+ }
118+}
119+
120+/// Where a school's uploaded blobs live: one directory per school under the
121+/// deployment's `FILES_PATH`. The slug's character set is what makes this a
122+/// plain `join` — it can contain no separator and no `..`.
123+pub fn school_files_path(root: &std::path::Path, slug: &Slug) -> PathBuf {
124+ root.join(slug.as_str())
125+}
126+
127+#[cfg(test)]
128+mod tests {
129+ use super::*;
130+
131+ use axum::http::StatusCode;
132+ use axum::routing::get;
133+ use axum::{Router, body::Body, http::Request};
134+ use tower::ServiceExt;
135+
136+ use crate::database::init_mem_tenants;
137+ use crate::domain::builder::{Builder, BuilderSession};
138+ use crate::domain::session::Session;
139+ use crate::domain::user::{Password, User, Username};
140+ use crate::tenant::DEMO_SLUG;
141+ use crate::web::{CurrentUser, RequireBuilder};
142+
143+ async fn school_surface(State(_): State<AppState>, CurrentUser(_): CurrentUser) -> StatusCode {
144+ StatusCode::OK
145+ }
146+
147+ async fn builder_surface(RequireBuilder(_): RequireBuilder) -> StatusCode {
148+ StatusCode::OK
149+ }
150+
151+ /// A two-route app, one live cookie of each kind, and the registry behind
152+ /// them.
153+ async fn harness() -> (Router, String, String, crate::tenant::Tenants) {
154+ let tenants = init_mem_tenants().await.expect("in-memory deployment");
155+ let school = tenants
156+ .get(&Slug::try_new(DEMO_SLUG).unwrap())
157+ .await
158+ .expect("the demo school");
159+
160+ let user = User::create(
161+ Username::try_new("ada").unwrap(),
162+ Password::try_new("secret1")
163+ .unwrap()
164+ .hash_async()
165+ .await
166+ .unwrap(),
167+ &school,
168+ )
169+ .await
170+ .unwrap();
171+ let session = Session::create(user.get_id(), &school).await.unwrap();
172+ let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str());
173+
174+ Builder::ensure(
175+ Username::try_new("operator").unwrap(),
176+ Password::try_new("secret1").unwrap(),
177+ tenants.control(),
178+ )
179+ .await
180+ .unwrap();
181+ let builder = Builder::find_by_username("operator", tenants.control())
182+ .await
183+ .unwrap()
184+ .unwrap();
185+ let builder_session = BuilderSession::create(builder.get_id(), tenants.control())
186+ .await
187+ .unwrap();
188+ let builder_cookie = format!("session=builder.{}", builder_session.token().as_str());
189+
190+ let state = AppState {
191+ db: tenants.control().clone(),
192+ tenants: tenants.clone(),
193+ files_path: std::env::temp_dir(),
194+ cookie_secure: false,
195+ rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
196+ chatbot_limit: Default::default(),
197+ exam_presence: Default::default(),
198+ board_hub: Default::default(),
199+ db_up: Default::default(),
200+ ai: None,
201+ };
202+ let app = Router::new()
203+ .route("/school", get(school_surface))
204+ .route("/builder", get(builder_surface))
205+ .with_state(state);
206+ (app, school_cookie, builder_cookie, tenants)
207+ }
208+
209+ async fn status(app: &Router, uri: &str, cookie: Option<&str>) -> StatusCode {
210+ let mut builder = Request::builder().uri(uri);
211+ if let Some(cookie) = cookie {
212+ builder = builder.header("cookie", cookie);
213+ }
214+ app.clone()
215+ .oneshot(builder.body(Body::empty()).unwrap())
216+ .await
217+ .unwrap()
218+ .status()
219+ }
220+
221+ /// The two principals share a cookie name and nothing else. Neither may
222+ /// ever be accepted where the other belongs — a builder holding school
223+ /// power, or a student reaching the school-management surface, is the one
224+ /// failure this whole split exists to prevent.
225+ #[tokio::test]
226+ async fn neither_cookie_works_on_the_others_surface() {
227+ let (app, school, builder, _) = harness().await;
228+
229+ assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK);
230+ assert_eq!(
231+ status(&app, "/builder", Some(&builder)).await,
232+ StatusCode::OK
233+ );
234+
235+ assert_eq!(
236+ status(&app, "/school", Some(&builder)).await,
237+ StatusCode::UNAUTHORIZED,
238+ "a builder cookie must not pass a school extractor"
239+ );
240+ assert_eq!(
241+ status(&app, "/builder", Some(&school)).await,
242+ StatusCode::UNAUTHORIZED,
243+ "a school cookie must not pass RequireBuilder"
244+ );
245+
246+ // A cookie with no school part names nothing resolvable — including the
247+ // pre-tenancy shape, which is deliberately not accepted anywhere.
248+ let bare = school.replace(&format!("{DEMO_SLUG}."), "");
249+ for uri in ["/school", "/builder"] {
250+ assert_eq!(
251+ status(&app, uri, Some(&bare)).await,
252+ StatusCode::UNAUTHORIZED,
253+ "{uri} accepted a cookie with no school"
254+ );
255+ assert_eq!(
256+ status(&app, uri, None).await,
257+ StatusCode::UNAUTHORIZED,
258+ "{uri} accepted no cookie at all"
259+ );
260+ }
261+ }
262+
263+ /// A suspended school is refused at the edge, before any handler — with a
264+ /// session that was perfectly good a moment earlier, and through a handle
265+ /// the registry had already cached.
266+ #[tokio::test]
267+ async fn a_suspension_refuses_a_live_session() {
268+ let (app, school, _, tenants) = harness().await;
269+ let demo = Slug::try_new(DEMO_SLUG).unwrap();
270+ assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK);
271+
272+ tenants
273+ .set_status(&demo, crate::tenant::SchoolStatus::Suspended)
274+ .await
275+ .unwrap();
276+ assert_eq!(
277+ status(&app, "/school", Some(&school)).await,
278+ StatusCode::FORBIDDEN,
279+ "a suspended school must be refused immediately, cached handle or not"
280+ );
281+
282+ tenants
283+ .set_status(&demo, crate::tenant::SchoolStatus::Active)
284+ .await
285+ .unwrap();
286+ assert_eq!(
287+ status(&app, "/school", Some(&school)).await,
288+ StatusCode::OK,
289+ "un-suspending must restore the very same session"
290+ );
291+ }
292+
293+ #[test]
294+ fn a_cookie_splits_at_its_first_dot_or_not_at_all() {
295+ assert_eq!(split_cookie("demo.abc123"), Some(("demo", "abc123")));
296+ assert_eq!(split_cookie("builder.abc123"), Some(("builder", "abc123")));
297+ // First dot, so a dotted token still yields the school it named.
298+ assert_eq!(split_cookie("demo.a.b"), Some(("demo", "a.b")));
299+ // A pre-tenancy cookie, an empty half, or nothing at all names no
300+ // school — every one of these must be refused, not guessed at.
301+ for bad in ["abc123", "", ".", "demo.", ".abc123"] {
302+ assert_eq!(split_cookie(bad), None, "{bad:?}");
303+ }
304+ }
305+}
src/web/terms.rsmodified+2 -1
@@ -1,5 +1,6 @@
1+use crate::web::tenant_state::State;
12 use axum::Json;
2-use axum::extract::{Path, Query, State};
3+use axum::extract::{Path, Query};
34 use axum::http::StatusCode;
45 use serde::{Deserialize, Serialize};
56 use utoipa::ToSchema;
src/web/users.rsmodified+2 -1
@@ -1,5 +1,6 @@
1+use crate::web::tenant_state::State;
12 use axum::Json;
2-use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
3+use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
34 use axum::http::StatusCode;
45 use axum::response::Response;
56 use serde::{Deserialize, Serialize};
src/web/work.rsmodified+2 -1
@@ -1,5 +1,6 @@
1+use crate::web::tenant_state::State;
12 use axum::Json;
2-use axum::extract::{Path, Query, State};
3+use axum::extract::{Path, Query};
34 use axum::http::StatusCode;
45 use serde::{Deserialize, Serialize};
56 use utoipa::ToSchema;
tests/ai_bridge.rsmodified+6 -8
@@ -816,11 +816,10 @@ async fn the_alpn_and_the_protocol_id_are_the_same_string() {
816816 /// (status, body).
817817 async fn fetch_certificate(ai: Option<AiBridge>) -> (axum::http::StatusCode, Value) {
818818 use tower::ServiceExt;
819- let db = hezarfen_backend::database::init_mem()
820- .await
821- .expect("mem db");
819+ let (tenants, _db) = common::mem_deployment().await;
822820 let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState {
823- db,
821+ db: tenants.control().clone(),
822+ tenants,
824823 files_path: std::env::temp_dir(),
825824 cookie_secure: false,
826825 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
@@ -950,11 +949,10 @@ use surrealdb::types::RecordId;
950949
951950 /// A router wired to `bridge`, plus a handle to its in-memory database.
952951 async fn chat_app(bridge: &AiBridge) -> (Router, Database) {
953- let db = hezarfen_backend::database::init_mem()
954- .await
955- .expect("mem db");
952+ let (tenants, db) = common::mem_deployment().await;
956953 let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState {
957- db: db.clone(),
954+ db: tenants.control().clone(),
955+ tenants,
958956 files_path: common::files_dir(),
959957 cookie_secure: false,
960958 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
tests/ai_protocol.rsmodified+8 -3
@@ -920,11 +920,16 @@ async fn a_chat_request_names_the_askers_school_role() {
920920 let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
921921 await_workers(&bridge, 1).await;
922922
923- let db = hezarfen_backend::database::init_mem()
923+ let tenants = hezarfen_backend::database::init_mem_tenants()
924924 .await
925- .expect("mem db");
925+ .expect("in-memory deployment");
926+ let db = tenants
927+ .get(&hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap())
928+ .await
929+ .expect("the demo school");
926930 let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState {
927- db: db.clone(),
931+ db: tenants.control().clone(),
932+ tenants,
928933 files_path: common::files_dir(),
929934 cookie_secure: false,
930935 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
tests/auth_enumeration.rsmodified+5 -5
@@ -12,13 +12,13 @@ use serde_json::json;
1212 #[tokio::test]
1313 async fn duplicate_register_is_indistinguishable_from_a_fresh_one() {
1414 let (app, db) = app_and_db().await;
15- let taken = json!({ "username": "ada", "password": "secret1" });
15+ let taken = json!({ "school": "demo", "username": "ada", "password": "secret1" });
1616
1717 let first = send(&app, "POST", "/auth/register", None, Some(taken.clone())).await;
1818 assert_eq!(first.status, StatusCode::CREATED);
1919
2020 // Same username again, different password: still 201, same body shape.
21- let dup_creds = json!({ "username": "ada", "password": "attacker" });
21+ let dup_creds = json!({ "school": "demo", "username": "ada", "password": "attacker" });
2222 let started = Instant::now();
2323 let dup = send(
2424 &app,
@@ -35,7 +35,7 @@ async fn duplicate_register_is_indistinguishable_from_a_fresh_one() {
3535 "POST",
3636 "/auth/register",
3737 None,
38- Some(json!({ "username": "grace", "password": "secret1" })),
38+ Some(json!({ "school": "demo", "username": "grace", "password": "secret1" })),
3939 )
4040 .await;
4141
@@ -122,7 +122,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() {
122122 "POST",
123123 "/auth/register",
124124 None,
125- Some(json!({ "username": "ada", "password": "secret1" })),
125+ Some(json!({ "school": "demo", "username": "ada", "password": "secret1" })),
126126 )
127127 .await;
128128 let taken = send(
@@ -130,7 +130,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() {
130130 "POST",
131131 "/auth/register",
132132 None,
133- Some(json!({ "username": "ada", "password": "another1" })),
133+ Some(json!({ "school": "demo", "username": "ada", "password": "another1" })),
134134 )
135135 .await;
136136
tests/common/mod.rsmodified+62 -5
@@ -12,6 +12,7 @@ use hezarfen_backend::ai::AiBridge;
1212 use hezarfen_backend::database::Database;
1313 use hezarfen_backend::rate_limit::RateLimitConfig;
1414 use hezarfen_backend::state::{AppState, DbHealth};
15+use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants};
1516 use hezarfen_backend::{build_router, database};
1617 use serde_json::{Value, json};
1718 use tempfile::TempDir;
@@ -43,6 +44,49 @@ pub async fn app_and_db() -> (Router, Database) {
4344 app_with_ai(None).await
4445 }
4546
47+/// [`app_and_db`] plus the registry behind it, for the suites whose subject is
48+/// tenancy itself (a second school, a suspension, the builder surface).
49+pub async fn app_and_tenants() -> (Router, Database, Tenants) {
50+ let (app, db, tenants) = app_parts(None, Default::default()).await;
51+ (app, db, tenants)
52+}
53+
54+/// Where the demo school's blobs land: one directory per school under
55+/// `FILES_PATH`, created on the school's first upload.
56+pub fn blob_dir() -> PathBuf {
57+ let dir = files_dir().join(DEMO_SLUG);
58+ std::fs::create_dir_all(&dir).expect("blob dir");
59+ dir
60+}
61+
62+/// The raw session token out of a `session=<school>.<token>` cookie value —
63+/// what a test needs when it writes a session row by hand.
64+pub fn cookie_token(cookie: &str) -> &str {
65+ cookie
66+ .trim_start_matches("session=")
67+ .split_once('.')
68+ .expect("a session cookie carries its school")
69+ .1
70+}
71+
72+/// An in-memory deployment: the registry, plus the demo school's handle. For
73+/// the suites that build their own `AppState` instead of using [`app_and_db`].
74+pub async fn mem_deployment() -> (Tenants, Database) {
75+ let tenants = database::init_mem_tenants()
76+ .await
77+ .expect("in-memory deployment");
78+ let db = demo_db(&tenants).await;
79+ (tenants, db)
80+}
81+
82+/// The demo school's handle out of a registry.
83+pub async fn demo_db(tenants: &Tenants) -> Database {
84+ tenants
85+ .get(&Slug::try_new(DEMO_SLUG).expect("the demo slug"))
86+ .await
87+ .expect("the demo school resolves")
88+}
89+
4690 /// The same router, with the AI bridge wired into its state. `build_router`
4791 /// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the
4892 /// bootstrap that makes a QUIC service's reads dispatch into a real router.
@@ -54,9 +98,22 @@ pub async fn app_with_ai(ai: Option<AiBridge>) -> (Router, Database) {
5498 /// database socket down under a running app — the api-read path re-checks it in
5599 /// place of the HTTP db guard it bypasses.
56100 pub async fn app_with_ai_health(ai: Option<AiBridge>, db_up: DbHealth) -> (Router, Database) {
57- let db = database::init_mem().await.expect("in-memory db");
101+ let (app, db, _) = app_parts(ai, db_up).await;
102+ (app, db)
103+}
104+
105+/// The one bootstrap: an in-memory deployment (control database + the demo
106+/// school), a router over it, and the demo school's handle — which is what
107+/// every suite means by "the database", since that is where users and rows
108+/// live.
109+async fn app_parts(ai: Option<AiBridge>, db_up: DbHealth) -> (Router, Database, Tenants) {
110+ let tenants = database::init_mem_tenants()
111+ .await
112+ .expect("in-memory deployment");
113+ let db = demo_db(&tenants).await;
58114 let app = build_router(AppState {
59- db: db.clone(),
115+ db: tenants.control().clone(),
116+ tenants: tenants.clone(),
60117 files_path: files_dir(),
61118 cookie_secure: false,
62119 // Off, so suites hammering the API never trip a limit; the dedicated
@@ -68,7 +125,7 @@ pub async fn app_with_ai_health(ai: Option<AiBridge>, db_up: DbHealth) -> (Route
68125 db_up,
69126 ai,
70127 });
71- (app, db)
128+ (app, db, tenants)
72129 }
73130
74131 /// A router backed by a fresh in-memory database.
@@ -91,7 +148,7 @@ pub async fn set_role(db: &Database, username: &str, role: &str) {
91148 /// Register (password `secret1`), promote to `role`, then log in. Returns the
92149 /// session `Cookie` value.
93150 pub async fn login_as(app: &Router, db: &Database, username: &str, role: &str) -> String {
94- let creds = json!({ "username": username, "password": "secret1" });
151+ let creds = json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" });
95152 let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await;
96153 assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
97154 set_role(db, username, role).await;
@@ -265,7 +322,7 @@ pub async fn upload_course_note_file(
265322
266323 /// Register (password `secret1`) then log in; returns the session `Cookie` value.
267324 pub async fn login(app: &Router, username: &str) -> String {
268- let creds = json!({ "username": username, "password": "secret1" });
325+ let creds = json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" });
269326 let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await;
270327 assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
271328 let res = send(app, "POST", "/auth/login", None, Some(creds)).await;
tests/e2e.rsmodified+13 -5
@@ -4,6 +4,7 @@
44 use hezarfen_backend::database::Database;
55 use hezarfen_backend::rate_limit::RateLimitConfig;
66 use hezarfen_backend::state::AppState;
7+use hezarfen_backend::tenant::{DEMO_SLUG, Slug};
78 use hezarfen_backend::{build_router, database};
89 use reqwest::{Client, StatusCode};
910 use serde_json::{Value, json};
@@ -17,9 +18,16 @@ async fn spawn_server() -> (String, Database) {
1718
1819 /// [`spawn_server`], with the AI bridge the chatbot relays through wired in.
1920 async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (String, Database) {
20- let db = database::init_mem().await.expect("in-memory db");
21+ let tenants = database::init_mem_tenants()
22+ .await
23+ .expect("in-memory deployment");
24+ let db = tenants
25+ .get(&Slug::try_new(DEMO_SLUG).unwrap())
26+ .await
27+ .expect("the demo school");
2128 let app = build_router(AppState {
22- db: db.clone(),
29+ db: tenants.control().clone(),
30+ tenants,
2331 // Kept (not auto-deleted) so the directory outlives this helper;
2432 // it's under the OS temp dir, reclaimed like any other temp file.
2533 files_path: tempfile::tempdir().expect("files dir").keep(),
@@ -67,7 +75,7 @@ fn client() -> Client {
6775 async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response {
6876 client
6977 .post(format!("{base}/auth/register"))
70- .json(&json!({ "username": user, "password": "secret1" }))
78+ .json(&json!({ "school": "demo", "username": user, "password": "secret1" }))
7179 .send()
7280 .await
7381 .unwrap()
@@ -76,7 +84,7 @@ async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response
7684 async fn login(client: &Client, base: &str, user: &str) {
7785 let res = client
7886 .post(format!("{base}/auth/login"))
79- .json(&json!({ "username": user, "password": "secret1" }))
87+ .json(&json!({ "school": "demo", "username": user, "password": "secret1" }))
8088 .send()
8189 .await
8290 .unwrap();
@@ -422,7 +430,7 @@ async fn attendance_rollup_across_users() {
422430 async fn raw_session_cookie(base: &str, user: &str) -> String {
423431 let res = Client::new()
424432 .post(format!("{base}/auth/login"))
425- .json(&json!({ "username": user, "password": "secret1" }))
433+ .json(&json!({ "school": "demo", "username": user, "password": "secret1" }))
426434 .send()
427435 .await
428436 .unwrap();
tests/etag.rsmodified+1 -1
@@ -154,7 +154,7 @@ async fn handler_owned_etag_passes_through_and_never_304s() {
154154 #[tokio::test]
155155 async fn mutations_are_never_etagged() {
156156 let app = mem_app().await;
157- let creds = serde_json::json!({ "username": "ann", "password": "secret1" });
157+ let creds = serde_json::json!({ "school": "demo", "username": "ann", "password": "secret1" });
158158 let res = app
159159 .clone()
160160 .oneshot(
tests/integration.rsmodified+77 -64
@@ -10,6 +10,7 @@ use common::{
1010 create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll,
1111 upload_course_note_file,
1212 };
13+use hezarfen_backend::build_router;
1314 use hezarfen_backend::constant::{
1415 BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_COURSE_NOTE_FILES,
1516 MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS,
@@ -28,7 +29,6 @@ use hezarfen_backend::domain::session::Session;
2829 use hezarfen_backend::domain::timestamp::Timestamp;
2930 use hezarfen_backend::domain::user::{Password, User, UserId, Username};
3031 use hezarfen_backend::state::AppState;
31-use hezarfen_backend::{build_router, database};
3232 use serde_json::json;
3333 use tower::ServiceExt;
3434
@@ -150,7 +150,8 @@ async fn limits_publishes_the_bounds_the_api_actually_enforces() {
150150 let max = res.body["user"]["max_username_len"]
151151 .as_u64()
152152 .expect("max_username_len is an integer") as usize;
153- let too_long = json!({ "username": "a".repeat(max + 1), "password": "secret1" });
153+ let too_long =
154+ json!({ "school": "demo", "username": "a".repeat(max + 1), "password": "secret1" });
154155 let res = send(&app, "POST", "/auth/register", None, Some(too_long)).await;
155156 assert_eq!(res.status, StatusCode::BAD_REQUEST);
156157 }
@@ -162,8 +163,10 @@ async fn limits_still_answers_while_the_database_is_down() {
162163 // row, so the outage guard must let it through — otherwise the client
163164 // falls back to the hard-coded copy this endpoint exists to remove.
164165 let db_up = hezarfen_backend::state::DbHealth::default();
166+ let (tenants, _db) = common::mem_deployment().await;
165167 let app = build_router(AppState {
166- db: database::init_mem().await.expect("in-memory db"),
168+ db: tenants.control().clone(),
169+ tenants,
167170 files_path: tempfile::tempdir().expect("files dir").keep(),
168171 cookie_secure: false,
169172 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
@@ -190,25 +193,25 @@ async fn register_validates_input() {
190193 let app = mem_app().await;
191194
192195 // Password too short -> 400.
193- let short = json!({ "username": "bob", "password": "123" });
196+ let short = json!({ "school": "demo", "username": "bob", "password": "123" });
194197 let res = send(&app, "POST", "/auth/register", None, Some(short)).await;
195198 assert_eq!(res.status, StatusCode::BAD_REQUEST);
196199
197200 // Blank username -> 400.
198- let blank = json!({ "username": " ", "password": "secret1" });
201+ let blank = json!({ "school": "demo", "username": " ", "password": "secret1" });
199202 let res = send(&app, "POST", "/auth/register", None, Some(blank)).await;
200203 assert_eq!(res.status, StatusCode::BAD_REQUEST);
201204
202205 // Uppercase anywhere in the username -> 400.
203206 for bad in ["Bob", "bOb", "BOB"] {
204- let upper = json!({ "username": bad, "password": "secret1" });
207+ let upper = json!({ "school": "demo", "username": bad, "password": "secret1" });
205208 let res = send(&app, "POST", "/auth/register", None, Some(upper)).await;
206209 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted");
207210 }
208211
209212 // Username must start and end with a letter or digit -> 400.
210213 for bad in ["-bob", "bob-", "_bob", "bob_", ".bob"] {
211- let edge = json!({ "username": bad, "password": "secret1" });
214+ let edge = json!({ "school": "demo", "username": bad, "password": "secret1" });
212215 let res = send(&app, "POST", "/auth/register", None, Some(edge)).await;
213216 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted");
214217 }
@@ -223,26 +226,26 @@ async fn register_validates_input() {
223226 "a/b",
224227 "a\"b",
225228 ] {
226- let ugly = json!({ "username": bad, "password": "secret1" });
229+ let ugly = json!({ "school": "demo", "username": bad, "password": "secret1" });
227230 let res = send(&app, "POST", "/auth/register", None, Some(ugly)).await;
228231 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad:?} accepted");
229232 }
230233
231234 // Consecutive separators -> 400.
232235 for bad in ["a--b", "a..b", "a__b", "a.-b"] {
233- let doubled = json!({ "username": bad, "password": "secret1" });
236+ let doubled = json!({ "school": "demo", "username": bad, "password": "secret1" });
234237 let res = send(&app, "POST", "/auth/register", None, Some(doubled)).await;
235238 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted");
236239 }
237240
238241 // Single separators between alphanumerics are fine -> 201.
239- let dotted = json!({ "username": "ali.k_1-b", "password": "secret1" });
242+ let dotted = json!({ "school": "demo", "username": "ali.k_1-b", "password": "secret1" });
240243 let res = send(&app, "POST", "/auth/register", None, Some(dotted)).await;
241244 assert_eq!(res.status, StatusCode::CREATED);
242245 assert_eq!(res.body["username"], "ali.k_1-b");
243246
244247 // Valid -> 201, no password echoed back, defaults to the student role.
245- let ok = json!({ "username": "bob", "password": "secret1" });
248+ let ok = json!({ "school": "demo", "username": "bob", "password": "secret1" });
246249 let res = send(&app, "POST", "/auth/register", None, Some(ok.clone())).await;
247250 assert_eq!(res.status, StatusCode::CREATED);
248251 assert_eq!(res.body["username"], "bob");
@@ -253,7 +256,7 @@ async fn register_validates_input() {
253256 // deliberately indistinguishable — see tests/auth_enumeration.rs), but the
254257 // write is still rejected: the original password keeps working and the
255258 // second one never becomes valid.
256- let dup = json!({ "username": "bob", "password": "hijack1" });
259+ let dup = json!({ "school": "demo", "username": "bob", "password": "hijack1" });
257260 let res = send(&app, "POST", "/auth/register", None, Some(dup.clone())).await;
258261 assert_eq!(res.status, StatusCode::CREATED);
259262 let res = send(&app, "POST", "/auth/login", None, Some(ok)).await;
@@ -284,7 +287,7 @@ async fn register_rejects_reserved_usernames() {
284287 "moderator",
285288 "staff",
286289 ] {
287- let creds = json!({ "username": name, "password": "secret1" });
290+ let creds = json!({ "school": "demo", "username": name, "password": "secret1" });
288291 let res = send(&app, "POST", "/auth/register", None, Some(creds)).await;
289292 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{name} accepted");
290293 let msg = res.body["error"].as_str().unwrap_or_default();
@@ -298,7 +301,7 @@ async fn register_rejects_reserved_usernames() {
298301 // (created through `ensure_admin`, not `/auth/register`) still logs in.
299302 // Covered by the admin bootstrap tests; here just prove a reserved name
300303 // is not permanently poisoned for login by the register-level check.
301- let creds = json!({ "username": "admin", "password": "wrong" });
304+ let creds = json!({ "school": "demo", "username": "admin", "password": "wrong" });
302305 let res = send(&app, "POST", "/auth/login", None, Some(creds)).await;
303306 assert_eq!(res.status, StatusCode::UNAUTHORIZED); // bad credentials, not "reserved"
304307 }
@@ -311,7 +314,7 @@ async fn login_rejects_bad_credentials() {
311314 "POST",
312315 "/auth/register",
313316 None,
314- Some(json!({ "username": "kate", "password": "secret1" })),
317+ Some(json!({ "school": "demo", "username": "kate", "password": "secret1" })),
315318 )
316319 .await;
317320
@@ -321,7 +324,7 @@ async fn login_rejects_bad_credentials() {
321324 "POST",
322325 "/auth/login",
323326 None,
324- Some(json!({ "username": "kate", "password": "wrong" })),
327+ Some(json!({ "school": "demo", "username": "kate", "password": "wrong" })),
325328 )
326329 .await;
327330 assert_eq!(res.status, StatusCode::UNAUTHORIZED);
@@ -332,7 +335,7 @@ async fn login_rejects_bad_credentials() {
332335 "POST",
333336 "/auth/login",
334337 None,
335- Some(json!({ "username": "ghost", "password": "secret1" })),
338+ Some(json!({ "school": "demo", "username": "ghost", "password": "secret1" })),
336339 )
337340 .await;
338341 assert_eq!(res.status, StatusCode::UNAUTHORIZED);
@@ -627,7 +630,7 @@ async fn a_demotion_to_parent_strands_no_note_and_no_blob() {
627630 .await;
628631 assert_eq!(up.status, StatusCode::CREATED);
629632 let file_id = id_of(&up.body);
630- let blob = common::files_dir().join(&file_id);
633+ let blob = common::blob_dir().join(&file_id);
631634 assert!(blob.exists(), "the upload must have written a blob");
632635
633636 // Demote through the real route, not a seeded role.
@@ -745,7 +748,7 @@ async fn a_demotion_to_parent_strands_no_note_and_no_blob() {
745748 StatusCode::NO_CONTENT
746749 );
747750 assert!(!blob.exists(), "deleting a file must unlink its blob");
748- let extra_blob = common::files_dir().join(id_of(&extra.body));
751+ let extra_blob = common::blob_dir().join(id_of(&extra.body));
749752 assert_eq!(
750753 send(
751754 &app,
@@ -959,7 +962,7 @@ async fn note_files_upload_download_delete_roundtrip() {
959962 StatusCode::NOT_FOUND
960963 );
961964 assert!(
962- !common::files_dir().join(&file_id).exists(),
965+ !common::blob_dir().join(&file_id).exists(),
963966 "blob must be unlinked with its row"
964967 );
965968 }
@@ -1238,13 +1241,13 @@ async fn malformed_json_bodies_answer_422_across_every_extractor_shape() {
12381241 (
12391242 "/auth/register",
12401243 None,
1241- r#"{"username": 5, "password": "secret1"}"#,
1244+ r#"{"school": "demo", "username": 5, "password": "secret1"}"#,
12421245 "plain Json, type mismatch",
12431246 ),
12441247 (
12451248 "/auth/register",
12461249 None,
1247- r#"{"username": "veli"}"#,
1250+ r#"{"school": "demo", "username": "veli"}"#,
12481251 "plain Json, missing required field",
12491252 ),
12501253 (
@@ -1288,7 +1291,7 @@ async fn malformed_json_bodies_answer_422_across_every_extractor_shape() {
12881291 for (body, why) in [
12891292 ("not json at all", "unparseable JSON"),
12901293 (
1291- r#"{"username": "a", "password": "secret1"}"#,
1294+ r#"{"school": "demo", "username": "a", "password": "secret1"}"#,
12921295 "well-typed value refused by a domain rule",
12931296 ),
12941297 ] {
@@ -1397,7 +1400,7 @@ async fn deleting_a_note_removes_its_files() {
13971400 let left: Vec<serde_json::Value> = rows.take(0).unwrap();
13981401 assert!(left.is_empty(), "note_file rows must cascade: {left:?}");
13991402 assert!(
1400- !common::files_dir().join(&file_id).exists(),
1403+ !common::blob_dir().join(&file_id).exists(),
14011404 "blob must be unlinked when its note dies"
14021405 );
14031406 }
@@ -5924,7 +5927,7 @@ async fn expired_session_is_unauthorized_before_any_purge() {
59245927 user = (SELECT VALUE user FROM ONLY session WHERE token = $live LIMIT 1), \
59255928 token = 'stale-token', expires_at = 1",
59265929 )
5927- .bind(("live", ali.trim_start_matches("session=").to_string()))
5930+ .bind(("live", common::cookie_token(&ali).to_string()))
59285931 .await
59295932 .unwrap()
59305933 .check()
@@ -5959,7 +5962,9 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
59595962 "POST",
59605963 "/auth/register",
59615964 None,
5962- Some(json!({ "username": "ali", "password": "secret1" })),
5965+ Some(
5966+ json!({ "school": "demo", "school": "demo", "username": "ali", "password": "secret1" }),
5967+ ),
59635968 )
59645969 .await;
59655970 assert_eq!(res.status, StatusCode::CREATED);
@@ -5974,7 +5979,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
59745979 "POST",
59755980 "/auth/register",
59765981 None,
5977- Some(json!({ "username": spoof, "password": "spoof1" })),
5982+ Some(json!({ "school": "demo", "username": spoof, "password": "spoof1" })),
59785983 )
59795984 .await;
59805985 assert_eq!(res.status, StatusCode::CREATED, "{spoof:?}");
@@ -6008,7 +6013,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
60086013 "POST",
60096014 "/auth/login",
60106015 None,
6011- Some(json!({ "username": attempt, "password": "secret1" })),
6016+ Some(json!({ "school": "demo", "username": attempt, "password": "secret1" })),
60126017 )
60136018 .await;
60146019 assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}");
@@ -6017,7 +6022,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
60176022 "POST",
60186023 "/auth/login",
60196024 None,
6020- Some(json!({ "username": attempt, "password": "spoof1" })),
6025+ Some(json!({ "school": "demo", "username": attempt, "password": "spoof1" })),
60216026 )
60226027 .await;
60236028 assert_eq!(
@@ -6033,7 +6038,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
60336038 "POST",
60346039 "/auth/register",
60356040 None,
6036- Some(json!({ "username": " veli ", "password": "secret1" })),
6041+ Some(json!({ "school": "demo", "username": " veli ", "password": "secret1" })),
60376042 )
60386043 .await;
60396044 assert_eq!(res.status, StatusCode::CREATED);
@@ -6046,7 +6051,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
60466051 "POST",
60476052 "/auth/login",
60486053 None,
6049- Some(json!({ "username": attempt, "password": "secret1" })),
6054+ Some(json!({ "school": "demo", "username": attempt, "password": "secret1" })),
60506055 )
60516056 .await;
60526057 assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}");
@@ -6340,7 +6345,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
63406345 "POST",
63416346 "/auth/register",
63426347 None,
6343- Some(json!({ "username": "dup", "password": "secret1" })),
6348+ Some(json!({ "school": "demo", "username": "dup", "password": "secret1" })),
63446349 )
63456350 .await
63466351 .status
@@ -6378,7 +6383,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
63786383 "POST",
63796384 "/auth/register",
63806385 None,
6381- Some(json!({ "username": "dup", "password": "hijack1" })),
6386+ Some(json!({ "school": "demo", "username": "dup", "password": "hijack1" })),
63826387 )
63836388 .await;
63846389 assert_eq!(res.status, StatusCode::CREATED);
@@ -6387,7 +6392,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
63876392 "POST",
63886393 "/auth/login",
63896394 None,
6390- Some(json!({ "username": "dup", "password": "secret1" })),
6395+ Some(json!({ "school": "demo", "username": "dup", "password": "secret1" })),
63916396 )
63926397 .await;
63936398 assert_eq!(res.status, StatusCode::OK, "the winning password broke");
@@ -6396,7 +6401,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
63966401 "POST",
63976402 "/auth/login",
63986403 None,
6399- Some(json!({ "username": "dup", "password": "hijack1" })),
6404+ Some(json!({ "school": "demo", "username": "dup", "password": "hijack1" })),
64006405 )
64016406 .await;
64026407 assert_eq!(
@@ -6465,7 +6470,7 @@ async fn child_lists_of_missing_parents_are_404() {
64656470 #[tokio::test]
64666471 async fn session_cookie_secure_attribute_follows_config() {
64676472 async fn login_set_cookie(app: &axum::Router) -> String {
6468- let creds = json!({ "username": "ada", "password": "secret1" });
6473+ let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" });
64696474 assert_eq!(
64706475 send(app, "POST", "/auth/register", None, Some(creds.clone()))
64716476 .await
@@ -6507,9 +6512,10 @@ async fn session_cookie_secure_attribute_follows_config() {
65076512 );
65086513
65096514 // With the flag on: Secure present.
6510- let db = database::init_mem().await.unwrap();
6515+ let (tenants, _db) = common::mem_deployment().await;
65116516 let app = build_router(AppState {
6512- db,
6517+ db: tenants.control().clone(),
6518+ tenants,
65136519 files_path: common::files_dir(),
65146520 cookie_secure: true,
65156521 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
@@ -6546,10 +6552,11 @@ async fn db_down_refuses_before_touching_the_database() {
65466552 ids.len()
65476553 }
65486554
6549- let db = database::init_mem().await.unwrap();
6555+ let (tenants, db) = common::mem_deployment().await;
65506556 let db_up = hezarfen_backend::state::DbHealth::default();
65516557 let app = build_router(AppState {
6552- db: db.clone(),
6558+ db: tenants.control().clone(),
6559+ tenants,
65536560 files_path: common::files_dir(),
65546561 cookie_secure: false,
65556562 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
@@ -6570,7 +6577,8 @@ async fn db_down_refuses_before_touching_the_database() {
65706577 .uri("/auth/register")
65716578 .header("content-type", "application/json")
65726579 .body(Body::from(
6573- json!({"username": "gulsah", "password": "sifre12345"}).to_string(),
6580+ json!({"school": "demo", "username": "gulsah", "password": "sifre12345"})
6581+ .to_string(),
65746582 ))
65756583 .unwrap(),
65766584 )
@@ -6594,7 +6602,8 @@ async fn db_down_refuses_before_touching_the_database() {
65946602 .uri("/auth/register")
65956603 .header("content-type", "application/json")
65966604 .body(Body::from(
6597- json!({"username": "kerem", "password": "sifre12345"}).to_string(),
6605+ json!({"school": "demo", "username": "kerem", "password": "sifre12345"})
6606+ .to_string(),
65986607 ))
65996608 .unwrap(),
66006609 )
@@ -6621,7 +6630,8 @@ async fn db_down_refuses_before_touching_the_database() {
66216630 .uri("/auth/register")
66226631 .header("content-type", "application/json")
66236632 .body(Body::from(
6624- json!({"username": "kerem", "password": "sifre12345"}).to_string(),
6633+ json!({"school": "demo", "username": "kerem", "password": "sifre12345"})
6634+ .to_string(),
66256635 ))
66266636 .unwrap(),
66276637 )
@@ -6814,7 +6824,7 @@ async fn admin_seed_creates_working_admin() {
68146824 let password = Password::try_new("secret1").unwrap();
68156825 User::ensure_admin(username, password, &db).await.unwrap();
68166826
6817- let creds = json!({ "username": "root", "password": "secret1" });
6827+ let creds = json!({ "school": "demo", "username": "root", "password": "secret1" });
68186828 let res = send(&app, "POST", "/auth/login", None, Some(creds)).await;
68196829 assert_eq!(res.status, StatusCode::OK);
68206830 assert_eq!(res.body["role"], "admin");
@@ -6836,7 +6846,7 @@ async fn admin_seed_is_idempotent() {
68366846 }
68376847
68386848 let cookie = {
6839- let creds = json!({ "username": "root", "password": "secret1" });
6849+ let creds = json!({ "school": "demo", "username": "root", "password": "secret1" });
68406850 let res = send(&app, "POST", "/auth/login", None, Some(creds)).await;
68416851 assert_eq!(res.status, StatusCode::OK);
68426852 res.cookie.expect("session cookie")
@@ -6863,7 +6873,7 @@ async fn admin_seed_refuses_existing_non_admin() {
68636873 assert_eq!(res.status, StatusCode::FORBIDDEN, "must not be promoted");
68646874
68656875 // ...and the original password still logs in (nothing was overwritten).
6866- let creds = json!({ "username": "squatter", "password": "secret1" });
6876+ let creds = json!({ "school": "demo", "username": "squatter", "password": "secret1" });
68676877 let res = send(&app, "POST", "/auth/login", None, Some(creds)).await;
68686878 assert_eq!(res.status, StatusCode::OK);
68696879 assert_eq!(res.body["role"], "student");
@@ -12450,7 +12460,7 @@ async fn question_images_author_serve_and_cascade() {
1245012460 assert_eq!(keys_before.len(), keys_after.len(), "replace adds no row");
1245112461 for stale in keys_before.iter().filter(|k| !keys_after.contains(k)) {
1245212462 assert!(
12453- !common::files_dir().join(stale).exists(),
12463+ !common::blob_dir().join(stale).exists(),
1245412464 "replaced blob lingers on disk"
1245512465 );
1245612466 }
@@ -12530,7 +12540,7 @@ async fn question_images_author_serve_and_cascade() {
1253012540 );
1253112541 for key in &keys {
1253212542 assert!(
12533- !common::files_dir().join(key).exists(),
12543+ !common::blob_dir().join(key).exists(),
1253412544 "blob {key} survived the exam delete"
1253512545 );
1253612546 }
@@ -12698,7 +12708,7 @@ async fn student_answer_images_serve_and_cascade() {
1269812708 // seq-1 answer-image row *and* its on-disk blob survive the new sitting.
1269912709 let pre = answer_image_blob_keys(&db).await;
1270012710 assert_eq!(pre.len(), 1);
12701- assert!(common::files_dir().join(&pre[0]).exists());
12711+ assert!(common::blob_dir().join(&pre[0]).exists());
1270212712 let res = send(
1270312713 &app,
1270412714 "POST",
@@ -12724,7 +12734,7 @@ async fn student_answer_images_serve_and_cascade() {
1272412734 "the retake kept the prior sitting's answer-image row (history)"
1272512735 );
1272612736 assert!(
12727- common::files_dir().join(&pre[0]).exists(),
12737+ common::blob_dir().join(&pre[0]).exists(),
1272812738 "the retake kept the prior sitting's answer-image blob on disk"
1272912739 );
1273012740
@@ -12749,7 +12759,7 @@ async fn student_answer_images_serve_and_cascade() {
1274912759 );
1275012760 for key in &keys {
1275112761 assert!(
12752- !common::files_dir().join(key).exists(),
12762+ !common::blob_dir().join(key).exists(),
1275312763 "answer-image blob {key} survived the exam delete"
1275412764 );
1275512765 }
@@ -12963,7 +12973,7 @@ async fn question_image_edits_follow_the_choices() {
1296312973 assert_eq!(dropped.len(), 1, "only the removed option's blob may go");
1296412974 for key in dropped {
1296512975 assert!(
12966- !common::files_dir().join(key).exists(),
12976+ !common::blob_dir().join(key).exists(),
1296712977 "dropped option blob lingers"
1296812978 );
1296912979 }
@@ -13028,7 +13038,7 @@ async fn question_image_edits_follow_the_choices() {
1302813038 assert!(image_blob_keys(&db).await.is_empty());
1302913039 for key in &keys {
1303013040 assert!(
13031- !common::files_dir().join(key).exists(),
13041+ !common::blob_dir().join(key).exists(),
1303213042 "blob {key} survived the question delete"
1303313043 );
1303413044 }
@@ -15685,7 +15695,7 @@ async fn homework_files_roundtrip_and_scope() {
1568515695 let res = send(&app, "DELETE", &file_uri, Some(&w.ali), None).await;
1568615696 assert_eq!(res.status, StatusCode::NO_CONTENT);
1568715697 assert!(
15688- !common::files_dir().join(&keys[0]).exists(),
15698+ !common::blob_dir().join(&keys[0]).exists(),
1568915699 "blob must be unlinked with its row"
1569015700 );
1569115701 let res = send(
@@ -16026,7 +16036,7 @@ async fn homework_gc_removes_rows_and_blobs() {
1602616036 let keys = homework_blob_keys(&db).await;
1602716037 assert_eq!(keys.len(), 3);
1602816038 for key in &keys {
16029- assert!(common::files_dir().join(key).exists(), "blob {key} on disk");
16039+ assert!(common::blob_dir().join(key).exists(), "blob {key} on disk");
1603016040 }
1603116041
1603216042 // Withdrawing a submission takes its file rows and blobs.
@@ -16043,7 +16053,7 @@ async fn homework_gc_removes_rows_and_blobs() {
1604316053 assert_eq!(remaining.len(), 2);
1604416054 for gone in keys.iter().filter(|key| !remaining.contains(key)) {
1604516055 assert!(
16046- !common::files_dir().join(gone).exists(),
16056+ !common::blob_dir().join(gone).exists(),
1604716057 "withdrawn blob {gone} must be unlinked"
1604816058 );
1604916059 }
@@ -16065,7 +16075,7 @@ async fn homework_gc_removes_rows_and_blobs() {
1606516075 assert_eq!(hw_row_count(&db, "homework").await, 1, "hw2 remains");
1606616076 for key in &remaining {
1606716077 assert!(
16068- !common::files_dir().join(key).exists(),
16078+ !common::blob_dir().join(key).exists(),
1606916079 "blob {key} must die with the homework"
1607016080 );
1607116081 }
@@ -16102,7 +16112,7 @@ async fn homework_gc_removes_rows_and_blobs() {
1610216112 }
1610316113 for key in &keys {
1610416114 assert!(
16105- !common::files_dir().join(key).exists(),
16115+ !common::blob_dir().join(key).exists(),
1610616116 "blob {key} must die with the course"
1610716117 );
1610816118 }
@@ -16482,9 +16492,10 @@ async fn chat_app_limited(
1648216492 ai: Option<AiBridge>,
1648316493 chatbot_limit: hezarfen_backend::rate_limit::UserRateLimiter,
1648416494 ) -> (axum::Router, Database) {
16485- let db = database::init_mem().await.expect("in-memory db");
16495+ let (tenants, db) = common::mem_deployment().await;
1648616496 let app = build_router(AppState {
16487- db: db.clone(),
16497+ db: tenants.control().clone(),
16498+ tenants,
1648816499 files_path: common::files_dir(),
1648916500 cookie_secure: false,
1649016501 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
@@ -20048,7 +20059,7 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() {
2004820059 // unreadable source mid-flight.
2004920060 let src_keys = bank_image_blob_keys(&db).await;
2005020061 assert_eq!(src_keys.len(), 2);
20051- tokio::fs::remove_file(common::files_dir().join(&src_keys[0]))
20062+ tokio::fs::remove_file(common::blob_dir().join(&src_keys[0]))
2005220063 .await
2005320064 .unwrap();
2005420065
@@ -20105,7 +20116,7 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() {
2010520116 "source bank rows changed"
2010620117 );
2010720118 assert!(
20108- common::files_dir().join(&src_keys[1]).exists(),
20119+ common::blob_dir().join(&src_keys[1]).exists(),
2010920120 "surviving source blob vanished"
2011020121 );
2011120122 }
@@ -24478,7 +24489,9 @@ async fn the_statement_reports_overdue_and_its_rollup_matches_the_balance() {
2447824489 "POST",
2447924490 "/auth/login",
2448024491 None,
24481- Some(json!({ "username": "ali", "password": "secret1" })),
24492+ Some(
24493+ json!({ "school": "demo", "school": "demo", "username": "ali", "password": "secret1" }),
24494+ ),
2448224495 )
2448324496 .await
2448424497 .cookie
@@ -27171,7 +27184,7 @@ async fn course_note_cap_refusal_and_course_delete_leave_no_orphan_blobs() {
2717127184 )
2717227185 .await;
2717327186 assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
27174- blob_paths.push(common::files_dir().join(id_of(&r.body)));
27187+ blob_paths.push(common::blob_dir().join(id_of(&r.body)));
2717527188 }
2717627189 for p in &blob_paths {
2717727190 assert!(p.exists(), "blob missing after upload: {p:?}");
tests/pagination.rsmodified+3 -2
@@ -14,7 +14,7 @@ use serde_json::json;
1414 async fn seed_students(app: &axum::Router, n: usize) {
1515 for i in 0..n {
1616 let name = format!("user{i:02}");
17- let creds = json!({ "username": name, "password": "secret1" });
17+ let creds = json!({ "school": "demo", "username": name, "password": "secret1" });
1818 let res = send(app, "POST", "/auth/register", None, Some(creds)).await;
1919 assert_eq!(res.status, StatusCode::CREATED, "register {name}");
2020 }
@@ -322,7 +322,8 @@ async fn user_search_is_paged_not_capped() {
322322 let teacher = login_as(&app, &db, "teacher", "teacher").await;
323323 // 12 accounts sharing the "grp" fragment — past the old cap.
324324 for i in 0..12 {
325- let creds = json!({ "username": format!("grp{i:02}"), "password": "secret1" });
325+ let creds =
326+ json!({ "school": "demo", "username": format!("grp{i:02}"), "password": "secret1" });
326327 let res = send(&app, "POST", "/auth/register", None, Some(creds)).await;
327328 assert_eq!(res.status, StatusCode::CREATED);
328329 }
tests/persistence.rsmodified+31 -20
@@ -13,6 +13,7 @@ use hezarfen_backend::database::Database;
1313 use hezarfen_backend::domain::timestamp::Timestamp;
1414 use hezarfen_backend::rate_limit::RateLimitConfig;
1515 use hezarfen_backend::state::AppState;
16+use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants};
1617 use hezarfen_backend::{build_router, database};
1718 use serde_json::json;
1819
@@ -20,8 +21,18 @@ use serde_json::json;
2021 /// a fresh router over it.
2122 async fn reboot(db: &Database) -> Router {
2223 database::migrate(db).await.expect("re-migration");
24+ // A new process: a new control database and a new connection cache, over
25+ // the school store the old one left behind.
26+ let tenants = Tenants::new_mem_adopting(
27+ &Slug::try_new(DEMO_SLUG).unwrap(),
28+ "Demo School",
29+ db.clone(),
30+ )
31+ .await
32+ .expect("adopt the demo school");
2333 build_router(AppState {
24- db: db.clone(),
34+ db: tenants.control().clone(),
35+ tenants,
2536 files_path: common::files_dir(),
2637 cookie_secure: false,
2738 rate_limit: RateLimitConfig::unlimited(),
@@ -40,7 +51,7 @@ async fn reboot(db: &Database) -> Router {
4051 async fn settings_and_terms_survive_remigration() {
4152 let (app, db) = common::app_and_db().await;
4253
43- let creds = json!({ "username": "boss", "password": "secret1" });
54+ let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" });
4455 send(&app, "POST", "/auth/register", None, Some(creds.clone())).await;
4556 set_role(&db, "boss", "manager").await;
4657 let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone()))
@@ -119,7 +130,7 @@ async fn settings_and_terms_survive_remigration() {
119130 #[tokio::test]
120131 async fn legacy_events_backfill_to_school_audience() {
121132 let (app, db) = common::app_and_db().await;
122- let creds = json!({ "username": "ali", "password": "secret1" });
133+ let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
123134
124135 // A normal event — then strip its audience the way an old binary's schema
125136 // would have left it: drop the column definitions so SCHEMAFULL stops
@@ -196,7 +207,7 @@ async fn legacy_events_backfill_to_school_audience() {
196207 #[tokio::test]
197208 async fn legacy_users_audiences_convert_to_registrations() {
198209 let (app, db) = common::app_and_db().await;
199- let creds = json!({ "username": "ali", "password": "secret1" });
210+ let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
200211
201212 // A registration-audience event — then rewrite it into the shape an old
202213 // binary left behind: restore the `audience.users` column definition and
@@ -212,7 +223,7 @@ async fn legacy_users_audiences_convert_to_registrations() {
212223 .await
213224 .cookie
214225 .unwrap();
215- let student = json!({ "username": "veli", "password": "secret1" });
226+ let student = json!({ "school": "demo", "username": "veli", "password": "secret1" });
216227 assert_eq!(
217228 send(&app, "POST", "/auth/register", None, Some(student.clone()))
218229 .await
@@ -294,7 +305,7 @@ async fn legacy_users_audiences_convert_to_registrations() {
294305 #[tokio::test]
295306 async fn legacy_subjectless_questions_are_destroyed_on_boot() {
296307 let (app, db) = common::app_and_db().await;
297- let creds = json!({ "username": "ali", "password": "secret1" });
308+ let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
298309
299310 // A full exam — course, subject, open exam, one answered question — then
300311 // strip the question's subject the way an old binary's schema would have
@@ -310,7 +321,7 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() {
310321 .await
311322 .cookie
312323 .unwrap();
313- let student = json!({ "username": "veli", "password": "secret1" });
324+ let student = json!({ "school": "demo", "username": "veli", "password": "secret1" });
314325 assert_eq!(
315326 send(&app, "POST", "/auth/register", None, Some(student.clone()))
316327 .await
@@ -434,7 +445,7 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() {
434445 #[tokio::test]
435446 async fn stale_staff_enrollments_are_swept_on_boot() {
436447 let (app, db) = common::app_and_db().await;
437- let creds = json!({ "username": "ali", "password": "secret1" });
448+ let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
438449
439450 // A course with three enrolled students, then age two rows the way a
440451 // pre-fix binary could have — flip one student to teacher directly in the
@@ -454,7 +465,7 @@ async fn stale_staff_enrollments_are_swept_on_boot() {
454465
455466 let mut ids = Vec::new();
456467 for name in ["veli", "ayse", "can"] {
457- let student = json!({ "username": name, "password": "secret1" });
468+ let student = json!({ "school": "demo", "username": name, "password": "secret1" });
458469 assert_eq!(
459470 send(&app, "POST", "/auth/register", None, Some(student.clone()))
460471 .await
@@ -646,8 +657,8 @@ async fn a_course_whose_count_outran_its_roster_is_repaired_and_deletable() {
646657 #[tokio::test]
647658 async fn legacy_exams_backfill_to_published() {
648659 let (app, db) = common::app_and_db().await;
649- let teacher_creds = json!({ "username": "ali", "password": "secret1" });
650- let student_creds = json!({ "username": "ayse", "password": "secret1" });
660+ let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
661+ let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" });
651662
652663 // A normal exam — then strip `draft` the way an old binary's schema would
653664 // have left it.
@@ -732,8 +743,8 @@ async fn appointments_survive_remigration() {
732743 const PROPOSED_END: i64 = START + 8_000_003;
733744
734745 let (app, db) = common::app_and_db().await;
735- let teacher_creds = json!({ "username": "ali", "password": "secret1" });
736- let student_creds = json!({ "username": "ayse", "password": "secret1" });
746+ let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
747+ let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" });
737748 for creds in [&teacher_creds, &student_creds] {
738749 assert_eq!(
739750 send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
@@ -879,8 +890,8 @@ async fn appointments_survive_remigration() {
879890 #[tokio::test]
880891 async fn attempt_history_survives_remigration() {
881892 let (app, db) = common::app_and_db().await;
882- let teacher_creds = json!({ "username": "ali", "password": "secret1" });
883- let student_creds = json!({ "username": "ayse", "password": "secret1" });
893+ let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
894+ let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" });
884895 for creds in [&teacher_creds, &student_creds] {
885896 assert_eq!(
886897 send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
@@ -1164,7 +1175,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
11641175 use hezarfen_backend::domain::user::UserId;
11651176
11661177 let (app, db) = common::app_and_db().await;
1167- let creds = json!({ "username": "ali", "password": "secret1" });
1178+ let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
11681179 assert_eq!(
11691180 send(&app, "POST", "/auth/register", None, Some(creds.clone()))
11701181 .await
@@ -1244,7 +1255,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
12441255 async fn settings_slots_without_a_serving_minute_still_patch() {
12451256 let (app, db) = common::app_and_db().await;
12461257
1247- let creds = json!({ "username": "boss", "password": "secret1" });
1258+ let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" });
12481259 send(&app, "POST", "/auth/register", None, Some(creds.clone())).await;
12491260 set_role(&db, "boss", "manager").await;
12501261 let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone()))
@@ -1948,8 +1959,8 @@ async fn settings_reference_counts_are_seeded_from_the_marks_and_menus_that_pred
19481959 #[tokio::test]
19491960 async fn fee_plans_and_their_charges_survive_remigration() {
19501961 let (app, db) = common::app_and_db().await;
1951- let manager_creds = json!({ "username": "ali", "password": "secret1" });
1952- let student_creds = json!({ "username": "ayse", "password": "secret1" });
1962+ let manager_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
1963+ let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" });
19531964 for creds in [&manager_creds, &student_creds] {
19541965 assert_eq!(
19551966 send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
@@ -2102,7 +2113,7 @@ async fn a_user_row_without_palette_color_still_reads_and_patches() {
21022113 #[tokio::test]
21032114 async fn boards_and_their_strokes_survive_remigration() {
21042115 let (app, db) = common::app_and_db().await;
2105- let creds = json!({ "username": "ali", "password": "secret1" });
2116+ let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
21062117 let cookie = common::login(&app, "ali").await;
21072118 let veli = common::login(&app, "veli").await;
21082119 let ali_id = me_id(&app, &cookie).await;
tests/rate_limit.rsmodified+14 -8
@@ -18,9 +18,12 @@ use tower::ServiceExt;
1818
1919 /// App with the given limits, backed by a fresh in-memory database.
2020 async fn app_with(rate_limit: RateLimitConfig) -> Router {
21- let db = database::init_mem().await.expect("in-memory db");
21+ let tenants = database::init_mem_tenants()
22+ .await
23+ .expect("in-memory deployment");
2224 build_router(AppState {
23- db,
25+ db: tenants.control().clone(),
26+ tenants,
2427 files_path: tempfile::tempdir().expect("files dir").keep(),
2528 cookie_secure: false,
2629 rate_limit,
@@ -68,7 +71,7 @@ async fn send_as(
6871 }
6972
7073 fn bad_login() -> Option<Value> {
71- Some(json!({ "username": "ghost", "password": "wrong-pass" }))
74+ Some(json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" }))
7275 }
7376
7477 fn auth_only(per_minute: u32) -> RateLimitConfig {
@@ -103,7 +106,7 @@ async fn login_attempts_hit_the_auth_limit() {
103106 #[tokio::test]
104107 async fn register_and_login_share_the_auth_bucket() {
105108 let app = app_with(auth_only(2)).await;
106- let creds = json!({ "username": "ada", "password": "secret1" });
109+ let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" });
107110
108111 let (status, _, _) = send_as(
109112 &app,
@@ -530,9 +533,12 @@ async fn a_down_database_leaves_each_process_on_its_local_budget() {
530533
531534 /// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`.
532535 async fn spawn_server(rate_limit: RateLimitConfig) -> String {
533- let db = database::init_mem().await.expect("in-memory db");
536+ let tenants = database::init_mem_tenants()
537+ .await
538+ .expect("in-memory deployment");
534539 let app = build_router(AppState {
535- db,
540+ db: tenants.control().clone(),
541+ tenants,
536542 files_path: tempfile::tempdir().expect("files dir").keep(),
537543 cookie_secure: false,
538544 rate_limit,
@@ -571,7 +577,7 @@ async fn real_connections_are_keyed_by_peer_address() {
571577 let res = client
572578 .post(format!("{base}/auth/login"))
573579 .header("x-forwarded-for", spoof)
574- .json(&json!({ "username": "ghost", "password": "wrong-pass" }))
580+ .json(&json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" }))
575581 .send()
576582 .await
577583 .unwrap();
@@ -581,7 +587,7 @@ async fn real_connections_are_keyed_by_peer_address() {
581587 let res = client
582588 .post(format!("{base}/auth/login"))
583589 .header("x-forwarded-for", "3.3.3.3")
584- .json(&json!({ "username": "ghost", "password": "wrong-pass" }))
590+ .json(&json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" }))
585591 .send()
586592 .await
587593 .unwrap();
tests/regress_bank_images.rsmodified+10 -4
@@ -27,6 +27,7 @@ mod common;
2727 use axum::Router;
2828 use axum::http::StatusCode;
2929 use common::{create_course, create_subject, id_of, login_as, send};
30+use hezarfen_backend::build_router;
3031 use hezarfen_backend::database::Database;
3132 use hezarfen_backend::domain::bank_question::BankQuestionId;
3233 use hezarfen_backend::domain::bank_question_image::BankQuestionImage;
@@ -34,7 +35,6 @@ use hezarfen_backend::domain::note_file::FileContentType;
3435 use hezarfen_backend::error::AppError;
3536 use hezarfen_backend::rate_limit::RateLimitConfig;
3637 use hezarfen_backend::state::AppState;
37-use hezarfen_backend::{build_router, database};
3838 use serde_json::json;
3939 use tempfile::TempDir;
4040
@@ -43,10 +43,11 @@ const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary";
4343 /// A router over a fresh in-memory database, with a blob directory nothing else
4444 /// writes to — so `blobs()` counts this test's files and no one else's.
4545 async fn mem_app() -> (Router, Database, TempDir) {
46- let db = database::init_mem().await.expect("in-memory db");
46+ let (tenants, db) = common::mem_deployment().await;
4747 let files = tempfile::tempdir().expect("files tempdir");
4848 let app = build_router(AppState {
49- db: db.clone(),
49+ db: tenants.control().clone(),
50+ tenants,
5051 files_path: files.path().to_path_buf(),
5152 cookie_secure: false,
5253 rate_limit: RateLimitConfig::unlimited(),
@@ -61,7 +62,12 @@ async fn mem_app() -> (Router, Database, TempDir) {
6162
6263 /// Every blob file currently on disk, by name.
6364 fn blobs(files: &TempDir) -> Vec<String> {
64- let mut names: Vec<String> = std::fs::read_dir(files.path())
65+ // Blobs live under the school's own subdirectory of `FILES_PATH`.
66+ let dir = files.path().join(hezarfen_backend::tenant::DEMO_SLUG);
67+ if !dir.exists() {
68+ return Vec::new();
69+ }
70+ let mut names: Vec<String> = std::fs::read_dir(&dir)
6571 .expect("read the blob dir")
6672 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
6773 .collect();
tests/regress_profile.rsmodified+1 -1
@@ -47,7 +47,7 @@ async fn upload_avatar(
4747 /// by every app in this binary, so a payload no other test writes is the only
4848 /// concurrency-safe way to count one test's own blobs.
4949 fn blobs_holding(bytes: &[u8]) -> usize {
50- std::fs::read_dir(common::files_dir())
50+ std::fs::read_dir(common::blob_dir())
5151 .expect("files dir")
5252 .filter_map(|entry| std::fs::read(entry.expect("dir entry").path()).ok())
5353 .filter(|found| found == bytes)
tests/regress_roles.rsmodified+2 -1
@@ -196,7 +196,8 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() {
196196 "/auth/login",
197197 None,
198198 Some(json!({
199- "username": "ali", "password": "secret1"
199+ "school": "demo",
200+ "school": "demo", "username": "ali", "password": "secret1"
200201 })),
201202 )
202203 .await
tests/spec_bounds.rsmodified+7 -2
@@ -24,9 +24,12 @@ use tower::ServiceExt;
2424
2525 /// The emitted OpenAPI document, as the server serves it.
2626 async fn spec() -> Value {
27- let db = database::init_mem().await.expect("in-memory db");
27+ let tenants = database::init_mem_tenants()
28+ .await
29+ .expect("in-memory deployment");
2830 let app = build_router(AppState {
29- db,
31+ db: tenants.control().clone(),
32+ tenants,
3033 files_path: tempfile::tempdir().expect("files dir").keep(),
3134 cookie_secure: false,
3235 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
@@ -59,6 +62,8 @@ async fn spec() -> Value {
5962 fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
6063 vec![
6164 // --- auth / users / notes / messages ---
65+ ("Credentials", "school", "minLength", MIN_SLUG_LEN as i64),
66+ ("Credentials", "school", "maxLength", MAX_SLUG_LEN as i64),
6267 (
6368 "Credentials",
6469 "username",