diff --git a/.env.example b/.env.example index f78d812..d4df4b8 100644 --- a/.env.example +++ b/.env.example @@ -8,9 +8,12 @@ DB_URL=ws://127.0.0.1:8000 DB_USER=root DB_PASS=root DB_NAMESPACE=hezarfen -DB_DATABASE=hezarfen +# The CONTROL database: the school registry and the builder accounts. Each +# school gets a database of its own inside DB_NAMESPACE, named by its slug. +DB_DATABASE=control -# Directory for uploaded note-file blobs (created at startup). +# Directory for uploaded note-file blobs (created at startup). Each school +# writes into a subdirectory of it named by its slug. FILES_PATH=./data/files # Optional log filter. @@ -43,12 +46,14 @@ RUST_LOG=info,hezarfen_backend=debug # trivially bypassed. When off (default), the peer address is used. # TRUST_PROXY=true -# Seed an admin account at startup: if this username doesn't exist yet it is -# created with this password and the `admin` role. Both must be set together. -# If the username exists as a non-admin, nothing is changed (a warning is -# logged) — the seed never promotes or rewrites an existing account. -# ADMIN_USERNAME=admin -# ADMIN_PASSWORD=admin123 +# Seed a BUILDER account at startup: the deployment operator who creates, +# suspends and drops schools. Not a user of any school and holds no role in +# one; its cookie is `builder.` where a school user's is +# `.`. Both must be set together. An existing account with this +# username is left exactly as it is — the seed never rewrites a credential, so +# changing the password here does not re-key a live builder. +# BUILDER_USERNAME=builder +# BUILDER_PASSWORD=builder123 # --- AI bridge (QUIC) ------------------------------------------------------- # The AI features run as separate services that dial IN to this backend over diff --git a/README.md b/README.md index 68bc308..297ef0c 100644 --- a/README.md +++ b/README.md @@ -430,7 +430,7 @@ drift from it**, which is enforced rather than asked for: and fails unless each one is either referenced by `src/web/limits.rs` or listed as a deliberate exclusion *with a reason*. A new constant breaks the suite until someone decides, consciously, whether clients need it. -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 174 published +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 176 published bounds back out of the emitted JSON, and asserts each equals its constant. This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal only** — a `const` there does not compile — so the annotations are @@ -844,10 +844,10 @@ window filtering, before paging; negative values are a `400` naming the field. | 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. | | GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, and a per-course breakdown with attendance rates. | | 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. | -| POST | `/auth/login` | no | Log in with username + password. Sets a `session` cookie on success. | +| POST | `/auth/login` | no | Log in with school + username + password. Sets a `session` cookie (`.`) on success. | | POST | `/auth/logout` | no | Log out: revoke the current session (if any) and clear the cookie. Idempotent — no session required; answers `204` either way. | | GET | `/auth/me` | student | Return the currently authenticated user. | -| 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". | +| 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". | | 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). | | 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. | | 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/ constant.rs validation limits validate.rs field validators (used by every newtype's try_new) error.rs ValidationError + AppError -> HTTP responses - database.rs SurrealDB server connect (ws) + SCHEMAFULL migration + database.rs SurrealDB server connect (ws) + SCHEMAFULL migration; init() + brings up the control database, migrate() a school's + tenant.rs Slug · SchoolStatus · School · Tenants: one database per + school inside one namespace, plus the control database that + registers them (DEMO_SLUG is the in-memory test school) migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR, - MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them + MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them, + and CONTROL_MIGRATION_BATCHES for the control database rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier - state.rs AppState { db, files_path, cookie_secure, rate_limit, + state.rs AppState { db, tenants, files_path, cookie_secure, rate_limit, chatbot_limit, exam_presence, board_hub, db_up, ai } ai/ QUIC bridge to the out-of-process AI services (see "AI bridge (QUIC)"; the HTTP half is web/ai.rs) @@ -4409,6 +4414,8 @@ src/ text_fold.rs case- and diacritic-insensitive folding for search, shared by the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…) session.rs SessionId · SessionToken · Session (7-day expiry) + builder.rs BuilderId · Builder · BuilderSession: the deployment operator + who creates and suspends schools, in the control database timestamp.rs Timestamp (unix-millisecond instant) note.rs NoteId · NoteTitle · NoteContent · Note note_file.rs NoteFileId · FileName · FileContentType · NoteFile (metadata row; @@ -4524,7 +4531,12 @@ src/ row per homework+user — its existence freezes the submission) web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers + auth extractors + tenant_state.rs State: the shadow of axum's State that resolves the + caller's school from the `.` cookie, so every + handler that imports it is school-scoped by construction + (TenantExt · SchoolSlug · split_cookie) extractor.rs CurrentUser · RequireTeacher · RequireManager · RequireAdmin + · RequireBuilder (the control-database principal) dto.rs shared UserResponse · CourseResponse · ExamResponse · SessionResponse schemas exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish) board_ws.rs the collaborative board room WebSocket (join replay, strokes diff --git a/src/ai/server.rs b/src/ai/server.rs index 9c06230..46562eb 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -29,9 +29,11 @@ use crate::domain::course_note::CourseNote; use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; use crate::domain::user::{User, UserId}; use crate::state::DbHealth; +use crate::tenant::{Slug, Tenants}; use crate::web::blob_path; use crate::web::courses::can_view_course; use crate::web::extractor::AiPrincipal; +use crate::web::tenant_state::{TenantExt, school_files_path}; /// What the bridge needs to come up. #[derive(Clone, Debug)] @@ -48,17 +50,43 @@ pub struct BridgeConfig { } /// What an api read needs to be answered: the router to dispatch into, the -/// database the acting principal is loaded from, and the liveness flag that +/// school the acting principal is loaded from, and the liveness flag that /// stands in for the HTTP db guard this path bypasses. struct ApiHandle { router: axum::Router, - db: Database, + tenants: Tenants, + /// The one school this bridge serves. + /// + /// corner-cut: `hab/1` frames carry no school, so the reverse api-read path + /// is pinned to [`crate::tenant::DEMO_SLUG`] — a deployment whose schools + /// are named anything else answers `unavailable` to every service read. + /// The upgrade is `hab/2`: put the school on `Hello`/`ApiRequest` and + /// resolve it per request. Nothing else about the bridge is single-school — + /// the outbound chatbot dispatch never touches a database. + slug: Slug, db_up: DbHealth, - /// Where course-note blobs live, for the byte stream — the same directory - /// `GET /course-notes/{id}/files/{file_id}` serves from. + /// Where uploaded blobs live — the deployment root; the school's own + /// directory is [`school_files_path`] of it. files_path: std::path::PathBuf, } +impl ApiHandle { + /// The school database this bridge reads, or the refusal a service gets. + async fn db(&self) -> Result { + self.tenants.get(&self.slug).await.map_err(|err| { + ( + "unavailable", + format!("the `{}` school is not reachable: {err}", self.slug), + ) + }) + } + + /// That school's blob directory. + fn files_dir(&self) -> std::path::PathBuf { + school_files_path(&self.files_path, &self.slug) + } +} + struct Inner { registry: AiRegistry, /// Armed once per process by [`crate::build_router`] (see @@ -240,7 +268,7 @@ impl AiBridge { pub(crate) fn arm_api( &self, router: axum::Router, - db: Database, + tenants: Tenants, db_up: DbHealth, files_path: std::path::PathBuf, ) { @@ -249,7 +277,8 @@ impl AiBridge { .api .set(ApiHandle { router, - db, + tenants, + slug: Slug::try_new(crate::tenant::DEMO_SLUG).expect("the demo slug is a slug"), db_up, files_path, }) @@ -468,6 +497,7 @@ async fn open_blob( "the database socket is down — retry".to_string(), )); } + let db = api.db().await?; let user = principal(api, request.on_behalf_of.as_deref()).await?; let missing = || { @@ -477,19 +507,19 @@ async fn open_blob( ) }; let unavailable = |e: crate::error::AppError| ("unavailable", e.to_string()); - let file = CourseNoteFile::read(&CourseNoteFileId::from_key(&request.file), &api.db) + let file = CourseNoteFile::read(&CourseNoteFileId::from_key(&request.file), &db) .await .map_err(unavailable)? .ok_or_else(missing)?; - let note = CourseNote::read(file.get_course_note(), &api.db) + let note = CourseNote::read(file.get_course_note(), &db) .await .map_err(unavailable)? .ok_or_else(missing)?; - let course = Course::read(note.get_course(), &api.db) + let course = Course::read(note.get_course(), &db) .await .map_err(unavailable)? .ok_or_else(missing)?; - if !can_view_course(&course, &user, &api.db) + if !can_view_course(&course, &user, &db) .await .map_err(unavailable)? { @@ -504,7 +534,7 @@ async fn open_blob( // The row exists but its blob does not: server-side damage (a lost volume // path), exactly as `download_file` reads it — not the service's `404`. - let path = blob_path(&api.files_path, file.get_id().key()); + let path = blob_path(&api.files_dir(), file.get_id().key()); let handle = tokio::fs::File::open(&path).await.map_err(|e| { ( "unavailable", @@ -548,7 +578,7 @@ async fn principal( // Both the bare key (`abc`, as a REST path spells it) and the record form // (`user:abc`) are accepted. let key = who.strip_prefix("user:").unwrap_or(who); - User::read(&UserId::from_key(key), &api.db) + User::read(&UserId::from_key(key), &api.db().await?) .await .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))? .ok_or_else(|| ("unknown_user", format!("no user `{who}`"))) @@ -627,6 +657,7 @@ async fn dispatch_api( // The role itself is re-read again by the extractor on the dispatched // request; see [`principal`] for why it is never taken from the frame. + let db = api.db().await?; let user = principal(api, on_behalf_of.as_deref()).await?; let target = match query.as_deref() { @@ -646,6 +677,12 @@ async fn dispatch_api( // An extension cannot be set from outside the process, which is what makes // this principal unforgeable over HTTP (see [`AiPrincipal`]). dispatched.extensions_mut().insert(AiPrincipal(user)); + // The dispatched request carries no cookie, so the school is handed over + // in the extension the shadow `State` reads first. + dispatched.extensions_mut().insert(TenantExt { + slug: api.slug.clone(), + db, + }); let response = tokio::time::timeout( Duration::from_secs(REQUEST_TIMEOUT_SECS), @@ -859,6 +896,7 @@ mod tests { refuse_before_dispatch, }; use crate::ai::protocol::read_frame; + use crate::tenant::Slug; /// An armed handle serving `router`. The database is never touched by these /// reads (nobody is named, so the principal is synthetic), but the handle @@ -866,7 +904,10 @@ mod tests { async fn armed(router: axum::Router) -> ApiHandle { ApiHandle { router, - db: crate::database::init_mem().await.expect("in-memory db"), + tenants: crate::database::init_mem_tenants() + .await + .expect("in-memory deployment"), + slug: Slug::try_new(crate::tenant::DEMO_SLUG).unwrap(), db_up: Default::default(), files_path: std::env::temp_dir(), } diff --git a/src/config.rs b/src/config.rs index e0266a2..e168f53 100644 --- a/src/config.rs +++ b/src/config.rs @@ -17,6 +17,9 @@ pub struct Config { pub db_user: String, pub db_pass: String, pub db_ns: String, + /// The **control** database inside `db_ns` (`DB_DATABASE`): the school + /// registry and the builder accounts. Every school gets a database of its + /// own, named by its slug. pub db_name: String, /// Directory for uploaded note-file blobs (`FILES_PATH`). pub files_path: String, @@ -31,11 +34,13 @@ pub struct Config { /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is /// keyed by user and is enforced inside the handler. pub chatbot_per_minute: u32, - /// Startup admin seed (`ADMIN_USERNAME` + `ADMIN_PASSWORD`). When both are - /// set, an admin account with these credentials is created at boot if the - /// username doesn't exist yet. Blank values count as unset. - pub admin_username: Option, - pub admin_password: Option, + /// Startup builder seed (`BUILDER_USERNAME` + `BUILDER_PASSWORD`). When + /// both are set, a builder account with these credentials is created in the + /// control database at boot if the username doesn't exist yet. Blank values + /// count as unset. A builder manages schools; it is not a user of any of + /// them. + pub builder_username: Option, + pub builder_password: Option, /// AI bridge listen address (`AI_QUIC_ADDR`, e.g. `0.0.0.0:8090`). Unset /// leaves the bridge off entirely: the API runs exactly as before and any /// AI-backed feature reports that no service is connected. @@ -62,7 +67,7 @@ impl Config { db_user: env::var("DB_USER").unwrap_or_else(|_| "root".into()), db_pass: env::var("DB_PASS").unwrap_or_else(|_| "root".into()), db_ns: env::var("DB_NAMESPACE").unwrap_or_else(|_| "hezarfen".into()), - db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "hezarfen".into()), + db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "control".into()), files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()), cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()), rate_limit: RateLimitConfig { @@ -80,8 +85,8 @@ impl Config { env::var("RATE_LIMIT_CHATBOT_PER_MINUTE").ok(), DEFAULT_CHATBOT_RATE_LIMIT, ), - admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()), - admin_password: parse_optional(env::var("ADMIN_PASSWORD").ok()), + builder_username: parse_optional(env::var("BUILDER_USERNAME").ok()), + builder_password: parse_optional(env::var("BUILDER_PASSWORD").ok()), ai_quic_addr: parse_optional(env::var("AI_QUIC_ADDR").ok()), ai_shared_token: parse_optional(env::var("AI_SHARED_TOKEN").ok()), ai_tls_cert: parse_optional(env::var("AI_TLS_CERT").ok()), diff --git a/src/constant.rs b/src/constant.rs index 22769b1..bcb8081 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -5,6 +5,12 @@ use crate::domain::message::Folder; use crate::domain::preferences::{Language, Theme}; use crate::domain::role::Role; +/// A school slug's length bounds — the name in front of the dot in the session +/// cookie, which is also the school's database name and its blob directory +/// (see [`crate::tenant::Slug`]). +pub const MIN_SLUG_LEN: usize = 2; +pub const MAX_SLUG_LEN: usize = 32; + pub const MIN_USERNAME_LEN: usize = 3; pub const MAX_USERNAME_LEN: usize = 32; diff --git a/src/database.rs b/src/database.rs index 3671dd3..3c3d71d 100644 --- a/src/database.rs +++ b/src/database.rs @@ -6,10 +6,12 @@ use surrealdb::opt::auth::Root; use crate::config::Config; use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; +use crate::domain::builder::Builder; use crate::domain::timestamp::Timestamp; -use crate::domain::user::{Password, User, Username}; +use crate::domain::user::{Password, Username}; use crate::error::AppError; -use crate::migration_sql::{BACKFILL, MIGRATION_BATCHES}; +use crate::migration_sql::{BACKFILL, CONTROL_MIGRATION_BATCHES, MIGRATION_BATCHES}; +use crate::tenant::Tenants; /// The shared database handle. /// @@ -27,14 +29,14 @@ use crate::migration_sql::{BACKFILL, MIGRATION_BATCHES}; /// Cloning the `Arc` shares the single session established at boot instead. pub type Database = std::sync::Arc>; -/// Connect to the SurrealDB server, sign in as root, apply the schema and seed -/// the admin. One process, one database, stop-the-world deploys — so all of it -/// runs unconditionally on every boot. -pub async fn init(cfg: &Config) -> Result { +/// Connect to the **control** database, sign in as root, apply the control +/// schema and seed the builder account. School databases are brought up +/// separately, one per school, by [`crate::tenant::Tenants`]. +pub async fn init(cfg: &Config) -> Result { // Validated before the connection, not after: half a credential pair is a // deployment mistake, and reporting it only after a successful dial buries // it under an outage that isn't one. - let admin = admin_credentials(cfg)?; + let builder = builder_credentials(cfg)?; let db = connect_with_retry(cfg).await; db.signin(Root { username: cfg.db_user.clone(), @@ -45,27 +47,28 @@ pub async fn init(cfg: &Config) -> Result { .use_db(cfg.db_name.clone()) .await?; let db = std::sync::Arc::new(db); - migrate(&db).await?; - if let Some((username, password)) = admin { - User::ensure_admin(username, password, &db).await?; + migrate_control(&db).await?; + if let Some((username, password)) = builder { + Builder::ensure(username, password, &db).await?; } - Ok(db) + Ok(Tenants::new_remote(db, cfg)) } -/// The `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap pair, if configured. +/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured. /// Both-or-neither: half a pair aborts startup rather than silently running -/// without the seed. -fn admin_credentials(cfg: &Config) -> Result, AppError> { - match (&cfg.admin_username, &cfg.admin_password) { +/// without the seed — and without a builder, a fresh deployment has nobody who +/// can create the first school. +fn builder_credentials(cfg: &Config) -> Result, AppError> { + match (&cfg.builder_username, &cfg.builder_password) { (Some(username), Some(password)) => Ok(Some(( Username::try_new(username) - .map_err(|err| AppError::Internal(format!("invalid ADMIN_USERNAME: {err}")))?, + .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?, Password::try_new(password) - .map_err(|err| AppError::Internal(format!("invalid ADMIN_PASSWORD: {err}")))?, + .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?, ))), (None, None) => Ok(None), _ => Err(AppError::Internal( - "ADMIN_USERNAME and ADMIN_PASSWORD must be set together".into(), + "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(), )), } } @@ -254,7 +257,9 @@ async fn connect_with_retry(cfg: &Config) -> Surreal { } } -/// A fresh in-memory database with the schema applied. For tests. +/// A fresh in-memory **school** database with the school schema applied. For +/// the unit tests whose subject is one school's own rows; a test that needs the +/// whole app (control database included) wants [`init_mem_tenants`]. pub async fn init_mem() -> Result { let db = surrealdb::engine::any::connect("memory").await?; db.use_ns("hezarfen").use_db("hezarfen").await?; @@ -262,6 +267,16 @@ pub async fn init_mem() -> Result { Ok(std::sync::Arc::new(db)) } +/// A fresh in-memory deployment: an empty control database plus one school, +/// [`crate::tenant::DEMO_SLUG`]. The bootstrap every router-level test uses. +pub async fn init_mem_tenants() -> Result { + let tenants = Tenants::new_mem().await?; + let demo = crate::tenant::Slug::try_new(crate::tenant::DEMO_SLUG) + .map_err(|err| AppError::Internal(format!("the demo slug is a slug: {err}")))?; + tenants.create(&demo, "Demo School").await?; + Ok(tenants) +} + /// A handle on a **real** SurrealDB server, in a scratch namespace of its own /// that is dropped and re-made on every call. For the tests whose subject is /// the store's own conflict detection, which [`init_mem`]'s embedded engine @@ -326,6 +341,16 @@ pub async fn migrate(db: &Surreal) -> Result<(), AppError> { Ok(()) } +/// Apply the **control** schema (schools, builders, the shared rate-limit +/// window). Idempotent, like [`migrate`], and takes no bound parameters — +/// nothing in the control batch is data-driven. +pub async fn migrate_control(db: &Surreal) -> Result<(), AppError> { + for sql in CONTROL_MIGRATION_BATCHES { + db.query(sql).await?.check()?; + } + Ok(()) +} + /// Parameters the batches are executed with. Bound, not baked into the SQL /// string: a `const` cannot be interpolated into another `const`, and a /// hand-copied 300000 would drift silently. The one-time blocks' fingerprints diff --git a/src/domain/builder.rs b/src/domain/builder.rs new file mode 100644 index 0000000..9cfb66a --- /dev/null +++ b/src/domain/builder.rs @@ -0,0 +1,253 @@ +//! The deployment operator's account, in the control database. +//! +//! A builder creates, suspends and drops schools; it is **not** a user of any +//! school and holds no role there. The two principals are kept apart by +//! construction: a builder row lives in a different database and its cookie +//! carries a different prefix (`builder.` against `.`), so +//! neither extractor can be fed the other's cookie. +//! +//! The credential newtypes are [`crate::domain::user`]'s — same rules, same +//! argon2 discipline, deliberately not a second copy that could drift. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::SESSION_DURATION_DAYS; +use crate::database::Database; +use crate::domain::session::SessionToken; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::{Password, PasswordHash, Username}; +use crate::error::AppError; + +pub const BUILDER_TABLE: &str = "builder"; +pub const BUILDER_SESSION_TABLE: &str = "builder_session"; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct BuilderId(RecordId); + +impl BuilderId { + pub fn generate() -> Self { + Self(RecordId::new(BUILDER_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(BUILDER_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct Builder { + id: BuilderId, + username: Username, + password_hash: PasswordHash, +} + +impl Builder { + pub fn get_id(&self) -> &BuilderId { + &self.id + } + + pub fn get_username(&self) -> &Username { + &self.username + } + + pub fn get_password_hash(&self) -> &PasswordHash { + &self.password_hash + } + + pub async fn find_by_username( + username: &str, + control: &Database, + ) -> Result, AppError> { + let mut result = control + .query("SELECT * FROM builder WHERE username = $u LIMIT 1") + .bind(("u", username.trim().to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + pub async fn read(id: &BuilderId, control: &Database) -> Result, AppError> { + Ok(control.select(id.record()).await?) + } + + /// Idempotent startup seed. An existing row is left exactly as it is — the + /// seed never rewrites a credential, so rotating `BUILDER_PASSWORD` in the + /// environment does not silently re-key a live account (delete the row to + /// re-seed). There is no role to promote here, so this cannot have + /// `ensure_admin`'s create-then-promote hole. + pub async fn ensure( + username: Username, + password: Password, + control: &Database, + ) -> Result<(), AppError> { + if Self::find_by_username(username.as_str(), control) + .await? + .is_some() + { + return Ok(()); + } + let builder = Builder { + id: BuilderId::generate(), + password_hash: password.hash_async().await?, + username, + }; + let created: Option = control + .create(builder.id.record()) + .content(builder.clone()) + .await?; + created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?; + tracing::info!( + username = builder.username.as_str(), + "seeded builder account" + ); + Ok(()) + } +} + +/// A builder's login session. [`crate::domain::session::Session`]'s shape +/// against the control database, with the token type shared so both cookies +/// are the same 64 hex chars. +#[derive(Debug, Clone, SurrealValue)] +pub struct BuilderSession { + id: RecordId, + builder: BuilderId, + token: SessionToken, + created_at: Timestamp, + expires_at: Timestamp, +} + +impl BuilderSession { + pub async fn create( + builder: &BuilderId, + control: &Database, + ) -> Result { + let session = BuilderSession { + id: RecordId::new(BUILDER_SESSION_TABLE, Ulid::new().to_string()), + builder: builder.clone(), + token: SessionToken::generate()?, + created_at: Timestamp::now(), + expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), + }; + let created: Option = + control.create(session.id.clone()).content(session).await?; + created.ok_or_else(|| AppError::Internal("failed to create the builder session".into())) + } + + pub fn token(&self) -> &SessionToken { + &self.token + } + + pub fn builder(&self) -> &BuilderId { + &self.builder + } + + pub fn is_expired(&self) -> bool { + self.expires_at.is_past() + } + + pub async fn find_by_token( + token: &str, + control: &Database, + ) -> Result, AppError> { + let mut result = control + .query("SELECT * FROM builder_session WHERE token = $tok LIMIT 1") + .bind(("tok", token.to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + pub async fn delete_by_token(token: &str, control: &Database) -> Result<(), AppError> { + control + .query("DELETE builder_session WHERE token = $tok") + .bind(("tok", token.to_string())) + .await? + .check()?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tenant::Tenants; + + #[tokio::test] + async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { + let tenants = Tenants::new_mem().await.unwrap(); + let control = tenants.control(); + let name = Username::try_new("builder1").unwrap(); + Builder::ensure(name.clone(), Password::try_new("secret1").unwrap(), control) + .await + .unwrap(); + let first = Builder::find_by_username("builder1", control) + .await + .unwrap() + .expect("seeded"); + + // A second boot with a *different* password must leave the row alone: + // an environment edit is not a password reset. + Builder::ensure(name, Password::try_new("secret2").unwrap(), control) + .await + .unwrap(); + let again = Builder::find_by_username("builder1", control) + .await + .unwrap() + .expect("still there"); + assert_eq!(again.get_id(), first.get_id()); + assert_eq!( + again.get_password_hash().as_str(), + first.get_password_hash().as_str() + ); + } + + #[tokio::test] + async fn a_builder_session_round_trips_and_deletes() { + let tenants = Tenants::new_mem().await.unwrap(); + let control = tenants.control(); + Builder::ensure( + Username::try_new("builder1").unwrap(), + Password::try_new("secret1").unwrap(), + control, + ) + .await + .unwrap(); + let builder = Builder::find_by_username("builder1", control) + .await + .unwrap() + .unwrap(); + + let session = BuilderSession::create(builder.get_id(), control) + .await + .unwrap(); + let token = session.token().as_str().to_string(); + let found = BuilderSession::find_by_token(&token, control) + .await + .unwrap() + .expect("found by token"); + assert_eq!(found.builder(), builder.get_id()); + assert!(!found.is_expired()); + + BuilderSession::delete_by_token(&token, control) + .await + .unwrap(); + assert!( + BuilderSession::find_by_token(&token, control) + .await + .unwrap() + .is_none() + ); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index cdf0ca6..3b11edb 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -11,6 +11,7 @@ pub mod bank_question; pub mod bank_question_image; pub mod board; pub mod board_stroke; +pub mod builder; pub mod cap; pub mod chatbot_message; pub mod chatbot_thread; diff --git a/src/lib.rs b/src/lib.rs index f8ab659..cb756f9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,6 +7,7 @@ pub mod error; pub mod migration_sql; pub mod rate_limit; pub mod state; +pub mod tenant; pub mod validate; pub mod web; @@ -161,7 +162,7 @@ pub fn build_router(state: AppState) -> Router { if let Some(ai) = &state.ai { ai.arm_api( service.clone(), - state.db.clone(), + state.tenants.clone(), state.db_up.clone(), state.files_path.clone(), ); diff --git a/src/main.rs b/src/main.rs index dd9dd19..72fd3eb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,17 +19,21 @@ async fn main() -> anyhow::Result<()> { // Hash the login decoy now, so the first unknown-username login is not the // one request that pays for it (see `PasswordHash::prewarm_decoy`). hezarfen_backend::domain::user::PasswordHash::prewarm_decoy(); - // Connects, migrates the schema and seeds the admin — all of it idempotent - // and unconditional on every boot. - let db = database::init(&cfg).await?; + // Connects to the control database, migrates it and seeds the builder — + // all of it idempotent and unconditional on every boot. School databases + // come up lazily, one connection each, on first use. + let tenants = database::init(&cfg).await?; let db_up = DbHealth::default(); - keepalive(db.clone(), db_up.clone()); + // The control connection is the one every request touches (the school + // lookup rides it), so it is the socket worth watching. + keepalive(tenants.control().clone(), db_up.clone()); tokio::fs::create_dir_all(&cfg.files_path) .await .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?; let ai = hezarfen_backend::ai::start_bridge(&cfg).await?; let app = build_router(AppState { - db, + db: tenants.control().clone(), + tenants, files_path: cfg.files_path.clone().into(), cookie_secure: cfg.cookie_secure, rate_limit: cfg.rate_limit.clone(), diff --git a/src/migration_sql.rs b/src/migration_sql.rs index 7b3abf4..c347772 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -1461,6 +1461,48 @@ pub const BACKFILL: &str = " }; "; +/// The **control** database's schema — the one database per deployment that +/// knows which schools exist and who may create them. Everything else lives in +/// a school database, whose schema is [`MIGRATION_BATCHES`] and is applied +/// per school by [`crate::tenant::Tenants::create`]. +/// +/// The `rate_limit` copy is deliberate: the shared per-IP window +/// (`crate::rate_limit::RateLimiter::share`) is billed against the control +/// handle, because the limiter runs in front of the router — before any cookie +/// has named a school. One budget per deployment is also the honest one for an +/// unauthenticated brute-forcer, who has not picked a school yet either. +pub const CONTROL_MIGRATION: &str = " + DEFINE TABLE IF NOT EXISTS school SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS slug ON school TYPE string; + DEFINE FIELD IF NOT EXISTS name ON school TYPE string; + DEFINE FIELD IF NOT EXISTS status ON school TYPE string; + DEFINE FIELD IF NOT EXISTS created_at ON school TYPE int; + -- Redundant with the `school:` id, and kept anyway: the id is the + -- fast path, the index is what makes a second row on the same slug + -- impossible if a future write ever mints an id some other way. + DEFINE INDEX IF NOT EXISTS school_slug ON school FIELDS slug UNIQUE; + + DEFINE TABLE IF NOT EXISTS builder SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS username ON builder TYPE string; + DEFINE FIELD IF NOT EXISTS password_hash ON builder TYPE string; + DEFINE INDEX IF NOT EXISTS builder_username ON builder FIELDS username UNIQUE; + + DEFINE TABLE IF NOT EXISTS builder_session SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS builder ON builder_session TYPE record; + DEFINE FIELD IF NOT EXISTS token ON builder_session TYPE string; + DEFINE FIELD IF NOT EXISTS created_at ON builder_session TYPE int; + DEFINE FIELD IF NOT EXISTS expires_at ON builder_session TYPE int; + DEFINE INDEX IF NOT EXISTS builder_session_token ON builder_session FIELDS token UNIQUE; + DEFINE INDEX IF NOT EXISTS builder_session_expires ON builder_session FIELDS expires_at; + + -- Verbatim from `MIGRATION`; see the note above this constant. + DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0; + DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int; +"; + +pub const CONTROL_MIGRATION_BATCHES: [&str; 1] = [CONTROL_MIGRATION]; + /// The migration batches, in the order a boot applies them — and the *only* /// list of them. [`crate::database::migrate`] runs exactly these. They stay /// three separate queries: statements in one batch see the schema as it stood diff --git a/src/state.rs b/src/state.rs index d23611e..74e1c2a 100644 --- a/src/state.rs +++ b/src/state.rs @@ -8,11 +8,19 @@ use tokio::sync::broadcast; use crate::ai::AiBridge; use crate::database::Database; use crate::rate_limit::{RateLimitConfig, UserRateLimiter}; +use crate::tenant::Tenants; /// Shared application state handed to every handler. #[derive(Clone)] pub struct AppState { + /// The database this request works in. At the router's root this is the + /// **control** database; `crate::web::tenant_state::State` swaps in the + /// caller's school before any handler that shadows `State` sees it. pub db: Database, + /// The school registry and its connections. Always the deployment-wide + /// one — it is never narrowed per request, so a handler can still reach + /// another school's handle deliberately. + pub tenants: Tenants, /// Directory holding uploaded note-file blobs, one file per /// `note_file` row, named by the row's key /// (from [`crate::config::Config::files_path`]). diff --git a/src/tenant.rs b/src/tenant.rs new file mode 100644 index 0000000..3b4b0a5 --- /dev/null +++ b/src/tenant.rs @@ -0,0 +1,652 @@ +//! Multi-school tenancy: one SurrealDB **database** per school inside one +//! namespace, plus a **control** database holding the school registry, the +//! builder accounts that manage it, and the deployment-wide rate-limit window. +//! +//! Isolation is the store's, not ours. A school database sees only its own +//! rows, so no handler needs a `WHERE school = …` it could forget: the school +//! is chosen once, at the edge (`crate::web::tenant_state::State`), and every +//! query underneath runs against that handle. +//! +//! # One connection per school, never a clone +//! +//! [`crate::database::Database`] is `Arc>` for the reason spelled +//! out there — `Surreal::clone()` mints a racing server-side session — and the +//! same reasoning forbids the obvious shortcut here: switching `use_db` on the +//! control handle would repoint *every* in-flight query on it. So a cache miss +//! dials a **new** connection, signs it in, and pins it to the school's +//! database for its lifetime. +//! +//! In-memory mode (tests) has no server to define databases on: each +//! `connect("memory")` is an independent datastore, so a school *is* its own +//! store and the cache is the only thing that finds it again. + +use std::collections::HashMap; +use std::sync::{Arc, RwLock}; + +use serde::Serialize; +use surrealdb::opt::auth::Root; +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::config::Config; +use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; +use crate::database::{Database, lost_the_race, migrate, migrate_control}; +use crate::domain::page::PagedList; +use crate::domain::timestamp::Timestamp; +use crate::error::{AppError, ValidationError}; + +pub(crate) const SCHOOL_TABLE: &str = "school"; + +/// The school every in-memory test bootstrap gets. Not special to the code — +/// just the one name the test harness and the suites agree on. +pub const DEMO_SLUG: &str = "demo"; + +/// Slugs that name something other than a school: the builder cookie prefix and +/// the control database itself. Refused at construction, so neither a login nor +/// a `DEFINE DATABASE` can ever be aimed at them. +pub const RESERVED_SLUGS: [&str; 2] = ["builder", "control"]; + +/// A school's identity everywhere it is named: the cookie prefix, the database +/// name, and the files subdirectory. The character set is deliberately the +/// intersection of what all three accept — lowercase alphanumerics and `-`, +/// starting with an alphanumeric — which is also what makes it safe to +/// interpolate into `DEFINE DATABASE` / `REMOVE DATABASE`, the two statements +/// SurrealQL gives no way to bind a name into. +#[derive(Debug, Clone, PartialEq, Eq, Hash, SurrealValue, Serialize)] +#[serde(transparent)] +pub struct Slug(String); + +/// `^[a-z0-9][a-z0-9-]{1,31}$`, spelled out. `regex` is a dev-dependency here +/// and this is five lines of `char` predicates — a runtime dependency would +/// cost more than it saves. +fn is_slug(value: &str) -> bool { + let ok_len = (MIN_SLUG_LEN..=MAX_SLUG_LEN).contains(&value.len()); + let ok_first = value + .chars() + .next() + .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()); + let ok_rest = value + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); + ok_len && ok_first && ok_rest +} + +impl Slug { + pub fn try_new(value: &str) -> Result { + if !is_slug(value) { + return Err(ValidationError::Invalid { + field: "school", + reason: "must be 2-32 characters of a-z, 0-9 and -, starting with a letter or digit", + }); + } + if RESERVED_SLUGS.contains(&value) { + return Err(ValidationError::Invalid { + field: "school", + reason: "this name is reserved", + }); + } + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for Slug { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +/// Whether a school may be reached at all. Suspension is immediate and total: +/// [`Tenants::get`] refuses before any handler runs, and login is no exception. +/// +/// Stored as a bare lowercase string, like [`crate::domain::role::Role`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue, Serialize)] +#[surreal(untagged, rename_all = "lowercase")] +#[serde(rename_all = "lowercase")] +pub enum SchoolStatus { + Active, + Suspended, +} + +impl SchoolStatus { + pub fn as_str(self) -> &'static str { + match self { + SchoolStatus::Active => "active", + SchoolStatus::Suspended => "suspended", + } + } + + pub fn try_from_str(value: &str) -> Result { + match value { + "active" => Ok(SchoolStatus::Active), + "suspended" => Ok(SchoolStatus::Suspended), + _ => Err(ValidationError::Invalid { + field: "status", + reason: "must be one of: active, suspended", + }), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SchoolId(RecordId); + +impl SchoolId { + /// The id **is** the slug, so the registry can never hold two rows for one + /// school even if the unique index were dropped. + pub fn from_slug(slug: &Slug) -> Self { + Self(RecordId::new(SCHOOL_TABLE, slug.as_str())) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A row in the control database's school registry. +#[derive(Debug, Clone, SurrealValue)] +pub struct School { + id: SchoolId, + slug: Slug, + name: String, + status: SchoolStatus, + created_at: Timestamp, +} + +impl School { + pub fn get_id(&self) -> &SchoolId { + &self.id + } + + pub fn slug(&self) -> &Slug { + &self.slug + } + + pub fn name(&self) -> &str { + &self.name + } + + pub fn status(&self) -> SchoolStatus { + self.status + } + + pub fn created_at(&self) -> Timestamp { + self.created_at + } + + pub async fn read(slug: &Slug, control: &Database) -> Result, AppError> { + Ok(control.select(SchoolId::from_slug(slug).record()).await?) + } + + /// One page of the registry, newest first. Same `(rows, total)` shape every + /// other list domain returns, so the builder API can wrap it in the usual + /// [`crate::web::Page`] envelope. + pub async fn list( + limit: Option, + offset: i64, + control: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new(SCHOOL_TABLE, "ORDER BY created_at DESC, id DESC") + .run::(limit, offset, control) + .await + } + + /// Rename a school. The slug is immutable — it names a database and a + /// directory, so it is the one field a rename must not touch. + pub async fn update_name( + slug: &Slug, + name: &str, + control: &Database, + ) -> Result { + let updated: Option = control + .query("UPDATE $id SET name = $name RETURN AFTER") + .bind(("id", SchoolId::from_slug(slug).record())) + .bind(("name", name.to_string())) + .await? + .check()? + .take::>(0)? + .into_iter() + .next(); + updated.ok_or(AppError::NotFound) + } +} + +/// How a school handle is minted. Remote dials the server the control handle +/// came from; `Mem` mints an independent embedded datastore per school. +#[derive(Debug)] +enum Mode { + Remote { + url: String, + user: String, + pass: String, + ns: String, + }, + Mem, +} + +/// The school registry plus its live connections. +#[derive(Clone)] +pub struct Tenants { + control: Database, + cache: Arc>>, + mode: Arc, +} + +impl Tenants { + /// Wrap an already-connected, already-migrated control handle. + pub fn new_remote(control: Database, cfg: &Config) -> Tenants { + Tenants { + control, + cache: Arc::new(RwLock::new(HashMap::new())), + mode: Arc::new(Mode::Remote { + url: cfg.db_url.clone(), + user: cfg.db_user.clone(), + pass: cfg.db_pass.clone(), + ns: cfg.db_ns.clone(), + }), + } + } + + /// A fresh in-memory control database with the control schema applied, and + /// no schools. For tests. + pub async fn new_mem() -> Result { + let control = surrealdb::engine::any::connect("memory").await?; + control.use_ns("hezarfen").use_db("control").await?; + migrate_control(&control).await?; + Ok(Tenants { + control: Arc::new(control), + cache: Arc::new(RwLock::new(HashMap::new())), + mode: Arc::new(Mode::Mem), + }) + } + + /// A fresh in-memory registry that already knows `slug`, backed by a handle + /// that already exists rather than a new store. + /// + /// This is how a suite simulates a reboot: the process (and so the registry, + /// the connection cache and the control database) is new, while the school's + /// data is the very data the previous process wrote. + pub async fn new_mem_adopting( + slug: &Slug, + name: &str, + db: Database, + ) -> Result { + let tenants = Tenants::new_mem().await?; + let school = School { + id: SchoolId::from_slug(slug), + slug: slug.clone(), + name: name.to_string(), + status: SchoolStatus::Active, + created_at: Timestamp::now(), + }; + let _: Option = tenants + .control + .create(school.id.record()) + .content(school) + .await?; + tenants + .cache + .write() + .expect("tenant cache lock") + .insert(slug.as_str().to_string(), db); + Ok(tenants) + } + + /// The control database: schools, builders, the shared rate-limit window. + /// Never `use_db`-switched — see this module's header. + pub fn control(&self) -> &Database { + &self.control + } + + /// The handle for a school a request may use, or the refusal a request + /// gets: unknown → `401` (a wrong school is a wrong credential, and a `404` + /// would enumerate the customer list), suspended → `403`. + /// + /// corner-cut: the registry row is read on every request, so a suspension + /// takes effect on the next call with no invalidation protocol. That is one + /// extra control-db round trip per request; cache the row with a short TTL + /// if it ever shows up in a profile — the eviction in [`Tenants::set_status`] + /// is already there to make a cached decision safe. + pub async fn get(&self, slug: &Slug) -> Result { + match School::read(slug, &self.control).await? { + None => Err(AppError::Unauthorized), + Some(school) if school.status == SchoolStatus::Suspended => { + self.evict(slug); + Err(AppError::Forbidden("school is suspended")) + } + Some(_) => self.handle(slug).await, + } + } + + /// [`Tenants::get`] for builder tooling, which must still reach a suspended + /// school to un-suspend or inspect it. Unknown → `404`, because a builder is + /// authenticated and there is nothing to hide from them. + pub async fn get_any_status(&self, slug: &Slug) -> Result<(Database, SchoolStatus), AppError> { + let school = School::read(slug, &self.control) + .await? + .ok_or(AppError::NotFound)?; + Ok((self.handle(slug).await?, school.status)) + } + + /// Register a school and bring its database into being: registry row first + /// (so a lost race is a `409` and not a half-made database), then + /// `DEFINE DATABASE`, then the school schema. + pub async fn create(&self, slug: &Slug, name: &str) -> Result { + let school = School { + id: SchoolId::from_slug(slug), + slug: slug.clone(), + name: name.to_string(), + status: SchoolStatus::Active, + created_at: Timestamp::now(), + }; + let created: Result, surrealdb::Error> = self + .control + .create(school.id.record()) + .content(school.clone()) + .await; + match created { + Ok(Some(_)) => {} + Ok(None) => return Err(AppError::Internal("failed to create the school".into())), + // The id is the slug, so "already exists" is exactly "taken" — and + // a lost transaction race is the same verdict reached differently. + Err(err) if lost_the_race(&err) => { + return Err(AppError::Conflict("school slug already taken")); + } + Err(err) => return Err(err.into()), + } + + let db = match &*self.mode { + Mode::Remote { .. } => { + // `slug` is `Slug`-validated, so this interpolation carries only + // `[a-z0-9-]` — SurrealQL cannot bind a database name. + self.control + .query(format!("DEFINE DATABASE IF NOT EXISTS {slug}")) + .await? + .check()?; + self.connect(slug).await? + } + Mode::Mem => self.connect(slug).await?, + }; + migrate(&db).await?; + self.cache + .write() + .expect("tenant cache lock") + .insert(slug.as_str().to_string(), db.clone()); + Ok(db) + } + + /// Flip a school between active and suspended. Suspending also drops the + /// cached handle, so nothing that already resolved keeps serving. + pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> { + let updated: Vec = self + .control + .query("UPDATE $id SET status = $status RETURN AFTER") + .bind(("id", SchoolId::from_slug(slug).record())) + .bind(("status", status)) + .await? + .check()? + .take(0)?; + if updated.is_empty() { + return Err(AppError::NotFound); + } + if status == SchoolStatus::Suspended { + self.evict(slug); + } + Ok(()) + } + + /// Delete a school outright: its data, then its registry row, then its + /// handle. Irreversible on purpose — there is no soft-delete state, that is + /// what [`SchoolStatus::Suspended`] is for. + pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> { + if let Mode::Remote { .. } = &*self.mode { + // Interpolation, not a bind: see `create`. + self.control + .query(format!("REMOVE DATABASE IF EXISTS {slug}")) + .await? + .check()?; + } + self.control + .query("DELETE $id") + .bind(("id", SchoolId::from_slug(slug).record())) + .await? + .check()?; + self.forget(slug); + Ok(()) + } + + /// Forget a school's connection. The next request dials a fresh one. + /// + /// A no-op in memory mode, where the cached handle *is* the school's + /// datastore and dropping it would delete the school's data rather than its + /// connection. Nothing depends on eviction for correctness — [`Tenants::get`] + /// re-reads the registry row on every request, so a suspension is refused + /// whether or not a handle survived it. [`Tenants::drop`], which does mean to + /// destroy the store, forgets it unconditionally. + pub fn evict(&self, slug: &Slug) { + if matches!(&*self.mode, Mode::Mem) { + return; + } + self.forget(slug); + } + + fn forget(&self, slug: &Slug) { + self.cache + .write() + .expect("tenant cache lock") + .remove(slug.as_str()); + } + + /// The cached handle, or a freshly dialled one. + async fn handle(&self, slug: &Slug) -> Result { + if let Some(db) = self + .cache + .read() + .expect("tenant cache lock") + .get(slug.as_str()) + { + return Ok(db.clone()); + } + let db = self.connect(slug).await?; + // In-memory mode has nowhere for a school's rows to have survived a + // cache miss, so a fresh store needs the schema. Remote already has it. + if matches!(&*self.mode, Mode::Mem) { + migrate(&db).await?; + } + // Losing the race here is harmless — both handles are equivalent — but + // the winner is kept so two requests never diverge onto two sessions. + Ok(self + .cache + .write() + .expect("tenant cache lock") + .entry(slug.as_str().to_string()) + .or_insert(db) + .clone()) + } + + /// One new connection, pinned to `slug`'s database for its lifetime. + async fn connect(&self, slug: &Slug) -> Result { + let db = match &*self.mode { + Mode::Remote { + url, + user, + pass, + ns, + } => { + let db = surrealdb::engine::any::connect(url.clone()).await?; + db.signin(Root { + username: user.clone(), + password: pass.clone(), + }) + .await?; + db.use_ns(ns.clone()).use_db(slug.as_str()).await?; + db + } + Mode::Mem => { + let db = surrealdb::engine::any::connect("memory").await?; + db.use_ns("hezarfen").use_db(slug.as_str()).await?; + db + } + }; + Ok(Arc::new(db)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn slug(value: &str) -> Slug { + Slug::try_new(value).expect(value) + } + + async fn count(db: &Database, table: &str) -> usize { + let mut rows = db + .query(format!("SELECT id FROM {table}")) + .await + .unwrap() + .check() + .unwrap(); + rows.take::>(0) + .unwrap() + .len() + } + + #[tokio::test] + async fn a_slug_names_a_school_and_nothing_reserved() { + for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] { + assert!(Slug::try_new(good).is_ok(), "{good:?} should be a slug"); + } + // Reserved words would collide with the builder cookie prefix and the + // control database itself — the two things a slug must never name. + for bad in [ + "builder", + "control", + "Demo", + "..", + "", + "x", + "-lead", + "has_underscore", + "has.dot", + &"x".repeat(33), + ] { + assert!(Slug::try_new(bad).is_err(), "{bad:?} must not be a slug"); + } + } + + #[tokio::test] + async fn two_schools_do_not_see_each_others_rows() { + let tenants = Tenants::new_mem().await.unwrap(); + let (a, b) = (slug("alpha"), slug("beta")); + let one = tenants.create(&a, "Alpha").await.unwrap(); + let two = tenants.create(&b, "Beta").await.unwrap(); + + one.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") + .await + .unwrap() + .check() + .unwrap(); + assert_eq!(count(&one, "user").await, 1); + assert_eq!( + count(&two, "user").await, + 0, + "a row written in one school must be invisible in the other" + ); + // A second `create` on a taken slug is a conflict, not a second school. + assert!(matches!( + tenants.create(&a, "Alpha again").await, + Err(AppError::Conflict(_)) + )); + } + + #[tokio::test] + async fn suspending_refuses_the_school_and_the_handle_it_already_had() { + let tenants = Tenants::new_mem().await.unwrap(); + let s = slug("alpha"); + tenants.create(&s, "Alpha").await.unwrap(); + // Cached by the first resolve; the suspension must beat the cache. + tenants.get(&s).await.expect("active school resolves"); + + tenants + .set_status(&s, SchoolStatus::Suspended) + .await + .unwrap(); + assert!(matches!( + tenants.get(&s).await, + Err(AppError::Forbidden("school is suspended")) + )); + // Builder tooling still reaches it, which is how it gets un-suspended. + let (_, status) = tenants.get_any_status(&s).await.unwrap(); + assert_eq!(status, SchoolStatus::Suspended); + + tenants.set_status(&s, SchoolStatus::Active).await.unwrap(); + assert!(tenants.get(&s).await.is_ok()); + // An unknown school is a bad credential, never a `404`. + assert!(matches!( + tenants.get(&slug("ghost")).await, + Err(AppError::Unauthorized) + )); + assert!(matches!( + tenants.get_any_status(&slug("ghost")).await, + Err(AppError::NotFound) + )); + } + + #[tokio::test] + async fn dropping_a_school_takes_its_rows_with_it() { + let tenants = Tenants::new_mem().await.unwrap(); + let s = slug("alpha"); + let db = tenants.create(&s, "Alpha").await.unwrap(); + db.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") + .await + .unwrap() + .check() + .unwrap(); + assert_eq!(count(&db, "user").await, 1); + + tenants.drop(&s).await.unwrap(); + assert!(matches!(tenants.get(&s).await, Err(AppError::Unauthorized))); + + let fresh = tenants.create(&s, "Alpha reborn").await.unwrap(); + assert_eq!( + count(&fresh, "user").await, + 0, + "a re-created school must not inherit the dropped one's rows" + ); + } + + #[tokio::test] + async fn the_registry_lists_and_renames() { + let tenants = Tenants::new_mem().await.unwrap(); + tenants.create(&slug("alpha"), "Alpha").await.unwrap(); + tenants.create(&slug("beta"), "Beta").await.unwrap(); + + let (rows, total) = School::list(None, 0, tenants.control()).await.unwrap(); + assert_eq!(total, 2); + assert_eq!(rows.len(), 2); + + let renamed = School::update_name(&slug("alpha"), "Alpha Koleji", tenants.control()) + .await + .unwrap(); + assert_eq!(renamed.name(), "Alpha Koleji"); + assert_eq!( + renamed.slug().as_str(), + "alpha", + "a rename never moves the slug" + ); + assert!(matches!( + School::update_name(&slug("ghost"), "Nope", tenants.control()).await, + Err(AppError::NotFound) + )); + } +} diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 698824f..b6aac2b 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -1,7 +1,8 @@ use std::collections::{HashMap, HashSet}; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; diff --git a/src/web/attendance.rs b/src/web/attendance.rs index c0354b4..9d3f24b 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::Path; use serde::Serialize; use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; diff --git a/src/web/auth.rs b/src/web/auth.rs index e6d8aed..4982d36 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -10,15 +10,18 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; +use crate::domain::builder::BuilderSession; use crate::domain::role::Role as DomainRole; use crate::domain::session::Session; use crate::domain::user::{Password, PasswordHash, User, Username}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::rate_limit::{RateLimitConfig, RateLimiter}; use crate::state::AppState; +use crate::tenant::Slug; use super::dto::Role; -use super::{CurrentUser, UserResponse}; +use super::tenant_state::split_cookie; +use super::{BUILDER_COOKIE_PREFIX, CurrentUser, UserResponse}; pub fn routes(state: &AppState) -> OpenApiRouter { // Strict per-IP limit on the two credential endpoints only — the @@ -44,6 +47,11 @@ pub fn routes(state: &AppState) -> OpenApiRouter { #[derive(Deserialize, ToSchema)] struct Credentials { + /// The school's slug — the name in front of the dot in the session cookie. + /// One backend serves many schools, so a username only identifies an + /// account together with this. + #[schema(example = "demo", min_length = 2, max_length = 32)] + school: String, #[schema(example = "ada", min_length = 3, max_length = 32)] username: String, #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] @@ -63,7 +71,7 @@ struct RegisterResponse { role: Role, } -/// Register a new user account: `{username, password}` in, `{username, role}` +/// 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". /// @@ -83,6 +91,8 @@ struct RegisterResponse { responses( (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), (status = 400, description = "Invalid username or password", body = ErrorResponse), + (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse), + (status = 403, description = "The school is suspended", body = ErrorResponse), (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), @@ -91,6 +101,12 @@ async fn register( State(st): State, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { + // The school first: a registration into a school that does not exist, or + // one that is suspended, must not reach the (expensive) hashing path — and + // an unknown school answers `401` here for the same anti-enumeration reason + // login does, rather than confirming which schools this deployment serves. + let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; + let db = st.tenants.get(&school).await?; let username = Username::try_new(&req.username)?; // Registration-level policy, not a `Username` invariant: these names read // as staff and invite impersonation, but the `ADMIN_USERNAME` bootstrap @@ -115,7 +131,7 @@ async fn register( username: username.as_str().to_string(), role: DomainRole::Student.into(), }; - match User::create(username, password_hash, &st.db).await { + match User::create(username, password_hash, &db).await { Ok(_) => {} // Taken. Log the real reason server-side; the caller gets the same 201 // and the same body, because telling the two apart is the whole thing @@ -128,7 +144,8 @@ async fn register( Ok((StatusCode::CREATED, Json(body))) } -/// Log in with username + password. Sets a `session` cookie on success. +/// Log in with school + username + password. Sets a `session` cookie +/// (`.`) on success. #[utoipa::path( post, path = "/login", @@ -136,7 +153,8 @@ async fn register( request_body = Credentials, responses( (status = 200, description = "Logged in; session cookie set", body = UserResponse), - (status = 401, description = "Bad credentials", body = ErrorResponse), + (status = 401, description = "Bad credentials, or no such school — deliberately indistinguishable", body = ErrorResponse), + (status = 403, description = "The school is suspended", body = ErrorResponse), (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), @@ -146,10 +164,17 @@ async fn login( jar: CookieJar, Json(req): Json, ) -> Result<(CookieJar, Json), AppError> { + // Resolved *before* the argon2 work: a login aimed at a school that does + // not exist is a bad credential (`401`, indistinguishable from a bad + // password — the school list is not public), and a suspended school is + // `403` for every request including this one, so neither should buy an + // attacker a hash. + let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; + let db = st.tenants.get(&school).await?; let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; // Usernames are stored trimmed (see `Username::try_new`); trim the lookup // the same way so a padded login attempt matches the canonical name. - let user = match User::find_by_username(req.username.trim(), &st.db).await? { + let user = match User::find_by_username(req.username.trim(), &db).await? { // Verification is `.await`ed so argon2 runs on the blocking pool instead // of stalling an async worker; that rules out a match guard, which // cannot await. @@ -169,10 +194,12 @@ async fn login( }; // The caller is genuine; opportunistically drop any expired session rows. - let _ = Session::purge_expired(&st.db).await; + let _ = Session::purge_expired(&db).await; - let session = Session::create(user.get_id(), &st.db).await?; - let cookie = Cookie::build(("session", session.token().as_str().to_string())) + let session = Session::create(user.get_id(), &db).await?; + // `.`: the cookie carries the school, so every later request + // finds its database without a second lookup path that could disagree. + let cookie = Cookie::build(("session", format!("{school}.{}", session.token().as_str()))) .path("/") .http_only(true) .secure(st.cookie_secure) @@ -198,8 +225,17 @@ async fn logout( State(st): State, jar: CookieJar, ) -> Result<(CookieJar, StatusCode), AppError> { - if let Some(cookie) = jar.get("session") { - Session::delete_by_token(cookie.value(), &st.db).await?; + // Best-effort: the cookie names its own school, so a logout resolves that + // school and deletes the row there. A cookie naming a school that is gone + // or suspended still clears below — logging out must never fail. + if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { + if prefix == BUILDER_COOKIE_PREFIX { + BuilderSession::delete_by_token(token, &st.db).await?; + } else if let Ok(slug) = Slug::try_new(prefix) + && let Ok(db) = st.tenants.get(&slug).await + { + Session::delete_by_token(token, &db).await?; + } } let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); Ok((jar, StatusCode::NO_CONTENT)) diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index bb83457..96453d7 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -15,8 +15,9 @@ use std::collections::HashMap; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::StatusCode; use axum::response::Response; use serde::{Deserialize, Serialize}; diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index 3b275f0..220d93a 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -58,8 +58,9 @@ use std::collections::VecDeque; use std::time::Duration; +use crate::web::tenant_state::State; +use axum::extract::Path; use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; -use axum::extract::{Path, State}; use axum::response::Response; use serde::Deserialize; use serde_json::{Value, json}; diff --git a/src/web/boards.rs b/src/web/boards.rs index ffb41a3..565ec42 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -18,8 +18,9 @@ //! mid-session keeps drawing over an already-open socket until the room hears //! about it, so a roster change *must* fan out. +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use serde_json::json; diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index b065f5a..e1d5d7c 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -20,8 +20,9 @@ use std::time::Duration; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use axum::response::sse::{Event, KeepAlive, Sse}; use axum::response::{IntoResponse, Response}; diff --git a/src/web/classes.rs b/src/web/classes.rs index 834598a..fb24bb2 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -7,8 +7,9 @@ //! and its roster are the office's (manager+), while attaching a course writes //! *that course's* roster and takes the same right enrolling into it does. +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::{IntoParams, ToSchema}; diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index c4f7761..f7ee79a 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -5,8 +5,9 @@ //! teacher, or manager+), reads need [`super::courses::can_view_course`] //! (management rights, or enrollment). +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; use axum::http::{HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; @@ -387,6 +388,7 @@ async fn upload_file( // the row insert fails, take the fresh blob back out. let file = CourseNoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); let path = blob_path(&st.files_path, file.get_id().key()); + crate::web::ensure_files_dir(&st.files_path).await?; tokio::fs::write(&path, &upload.data) .await .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; diff --git a/src/web/courses.rs b/src/web/courses.rs index cfe7e3b..c926353 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -1415,6 +1416,7 @@ mod tests { let course = course(&manager, &db).await; let st = AppState { db: db.clone(), + tenants: crate::database::init_mem_tenants().await.unwrap(), files_path: std::env::temp_dir(), cookie_secure: false, rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), diff --git a/src/web/events.rs b/src/web/events.rs index 829f371..8a6b475 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 90cc1a5..440dffc 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -56,8 +56,9 @@ use std::time::Duration; +use crate::web::tenant_state::State; +use axum::extract::Path; use axum::extract::ws::{WebSocket, WebSocketUpgrade}; -use axum::extract::{Path, State}; use axum::response::Response; use serde::Deserialize; use serde_json::{Value, json}; diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index b022859..d264df5 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -1,7 +1,8 @@ use std::collections::{HashMap, HashSet}; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::StatusCode; use axum::response::Response; use serde::{Deserialize, Serialize}; diff --git a/src/web/extractor.rs b/src/web/extractor.rs index 0e6e655..9ad6d50 100644 --- a/src/web/extractor.rs +++ b/src/web/extractor.rs @@ -2,11 +2,14 @@ use axum::extract::{FromRef, FromRequestParts}; use axum::http::request::Parts; use axum_extra::extract::CookieJar; +use crate::database::Database; +use crate::domain::builder::{Builder, BuilderSession}; use crate::domain::role::Role; use crate::domain::session::Session; use crate::domain::user::User; use crate::error::AppError; use crate::state::AppState; +use crate::web::tenant_state::{resolve_tenant, split_cookie}; /// A principal injected as a request extension by the AI bridge, for the /// synthetic requests it dispatches into the router. Extensions cannot be set @@ -18,6 +21,11 @@ pub(crate) struct AiPrincipal(pub User); /// [`AiPrincipal`] extension wins over the cookie. The role is read fresh from /// the row on every request, so a role change takes effect on the user's next /// call — no re-login required. +/// +/// The school is resolved by the very helper `State` uses +/// ([`resolve_tenant`]), so the principal and the rows a handler then reads can +/// never come from two different databases. A `builder.` cookie names no +/// school and so cannot reach here at all. async fn authed_user(parts: &mut Parts, state: &S) -> Result where S: Send + Sync, @@ -27,24 +35,22 @@ where return Ok(principal.0.clone()); } + let (_, db) = resolve_tenant(parts, state).await?; + let jar = CookieJar::from_request_parts(parts, state) .await .map_err(|_| AppError::Unauthorized)?; - let token = jar - .get("session") - .map(|cookie| cookie.value().to_owned()) - .ok_or(AppError::Unauthorized)?; - - let app = AppState::from_ref(state); + let cookie = jar.get("session").ok_or(AppError::Unauthorized)?; + let (_, token) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?; - let session = Session::find_by_token(&token, &app.db) + let session = Session::find_by_token(token, &db) .await? .ok_or(AppError::Unauthorized)?; if session.is_expired() { return Err(AppError::Unauthorized); } - User::read(session.user(), &app.db) + User::read(session.user(), &db) .await? .ok_or(AppError::Unauthorized) } @@ -144,3 +150,45 @@ where Ok(RequireAdmin(user)) } } + +/// The deployment operator behind a `builder.` cookie, resolved against +/// the **control** database. Any school cookie is `401` here, and this cookie +/// is `401` on every school surface (`resolve_tenant` refuses the `builder` +/// prefix as a slug) — the two principals share a cookie name and nothing else. +pub struct RequireBuilder(pub Builder); + +impl FromRequestParts for RequireBuilder +where + S: Send + Sync, + AppState: FromRef, +{ + type Rejection = AppError; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + let jar = CookieJar::from_request_parts(parts, state) + .await + .map_err(|_| AppError::Unauthorized)?; + let cookie = jar.get("session").ok_or(AppError::Unauthorized)?; + let (prefix, token) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?; + if prefix != BUILDER_COOKIE_PREFIX { + return Err(AppError::Unauthorized); + } + + let control: Database = AppState::from_ref(state).tenants.control().clone(); + let session = BuilderSession::find_by_token(token, &control) + .await? + .ok_or(AppError::Unauthorized)?; + if session.is_expired() { + return Err(AppError::Unauthorized); + } + Ok(RequireBuilder( + Builder::read(session.builder(), &control) + .await? + .ok_or(AppError::Unauthorized)?, + )) + } +} + +/// The cookie prefix a builder session carries in place of a school slug. +/// `Slug::try_new` reserves this word, so it can never also name a school. +pub const BUILDER_COOKIE_PREFIX: &str = "builder"; diff --git a/src/web/homework.rs b/src/web/homework.rs index 0ca2e68..64f0582 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -5,8 +5,9 @@ //! [`super::courses`]); everything shares the visibility rule //! ([`Homework::student_sees`]) and the [`HOMEWORK_LOCK`]. +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; use axum::http::{HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; @@ -964,6 +965,7 @@ async fn upload_submission_file( upload.data.len() as i64, ); let path = blob_path(&st.files_path, file.get_file()); + crate::web::ensure_files_dir(&st.files_path).await?; tokio::fs::write(&path, &upload.data) .await .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; diff --git a/src/web/image.rs b/src/web/image.rs index 5402a41..9851b0b 100644 --- a/src/web/image.rs +++ b/src/web/image.rs @@ -62,6 +62,7 @@ pub(crate) async fn store_blob( where Fut: Future), AppError>>, { + crate::web::ensure_files_dir(&st.files_path).await?; let path = blob_path(&st.files_path, file); tokio::fs::write(&path, data) .await diff --git a/src/web/limits.rs b/src/web/limits.rs index 0a2185c..d71acb4 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -29,6 +29,14 @@ pub fn routes() -> OpenApiRouter { /// Account fields: credentials, profile, and the closed role set. #[derive(Serialize, ToSchema)] struct UserLimits { + /// The school slug the login and registration forms ask for, in front of + /// the dot in the session cookie. Lowercase `a-z`, `0-9` and `-`, starting + /// with a letter or digit. + min_slug_len: usize, + max_slug_len: usize, + /// Slugs no school may take — they name the builder cookie prefix and the + /// control database. + reserved_slugs: Vec<&'static str>, min_username_len: usize, max_username_len: usize, /// Separators allowed inside a username — never at the edges, never doubled. @@ -462,6 +470,9 @@ impl LimitsResponse { fn new(st: &AppState) -> Self { Self { user: UserLimits { + min_slug_len: MIN_SLUG_LEN, + max_slug_len: MAX_SLUG_LEN, + reserved_slugs: crate::tenant::RESERVED_SLUGS.to_vec(), min_username_len: MIN_USERNAME_LEN, max_username_len: MAX_USERNAME_LEN, username_separators: USERNAME_SEPARATORS.iter().map(char::to_string).collect(), diff --git a/src/web/marks.rs b/src/web/marks.rs index 24c9fb5..cba2b81 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::Path; use serde::Serialize; use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; diff --git a/src/web/meals.rs b/src/web/meals.rs index 8dab971..8b27a79 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -9,8 +9,9 @@ //! Money only ever *appends* here (see [`MealLedger`]): booking charges a price //! snapshot, cancelling reverses it, and recording a payment is admin-only. +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::{IntoParams, ToSchema}; diff --git a/src/web/messages.rs b/src/web/messages.rs index c1c8642..ea6f420 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -1,7 +1,8 @@ use std::collections::{HashMap, HashSet}; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::{IntoParams, ToSchema}; diff --git a/src/web/mod.rs b/src/web/mod.rs index e2865bc..788714f 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -35,6 +35,8 @@ pub mod terms; pub mod users; pub mod work; +pub mod tenant_state; + mod dto; // `pub(crate)` for `AiPrincipal`: the AI bridge injects it as an extension on // the requests it dispatches into the router (see `ai::server`). @@ -46,7 +48,10 @@ pub use dto::{ CourseResponse, ExamResponse, HomeworkResponse, PersonRef, SessionResponse, SubjectResponse, UserResponse, course_people, person_map, }; -pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher}; +pub use extractor::{ + BUILDER_COOKIE_PREFIX, CurrentUser, RequireAdmin, RequireBuilder, RequireManager, + RequireStudent, RequireTeacher, +}; pub(crate) use image::{ImageUpload, read_image_upload, store_blob}; pub use page::{Page, PageParams, Scheduled, WindowParams, paginate}; @@ -187,6 +192,20 @@ pub(crate) fn blob_path(files_path: &FsPath, key: &str) -> PathBuf { files_path.join(key) } +/// Make sure a school's blob directory exists before writing into it. +/// +/// `FILES_PATH` is the deployment root and `main` creates only that; each +/// school's subdirectory appears the first time that school stores a file, so +/// nothing has to be provisioned when a school is created. +pub(crate) async fn ensure_files_dir(files_path: &FsPath) -> Result<(), AppError> { + tokio::fs::create_dir_all(files_path).await.map_err(|err| { + AppError::Internal(format!( + "failed to create the files directory {}: {err}", + files_path.display() + )) + }) +} + /// Best-effort blob removal after its row is gone. Failure only strands an /// unreachable file on disk, so it is logged rather than surfaced. pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) { diff --git a/src/web/notes.rs b/src/web/notes.rs index d22d712..74e890c 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -1,5 +1,6 @@ +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; use axum::http::{HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; @@ -283,6 +284,7 @@ async fn upload_file( // the row insert fails, take the fresh blob back out. let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); let path = blob_path(&st.files_path, file.get_id().key()); + crate::web::ensure_files_dir(&st.files_path).await?; tokio::fs::write(&path, &upload.data) .await .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; diff --git a/src/web/payments.rs b/src/web/payments.rs index c4a273e..f927a97 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -13,8 +13,9 @@ use std::collections::HashMap; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; diff --git a/src/web/pomodoro.rs b/src/web/pomodoro.rs index b93bc5e..927f85b 100644 --- a/src/web/pomodoro.rs +++ b/src/web/pomodoro.rs @@ -1,5 +1,6 @@ +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::Serialize; use utoipa::ToSchema; diff --git a/src/web/questions.rs b/src/web/questions.rs index e4b7a80..bbcd84a 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -8,8 +8,9 @@ //! opposite: unmoderated, so their author may edit the body and attach, //! replace, or drop one photo at any time — moderation there is delete-only. +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::StatusCode; use axum::response::Response; use serde::{Deserialize, Serialize}; diff --git a/src/web/sessions.rs b/src/web/sessions.rs index cf8f66f..3e5d50c 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; diff --git a/src/web/settings.rs b/src/web/settings.rs index d6be898..f664175 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -1,5 +1,5 @@ +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::State; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; diff --git a/src/web/subjects.rs b/src/web/subjects.rs index cee5977..303a71e 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -1,5 +1,6 @@ +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::Path; use axum::http::StatusCode; use serde::Deserialize; use utoipa::ToSchema; diff --git a/src/web/tenant_state.rs b/src/web/tenant_state.rs new file mode 100644 index 0000000..53b8e16 --- /dev/null +++ b/src/web/tenant_state.rs @@ -0,0 +1,305 @@ +//! The school-scoped replacement for `axum::extract::State`. +//! +//! [`State`] is named to **shadow** `axum::extract::State` on purpose: a +//! handler file swaps one import and every `State(st)` in it starts working in +//! the caller's school instead of the control database, with no handler body +//! touched. That is the whole design — there is no `st.db` a handler could +//! forget to scope, because the only `st` it can name is already scoped. +//! +//! Three files keep the real `axum::extract::State` because they legitimately +//! see the control database: `web::auth` (it resolves the school itself, and +//! its rate limiter is deployment-wide), `web::limits` (constants, no rows) and +//! `web::ai` (bridge certificate, no rows). + +use std::path::PathBuf; + +use axum::extract::{FromRef, FromRequestParts}; +use axum::http::request::Parts; +use axum_extra::extract::CookieJar; + +use crate::database::Database; +use crate::error::AppError; +use crate::state::AppState; +use crate::tenant::Slug; + +/// The school a request has already been resolved into, injected as a request +/// extension by an in-process caller that has no cookie — today only the AI +/// bridge. Extensions cannot be set from outside the process, so this is +/// unforgeable over HTTP, exactly like +/// [`crate::web::extractor::AiPrincipal`]. +#[derive(Clone)] +pub struct TenantExt { + pub slug: Slug, + pub db: Database, +} + +/// Split a `session` cookie into its school part and its token. `builder` in +/// the first position is the deployment operator; anything else is a slug. +/// +/// Splits at the **first** dot, so a token can never be mistaken for a slug no +/// matter what it contains (it is hex today, and this does not depend on that). +pub fn split_cookie(value: &str) -> Option<(&str, &str)> { + let (prefix, token) = value.split_once('.')?; + (!prefix.is_empty() && !token.is_empty()).then_some((prefix, token)) +} + +/// The school behind this request: the `TenantExt` extension if one was +/// injected, else the `session` cookie's prefix. +/// +/// Shared with [`crate::web::extractor`] so the two can never disagree about +/// which school a request belongs to — the authenticated user and the rows +/// they read must come from the same database. +pub(crate) async fn resolve_tenant( + parts: &mut Parts, + state: &S, +) -> Result<(Slug, Database), AppError> +where + S: Send + Sync, + AppState: FromRef, +{ + if let Some(tenant) = parts.extensions.get::() { + return Ok((tenant.slug.clone(), tenant.db.clone())); + } + let jar = CookieJar::from_request_parts(parts, state) + .await + .map_err(|_| AppError::Unauthorized)?; + let cookie = jar.get("session").ok_or(AppError::Unauthorized)?; + // A builder cookie names no school, and a cookie with no dot names nothing + // at all. Both are `401` here: the builder surface is a different extractor + // (`RequireBuilder`), and this one must never let it in. + let (prefix, _) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?; + let slug = Slug::try_new(prefix).map_err(|_| AppError::Unauthorized)?; + + let app = AppState::from_ref(state); + let db = app.tenants.get(&slug).await?; + Ok((slug, db)) +} + +/// The application state, narrowed to the caller's school. Drop-in for +/// `axum::extract::State` in every handler that reads school data. +/// +/// Unauthenticated callers are refused *here*, before the handler runs — which +/// is correct for every route that uses it, since all of them already require a +/// session to do anything. +pub struct State(pub T); + +impl FromRequestParts for State +where + S: Send + Sync, + AppState: FromRef, +{ + type Rejection = AppError; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + let (slug, db) = resolve_tenant(parts, state).await?; + let app = AppState::from_ref(state); + Ok(State(AppState { + db, + files_path: school_files_path(&app.files_path, &slug), + ..app + })) + } +} + +/// Just the school, for the handlers that need it as a key prefix (the exam +/// presence map, the whiteboard hub) rather than as a database handle. +pub struct SchoolSlug(pub Slug); + +impl FromRequestParts for SchoolSlug +where + S: Send + Sync, + AppState: FromRef, +{ + type Rejection = AppError; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + Ok(SchoolSlug(resolve_tenant(parts, state).await?.0)) + } +} + +/// Where a school's uploaded blobs live: one directory per school under the +/// deployment's `FILES_PATH`. The slug's character set is what makes this a +/// plain `join` — it can contain no separator and no `..`. +pub fn school_files_path(root: &std::path::Path, slug: &Slug) -> PathBuf { + root.join(slug.as_str()) +} + +#[cfg(test)] +mod tests { + use super::*; + + use axum::http::StatusCode; + use axum::routing::get; + use axum::{Router, body::Body, http::Request}; + use tower::ServiceExt; + + use crate::database::init_mem_tenants; + use crate::domain::builder::{Builder, BuilderSession}; + use crate::domain::session::Session; + use crate::domain::user::{Password, User, Username}; + use crate::tenant::DEMO_SLUG; + use crate::web::{CurrentUser, RequireBuilder}; + + async fn school_surface(State(_): State, CurrentUser(_): CurrentUser) -> StatusCode { + StatusCode::OK + } + + async fn builder_surface(RequireBuilder(_): RequireBuilder) -> StatusCode { + StatusCode::OK + } + + /// A two-route app, one live cookie of each kind, and the registry behind + /// them. + async fn harness() -> (Router, String, String, crate::tenant::Tenants) { + let tenants = init_mem_tenants().await.expect("in-memory deployment"); + let school = tenants + .get(&Slug::try_new(DEMO_SLUG).unwrap()) + .await + .expect("the demo school"); + + let user = User::create( + Username::try_new("ada").unwrap(), + Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(), + &school, + ) + .await + .unwrap(); + let session = Session::create(user.get_id(), &school).await.unwrap(); + let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str()); + + Builder::ensure( + Username::try_new("operator").unwrap(), + Password::try_new("secret1").unwrap(), + tenants.control(), + ) + .await + .unwrap(); + let builder = Builder::find_by_username("operator", tenants.control()) + .await + .unwrap() + .unwrap(); + let builder_session = BuilderSession::create(builder.get_id(), tenants.control()) + .await + .unwrap(); + let builder_cookie = format!("session=builder.{}", builder_session.token().as_str()); + + let state = AppState { + db: tenants.control().clone(), + tenants: tenants.clone(), + files_path: std::env::temp_dir(), + cookie_secure: false, + rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + exam_presence: Default::default(), + board_hub: Default::default(), + db_up: Default::default(), + ai: None, + }; + let app = Router::new() + .route("/school", get(school_surface)) + .route("/builder", get(builder_surface)) + .with_state(state); + (app, school_cookie, builder_cookie, tenants) + } + + async fn status(app: &Router, uri: &str, cookie: Option<&str>) -> StatusCode { + let mut builder = Request::builder().uri(uri); + if let Some(cookie) = cookie { + builder = builder.header("cookie", cookie); + } + app.clone() + .oneshot(builder.body(Body::empty()).unwrap()) + .await + .unwrap() + .status() + } + + /// The two principals share a cookie name and nothing else. Neither may + /// ever be accepted where the other belongs — a builder holding school + /// power, or a student reaching the school-management surface, is the one + /// failure this whole split exists to prevent. + #[tokio::test] + async fn neither_cookie_works_on_the_others_surface() { + let (app, school, builder, _) = harness().await; + + assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK); + assert_eq!( + status(&app, "/builder", Some(&builder)).await, + StatusCode::OK + ); + + assert_eq!( + status(&app, "/school", Some(&builder)).await, + StatusCode::UNAUTHORIZED, + "a builder cookie must not pass a school extractor" + ); + assert_eq!( + status(&app, "/builder", Some(&school)).await, + StatusCode::UNAUTHORIZED, + "a school cookie must not pass RequireBuilder" + ); + + // A cookie with no school part names nothing resolvable — including the + // pre-tenancy shape, which is deliberately not accepted anywhere. + let bare = school.replace(&format!("{DEMO_SLUG}."), ""); + for uri in ["/school", "/builder"] { + assert_eq!( + status(&app, uri, Some(&bare)).await, + StatusCode::UNAUTHORIZED, + "{uri} accepted a cookie with no school" + ); + assert_eq!( + status(&app, uri, None).await, + StatusCode::UNAUTHORIZED, + "{uri} accepted no cookie at all" + ); + } + } + + /// A suspended school is refused at the edge, before any handler — with a + /// session that was perfectly good a moment earlier, and through a handle + /// the registry had already cached. + #[tokio::test] + async fn a_suspension_refuses_a_live_session() { + let (app, school, _, tenants) = harness().await; + let demo = Slug::try_new(DEMO_SLUG).unwrap(); + assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK); + + tenants + .set_status(&demo, crate::tenant::SchoolStatus::Suspended) + .await + .unwrap(); + assert_eq!( + status(&app, "/school", Some(&school)).await, + StatusCode::FORBIDDEN, + "a suspended school must be refused immediately, cached handle or not" + ); + + tenants + .set_status(&demo, crate::tenant::SchoolStatus::Active) + .await + .unwrap(); + assert_eq!( + status(&app, "/school", Some(&school)).await, + StatusCode::OK, + "un-suspending must restore the very same session" + ); + } + + #[test] + fn a_cookie_splits_at_its_first_dot_or_not_at_all() { + assert_eq!(split_cookie("demo.abc123"), Some(("demo", "abc123"))); + assert_eq!(split_cookie("builder.abc123"), Some(("builder", "abc123"))); + // First dot, so a dotted token still yields the school it named. + assert_eq!(split_cookie("demo.a.b"), Some(("demo", "a.b"))); + // A pre-tenancy cookie, an empty half, or nothing at all names no + // school — every one of these must be refused, not guessed at. + for bad in ["abc123", "", ".", "demo.", ".abc123"] { + assert_eq!(split_cookie(bad), None, "{bad:?}"); + } + } +} diff --git a/src/web/terms.rs b/src/web/terms.rs index 2b72276..4506b15 100644 --- a/src/web/terms.rs +++ b/src/web/terms.rs @@ -1,5 +1,6 @@ +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; diff --git a/src/web/users.rs b/src/web/users.rs index 07d43e5..6e15242 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -1,5 +1,6 @@ +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::StatusCode; use axum::response::Response; use serde::{Deserialize, Serialize}; diff --git a/src/web/work.rs b/src/web/work.rs index f9d51ad..bd9438c 100644 --- a/src/web/work.rs +++ b/src/web/work.rs @@ -1,5 +1,6 @@ +use crate::web::tenant_state::State; use axum::Json; -use axum::extract::{Path, Query, State}; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index db5493f..67e5061 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -816,11 +816,10 @@ async fn the_alpn_and_the_protocol_id_are_the_same_string() { /// (status, body). async fn fetch_certificate(ai: Option) -> (axum::http::StatusCode, Value) { use tower::ServiceExt; - let db = hezarfen_backend::database::init_mem() - .await - .expect("mem db"); + let (tenants, _db) = common::mem_deployment().await; let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { - db, + db: tenants.control().clone(), + tenants, files_path: std::env::temp_dir(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), @@ -950,11 +949,10 @@ use surrealdb::types::RecordId; /// A router wired to `bridge`, plus a handle to its in-memory database. async fn chat_app(bridge: &AiBridge) -> (Router, Database) { - let db = hezarfen_backend::database::init_mem() - .await - .expect("mem db"); + let (tenants, db) = common::mem_deployment().await; let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { - db: db.clone(), + db: tenants.control().clone(), + tenants, files_path: common::files_dir(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), diff --git a/tests/ai_protocol.rs b/tests/ai_protocol.rs index fc760c8..82e261b 100644 --- a/tests/ai_protocol.rs +++ b/tests/ai_protocol.rs @@ -920,11 +920,16 @@ async fn a_chat_request_names_the_askers_school_role() { let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; await_workers(&bridge, 1).await; - let db = hezarfen_backend::database::init_mem() + let tenants = hezarfen_backend::database::init_mem_tenants() .await - .expect("mem db"); + .expect("in-memory deployment"); + let db = tenants + .get(&hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap()) + .await + .expect("the demo school"); let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { - db: db.clone(), + db: tenants.control().clone(), + tenants, files_path: common::files_dir(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), diff --git a/tests/auth_enumeration.rs b/tests/auth_enumeration.rs index 60f7438..a2cafb4 100644 --- a/tests/auth_enumeration.rs +++ b/tests/auth_enumeration.rs @@ -12,13 +12,13 @@ use serde_json::json; #[tokio::test] async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { let (app, db) = app_and_db().await; - let taken = json!({ "username": "ada", "password": "secret1" }); + let taken = json!({ "school": "demo", "username": "ada", "password": "secret1" }); let first = send(&app, "POST", "/auth/register", None, Some(taken.clone())).await; assert_eq!(first.status, StatusCode::CREATED); // Same username again, different password: still 201, same body shape. - let dup_creds = json!({ "username": "ada", "password": "attacker" }); + let dup_creds = json!({ "school": "demo", "username": "ada", "password": "attacker" }); let started = Instant::now(); let dup = send( &app, @@ -35,7 +35,7 @@ async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { "POST", "/auth/register", None, - Some(json!({ "username": "grace", "password": "secret1" })), + Some(json!({ "school": "demo", "username": "grace", "password": "secret1" })), ) .await; @@ -122,7 +122,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() { "POST", "/auth/register", None, - Some(json!({ "username": "ada", "password": "secret1" })), + Some(json!({ "school": "demo", "username": "ada", "password": "secret1" })), ) .await; let taken = send( @@ -130,7 +130,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() { "POST", "/auth/register", None, - Some(json!({ "username": "ada", "password": "another1" })), + Some(json!({ "school": "demo", "username": "ada", "password": "another1" })), ) .await; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 4c2e91b..b9b00f8 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -12,6 +12,7 @@ use hezarfen_backend::ai::AiBridge; use hezarfen_backend::database::Database; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::{AppState, DbHealth}; +use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; use hezarfen_backend::{build_router, database}; use serde_json::{Value, json}; use tempfile::TempDir; @@ -43,6 +44,49 @@ pub async fn app_and_db() -> (Router, Database) { app_with_ai(None).await } +/// [`app_and_db`] plus the registry behind it, for the suites whose subject is +/// tenancy itself (a second school, a suspension, the builder surface). +pub async fn app_and_tenants() -> (Router, Database, Tenants) { + let (app, db, tenants) = app_parts(None, Default::default()).await; + (app, db, tenants) +} + +/// Where the demo school's blobs land: one directory per school under +/// `FILES_PATH`, created on the school's first upload. +pub fn blob_dir() -> PathBuf { + let dir = files_dir().join(DEMO_SLUG); + std::fs::create_dir_all(&dir).expect("blob dir"); + dir +} + +/// The raw session token out of a `session=.` cookie value — +/// what a test needs when it writes a session row by hand. +pub fn cookie_token(cookie: &str) -> &str { + cookie + .trim_start_matches("session=") + .split_once('.') + .expect("a session cookie carries its school") + .1 +} + +/// An in-memory deployment: the registry, plus the demo school's handle. For +/// the suites that build their own `AppState` instead of using [`app_and_db`]. +pub async fn mem_deployment() -> (Tenants, Database) { + let tenants = database::init_mem_tenants() + .await + .expect("in-memory deployment"); + let db = demo_db(&tenants).await; + (tenants, db) +} + +/// The demo school's handle out of a registry. +pub async fn demo_db(tenants: &Tenants) -> Database { + tenants + .get(&Slug::try_new(DEMO_SLUG).expect("the demo slug")) + .await + .expect("the demo school resolves") +} + /// The same router, with the AI bridge wired into its state. `build_router` /// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the /// 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) -> (Router, Database) { /// database socket down under a running app — the api-read path re-checks it in /// place of the HTTP db guard it bypasses. pub async fn app_with_ai_health(ai: Option, db_up: DbHealth) -> (Router, Database) { - let db = database::init_mem().await.expect("in-memory db"); + let (app, db, _) = app_parts(ai, db_up).await; + (app, db) +} + +/// The one bootstrap: an in-memory deployment (control database + the demo +/// school), a router over it, and the demo school's handle — which is what +/// every suite means by "the database", since that is where users and rows +/// live. +async fn app_parts(ai: Option, db_up: DbHealth) -> (Router, Database, Tenants) { + let tenants = database::init_mem_tenants() + .await + .expect("in-memory deployment"); + let db = demo_db(&tenants).await; let app = build_router(AppState { - db: db.clone(), + db: tenants.control().clone(), + tenants: tenants.clone(), files_path: files_dir(), cookie_secure: false, // 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, db_up: DbHealth) -> (Route db_up, ai, }); - (app, db) + (app, db, tenants) } /// A router backed by a fresh in-memory database. @@ -91,7 +148,7 @@ pub async fn set_role(db: &Database, username: &str, role: &str) { /// Register (password `secret1`), promote to `role`, then log in. Returns the /// session `Cookie` value. pub async fn login_as(app: &Router, db: &Database, username: &str, role: &str) -> String { - let creds = json!({ "username": username, "password": "secret1" }); + let creds = json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" }); let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); set_role(db, username, role).await; @@ -265,7 +322,7 @@ pub async fn upload_course_note_file( /// Register (password `secret1`) then log in; returns the session `Cookie` value. pub async fn login(app: &Router, username: &str) -> String { - let creds = json!({ "username": username, "password": "secret1" }); + let creds = json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" }); let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); let res = send(app, "POST", "/auth/login", None, Some(creds)).await; diff --git a/tests/e2e.rs b/tests/e2e.rs index afb1a40..a4d3a87 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -4,6 +4,7 @@ use hezarfen_backend::database::Database; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::AppState; +use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; use hezarfen_backend::{build_router, database}; use reqwest::{Client, StatusCode}; use serde_json::{Value, json}; @@ -17,9 +18,16 @@ async fn spawn_server() -> (String, Database) { /// [`spawn_server`], with the AI bridge the chatbot relays through wired in. async fn spawn_server_with_ai(ai: Option) -> (String, Database) { - let db = database::init_mem().await.expect("in-memory db"); + let tenants = database::init_mem_tenants() + .await + .expect("in-memory deployment"); + let db = tenants + .get(&Slug::try_new(DEMO_SLUG).unwrap()) + .await + .expect("the demo school"); let app = build_router(AppState { - db: db.clone(), + db: tenants.control().clone(), + tenants, // Kept (not auto-deleted) so the directory outlives this helper; // it's under the OS temp dir, reclaimed like any other temp file. files_path: tempfile::tempdir().expect("files dir").keep(), @@ -67,7 +75,7 @@ fn client() -> Client { async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response { client .post(format!("{base}/auth/register")) - .json(&json!({ "username": user, "password": "secret1" })) + .json(&json!({ "school": "demo", "username": user, "password": "secret1" })) .send() .await .unwrap() @@ -76,7 +84,7 @@ async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response async fn login(client: &Client, base: &str, user: &str) { let res = client .post(format!("{base}/auth/login")) - .json(&json!({ "username": user, "password": "secret1" })) + .json(&json!({ "school": "demo", "username": user, "password": "secret1" })) .send() .await .unwrap(); @@ -422,7 +430,7 @@ async fn attendance_rollup_across_users() { async fn raw_session_cookie(base: &str, user: &str) -> String { let res = Client::new() .post(format!("{base}/auth/login")) - .json(&json!({ "username": user, "password": "secret1" })) + .json(&json!({ "school": "demo", "username": user, "password": "secret1" })) .send() .await .unwrap(); diff --git a/tests/etag.rs b/tests/etag.rs index 22a40a3..e6f80d2 100644 --- a/tests/etag.rs +++ b/tests/etag.rs @@ -154,7 +154,7 @@ async fn handler_owned_etag_passes_through_and_never_304s() { #[tokio::test] async fn mutations_are_never_etagged() { let app = mem_app().await; - let creds = serde_json::json!({ "username": "ann", "password": "secret1" }); + let creds = serde_json::json!({ "school": "demo", "username": "ann", "password": "secret1" }); let res = app .clone() .oneshot( diff --git a/tests/integration.rs b/tests/integration.rs index cac2f2a..3cb21d1 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -10,6 +10,7 @@ use common::{ create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll, upload_course_note_file, }; +use hezarfen_backend::build_router; use hezarfen_backend::constant::{ BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_COURSE_NOTE_FILES, MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS, @@ -28,7 +29,6 @@ use hezarfen_backend::domain::session::Session; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::{Password, User, UserId, Username}; use hezarfen_backend::state::AppState; -use hezarfen_backend::{build_router, database}; use serde_json::json; use tower::ServiceExt; @@ -150,7 +150,8 @@ async fn limits_publishes_the_bounds_the_api_actually_enforces() { let max = res.body["user"]["max_username_len"] .as_u64() .expect("max_username_len is an integer") as usize; - let too_long = json!({ "username": "a".repeat(max + 1), "password": "secret1" }); + let too_long = + json!({ "school": "demo", "username": "a".repeat(max + 1), "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(too_long)).await; assert_eq!(res.status, StatusCode::BAD_REQUEST); } @@ -162,8 +163,10 @@ async fn limits_still_answers_while_the_database_is_down() { // row, so the outage guard must let it through — otherwise the client // falls back to the hard-coded copy this endpoint exists to remove. let db_up = hezarfen_backend::state::DbHealth::default(); + let (tenants, _db) = common::mem_deployment().await; let app = build_router(AppState { - db: database::init_mem().await.expect("in-memory db"), + db: tenants.control().clone(), + tenants, files_path: tempfile::tempdir().expect("files dir").keep(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), @@ -190,25 +193,25 @@ async fn register_validates_input() { let app = mem_app().await; // Password too short -> 400. - let short = json!({ "username": "bob", "password": "123" }); + let short = json!({ "school": "demo", "username": "bob", "password": "123" }); let res = send(&app, "POST", "/auth/register", None, Some(short)).await; assert_eq!(res.status, StatusCode::BAD_REQUEST); // Blank username -> 400. - let blank = json!({ "username": " ", "password": "secret1" }); + let blank = json!({ "school": "demo", "username": " ", "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(blank)).await; assert_eq!(res.status, StatusCode::BAD_REQUEST); // Uppercase anywhere in the username -> 400. for bad in ["Bob", "bOb", "BOB"] { - let upper = json!({ "username": bad, "password": "secret1" }); + let upper = json!({ "school": "demo", "username": bad, "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(upper)).await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); } // Username must start and end with a letter or digit -> 400. for bad in ["-bob", "bob-", "_bob", "bob_", ".bob"] { - let edge = json!({ "username": bad, "password": "secret1" }); + let edge = json!({ "school": "demo", "username": bad, "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(edge)).await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); } @@ -223,26 +226,26 @@ async fn register_validates_input() { "a/b", "a\"b", ] { - let ugly = json!({ "username": bad, "password": "secret1" }); + let ugly = json!({ "school": "demo", "username": bad, "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(ugly)).await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad:?} accepted"); } // Consecutive separators -> 400. for bad in ["a--b", "a..b", "a__b", "a.-b"] { - let doubled = json!({ "username": bad, "password": "secret1" }); + let doubled = json!({ "school": "demo", "username": bad, "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(doubled)).await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); } // Single separators between alphanumerics are fine -> 201. - let dotted = json!({ "username": "ali.k_1-b", "password": "secret1" }); + let dotted = json!({ "school": "demo", "username": "ali.k_1-b", "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(dotted)).await; assert_eq!(res.status, StatusCode::CREATED); assert_eq!(res.body["username"], "ali.k_1-b"); // Valid -> 201, no password echoed back, defaults to the student role. - let ok = json!({ "username": "bob", "password": "secret1" }); + let ok = json!({ "school": "demo", "username": "bob", "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(ok.clone())).await; assert_eq!(res.status, StatusCode::CREATED); assert_eq!(res.body["username"], "bob"); @@ -253,7 +256,7 @@ async fn register_validates_input() { // deliberately indistinguishable — see tests/auth_enumeration.rs), but the // write is still rejected: the original password keeps working and the // second one never becomes valid. - let dup = json!({ "username": "bob", "password": "hijack1" }); + let dup = json!({ "school": "demo", "username": "bob", "password": "hijack1" }); let res = send(&app, "POST", "/auth/register", None, Some(dup.clone())).await; assert_eq!(res.status, StatusCode::CREATED); let res = send(&app, "POST", "/auth/login", None, Some(ok)).await; @@ -284,7 +287,7 @@ async fn register_rejects_reserved_usernames() { "moderator", "staff", ] { - let creds = json!({ "username": name, "password": "secret1" }); + let creds = json!({ "school": "demo", "username": name, "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(creds)).await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{name} accepted"); let msg = res.body["error"].as_str().unwrap_or_default(); @@ -298,7 +301,7 @@ async fn register_rejects_reserved_usernames() { // (created through `ensure_admin`, not `/auth/register`) still logs in. // Covered by the admin bootstrap tests; here just prove a reserved name // is not permanently poisoned for login by the register-level check. - let creds = json!({ "username": "admin", "password": "wrong" }); + let creds = json!({ "school": "demo", "username": "admin", "password": "wrong" }); let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; assert_eq!(res.status, StatusCode::UNAUTHORIZED); // bad credentials, not "reserved" } @@ -311,7 +314,7 @@ async fn login_rejects_bad_credentials() { "POST", "/auth/register", None, - Some(json!({ "username": "kate", "password": "secret1" })), + Some(json!({ "school": "demo", "username": "kate", "password": "secret1" })), ) .await; @@ -321,7 +324,7 @@ async fn login_rejects_bad_credentials() { "POST", "/auth/login", None, - Some(json!({ "username": "kate", "password": "wrong" })), + Some(json!({ "school": "demo", "username": "kate", "password": "wrong" })), ) .await; assert_eq!(res.status, StatusCode::UNAUTHORIZED); @@ -332,7 +335,7 @@ async fn login_rejects_bad_credentials() { "POST", "/auth/login", None, - Some(json!({ "username": "ghost", "password": "secret1" })), + Some(json!({ "school": "demo", "username": "ghost", "password": "secret1" })), ) .await; assert_eq!(res.status, StatusCode::UNAUTHORIZED); @@ -627,7 +630,7 @@ async fn a_demotion_to_parent_strands_no_note_and_no_blob() { .await; assert_eq!(up.status, StatusCode::CREATED); let file_id = id_of(&up.body); - let blob = common::files_dir().join(&file_id); + let blob = common::blob_dir().join(&file_id); assert!(blob.exists(), "the upload must have written a blob"); // 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() { StatusCode::NO_CONTENT ); assert!(!blob.exists(), "deleting a file must unlink its blob"); - let extra_blob = common::files_dir().join(id_of(&extra.body)); + let extra_blob = common::blob_dir().join(id_of(&extra.body)); assert_eq!( send( &app, @@ -959,7 +962,7 @@ async fn note_files_upload_download_delete_roundtrip() { StatusCode::NOT_FOUND ); assert!( - !common::files_dir().join(&file_id).exists(), + !common::blob_dir().join(&file_id).exists(), "blob must be unlinked with its row" ); } @@ -1238,13 +1241,13 @@ async fn malformed_json_bodies_answer_422_across_every_extractor_shape() { ( "/auth/register", None, - r#"{"username": 5, "password": "secret1"}"#, + r#"{"school": "demo", "username": 5, "password": "secret1"}"#, "plain Json, type mismatch", ), ( "/auth/register", None, - r#"{"username": "veli"}"#, + r#"{"school": "demo", "username": "veli"}"#, "plain Json, missing required field", ), ( @@ -1288,7 +1291,7 @@ async fn malformed_json_bodies_answer_422_across_every_extractor_shape() { for (body, why) in [ ("not json at all", "unparseable JSON"), ( - r#"{"username": "a", "password": "secret1"}"#, + r#"{"school": "demo", "username": "a", "password": "secret1"}"#, "well-typed value refused by a domain rule", ), ] { @@ -1397,7 +1400,7 @@ async fn deleting_a_note_removes_its_files() { let left: Vec = rows.take(0).unwrap(); assert!(left.is_empty(), "note_file rows must cascade: {left:?}"); assert!( - !common::files_dir().join(&file_id).exists(), + !common::blob_dir().join(&file_id).exists(), "blob must be unlinked when its note dies" ); } @@ -5924,7 +5927,7 @@ async fn expired_session_is_unauthorized_before_any_purge() { user = (SELECT VALUE user FROM ONLY session WHERE token = $live LIMIT 1), \ token = 'stale-token', expires_at = 1", ) - .bind(("live", ali.trim_start_matches("session=").to_string())) + .bind(("live", common::cookie_token(&ali).to_string())) .await .unwrap() .check() @@ -5959,7 +5962,9 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { "POST", "/auth/register", None, - Some(json!({ "username": "ali", "password": "secret1" })), + Some( + json!({ "school": "demo", "school": "demo", "username": "ali", "password": "secret1" }), + ), ) .await; assert_eq!(res.status, StatusCode::CREATED); @@ -5974,7 +5979,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { "POST", "/auth/register", None, - Some(json!({ "username": spoof, "password": "spoof1" })), + Some(json!({ "school": "demo", "username": spoof, "password": "spoof1" })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{spoof:?}"); @@ -6008,7 +6013,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { "POST", "/auth/login", None, - Some(json!({ "username": attempt, "password": "secret1" })), + Some(json!({ "school": "demo", "username": attempt, "password": "secret1" })), ) .await; assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); @@ -6017,7 +6022,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { "POST", "/auth/login", None, - Some(json!({ "username": attempt, "password": "spoof1" })), + Some(json!({ "school": "demo", "username": attempt, "password": "spoof1" })), ) .await; assert_eq!( @@ -6033,7 +6038,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { "POST", "/auth/register", None, - Some(json!({ "username": " veli ", "password": "secret1" })), + Some(json!({ "school": "demo", "username": " veli ", "password": "secret1" })), ) .await; assert_eq!(res.status, StatusCode::CREATED); @@ -6046,7 +6051,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { "POST", "/auth/login", None, - Some(json!({ "username": attempt, "password": "secret1" })), + Some(json!({ "school": "demo", "username": attempt, "password": "secret1" })), ) .await; assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); @@ -6340,7 +6345,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { "POST", "/auth/register", None, - Some(json!({ "username": "dup", "password": "secret1" })), + Some(json!({ "school": "demo", "username": "dup", "password": "secret1" })), ) .await .status @@ -6378,7 +6383,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { "POST", "/auth/register", None, - Some(json!({ "username": "dup", "password": "hijack1" })), + Some(json!({ "school": "demo", "username": "dup", "password": "hijack1" })), ) .await; assert_eq!(res.status, StatusCode::CREATED); @@ -6387,7 +6392,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { "POST", "/auth/login", None, - Some(json!({ "username": "dup", "password": "secret1" })), + Some(json!({ "school": "demo", "username": "dup", "password": "secret1" })), ) .await; assert_eq!(res.status, StatusCode::OK, "the winning password broke"); @@ -6396,7 +6401,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { "POST", "/auth/login", None, - Some(json!({ "username": "dup", "password": "hijack1" })), + Some(json!({ "school": "demo", "username": "dup", "password": "hijack1" })), ) .await; assert_eq!( @@ -6465,7 +6470,7 @@ async fn child_lists_of_missing_parents_are_404() { #[tokio::test] async fn session_cookie_secure_attribute_follows_config() { async fn login_set_cookie(app: &axum::Router) -> String { - let creds = json!({ "username": "ada", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" }); assert_eq!( send(app, "POST", "/auth/register", None, Some(creds.clone())) .await @@ -6507,9 +6512,10 @@ async fn session_cookie_secure_attribute_follows_config() { ); // With the flag on: Secure present. - let db = database::init_mem().await.unwrap(); + let (tenants, _db) = common::mem_deployment().await; let app = build_router(AppState { - db, + db: tenants.control().clone(), + tenants, files_path: common::files_dir(), cookie_secure: true, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), @@ -6546,10 +6552,11 @@ async fn db_down_refuses_before_touching_the_database() { ids.len() } - let db = database::init_mem().await.unwrap(); + let (tenants, db) = common::mem_deployment().await; let db_up = hezarfen_backend::state::DbHealth::default(); let app = build_router(AppState { - db: db.clone(), + db: tenants.control().clone(), + tenants, files_path: common::files_dir(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), @@ -6570,7 +6577,8 @@ async fn db_down_refuses_before_touching_the_database() { .uri("/auth/register") .header("content-type", "application/json") .body(Body::from( - json!({"username": "gulsah", "password": "sifre12345"}).to_string(), + json!({"school": "demo", "username": "gulsah", "password": "sifre12345"}) + .to_string(), )) .unwrap(), ) @@ -6594,7 +6602,8 @@ async fn db_down_refuses_before_touching_the_database() { .uri("/auth/register") .header("content-type", "application/json") .body(Body::from( - json!({"username": "kerem", "password": "sifre12345"}).to_string(), + json!({"school": "demo", "username": "kerem", "password": "sifre12345"}) + .to_string(), )) .unwrap(), ) @@ -6621,7 +6630,8 @@ async fn db_down_refuses_before_touching_the_database() { .uri("/auth/register") .header("content-type", "application/json") .body(Body::from( - json!({"username": "kerem", "password": "sifre12345"}).to_string(), + json!({"school": "demo", "username": "kerem", "password": "sifre12345"}) + .to_string(), )) .unwrap(), ) @@ -6814,7 +6824,7 @@ async fn admin_seed_creates_working_admin() { let password = Password::try_new("secret1").unwrap(); User::ensure_admin(username, password, &db).await.unwrap(); - let creds = json!({ "username": "root", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "root", "password": "secret1" }); let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; assert_eq!(res.status, StatusCode::OK); assert_eq!(res.body["role"], "admin"); @@ -6836,7 +6846,7 @@ async fn admin_seed_is_idempotent() { } let cookie = { - let creds = json!({ "username": "root", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "root", "password": "secret1" }); let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; assert_eq!(res.status, StatusCode::OK); res.cookie.expect("session cookie") @@ -6863,7 +6873,7 @@ async fn admin_seed_refuses_existing_non_admin() { assert_eq!(res.status, StatusCode::FORBIDDEN, "must not be promoted"); // ...and the original password still logs in (nothing was overwritten). - let creds = json!({ "username": "squatter", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "squatter", "password": "secret1" }); let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; assert_eq!(res.status, StatusCode::OK); assert_eq!(res.body["role"], "student"); @@ -12450,7 +12460,7 @@ async fn question_images_author_serve_and_cascade() { assert_eq!(keys_before.len(), keys_after.len(), "replace adds no row"); for stale in keys_before.iter().filter(|k| !keys_after.contains(k)) { assert!( - !common::files_dir().join(stale).exists(), + !common::blob_dir().join(stale).exists(), "replaced blob lingers on disk" ); } @@ -12530,7 +12540,7 @@ async fn question_images_author_serve_and_cascade() { ); for key in &keys { assert!( - !common::files_dir().join(key).exists(), + !common::blob_dir().join(key).exists(), "blob {key} survived the exam delete" ); } @@ -12698,7 +12708,7 @@ async fn student_answer_images_serve_and_cascade() { // seq-1 answer-image row *and* its on-disk blob survive the new sitting. let pre = answer_image_blob_keys(&db).await; assert_eq!(pre.len(), 1); - assert!(common::files_dir().join(&pre[0]).exists()); + assert!(common::blob_dir().join(&pre[0]).exists()); let res = send( &app, "POST", @@ -12724,7 +12734,7 @@ async fn student_answer_images_serve_and_cascade() { "the retake kept the prior sitting's answer-image row (history)" ); assert!( - common::files_dir().join(&pre[0]).exists(), + common::blob_dir().join(&pre[0]).exists(), "the retake kept the prior sitting's answer-image blob on disk" ); @@ -12749,7 +12759,7 @@ async fn student_answer_images_serve_and_cascade() { ); for key in &keys { assert!( - !common::files_dir().join(key).exists(), + !common::blob_dir().join(key).exists(), "answer-image blob {key} survived the exam delete" ); } @@ -12963,7 +12973,7 @@ async fn question_image_edits_follow_the_choices() { assert_eq!(dropped.len(), 1, "only the removed option's blob may go"); for key in dropped { assert!( - !common::files_dir().join(key).exists(), + !common::blob_dir().join(key).exists(), "dropped option blob lingers" ); } @@ -13028,7 +13038,7 @@ async fn question_image_edits_follow_the_choices() { assert!(image_blob_keys(&db).await.is_empty()); for key in &keys { assert!( - !common::files_dir().join(key).exists(), + !common::blob_dir().join(key).exists(), "blob {key} survived the question delete" ); } @@ -15685,7 +15695,7 @@ async fn homework_files_roundtrip_and_scope() { let res = send(&app, "DELETE", &file_uri, Some(&w.ali), None).await; assert_eq!(res.status, StatusCode::NO_CONTENT); assert!( - !common::files_dir().join(&keys[0]).exists(), + !common::blob_dir().join(&keys[0]).exists(), "blob must be unlinked with its row" ); let res = send( @@ -16026,7 +16036,7 @@ async fn homework_gc_removes_rows_and_blobs() { let keys = homework_blob_keys(&db).await; assert_eq!(keys.len(), 3); for key in &keys { - assert!(common::files_dir().join(key).exists(), "blob {key} on disk"); + assert!(common::blob_dir().join(key).exists(), "blob {key} on disk"); } // Withdrawing a submission takes its file rows and blobs. @@ -16043,7 +16053,7 @@ async fn homework_gc_removes_rows_and_blobs() { assert_eq!(remaining.len(), 2); for gone in keys.iter().filter(|key| !remaining.contains(key)) { assert!( - !common::files_dir().join(gone).exists(), + !common::blob_dir().join(gone).exists(), "withdrawn blob {gone} must be unlinked" ); } @@ -16065,7 +16075,7 @@ async fn homework_gc_removes_rows_and_blobs() { assert_eq!(hw_row_count(&db, "homework").await, 1, "hw2 remains"); for key in &remaining { assert!( - !common::files_dir().join(key).exists(), + !common::blob_dir().join(key).exists(), "blob {key} must die with the homework" ); } @@ -16102,7 +16112,7 @@ async fn homework_gc_removes_rows_and_blobs() { } for key in &keys { assert!( - !common::files_dir().join(key).exists(), + !common::blob_dir().join(key).exists(), "blob {key} must die with the course" ); } @@ -16482,9 +16492,10 @@ async fn chat_app_limited( ai: Option, chatbot_limit: hezarfen_backend::rate_limit::UserRateLimiter, ) -> (axum::Router, Database) { - let db = database::init_mem().await.expect("in-memory db"); + let (tenants, db) = common::mem_deployment().await; let app = build_router(AppState { - db: db.clone(), + db: tenants.control().clone(), + tenants, files_path: common::files_dir(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), @@ -20048,7 +20059,7 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() { // unreadable source mid-flight. let src_keys = bank_image_blob_keys(&db).await; assert_eq!(src_keys.len(), 2); - tokio::fs::remove_file(common::files_dir().join(&src_keys[0])) + tokio::fs::remove_file(common::blob_dir().join(&src_keys[0])) .await .unwrap(); @@ -20105,7 +20116,7 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() { "source bank rows changed" ); assert!( - common::files_dir().join(&src_keys[1]).exists(), + common::blob_dir().join(&src_keys[1]).exists(), "surviving source blob vanished" ); } @@ -24478,7 +24489,9 @@ async fn the_statement_reports_overdue_and_its_rollup_matches_the_balance() { "POST", "/auth/login", None, - Some(json!({ "username": "ali", "password": "secret1" })), + Some( + json!({ "school": "demo", "school": "demo", "username": "ali", "password": "secret1" }), + ), ) .await .cookie @@ -27171,7 +27184,7 @@ async fn course_note_cap_refusal_and_course_delete_leave_no_orphan_blobs() { ) .await; assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); - blob_paths.push(common::files_dir().join(id_of(&r.body))); + blob_paths.push(common::blob_dir().join(id_of(&r.body))); } for p in &blob_paths { assert!(p.exists(), "blob missing after upload: {p:?}"); diff --git a/tests/pagination.rs b/tests/pagination.rs index e439651..f19e7ba 100644 --- a/tests/pagination.rs +++ b/tests/pagination.rs @@ -14,7 +14,7 @@ use serde_json::json; async fn seed_students(app: &axum::Router, n: usize) { for i in 0..n { let name = format!("user{i:02}"); - let creds = json!({ "username": name, "password": "secret1" }); + let creds = json!({ "school": "demo", "username": name, "password": "secret1" }); let res = send(app, "POST", "/auth/register", None, Some(creds)).await; assert_eq!(res.status, StatusCode::CREATED, "register {name}"); } @@ -322,7 +322,8 @@ async fn user_search_is_paged_not_capped() { let teacher = login_as(&app, &db, "teacher", "teacher").await; // 12 accounts sharing the "grp" fragment — past the old cap. for i in 0..12 { - let creds = json!({ "username": format!("grp{i:02}"), "password": "secret1" }); + let creds = + json!({ "school": "demo", "username": format!("grp{i:02}"), "password": "secret1" }); let res = send(&app, "POST", "/auth/register", None, Some(creds)).await; assert_eq!(res.status, StatusCode::CREATED); } diff --git a/tests/persistence.rs b/tests/persistence.rs index 6d6598c..fc5df3d 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -13,6 +13,7 @@ use hezarfen_backend::database::Database; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::AppState; +use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; use hezarfen_backend::{build_router, database}; use serde_json::json; @@ -20,8 +21,18 @@ use serde_json::json; /// a fresh router over it. async fn reboot(db: &Database) -> Router { database::migrate(db).await.expect("re-migration"); + // A new process: a new control database and a new connection cache, over + // the school store the old one left behind. + let tenants = Tenants::new_mem_adopting( + &Slug::try_new(DEMO_SLUG).unwrap(), + "Demo School", + db.clone(), + ) + .await + .expect("adopt the demo school"); build_router(AppState { - db: db.clone(), + db: tenants.control().clone(), + tenants, files_path: common::files_dir(), cookie_secure: false, rate_limit: RateLimitConfig::unlimited(), @@ -40,7 +51,7 @@ async fn reboot(db: &Database) -> Router { async fn settings_and_terms_survive_remigration() { let (app, db) = common::app_and_db().await; - let creds = json!({ "username": "boss", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; set_role(&db, "boss", "manager").await; let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) @@ -119,7 +130,7 @@ async fn settings_and_terms_survive_remigration() { #[tokio::test] async fn legacy_events_backfill_to_school_audience() { let (app, db) = common::app_and_db().await; - let creds = json!({ "username": "ali", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); // A normal event — then strip its audience the way an old binary's schema // would have left it: drop the column definitions so SCHEMAFULL stops @@ -196,7 +207,7 @@ async fn legacy_events_backfill_to_school_audience() { #[tokio::test] async fn legacy_users_audiences_convert_to_registrations() { let (app, db) = common::app_and_db().await; - let creds = json!({ "username": "ali", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); // A registration-audience event — then rewrite it into the shape an old // binary left behind: restore the `audience.users` column definition and @@ -212,7 +223,7 @@ async fn legacy_users_audiences_convert_to_registrations() { .await .cookie .unwrap(); - let student = json!({ "username": "veli", "password": "secret1" }); + let student = json!({ "school": "demo", "username": "veli", "password": "secret1" }); assert_eq!( send(&app, "POST", "/auth/register", None, Some(student.clone())) .await @@ -294,7 +305,7 @@ async fn legacy_users_audiences_convert_to_registrations() { #[tokio::test] async fn legacy_subjectless_questions_are_destroyed_on_boot() { let (app, db) = common::app_and_db().await; - let creds = json!({ "username": "ali", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); // A full exam — course, subject, open exam, one answered question — then // 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() { .await .cookie .unwrap(); - let student = json!({ "username": "veli", "password": "secret1" }); + let student = json!({ "school": "demo", "username": "veli", "password": "secret1" }); assert_eq!( send(&app, "POST", "/auth/register", None, Some(student.clone())) .await @@ -434,7 +445,7 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() { #[tokio::test] async fn stale_staff_enrollments_are_swept_on_boot() { let (app, db) = common::app_and_db().await; - let creds = json!({ "username": "ali", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); // A course with three enrolled students, then age two rows the way a // 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() { let mut ids = Vec::new(); for name in ["veli", "ayse", "can"] { - let student = json!({ "username": name, "password": "secret1" }); + let student = json!({ "school": "demo", "username": name, "password": "secret1" }); assert_eq!( send(&app, "POST", "/auth/register", None, Some(student.clone())) .await @@ -646,8 +657,8 @@ async fn a_course_whose_count_outran_its_roster_is_repaired_and_deletable() { #[tokio::test] async fn legacy_exams_backfill_to_published() { let (app, db) = common::app_and_db().await; - let teacher_creds = json!({ "username": "ali", "password": "secret1" }); - let student_creds = json!({ "username": "ayse", "password": "secret1" }); + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); // A normal exam — then strip `draft` the way an old binary's schema would // have left it. @@ -732,8 +743,8 @@ async fn appointments_survive_remigration() { const PROPOSED_END: i64 = START + 8_000_003; let (app, db) = common::app_and_db().await; - let teacher_creds = json!({ "username": "ali", "password": "secret1" }); - let student_creds = json!({ "username": "ayse", "password": "secret1" }); + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); for creds in [&teacher_creds, &student_creds] { assert_eq!( send(&app, "POST", "/auth/register", None, Some((*creds).clone())) @@ -879,8 +890,8 @@ async fn appointments_survive_remigration() { #[tokio::test] async fn attempt_history_survives_remigration() { let (app, db) = common::app_and_db().await; - let teacher_creds = json!({ "username": "ali", "password": "secret1" }); - let student_creds = json!({ "username": "ayse", "password": "secret1" }); + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); for creds in [&teacher_creds, &student_creds] { assert_eq!( send(&app, "POST", "/auth/register", None, Some((*creds).clone())) @@ -1164,7 +1175,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() { use hezarfen_backend::domain::user::UserId; let (app, db) = common::app_and_db().await; - let creds = json!({ "username": "ali", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); assert_eq!( send(&app, "POST", "/auth/register", None, Some(creds.clone())) .await @@ -1244,7 +1255,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() { async fn settings_slots_without_a_serving_minute_still_patch() { let (app, db) = common::app_and_db().await; - let creds = json!({ "username": "boss", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; set_role(&db, "boss", "manager").await; 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 #[tokio::test] async fn fee_plans_and_their_charges_survive_remigration() { let (app, db) = common::app_and_db().await; - let manager_creds = json!({ "username": "ali", "password": "secret1" }); - let student_creds = json!({ "username": "ayse", "password": "secret1" }); + let manager_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); for creds in [&manager_creds, &student_creds] { assert_eq!( 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() { #[tokio::test] async fn boards_and_their_strokes_survive_remigration() { let (app, db) = common::app_and_db().await; - let creds = json!({ "username": "ali", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); let cookie = common::login(&app, "ali").await; let veli = common::login(&app, "veli").await; let ali_id = me_id(&app, &cookie).await; diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index 2765461..615dc48 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -18,9 +18,12 @@ use tower::ServiceExt; /// App with the given limits, backed by a fresh in-memory database. async fn app_with(rate_limit: RateLimitConfig) -> Router { - let db = database::init_mem().await.expect("in-memory db"); + let tenants = database::init_mem_tenants() + .await + .expect("in-memory deployment"); build_router(AppState { - db, + db: tenants.control().clone(), + tenants, files_path: tempfile::tempdir().expect("files dir").keep(), cookie_secure: false, rate_limit, @@ -68,7 +71,7 @@ async fn send_as( } fn bad_login() -> Option { - Some(json!({ "username": "ghost", "password": "wrong-pass" })) + Some(json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" })) } fn auth_only(per_minute: u32) -> RateLimitConfig { @@ -103,7 +106,7 @@ async fn login_attempts_hit_the_auth_limit() { #[tokio::test] async fn register_and_login_share_the_auth_bucket() { let app = app_with(auth_only(2)).await; - let creds = json!({ "username": "ada", "password": "secret1" }); + let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" }); let (status, _, _) = send_as( &app, @@ -530,9 +533,12 @@ async fn a_down_database_leaves_each_process_on_its_local_budget() { /// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`. async fn spawn_server(rate_limit: RateLimitConfig) -> String { - let db = database::init_mem().await.expect("in-memory db"); + let tenants = database::init_mem_tenants() + .await + .expect("in-memory deployment"); let app = build_router(AppState { - db, + db: tenants.control().clone(), + tenants, files_path: tempfile::tempdir().expect("files dir").keep(), cookie_secure: false, rate_limit, @@ -571,7 +577,7 @@ async fn real_connections_are_keyed_by_peer_address() { let res = client .post(format!("{base}/auth/login")) .header("x-forwarded-for", spoof) - .json(&json!({ "username": "ghost", "password": "wrong-pass" })) + .json(&json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" })) .send() .await .unwrap(); @@ -581,7 +587,7 @@ async fn real_connections_are_keyed_by_peer_address() { let res = client .post(format!("{base}/auth/login")) .header("x-forwarded-for", "3.3.3.3") - .json(&json!({ "username": "ghost", "password": "wrong-pass" })) + .json(&json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" })) .send() .await .unwrap(); diff --git a/tests/regress_bank_images.rs b/tests/regress_bank_images.rs index 1608dee..8168392 100644 --- a/tests/regress_bank_images.rs +++ b/tests/regress_bank_images.rs @@ -27,6 +27,7 @@ mod common; use axum::Router; use axum::http::StatusCode; use common::{create_course, create_subject, id_of, login_as, send}; +use hezarfen_backend::build_router; use hezarfen_backend::database::Database; use hezarfen_backend::domain::bank_question::BankQuestionId; use hezarfen_backend::domain::bank_question_image::BankQuestionImage; @@ -34,7 +35,6 @@ use hezarfen_backend::domain::note_file::FileContentType; use hezarfen_backend::error::AppError; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::AppState; -use hezarfen_backend::{build_router, database}; use serde_json::json; use tempfile::TempDir; @@ -43,10 +43,11 @@ const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary"; /// A router over a fresh in-memory database, with a blob directory nothing else /// writes to — so `blobs()` counts this test's files and no one else's. async fn mem_app() -> (Router, Database, TempDir) { - let db = database::init_mem().await.expect("in-memory db"); + let (tenants, db) = common::mem_deployment().await; let files = tempfile::tempdir().expect("files tempdir"); let app = build_router(AppState { - db: db.clone(), + db: tenants.control().clone(), + tenants, files_path: files.path().to_path_buf(), cookie_secure: false, rate_limit: RateLimitConfig::unlimited(), @@ -61,7 +62,12 @@ async fn mem_app() -> (Router, Database, TempDir) { /// Every blob file currently on disk, by name. fn blobs(files: &TempDir) -> Vec { - let mut names: Vec = std::fs::read_dir(files.path()) + // Blobs live under the school's own subdirectory of `FILES_PATH`. + let dir = files.path().join(hezarfen_backend::tenant::DEMO_SLUG); + if !dir.exists() { + return Vec::new(); + } + let mut names: Vec = std::fs::read_dir(&dir) .expect("read the blob dir") .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) .collect(); diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs index 0f029ff..a3d17bf 100644 --- a/tests/regress_profile.rs +++ b/tests/regress_profile.rs @@ -47,7 +47,7 @@ async fn upload_avatar( /// by every app in this binary, so a payload no other test writes is the only /// concurrency-safe way to count one test's own blobs. fn blobs_holding(bytes: &[u8]) -> usize { - std::fs::read_dir(common::files_dir()) + std::fs::read_dir(common::blob_dir()) .expect("files dir") .filter_map(|entry| std::fs::read(entry.expect("dir entry").path()).ok()) .filter(|found| found == bytes) diff --git a/tests/regress_roles.rs b/tests/regress_roles.rs index 8e00211..ab02bb9 100644 --- a/tests/regress_roles.rs +++ b/tests/regress_roles.rs @@ -196,7 +196,8 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() { "/auth/login", None, Some(json!({ - "username": "ali", "password": "secret1" + "school": "demo", + "school": "demo", "username": "ali", "password": "secret1" })), ) .await diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 6b07f69..0075c9a 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -24,9 +24,12 @@ use tower::ServiceExt; /// The emitted OpenAPI document, as the server serves it. async fn spec() -> Value { - let db = database::init_mem().await.expect("in-memory db"); + let tenants = database::init_mem_tenants() + .await + .expect("in-memory deployment"); let app = build_router(AppState { - db, + db: tenants.control().clone(), + tenants, files_path: tempfile::tempdir().expect("files dir").keep(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), @@ -59,6 +62,8 @@ async fn spec() -> Value { fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { vec![ // --- auth / users / notes / messages --- + ("Credentials", "school", "minLength", MIN_SLUG_LEN as i64), + ("Credentials", "school", "maxLength", MAX_SLUG_LEN as i64), ( "Credentials", "username",