One database per school behind a control registry
Browse files at this commitb7dfc0cbbafa37c46c15860077b0ce2a7b0e683bParent: b8069dc- feat
- one database per school behind a control registry
- login names the school
59 changed files +1850 -235
- .env.example +13 -8
- README.md +18 -6
- src/ai/server.rs +54 -13
- src/config.rs +13 -8
- src/constant.rs +6 -0
- src/database.rs +44 -19
- src/domain/builder.rs +253 -0
- src/domain/mod.rs +1 -0
- src/lib.rs +2 -1
- src/main.rs +9 -5
- src/migration_sql.rs +42 -0
- src/state.rs +8 -0
- src/tenant.rs +652 -0
- src/web/appointments.rs +2 -1
- src/web/attendance.rs +2 -1
- src/web/auth.rs +47 -11
- src/web/bank_questions.rs +2 -1
- src/web/board_ws.rs +2 -1
- src/web/boards.rs +2 -1
- src/web/chatbot.rs +2 -1
- src/web/classes.rs +2 -1
- src/web/course_notes.rs +3 -1
- src/web/courses.rs +3 -1
- src/web/events.rs +2 -1
- src/web/exam_ws.rs +2 -1
- src/web/exams/mod.rs +2 -1
- src/web/extractor.rs +56 -8
- src/web/homework.rs +3 -1
- src/web/image.rs +1 -0
- src/web/limits.rs +11 -0
- src/web/marks.rs +2 -1
- src/web/meals.rs +2 -1
- src/web/messages.rs +2 -1
- src/web/mod.rs +20 -1
- src/web/notes.rs +3 -1
- src/web/payments.rs +2 -1
- src/web/pomodoro.rs +2 -1
- src/web/questions.rs +2 -1
- src/web/sessions.rs +2 -1
- src/web/settings.rs +1 -1
- src/web/subjects.rs +2 -1
- src/web/tenant_state.rs +305 -0
- src/web/terms.rs +2 -1
- src/web/users.rs +2 -1
- src/web/work.rs +2 -1
- tests/ai_bridge.rs +6 -8
- tests/ai_protocol.rs +8 -3
- tests/auth_enumeration.rs +5 -5
- tests/common/mod.rs +62 -5
- tests/e2e.rs +13 -5
- tests/etag.rs +1 -1
- tests/integration.rs +77 -64
- tests/pagination.rs +3 -2
- tests/persistence.rs +31 -20
- tests/rate_limit.rs +14 -8
- tests/regress_bank_images.rs +10 -4
- tests/regress_profile.rs +1 -1
- tests/regress_roles.rs +2 -1
- tests/spec_bounds.rs +7 -2
.env.examplemodified+13 -8
| @@ -8,9 +8,12 @@ DB_URL=ws://127.0.0.1:8000 | ||
| 8 | 8 | DB_USER=root |
| 9 | 9 | DB_PASS=root |
| 10 | 10 | DB_NAMESPACE=hezarfen |
| 11 | -DB_DATABASE=hezarfen | |
| 11 | +# The CONTROL database: the school registry and the builder accounts. Each | |
| 12 | +# school gets a database of its own inside DB_NAMESPACE, named by its slug. | |
| 13 | +DB_DATABASE=control | |
| 12 | 14 | |
| 13 | -# Directory for uploaded note-file blobs (created at startup). | |
| 15 | +# Directory for uploaded note-file blobs (created at startup). Each school | |
| 16 | +# writes into a subdirectory of it named by its slug. | |
| 14 | 17 | FILES_PATH=./data/files |
| 15 | 18 | |
| 16 | 19 | # Optional log filter. |
| @@ -43,12 +46,14 @@ RUST_LOG=info,hezarfen_backend=debug | ||
| 43 | 46 | # trivially bypassed. When off (default), the peer address is used. |
| 44 | 47 | # TRUST_PROXY=true |
| 45 | 48 | |
| 46 | -# Seed an admin account at startup: if this username doesn't exist yet it is | |
| 47 | -# created with this password and the `admin` role. Both must be set together. | |
| 48 | -# If the username exists as a non-admin, nothing is changed (a warning is | |
| 49 | -# logged) — the seed never promotes or rewrites an existing account. | |
| 50 | -# ADMIN_USERNAME=admin | |
| 51 | -# ADMIN_PASSWORD=admin123 | |
| 49 | +# Seed a BUILDER account at startup: the deployment operator who creates, | |
| 50 | +# suspends and drops schools. Not a user of any school and holds no role in | |
| 51 | +# one; its cookie is `builder.<token>` where a school user's is | |
| 52 | +# `<slug>.<token>`. Both must be set together. An existing account with this | |
| 53 | +# username is left exactly as it is — the seed never rewrites a credential, so | |
| 54 | +# changing the password here does not re-key a live builder. | |
| 55 | +# BUILDER_USERNAME=builder | |
| 56 | +# BUILDER_PASSWORD=builder123 | |
| 52 | 57 | |
| 53 | 58 | # --- AI bridge (QUIC) ------------------------------------------------------- |
| 54 | 59 | # The AI features run as separate services that dial IN to this backend over |
README.mdmodified+18 -6
| @@ -430,7 +430,7 @@ drift from it**, which is enforced rather than asked for: | ||
| 430 | 430 | and fails unless each one is either referenced by `src/web/limits.rs` or |
| 431 | 431 | listed as a deliberate exclusion *with a reason*. A new constant breaks the |
| 432 | 432 | suite until someone decides, consciously, whether clients need it. |
| 433 | -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 174 published | |
| 433 | +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 176 published | |
| 434 | 434 | bounds back out of the emitted JSON, and asserts each equals its constant. |
| 435 | 435 | This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal |
| 436 | 436 | 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. | ||
| 844 | 844 | | 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. | |
| 845 | 845 | | GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, and a per-course breakdown with attendance rates. | |
| 846 | 846 | | GET | `/attendance/{user}` | teacher | Any user's attendance report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every course; a teacher sees the event tallies plus only the roll-call blocks of the target's courses they manage. | |
| 847 | -| POST | `/auth/login` | no | Log in with username + password. Sets a `session` cookie on success. | | |
| 847 | +| POST | `/auth/login` | no | Log in with school + username + password. Sets a `session` cookie (`<school>.<token>`) on success. | | |
| 848 | 848 | | POST | `/auth/logout` | no | Log out: revoke the current session (if any) and clear the cookie. Idempotent — no session required; answers `204` either way. | |
| 849 | 849 | | GET | `/auth/me` | student | Return the currently authenticated user. | |
| 850 | -| POST | `/auth/register` | no | Register a new user account: `{username, password}` in, `{username, role}` back (no `id`; new accounts are `student`). Always `201`, even if the name was already taken — see "Auth model". | | |
| 850 | +| POST | `/auth/register` | no | Register a new user account: `{school, username, password}` in, `{username, role}` back (no `id`; new accounts are `student`). Always `201`, even if the name was already taken — see "Auth model". | | |
| 851 | 851 | | 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). | |
| 852 | 852 | | 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. | |
| 853 | 853 | | 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/ | ||
| 4376 | 4376 | constant.rs validation limits |
| 4377 | 4377 | validate.rs field validators (used by every newtype's try_new) |
| 4378 | 4378 | error.rs ValidationError + AppError -> HTTP responses |
| 4379 | - database.rs SurrealDB server connect (ws) + SCHEMAFULL migration | |
| 4379 | + database.rs SurrealDB server connect (ws) + SCHEMAFULL migration; init() | |
| 4380 | + brings up the control database, migrate() a school's | |
| 4381 | + tenant.rs Slug · SchoolStatus · School · Tenants: one database per | |
| 4382 | + school inside one namespace, plus the control database that | |
| 4383 | + registers them (DEMO_SLUG is the in-memory test school) | |
| 4380 | 4384 | migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR, |
| 4381 | - MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them | |
| 4385 | + MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them, | |
| 4386 | + and CONTROL_MIGRATION_BATCHES for the control database | |
| 4382 | 4387 | rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier |
| 4383 | - state.rs AppState { db, files_path, cookie_secure, rate_limit, | |
| 4388 | + state.rs AppState { db, tenants, files_path, cookie_secure, rate_limit, | |
| 4384 | 4389 | chatbot_limit, exam_presence, board_hub, db_up, ai } |
| 4385 | 4390 | ai/ QUIC bridge to the out-of-process AI services |
| 4386 | 4391 | (see "AI bridge (QUIC)"; the HTTP half is web/ai.rs) |
| @@ -4409,6 +4414,8 @@ src/ | ||
| 4409 | 4414 | text_fold.rs case- and diacritic-insensitive folding for search, shared by |
| 4410 | 4415 | the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…) |
| 4411 | 4416 | session.rs SessionId · SessionToken · Session (7-day expiry) |
| 4417 | + builder.rs BuilderId · Builder · BuilderSession: the deployment operator | |
| 4418 | + who creates and suspends schools, in the control database | |
| 4412 | 4419 | timestamp.rs Timestamp (unix-millisecond instant) |
| 4413 | 4420 | note.rs NoteId · NoteTitle · NoteContent · Note |
| 4414 | 4421 | note_file.rs NoteFileId · FileName · FileContentType · NoteFile (metadata row; |
| @@ -4524,7 +4531,12 @@ src/ | ||
| 4524 | 4531 | row per homework+user — its existence freezes the submission) |
| 4525 | 4532 | web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers + |
| 4526 | 4533 | auth extractors |
| 4534 | + tenant_state.rs State<AppState>: the shadow of axum's State that resolves the | |
| 4535 | + caller's school from the `<slug>.<token>` cookie, so every | |
| 4536 | + handler that imports it is school-scoped by construction | |
| 4537 | + (TenantExt · SchoolSlug · split_cookie) | |
| 4527 | 4538 | extractor.rs CurrentUser · RequireTeacher · RequireManager · RequireAdmin |
| 4539 | + · RequireBuilder (the control-database principal) | |
| 4528 | 4540 | dto.rs shared UserResponse · CourseResponse · ExamResponse · SessionResponse schemas |
| 4529 | 4541 | exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish) |
| 4530 | 4542 | board_ws.rs the collaborative board room WebSocket (join replay, strokes |
src/ai/server.rsmodified+54 -13
| @@ -29,9 +29,11 @@ use crate::domain::course_note::CourseNote; | ||
| 29 | 29 | use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; |
| 30 | 30 | use crate::domain::user::{User, UserId}; |
| 31 | 31 | use crate::state::DbHealth; |
| 32 | +use crate::tenant::{Slug, Tenants}; | |
| 32 | 33 | use crate::web::blob_path; |
| 33 | 34 | use crate::web::courses::can_view_course; |
| 34 | 35 | use crate::web::extractor::AiPrincipal; |
| 36 | +use crate::web::tenant_state::{TenantExt, school_files_path}; | |
| 35 | 37 | |
| 36 | 38 | /// What the bridge needs to come up. |
| 37 | 39 | #[derive(Clone, Debug)] |
| @@ -48,17 +50,43 @@ pub struct BridgeConfig { | ||
| 48 | 50 | } |
| 49 | 51 | |
| 50 | 52 | /// What an api read needs to be answered: the router to dispatch into, the |
| 51 | -/// database the acting principal is loaded from, and the liveness flag that | |
| 53 | +/// school the acting principal is loaded from, and the liveness flag that | |
| 52 | 54 | /// stands in for the HTTP db guard this path bypasses. |
| 53 | 55 | struct ApiHandle { |
| 54 | 56 | router: axum::Router, |
| 55 | - db: Database, | |
| 57 | + tenants: Tenants, | |
| 58 | + /// The one school this bridge serves. | |
| 59 | + /// | |
| 60 | + /// corner-cut: `hab/1` frames carry no school, so the reverse api-read path | |
| 61 | + /// is pinned to [`crate::tenant::DEMO_SLUG`] — a deployment whose schools | |
| 62 | + /// are named anything else answers `unavailable` to every service read. | |
| 63 | + /// The upgrade is `hab/2`: put the school on `Hello`/`ApiRequest` and | |
| 64 | + /// resolve it per request. Nothing else about the bridge is single-school — | |
| 65 | + /// the outbound chatbot dispatch never touches a database. | |
| 66 | + slug: Slug, | |
| 56 | 67 | db_up: DbHealth, |
| 57 | - /// Where course-note blobs live, for the byte stream — the same directory | |
| 58 | - /// `GET /course-notes/{id}/files/{file_id}` serves from. | |
| 68 | + /// Where uploaded blobs live — the deployment root; the school's own | |
| 69 | + /// directory is [`school_files_path`] of it. | |
| 59 | 70 | files_path: std::path::PathBuf, |
| 60 | 71 | } |
| 61 | 72 | |
| 73 | +impl ApiHandle { | |
| 74 | + /// The school database this bridge reads, or the refusal a service gets. | |
| 75 | + async fn db(&self) -> Result<Database, (&'static str, String)> { | |
| 76 | + self.tenants.get(&self.slug).await.map_err(|err| { | |
| 77 | + ( | |
| 78 | + "unavailable", | |
| 79 | + format!("the `{}` school is not reachable: {err}", self.slug), | |
| 80 | + ) | |
| 81 | + }) | |
| 82 | + } | |
| 83 | + | |
| 84 | + /// That school's blob directory. | |
| 85 | + fn files_dir(&self) -> std::path::PathBuf { | |
| 86 | + school_files_path(&self.files_path, &self.slug) | |
| 87 | + } | |
| 88 | +} | |
| 89 | + | |
| 62 | 90 | struct Inner { |
| 63 | 91 | registry: AiRegistry, |
| 64 | 92 | /// Armed once per process by [`crate::build_router`] (see |
| @@ -240,7 +268,7 @@ impl AiBridge { | ||
| 240 | 268 | pub(crate) fn arm_api( |
| 241 | 269 | &self, |
| 242 | 270 | router: axum::Router, |
| 243 | - db: Database, | |
| 271 | + tenants: Tenants, | |
| 244 | 272 | db_up: DbHealth, |
| 245 | 273 | files_path: std::path::PathBuf, |
| 246 | 274 | ) { |
| @@ -249,7 +277,8 @@ impl AiBridge { | ||
| 249 | 277 | .api |
| 250 | 278 | .set(ApiHandle { |
| 251 | 279 | router, |
| 252 | - db, | |
| 280 | + tenants, | |
| 281 | + slug: Slug::try_new(crate::tenant::DEMO_SLUG).expect("the demo slug is a slug"), | |
| 253 | 282 | db_up, |
| 254 | 283 | files_path, |
| 255 | 284 | }) |
| @@ -468,6 +497,7 @@ async fn open_blob( | ||
| 468 | 497 | "the database socket is down — retry".to_string(), |
| 469 | 498 | )); |
| 470 | 499 | } |
| 500 | + let db = api.db().await?; | |
| 471 | 501 | let user = principal(api, request.on_behalf_of.as_deref()).await?; |
| 472 | 502 | |
| 473 | 503 | let missing = || { |
| @@ -477,19 +507,19 @@ async fn open_blob( | ||
| 477 | 507 | ) |
| 478 | 508 | }; |
| 479 | 509 | let unavailable = |e: crate::error::AppError| ("unavailable", e.to_string()); |
| 480 | - let file = CourseNoteFile::read(&CourseNoteFileId::from_key(&request.file), &api.db) | |
| 510 | + let file = CourseNoteFile::read(&CourseNoteFileId::from_key(&request.file), &db) | |
| 481 | 511 | .await |
| 482 | 512 | .map_err(unavailable)? |
| 483 | 513 | .ok_or_else(missing)?; |
| 484 | - let note = CourseNote::read(file.get_course_note(), &api.db) | |
| 514 | + let note = CourseNote::read(file.get_course_note(), &db) | |
| 485 | 515 | .await |
| 486 | 516 | .map_err(unavailable)? |
| 487 | 517 | .ok_or_else(missing)?; |
| 488 | - let course = Course::read(note.get_course(), &api.db) | |
| 518 | + let course = Course::read(note.get_course(), &db) | |
| 489 | 519 | .await |
| 490 | 520 | .map_err(unavailable)? |
| 491 | 521 | .ok_or_else(missing)?; |
| 492 | - if !can_view_course(&course, &user, &api.db) | |
| 522 | + if !can_view_course(&course, &user, &db) | |
| 493 | 523 | .await |
| 494 | 524 | .map_err(unavailable)? |
| 495 | 525 | { |
| @@ -504,7 +534,7 @@ async fn open_blob( | ||
| 504 | 534 | |
| 505 | 535 | // The row exists but its blob does not: server-side damage (a lost volume |
| 506 | 536 | // path), exactly as `download_file` reads it — not the service's `404`. |
| 507 | - let path = blob_path(&api.files_path, file.get_id().key()); | |
| 537 | + let path = blob_path(&api.files_dir(), file.get_id().key()); | |
| 508 | 538 | let handle = tokio::fs::File::open(&path).await.map_err(|e| { |
| 509 | 539 | ( |
| 510 | 540 | "unavailable", |
| @@ -548,7 +578,7 @@ async fn principal( | ||
| 548 | 578 | // Both the bare key (`abc`, as a REST path spells it) and the record form |
| 549 | 579 | // (`user:abc`) are accepted. |
| 550 | 580 | let key = who.strip_prefix("user:").unwrap_or(who); |
| 551 | - User::read(&UserId::from_key(key), &api.db) | |
| 581 | + User::read(&UserId::from_key(key), &api.db().await?) | |
| 552 | 582 | .await |
| 553 | 583 | .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))? |
| 554 | 584 | .ok_or_else(|| ("unknown_user", format!("no user `{who}`"))) |
| @@ -627,6 +657,7 @@ async fn dispatch_api( | ||
| 627 | 657 | |
| 628 | 658 | // The role itself is re-read again by the extractor on the dispatched |
| 629 | 659 | // request; see [`principal`] for why it is never taken from the frame. |
| 660 | + let db = api.db().await?; | |
| 630 | 661 | let user = principal(api, on_behalf_of.as_deref()).await?; |
| 631 | 662 | |
| 632 | 663 | let target = match query.as_deref() { |
| @@ -646,6 +677,12 @@ async fn dispatch_api( | ||
| 646 | 677 | // An extension cannot be set from outside the process, which is what makes |
| 647 | 678 | // this principal unforgeable over HTTP (see [`AiPrincipal`]). |
| 648 | 679 | dispatched.extensions_mut().insert(AiPrincipal(user)); |
| 680 | + // The dispatched request carries no cookie, so the school is handed over | |
| 681 | + // in the extension the shadow `State` reads first. | |
| 682 | + dispatched.extensions_mut().insert(TenantExt { | |
| 683 | + slug: api.slug.clone(), | |
| 684 | + db, | |
| 685 | + }); | |
| 649 | 686 | |
| 650 | 687 | let response = tokio::time::timeout( |
| 651 | 688 | Duration::from_secs(REQUEST_TIMEOUT_SECS), |
| @@ -859,6 +896,7 @@ mod tests { | ||
| 859 | 896 | refuse_before_dispatch, |
| 860 | 897 | }; |
| 861 | 898 | use crate::ai::protocol::read_frame; |
| 899 | + use crate::tenant::Slug; | |
| 862 | 900 | |
| 863 | 901 | /// An armed handle serving `router`. The database is never touched by these |
| 864 | 902 | /// reads (nobody is named, so the principal is synthetic), but the handle |
| @@ -866,7 +904,10 @@ mod tests { | ||
| 866 | 904 | async fn armed(router: axum::Router) -> ApiHandle { |
| 867 | 905 | ApiHandle { |
| 868 | 906 | router, |
| 869 | - db: crate::database::init_mem().await.expect("in-memory db"), | |
| 907 | + tenants: crate::database::init_mem_tenants() | |
| 908 | + .await | |
| 909 | + .expect("in-memory deployment"), | |
| 910 | + slug: Slug::try_new(crate::tenant::DEMO_SLUG).unwrap(), | |
| 870 | 911 | db_up: Default::default(), |
| 871 | 912 | files_path: std::env::temp_dir(), |
| 872 | 913 | } |
src/config.rsmodified+13 -8
| @@ -17,6 +17,9 @@ pub struct Config { | ||
| 17 | 17 | pub db_user: String, |
| 18 | 18 | pub db_pass: String, |
| 19 | 19 | pub db_ns: String, |
| 20 | + /// The **control** database inside `db_ns` (`DB_DATABASE`): the school | |
| 21 | + /// registry and the builder accounts. Every school gets a database of its | |
| 22 | + /// own, named by its slug. | |
| 20 | 23 | pub db_name: String, |
| 21 | 24 | /// Directory for uploaded note-file blobs (`FILES_PATH`). |
| 22 | 25 | pub files_path: String, |
| @@ -31,11 +34,13 @@ pub struct Config { | ||
| 31 | 34 | /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is |
| 32 | 35 | /// keyed by user and is enforced inside the handler. |
| 33 | 36 | pub chatbot_per_minute: u32, |
| 34 | - /// Startup admin seed (`ADMIN_USERNAME` + `ADMIN_PASSWORD`). When both are | |
| 35 | - /// set, an admin account with these credentials is created at boot if the | |
| 36 | - /// username doesn't exist yet. Blank values count as unset. | |
| 37 | - pub admin_username: Option<String>, | |
| 38 | - pub admin_password: Option<String>, | |
| 37 | + /// Startup builder seed (`BUILDER_USERNAME` + `BUILDER_PASSWORD`). When | |
| 38 | + /// both are set, a builder account with these credentials is created in the | |
| 39 | + /// control database at boot if the username doesn't exist yet. Blank values | |
| 40 | + /// count as unset. A builder manages schools; it is not a user of any of | |
| 41 | + /// them. | |
| 42 | + pub builder_username: Option<String>, | |
| 43 | + pub builder_password: Option<String>, | |
| 39 | 44 | /// AI bridge listen address (`AI_QUIC_ADDR`, e.g. `0.0.0.0:8090`). Unset |
| 40 | 45 | /// leaves the bridge off entirely: the API runs exactly as before and any |
| 41 | 46 | /// AI-backed feature reports that no service is connected. |
| @@ -62,7 +67,7 @@ impl Config { | ||
| 62 | 67 | db_user: env::var("DB_USER").unwrap_or_else(|_| "root".into()), |
| 63 | 68 | db_pass: env::var("DB_PASS").unwrap_or_else(|_| "root".into()), |
| 64 | 69 | db_ns: env::var("DB_NAMESPACE").unwrap_or_else(|_| "hezarfen".into()), |
| 65 | - db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "hezarfen".into()), | |
| 70 | + db_name: env::var("DB_DATABASE").unwrap_or_else(|_| "control".into()), | |
| 66 | 71 | files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()), |
| 67 | 72 | cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()), |
| 68 | 73 | rate_limit: RateLimitConfig { |
| @@ -80,8 +85,8 @@ impl Config { | ||
| 80 | 85 | env::var("RATE_LIMIT_CHATBOT_PER_MINUTE").ok(), |
| 81 | 86 | DEFAULT_CHATBOT_RATE_LIMIT, |
| 82 | 87 | ), |
| 83 | - admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()), | |
| 84 | - admin_password: parse_optional(env::var("ADMIN_PASSWORD").ok()), | |
| 88 | + builder_username: parse_optional(env::var("BUILDER_USERNAME").ok()), | |
| 89 | + builder_password: parse_optional(env::var("BUILDER_PASSWORD").ok()), | |
| 85 | 90 | ai_quic_addr: parse_optional(env::var("AI_QUIC_ADDR").ok()), |
| 86 | 91 | ai_shared_token: parse_optional(env::var("AI_SHARED_TOKEN").ok()), |
| 87 | 92 | ai_tls_cert: parse_optional(env::var("AI_TLS_CERT").ok()), |
src/constant.rsmodified+6 -0
| @@ -5,6 +5,12 @@ use crate::domain::message::Folder; | ||
| 5 | 5 | use crate::domain::preferences::{Language, Theme}; |
| 6 | 6 | use crate::domain::role::Role; |
| 7 | 7 | |
| 8 | +/// A school slug's length bounds — the name in front of the dot in the session | |
| 9 | +/// cookie, which is also the school's database name and its blob directory | |
| 10 | +/// (see [`crate::tenant::Slug`]). | |
| 11 | +pub const MIN_SLUG_LEN: usize = 2; | |
| 12 | +pub const MAX_SLUG_LEN: usize = 32; | |
| 13 | + | |
| 8 | 14 | pub const MIN_USERNAME_LEN: usize = 3; |
| 9 | 15 | pub const MAX_USERNAME_LEN: usize = 32; |
| 10 | 16 |
src/database.rsmodified+44 -19
| @@ -6,10 +6,12 @@ use surrealdb::opt::auth::Root; | ||
| 6 | 6 | |
| 7 | 7 | use crate::config::Config; |
| 8 | 8 | use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; |
| 9 | +use crate::domain::builder::Builder; | |
| 9 | 10 | use crate::domain::timestamp::Timestamp; |
| 10 | -use crate::domain::user::{Password, User, Username}; | |
| 11 | +use crate::domain::user::{Password, Username}; | |
| 11 | 12 | use crate::error::AppError; |
| 12 | -use crate::migration_sql::{BACKFILL, MIGRATION_BATCHES}; | |
| 13 | +use crate::migration_sql::{BACKFILL, CONTROL_MIGRATION_BATCHES, MIGRATION_BATCHES}; | |
| 14 | +use crate::tenant::Tenants; | |
| 13 | 15 | |
| 14 | 16 | /// The shared database handle. |
| 15 | 17 | /// |
| @@ -27,14 +29,14 @@ use crate::migration_sql::{BACKFILL, MIGRATION_BATCHES}; | ||
| 27 | 29 | /// Cloning the `Arc` shares the single session established at boot instead. |
| 28 | 30 | pub type Database = std::sync::Arc<Surreal<Any>>; |
| 29 | 31 | |
| 30 | -/// Connect to the SurrealDB server, sign in as root, apply the schema and seed | |
| 31 | -/// the admin. One process, one database, stop-the-world deploys — so all of it | |
| 32 | -/// runs unconditionally on every boot. | |
| 33 | -pub async fn init(cfg: &Config) -> Result<Database, AppError> { | |
| 32 | +/// Connect to the **control** database, sign in as root, apply the control | |
| 33 | +/// schema and seed the builder account. School databases are brought up | |
| 34 | +/// separately, one per school, by [`crate::tenant::Tenants`]. | |
| 35 | +pub async fn init(cfg: &Config) -> Result<Tenants, AppError> { | |
| 34 | 36 | // Validated before the connection, not after: half a credential pair is a |
| 35 | 37 | // deployment mistake, and reporting it only after a successful dial buries |
| 36 | 38 | // it under an outage that isn't one. |
| 37 | - let admin = admin_credentials(cfg)?; | |
| 39 | + let builder = builder_credentials(cfg)?; | |
| 38 | 40 | let db = connect_with_retry(cfg).await; |
| 39 | 41 | db.signin(Root { |
| 40 | 42 | username: cfg.db_user.clone(), |
| @@ -45,27 +47,28 @@ pub async fn init(cfg: &Config) -> Result<Database, AppError> { | ||
| 45 | 47 | .use_db(cfg.db_name.clone()) |
| 46 | 48 | .await?; |
| 47 | 49 | let db = std::sync::Arc::new(db); |
| 48 | - migrate(&db).await?; | |
| 49 | - if let Some((username, password)) = admin { | |
| 50 | - User::ensure_admin(username, password, &db).await?; | |
| 50 | + migrate_control(&db).await?; | |
| 51 | + if let Some((username, password)) = builder { | |
| 52 | + Builder::ensure(username, password, &db).await?; | |
| 51 | 53 | } |
| 52 | - Ok(db) | |
| 54 | + Ok(Tenants::new_remote(db, cfg)) | |
| 53 | 55 | } |
| 54 | 56 | |
| 55 | -/// The `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap pair, if configured. | |
| 57 | +/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured. | |
| 56 | 58 | /// Both-or-neither: half a pair aborts startup rather than silently running |
| 57 | -/// without the seed. | |
| 58 | -fn admin_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> { | |
| 59 | - match (&cfg.admin_username, &cfg.admin_password) { | |
| 59 | +/// without the seed — and without a builder, a fresh deployment has nobody who | |
| 60 | +/// can create the first school. | |
| 61 | +fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> { | |
| 62 | + match (&cfg.builder_username, &cfg.builder_password) { | |
| 60 | 63 | (Some(username), Some(password)) => Ok(Some(( |
| 61 | 64 | Username::try_new(username) |
| 62 | - .map_err(|err| AppError::Internal(format!("invalid ADMIN_USERNAME: {err}")))?, | |
| 65 | + .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?, | |
| 63 | 66 | Password::try_new(password) |
| 64 | - .map_err(|err| AppError::Internal(format!("invalid ADMIN_PASSWORD: {err}")))?, | |
| 67 | + .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?, | |
| 65 | 68 | ))), |
| 66 | 69 | (None, None) => Ok(None), |
| 67 | 70 | _ => Err(AppError::Internal( |
| 68 | - "ADMIN_USERNAME and ADMIN_PASSWORD must be set together".into(), | |
| 71 | + "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(), | |
| 69 | 72 | )), |
| 70 | 73 | } |
| 71 | 74 | } |
| @@ -254,7 +257,9 @@ async fn connect_with_retry(cfg: &Config) -> Surreal<Any> { | ||
| 254 | 257 | } |
| 255 | 258 | } |
| 256 | 259 | |
| 257 | -/// A fresh in-memory database with the schema applied. For tests. | |
| 260 | +/// A fresh in-memory **school** database with the school schema applied. For | |
| 261 | +/// the unit tests whose subject is one school's own rows; a test that needs the | |
| 262 | +/// whole app (control database included) wants [`init_mem_tenants`]. | |
| 258 | 263 | pub async fn init_mem() -> Result<Database, AppError> { |
| 259 | 264 | let db = surrealdb::engine::any::connect("memory").await?; |
| 260 | 265 | db.use_ns("hezarfen").use_db("hezarfen").await?; |
| @@ -262,6 +267,16 @@ pub async fn init_mem() -> Result<Database, AppError> { | ||
| 262 | 267 | Ok(std::sync::Arc::new(db)) |
| 263 | 268 | } |
| 264 | 269 | |
| 270 | +/// A fresh in-memory deployment: an empty control database plus one school, | |
| 271 | +/// [`crate::tenant::DEMO_SLUG`]. The bootstrap every router-level test uses. | |
| 272 | +pub async fn init_mem_tenants() -> Result<Tenants, AppError> { | |
| 273 | + let tenants = Tenants::new_mem().await?; | |
| 274 | + let demo = crate::tenant::Slug::try_new(crate::tenant::DEMO_SLUG) | |
| 275 | + .map_err(|err| AppError::Internal(format!("the demo slug is a slug: {err}")))?; | |
| 276 | + tenants.create(&demo, "Demo School").await?; | |
| 277 | + Ok(tenants) | |
| 278 | +} | |
| 279 | + | |
| 265 | 280 | /// A handle on a **real** SurrealDB server, in a scratch namespace of its own |
| 266 | 281 | /// that is dropped and re-made on every call. For the tests whose subject is |
| 267 | 282 | /// the store's own conflict detection, which [`init_mem`]'s embedded engine |
| @@ -326,6 +341,16 @@ pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { | ||
| 326 | 341 | Ok(()) |
| 327 | 342 | } |
| 328 | 343 | |
| 344 | +/// Apply the **control** schema (schools, builders, the shared rate-limit | |
| 345 | +/// window). Idempotent, like [`migrate`], and takes no bound parameters — | |
| 346 | +/// nothing in the control batch is data-driven. | |
| 347 | +pub async fn migrate_control(db: &Surreal<Any>) -> Result<(), AppError> { | |
| 348 | + for sql in CONTROL_MIGRATION_BATCHES { | |
| 349 | + db.query(sql).await?.check()?; | |
| 350 | + } | |
| 351 | + Ok(()) | |
| 352 | +} | |
| 353 | + | |
| 329 | 354 | /// Parameters the batches are executed with. Bound, not baked into the SQL |
| 330 | 355 | /// string: a `const` cannot be interpolated into another `const`, and a |
| 331 | 356 | /// hand-copied 300000 would drift silently. The one-time blocks' fingerprints |
src/domain/builder.rsadded+253 -0
| @@ -0,0 +1,253 @@ | ||
| 1 | +//! The deployment operator's account, in the control database. | |
| 2 | +//! | |
| 3 | +//! A builder creates, suspends and drops schools; it is **not** a user of any | |
| 4 | +//! school and holds no role there. The two principals are kept apart by | |
| 5 | +//! construction: a builder row lives in a different database and its cookie | |
| 6 | +//! carries a different prefix (`builder.<token>` against `<slug>.<token>`), so | |
| 7 | +//! neither extractor can be fed the other's cookie. | |
| 8 | +//! | |
| 9 | +//! The credential newtypes are [`crate::domain::user`]'s — same rules, same | |
| 10 | +//! argon2 discipline, deliberately not a second copy that could drift. | |
| 11 | + | |
| 12 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | |
| 13 | +use ulid::Ulid; | |
| 14 | + | |
| 15 | +use crate::constant::SESSION_DURATION_DAYS; | |
| 16 | +use crate::database::Database; | |
| 17 | +use crate::domain::session::SessionToken; | |
| 18 | +use crate::domain::timestamp::Timestamp; | |
| 19 | +use crate::domain::user::{Password, PasswordHash, Username}; | |
| 20 | +use crate::error::AppError; | |
| 21 | + | |
| 22 | +pub const BUILDER_TABLE: &str = "builder"; | |
| 23 | +pub const BUILDER_SESSION_TABLE: &str = "builder_session"; | |
| 24 | + | |
| 25 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 26 | +pub struct BuilderId(RecordId); | |
| 27 | + | |
| 28 | +impl BuilderId { | |
| 29 | + pub fn generate() -> Self { | |
| 30 | + Self(RecordId::new(BUILDER_TABLE, Ulid::new().to_string())) | |
| 31 | + } | |
| 32 | + | |
| 33 | + pub fn from_key(key: &str) -> Self { | |
| 34 | + Self(RecordId::new(BUILDER_TABLE, key)) | |
| 35 | + } | |
| 36 | + | |
| 37 | + pub fn record(&self) -> RecordId { | |
| 38 | + self.0.clone() | |
| 39 | + } | |
| 40 | + | |
| 41 | + pub fn key(&self) -> &str { | |
| 42 | + match &self.0.key { | |
| 43 | + RecordIdKey::String(key) => key, | |
| 44 | + _ => "", | |
| 45 | + } | |
| 46 | + } | |
| 47 | +} | |
| 48 | + | |
| 49 | +#[derive(Debug, Clone, SurrealValue)] | |
| 50 | +pub struct Builder { | |
| 51 | + id: BuilderId, | |
| 52 | + username: Username, | |
| 53 | + password_hash: PasswordHash, | |
| 54 | +} | |
| 55 | + | |
| 56 | +impl Builder { | |
| 57 | + pub fn get_id(&self) -> &BuilderId { | |
| 58 | + &self.id | |
| 59 | + } | |
| 60 | + | |
| 61 | + pub fn get_username(&self) -> &Username { | |
| 62 | + &self.username | |
| 63 | + } | |
| 64 | + | |
| 65 | + pub fn get_password_hash(&self) -> &PasswordHash { | |
| 66 | + &self.password_hash | |
| 67 | + } | |
| 68 | + | |
| 69 | + pub async fn find_by_username( | |
| 70 | + username: &str, | |
| 71 | + control: &Database, | |
| 72 | + ) -> Result<Option<Builder>, AppError> { | |
| 73 | + let mut result = control | |
| 74 | + .query("SELECT * FROM builder WHERE username = $u LIMIT 1") | |
| 75 | + .bind(("u", username.trim().to_string())) | |
| 76 | + .await? | |
| 77 | + .check()?; | |
| 78 | + Ok(result.take::<Vec<Builder>>(0)?.into_iter().next()) | |
| 79 | + } | |
| 80 | + | |
| 81 | + pub async fn read(id: &BuilderId, control: &Database) -> Result<Option<Builder>, AppError> { | |
| 82 | + Ok(control.select(id.record()).await?) | |
| 83 | + } | |
| 84 | + | |
| 85 | + /// Idempotent startup seed. An existing row is left exactly as it is — the | |
| 86 | + /// seed never rewrites a credential, so rotating `BUILDER_PASSWORD` in the | |
| 87 | + /// environment does not silently re-key a live account (delete the row to | |
| 88 | + /// re-seed). There is no role to promote here, so this cannot have | |
| 89 | + /// `ensure_admin`'s create-then-promote hole. | |
| 90 | + pub async fn ensure( | |
| 91 | + username: Username, | |
| 92 | + password: Password, | |
| 93 | + control: &Database, | |
| 94 | + ) -> Result<(), AppError> { | |
| 95 | + if Self::find_by_username(username.as_str(), control) | |
| 96 | + .await? | |
| 97 | + .is_some() | |
| 98 | + { | |
| 99 | + return Ok(()); | |
| 100 | + } | |
| 101 | + let builder = Builder { | |
| 102 | + id: BuilderId::generate(), | |
| 103 | + password_hash: password.hash_async().await?, | |
| 104 | + username, | |
| 105 | + }; | |
| 106 | + let created: Option<Builder> = control | |
| 107 | + .create(builder.id.record()) | |
| 108 | + .content(builder.clone()) | |
| 109 | + .await?; | |
| 110 | + created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?; | |
| 111 | + tracing::info!( | |
| 112 | + username = builder.username.as_str(), | |
| 113 | + "seeded builder account" | |
| 114 | + ); | |
| 115 | + Ok(()) | |
| 116 | + } | |
| 117 | +} | |
| 118 | + | |
| 119 | +/// A builder's login session. [`crate::domain::session::Session`]'s shape | |
| 120 | +/// against the control database, with the token type shared so both cookies | |
| 121 | +/// are the same 64 hex chars. | |
| 122 | +#[derive(Debug, Clone, SurrealValue)] | |
| 123 | +pub struct BuilderSession { | |
| 124 | + id: RecordId, | |
| 125 | + builder: BuilderId, | |
| 126 | + token: SessionToken, | |
| 127 | + created_at: Timestamp, | |
| 128 | + expires_at: Timestamp, | |
| 129 | +} | |
| 130 | + | |
| 131 | +impl BuilderSession { | |
| 132 | + pub async fn create( | |
| 133 | + builder: &BuilderId, | |
| 134 | + control: &Database, | |
| 135 | + ) -> Result<BuilderSession, AppError> { | |
| 136 | + let session = BuilderSession { | |
| 137 | + id: RecordId::new(BUILDER_SESSION_TABLE, Ulid::new().to_string()), | |
| 138 | + builder: builder.clone(), | |
| 139 | + token: SessionToken::generate()?, | |
| 140 | + created_at: Timestamp::now(), | |
| 141 | + expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), | |
| 142 | + }; | |
| 143 | + let created: Option<BuilderSession> = | |
| 144 | + control.create(session.id.clone()).content(session).await?; | |
| 145 | + created.ok_or_else(|| AppError::Internal("failed to create the builder session".into())) | |
| 146 | + } | |
| 147 | + | |
| 148 | + pub fn token(&self) -> &SessionToken { | |
| 149 | + &self.token | |
| 150 | + } | |
| 151 | + | |
| 152 | + pub fn builder(&self) -> &BuilderId { | |
| 153 | + &self.builder | |
| 154 | + } | |
| 155 | + | |
| 156 | + pub fn is_expired(&self) -> bool { | |
| 157 | + self.expires_at.is_past() | |
| 158 | + } | |
| 159 | + | |
| 160 | + pub async fn find_by_token( | |
| 161 | + token: &str, | |
| 162 | + control: &Database, | |
| 163 | + ) -> Result<Option<BuilderSession>, AppError> { | |
| 164 | + let mut result = control | |
| 165 | + .query("SELECT * FROM builder_session WHERE token = $tok LIMIT 1") | |
| 166 | + .bind(("tok", token.to_string())) | |
| 167 | + .await? | |
| 168 | + .check()?; | |
| 169 | + Ok(result.take::<Vec<BuilderSession>>(0)?.into_iter().next()) | |
| 170 | + } | |
| 171 | + | |
| 172 | + pub async fn delete_by_token(token: &str, control: &Database) -> Result<(), AppError> { | |
| 173 | + control | |
| 174 | + .query("DELETE builder_session WHERE token = $tok") | |
| 175 | + .bind(("tok", token.to_string())) | |
| 176 | + .await? | |
| 177 | + .check()?; | |
| 178 | + Ok(()) | |
| 179 | + } | |
| 180 | +} | |
| 181 | + | |
| 182 | +#[cfg(test)] | |
| 183 | +mod tests { | |
| 184 | + use super::*; | |
| 185 | + use crate::tenant::Tenants; | |
| 186 | + | |
| 187 | + #[tokio::test] | |
| 188 | + async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { | |
| 189 | + let tenants = Tenants::new_mem().await.unwrap(); | |
| 190 | + let control = tenants.control(); | |
| 191 | + let name = Username::try_new("builder1").unwrap(); | |
| 192 | + Builder::ensure(name.clone(), Password::try_new("secret1").unwrap(), control) | |
| 193 | + .await | |
| 194 | + .unwrap(); | |
| 195 | + let first = Builder::find_by_username("builder1", control) | |
| 196 | + .await | |
| 197 | + .unwrap() | |
| 198 | + .expect("seeded"); | |
| 199 | + | |
| 200 | + // A second boot with a *different* password must leave the row alone: | |
| 201 | + // an environment edit is not a password reset. | |
| 202 | + Builder::ensure(name, Password::try_new("secret2").unwrap(), control) | |
| 203 | + .await | |
| 204 | + .unwrap(); | |
| 205 | + let again = Builder::find_by_username("builder1", control) | |
| 206 | + .await | |
| 207 | + .unwrap() | |
| 208 | + .expect("still there"); | |
| 209 | + assert_eq!(again.get_id(), first.get_id()); | |
| 210 | + assert_eq!( | |
| 211 | + again.get_password_hash().as_str(), | |
| 212 | + first.get_password_hash().as_str() | |
| 213 | + ); | |
| 214 | + } | |
| 215 | + | |
| 216 | + #[tokio::test] | |
| 217 | + async fn a_builder_session_round_trips_and_deletes() { | |
| 218 | + let tenants = Tenants::new_mem().await.unwrap(); | |
| 219 | + let control = tenants.control(); | |
| 220 | + Builder::ensure( | |
| 221 | + Username::try_new("builder1").unwrap(), | |
| 222 | + Password::try_new("secret1").unwrap(), | |
| 223 | + control, | |
| 224 | + ) | |
| 225 | + .await | |
| 226 | + .unwrap(); | |
| 227 | + let builder = Builder::find_by_username("builder1", control) | |
| 228 | + .await | |
| 229 | + .unwrap() | |
| 230 | + .unwrap(); | |
| 231 | + | |
| 232 | + let session = BuilderSession::create(builder.get_id(), control) | |
| 233 | + .await | |
| 234 | + .unwrap(); | |
| 235 | + let token = session.token().as_str().to_string(); | |
| 236 | + let found = BuilderSession::find_by_token(&token, control) | |
| 237 | + .await | |
| 238 | + .unwrap() | |
| 239 | + .expect("found by token"); | |
| 240 | + assert_eq!(found.builder(), builder.get_id()); | |
| 241 | + assert!(!found.is_expired()); | |
| 242 | + | |
| 243 | + BuilderSession::delete_by_token(&token, control) | |
| 244 | + .await | |
| 245 | + .unwrap(); | |
| 246 | + assert!( | |
| 247 | + BuilderSession::find_by_token(&token, control) | |
| 248 | + .await | |
| 249 | + .unwrap() | |
| 250 | + .is_none() | |
| 251 | + ); | |
| 252 | + } | |
| 253 | +} |
src/domain/mod.rsmodified+1 -0
| @@ -11,6 +11,7 @@ pub mod bank_question; | ||
| 11 | 11 | pub mod bank_question_image; |
| 12 | 12 | pub mod board; |
| 13 | 13 | pub mod board_stroke; |
| 14 | +pub mod builder; | |
| 14 | 15 | pub mod cap; |
| 15 | 16 | pub mod chatbot_message; |
| 16 | 17 | pub mod chatbot_thread; |
src/lib.rsmodified+2 -1
| @@ -7,6 +7,7 @@ pub mod error; | ||
| 7 | 7 | pub mod migration_sql; |
| 8 | 8 | pub mod rate_limit; |
| 9 | 9 | pub mod state; |
| 10 | +pub mod tenant; | |
| 10 | 11 | pub mod validate; |
| 11 | 12 | pub mod web; |
| 12 | 13 | |
| @@ -161,7 +162,7 @@ pub fn build_router(state: AppState) -> Router { | ||
| 161 | 162 | if let Some(ai) = &state.ai { |
| 162 | 163 | ai.arm_api( |
| 163 | 164 | service.clone(), |
| 164 | - state.db.clone(), | |
| 165 | + state.tenants.clone(), | |
| 165 | 166 | state.db_up.clone(), |
| 166 | 167 | state.files_path.clone(), |
| 167 | 168 | ); |
src/main.rsmodified+9 -5
| @@ -19,17 +19,21 @@ async fn main() -> anyhow::Result<()> { | ||
| 19 | 19 | // Hash the login decoy now, so the first unknown-username login is not the |
| 20 | 20 | // one request that pays for it (see `PasswordHash::prewarm_decoy`). |
| 21 | 21 | hezarfen_backend::domain::user::PasswordHash::prewarm_decoy(); |
| 22 | - // Connects, migrates the schema and seeds the admin — all of it idempotent | |
| 23 | - // and unconditional on every boot. | |
| 24 | - let db = database::init(&cfg).await?; | |
| 22 | + // Connects to the control database, migrates it and seeds the builder — | |
| 23 | + // all of it idempotent and unconditional on every boot. School databases | |
| 24 | + // come up lazily, one connection each, on first use. | |
| 25 | + let tenants = database::init(&cfg).await?; | |
| 25 | 26 | let db_up = DbHealth::default(); |
| 26 | - keepalive(db.clone(), db_up.clone()); | |
| 27 | + // The control connection is the one every request touches (the school | |
| 28 | + // lookup rides it), so it is the socket worth watching. | |
| 29 | + keepalive(tenants.control().clone(), db_up.clone()); | |
| 27 | 30 | tokio::fs::create_dir_all(&cfg.files_path) |
| 28 | 31 | .await |
| 29 | 32 | .with_context(|| format!("failed to create the files directory {}", cfg.files_path))?; |
| 30 | 33 | let ai = hezarfen_backend::ai::start_bridge(&cfg).await?; |
| 31 | 34 | let app = build_router(AppState { |
| 32 | - db, | |
| 35 | + db: tenants.control().clone(), | |
| 36 | + tenants, | |
| 33 | 37 | files_path: cfg.files_path.clone().into(), |
| 34 | 38 | cookie_secure: cfg.cookie_secure, |
| 35 | 39 | rate_limit: cfg.rate_limit.clone(), |
src/migration_sql.rsmodified+42 -0
| @@ -1461,6 +1461,48 @@ pub const BACKFILL: &str = " | ||
| 1461 | 1461 | }; |
| 1462 | 1462 | "; |
| 1463 | 1463 | |
| 1464 | +/// The **control** database's schema — the one database per deployment that | |
| 1465 | +/// knows which schools exist and who may create them. Everything else lives in | |
| 1466 | +/// a school database, whose schema is [`MIGRATION_BATCHES`] and is applied | |
| 1467 | +/// per school by [`crate::tenant::Tenants::create`]. | |
| 1468 | +/// | |
| 1469 | +/// The `rate_limit` copy is deliberate: the shared per-IP window | |
| 1470 | +/// (`crate::rate_limit::RateLimiter::share`) is billed against the control | |
| 1471 | +/// handle, because the limiter runs in front of the router — before any cookie | |
| 1472 | +/// has named a school. One budget per deployment is also the honest one for an | |
| 1473 | +/// unauthenticated brute-forcer, who has not picked a school yet either. | |
| 1474 | +pub const CONTROL_MIGRATION: &str = " | |
| 1475 | + DEFINE TABLE IF NOT EXISTS school SCHEMAFULL; | |
| 1476 | + DEFINE FIELD IF NOT EXISTS slug ON school TYPE string; | |
| 1477 | + DEFINE FIELD IF NOT EXISTS name ON school TYPE string; | |
| 1478 | + DEFINE FIELD IF NOT EXISTS status ON school TYPE string; | |
| 1479 | + DEFINE FIELD IF NOT EXISTS created_at ON school TYPE int; | |
| 1480 | + -- Redundant with the `school:<slug>` id, and kept anyway: the id is the | |
| 1481 | + -- fast path, the index is what makes a second row on the same slug | |
| 1482 | + -- impossible if a future write ever mints an id some other way. | |
| 1483 | + DEFINE INDEX IF NOT EXISTS school_slug ON school FIELDS slug UNIQUE; | |
| 1484 | + | |
| 1485 | + DEFINE TABLE IF NOT EXISTS builder SCHEMAFULL; | |
| 1486 | + DEFINE FIELD IF NOT EXISTS username ON builder TYPE string; | |
| 1487 | + DEFINE FIELD IF NOT EXISTS password_hash ON builder TYPE string; | |
| 1488 | + DEFINE INDEX IF NOT EXISTS builder_username ON builder FIELDS username UNIQUE; | |
| 1489 | + | |
| 1490 | + DEFINE TABLE IF NOT EXISTS builder_session SCHEMAFULL; | |
| 1491 | + DEFINE FIELD IF NOT EXISTS builder ON builder_session TYPE record<builder>; | |
| 1492 | + DEFINE FIELD IF NOT EXISTS token ON builder_session TYPE string; | |
| 1493 | + DEFINE FIELD IF NOT EXISTS created_at ON builder_session TYPE int; | |
| 1494 | + DEFINE FIELD IF NOT EXISTS expires_at ON builder_session TYPE int; | |
| 1495 | + DEFINE INDEX IF NOT EXISTS builder_session_token ON builder_session FIELDS token UNIQUE; | |
| 1496 | + DEFINE INDEX IF NOT EXISTS builder_session_expires ON builder_session FIELDS expires_at; | |
| 1497 | + | |
| 1498 | + -- Verbatim from `MIGRATION`; see the note above this constant. | |
| 1499 | + DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL; | |
| 1500 | + DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0; | |
| 1501 | + DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int; | |
| 1502 | +"; | |
| 1503 | + | |
| 1504 | +pub const CONTROL_MIGRATION_BATCHES: [&str; 1] = [CONTROL_MIGRATION]; | |
| 1505 | + | |
| 1464 | 1506 | /// The migration batches, in the order a boot applies them — and the *only* |
| 1465 | 1507 | /// list of them. [`crate::database::migrate`] runs exactly these. They stay |
| 1466 | 1508 | /// three separate queries: statements in one batch see the schema as it stood |
src/state.rsmodified+8 -0
| @@ -8,11 +8,19 @@ use tokio::sync::broadcast; | ||
| 8 | 8 | use crate::ai::AiBridge; |
| 9 | 9 | use crate::database::Database; |
| 10 | 10 | use crate::rate_limit::{RateLimitConfig, UserRateLimiter}; |
| 11 | +use crate::tenant::Tenants; | |
| 11 | 12 | |
| 12 | 13 | /// Shared application state handed to every handler. |
| 13 | 14 | #[derive(Clone)] |
| 14 | 15 | pub struct AppState { |
| 16 | + /// The database this request works in. At the router's root this is the | |
| 17 | + /// **control** database; `crate::web::tenant_state::State` swaps in the | |
| 18 | + /// caller's school before any handler that shadows `State` sees it. | |
| 15 | 19 | pub db: Database, |
| 20 | + /// The school registry and its connections. Always the deployment-wide | |
| 21 | + /// one — it is never narrowed per request, so a handler can still reach | |
| 22 | + /// another school's handle deliberately. | |
| 23 | + pub tenants: Tenants, | |
| 16 | 24 | /// Directory holding uploaded note-file blobs, one file per |
| 17 | 25 | /// `note_file` row, named by the row's key |
| 18 | 26 | /// (from [`crate::config::Config::files_path`]). |
src/tenant.rsadded+652 -0
| @@ -0,0 +1,652 @@ | ||
| 1 | +//! Multi-school tenancy: one SurrealDB **database** per school inside one | |
| 2 | +//! namespace, plus a **control** database holding the school registry, the | |
| 3 | +//! builder accounts that manage it, and the deployment-wide rate-limit window. | |
| 4 | +//! | |
| 5 | +//! Isolation is the store's, not ours. A school database sees only its own | |
| 6 | +//! rows, so no handler needs a `WHERE school = …` it could forget: the school | |
| 7 | +//! is chosen once, at the edge (`crate::web::tenant_state::State`), and every | |
| 8 | +//! query underneath runs against that handle. | |
| 9 | +//! | |
| 10 | +//! # One connection per school, never a clone | |
| 11 | +//! | |
| 12 | +//! [`crate::database::Database`] is `Arc<Surreal<Any>>` for the reason spelled | |
| 13 | +//! out there — `Surreal::clone()` mints a racing server-side session — and the | |
| 14 | +//! same reasoning forbids the obvious shortcut here: switching `use_db` on the | |
| 15 | +//! control handle would repoint *every* in-flight query on it. So a cache miss | |
| 16 | +//! dials a **new** connection, signs it in, and pins it to the school's | |
| 17 | +//! database for its lifetime. | |
| 18 | +//! | |
| 19 | +//! In-memory mode (tests) has no server to define databases on: each | |
| 20 | +//! `connect("memory")` is an independent datastore, so a school *is* its own | |
| 21 | +//! store and the cache is the only thing that finds it again. | |
| 22 | + | |
| 23 | +use std::collections::HashMap; | |
| 24 | +use std::sync::{Arc, RwLock}; | |
| 25 | + | |
| 26 | +use serde::Serialize; | |
| 27 | +use surrealdb::opt::auth::Root; | |
| 28 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | |
| 29 | + | |
| 30 | +use crate::config::Config; | |
| 31 | +use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; | |
| 32 | +use crate::database::{Database, lost_the_race, migrate, migrate_control}; | |
| 33 | +use crate::domain::page::PagedList; | |
| 34 | +use crate::domain::timestamp::Timestamp; | |
| 35 | +use crate::error::{AppError, ValidationError}; | |
| 36 | + | |
| 37 | +pub(crate) const SCHOOL_TABLE: &str = "school"; | |
| 38 | + | |
| 39 | +/// The school every in-memory test bootstrap gets. Not special to the code — | |
| 40 | +/// just the one name the test harness and the suites agree on. | |
| 41 | +pub const DEMO_SLUG: &str = "demo"; | |
| 42 | + | |
| 43 | +/// Slugs that name something other than a school: the builder cookie prefix and | |
| 44 | +/// the control database itself. Refused at construction, so neither a login nor | |
| 45 | +/// a `DEFINE DATABASE` can ever be aimed at them. | |
| 46 | +pub const RESERVED_SLUGS: [&str; 2] = ["builder", "control"]; | |
| 47 | + | |
| 48 | +/// A school's identity everywhere it is named: the cookie prefix, the database | |
| 49 | +/// name, and the files subdirectory. The character set is deliberately the | |
| 50 | +/// intersection of what all three accept — lowercase alphanumerics and `-`, | |
| 51 | +/// starting with an alphanumeric — which is also what makes it safe to | |
| 52 | +/// interpolate into `DEFINE DATABASE` / `REMOVE DATABASE`, the two statements | |
| 53 | +/// SurrealQL gives no way to bind a name into. | |
| 54 | +#[derive(Debug, Clone, PartialEq, Eq, Hash, SurrealValue, Serialize)] | |
| 55 | +#[serde(transparent)] | |
| 56 | +pub struct Slug(String); | |
| 57 | + | |
| 58 | +/// `^[a-z0-9][a-z0-9-]{1,31}$`, spelled out. `regex` is a dev-dependency here | |
| 59 | +/// and this is five lines of `char` predicates — a runtime dependency would | |
| 60 | +/// cost more than it saves. | |
| 61 | +fn is_slug(value: &str) -> bool { | |
| 62 | + let ok_len = (MIN_SLUG_LEN..=MAX_SLUG_LEN).contains(&value.len()); | |
| 63 | + let ok_first = value | |
| 64 | + .chars() | |
| 65 | + .next() | |
| 66 | + .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()); | |
| 67 | + let ok_rest = value | |
| 68 | + .chars() | |
| 69 | + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); | |
| 70 | + ok_len && ok_first && ok_rest | |
| 71 | +} | |
| 72 | + | |
| 73 | +impl Slug { | |
| 74 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | |
| 75 | + if !is_slug(value) { | |
| 76 | + return Err(ValidationError::Invalid { | |
| 77 | + field: "school", | |
| 78 | + reason: "must be 2-32 characters of a-z, 0-9 and -, starting with a letter or digit", | |
| 79 | + }); | |
| 80 | + } | |
| 81 | + if RESERVED_SLUGS.contains(&value) { | |
| 82 | + return Err(ValidationError::Invalid { | |
| 83 | + field: "school", | |
| 84 | + reason: "this name is reserved", | |
| 85 | + }); | |
| 86 | + } | |
| 87 | + Ok(Self(value.to_string())) | |
| 88 | + } | |
| 89 | + | |
| 90 | + pub fn as_str(&self) -> &str { | |
| 91 | + &self.0 | |
| 92 | + } | |
| 93 | +} | |
| 94 | + | |
| 95 | +impl std::fmt::Display for Slug { | |
| 96 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 97 | + f.write_str(&self.0) | |
| 98 | + } | |
| 99 | +} | |
| 100 | + | |
| 101 | +/// Whether a school may be reached at all. Suspension is immediate and total: | |
| 102 | +/// [`Tenants::get`] refuses before any handler runs, and login is no exception. | |
| 103 | +/// | |
| 104 | +/// Stored as a bare lowercase string, like [`crate::domain::role::Role`]. | |
| 105 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue, Serialize)] | |
| 106 | +#[surreal(untagged, rename_all = "lowercase")] | |
| 107 | +#[serde(rename_all = "lowercase")] | |
| 108 | +pub enum SchoolStatus { | |
| 109 | + Active, | |
| 110 | + Suspended, | |
| 111 | +} | |
| 112 | + | |
| 113 | +impl SchoolStatus { | |
| 114 | + pub fn as_str(self) -> &'static str { | |
| 115 | + match self { | |
| 116 | + SchoolStatus::Active => "active", | |
| 117 | + SchoolStatus::Suspended => "suspended", | |
| 118 | + } | |
| 119 | + } | |
| 120 | + | |
| 121 | + pub fn try_from_str(value: &str) -> Result<Self, ValidationError> { | |
| 122 | + match value { | |
| 123 | + "active" => Ok(SchoolStatus::Active), | |
| 124 | + "suspended" => Ok(SchoolStatus::Suspended), | |
| 125 | + _ => Err(ValidationError::Invalid { | |
| 126 | + field: "status", | |
| 127 | + reason: "must be one of: active, suspended", | |
| 128 | + }), | |
| 129 | + } | |
| 130 | + } | |
| 131 | +} | |
| 132 | + | |
| 133 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 134 | +pub struct SchoolId(RecordId); | |
| 135 | + | |
| 136 | +impl SchoolId { | |
| 137 | + /// The id **is** the slug, so the registry can never hold two rows for one | |
| 138 | + /// school even if the unique index were dropped. | |
| 139 | + pub fn from_slug(slug: &Slug) -> Self { | |
| 140 | + Self(RecordId::new(SCHOOL_TABLE, slug.as_str())) | |
| 141 | + } | |
| 142 | + | |
| 143 | + pub fn record(&self) -> RecordId { | |
| 144 | + self.0.clone() | |
| 145 | + } | |
| 146 | + | |
| 147 | + pub fn key(&self) -> &str { | |
| 148 | + match &self.0.key { | |
| 149 | + RecordIdKey::String(key) => key, | |
| 150 | + _ => "", | |
| 151 | + } | |
| 152 | + } | |
| 153 | +} | |
| 154 | + | |
| 155 | +/// A row in the control database's school registry. | |
| 156 | +#[derive(Debug, Clone, SurrealValue)] | |
| 157 | +pub struct School { | |
| 158 | + id: SchoolId, | |
| 159 | + slug: Slug, | |
| 160 | + name: String, | |
| 161 | + status: SchoolStatus, | |
| 162 | + created_at: Timestamp, | |
| 163 | +} | |
| 164 | + | |
| 165 | +impl School { | |
| 166 | + pub fn get_id(&self) -> &SchoolId { | |
| 167 | + &self.id | |
| 168 | + } | |
| 169 | + | |
| 170 | + pub fn slug(&self) -> &Slug { | |
| 171 | + &self.slug | |
| 172 | + } | |
| 173 | + | |
| 174 | + pub fn name(&self) -> &str { | |
| 175 | + &self.name | |
| 176 | + } | |
| 177 | + | |
| 178 | + pub fn status(&self) -> SchoolStatus { | |
| 179 | + self.status | |
| 180 | + } | |
| 181 | + | |
| 182 | + pub fn created_at(&self) -> Timestamp { | |
| 183 | + self.created_at | |
| 184 | + } | |
| 185 | + | |
| 186 | + pub async fn read(slug: &Slug, control: &Database) -> Result<Option<School>, AppError> { | |
| 187 | + Ok(control.select(SchoolId::from_slug(slug).record()).await?) | |
| 188 | + } | |
| 189 | + | |
| 190 | + /// One page of the registry, newest first. Same `(rows, total)` shape every | |
| 191 | + /// other list domain returns, so the builder API can wrap it in the usual | |
| 192 | + /// [`crate::web::Page`] envelope. | |
| 193 | + pub async fn list( | |
| 194 | + limit: Option<i64>, | |
| 195 | + offset: i64, | |
| 196 | + control: &Database, | |
| 197 | + ) -> Result<(Vec<School>, i64), AppError> { | |
| 198 | + PagedList::new(SCHOOL_TABLE, "ORDER BY created_at DESC, id DESC") | |
| 199 | + .run::<School>(limit, offset, control) | |
| 200 | + .await | |
| 201 | + } | |
| 202 | + | |
| 203 | + /// Rename a school. The slug is immutable — it names a database and a | |
| 204 | + /// directory, so it is the one field a rename must not touch. | |
| 205 | + pub async fn update_name( | |
| 206 | + slug: &Slug, | |
| 207 | + name: &str, | |
| 208 | + control: &Database, | |
| 209 | + ) -> Result<School, AppError> { | |
| 210 | + let updated: Option<School> = control | |
| 211 | + .query("UPDATE $id SET name = $name RETURN AFTER") | |
| 212 | + .bind(("id", SchoolId::from_slug(slug).record())) | |
| 213 | + .bind(("name", name.to_string())) | |
| 214 | + .await? | |
| 215 | + .check()? | |
| 216 | + .take::<Vec<School>>(0)? | |
| 217 | + .into_iter() | |
| 218 | + .next(); | |
| 219 | + updated.ok_or(AppError::NotFound) | |
| 220 | + } | |
| 221 | +} | |
| 222 | + | |
| 223 | +/// How a school handle is minted. Remote dials the server the control handle | |
| 224 | +/// came from; `Mem` mints an independent embedded datastore per school. | |
| 225 | +#[derive(Debug)] | |
| 226 | +enum Mode { | |
| 227 | + Remote { | |
| 228 | + url: String, | |
| 229 | + user: String, | |
| 230 | + pass: String, | |
| 231 | + ns: String, | |
| 232 | + }, | |
| 233 | + Mem, | |
| 234 | +} | |
| 235 | + | |
| 236 | +/// The school registry plus its live connections. | |
| 237 | +#[derive(Clone)] | |
| 238 | +pub struct Tenants { | |
| 239 | + control: Database, | |
| 240 | + cache: Arc<RwLock<HashMap<String, Database>>>, | |
| 241 | + mode: Arc<Mode>, | |
| 242 | +} | |
| 243 | + | |
| 244 | +impl Tenants { | |
| 245 | + /// Wrap an already-connected, already-migrated control handle. | |
| 246 | + pub fn new_remote(control: Database, cfg: &Config) -> Tenants { | |
| 247 | + Tenants { | |
| 248 | + control, | |
| 249 | + cache: Arc::new(RwLock::new(HashMap::new())), | |
| 250 | + mode: Arc::new(Mode::Remote { | |
| 251 | + url: cfg.db_url.clone(), | |
| 252 | + user: cfg.db_user.clone(), | |
| 253 | + pass: cfg.db_pass.clone(), | |
| 254 | + ns: cfg.db_ns.clone(), | |
| 255 | + }), | |
| 256 | + } | |
| 257 | + } | |
| 258 | + | |
| 259 | + /// A fresh in-memory control database with the control schema applied, and | |
| 260 | + /// no schools. For tests. | |
| 261 | + pub async fn new_mem() -> Result<Tenants, AppError> { | |
| 262 | + let control = surrealdb::engine::any::connect("memory").await?; | |
| 263 | + control.use_ns("hezarfen").use_db("control").await?; | |
| 264 | + migrate_control(&control).await?; | |
| 265 | + Ok(Tenants { | |
| 266 | + control: Arc::new(control), | |
| 267 | + cache: Arc::new(RwLock::new(HashMap::new())), | |
| 268 | + mode: Arc::new(Mode::Mem), | |
| 269 | + }) | |
| 270 | + } | |
| 271 | + | |
| 272 | + /// A fresh in-memory registry that already knows `slug`, backed by a handle | |
| 273 | + /// that already exists rather than a new store. | |
| 274 | + /// | |
| 275 | + /// This is how a suite simulates a reboot: the process (and so the registry, | |
| 276 | + /// the connection cache and the control database) is new, while the school's | |
| 277 | + /// data is the very data the previous process wrote. | |
| 278 | + pub async fn new_mem_adopting( | |
| 279 | + slug: &Slug, | |
| 280 | + name: &str, | |
| 281 | + db: Database, | |
| 282 | + ) -> Result<Tenants, AppError> { | |
| 283 | + let tenants = Tenants::new_mem().await?; | |
| 284 | + let school = School { | |
| 285 | + id: SchoolId::from_slug(slug), | |
| 286 | + slug: slug.clone(), | |
| 287 | + name: name.to_string(), | |
| 288 | + status: SchoolStatus::Active, | |
| 289 | + created_at: Timestamp::now(), | |
| 290 | + }; | |
| 291 | + let _: Option<School> = tenants | |
| 292 | + .control | |
| 293 | + .create(school.id.record()) | |
| 294 | + .content(school) | |
| 295 | + .await?; | |
| 296 | + tenants | |
| 297 | + .cache | |
| 298 | + .write() | |
| 299 | + .expect("tenant cache lock") | |
| 300 | + .insert(slug.as_str().to_string(), db); | |
| 301 | + Ok(tenants) | |
| 302 | + } | |
| 303 | + | |
| 304 | + /// The control database: schools, builders, the shared rate-limit window. | |
| 305 | + /// Never `use_db`-switched — see this module's header. | |
| 306 | + pub fn control(&self) -> &Database { | |
| 307 | + &self.control | |
| 308 | + } | |
| 309 | + | |
| 310 | + /// The handle for a school a request may use, or the refusal a request | |
| 311 | + /// gets: unknown → `401` (a wrong school is a wrong credential, and a `404` | |
| 312 | + /// would enumerate the customer list), suspended → `403`. | |
| 313 | + /// | |
| 314 | + /// corner-cut: the registry row is read on every request, so a suspension | |
| 315 | + /// takes effect on the next call with no invalidation protocol. That is one | |
| 316 | + /// extra control-db round trip per request; cache the row with a short TTL | |
| 317 | + /// if it ever shows up in a profile — the eviction in [`Tenants::set_status`] | |
| 318 | + /// is already there to make a cached decision safe. | |
| 319 | + pub async fn get(&self, slug: &Slug) -> Result<Database, AppError> { | |
| 320 | + match School::read(slug, &self.control).await? { | |
| 321 | + None => Err(AppError::Unauthorized), | |
| 322 | + Some(school) if school.status == SchoolStatus::Suspended => { | |
| 323 | + self.evict(slug); | |
| 324 | + Err(AppError::Forbidden("school is suspended")) | |
| 325 | + } | |
| 326 | + Some(_) => self.handle(slug).await, | |
| 327 | + } | |
| 328 | + } | |
| 329 | + | |
| 330 | + /// [`Tenants::get`] for builder tooling, which must still reach a suspended | |
| 331 | + /// school to un-suspend or inspect it. Unknown → `404`, because a builder is | |
| 332 | + /// authenticated and there is nothing to hide from them. | |
| 333 | + pub async fn get_any_status(&self, slug: &Slug) -> Result<(Database, SchoolStatus), AppError> { | |
| 334 | + let school = School::read(slug, &self.control) | |
| 335 | + .await? | |
| 336 | + .ok_or(AppError::NotFound)?; | |
| 337 | + Ok((self.handle(slug).await?, school.status)) | |
| 338 | + } | |
| 339 | + | |
| 340 | + /// Register a school and bring its database into being: registry row first | |
| 341 | + /// (so a lost race is a `409` and not a half-made database), then | |
| 342 | + /// `DEFINE DATABASE`, then the school schema. | |
| 343 | + pub async fn create(&self, slug: &Slug, name: &str) -> Result<Database, AppError> { | |
| 344 | + let school = School { | |
| 345 | + id: SchoolId::from_slug(slug), | |
| 346 | + slug: slug.clone(), | |
| 347 | + name: name.to_string(), | |
| 348 | + status: SchoolStatus::Active, | |
| 349 | + created_at: Timestamp::now(), | |
| 350 | + }; | |
| 351 | + let created: Result<Option<School>, surrealdb::Error> = self | |
| 352 | + .control | |
| 353 | + .create(school.id.record()) | |
| 354 | + .content(school.clone()) | |
| 355 | + .await; | |
| 356 | + match created { | |
| 357 | + Ok(Some(_)) => {} | |
| 358 | + Ok(None) => return Err(AppError::Internal("failed to create the school".into())), | |
| 359 | + // The id is the slug, so "already exists" is exactly "taken" — and | |
| 360 | + // a lost transaction race is the same verdict reached differently. | |
| 361 | + Err(err) if lost_the_race(&err) => { | |
| 362 | + return Err(AppError::Conflict("school slug already taken")); | |
| 363 | + } | |
| 364 | + Err(err) => return Err(err.into()), | |
| 365 | + } | |
| 366 | + | |
| 367 | + let db = match &*self.mode { | |
| 368 | + Mode::Remote { .. } => { | |
| 369 | + // `slug` is `Slug`-validated, so this interpolation carries only | |
| 370 | + // `[a-z0-9-]` — SurrealQL cannot bind a database name. | |
| 371 | + self.control | |
| 372 | + .query(format!("DEFINE DATABASE IF NOT EXISTS {slug}")) | |
| 373 | + .await? | |
| 374 | + .check()?; | |
| 375 | + self.connect(slug).await? | |
| 376 | + } | |
| 377 | + Mode::Mem => self.connect(slug).await?, | |
| 378 | + }; | |
| 379 | + migrate(&db).await?; | |
| 380 | + self.cache | |
| 381 | + .write() | |
| 382 | + .expect("tenant cache lock") | |
| 383 | + .insert(slug.as_str().to_string(), db.clone()); | |
| 384 | + Ok(db) | |
| 385 | + } | |
| 386 | + | |
| 387 | + /// Flip a school between active and suspended. Suspending also drops the | |
| 388 | + /// cached handle, so nothing that already resolved keeps serving. | |
| 389 | + pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> { | |
| 390 | + let updated: Vec<School> = self | |
| 391 | + .control | |
| 392 | + .query("UPDATE $id SET status = $status RETURN AFTER") | |
| 393 | + .bind(("id", SchoolId::from_slug(slug).record())) | |
| 394 | + .bind(("status", status)) | |
| 395 | + .await? | |
| 396 | + .check()? | |
| 397 | + .take(0)?; | |
| 398 | + if updated.is_empty() { | |
| 399 | + return Err(AppError::NotFound); | |
| 400 | + } | |
| 401 | + if status == SchoolStatus::Suspended { | |
| 402 | + self.evict(slug); | |
| 403 | + } | |
| 404 | + Ok(()) | |
| 405 | + } | |
| 406 | + | |
| 407 | + /// Delete a school outright: its data, then its registry row, then its | |
| 408 | + /// handle. Irreversible on purpose — there is no soft-delete state, that is | |
| 409 | + /// what [`SchoolStatus::Suspended`] is for. | |
| 410 | + pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> { | |
| 411 | + if let Mode::Remote { .. } = &*self.mode { | |
| 412 | + // Interpolation, not a bind: see `create`. | |
| 413 | + self.control | |
| 414 | + .query(format!("REMOVE DATABASE IF EXISTS {slug}")) | |
| 415 | + .await? | |
| 416 | + .check()?; | |
| 417 | + } | |
| 418 | + self.control | |
| 419 | + .query("DELETE $id") | |
| 420 | + .bind(("id", SchoolId::from_slug(slug).record())) | |
| 421 | + .await? | |
| 422 | + .check()?; | |
| 423 | + self.forget(slug); | |
| 424 | + Ok(()) | |
| 425 | + } | |
| 426 | + | |
| 427 | + /// Forget a school's connection. The next request dials a fresh one. | |
| 428 | + /// | |
| 429 | + /// A no-op in memory mode, where the cached handle *is* the school's | |
| 430 | + /// datastore and dropping it would delete the school's data rather than its | |
| 431 | + /// connection. Nothing depends on eviction for correctness — [`Tenants::get`] | |
| 432 | + /// re-reads the registry row on every request, so a suspension is refused | |
| 433 | + /// whether or not a handle survived it. [`Tenants::drop`], which does mean to | |
| 434 | + /// destroy the store, forgets it unconditionally. | |
| 435 | + pub fn evict(&self, slug: &Slug) { | |
| 436 | + if matches!(&*self.mode, Mode::Mem) { | |
| 437 | + return; | |
| 438 | + } | |
| 439 | + self.forget(slug); | |
| 440 | + } | |
| 441 | + | |
| 442 | + fn forget(&self, slug: &Slug) { | |
| 443 | + self.cache | |
| 444 | + .write() | |
| 445 | + .expect("tenant cache lock") | |
| 446 | + .remove(slug.as_str()); | |
| 447 | + } | |
| 448 | + | |
| 449 | + /// The cached handle, or a freshly dialled one. | |
| 450 | + async fn handle(&self, slug: &Slug) -> Result<Database, AppError> { | |
| 451 | + if let Some(db) = self | |
| 452 | + .cache | |
| 453 | + .read() | |
| 454 | + .expect("tenant cache lock") | |
| 455 | + .get(slug.as_str()) | |
| 456 | + { | |
| 457 | + return Ok(db.clone()); | |
| 458 | + } | |
| 459 | + let db = self.connect(slug).await?; | |
| 460 | + // In-memory mode has nowhere for a school's rows to have survived a | |
| 461 | + // cache miss, so a fresh store needs the schema. Remote already has it. | |
| 462 | + if matches!(&*self.mode, Mode::Mem) { | |
| 463 | + migrate(&db).await?; | |
| 464 | + } | |
| 465 | + // Losing the race here is harmless — both handles are equivalent — but | |
| 466 | + // the winner is kept so two requests never diverge onto two sessions. | |
| 467 | + Ok(self | |
| 468 | + .cache | |
| 469 | + .write() | |
| 470 | + .expect("tenant cache lock") | |
| 471 | + .entry(slug.as_str().to_string()) | |
| 472 | + .or_insert(db) | |
| 473 | + .clone()) | |
| 474 | + } | |
| 475 | + | |
| 476 | + /// One new connection, pinned to `slug`'s database for its lifetime. | |
| 477 | + async fn connect(&self, slug: &Slug) -> Result<Database, AppError> { | |
| 478 | + let db = match &*self.mode { | |
| 479 | + Mode::Remote { | |
| 480 | + url, | |
| 481 | + user, | |
| 482 | + pass, | |
| 483 | + ns, | |
| 484 | + } => { | |
| 485 | + let db = surrealdb::engine::any::connect(url.clone()).await?; | |
| 486 | + db.signin(Root { | |
| 487 | + username: user.clone(), | |
| 488 | + password: pass.clone(), | |
| 489 | + }) | |
| 490 | + .await?; | |
| 491 | + db.use_ns(ns.clone()).use_db(slug.as_str()).await?; | |
| 492 | + db | |
| 493 | + } | |
| 494 | + Mode::Mem => { | |
| 495 | + let db = surrealdb::engine::any::connect("memory").await?; | |
| 496 | + db.use_ns("hezarfen").use_db(slug.as_str()).await?; | |
| 497 | + db | |
| 498 | + } | |
| 499 | + }; | |
| 500 | + Ok(Arc::new(db)) | |
| 501 | + } | |
| 502 | +} | |
| 503 | + | |
| 504 | +#[cfg(test)] | |
| 505 | +mod tests { | |
| 506 | + use super::*; | |
| 507 | + | |
| 508 | + fn slug(value: &str) -> Slug { | |
| 509 | + Slug::try_new(value).expect(value) | |
| 510 | + } | |
| 511 | + | |
| 512 | + async fn count(db: &Database, table: &str) -> usize { | |
| 513 | + let mut rows = db | |
| 514 | + .query(format!("SELECT id FROM {table}")) | |
| 515 | + .await | |
| 516 | + .unwrap() | |
| 517 | + .check() | |
| 518 | + .unwrap(); | |
| 519 | + rows.take::<Vec<surrealdb::types::RecordId>>(0) | |
| 520 | + .unwrap() | |
| 521 | + .len() | |
| 522 | + } | |
| 523 | + | |
| 524 | + #[tokio::test] | |
| 525 | + async fn a_slug_names_a_school_and_nothing_reserved() { | |
| 526 | + for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] { | |
| 527 | + assert!(Slug::try_new(good).is_ok(), "{good:?} should be a slug"); | |
| 528 | + } | |
| 529 | + // Reserved words would collide with the builder cookie prefix and the | |
| 530 | + // control database itself — the two things a slug must never name. | |
| 531 | + for bad in [ | |
| 532 | + "builder", | |
| 533 | + "control", | |
| 534 | + "Demo", | |
| 535 | + "..", | |
| 536 | + "", | |
| 537 | + "x", | |
| 538 | + "-lead", | |
| 539 | + "has_underscore", | |
| 540 | + "has.dot", | |
| 541 | + &"x".repeat(33), | |
| 542 | + ] { | |
| 543 | + assert!(Slug::try_new(bad).is_err(), "{bad:?} must not be a slug"); | |
| 544 | + } | |
| 545 | + } | |
| 546 | + | |
| 547 | + #[tokio::test] | |
| 548 | + async fn two_schools_do_not_see_each_others_rows() { | |
| 549 | + let tenants = Tenants::new_mem().await.unwrap(); | |
| 550 | + let (a, b) = (slug("alpha"), slug("beta")); | |
| 551 | + let one = tenants.create(&a, "Alpha").await.unwrap(); | |
| 552 | + let two = tenants.create(&b, "Beta").await.unwrap(); | |
| 553 | + | |
| 554 | + one.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") | |
| 555 | + .await | |
| 556 | + .unwrap() | |
| 557 | + .check() | |
| 558 | + .unwrap(); | |
| 559 | + assert_eq!(count(&one, "user").await, 1); | |
| 560 | + assert_eq!( | |
| 561 | + count(&two, "user").await, | |
| 562 | + 0, | |
| 563 | + "a row written in one school must be invisible in the other" | |
| 564 | + ); | |
| 565 | + // A second `create` on a taken slug is a conflict, not a second school. | |
| 566 | + assert!(matches!( | |
| 567 | + tenants.create(&a, "Alpha again").await, | |
| 568 | + Err(AppError::Conflict(_)) | |
| 569 | + )); | |
| 570 | + } | |
| 571 | + | |
| 572 | + #[tokio::test] | |
| 573 | + async fn suspending_refuses_the_school_and_the_handle_it_already_had() { | |
| 574 | + let tenants = Tenants::new_mem().await.unwrap(); | |
| 575 | + let s = slug("alpha"); | |
| 576 | + tenants.create(&s, "Alpha").await.unwrap(); | |
| 577 | + // Cached by the first resolve; the suspension must beat the cache. | |
| 578 | + tenants.get(&s).await.expect("active school resolves"); | |
| 579 | + | |
| 580 | + tenants | |
| 581 | + .set_status(&s, SchoolStatus::Suspended) | |
| 582 | + .await | |
| 583 | + .unwrap(); | |
| 584 | + assert!(matches!( | |
| 585 | + tenants.get(&s).await, | |
| 586 | + Err(AppError::Forbidden("school is suspended")) | |
| 587 | + )); | |
| 588 | + // Builder tooling still reaches it, which is how it gets un-suspended. | |
| 589 | + let (_, status) = tenants.get_any_status(&s).await.unwrap(); | |
| 590 | + assert_eq!(status, SchoolStatus::Suspended); | |
| 591 | + | |
| 592 | + tenants.set_status(&s, SchoolStatus::Active).await.unwrap(); | |
| 593 | + assert!(tenants.get(&s).await.is_ok()); | |
| 594 | + // An unknown school is a bad credential, never a `404`. | |
| 595 | + assert!(matches!( | |
| 596 | + tenants.get(&slug("ghost")).await, | |
| 597 | + Err(AppError::Unauthorized) | |
| 598 | + )); | |
| 599 | + assert!(matches!( | |
| 600 | + tenants.get_any_status(&slug("ghost")).await, | |
| 601 | + Err(AppError::NotFound) | |
| 602 | + )); | |
| 603 | + } | |
| 604 | + | |
| 605 | + #[tokio::test] | |
| 606 | + async fn dropping_a_school_takes_its_rows_with_it() { | |
| 607 | + let tenants = Tenants::new_mem().await.unwrap(); | |
| 608 | + let s = slug("alpha"); | |
| 609 | + let db = tenants.create(&s, "Alpha").await.unwrap(); | |
| 610 | + db.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") | |
| 611 | + .await | |
| 612 | + .unwrap() | |
| 613 | + .check() | |
| 614 | + .unwrap(); | |
| 615 | + assert_eq!(count(&db, "user").await, 1); | |
| 616 | + | |
| 617 | + tenants.drop(&s).await.unwrap(); | |
| 618 | + assert!(matches!(tenants.get(&s).await, Err(AppError::Unauthorized))); | |
| 619 | + | |
| 620 | + let fresh = tenants.create(&s, "Alpha reborn").await.unwrap(); | |
| 621 | + assert_eq!( | |
| 622 | + count(&fresh, "user").await, | |
| 623 | + 0, | |
| 624 | + "a re-created school must not inherit the dropped one's rows" | |
| 625 | + ); | |
| 626 | + } | |
| 627 | + | |
| 628 | + #[tokio::test] | |
| 629 | + async fn the_registry_lists_and_renames() { | |
| 630 | + let tenants = Tenants::new_mem().await.unwrap(); | |
| 631 | + tenants.create(&slug("alpha"), "Alpha").await.unwrap(); | |
| 632 | + tenants.create(&slug("beta"), "Beta").await.unwrap(); | |
| 633 | + | |
| 634 | + let (rows, total) = School::list(None, 0, tenants.control()).await.unwrap(); | |
| 635 | + assert_eq!(total, 2); | |
| 636 | + assert_eq!(rows.len(), 2); | |
| 637 | + | |
| 638 | + let renamed = School::update_name(&slug("alpha"), "Alpha Koleji", tenants.control()) | |
| 639 | + .await | |
| 640 | + .unwrap(); | |
| 641 | + assert_eq!(renamed.name(), "Alpha Koleji"); | |
| 642 | + assert_eq!( | |
| 643 | + renamed.slug().as_str(), | |
| 644 | + "alpha", | |
| 645 | + "a rename never moves the slug" | |
| 646 | + ); | |
| 647 | + assert!(matches!( | |
| 648 | + School::update_name(&slug("ghost"), "Nope", tenants.control()).await, | |
| 649 | + Err(AppError::NotFound) | |
| 650 | + )); | |
| 651 | + } | |
| 652 | +} |
src/web/appointments.rsmodified+2 -1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | use std::collections::{HashMap, HashSet}; |
| 2 | 2 | |
| 3 | +use crate::web::tenant_state::State; | |
| 3 | 4 | use axum::Json; |
| 4 | -use axum::extract::{Path, Query, State}; | |
| 5 | +use axum::extract::{Path, Query}; | |
| 5 | 6 | use axum::http::StatusCode; |
| 6 | 7 | use serde::{Deserialize, Serialize}; |
| 7 | 8 | use utoipa::ToSchema; |
src/web/attendance.rsmodified+2 -1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | use std::collections::HashMap; |
| 2 | 2 | |
| 3 | +use crate::web::tenant_state::State; | |
| 3 | 4 | use axum::Json; |
| 4 | -use axum::extract::{Path, State}; | |
| 5 | +use axum::extract::Path; | |
| 5 | 6 | use serde::Serialize; |
| 6 | 7 | use utoipa::ToSchema; |
| 7 | 8 | use utoipa_axum::router::OpenApiRouter; |
src/web/auth.rsmodified+47 -11
| @@ -10,15 +10,18 @@ use utoipa_axum::router::OpenApiRouter; | ||
| 10 | 10 | use utoipa_axum::routes; |
| 11 | 11 | |
| 12 | 12 | use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; |
| 13 | +use crate::domain::builder::BuilderSession; | |
| 13 | 14 | use crate::domain::role::Role as DomainRole; |
| 14 | 15 | use crate::domain::session::Session; |
| 15 | 16 | use crate::domain::user::{Password, PasswordHash, User, Username}; |
| 16 | 17 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 17 | 18 | use crate::rate_limit::{RateLimitConfig, RateLimiter}; |
| 18 | 19 | use crate::state::AppState; |
| 20 | +use crate::tenant::Slug; | |
| 19 | 21 | |
| 20 | 22 | use super::dto::Role; |
| 21 | -use super::{CurrentUser, UserResponse}; | |
| 23 | +use super::tenant_state::split_cookie; | |
| 24 | +use super::{BUILDER_COOKIE_PREFIX, CurrentUser, UserResponse}; | |
| 22 | 25 | |
| 23 | 26 | pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { |
| 24 | 27 | // Strict per-IP limit on the two credential endpoints only — the |
| @@ -44,6 +47,11 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { | ||
| 44 | 47 | |
| 45 | 48 | #[derive(Deserialize, ToSchema)] |
| 46 | 49 | struct Credentials { |
| 50 | + /// The school's slug — the name in front of the dot in the session cookie. | |
| 51 | + /// One backend serves many schools, so a username only identifies an | |
| 52 | + /// account together with this. | |
| 53 | + #[schema(example = "demo", min_length = 2, max_length = 32)] | |
| 54 | + school: String, | |
| 47 | 55 | #[schema(example = "ada", min_length = 3, max_length = 32)] |
| 48 | 56 | username: String, |
| 49 | 57 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| @@ -63,7 +71,7 @@ struct RegisterResponse { | ||
| 63 | 71 | role: Role, |
| 64 | 72 | } |
| 65 | 73 | |
| 66 | -/// Register a new user account: `{username, password}` in, `{username, role}` | |
| 74 | +/// Register a new user account: `{school, username, password}` in, `{username, role}` | |
| 67 | 75 | /// back (no `id`; new accounts are `student`). Always `201`, even if the name |
| 68 | 76 | /// was already taken — see "Auth model". |
| 69 | 77 | /// |
| @@ -83,6 +91,8 @@ struct RegisterResponse { | ||
| 83 | 91 | responses( |
| 84 | 92 | (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), |
| 85 | 93 | (status = 400, description = "Invalid username or password", body = ErrorResponse), |
| 94 | + (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse), | |
| 95 | + (status = 403, description = "The school is suspended", body = ErrorResponse), | |
| 86 | 96 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 87 | 97 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 88 | 98 | ), |
| @@ -91,6 +101,12 @@ async fn register( | ||
| 91 | 101 | State(st): State<AppState>, |
| 92 | 102 | Json(req): Json<Credentials>, |
| 93 | 103 | ) -> Result<(StatusCode, Json<RegisterResponse>), AppError> { |
| 104 | + // The school first: a registration into a school that does not exist, or | |
| 105 | + // one that is suspended, must not reach the (expensive) hashing path — and | |
| 106 | + // an unknown school answers `401` here for the same anti-enumeration reason | |
| 107 | + // login does, rather than confirming which schools this deployment serves. | |
| 108 | + let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; | |
| 109 | + let db = st.tenants.get(&school).await?; | |
| 94 | 110 | let username = Username::try_new(&req.username)?; |
| 95 | 111 | // Registration-level policy, not a `Username` invariant: these names read |
| 96 | 112 | // as staff and invite impersonation, but the `ADMIN_USERNAME` bootstrap |
| @@ -115,7 +131,7 @@ async fn register( | ||
| 115 | 131 | username: username.as_str().to_string(), |
| 116 | 132 | role: DomainRole::Student.into(), |
| 117 | 133 | }; |
| 118 | - match User::create(username, password_hash, &st.db).await { | |
| 134 | + match User::create(username, password_hash, &db).await { | |
| 119 | 135 | Ok(_) => {} |
| 120 | 136 | // Taken. Log the real reason server-side; the caller gets the same 201 |
| 121 | 137 | // and the same body, because telling the two apart is the whole thing |
| @@ -128,7 +144,8 @@ async fn register( | ||
| 128 | 144 | Ok((StatusCode::CREATED, Json(body))) |
| 129 | 145 | } |
| 130 | 146 | |
| 131 | -/// Log in with username + password. Sets a `session` cookie on success. | |
| 147 | +/// Log in with school + username + password. Sets a `session` cookie | |
| 148 | +/// (`<school>.<token>`) on success. | |
| 132 | 149 | #[utoipa::path( |
| 133 | 150 | post, |
| 134 | 151 | path = "/login", |
| @@ -136,7 +153,8 @@ async fn register( | ||
| 136 | 153 | request_body = Credentials, |
| 137 | 154 | responses( |
| 138 | 155 | (status = 200, description = "Logged in; session cookie set", body = UserResponse), |
| 139 | - (status = 401, description = "Bad credentials", body = ErrorResponse), | |
| 156 | + (status = 401, description = "Bad credentials, or no such school — deliberately indistinguishable", body = ErrorResponse), | |
| 157 | + (status = 403, description = "The school is suspended", body = ErrorResponse), | |
| 140 | 158 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 141 | 159 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 142 | 160 | ), |
| @@ -146,10 +164,17 @@ async fn login( | ||
| 146 | 164 | jar: CookieJar, |
| 147 | 165 | Json(req): Json<Credentials>, |
| 148 | 166 | ) -> Result<(CookieJar, Json<UserResponse>), AppError> { |
| 167 | + // Resolved *before* the argon2 work: a login aimed at a school that does | |
| 168 | + // not exist is a bad credential (`401`, indistinguishable from a bad | |
| 169 | + // password — the school list is not public), and a suspended school is | |
| 170 | + // `403` for every request including this one, so neither should buy an | |
| 171 | + // attacker a hash. | |
| 172 | + let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; | |
| 173 | + let db = st.tenants.get(&school).await?; | |
| 149 | 174 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; |
| 150 | 175 | // Usernames are stored trimmed (see `Username::try_new`); trim the lookup |
| 151 | 176 | // the same way so a padded login attempt matches the canonical name. |
| 152 | - let user = match User::find_by_username(req.username.trim(), &st.db).await? { | |
| 177 | + let user = match User::find_by_username(req.username.trim(), &db).await? { | |
| 153 | 178 | // Verification is `.await`ed so argon2 runs on the blocking pool instead |
| 154 | 179 | // of stalling an async worker; that rules out a match guard, which |
| 155 | 180 | // cannot await. |
| @@ -169,10 +194,12 @@ async fn login( | ||
| 169 | 194 | }; |
| 170 | 195 | |
| 171 | 196 | // The caller is genuine; opportunistically drop any expired session rows. |
| 172 | - let _ = Session::purge_expired(&st.db).await; | |
| 197 | + let _ = Session::purge_expired(&db).await; | |
| 173 | 198 | |
| 174 | - let session = Session::create(user.get_id(), &st.db).await?; | |
| 175 | - let cookie = Cookie::build(("session", session.token().as_str().to_string())) | |
| 199 | + let session = Session::create(user.get_id(), &db).await?; | |
| 200 | + // `<slug>.<token>`: the cookie carries the school, so every later request | |
| 201 | + // finds its database without a second lookup path that could disagree. | |
| 202 | + let cookie = Cookie::build(("session", format!("{school}.{}", session.token().as_str()))) | |
| 176 | 203 | .path("/") |
| 177 | 204 | .http_only(true) |
| 178 | 205 | .secure(st.cookie_secure) |
| @@ -198,8 +225,17 @@ async fn logout( | ||
| 198 | 225 | State(st): State<AppState>, |
| 199 | 226 | jar: CookieJar, |
| 200 | 227 | ) -> Result<(CookieJar, StatusCode), AppError> { |
| 201 | - if let Some(cookie) = jar.get("session") { | |
| 202 | - Session::delete_by_token(cookie.value(), &st.db).await?; | |
| 228 | + // Best-effort: the cookie names its own school, so a logout resolves that | |
| 229 | + // school and deletes the row there. A cookie naming a school that is gone | |
| 230 | + // or suspended still clears below — logging out must never fail. | |
| 231 | + if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { | |
| 232 | + if prefix == BUILDER_COOKIE_PREFIX { | |
| 233 | + BuilderSession::delete_by_token(token, &st.db).await?; | |
| 234 | + } else if let Ok(slug) = Slug::try_new(prefix) | |
| 235 | + && let Ok(db) = st.tenants.get(&slug).await | |
| 236 | + { | |
| 237 | + Session::delete_by_token(token, &db).await?; | |
| 238 | + } | |
| 203 | 239 | } |
| 204 | 240 | let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); |
| 205 | 241 | Ok((jar, StatusCode::NO_CONTENT)) |
src/web/bank_questions.rsmodified+2 -1
| @@ -15,8 +15,9 @@ | ||
| 15 | 15 | |
| 16 | 16 | use std::collections::HashMap; |
| 17 | 17 | |
| 18 | +use crate::web::tenant_state::State; | |
| 18 | 19 | use axum::Json; |
| 19 | -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | |
| 20 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; | |
| 20 | 21 | use axum::http::StatusCode; |
| 21 | 22 | use axum::response::Response; |
| 22 | 23 | use serde::{Deserialize, Serialize}; |
src/web/board_ws.rsmodified+2 -1
| @@ -58,8 +58,9 @@ | ||
| 58 | 58 | use std::collections::VecDeque; |
| 59 | 59 | use std::time::Duration; |
| 60 | 60 | |
| 61 | +use crate::web::tenant_state::State; | |
| 62 | +use axum::extract::Path; | |
| 61 | 63 | use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; |
| 62 | -use axum::extract::{Path, State}; | |
| 63 | 64 | use axum::response::Response; |
| 64 | 65 | use serde::Deserialize; |
| 65 | 66 | use serde_json::{Value, json}; |
src/web/boards.rsmodified+2 -1
| @@ -18,8 +18,9 @@ | ||
| 18 | 18 | //! mid-session keeps drawing over an already-open socket until the room hears |
| 19 | 19 | //! about it, so a roster change *must* fan out. |
| 20 | 20 | |
| 21 | +use crate::web::tenant_state::State; | |
| 21 | 22 | use axum::Json; |
| 22 | -use axum::extract::{Path, Query, State}; | |
| 23 | +use axum::extract::{Path, Query}; | |
| 23 | 24 | use axum::http::StatusCode; |
| 24 | 25 | use serde::{Deserialize, Serialize}; |
| 25 | 26 | use serde_json::json; |
src/web/chatbot.rsmodified+2 -1
| @@ -20,8 +20,9 @@ | ||
| 20 | 20 | |
| 21 | 21 | use std::time::Duration; |
| 22 | 22 | |
| 23 | +use crate::web::tenant_state::State; | |
| 23 | 24 | use axum::Json; |
| 24 | -use axum::extract::{Path, Query, State}; | |
| 25 | +use axum::extract::{Path, Query}; | |
| 25 | 26 | use axum::http::StatusCode; |
| 26 | 27 | use axum::response::sse::{Event, KeepAlive, Sse}; |
| 27 | 28 | use axum::response::{IntoResponse, Response}; |
src/web/classes.rsmodified+2 -1
| @@ -7,8 +7,9 @@ | ||
| 7 | 7 | //! and its roster are the office's (manager+), while attaching a course writes |
| 8 | 8 | //! *that course's* roster and takes the same right enrolling into it does. |
| 9 | 9 | |
| 10 | +use crate::web::tenant_state::State; | |
| 10 | 11 | use axum::Json; |
| 11 | -use axum::extract::{Path, Query, State}; | |
| 12 | +use axum::extract::{Path, Query}; | |
| 12 | 13 | use axum::http::StatusCode; |
| 13 | 14 | use serde::{Deserialize, Serialize}; |
| 14 | 15 | use utoipa::{IntoParams, ToSchema}; |
src/web/course_notes.rsmodified+3 -1
| @@ -5,8 +5,9 @@ | ||
| 5 | 5 | //! teacher, or manager+), reads need [`super::courses::can_view_course`] |
| 6 | 6 | //! (management rights, or enrollment). |
| 7 | 7 | |
| 8 | +use crate::web::tenant_state::State; | |
| 8 | 9 | use axum::Json; |
| 9 | -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | |
| 10 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; | |
| 10 | 11 | use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; |
| 11 | 12 | use axum::http::{HeaderValue, StatusCode}; |
| 12 | 13 | use axum::response::{IntoResponse, Response}; |
| @@ -387,6 +388,7 @@ async fn upload_file( | ||
| 387 | 388 | // the row insert fails, take the fresh blob back out. |
| 388 | 389 | let file = CourseNoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); |
| 389 | 390 | let path = blob_path(&st.files_path, file.get_id().key()); |
| 391 | + crate::web::ensure_files_dir(&st.files_path).await?; | |
| 390 | 392 | tokio::fs::write(&path, &upload.data) |
| 391 | 393 | .await |
| 392 | 394 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; |
src/web/courses.rsmodified+3 -1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | use std::collections::HashMap; |
| 2 | 2 | |
| 3 | +use crate::web::tenant_state::State; | |
| 3 | 4 | use axum::Json; |
| 4 | -use axum::extract::{Path, Query, State}; | |
| 5 | +use axum::extract::{Path, Query}; | |
| 5 | 6 | use axum::http::StatusCode; |
| 6 | 7 | use serde::{Deserialize, Serialize}; |
| 7 | 8 | use utoipa::ToSchema; |
| @@ -1415,6 +1416,7 @@ mod tests { | ||
| 1415 | 1416 | let course = course(&manager, &db).await; |
| 1416 | 1417 | let st = AppState { |
| 1417 | 1418 | db: db.clone(), |
| 1419 | + tenants: crate::database::init_mem_tenants().await.unwrap(), | |
| 1418 | 1420 | files_path: std::env::temp_dir(), |
| 1419 | 1421 | cookie_secure: false, |
| 1420 | 1422 | rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), |
src/web/events.rsmodified+2 -1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | use std::collections::HashMap; |
| 2 | 2 | |
| 3 | +use crate::web::tenant_state::State; | |
| 3 | 4 | use axum::Json; |
| 4 | -use axum::extract::{Path, Query, State}; | |
| 5 | +use axum::extract::{Path, Query}; | |
| 5 | 6 | use axum::http::StatusCode; |
| 6 | 7 | use serde::{Deserialize, Serialize}; |
| 7 | 8 | use utoipa::ToSchema; |
src/web/exam_ws.rsmodified+2 -1
| @@ -56,8 +56,9 @@ | ||
| 56 | 56 | |
| 57 | 57 | use std::time::Duration; |
| 58 | 58 | |
| 59 | +use crate::web::tenant_state::State; | |
| 60 | +use axum::extract::Path; | |
| 59 | 61 | use axum::extract::ws::{WebSocket, WebSocketUpgrade}; |
| 60 | -use axum::extract::{Path, State}; | |
| 61 | 62 | use axum::response::Response; |
| 62 | 63 | use serde::Deserialize; |
| 63 | 64 | use serde_json::{Value, json}; |
src/web/exams/mod.rsmodified+2 -1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | use std::collections::{HashMap, HashSet}; |
| 2 | 2 | |
| 3 | +use crate::web::tenant_state::State; | |
| 3 | 4 | use axum::Json; |
| 4 | -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | |
| 5 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; | |
| 5 | 6 | use axum::http::StatusCode; |
| 6 | 7 | use axum::response::Response; |
| 7 | 8 | use serde::{Deserialize, Serialize}; |
src/web/extractor.rsmodified+56 -8
| @@ -2,11 +2,14 @@ use axum::extract::{FromRef, FromRequestParts}; | ||
| 2 | 2 | use axum::http::request::Parts; |
| 3 | 3 | use axum_extra::extract::CookieJar; |
| 4 | 4 | |
| 5 | +use crate::database::Database; | |
| 6 | +use crate::domain::builder::{Builder, BuilderSession}; | |
| 5 | 7 | use crate::domain::role::Role; |
| 6 | 8 | use crate::domain::session::Session; |
| 7 | 9 | use crate::domain::user::User; |
| 8 | 10 | use crate::error::AppError; |
| 9 | 11 | use crate::state::AppState; |
| 12 | +use crate::web::tenant_state::{resolve_tenant, split_cookie}; | |
| 10 | 13 | |
| 11 | 14 | /// A principal injected as a request extension by the AI bridge, for the |
| 12 | 15 | /// synthetic requests it dispatches into the router. Extensions cannot be set |
| @@ -18,6 +21,11 @@ pub(crate) struct AiPrincipal(pub User); | ||
| 18 | 21 | /// [`AiPrincipal`] extension wins over the cookie. The role is read fresh from |
| 19 | 22 | /// the row on every request, so a role change takes effect on the user's next |
| 20 | 23 | /// call — no re-login required. |
| 24 | +/// | |
| 25 | +/// The school is resolved by the very helper `State<AppState>` uses | |
| 26 | +/// ([`resolve_tenant`]), so the principal and the rows a handler then reads can | |
| 27 | +/// never come from two different databases. A `builder.<token>` cookie names no | |
| 28 | +/// school and so cannot reach here at all. | |
| 21 | 29 | async fn authed_user<S>(parts: &mut Parts, state: &S) -> Result<User, AppError> |
| 22 | 30 | where |
| 23 | 31 | S: Send + Sync, |
| @@ -27,24 +35,22 @@ where | ||
| 27 | 35 | return Ok(principal.0.clone()); |
| 28 | 36 | } |
| 29 | 37 | |
| 38 | + let (_, db) = resolve_tenant(parts, state).await?; | |
| 39 | + | |
| 30 | 40 | let jar = CookieJar::from_request_parts(parts, state) |
| 31 | 41 | .await |
| 32 | 42 | .map_err(|_| AppError::Unauthorized)?; |
| 33 | - let token = jar | |
| 34 | - .get("session") | |
| 35 | - .map(|cookie| cookie.value().to_owned()) | |
| 36 | - .ok_or(AppError::Unauthorized)?; | |
| 37 | - | |
| 38 | - let app = AppState::from_ref(state); | |
| 43 | + let cookie = jar.get("session").ok_or(AppError::Unauthorized)?; | |
| 44 | + let (_, token) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?; | |
| 39 | 45 | |
| 40 | - let session = Session::find_by_token(&token, &app.db) | |
| 46 | + let session = Session::find_by_token(token, &db) | |
| 41 | 47 | .await? |
| 42 | 48 | .ok_or(AppError::Unauthorized)?; |
| 43 | 49 | if session.is_expired() { |
| 44 | 50 | return Err(AppError::Unauthorized); |
| 45 | 51 | } |
| 46 | 52 | |
| 47 | - User::read(session.user(), &app.db) | |
| 53 | + User::read(session.user(), &db) | |
| 48 | 54 | .await? |
| 49 | 55 | .ok_or(AppError::Unauthorized) |
| 50 | 56 | } |
| @@ -144,3 +150,45 @@ where | ||
| 144 | 150 | Ok(RequireAdmin(user)) |
| 145 | 151 | } |
| 146 | 152 | } |
| 153 | + | |
| 154 | +/// The deployment operator behind a `builder.<token>` cookie, resolved against | |
| 155 | +/// the **control** database. Any school cookie is `401` here, and this cookie | |
| 156 | +/// is `401` on every school surface (`resolve_tenant` refuses the `builder` | |
| 157 | +/// prefix as a slug) — the two principals share a cookie name and nothing else. | |
| 158 | +pub struct RequireBuilder(pub Builder); | |
| 159 | + | |
| 160 | +impl<S> FromRequestParts<S> for RequireBuilder | |
| 161 | +where | |
| 162 | + S: Send + Sync, | |
| 163 | + AppState: FromRef<S>, | |
| 164 | +{ | |
| 165 | + type Rejection = AppError; | |
| 166 | + | |
| 167 | + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | |
| 168 | + let jar = CookieJar::from_request_parts(parts, state) | |
| 169 | + .await | |
| 170 | + .map_err(|_| AppError::Unauthorized)?; | |
| 171 | + let cookie = jar.get("session").ok_or(AppError::Unauthorized)?; | |
| 172 | + let (prefix, token) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?; | |
| 173 | + if prefix != BUILDER_COOKIE_PREFIX { | |
| 174 | + return Err(AppError::Unauthorized); | |
| 175 | + } | |
| 176 | + | |
| 177 | + let control: Database = AppState::from_ref(state).tenants.control().clone(); | |
| 178 | + let session = BuilderSession::find_by_token(token, &control) | |
| 179 | + .await? | |
| 180 | + .ok_or(AppError::Unauthorized)?; | |
| 181 | + if session.is_expired() { | |
| 182 | + return Err(AppError::Unauthorized); | |
| 183 | + } | |
| 184 | + Ok(RequireBuilder( | |
| 185 | + Builder::read(session.builder(), &control) | |
| 186 | + .await? | |
| 187 | + .ok_or(AppError::Unauthorized)?, | |
| 188 | + )) | |
| 189 | + } | |
| 190 | +} | |
| 191 | + | |
| 192 | +/// The cookie prefix a builder session carries in place of a school slug. | |
| 193 | +/// `Slug::try_new` reserves this word, so it can never also name a school. | |
| 194 | +pub const BUILDER_COOKIE_PREFIX: &str = "builder"; |
src/web/homework.rsmodified+3 -1
| @@ -5,8 +5,9 @@ | ||
| 5 | 5 | //! [`super::courses`]); everything shares the visibility rule |
| 6 | 6 | //! ([`Homework::student_sees`]) and the [`HOMEWORK_LOCK`]. |
| 7 | 7 | |
| 8 | +use crate::web::tenant_state::State; | |
| 8 | 9 | use axum::Json; |
| 9 | -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | |
| 10 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; | |
| 10 | 11 | use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; |
| 11 | 12 | use axum::http::{HeaderValue, StatusCode}; |
| 12 | 13 | use axum::response::{IntoResponse, Response}; |
| @@ -964,6 +965,7 @@ async fn upload_submission_file( | ||
| 964 | 965 | upload.data.len() as i64, |
| 965 | 966 | ); |
| 966 | 967 | let path = blob_path(&st.files_path, file.get_file()); |
| 968 | + crate::web::ensure_files_dir(&st.files_path).await?; | |
| 967 | 969 | tokio::fs::write(&path, &upload.data) |
| 968 | 970 | .await |
| 969 | 971 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; |
src/web/image.rsmodified+1 -0
| @@ -62,6 +62,7 @@ pub(crate) async fn store_blob<T, Fut>( | ||
| 62 | 62 | where |
| 63 | 63 | Fut: Future<Output = Result<(T, Option<String>), AppError>>, |
| 64 | 64 | { |
| 65 | + crate::web::ensure_files_dir(&st.files_path).await?; | |
| 65 | 66 | let path = blob_path(&st.files_path, file); |
| 66 | 67 | tokio::fs::write(&path, data) |
| 67 | 68 | .await |
src/web/limits.rsmodified+11 -0
| @@ -29,6 +29,14 @@ pub fn routes() -> OpenApiRouter<AppState> { | ||
| 29 | 29 | /// Account fields: credentials, profile, and the closed role set. |
| 30 | 30 | #[derive(Serialize, ToSchema)] |
| 31 | 31 | struct UserLimits { |
| 32 | + /// The school slug the login and registration forms ask for, in front of | |
| 33 | + /// the dot in the session cookie. Lowercase `a-z`, `0-9` and `-`, starting | |
| 34 | + /// with a letter or digit. | |
| 35 | + min_slug_len: usize, | |
| 36 | + max_slug_len: usize, | |
| 37 | + /// Slugs no school may take — they name the builder cookie prefix and the | |
| 38 | + /// control database. | |
| 39 | + reserved_slugs: Vec<&'static str>, | |
| 32 | 40 | min_username_len: usize, |
| 33 | 41 | max_username_len: usize, |
| 34 | 42 | /// Separators allowed inside a username — never at the edges, never doubled. |
| @@ -462,6 +470,9 @@ impl LimitsResponse { | ||
| 462 | 470 | fn new(st: &AppState) -> Self { |
| 463 | 471 | Self { |
| 464 | 472 | user: UserLimits { |
| 473 | + min_slug_len: MIN_SLUG_LEN, | |
| 474 | + max_slug_len: MAX_SLUG_LEN, | |
| 475 | + reserved_slugs: crate::tenant::RESERVED_SLUGS.to_vec(), | |
| 465 | 476 | min_username_len: MIN_USERNAME_LEN, |
| 466 | 477 | max_username_len: MAX_USERNAME_LEN, |
| 467 | 478 | username_separators: USERNAME_SEPARATORS.iter().map(char::to_string).collect(), |
src/web/marks.rsmodified+2 -1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | use std::collections::HashMap; |
| 2 | 2 | |
| 3 | +use crate::web::tenant_state::State; | |
| 3 | 4 | use axum::Json; |
| 4 | -use axum::extract::{Path, State}; | |
| 5 | +use axum::extract::Path; | |
| 5 | 6 | use serde::Serialize; |
| 6 | 7 | use utoipa::ToSchema; |
| 7 | 8 | use utoipa_axum::router::OpenApiRouter; |
src/web/meals.rsmodified+2 -1
| @@ -9,8 +9,9 @@ | ||
| 9 | 9 | //! Money only ever *appends* here (see [`MealLedger`]): booking charges a price |
| 10 | 10 | //! snapshot, cancelling reverses it, and recording a payment is admin-only. |
| 11 | 11 | |
| 12 | +use crate::web::tenant_state::State; | |
| 12 | 13 | use axum::Json; |
| 13 | -use axum::extract::{Path, Query, State}; | |
| 14 | +use axum::extract::{Path, Query}; | |
| 14 | 15 | use axum::http::StatusCode; |
| 15 | 16 | use serde::{Deserialize, Serialize}; |
| 16 | 17 | use utoipa::{IntoParams, ToSchema}; |
src/web/messages.rsmodified+2 -1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | use std::collections::{HashMap, HashSet}; |
| 2 | 2 | |
| 3 | +use crate::web::tenant_state::State; | |
| 3 | 4 | use axum::Json; |
| 4 | -use axum::extract::{Path, Query, State}; | |
| 5 | +use axum::extract::{Path, Query}; | |
| 5 | 6 | use axum::http::StatusCode; |
| 6 | 7 | use serde::{Deserialize, Serialize}; |
| 7 | 8 | use utoipa::{IntoParams, ToSchema}; |
src/web/mod.rsmodified+20 -1
| @@ -35,6 +35,8 @@ pub mod terms; | ||
| 35 | 35 | pub mod users; |
| 36 | 36 | pub mod work; |
| 37 | 37 | |
| 38 | +pub mod tenant_state; | |
| 39 | + | |
| 38 | 40 | mod dto; |
| 39 | 41 | // `pub(crate)` for `AiPrincipal`: the AI bridge injects it as an extension on |
| 40 | 42 | // the requests it dispatches into the router (see `ai::server`). |
| @@ -46,7 +48,10 @@ pub use dto::{ | ||
| 46 | 48 | CourseResponse, ExamResponse, HomeworkResponse, PersonRef, SessionResponse, SubjectResponse, |
| 47 | 49 | UserResponse, course_people, person_map, |
| 48 | 50 | }; |
| 49 | -pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher}; | |
| 51 | +pub use extractor::{ | |
| 52 | + BUILDER_COOKIE_PREFIX, CurrentUser, RequireAdmin, RequireBuilder, RequireManager, | |
| 53 | + RequireStudent, RequireTeacher, | |
| 54 | +}; | |
| 50 | 55 | pub(crate) use image::{ImageUpload, read_image_upload, store_blob}; |
| 51 | 56 | pub use page::{Page, PageParams, Scheduled, WindowParams, paginate}; |
| 52 | 57 | |
| @@ -187,6 +192,20 @@ pub(crate) fn blob_path(files_path: &FsPath, key: &str) -> PathBuf { | ||
| 187 | 192 | files_path.join(key) |
| 188 | 193 | } |
| 189 | 194 | |
| 195 | +/// Make sure a school's blob directory exists before writing into it. | |
| 196 | +/// | |
| 197 | +/// `FILES_PATH` is the deployment root and `main` creates only that; each | |
| 198 | +/// school's subdirectory appears the first time that school stores a file, so | |
| 199 | +/// nothing has to be provisioned when a school is created. | |
| 200 | +pub(crate) async fn ensure_files_dir(files_path: &FsPath) -> Result<(), AppError> { | |
| 201 | + tokio::fs::create_dir_all(files_path).await.map_err(|err| { | |
| 202 | + AppError::Internal(format!( | |
| 203 | + "failed to create the files directory {}: {err}", | |
| 204 | + files_path.display() | |
| 205 | + )) | |
| 206 | + }) | |
| 207 | +} | |
| 208 | + | |
| 190 | 209 | /// Best-effort blob removal after its row is gone. Failure only strands an |
| 191 | 210 | /// unreachable file on disk, so it is logged rather than surfaced. |
| 192 | 211 | pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) { |
src/web/notes.rsmodified+3 -1
| @@ -1,5 +1,6 @@ | ||
| 1 | +use crate::web::tenant_state::State; | |
| 1 | 2 | use axum::Json; |
| 2 | -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | |
| 3 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; | |
| 3 | 4 | use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; |
| 4 | 5 | use axum::http::{HeaderValue, StatusCode}; |
| 5 | 6 | use axum::response::{IntoResponse, Response}; |
| @@ -283,6 +284,7 @@ async fn upload_file( | ||
| 283 | 284 | // the row insert fails, take the fresh blob back out. |
| 284 | 285 | let file = NoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64); |
| 285 | 286 | let path = blob_path(&st.files_path, file.get_id().key()); |
| 287 | + crate::web::ensure_files_dir(&st.files_path).await?; | |
| 286 | 288 | tokio::fs::write(&path, &upload.data) |
| 287 | 289 | .await |
| 288 | 290 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; |
src/web/payments.rsmodified+2 -1
| @@ -13,8 +13,9 @@ | ||
| 13 | 13 | |
| 14 | 14 | use std::collections::HashMap; |
| 15 | 15 | |
| 16 | +use crate::web::tenant_state::State; | |
| 16 | 17 | use axum::Json; |
| 17 | -use axum::extract::{Path, Query, State}; | |
| 18 | +use axum::extract::{Path, Query}; | |
| 18 | 19 | use axum::http::StatusCode; |
| 19 | 20 | use serde::{Deserialize, Serialize}; |
| 20 | 21 | use utoipa::ToSchema; |
src/web/pomodoro.rsmodified+2 -1
| @@ -1,5 +1,6 @@ | ||
| 1 | +use crate::web::tenant_state::State; | |
| 1 | 2 | use axum::Json; |
| 2 | -use axum::extract::{Path, Query, State}; | |
| 3 | +use axum::extract::{Path, Query}; | |
| 3 | 4 | use axum::http::StatusCode; |
| 4 | 5 | use serde::Serialize; |
| 5 | 6 | use utoipa::ToSchema; |
src/web/questions.rsmodified+2 -1
| @@ -8,8 +8,9 @@ | ||
| 8 | 8 | //! opposite: unmoderated, so their author may edit the body and attach, |
| 9 | 9 | //! replace, or drop one photo at any time — moderation there is delete-only. |
| 10 | 10 | |
| 11 | +use crate::web::tenant_state::State; | |
| 11 | 12 | use axum::Json; |
| 12 | -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | |
| 13 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; | |
| 13 | 14 | use axum::http::StatusCode; |
| 14 | 15 | use axum::response::Response; |
| 15 | 16 | use serde::{Deserialize, Serialize}; |
src/web/sessions.rsmodified+2 -1
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | use std::collections::HashMap; |
| 2 | 2 | |
| 3 | +use crate::web::tenant_state::State; | |
| 3 | 4 | use axum::Json; |
| 4 | -use axum::extract::{Path, Query, State}; | |
| 5 | +use axum::extract::{Path, Query}; | |
| 5 | 6 | use axum::http::StatusCode; |
| 6 | 7 | use serde::{Deserialize, Serialize}; |
| 7 | 8 | use utoipa::ToSchema; |
src/web/settings.rsmodified+1 -1
| @@ -1,5 +1,5 @@ | ||
| 1 | +use crate::web::tenant_state::State; | |
| 1 | 2 | use axum::Json; |
| 2 | -use axum::extract::State; | |
| 3 | 3 | use serde::{Deserialize, Serialize}; |
| 4 | 4 | use utoipa::ToSchema; |
| 5 | 5 | use utoipa_axum::router::OpenApiRouter; |
src/web/subjects.rsmodified+2 -1
| @@ -1,5 +1,6 @@ | ||
| 1 | +use crate::web::tenant_state::State; | |
| 1 | 2 | use axum::Json; |
| 2 | -use axum::extract::{Path, State}; | |
| 3 | +use axum::extract::Path; | |
| 3 | 4 | use axum::http::StatusCode; |
| 4 | 5 | use serde::Deserialize; |
| 5 | 6 | use utoipa::ToSchema; |
src/web/tenant_state.rsadded+305 -0
| @@ -0,0 +1,305 @@ | ||
| 1 | +//! The school-scoped replacement for `axum::extract::State`. | |
| 2 | +//! | |
| 3 | +//! [`State`] is named to **shadow** `axum::extract::State` on purpose: a | |
| 4 | +//! handler file swaps one import and every `State(st)` in it starts working in | |
| 5 | +//! the caller's school instead of the control database, with no handler body | |
| 6 | +//! touched. That is the whole design — there is no `st.db` a handler could | |
| 7 | +//! forget to scope, because the only `st` it can name is already scoped. | |
| 8 | +//! | |
| 9 | +//! Three files keep the real `axum::extract::State` because they legitimately | |
| 10 | +//! see the control database: `web::auth` (it resolves the school itself, and | |
| 11 | +//! its rate limiter is deployment-wide), `web::limits` (constants, no rows) and | |
| 12 | +//! `web::ai` (bridge certificate, no rows). | |
| 13 | + | |
| 14 | +use std::path::PathBuf; | |
| 15 | + | |
| 16 | +use axum::extract::{FromRef, FromRequestParts}; | |
| 17 | +use axum::http::request::Parts; | |
| 18 | +use axum_extra::extract::CookieJar; | |
| 19 | + | |
| 20 | +use crate::database::Database; | |
| 21 | +use crate::error::AppError; | |
| 22 | +use crate::state::AppState; | |
| 23 | +use crate::tenant::Slug; | |
| 24 | + | |
| 25 | +/// The school a request has already been resolved into, injected as a request | |
| 26 | +/// extension by an in-process caller that has no cookie — today only the AI | |
| 27 | +/// bridge. Extensions cannot be set from outside the process, so this is | |
| 28 | +/// unforgeable over HTTP, exactly like | |
| 29 | +/// [`crate::web::extractor::AiPrincipal`]. | |
| 30 | +#[derive(Clone)] | |
| 31 | +pub struct TenantExt { | |
| 32 | + pub slug: Slug, | |
| 33 | + pub db: Database, | |
| 34 | +} | |
| 35 | + | |
| 36 | +/// Split a `session` cookie into its school part and its token. `builder` in | |
| 37 | +/// the first position is the deployment operator; anything else is a slug. | |
| 38 | +/// | |
| 39 | +/// Splits at the **first** dot, so a token can never be mistaken for a slug no | |
| 40 | +/// matter what it contains (it is hex today, and this does not depend on that). | |
| 41 | +pub fn split_cookie(value: &str) -> Option<(&str, &str)> { | |
| 42 | + let (prefix, token) = value.split_once('.')?; | |
| 43 | + (!prefix.is_empty() && !token.is_empty()).then_some((prefix, token)) | |
| 44 | +} | |
| 45 | + | |
| 46 | +/// The school behind this request: the `TenantExt` extension if one was | |
| 47 | +/// injected, else the `session` cookie's prefix. | |
| 48 | +/// | |
| 49 | +/// Shared with [`crate::web::extractor`] so the two can never disagree about | |
| 50 | +/// which school a request belongs to — the authenticated user and the rows | |
| 51 | +/// they read must come from the same database. | |
| 52 | +pub(crate) async fn resolve_tenant<S>( | |
| 53 | + parts: &mut Parts, | |
| 54 | + state: &S, | |
| 55 | +) -> Result<(Slug, Database), AppError> | |
| 56 | +where | |
| 57 | + S: Send + Sync, | |
| 58 | + AppState: FromRef<S>, | |
| 59 | +{ | |
| 60 | + if let Some(tenant) = parts.extensions.get::<TenantExt>() { | |
| 61 | + return Ok((tenant.slug.clone(), tenant.db.clone())); | |
| 62 | + } | |
| 63 | + let jar = CookieJar::from_request_parts(parts, state) | |
| 64 | + .await | |
| 65 | + .map_err(|_| AppError::Unauthorized)?; | |
| 66 | + let cookie = jar.get("session").ok_or(AppError::Unauthorized)?; | |
| 67 | + // A builder cookie names no school, and a cookie with no dot names nothing | |
| 68 | + // at all. Both are `401` here: the builder surface is a different extractor | |
| 69 | + // (`RequireBuilder`), and this one must never let it in. | |
| 70 | + let (prefix, _) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?; | |
| 71 | + let slug = Slug::try_new(prefix).map_err(|_| AppError::Unauthorized)?; | |
| 72 | + | |
| 73 | + let app = AppState::from_ref(state); | |
| 74 | + let db = app.tenants.get(&slug).await?; | |
| 75 | + Ok((slug, db)) | |
| 76 | +} | |
| 77 | + | |
| 78 | +/// The application state, narrowed to the caller's school. Drop-in for | |
| 79 | +/// `axum::extract::State<AppState>` in every handler that reads school data. | |
| 80 | +/// | |
| 81 | +/// Unauthenticated callers are refused *here*, before the handler runs — which | |
| 82 | +/// is correct for every route that uses it, since all of them already require a | |
| 83 | +/// session to do anything. | |
| 84 | +pub struct State<T>(pub T); | |
| 85 | + | |
| 86 | +impl<S> FromRequestParts<S> for State<AppState> | |
| 87 | +where | |
| 88 | + S: Send + Sync, | |
| 89 | + AppState: FromRef<S>, | |
| 90 | +{ | |
| 91 | + type Rejection = AppError; | |
| 92 | + | |
| 93 | + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | |
| 94 | + let (slug, db) = resolve_tenant(parts, state).await?; | |
| 95 | + let app = AppState::from_ref(state); | |
| 96 | + Ok(State(AppState { | |
| 97 | + db, | |
| 98 | + files_path: school_files_path(&app.files_path, &slug), | |
| 99 | + ..app | |
| 100 | + })) | |
| 101 | + } | |
| 102 | +} | |
| 103 | + | |
| 104 | +/// Just the school, for the handlers that need it as a key prefix (the exam | |
| 105 | +/// presence map, the whiteboard hub) rather than as a database handle. | |
| 106 | +pub struct SchoolSlug(pub Slug); | |
| 107 | + | |
| 108 | +impl<S> FromRequestParts<S> for SchoolSlug | |
| 109 | +where | |
| 110 | + S: Send + Sync, | |
| 111 | + AppState: FromRef<S>, | |
| 112 | +{ | |
| 113 | + type Rejection = AppError; | |
| 114 | + | |
| 115 | + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | |
| 116 | + Ok(SchoolSlug(resolve_tenant(parts, state).await?.0)) | |
| 117 | + } | |
| 118 | +} | |
| 119 | + | |
| 120 | +/// Where a school's uploaded blobs live: one directory per school under the | |
| 121 | +/// deployment's `FILES_PATH`. The slug's character set is what makes this a | |
| 122 | +/// plain `join` — it can contain no separator and no `..`. | |
| 123 | +pub fn school_files_path(root: &std::path::Path, slug: &Slug) -> PathBuf { | |
| 124 | + root.join(slug.as_str()) | |
| 125 | +} | |
| 126 | + | |
| 127 | +#[cfg(test)] | |
| 128 | +mod tests { | |
| 129 | + use super::*; | |
| 130 | + | |
| 131 | + use axum::http::StatusCode; | |
| 132 | + use axum::routing::get; | |
| 133 | + use axum::{Router, body::Body, http::Request}; | |
| 134 | + use tower::ServiceExt; | |
| 135 | + | |
| 136 | + use crate::database::init_mem_tenants; | |
| 137 | + use crate::domain::builder::{Builder, BuilderSession}; | |
| 138 | + use crate::domain::session::Session; | |
| 139 | + use crate::domain::user::{Password, User, Username}; | |
| 140 | + use crate::tenant::DEMO_SLUG; | |
| 141 | + use crate::web::{CurrentUser, RequireBuilder}; | |
| 142 | + | |
| 143 | + async fn school_surface(State(_): State<AppState>, CurrentUser(_): CurrentUser) -> StatusCode { | |
| 144 | + StatusCode::OK | |
| 145 | + } | |
| 146 | + | |
| 147 | + async fn builder_surface(RequireBuilder(_): RequireBuilder) -> StatusCode { | |
| 148 | + StatusCode::OK | |
| 149 | + } | |
| 150 | + | |
| 151 | + /// A two-route app, one live cookie of each kind, and the registry behind | |
| 152 | + /// them. | |
| 153 | + async fn harness() -> (Router, String, String, crate::tenant::Tenants) { | |
| 154 | + let tenants = init_mem_tenants().await.expect("in-memory deployment"); | |
| 155 | + let school = tenants | |
| 156 | + .get(&Slug::try_new(DEMO_SLUG).unwrap()) | |
| 157 | + .await | |
| 158 | + .expect("the demo school"); | |
| 159 | + | |
| 160 | + let user = User::create( | |
| 161 | + Username::try_new("ada").unwrap(), | |
| 162 | + Password::try_new("secret1") | |
| 163 | + .unwrap() | |
| 164 | + .hash_async() | |
| 165 | + .await | |
| 166 | + .unwrap(), | |
| 167 | + &school, | |
| 168 | + ) | |
| 169 | + .await | |
| 170 | + .unwrap(); | |
| 171 | + let session = Session::create(user.get_id(), &school).await.unwrap(); | |
| 172 | + let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str()); | |
| 173 | + | |
| 174 | + Builder::ensure( | |
| 175 | + Username::try_new("operator").unwrap(), | |
| 176 | + Password::try_new("secret1").unwrap(), | |
| 177 | + tenants.control(), | |
| 178 | + ) | |
| 179 | + .await | |
| 180 | + .unwrap(); | |
| 181 | + let builder = Builder::find_by_username("operator", tenants.control()) | |
| 182 | + .await | |
| 183 | + .unwrap() | |
| 184 | + .unwrap(); | |
| 185 | + let builder_session = BuilderSession::create(builder.get_id(), tenants.control()) | |
| 186 | + .await | |
| 187 | + .unwrap(); | |
| 188 | + let builder_cookie = format!("session=builder.{}", builder_session.token().as_str()); | |
| 189 | + | |
| 190 | + let state = AppState { | |
| 191 | + db: tenants.control().clone(), | |
| 192 | + tenants: tenants.clone(), | |
| 193 | + files_path: std::env::temp_dir(), | |
| 194 | + cookie_secure: false, | |
| 195 | + rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), | |
| 196 | + chatbot_limit: Default::default(), | |
| 197 | + exam_presence: Default::default(), | |
| 198 | + board_hub: Default::default(), | |
| 199 | + db_up: Default::default(), | |
| 200 | + ai: None, | |
| 201 | + }; | |
| 202 | + let app = Router::new() | |
| 203 | + .route("/school", get(school_surface)) | |
| 204 | + .route("/builder", get(builder_surface)) | |
| 205 | + .with_state(state); | |
| 206 | + (app, school_cookie, builder_cookie, tenants) | |
| 207 | + } | |
| 208 | + | |
| 209 | + async fn status(app: &Router, uri: &str, cookie: Option<&str>) -> StatusCode { | |
| 210 | + let mut builder = Request::builder().uri(uri); | |
| 211 | + if let Some(cookie) = cookie { | |
| 212 | + builder = builder.header("cookie", cookie); | |
| 213 | + } | |
| 214 | + app.clone() | |
| 215 | + .oneshot(builder.body(Body::empty()).unwrap()) | |
| 216 | + .await | |
| 217 | + .unwrap() | |
| 218 | + .status() | |
| 219 | + } | |
| 220 | + | |
| 221 | + /// The two principals share a cookie name and nothing else. Neither may | |
| 222 | + /// ever be accepted where the other belongs — a builder holding school | |
| 223 | + /// power, or a student reaching the school-management surface, is the one | |
| 224 | + /// failure this whole split exists to prevent. | |
| 225 | + #[tokio::test] | |
| 226 | + async fn neither_cookie_works_on_the_others_surface() { | |
| 227 | + let (app, school, builder, _) = harness().await; | |
| 228 | + | |
| 229 | + assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK); | |
| 230 | + assert_eq!( | |
| 231 | + status(&app, "/builder", Some(&builder)).await, | |
| 232 | + StatusCode::OK | |
| 233 | + ); | |
| 234 | + | |
| 235 | + assert_eq!( | |
| 236 | + status(&app, "/school", Some(&builder)).await, | |
| 237 | + StatusCode::UNAUTHORIZED, | |
| 238 | + "a builder cookie must not pass a school extractor" | |
| 239 | + ); | |
| 240 | + assert_eq!( | |
| 241 | + status(&app, "/builder", Some(&school)).await, | |
| 242 | + StatusCode::UNAUTHORIZED, | |
| 243 | + "a school cookie must not pass RequireBuilder" | |
| 244 | + ); | |
| 245 | + | |
| 246 | + // A cookie with no school part names nothing resolvable — including the | |
| 247 | + // pre-tenancy shape, which is deliberately not accepted anywhere. | |
| 248 | + let bare = school.replace(&format!("{DEMO_SLUG}."), ""); | |
| 249 | + for uri in ["/school", "/builder"] { | |
| 250 | + assert_eq!( | |
| 251 | + status(&app, uri, Some(&bare)).await, | |
| 252 | + StatusCode::UNAUTHORIZED, | |
| 253 | + "{uri} accepted a cookie with no school" | |
| 254 | + ); | |
| 255 | + assert_eq!( | |
| 256 | + status(&app, uri, None).await, | |
| 257 | + StatusCode::UNAUTHORIZED, | |
| 258 | + "{uri} accepted no cookie at all" | |
| 259 | + ); | |
| 260 | + } | |
| 261 | + } | |
| 262 | + | |
| 263 | + /// A suspended school is refused at the edge, before any handler — with a | |
| 264 | + /// session that was perfectly good a moment earlier, and through a handle | |
| 265 | + /// the registry had already cached. | |
| 266 | + #[tokio::test] | |
| 267 | + async fn a_suspension_refuses_a_live_session() { | |
| 268 | + let (app, school, _, tenants) = harness().await; | |
| 269 | + let demo = Slug::try_new(DEMO_SLUG).unwrap(); | |
| 270 | + assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK); | |
| 271 | + | |
| 272 | + tenants | |
| 273 | + .set_status(&demo, crate::tenant::SchoolStatus::Suspended) | |
| 274 | + .await | |
| 275 | + .unwrap(); | |
| 276 | + assert_eq!( | |
| 277 | + status(&app, "/school", Some(&school)).await, | |
| 278 | + StatusCode::FORBIDDEN, | |
| 279 | + "a suspended school must be refused immediately, cached handle or not" | |
| 280 | + ); | |
| 281 | + | |
| 282 | + tenants | |
| 283 | + .set_status(&demo, crate::tenant::SchoolStatus::Active) | |
| 284 | + .await | |
| 285 | + .unwrap(); | |
| 286 | + assert_eq!( | |
| 287 | + status(&app, "/school", Some(&school)).await, | |
| 288 | + StatusCode::OK, | |
| 289 | + "un-suspending must restore the very same session" | |
| 290 | + ); | |
| 291 | + } | |
| 292 | + | |
| 293 | + #[test] | |
| 294 | + fn a_cookie_splits_at_its_first_dot_or_not_at_all() { | |
| 295 | + assert_eq!(split_cookie("demo.abc123"), Some(("demo", "abc123"))); | |
| 296 | + assert_eq!(split_cookie("builder.abc123"), Some(("builder", "abc123"))); | |
| 297 | + // First dot, so a dotted token still yields the school it named. | |
| 298 | + assert_eq!(split_cookie("demo.a.b"), Some(("demo", "a.b"))); | |
| 299 | + // A pre-tenancy cookie, an empty half, or nothing at all names no | |
| 300 | + // school — every one of these must be refused, not guessed at. | |
| 301 | + for bad in ["abc123", "", ".", "demo.", ".abc123"] { | |
| 302 | + assert_eq!(split_cookie(bad), None, "{bad:?}"); | |
| 303 | + } | |
| 304 | + } | |
| 305 | +} |
src/web/terms.rsmodified+2 -1
| @@ -1,5 +1,6 @@ | ||
| 1 | +use crate::web::tenant_state::State; | |
| 1 | 2 | use axum::Json; |
| 2 | -use axum::extract::{Path, Query, State}; | |
| 3 | +use axum::extract::{Path, Query}; | |
| 3 | 4 | use axum::http::StatusCode; |
| 4 | 5 | use serde::{Deserialize, Serialize}; |
| 5 | 6 | use utoipa::ToSchema; |
src/web/users.rsmodified+2 -1
| @@ -1,5 +1,6 @@ | ||
| 1 | +use crate::web::tenant_state::State; | |
| 1 | 2 | use axum::Json; |
| 2 | -use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | |
| 3 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; | |
| 3 | 4 | use axum::http::StatusCode; |
| 4 | 5 | use axum::response::Response; |
| 5 | 6 | use serde::{Deserialize, Serialize}; |
src/web/work.rsmodified+2 -1
| @@ -1,5 +1,6 @@ | ||
| 1 | +use crate::web::tenant_state::State; | |
| 1 | 2 | use axum::Json; |
| 2 | -use axum::extract::{Path, Query, State}; | |
| 3 | +use axum::extract::{Path, Query}; | |
| 3 | 4 | use axum::http::StatusCode; |
| 4 | 5 | use serde::{Deserialize, Serialize}; |
| 5 | 6 | use utoipa::ToSchema; |
tests/ai_bridge.rsmodified+6 -8
| @@ -816,11 +816,10 @@ async fn the_alpn_and_the_protocol_id_are_the_same_string() { | ||
| 816 | 816 | /// (status, body). |
| 817 | 817 | async fn fetch_certificate(ai: Option<AiBridge>) -> (axum::http::StatusCode, Value) { |
| 818 | 818 | use tower::ServiceExt; |
| 819 | - let db = hezarfen_backend::database::init_mem() | |
| 820 | - .await | |
| 821 | - .expect("mem db"); | |
| 819 | + let (tenants, _db) = common::mem_deployment().await; | |
| 822 | 820 | let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { |
| 823 | - db, | |
| 821 | + db: tenants.control().clone(), | |
| 822 | + tenants, | |
| 824 | 823 | files_path: std::env::temp_dir(), |
| 825 | 824 | cookie_secure: false, |
| 826 | 825 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| @@ -950,11 +949,10 @@ use surrealdb::types::RecordId; | ||
| 950 | 949 | |
| 951 | 950 | /// A router wired to `bridge`, plus a handle to its in-memory database. |
| 952 | 951 | async fn chat_app(bridge: &AiBridge) -> (Router, Database) { |
| 953 | - let db = hezarfen_backend::database::init_mem() | |
| 954 | - .await | |
| 955 | - .expect("mem db"); | |
| 952 | + let (tenants, db) = common::mem_deployment().await; | |
| 956 | 953 | let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { |
| 957 | - db: db.clone(), | |
| 954 | + db: tenants.control().clone(), | |
| 955 | + tenants, | |
| 958 | 956 | files_path: common::files_dir(), |
| 959 | 957 | cookie_secure: false, |
| 960 | 958 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
tests/ai_protocol.rsmodified+8 -3
| @@ -920,11 +920,16 @@ async fn a_chat_request_names_the_askers_school_role() { | ||
| 920 | 920 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; |
| 921 | 921 | await_workers(&bridge, 1).await; |
| 922 | 922 | |
| 923 | - let db = hezarfen_backend::database::init_mem() | |
| 923 | + let tenants = hezarfen_backend::database::init_mem_tenants() | |
| 924 | 924 | .await |
| 925 | - .expect("mem db"); | |
| 925 | + .expect("in-memory deployment"); | |
| 926 | + let db = tenants | |
| 927 | + .get(&hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap()) | |
| 928 | + .await | |
| 929 | + .expect("the demo school"); | |
| 926 | 930 | let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { |
| 927 | - db: db.clone(), | |
| 931 | + db: tenants.control().clone(), | |
| 932 | + tenants, | |
| 928 | 933 | files_path: common::files_dir(), |
| 929 | 934 | cookie_secure: false, |
| 930 | 935 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
tests/auth_enumeration.rsmodified+5 -5
| @@ -12,13 +12,13 @@ use serde_json::json; | ||
| 12 | 12 | #[tokio::test] |
| 13 | 13 | async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { |
| 14 | 14 | let (app, db) = app_and_db().await; |
| 15 | - let taken = json!({ "username": "ada", "password": "secret1" }); | |
| 15 | + let taken = json!({ "school": "demo", "username": "ada", "password": "secret1" }); | |
| 16 | 16 | |
| 17 | 17 | let first = send(&app, "POST", "/auth/register", None, Some(taken.clone())).await; |
| 18 | 18 | assert_eq!(first.status, StatusCode::CREATED); |
| 19 | 19 | |
| 20 | 20 | // Same username again, different password: still 201, same body shape. |
| 21 | - let dup_creds = json!({ "username": "ada", "password": "attacker" }); | |
| 21 | + let dup_creds = json!({ "school": "demo", "username": "ada", "password": "attacker" }); | |
| 22 | 22 | let started = Instant::now(); |
| 23 | 23 | let dup = send( |
| 24 | 24 | &app, |
| @@ -35,7 +35,7 @@ async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { | ||
| 35 | 35 | "POST", |
| 36 | 36 | "/auth/register", |
| 37 | 37 | None, |
| 38 | - Some(json!({ "username": "grace", "password": "secret1" })), | |
| 38 | + Some(json!({ "school": "demo", "username": "grace", "password": "secret1" })), | |
| 39 | 39 | ) |
| 40 | 40 | .await; |
| 41 | 41 | |
| @@ -122,7 +122,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() { | ||
| 122 | 122 | "POST", |
| 123 | 123 | "/auth/register", |
| 124 | 124 | None, |
| 125 | - Some(json!({ "username": "ada", "password": "secret1" })), | |
| 125 | + Some(json!({ "school": "demo", "username": "ada", "password": "secret1" })), | |
| 126 | 126 | ) |
| 127 | 127 | .await; |
| 128 | 128 | let taken = send( |
| @@ -130,7 +130,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() { | ||
| 130 | 130 | "POST", |
| 131 | 131 | "/auth/register", |
| 132 | 132 | None, |
| 133 | - Some(json!({ "username": "ada", "password": "another1" })), | |
| 133 | + Some(json!({ "school": "demo", "username": "ada", "password": "another1" })), | |
| 134 | 134 | ) |
| 135 | 135 | .await; |
| 136 | 136 |
tests/common/mod.rsmodified+62 -5
| @@ -12,6 +12,7 @@ use hezarfen_backend::ai::AiBridge; | ||
| 12 | 12 | use hezarfen_backend::database::Database; |
| 13 | 13 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 14 | 14 | use hezarfen_backend::state::{AppState, DbHealth}; |
| 15 | +use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; | |
| 15 | 16 | use hezarfen_backend::{build_router, database}; |
| 16 | 17 | use serde_json::{Value, json}; |
| 17 | 18 | use tempfile::TempDir; |
| @@ -43,6 +44,49 @@ pub async fn app_and_db() -> (Router, Database) { | ||
| 43 | 44 | app_with_ai(None).await |
| 44 | 45 | } |
| 45 | 46 | |
| 47 | +/// [`app_and_db`] plus the registry behind it, for the suites whose subject is | |
| 48 | +/// tenancy itself (a second school, a suspension, the builder surface). | |
| 49 | +pub async fn app_and_tenants() -> (Router, Database, Tenants) { | |
| 50 | + let (app, db, tenants) = app_parts(None, Default::default()).await; | |
| 51 | + (app, db, tenants) | |
| 52 | +} | |
| 53 | + | |
| 54 | +/// Where the demo school's blobs land: one directory per school under | |
| 55 | +/// `FILES_PATH`, created on the school's first upload. | |
| 56 | +pub fn blob_dir() -> PathBuf { | |
| 57 | + let dir = files_dir().join(DEMO_SLUG); | |
| 58 | + std::fs::create_dir_all(&dir).expect("blob dir"); | |
| 59 | + dir | |
| 60 | +} | |
| 61 | + | |
| 62 | +/// The raw session token out of a `session=<school>.<token>` cookie value — | |
| 63 | +/// what a test needs when it writes a session row by hand. | |
| 64 | +pub fn cookie_token(cookie: &str) -> &str { | |
| 65 | + cookie | |
| 66 | + .trim_start_matches("session=") | |
| 67 | + .split_once('.') | |
| 68 | + .expect("a session cookie carries its school") | |
| 69 | + .1 | |
| 70 | +} | |
| 71 | + | |
| 72 | +/// An in-memory deployment: the registry, plus the demo school's handle. For | |
| 73 | +/// the suites that build their own `AppState` instead of using [`app_and_db`]. | |
| 74 | +pub async fn mem_deployment() -> (Tenants, Database) { | |
| 75 | + let tenants = database::init_mem_tenants() | |
| 76 | + .await | |
| 77 | + .expect("in-memory deployment"); | |
| 78 | + let db = demo_db(&tenants).await; | |
| 79 | + (tenants, db) | |
| 80 | +} | |
| 81 | + | |
| 82 | +/// The demo school's handle out of a registry. | |
| 83 | +pub async fn demo_db(tenants: &Tenants) -> Database { | |
| 84 | + tenants | |
| 85 | + .get(&Slug::try_new(DEMO_SLUG).expect("the demo slug")) | |
| 86 | + .await | |
| 87 | + .expect("the demo school resolves") | |
| 88 | +} | |
| 89 | + | |
| 46 | 90 | /// The same router, with the AI bridge wired into its state. `build_router` |
| 47 | 91 | /// arms the bridge's api-read handle whenever `ai` is `Some`, so this is the |
| 48 | 92 | /// bootstrap that makes a QUIC service's reads dispatch into a real router. |
| @@ -54,9 +98,22 @@ pub async fn app_with_ai(ai: Option<AiBridge>) -> (Router, Database) { | ||
| 54 | 98 | /// database socket down under a running app — the api-read path re-checks it in |
| 55 | 99 | /// place of the HTTP db guard it bypasses. |
| 56 | 100 | pub async fn app_with_ai_health(ai: Option<AiBridge>, db_up: DbHealth) -> (Router, Database) { |
| 57 | - let db = database::init_mem().await.expect("in-memory db"); | |
| 101 | + let (app, db, _) = app_parts(ai, db_up).await; | |
| 102 | + (app, db) | |
| 103 | +} | |
| 104 | + | |
| 105 | +/// The one bootstrap: an in-memory deployment (control database + the demo | |
| 106 | +/// school), a router over it, and the demo school's handle — which is what | |
| 107 | +/// every suite means by "the database", since that is where users and rows | |
| 108 | +/// live. | |
| 109 | +async fn app_parts(ai: Option<AiBridge>, db_up: DbHealth) -> (Router, Database, Tenants) { | |
| 110 | + let tenants = database::init_mem_tenants() | |
| 111 | + .await | |
| 112 | + .expect("in-memory deployment"); | |
| 113 | + let db = demo_db(&tenants).await; | |
| 58 | 114 | let app = build_router(AppState { |
| 59 | - db: db.clone(), | |
| 115 | + db: tenants.control().clone(), | |
| 116 | + tenants: tenants.clone(), | |
| 60 | 117 | files_path: files_dir(), |
| 61 | 118 | cookie_secure: false, |
| 62 | 119 | // Off, so suites hammering the API never trip a limit; the dedicated |
| @@ -68,7 +125,7 @@ pub async fn app_with_ai_health(ai: Option<AiBridge>, db_up: DbHealth) -> (Route | ||
| 68 | 125 | db_up, |
| 69 | 126 | ai, |
| 70 | 127 | }); |
| 71 | - (app, db) | |
| 128 | + (app, db, tenants) | |
| 72 | 129 | } |
| 73 | 130 | |
| 74 | 131 | /// A router backed by a fresh in-memory database. |
| @@ -91,7 +148,7 @@ pub async fn set_role(db: &Database, username: &str, role: &str) { | ||
| 91 | 148 | /// Register (password `secret1`), promote to `role`, then log in. Returns the |
| 92 | 149 | /// session `Cookie` value. |
| 93 | 150 | pub async fn login_as(app: &Router, db: &Database, username: &str, role: &str) -> String { |
| 94 | - let creds = json!({ "username": username, "password": "secret1" }); | |
| 151 | + let creds = json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" }); | |
| 95 | 152 | let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; |
| 96 | 153 | assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); |
| 97 | 154 | set_role(db, username, role).await; |
| @@ -265,7 +322,7 @@ pub async fn upload_course_note_file( | ||
| 265 | 322 | |
| 266 | 323 | /// Register (password `secret1`) then log in; returns the session `Cookie` value. |
| 267 | 324 | pub async fn login(app: &Router, username: &str) -> String { |
| 268 | - let creds = json!({ "username": username, "password": "secret1" }); | |
| 325 | + let creds = json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" }); | |
| 269 | 326 | let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; |
| 270 | 327 | assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); |
| 271 | 328 | let res = send(app, "POST", "/auth/login", None, Some(creds)).await; |
tests/e2e.rsmodified+13 -5
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | use hezarfen_backend::database::Database; |
| 5 | 5 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 6 | 6 | use hezarfen_backend::state::AppState; |
| 7 | +use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; | |
| 7 | 8 | use hezarfen_backend::{build_router, database}; |
| 8 | 9 | use reqwest::{Client, StatusCode}; |
| 9 | 10 | use serde_json::{Value, json}; |
| @@ -17,9 +18,16 @@ async fn spawn_server() -> (String, Database) { | ||
| 17 | 18 | |
| 18 | 19 | /// [`spawn_server`], with the AI bridge the chatbot relays through wired in. |
| 19 | 20 | async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (String, Database) { |
| 20 | - let db = database::init_mem().await.expect("in-memory db"); | |
| 21 | + let tenants = database::init_mem_tenants() | |
| 22 | + .await | |
| 23 | + .expect("in-memory deployment"); | |
| 24 | + let db = tenants | |
| 25 | + .get(&Slug::try_new(DEMO_SLUG).unwrap()) | |
| 26 | + .await | |
| 27 | + .expect("the demo school"); | |
| 21 | 28 | let app = build_router(AppState { |
| 22 | - db: db.clone(), | |
| 29 | + db: tenants.control().clone(), | |
| 30 | + tenants, | |
| 23 | 31 | // Kept (not auto-deleted) so the directory outlives this helper; |
| 24 | 32 | // it's under the OS temp dir, reclaimed like any other temp file. |
| 25 | 33 | files_path: tempfile::tempdir().expect("files dir").keep(), |
| @@ -67,7 +75,7 @@ fn client() -> Client { | ||
| 67 | 75 | async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response { |
| 68 | 76 | client |
| 69 | 77 | .post(format!("{base}/auth/register")) |
| 70 | - .json(&json!({ "username": user, "password": "secret1" })) | |
| 78 | + .json(&json!({ "school": "demo", "username": user, "password": "secret1" })) | |
| 71 | 79 | .send() |
| 72 | 80 | .await |
| 73 | 81 | .unwrap() |
| @@ -76,7 +84,7 @@ async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response | ||
| 76 | 84 | async fn login(client: &Client, base: &str, user: &str) { |
| 77 | 85 | let res = client |
| 78 | 86 | .post(format!("{base}/auth/login")) |
| 79 | - .json(&json!({ "username": user, "password": "secret1" })) | |
| 87 | + .json(&json!({ "school": "demo", "username": user, "password": "secret1" })) | |
| 80 | 88 | .send() |
| 81 | 89 | .await |
| 82 | 90 | .unwrap(); |
| @@ -422,7 +430,7 @@ async fn attendance_rollup_across_users() { | ||
| 422 | 430 | async fn raw_session_cookie(base: &str, user: &str) -> String { |
| 423 | 431 | let res = Client::new() |
| 424 | 432 | .post(format!("{base}/auth/login")) |
| 425 | - .json(&json!({ "username": user, "password": "secret1" })) | |
| 433 | + .json(&json!({ "school": "demo", "username": user, "password": "secret1" })) | |
| 426 | 434 | .send() |
| 427 | 435 | .await |
| 428 | 436 | .unwrap(); |
tests/etag.rsmodified+1 -1
| @@ -154,7 +154,7 @@ async fn handler_owned_etag_passes_through_and_never_304s() { | ||
| 154 | 154 | #[tokio::test] |
| 155 | 155 | async fn mutations_are_never_etagged() { |
| 156 | 156 | let app = mem_app().await; |
| 157 | - let creds = serde_json::json!({ "username": "ann", "password": "secret1" }); | |
| 157 | + let creds = serde_json::json!({ "school": "demo", "username": "ann", "password": "secret1" }); | |
| 158 | 158 | let res = app |
| 159 | 159 | .clone() |
| 160 | 160 | .oneshot( |
tests/integration.rsmodified+77 -64
| @@ -10,6 +10,7 @@ use common::{ | ||
| 10 | 10 | create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll, |
| 11 | 11 | upload_course_note_file, |
| 12 | 12 | }; |
| 13 | +use hezarfen_backend::build_router; | |
| 13 | 14 | use hezarfen_backend::constant::{ |
| 14 | 15 | BANK_VISIBILITY_SCHOOL, MAX_BOARD_STROKES, MAX_BOARDS_PER_CREATOR, MAX_COURSE_NOTE_FILES, |
| 15 | 16 | MAX_EPOCH_STROKES, MAX_FEE_PLAN_ASSIGN_STUDENTS, |
| @@ -28,7 +29,6 @@ use hezarfen_backend::domain::session::Session; | ||
| 28 | 29 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 29 | 30 | use hezarfen_backend::domain::user::{Password, User, UserId, Username}; |
| 30 | 31 | use hezarfen_backend::state::AppState; |
| 31 | -use hezarfen_backend::{build_router, database}; | |
| 32 | 32 | use serde_json::json; |
| 33 | 33 | use tower::ServiceExt; |
| 34 | 34 | |
| @@ -150,7 +150,8 @@ async fn limits_publishes_the_bounds_the_api_actually_enforces() { | ||
| 150 | 150 | let max = res.body["user"]["max_username_len"] |
| 151 | 151 | .as_u64() |
| 152 | 152 | .expect("max_username_len is an integer") as usize; |
| 153 | - let too_long = json!({ "username": "a".repeat(max + 1), "password": "secret1" }); | |
| 153 | + let too_long = | |
| 154 | + json!({ "school": "demo", "username": "a".repeat(max + 1), "password": "secret1" }); | |
| 154 | 155 | let res = send(&app, "POST", "/auth/register", None, Some(too_long)).await; |
| 155 | 156 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 156 | 157 | } |
| @@ -162,8 +163,10 @@ async fn limits_still_answers_while_the_database_is_down() { | ||
| 162 | 163 | // row, so the outage guard must let it through — otherwise the client |
| 163 | 164 | // falls back to the hard-coded copy this endpoint exists to remove. |
| 164 | 165 | let db_up = hezarfen_backend::state::DbHealth::default(); |
| 166 | + let (tenants, _db) = common::mem_deployment().await; | |
| 165 | 167 | let app = build_router(AppState { |
| 166 | - db: database::init_mem().await.expect("in-memory db"), | |
| 168 | + db: tenants.control().clone(), | |
| 169 | + tenants, | |
| 167 | 170 | files_path: tempfile::tempdir().expect("files dir").keep(), |
| 168 | 171 | cookie_secure: false, |
| 169 | 172 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| @@ -190,25 +193,25 @@ async fn register_validates_input() { | ||
| 190 | 193 | let app = mem_app().await; |
| 191 | 194 | |
| 192 | 195 | // Password too short -> 400. |
| 193 | - let short = json!({ "username": "bob", "password": "123" }); | |
| 196 | + let short = json!({ "school": "demo", "username": "bob", "password": "123" }); | |
| 194 | 197 | let res = send(&app, "POST", "/auth/register", None, Some(short)).await; |
| 195 | 198 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 196 | 199 | |
| 197 | 200 | // Blank username -> 400. |
| 198 | - let blank = json!({ "username": " ", "password": "secret1" }); | |
| 201 | + let blank = json!({ "school": "demo", "username": " ", "password": "secret1" }); | |
| 199 | 202 | let res = send(&app, "POST", "/auth/register", None, Some(blank)).await; |
| 200 | 203 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 201 | 204 | |
| 202 | 205 | // Uppercase anywhere in the username -> 400. |
| 203 | 206 | for bad in ["Bob", "bOb", "BOB"] { |
| 204 | - let upper = json!({ "username": bad, "password": "secret1" }); | |
| 207 | + let upper = json!({ "school": "demo", "username": bad, "password": "secret1" }); | |
| 205 | 208 | let res = send(&app, "POST", "/auth/register", None, Some(upper)).await; |
| 206 | 209 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); |
| 207 | 210 | } |
| 208 | 211 | |
| 209 | 212 | // Username must start and end with a letter or digit -> 400. |
| 210 | 213 | for bad in ["-bob", "bob-", "_bob", "bob_", ".bob"] { |
| 211 | - let edge = json!({ "username": bad, "password": "secret1" }); | |
| 214 | + let edge = json!({ "school": "demo", "username": bad, "password": "secret1" }); | |
| 212 | 215 | let res = send(&app, "POST", "/auth/register", None, Some(edge)).await; |
| 213 | 216 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); |
| 214 | 217 | } |
| @@ -223,26 +226,26 @@ async fn register_validates_input() { | ||
| 223 | 226 | "a/b", |
| 224 | 227 | "a\"b", |
| 225 | 228 | ] { |
| 226 | - let ugly = json!({ "username": bad, "password": "secret1" }); | |
| 229 | + let ugly = json!({ "school": "demo", "username": bad, "password": "secret1" }); | |
| 227 | 230 | let res = send(&app, "POST", "/auth/register", None, Some(ugly)).await; |
| 228 | 231 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad:?} accepted"); |
| 229 | 232 | } |
| 230 | 233 | |
| 231 | 234 | // Consecutive separators -> 400. |
| 232 | 235 | for bad in ["a--b", "a..b", "a__b", "a.-b"] { |
| 233 | - let doubled = json!({ "username": bad, "password": "secret1" }); | |
| 236 | + let doubled = json!({ "school": "demo", "username": bad, "password": "secret1" }); | |
| 234 | 237 | let res = send(&app, "POST", "/auth/register", None, Some(doubled)).await; |
| 235 | 238 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); |
| 236 | 239 | } |
| 237 | 240 | |
| 238 | 241 | // Single separators between alphanumerics are fine -> 201. |
| 239 | - let dotted = json!({ "username": "ali.k_1-b", "password": "secret1" }); | |
| 242 | + let dotted = json!({ "school": "demo", "username": "ali.k_1-b", "password": "secret1" }); | |
| 240 | 243 | let res = send(&app, "POST", "/auth/register", None, Some(dotted)).await; |
| 241 | 244 | assert_eq!(res.status, StatusCode::CREATED); |
| 242 | 245 | assert_eq!(res.body["username"], "ali.k_1-b"); |
| 243 | 246 | |
| 244 | 247 | // Valid -> 201, no password echoed back, defaults to the student role. |
| 245 | - let ok = json!({ "username": "bob", "password": "secret1" }); | |
| 248 | + let ok = json!({ "school": "demo", "username": "bob", "password": "secret1" }); | |
| 246 | 249 | let res = send(&app, "POST", "/auth/register", None, Some(ok.clone())).await; |
| 247 | 250 | assert_eq!(res.status, StatusCode::CREATED); |
| 248 | 251 | assert_eq!(res.body["username"], "bob"); |
| @@ -253,7 +256,7 @@ async fn register_validates_input() { | ||
| 253 | 256 | // deliberately indistinguishable — see tests/auth_enumeration.rs), but the |
| 254 | 257 | // write is still rejected: the original password keeps working and the |
| 255 | 258 | // second one never becomes valid. |
| 256 | - let dup = json!({ "username": "bob", "password": "hijack1" }); | |
| 259 | + let dup = json!({ "school": "demo", "username": "bob", "password": "hijack1" }); | |
| 257 | 260 | let res = send(&app, "POST", "/auth/register", None, Some(dup.clone())).await; |
| 258 | 261 | assert_eq!(res.status, StatusCode::CREATED); |
| 259 | 262 | let res = send(&app, "POST", "/auth/login", None, Some(ok)).await; |
| @@ -284,7 +287,7 @@ async fn register_rejects_reserved_usernames() { | ||
| 284 | 287 | "moderator", |
| 285 | 288 | "staff", |
| 286 | 289 | ] { |
| 287 | - let creds = json!({ "username": name, "password": "secret1" }); | |
| 290 | + let creds = json!({ "school": "demo", "username": name, "password": "secret1" }); | |
| 288 | 291 | let res = send(&app, "POST", "/auth/register", None, Some(creds)).await; |
| 289 | 292 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{name} accepted"); |
| 290 | 293 | let msg = res.body["error"].as_str().unwrap_or_default(); |
| @@ -298,7 +301,7 @@ async fn register_rejects_reserved_usernames() { | ||
| 298 | 301 | // (created through `ensure_admin`, not `/auth/register`) still logs in. |
| 299 | 302 | // Covered by the admin bootstrap tests; here just prove a reserved name |
| 300 | 303 | // is not permanently poisoned for login by the register-level check. |
| 301 | - let creds = json!({ "username": "admin", "password": "wrong" }); | |
| 304 | + let creds = json!({ "school": "demo", "username": "admin", "password": "wrong" }); | |
| 302 | 305 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 303 | 306 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); // bad credentials, not "reserved" |
| 304 | 307 | } |
| @@ -311,7 +314,7 @@ async fn login_rejects_bad_credentials() { | ||
| 311 | 314 | "POST", |
| 312 | 315 | "/auth/register", |
| 313 | 316 | None, |
| 314 | - Some(json!({ "username": "kate", "password": "secret1" })), | |
| 317 | + Some(json!({ "school": "demo", "username": "kate", "password": "secret1" })), | |
| 315 | 318 | ) |
| 316 | 319 | .await; |
| 317 | 320 | |
| @@ -321,7 +324,7 @@ async fn login_rejects_bad_credentials() { | ||
| 321 | 324 | "POST", |
| 322 | 325 | "/auth/login", |
| 323 | 326 | None, |
| 324 | - Some(json!({ "username": "kate", "password": "wrong" })), | |
| 327 | + Some(json!({ "school": "demo", "username": "kate", "password": "wrong" })), | |
| 325 | 328 | ) |
| 326 | 329 | .await; |
| 327 | 330 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| @@ -332,7 +335,7 @@ async fn login_rejects_bad_credentials() { | ||
| 332 | 335 | "POST", |
| 333 | 336 | "/auth/login", |
| 334 | 337 | None, |
| 335 | - Some(json!({ "username": "ghost", "password": "secret1" })), | |
| 338 | + Some(json!({ "school": "demo", "username": "ghost", "password": "secret1" })), | |
| 336 | 339 | ) |
| 337 | 340 | .await; |
| 338 | 341 | assert_eq!(res.status, StatusCode::UNAUTHORIZED); |
| @@ -627,7 +630,7 @@ async fn a_demotion_to_parent_strands_no_note_and_no_blob() { | ||
| 627 | 630 | .await; |
| 628 | 631 | assert_eq!(up.status, StatusCode::CREATED); |
| 629 | 632 | let file_id = id_of(&up.body); |
| 630 | - let blob = common::files_dir().join(&file_id); | |
| 633 | + let blob = common::blob_dir().join(&file_id); | |
| 631 | 634 | assert!(blob.exists(), "the upload must have written a blob"); |
| 632 | 635 | |
| 633 | 636 | // 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() { | ||
| 745 | 748 | StatusCode::NO_CONTENT |
| 746 | 749 | ); |
| 747 | 750 | assert!(!blob.exists(), "deleting a file must unlink its blob"); |
| 748 | - let extra_blob = common::files_dir().join(id_of(&extra.body)); | |
| 751 | + let extra_blob = common::blob_dir().join(id_of(&extra.body)); | |
| 749 | 752 | assert_eq!( |
| 750 | 753 | send( |
| 751 | 754 | &app, |
| @@ -959,7 +962,7 @@ async fn note_files_upload_download_delete_roundtrip() { | ||
| 959 | 962 | StatusCode::NOT_FOUND |
| 960 | 963 | ); |
| 961 | 964 | assert!( |
| 962 | - !common::files_dir().join(&file_id).exists(), | |
| 965 | + !common::blob_dir().join(&file_id).exists(), | |
| 963 | 966 | "blob must be unlinked with its row" |
| 964 | 967 | ); |
| 965 | 968 | } |
| @@ -1238,13 +1241,13 @@ async fn malformed_json_bodies_answer_422_across_every_extractor_shape() { | ||
| 1238 | 1241 | ( |
| 1239 | 1242 | "/auth/register", |
| 1240 | 1243 | None, |
| 1241 | - r#"{"username": 5, "password": "secret1"}"#, | |
| 1244 | + r#"{"school": "demo", "username": 5, "password": "secret1"}"#, | |
| 1242 | 1245 | "plain Json, type mismatch", |
| 1243 | 1246 | ), |
| 1244 | 1247 | ( |
| 1245 | 1248 | "/auth/register", |
| 1246 | 1249 | None, |
| 1247 | - r#"{"username": "veli"}"#, | |
| 1250 | + r#"{"school": "demo", "username": "veli"}"#, | |
| 1248 | 1251 | "plain Json, missing required field", |
| 1249 | 1252 | ), |
| 1250 | 1253 | ( |
| @@ -1288,7 +1291,7 @@ async fn malformed_json_bodies_answer_422_across_every_extractor_shape() { | ||
| 1288 | 1291 | for (body, why) in [ |
| 1289 | 1292 | ("not json at all", "unparseable JSON"), |
| 1290 | 1293 | ( |
| 1291 | - r#"{"username": "a", "password": "secret1"}"#, | |
| 1294 | + r#"{"school": "demo", "username": "a", "password": "secret1"}"#, | |
| 1292 | 1295 | "well-typed value refused by a domain rule", |
| 1293 | 1296 | ), |
| 1294 | 1297 | ] { |
| @@ -1397,7 +1400,7 @@ async fn deleting_a_note_removes_its_files() { | ||
| 1397 | 1400 | let left: Vec<serde_json::Value> = rows.take(0).unwrap(); |
| 1398 | 1401 | assert!(left.is_empty(), "note_file rows must cascade: {left:?}"); |
| 1399 | 1402 | assert!( |
| 1400 | - !common::files_dir().join(&file_id).exists(), | |
| 1403 | + !common::blob_dir().join(&file_id).exists(), | |
| 1401 | 1404 | "blob must be unlinked when its note dies" |
| 1402 | 1405 | ); |
| 1403 | 1406 | } |
| @@ -5924,7 +5927,7 @@ async fn expired_session_is_unauthorized_before_any_purge() { | ||
| 5924 | 5927 | user = (SELECT VALUE user FROM ONLY session WHERE token = $live LIMIT 1), \ |
| 5925 | 5928 | token = 'stale-token', expires_at = 1", |
| 5926 | 5929 | ) |
| 5927 | - .bind(("live", ali.trim_start_matches("session=").to_string())) | |
| 5930 | + .bind(("live", common::cookie_token(&ali).to_string())) | |
| 5928 | 5931 | .await |
| 5929 | 5932 | .unwrap() |
| 5930 | 5933 | .check() |
| @@ -5959,7 +5962,9 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 5959 | 5962 | "POST", |
| 5960 | 5963 | "/auth/register", |
| 5961 | 5964 | None, |
| 5962 | - Some(json!({ "username": "ali", "password": "secret1" })), | |
| 5965 | + Some( | |
| 5966 | + json!({ "school": "demo", "school": "demo", "username": "ali", "password": "secret1" }), | |
| 5967 | + ), | |
| 5963 | 5968 | ) |
| 5964 | 5969 | .await; |
| 5965 | 5970 | assert_eq!(res.status, StatusCode::CREATED); |
| @@ -5974,7 +5979,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 5974 | 5979 | "POST", |
| 5975 | 5980 | "/auth/register", |
| 5976 | 5981 | None, |
| 5977 | - Some(json!({ "username": spoof, "password": "spoof1" })), | |
| 5982 | + Some(json!({ "school": "demo", "username": spoof, "password": "spoof1" })), | |
| 5978 | 5983 | ) |
| 5979 | 5984 | .await; |
| 5980 | 5985 | assert_eq!(res.status, StatusCode::CREATED, "{spoof:?}"); |
| @@ -6008,7 +6013,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 6008 | 6013 | "POST", |
| 6009 | 6014 | "/auth/login", |
| 6010 | 6015 | None, |
| 6011 | - Some(json!({ "username": attempt, "password": "secret1" })), | |
| 6016 | + Some(json!({ "school": "demo", "username": attempt, "password": "secret1" })), | |
| 6012 | 6017 | ) |
| 6013 | 6018 | .await; |
| 6014 | 6019 | assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); |
| @@ -6017,7 +6022,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 6017 | 6022 | "POST", |
| 6018 | 6023 | "/auth/login", |
| 6019 | 6024 | None, |
| 6020 | - Some(json!({ "username": attempt, "password": "spoof1" })), | |
| 6025 | + Some(json!({ "school": "demo", "username": attempt, "password": "spoof1" })), | |
| 6021 | 6026 | ) |
| 6022 | 6027 | .await; |
| 6023 | 6028 | assert_eq!( |
| @@ -6033,7 +6038,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 6033 | 6038 | "POST", |
| 6034 | 6039 | "/auth/register", |
| 6035 | 6040 | None, |
| 6036 | - Some(json!({ "username": " veli ", "password": "secret1" })), | |
| 6041 | + Some(json!({ "school": "demo", "username": " veli ", "password": "secret1" })), | |
| 6037 | 6042 | ) |
| 6038 | 6043 | .await; |
| 6039 | 6044 | assert_eq!(res.status, StatusCode::CREATED); |
| @@ -6046,7 +6051,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 6046 | 6051 | "POST", |
| 6047 | 6052 | "/auth/login", |
| 6048 | 6053 | None, |
| 6049 | - Some(json!({ "username": attempt, "password": "secret1" })), | |
| 6054 | + Some(json!({ "school": "demo", "username": attempt, "password": "secret1" })), | |
| 6050 | 6055 | ) |
| 6051 | 6056 | .await; |
| 6052 | 6057 | assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); |
| @@ -6340,7 +6345,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | ||
| 6340 | 6345 | "POST", |
| 6341 | 6346 | "/auth/register", |
| 6342 | 6347 | None, |
| 6343 | - Some(json!({ "username": "dup", "password": "secret1" })), | |
| 6348 | + Some(json!({ "school": "demo", "username": "dup", "password": "secret1" })), | |
| 6344 | 6349 | ) |
| 6345 | 6350 | .await |
| 6346 | 6351 | .status |
| @@ -6378,7 +6383,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | ||
| 6378 | 6383 | "POST", |
| 6379 | 6384 | "/auth/register", |
| 6380 | 6385 | None, |
| 6381 | - Some(json!({ "username": "dup", "password": "hijack1" })), | |
| 6386 | + Some(json!({ "school": "demo", "username": "dup", "password": "hijack1" })), | |
| 6382 | 6387 | ) |
| 6383 | 6388 | .await; |
| 6384 | 6389 | assert_eq!(res.status, StatusCode::CREATED); |
| @@ -6387,7 +6392,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | ||
| 6387 | 6392 | "POST", |
| 6388 | 6393 | "/auth/login", |
| 6389 | 6394 | None, |
| 6390 | - Some(json!({ "username": "dup", "password": "secret1" })), | |
| 6395 | + Some(json!({ "school": "demo", "username": "dup", "password": "secret1" })), | |
| 6391 | 6396 | ) |
| 6392 | 6397 | .await; |
| 6393 | 6398 | assert_eq!(res.status, StatusCode::OK, "the winning password broke"); |
| @@ -6396,7 +6401,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | ||
| 6396 | 6401 | "POST", |
| 6397 | 6402 | "/auth/login", |
| 6398 | 6403 | None, |
| 6399 | - Some(json!({ "username": "dup", "password": "hijack1" })), | |
| 6404 | + Some(json!({ "school": "demo", "username": "dup", "password": "hijack1" })), | |
| 6400 | 6405 | ) |
| 6401 | 6406 | .await; |
| 6402 | 6407 | assert_eq!( |
| @@ -6465,7 +6470,7 @@ async fn child_lists_of_missing_parents_are_404() { | ||
| 6465 | 6470 | #[tokio::test] |
| 6466 | 6471 | async fn session_cookie_secure_attribute_follows_config() { |
| 6467 | 6472 | async fn login_set_cookie(app: &axum::Router) -> String { |
| 6468 | - let creds = json!({ "username": "ada", "password": "secret1" }); | |
| 6473 | + let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" }); | |
| 6469 | 6474 | assert_eq!( |
| 6470 | 6475 | send(app, "POST", "/auth/register", None, Some(creds.clone())) |
| 6471 | 6476 | .await |
| @@ -6507,9 +6512,10 @@ async fn session_cookie_secure_attribute_follows_config() { | ||
| 6507 | 6512 | ); |
| 6508 | 6513 | |
| 6509 | 6514 | // With the flag on: Secure present. |
| 6510 | - let db = database::init_mem().await.unwrap(); | |
| 6515 | + let (tenants, _db) = common::mem_deployment().await; | |
| 6511 | 6516 | let app = build_router(AppState { |
| 6512 | - db, | |
| 6517 | + db: tenants.control().clone(), | |
| 6518 | + tenants, | |
| 6513 | 6519 | files_path: common::files_dir(), |
| 6514 | 6520 | cookie_secure: true, |
| 6515 | 6521 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| @@ -6546,10 +6552,11 @@ async fn db_down_refuses_before_touching_the_database() { | ||
| 6546 | 6552 | ids.len() |
| 6547 | 6553 | } |
| 6548 | 6554 | |
| 6549 | - let db = database::init_mem().await.unwrap(); | |
| 6555 | + let (tenants, db) = common::mem_deployment().await; | |
| 6550 | 6556 | let db_up = hezarfen_backend::state::DbHealth::default(); |
| 6551 | 6557 | let app = build_router(AppState { |
| 6552 | - db: db.clone(), | |
| 6558 | + db: tenants.control().clone(), | |
| 6559 | + tenants, | |
| 6553 | 6560 | files_path: common::files_dir(), |
| 6554 | 6561 | cookie_secure: false, |
| 6555 | 6562 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| @@ -6570,7 +6577,8 @@ async fn db_down_refuses_before_touching_the_database() { | ||
| 6570 | 6577 | .uri("/auth/register") |
| 6571 | 6578 | .header("content-type", "application/json") |
| 6572 | 6579 | .body(Body::from( |
| 6573 | - json!({"username": "gulsah", "password": "sifre12345"}).to_string(), | |
| 6580 | + json!({"school": "demo", "username": "gulsah", "password": "sifre12345"}) | |
| 6581 | + .to_string(), | |
| 6574 | 6582 | )) |
| 6575 | 6583 | .unwrap(), |
| 6576 | 6584 | ) |
| @@ -6594,7 +6602,8 @@ async fn db_down_refuses_before_touching_the_database() { | ||
| 6594 | 6602 | .uri("/auth/register") |
| 6595 | 6603 | .header("content-type", "application/json") |
| 6596 | 6604 | .body(Body::from( |
| 6597 | - json!({"username": "kerem", "password": "sifre12345"}).to_string(), | |
| 6605 | + json!({"school": "demo", "username": "kerem", "password": "sifre12345"}) | |
| 6606 | + .to_string(), | |
| 6598 | 6607 | )) |
| 6599 | 6608 | .unwrap(), |
| 6600 | 6609 | ) |
| @@ -6621,7 +6630,8 @@ async fn db_down_refuses_before_touching_the_database() { | ||
| 6621 | 6630 | .uri("/auth/register") |
| 6622 | 6631 | .header("content-type", "application/json") |
| 6623 | 6632 | .body(Body::from( |
| 6624 | - json!({"username": "kerem", "password": "sifre12345"}).to_string(), | |
| 6633 | + json!({"school": "demo", "username": "kerem", "password": "sifre12345"}) | |
| 6634 | + .to_string(), | |
| 6625 | 6635 | )) |
| 6626 | 6636 | .unwrap(), |
| 6627 | 6637 | ) |
| @@ -6814,7 +6824,7 @@ async fn admin_seed_creates_working_admin() { | ||
| 6814 | 6824 | let password = Password::try_new("secret1").unwrap(); |
| 6815 | 6825 | User::ensure_admin(username, password, &db).await.unwrap(); |
| 6816 | 6826 | |
| 6817 | - let creds = json!({ "username": "root", "password": "secret1" }); | |
| 6827 | + let creds = json!({ "school": "demo", "username": "root", "password": "secret1" }); | |
| 6818 | 6828 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 6819 | 6829 | assert_eq!(res.status, StatusCode::OK); |
| 6820 | 6830 | assert_eq!(res.body["role"], "admin"); |
| @@ -6836,7 +6846,7 @@ async fn admin_seed_is_idempotent() { | ||
| 6836 | 6846 | } |
| 6837 | 6847 | |
| 6838 | 6848 | let cookie = { |
| 6839 | - let creds = json!({ "username": "root", "password": "secret1" }); | |
| 6849 | + let creds = json!({ "school": "demo", "username": "root", "password": "secret1" }); | |
| 6840 | 6850 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 6841 | 6851 | assert_eq!(res.status, StatusCode::OK); |
| 6842 | 6852 | res.cookie.expect("session cookie") |
| @@ -6863,7 +6873,7 @@ async fn admin_seed_refuses_existing_non_admin() { | ||
| 6863 | 6873 | assert_eq!(res.status, StatusCode::FORBIDDEN, "must not be promoted"); |
| 6864 | 6874 | |
| 6865 | 6875 | // ...and the original password still logs in (nothing was overwritten). |
| 6866 | - let creds = json!({ "username": "squatter", "password": "secret1" }); | |
| 6876 | + let creds = json!({ "school": "demo", "username": "squatter", "password": "secret1" }); | |
| 6867 | 6877 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| 6868 | 6878 | assert_eq!(res.status, StatusCode::OK); |
| 6869 | 6879 | assert_eq!(res.body["role"], "student"); |
| @@ -12450,7 +12460,7 @@ async fn question_images_author_serve_and_cascade() { | ||
| 12450 | 12460 | assert_eq!(keys_before.len(), keys_after.len(), "replace adds no row"); |
| 12451 | 12461 | for stale in keys_before.iter().filter(|k| !keys_after.contains(k)) { |
| 12452 | 12462 | assert!( |
| 12453 | - !common::files_dir().join(stale).exists(), | |
| 12463 | + !common::blob_dir().join(stale).exists(), | |
| 12454 | 12464 | "replaced blob lingers on disk" |
| 12455 | 12465 | ); |
| 12456 | 12466 | } |
| @@ -12530,7 +12540,7 @@ async fn question_images_author_serve_and_cascade() { | ||
| 12530 | 12540 | ); |
| 12531 | 12541 | for key in &keys { |
| 12532 | 12542 | assert!( |
| 12533 | - !common::files_dir().join(key).exists(), | |
| 12543 | + !common::blob_dir().join(key).exists(), | |
| 12534 | 12544 | "blob {key} survived the exam delete" |
| 12535 | 12545 | ); |
| 12536 | 12546 | } |
| @@ -12698,7 +12708,7 @@ async fn student_answer_images_serve_and_cascade() { | ||
| 12698 | 12708 | // seq-1 answer-image row *and* its on-disk blob survive the new sitting. |
| 12699 | 12709 | let pre = answer_image_blob_keys(&db).await; |
| 12700 | 12710 | assert_eq!(pre.len(), 1); |
| 12701 | - assert!(common::files_dir().join(&pre[0]).exists()); | |
| 12711 | + assert!(common::blob_dir().join(&pre[0]).exists()); | |
| 12702 | 12712 | let res = send( |
| 12703 | 12713 | &app, |
| 12704 | 12714 | "POST", |
| @@ -12724,7 +12734,7 @@ async fn student_answer_images_serve_and_cascade() { | ||
| 12724 | 12734 | "the retake kept the prior sitting's answer-image row (history)" |
| 12725 | 12735 | ); |
| 12726 | 12736 | assert!( |
| 12727 | - common::files_dir().join(&pre[0]).exists(), | |
| 12737 | + common::blob_dir().join(&pre[0]).exists(), | |
| 12728 | 12738 | "the retake kept the prior sitting's answer-image blob on disk" |
| 12729 | 12739 | ); |
| 12730 | 12740 | |
| @@ -12749,7 +12759,7 @@ async fn student_answer_images_serve_and_cascade() { | ||
| 12749 | 12759 | ); |
| 12750 | 12760 | for key in &keys { |
| 12751 | 12761 | assert!( |
| 12752 | - !common::files_dir().join(key).exists(), | |
| 12762 | + !common::blob_dir().join(key).exists(), | |
| 12753 | 12763 | "answer-image blob {key} survived the exam delete" |
| 12754 | 12764 | ); |
| 12755 | 12765 | } |
| @@ -12963,7 +12973,7 @@ async fn question_image_edits_follow_the_choices() { | ||
| 12963 | 12973 | assert_eq!(dropped.len(), 1, "only the removed option's blob may go"); |
| 12964 | 12974 | for key in dropped { |
| 12965 | 12975 | assert!( |
| 12966 | - !common::files_dir().join(key).exists(), | |
| 12976 | + !common::blob_dir().join(key).exists(), | |
| 12967 | 12977 | "dropped option blob lingers" |
| 12968 | 12978 | ); |
| 12969 | 12979 | } |
| @@ -13028,7 +13038,7 @@ async fn question_image_edits_follow_the_choices() { | ||
| 13028 | 13038 | assert!(image_blob_keys(&db).await.is_empty()); |
| 13029 | 13039 | for key in &keys { |
| 13030 | 13040 | assert!( |
| 13031 | - !common::files_dir().join(key).exists(), | |
| 13041 | + !common::blob_dir().join(key).exists(), | |
| 13032 | 13042 | "blob {key} survived the question delete" |
| 13033 | 13043 | ); |
| 13034 | 13044 | } |
| @@ -15685,7 +15695,7 @@ async fn homework_files_roundtrip_and_scope() { | ||
| 15685 | 15695 | let res = send(&app, "DELETE", &file_uri, Some(&w.ali), None).await; |
| 15686 | 15696 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 15687 | 15697 | assert!( |
| 15688 | - !common::files_dir().join(&keys[0]).exists(), | |
| 15698 | + !common::blob_dir().join(&keys[0]).exists(), | |
| 15689 | 15699 | "blob must be unlinked with its row" |
| 15690 | 15700 | ); |
| 15691 | 15701 | let res = send( |
| @@ -16026,7 +16036,7 @@ async fn homework_gc_removes_rows_and_blobs() { | ||
| 16026 | 16036 | let keys = homework_blob_keys(&db).await; |
| 16027 | 16037 | assert_eq!(keys.len(), 3); |
| 16028 | 16038 | for key in &keys { |
| 16029 | - assert!(common::files_dir().join(key).exists(), "blob {key} on disk"); | |
| 16039 | + assert!(common::blob_dir().join(key).exists(), "blob {key} on disk"); | |
| 16030 | 16040 | } |
| 16031 | 16041 | |
| 16032 | 16042 | // Withdrawing a submission takes its file rows and blobs. |
| @@ -16043,7 +16053,7 @@ async fn homework_gc_removes_rows_and_blobs() { | ||
| 16043 | 16053 | assert_eq!(remaining.len(), 2); |
| 16044 | 16054 | for gone in keys.iter().filter(|key| !remaining.contains(key)) { |
| 16045 | 16055 | assert!( |
| 16046 | - !common::files_dir().join(gone).exists(), | |
| 16056 | + !common::blob_dir().join(gone).exists(), | |
| 16047 | 16057 | "withdrawn blob {gone} must be unlinked" |
| 16048 | 16058 | ); |
| 16049 | 16059 | } |
| @@ -16065,7 +16075,7 @@ async fn homework_gc_removes_rows_and_blobs() { | ||
| 16065 | 16075 | assert_eq!(hw_row_count(&db, "homework").await, 1, "hw2 remains"); |
| 16066 | 16076 | for key in &remaining { |
| 16067 | 16077 | assert!( |
| 16068 | - !common::files_dir().join(key).exists(), | |
| 16078 | + !common::blob_dir().join(key).exists(), | |
| 16069 | 16079 | "blob {key} must die with the homework" |
| 16070 | 16080 | ); |
| 16071 | 16081 | } |
| @@ -16102,7 +16112,7 @@ async fn homework_gc_removes_rows_and_blobs() { | ||
| 16102 | 16112 | } |
| 16103 | 16113 | for key in &keys { |
| 16104 | 16114 | assert!( |
| 16105 | - !common::files_dir().join(key).exists(), | |
| 16115 | + !common::blob_dir().join(key).exists(), | |
| 16106 | 16116 | "blob {key} must die with the course" |
| 16107 | 16117 | ); |
| 16108 | 16118 | } |
| @@ -16482,9 +16492,10 @@ async fn chat_app_limited( | ||
| 16482 | 16492 | ai: Option<AiBridge>, |
| 16483 | 16493 | chatbot_limit: hezarfen_backend::rate_limit::UserRateLimiter, |
| 16484 | 16494 | ) -> (axum::Router, Database) { |
| 16485 | - let db = database::init_mem().await.expect("in-memory db"); | |
| 16495 | + let (tenants, db) = common::mem_deployment().await; | |
| 16486 | 16496 | let app = build_router(AppState { |
| 16487 | - db: db.clone(), | |
| 16497 | + db: tenants.control().clone(), | |
| 16498 | + tenants, | |
| 16488 | 16499 | files_path: common::files_dir(), |
| 16489 | 16500 | cookie_secure: false, |
| 16490 | 16501 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| @@ -20048,7 +20059,7 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() { | ||
| 20048 | 20059 | // unreadable source mid-flight. |
| 20049 | 20060 | let src_keys = bank_image_blob_keys(&db).await; |
| 20050 | 20061 | assert_eq!(src_keys.len(), 2); |
| 20051 | - tokio::fs::remove_file(common::files_dir().join(&src_keys[0])) | |
| 20062 | + tokio::fs::remove_file(common::blob_dir().join(&src_keys[0])) | |
| 20052 | 20063 | .await |
| 20053 | 20064 | .unwrap(); |
| 20054 | 20065 | |
| @@ -20105,7 +20116,7 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() { | ||
| 20105 | 20116 | "source bank rows changed" |
| 20106 | 20117 | ); |
| 20107 | 20118 | assert!( |
| 20108 | - common::files_dir().join(&src_keys[1]).exists(), | |
| 20119 | + common::blob_dir().join(&src_keys[1]).exists(), | |
| 20109 | 20120 | "surviving source blob vanished" |
| 20110 | 20121 | ); |
| 20111 | 20122 | } |
| @@ -24478,7 +24489,9 @@ async fn the_statement_reports_overdue_and_its_rollup_matches_the_balance() { | ||
| 24478 | 24489 | "POST", |
| 24479 | 24490 | "/auth/login", |
| 24480 | 24491 | None, |
| 24481 | - Some(json!({ "username": "ali", "password": "secret1" })), | |
| 24492 | + Some( | |
| 24493 | + json!({ "school": "demo", "school": "demo", "username": "ali", "password": "secret1" }), | |
| 24494 | + ), | |
| 24482 | 24495 | ) |
| 24483 | 24496 | .await |
| 24484 | 24497 | .cookie |
| @@ -27171,7 +27184,7 @@ async fn course_note_cap_refusal_and_course_delete_leave_no_orphan_blobs() { | ||
| 27171 | 27184 | ) |
| 27172 | 27185 | .await; |
| 27173 | 27186 | assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); |
| 27174 | - blob_paths.push(common::files_dir().join(id_of(&r.body))); | |
| 27187 | + blob_paths.push(common::blob_dir().join(id_of(&r.body))); | |
| 27175 | 27188 | } |
| 27176 | 27189 | for p in &blob_paths { |
| 27177 | 27190 | assert!(p.exists(), "blob missing after upload: {p:?}"); |
tests/pagination.rsmodified+3 -2
| @@ -14,7 +14,7 @@ use serde_json::json; | ||
| 14 | 14 | async fn seed_students(app: &axum::Router, n: usize) { |
| 15 | 15 | for i in 0..n { |
| 16 | 16 | let name = format!("user{i:02}"); |
| 17 | - let creds = json!({ "username": name, "password": "secret1" }); | |
| 17 | + let creds = json!({ "school": "demo", "username": name, "password": "secret1" }); | |
| 18 | 18 | let res = send(app, "POST", "/auth/register", None, Some(creds)).await; |
| 19 | 19 | assert_eq!(res.status, StatusCode::CREATED, "register {name}"); |
| 20 | 20 | } |
| @@ -322,7 +322,8 @@ async fn user_search_is_paged_not_capped() { | ||
| 322 | 322 | let teacher = login_as(&app, &db, "teacher", "teacher").await; |
| 323 | 323 | // 12 accounts sharing the "grp" fragment — past the old cap. |
| 324 | 324 | for i in 0..12 { |
| 325 | - let creds = json!({ "username": format!("grp{i:02}"), "password": "secret1" }); | |
| 325 | + let creds = | |
| 326 | + json!({ "school": "demo", "username": format!("grp{i:02}"), "password": "secret1" }); | |
| 326 | 327 | let res = send(&app, "POST", "/auth/register", None, Some(creds)).await; |
| 327 | 328 | assert_eq!(res.status, StatusCode::CREATED); |
| 328 | 329 | } |
tests/persistence.rsmodified+31 -20
| @@ -13,6 +13,7 @@ use hezarfen_backend::database::Database; | ||
| 13 | 13 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 14 | 14 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 15 | 15 | use hezarfen_backend::state::AppState; |
| 16 | +use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; | |
| 16 | 17 | use hezarfen_backend::{build_router, database}; |
| 17 | 18 | use serde_json::json; |
| 18 | 19 | |
| @@ -20,8 +21,18 @@ use serde_json::json; | ||
| 20 | 21 | /// a fresh router over it. |
| 21 | 22 | async fn reboot(db: &Database) -> Router { |
| 22 | 23 | database::migrate(db).await.expect("re-migration"); |
| 24 | + // A new process: a new control database and a new connection cache, over | |
| 25 | + // the school store the old one left behind. | |
| 26 | + let tenants = Tenants::new_mem_adopting( | |
| 27 | + &Slug::try_new(DEMO_SLUG).unwrap(), | |
| 28 | + "Demo School", | |
| 29 | + db.clone(), | |
| 30 | + ) | |
| 31 | + .await | |
| 32 | + .expect("adopt the demo school"); | |
| 23 | 33 | build_router(AppState { |
| 24 | - db: db.clone(), | |
| 34 | + db: tenants.control().clone(), | |
| 35 | + tenants, | |
| 25 | 36 | files_path: common::files_dir(), |
| 26 | 37 | cookie_secure: false, |
| 27 | 38 | rate_limit: RateLimitConfig::unlimited(), |
| @@ -40,7 +51,7 @@ async fn reboot(db: &Database) -> Router { | ||
| 40 | 51 | async fn settings_and_terms_survive_remigration() { |
| 41 | 52 | let (app, db) = common::app_and_db().await; |
| 42 | 53 | |
| 43 | - let creds = json!({ "username": "boss", "password": "secret1" }); | |
| 54 | + let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); | |
| 44 | 55 | send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; |
| 45 | 56 | set_role(&db, "boss", "manager").await; |
| 46 | 57 | let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) |
| @@ -119,7 +130,7 @@ async fn settings_and_terms_survive_remigration() { | ||
| 119 | 130 | #[tokio::test] |
| 120 | 131 | async fn legacy_events_backfill_to_school_audience() { |
| 121 | 132 | let (app, db) = common::app_and_db().await; |
| 122 | - let creds = json!({ "username": "ali", "password": "secret1" }); | |
| 133 | + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 123 | 134 | |
| 124 | 135 | // A normal event — then strip its audience the way an old binary's schema |
| 125 | 136 | // would have left it: drop the column definitions so SCHEMAFULL stops |
| @@ -196,7 +207,7 @@ async fn legacy_events_backfill_to_school_audience() { | ||
| 196 | 207 | #[tokio::test] |
| 197 | 208 | async fn legacy_users_audiences_convert_to_registrations() { |
| 198 | 209 | let (app, db) = common::app_and_db().await; |
| 199 | - let creds = json!({ "username": "ali", "password": "secret1" }); | |
| 210 | + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 200 | 211 | |
| 201 | 212 | // A registration-audience event — then rewrite it into the shape an old |
| 202 | 213 | // binary left behind: restore the `audience.users` column definition and |
| @@ -212,7 +223,7 @@ async fn legacy_users_audiences_convert_to_registrations() { | ||
| 212 | 223 | .await |
| 213 | 224 | .cookie |
| 214 | 225 | .unwrap(); |
| 215 | - let student = json!({ "username": "veli", "password": "secret1" }); | |
| 226 | + let student = json!({ "school": "demo", "username": "veli", "password": "secret1" }); | |
| 216 | 227 | assert_eq!( |
| 217 | 228 | send(&app, "POST", "/auth/register", None, Some(student.clone())) |
| 218 | 229 | .await |
| @@ -294,7 +305,7 @@ async fn legacy_users_audiences_convert_to_registrations() { | ||
| 294 | 305 | #[tokio::test] |
| 295 | 306 | async fn legacy_subjectless_questions_are_destroyed_on_boot() { |
| 296 | 307 | let (app, db) = common::app_and_db().await; |
| 297 | - let creds = json!({ "username": "ali", "password": "secret1" }); | |
| 308 | + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 298 | 309 | |
| 299 | 310 | // A full exam — course, subject, open exam, one answered question — then |
| 300 | 311 | // 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() { | ||
| 310 | 321 | .await |
| 311 | 322 | .cookie |
| 312 | 323 | .unwrap(); |
| 313 | - let student = json!({ "username": "veli", "password": "secret1" }); | |
| 324 | + let student = json!({ "school": "demo", "username": "veli", "password": "secret1" }); | |
| 314 | 325 | assert_eq!( |
| 315 | 326 | send(&app, "POST", "/auth/register", None, Some(student.clone())) |
| 316 | 327 | .await |
| @@ -434,7 +445,7 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() { | ||
| 434 | 445 | #[tokio::test] |
| 435 | 446 | async fn stale_staff_enrollments_are_swept_on_boot() { |
| 436 | 447 | let (app, db) = common::app_and_db().await; |
| 437 | - let creds = json!({ "username": "ali", "password": "secret1" }); | |
| 448 | + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 438 | 449 | |
| 439 | 450 | // A course with three enrolled students, then age two rows the way a |
| 440 | 451 | // 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() { | ||
| 454 | 465 | |
| 455 | 466 | let mut ids = Vec::new(); |
| 456 | 467 | for name in ["veli", "ayse", "can"] { |
| 457 | - let student = json!({ "username": name, "password": "secret1" }); | |
| 468 | + let student = json!({ "school": "demo", "username": name, "password": "secret1" }); | |
| 458 | 469 | assert_eq!( |
| 459 | 470 | send(&app, "POST", "/auth/register", None, Some(student.clone())) |
| 460 | 471 | .await |
| @@ -646,8 +657,8 @@ async fn a_course_whose_count_outran_its_roster_is_repaired_and_deletable() { | ||
| 646 | 657 | #[tokio::test] |
| 647 | 658 | async fn legacy_exams_backfill_to_published() { |
| 648 | 659 | let (app, db) = common::app_and_db().await; |
| 649 | - let teacher_creds = json!({ "username": "ali", "password": "secret1" }); | |
| 650 | - let student_creds = json!({ "username": "ayse", "password": "secret1" }); | |
| 660 | + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 661 | + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); | |
| 651 | 662 | |
| 652 | 663 | // A normal exam — then strip `draft` the way an old binary's schema would |
| 653 | 664 | // have left it. |
| @@ -732,8 +743,8 @@ async fn appointments_survive_remigration() { | ||
| 732 | 743 | const PROPOSED_END: i64 = START + 8_000_003; |
| 733 | 744 | |
| 734 | 745 | let (app, db) = common::app_and_db().await; |
| 735 | - let teacher_creds = json!({ "username": "ali", "password": "secret1" }); | |
| 736 | - let student_creds = json!({ "username": "ayse", "password": "secret1" }); | |
| 746 | + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 747 | + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); | |
| 737 | 748 | for creds in [&teacher_creds, &student_creds] { |
| 738 | 749 | assert_eq!( |
| 739 | 750 | send(&app, "POST", "/auth/register", None, Some((*creds).clone())) |
| @@ -879,8 +890,8 @@ async fn appointments_survive_remigration() { | ||
| 879 | 890 | #[tokio::test] |
| 880 | 891 | async fn attempt_history_survives_remigration() { |
| 881 | 892 | let (app, db) = common::app_and_db().await; |
| 882 | - let teacher_creds = json!({ "username": "ali", "password": "secret1" }); | |
| 883 | - let student_creds = json!({ "username": "ayse", "password": "secret1" }); | |
| 893 | + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 894 | + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); | |
| 884 | 895 | for creds in [&teacher_creds, &student_creds] { |
| 885 | 896 | assert_eq!( |
| 886 | 897 | send(&app, "POST", "/auth/register", None, Some((*creds).clone())) |
| @@ -1164,7 +1175,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() { | ||
| 1164 | 1175 | use hezarfen_backend::domain::user::UserId; |
| 1165 | 1176 | |
| 1166 | 1177 | let (app, db) = common::app_and_db().await; |
| 1167 | - let creds = json!({ "username": "ali", "password": "secret1" }); | |
| 1178 | + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 1168 | 1179 | assert_eq!( |
| 1169 | 1180 | send(&app, "POST", "/auth/register", None, Some(creds.clone())) |
| 1170 | 1181 | .await |
| @@ -1244,7 +1255,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() { | ||
| 1244 | 1255 | async fn settings_slots_without_a_serving_minute_still_patch() { |
| 1245 | 1256 | let (app, db) = common::app_and_db().await; |
| 1246 | 1257 | |
| 1247 | - let creds = json!({ "username": "boss", "password": "secret1" }); | |
| 1258 | + let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); | |
| 1248 | 1259 | send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; |
| 1249 | 1260 | set_role(&db, "boss", "manager").await; |
| 1250 | 1261 | 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 | ||
| 1948 | 1959 | #[tokio::test] |
| 1949 | 1960 | async fn fee_plans_and_their_charges_survive_remigration() { |
| 1950 | 1961 | let (app, db) = common::app_and_db().await; |
| 1951 | - let manager_creds = json!({ "username": "ali", "password": "secret1" }); | |
| 1952 | - let student_creds = json!({ "username": "ayse", "password": "secret1" }); | |
| 1962 | + let manager_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 1963 | + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); | |
| 1953 | 1964 | for creds in [&manager_creds, &student_creds] { |
| 1954 | 1965 | assert_eq!( |
| 1955 | 1966 | 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() { | ||
| 2102 | 2113 | #[tokio::test] |
| 2103 | 2114 | async fn boards_and_their_strokes_survive_remigration() { |
| 2104 | 2115 | let (app, db) = common::app_and_db().await; |
| 2105 | - let creds = json!({ "username": "ali", "password": "secret1" }); | |
| 2116 | + let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | |
| 2106 | 2117 | let cookie = common::login(&app, "ali").await; |
| 2107 | 2118 | let veli = common::login(&app, "veli").await; |
| 2108 | 2119 | let ali_id = me_id(&app, &cookie).await; |
tests/rate_limit.rsmodified+14 -8
| @@ -18,9 +18,12 @@ use tower::ServiceExt; | ||
| 18 | 18 | |
| 19 | 19 | /// App with the given limits, backed by a fresh in-memory database. |
| 20 | 20 | async fn app_with(rate_limit: RateLimitConfig) -> Router { |
| 21 | - let db = database::init_mem().await.expect("in-memory db"); | |
| 21 | + let tenants = database::init_mem_tenants() | |
| 22 | + .await | |
| 23 | + .expect("in-memory deployment"); | |
| 22 | 24 | build_router(AppState { |
| 23 | - db, | |
| 25 | + db: tenants.control().clone(), | |
| 26 | + tenants, | |
| 24 | 27 | files_path: tempfile::tempdir().expect("files dir").keep(), |
| 25 | 28 | cookie_secure: false, |
| 26 | 29 | rate_limit, |
| @@ -68,7 +71,7 @@ async fn send_as( | ||
| 68 | 71 | } |
| 69 | 72 | |
| 70 | 73 | fn bad_login() -> Option<Value> { |
| 71 | - Some(json!({ "username": "ghost", "password": "wrong-pass" })) | |
| 74 | + Some(json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" })) | |
| 72 | 75 | } |
| 73 | 76 | |
| 74 | 77 | fn auth_only(per_minute: u32) -> RateLimitConfig { |
| @@ -103,7 +106,7 @@ async fn login_attempts_hit_the_auth_limit() { | ||
| 103 | 106 | #[tokio::test] |
| 104 | 107 | async fn register_and_login_share_the_auth_bucket() { |
| 105 | 108 | let app = app_with(auth_only(2)).await; |
| 106 | - let creds = json!({ "username": "ada", "password": "secret1" }); | |
| 109 | + let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" }); | |
| 107 | 110 | |
| 108 | 111 | let (status, _, _) = send_as( |
| 109 | 112 | &app, |
| @@ -530,9 +533,12 @@ async fn a_down_database_leaves_each_process_on_its_local_budget() { | ||
| 530 | 533 | |
| 531 | 534 | /// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`. |
| 532 | 535 | async fn spawn_server(rate_limit: RateLimitConfig) -> String { |
| 533 | - let db = database::init_mem().await.expect("in-memory db"); | |
| 536 | + let tenants = database::init_mem_tenants() | |
| 537 | + .await | |
| 538 | + .expect("in-memory deployment"); | |
| 534 | 539 | let app = build_router(AppState { |
| 535 | - db, | |
| 540 | + db: tenants.control().clone(), | |
| 541 | + tenants, | |
| 536 | 542 | files_path: tempfile::tempdir().expect("files dir").keep(), |
| 537 | 543 | cookie_secure: false, |
| 538 | 544 | rate_limit, |
| @@ -571,7 +577,7 @@ async fn real_connections_are_keyed_by_peer_address() { | ||
| 571 | 577 | let res = client |
| 572 | 578 | .post(format!("{base}/auth/login")) |
| 573 | 579 | .header("x-forwarded-for", spoof) |
| 574 | - .json(&json!({ "username": "ghost", "password": "wrong-pass" })) | |
| 580 | + .json(&json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" })) | |
| 575 | 581 | .send() |
| 576 | 582 | .await |
| 577 | 583 | .unwrap(); |
| @@ -581,7 +587,7 @@ async fn real_connections_are_keyed_by_peer_address() { | ||
| 581 | 587 | let res = client |
| 582 | 588 | .post(format!("{base}/auth/login")) |
| 583 | 589 | .header("x-forwarded-for", "3.3.3.3") |
| 584 | - .json(&json!({ "username": "ghost", "password": "wrong-pass" })) | |
| 590 | + .json(&json!({ "school": "demo", "username": "ghost", "password": "wrong-pass" })) | |
| 585 | 591 | .send() |
| 586 | 592 | .await |
| 587 | 593 | .unwrap(); |
tests/regress_bank_images.rsmodified+10 -4
| @@ -27,6 +27,7 @@ mod common; | ||
| 27 | 27 | use axum::Router; |
| 28 | 28 | use axum::http::StatusCode; |
| 29 | 29 | use common::{create_course, create_subject, id_of, login_as, send}; |
| 30 | +use hezarfen_backend::build_router; | |
| 30 | 31 | use hezarfen_backend::database::Database; |
| 31 | 32 | use hezarfen_backend::domain::bank_question::BankQuestionId; |
| 32 | 33 | use hezarfen_backend::domain::bank_question_image::BankQuestionImage; |
| @@ -34,7 +35,6 @@ use hezarfen_backend::domain::note_file::FileContentType; | ||
| 34 | 35 | use hezarfen_backend::error::AppError; |
| 35 | 36 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 36 | 37 | use hezarfen_backend::state::AppState; |
| 37 | -use hezarfen_backend::{build_router, database}; | |
| 38 | 38 | use serde_json::json; |
| 39 | 39 | use tempfile::TempDir; |
| 40 | 40 | |
| @@ -43,10 +43,11 @@ const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary"; | ||
| 43 | 43 | /// A router over a fresh in-memory database, with a blob directory nothing else |
| 44 | 44 | /// writes to — so `blobs()` counts this test's files and no one else's. |
| 45 | 45 | async fn mem_app() -> (Router, Database, TempDir) { |
| 46 | - let db = database::init_mem().await.expect("in-memory db"); | |
| 46 | + let (tenants, db) = common::mem_deployment().await; | |
| 47 | 47 | let files = tempfile::tempdir().expect("files tempdir"); |
| 48 | 48 | let app = build_router(AppState { |
| 49 | - db: db.clone(), | |
| 49 | + db: tenants.control().clone(), | |
| 50 | + tenants, | |
| 50 | 51 | files_path: files.path().to_path_buf(), |
| 51 | 52 | cookie_secure: false, |
| 52 | 53 | rate_limit: RateLimitConfig::unlimited(), |
| @@ -61,7 +62,12 @@ async fn mem_app() -> (Router, Database, TempDir) { | ||
| 61 | 62 | |
| 62 | 63 | /// Every blob file currently on disk, by name. |
| 63 | 64 | fn blobs(files: &TempDir) -> Vec<String> { |
| 64 | - let mut names: Vec<String> = std::fs::read_dir(files.path()) | |
| 65 | + // Blobs live under the school's own subdirectory of `FILES_PATH`. | |
| 66 | + let dir = files.path().join(hezarfen_backend::tenant::DEMO_SLUG); | |
| 67 | + if !dir.exists() { | |
| 68 | + return Vec::new(); | |
| 69 | + } | |
| 70 | + let mut names: Vec<String> = std::fs::read_dir(&dir) | |
| 65 | 71 | .expect("read the blob dir") |
| 66 | 72 | .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) |
| 67 | 73 | .collect(); |
tests/regress_profile.rsmodified+1 -1
| @@ -47,7 +47,7 @@ async fn upload_avatar( | ||
| 47 | 47 | /// by every app in this binary, so a payload no other test writes is the only |
| 48 | 48 | /// concurrency-safe way to count one test's own blobs. |
| 49 | 49 | fn blobs_holding(bytes: &[u8]) -> usize { |
| 50 | - std::fs::read_dir(common::files_dir()) | |
| 50 | + std::fs::read_dir(common::blob_dir()) | |
| 51 | 51 | .expect("files dir") |
| 52 | 52 | .filter_map(|entry| std::fs::read(entry.expect("dir entry").path()).ok()) |
| 53 | 53 | .filter(|found| found == bytes) |
tests/regress_roles.rsmodified+2 -1
| @@ -196,7 +196,8 @@ async fn a_promotion_keeps_the_signup_the_promoted_user_can_still_free() { | ||
| 196 | 196 | "/auth/login", |
| 197 | 197 | None, |
| 198 | 198 | Some(json!({ |
| 199 | - "username": "ali", "password": "secret1" | |
| 199 | + "school": "demo", | |
| 200 | + "school": "demo", "username": "ali", "password": "secret1" | |
| 200 | 201 | })), |
| 201 | 202 | ) |
| 202 | 203 | .await |
tests/spec_bounds.rsmodified+7 -2
| @@ -24,9 +24,12 @@ use tower::ServiceExt; | ||
| 24 | 24 | |
| 25 | 25 | /// The emitted OpenAPI document, as the server serves it. |
| 26 | 26 | async fn spec() -> Value { |
| 27 | - let db = database::init_mem().await.expect("in-memory db"); | |
| 27 | + let tenants = database::init_mem_tenants() | |
| 28 | + .await | |
| 29 | + .expect("in-memory deployment"); | |
| 28 | 30 | let app = build_router(AppState { |
| 29 | - db, | |
| 31 | + db: tenants.control().clone(), | |
| 32 | + tenants, | |
| 30 | 33 | files_path: tempfile::tempdir().expect("files dir").keep(), |
| 31 | 34 | cookie_secure: false, |
| 32 | 35 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| @@ -59,6 +62,8 @@ async fn spec() -> Value { | ||
| 59 | 62 | fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { |
| 60 | 63 | vec![ |
| 61 | 64 | // --- auth / users / notes / messages --- |
| 65 | + ("Credentials", "school", "minLength", MIN_SLUG_LEN as i64), | |
| 66 | + ("Credentials", "school", "maxLength", MAX_SLUG_LEN as i64), | |
| 62 | 67 | ( |
| 63 | 68 | "Credentials", |
| 64 | 69 | "username", |