From 5d7f87ca136849ee5310cdbd60055db690e95bdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 01:29:44 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20per-school=20modules;=20a?= =?UTF-8?q?=20disabled=20module=20answers=20403=20on=20every=20route=20in?= =?UTF-8?q?=20its=20nest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Twenty-one modules, one per router nest, with an explicit dependency graph derived from the record links (exams need courses and subjects, marks need exams, …) and four packages for the catalog. The enabled set lives on the school's control row and rides the tenant resolution that already happens once per request; every nest carries a route_layer gate, the four child creates inside /courses are gated by their own module, and the AI blob stream refuses `module_disabled` when course notes are off. --- README.md | 8 +- src/ai/server.rs | 32 ++- src/database.rs | 15 +- src/error.rs | 34 ++++ src/lib.rs | 117 +++++++++-- src/migration_sql.rs | 8 + src/module.rs | 425 ++++++++++++++++++++++++++++++++++++++++ src/tenant.rs | 90 ++++++++- src/web/board_ws.rs | 2 + src/web/builder.rs | 7 +- src/web/chatbot.rs | 4 +- src/web/courses.rs | 25 ++- src/web/extractor.rs | 2 +- src/web/mod.rs | 1 + src/web/module_gate.rs | 71 +++++++ src/web/room.rs | 4 + src/web/tenant_state.rs | 101 +++++++++- tests/ai_bridge.rs | 6 +- tests/ai_protocol.rs | 7 +- tests/common/mod.rs | 7 +- tests/integration.rs | 126 +++++++++++- tests/persistence.rs | 72 +++++++ 22 files changed, 1101 insertions(+), 63 deletions(-) create mode 100644 src/module.rs create mode 100644 src/web/module_gate.rs diff --git a/README.md b/README.md index 1d96404..0bd648d 100644 --- a/README.md +++ b/README.md @@ -3816,6 +3816,7 @@ slow-but-reading service is never cut off. | `not_found` | No `course_note_file` with that key *in that school*, or its note or course is gone | | `forbidden` | The principal may not view that file's course | | `unknown_school` / `school_suspended` | As for an api read | +| `module_disabled` | That school has no `course_notes` module — this stream bypasses the router, so it checks the entitlement itself | | `unknown_user` | `on_behalf_of` names no user of that school | | `unavailable` | The api is not serving yet, the database socket is down, or the row's blob is missing from disk — retryable | @@ -4502,6 +4503,8 @@ src/ migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR, MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them, and CONTROL_MIGRATION_BATCHES for the control database + module.rs Module (one router nest a school may buy) · Package · + ModuleSet: dependency edges, validation, stored names rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier state.rs AppState { db, tenants, files_path, cookie_secure, rate_limit, chatbot_limit, exam_presence, board_hub, db_up, ai } @@ -4660,7 +4663,10 @@ src/ tenant_state.rs State: the shadow of axum's State that resolves the caller's school from the `.` cookie, so every handler that imports it is school-scoped by construction - (TenantExt · SchoolSlug · split_cookie) + (ResolvedTenant · TenantExt · SchoolSlug · split_cookie) + module_gate.rs one route_layer per nest: a module the school has not bought + answers 403 {error, module} on every route in it, while an + unmatched path inside it still 404s builder.rs the vendor surface: /builder/login|logout|me and /schools/* (create · list · rename/suspend · delete · admin-password · enter) image.rs the halves every image upload shares: the `file` part under the diff --git a/src/ai/server.rs b/src/ai/server.rs index e9064f2..857fd7f 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -29,12 +29,13 @@ use crate::domain::course_note::CourseNote; use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; use crate::domain::user::{User, UserId}; use crate::error::AppError; +use crate::module::Module; use crate::state::DbHealth; use crate::tenant::{Slug, Tenants}; use crate::web::blob_path; use crate::web::courses::can_view_course; use crate::web::extractor::AiPrincipal; -use crate::web::tenant_state::{TenantExt, school_files_path}; +use crate::web::tenant_state::{ResolvedTenant, TenantExt, school_files_path}; /// What the bridge needs to come up. #[derive(Clone, Debug)] @@ -74,14 +75,14 @@ impl ApiHandle { /// has no such customer, and `school_suspended` means it has one that is /// switched off — a service that retries the first two forever learns /// nothing, while the third is worth retrying later. - async fn school(&self, school: &str) -> Result<(Slug, Database), (&'static str, String)> { + async fn school(&self, school: &str) -> Result { let slug = Slug::try_new(school).map_err(|err| { ( "malformed", format!("`{school}` is not a school slug: {err}"), ) })?; - let db = self.tenants.get(&slug).await.map_err(|err| match err { + self.tenants.resolve(&slug).await.map_err(|err| match err { AppError::Unauthorized => ( "unknown_school", format!("this deployment serves no `{slug}` school"), @@ -94,8 +95,7 @@ impl ApiHandle { "unavailable", format!("the `{slug}` school is not reachable: {other}"), ), - })?; - Ok((slug, db)) + }) } /// One school's blob directory. @@ -531,7 +531,16 @@ async fn open_blob( "the database socket is down — retry".to_string(), )); } - let (slug, db) = api.school(&request.school).await?; + let tenant = api.school(&request.school).await?; + let (slug, db) = (tenant.slug, tenant.db); + // This stream bypasses the router, so it also bypasses the route_layer the + // module gate is — the entitlement is checked here by hand instead. + if !tenant.modules.contains(Module::CourseNotes) { + return Err(( + "module_disabled", + format!("the `{slug}` school has no `course_notes` module"), + )); + } let user = principal(&db, request.on_behalf_of.as_deref()).await?; let missing = || { @@ -695,7 +704,8 @@ async fn dispatch_api( // The school comes off the frame, so this is where a service naming a // stranger's slug (or a suspended school's) is stopped — before a row of // anyone's data is read. - let (slug, db) = api.school(&school).await?; + let tenant = api.school(&school).await?; + let db = tenant.db.clone(); // The role itself is re-read again by the extractor on the dispatched // request; see [`principal`] for why it is never taken from the frame. let user = principal(&db, on_behalf_of.as_deref()).await?; @@ -719,7 +729,13 @@ async fn dispatch_api( dispatched.extensions_mut().insert(AiPrincipal(user)); // The dispatched request carries no cookie, so the school is handed over // in the extension the shadow `State` reads first. - dispatched.extensions_mut().insert(TenantExt { slug, db }); + // Carries the school's entitlements too, so the router's module gate + // refuses a disabled nest on this path exactly as it does over HTTP. + dispatched.extensions_mut().insert(TenantExt { + slug: tenant.slug, + db, + modules: tenant.modules, + }); let response = tokio::time::timeout( Duration::from_secs(REQUEST_TIMEOUT_SECS), diff --git a/src/database.rs b/src/database.rs index db80534..90de618 100644 --- a/src/database.rs +++ b/src/database.rs @@ -273,7 +273,9 @@ pub async fn init_mem_tenants() -> Result { let tenants = Tenants::new_mem().await?; let demo = crate::tenant::Slug::try_new(crate::tenant::DEMO_SLUG) .map_err(|err| AppError::Internal(format!("the demo slug is a slug: {err}")))?; - tenants.create(&demo, "Demo School").await?; + tenants + .create(&demo, "Demo School", crate::module::ModuleSet::all()) + .await?; Ok(tenants) } @@ -374,11 +376,16 @@ pub async fn migrate(db: &Surreal) -> Result<(), AppError> { } /// Apply the **control** schema (schools, builders, the shared rate-limit -/// window). Idempotent, like [`migrate`], and takes no bound parameters — -/// nothing in the control batch is data-driven. +/// window). Idempotent, like [`migrate`]. pub async fn migrate_control(db: &Surreal) -> Result<(), AppError> { + // The one data-driven parameter in this batch: the module list a school + // written before entitlements existed is backfilled to. + let all_modules = crate::module::ModuleSet::all().names(); for sql in CONTROL_MIGRATION_BATCHES { - db.query(sql).await?.check()?; + db.query(sql) + .bind(("all_modules", all_modules.clone())) + .await? + .check()?; } Ok(()) } diff --git a/src/error.rs b/src/error.rs index 554e639..32f7ba0 100644 --- a/src/error.rs +++ b/src/error.rs @@ -42,6 +42,12 @@ pub enum ValidationError { field: &'static str, reason: &'static str, }, + /// A closed value set refused a name it does not contain — and says which + /// name, which [`ValidationError::Invalid`] cannot: its `reason` is + /// `&'static str`, so the offending value could only be described, never + /// quoted. + #[error("{field}: `{value}` is not a known {field}")] + Unknown { field: &'static str, value: String }, } /// The single error type every fallible operation returns. @@ -55,6 +61,11 @@ pub enum AppError { Unauthorized, #[error("forbidden: {0}")] Forbidden(&'static str), + /// The school has not bought this module. A dedicated arm because the body + /// carries a second key — the module's name — so a client can tell "your + /// school does not have this" from every other `403` without parsing prose. + #[error("module disabled: {0}")] + ModuleDisabled(crate::module::Module), #[error("conflict: {0}")] Conflict(&'static str), /// A 409 whose message is only known at runtime — e.g. the specific @@ -168,6 +179,14 @@ impl IntoResponse for AppError { ) .into_response(); } + // Also carries a second key: which module was refused. + AppError::ModuleDisabled(module) => { + return ( + StatusCode::FORBIDDEN, + Json(json!({ "error": "module disabled", "module": module.as_str() })), + ) + .into_response(); + } AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()), AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), @@ -219,6 +238,21 @@ mod tests { assert!(matches!(AppError::from(e), AppError::DbUnavailable)); } + /// The refusal a gated nest answers with. Both keys, and the `403` — a + /// client switches on `module`, so neither may drift. + #[tokio::test] + async fn a_disabled_module_is_a_403_naming_itself() { + use crate::module::Module; + let response = AppError::ModuleDisabled(Module::CourseNotes).into_response(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + let body = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + let body: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["error"], "module disabled"); + assert_eq!(body["module"], "course_notes"); + } + #[test] fn real_errors_stay_db_errors() { // A genuine authorization verdict shares the suffix but must not match. diff --git a/src/lib.rs b/src/lib.rs index 6a36d1c..d1b1771 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod database; pub mod domain; pub mod error; pub mod migration_sql; +pub mod module; pub mod rate_limit; pub mod state; pub mod tenant; @@ -27,8 +28,10 @@ use utoipa_axum::routes; use utoipa_swagger_ui::SwaggerUi; use crate::error::AppError; +use crate::module::Module; use crate::rate_limit::RateLimiter; use crate::state::AppState; +use crate::web::module_gate::gate; /// Top-level OpenAPI document. Per-path operations and schemas are collected /// automatically from the `#[utoipa::path]`-annotated handlers via `utoipa-axum`. @@ -88,6 +91,33 @@ impl Modify for SecurityAddon { } } +/// `/courses` and the four foreign-module route pairs mounted inside it. The +/// children carry their own module's gate *and*, through the outer one applied +/// here, the course gate — so either module being off refuses them. +fn courses_router(state: &AppState) -> OpenApiRouter { + let children = gate(web::courses::exam_routes(), state, Module::Exams) + .merge(gate( + web::courses::session_routes(), + state, + Module::Sessions, + )) + .merge(gate( + web::courses::subject_routes(), + state, + Module::Subjects, + )) + .merge(gate( + web::courses::homework_routes(), + state, + Module::Homework, + )); + gate( + web::courses::routes().merge(children), + state, + Module::Courses, + ) +} + /// Assemble the full application router. Shared by `main` and the test suites. /// /// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at @@ -101,30 +131,75 @@ pub fn build_router(state: AppState) -> Router { .nest("/ai", web::ai::routes()) .nest("/auth", web::auth::routes(&state)) .merge(web::builder::routes(&state)) - .nest("/chatbot", web::chatbot::routes()) + .nest( + "/chatbot", + gate(web::chatbot::routes(), &state, Module::Chatbot), + ) .nest("/users", web::users::routes()) - .nest("/notes", web::notes::routes()) - .nest("/messages", web::messages::routes()) - .nest("/events", web::events::routes()) - .nest("/appointments", web::appointments::routes()) - .nest("/courses", web::courses::routes()) - .nest("/course-notes", web::course_notes::routes()) - .nest("/classes", web::classes::routes()) - .nest("/sessions", web::sessions::routes()) - .nest("/exams", web::exams::routes()) - .nest("/marks", web::marks::routes()) - .nest("/meals", web::meals::routes()) - .nest("/payments", web::payments::routes()) - .nest("/work", web::work::routes()) - .nest("/pomodoro", web::pomodoro::routes()) - .nest("/questions", web::questions::routes()) - .nest("/bank-questions", web::bank_questions::routes()) - .nest("/attendance", web::attendance::routes()) + .nest("/notes", gate(web::notes::routes(), &state, Module::Notes)) + .nest( + "/messages", + gate(web::messages::routes(), &state, Module::Messages), + ) + .nest( + "/events", + gate(web::events::routes(), &state, Module::Events), + ) + .nest( + "/appointments", + gate(web::appointments::routes(), &state, Module::Appointments), + ) + .nest("/courses", courses_router(&state)) + .nest( + "/course-notes", + gate(web::course_notes::routes(), &state, Module::CourseNotes), + ) + .nest( + "/classes", + gate(web::classes::routes(), &state, Module::Classes), + ) + .nest( + "/sessions", + gate(web::sessions::routes(), &state, Module::Sessions), + ) + .nest("/exams", gate(web::exams::routes(), &state, Module::Exams)) + .nest("/marks", gate(web::marks::routes(), &state, Module::Marks)) + .nest("/meals", gate(web::meals::routes(), &state, Module::Meals)) + .nest( + "/payments", + gate(web::payments::routes(), &state, Module::Payments), + ) + .nest("/work", gate(web::work::routes(), &state, Module::Work)) + .nest( + "/pomodoro", + gate(web::pomodoro::routes(), &state, Module::Pomodoro), + ) + .nest( + "/questions", + gate(web::questions::routes(), &state, Module::Questions), + ) + .nest( + "/bank-questions", + gate(web::bank_questions::routes(), &state, Module::BankQuestions), + ) + .nest( + "/attendance", + gate(web::attendance::routes(), &state, Module::Attendance), + ) .nest("/settings", web::settings::routes()) - .nest("/subjects", web::subjects::routes()) - .nest("/homework", web::homework::routes()) + .nest( + "/subjects", + gate(web::subjects::routes(), &state, Module::Subjects), + ) + .nest( + "/homework", + gate(web::homework::routes(), &state, Module::Homework), + ) .nest("/terms", web::terms::routes()) - .nest("/boards", web::boards::routes()) + .nest( + "/boards", + gate(web::boards::routes(), &state, Module::Boards), + ) .split_for_parts(); // Catch-all per-IP limit over every route (Swagger included). Kept inside diff --git a/src/migration_sql.rs b/src/migration_sql.rs index c347772..c558022 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -1477,6 +1477,14 @@ pub const CONTROL_MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS name ON school TYPE string; DEFINE FIELD IF NOT EXISTS status ON school TYPE string; DEFINE FIELD IF NOT EXISTS created_at ON school TYPE int; + -- Which product modules this school has bought (see `crate::module`). The + -- names are bound from `Module::ALL`, never spelled here, so a new module + -- cannot be forgotten in this string. + DEFINE FIELD IF NOT EXISTS modules ON school TYPE array DEFAULT []; + -- Only `NONE` — a row written before the field existed, which predates the + -- idea of buying modules and so had all of them. An empty array is a + -- deliberate \"nothing enabled\" and must never be re-widened by a boot. + UPDATE school SET modules = $all_modules WHERE modules = NONE; -- Redundant with the `school:` id, and kept anyway: the id is the -- fast path, the index is what makes a second row on the same slug -- impossible if a future write ever mints an id some other way. diff --git a/src/module.rs b/src/module.rs new file mode 100644 index 0000000..a5cbe66 --- /dev/null +++ b/src/module.rs @@ -0,0 +1,425 @@ +//! Per-school **module entitlements**: which parts of the product a school has +//! bought. A module is exactly one router nest (`/meals`, `/exams`, …), so the +//! unit a school is sold and the unit the router refuses are the same thing — +//! there is no per-route entitlement to keep in sync with a per-route guard. +//! +//! A disabled module answers `403 {"error":"module disabled","module":""}` +//! on every route in its nest ([`crate::web::module_gate`]), while an unmatched +//! path inside it still `404`s, because the gate is a `route_layer`. +//! +//! Stored on the school registry row as bare lowercase strings, like +//! [`crate::tenant::SchoolStatus`] — see [`crate::tenant::School::modules`]. + +use std::collections::BTreeSet; + +use serde::Serialize; + +use crate::error::{AppError, ValidationError}; + +/// One router nest a school may have switched on or off. +/// +/// `Ord` is the declaration order and is only ever used to key the +/// [`ModuleSet`] — every user-visible ordering goes through +/// [`ModuleSet::names`], which sorts the strings. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Module { + Chatbot, + Notes, + Messages, + Events, + Appointments, + Courses, + CourseNotes, + Classes, + Sessions, + Exams, + Marks, + Meals, + Payments, + Work, + Pomodoro, + Questions, + BankQuestions, + Attendance, + Subjects, + Homework, + Boards, +} + +/// The commercial bundle a module is sold in. A package is a name for a set of +/// modules and nothing more — entitlement is always stored per module, so a +/// re-packaging never has to migrate a school's row. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Package { + Academics, + Communication, + Operations, + Ai, +} + +impl Module { + pub const ALL: [Module; 21] = [ + Module::Chatbot, + Module::Notes, + Module::Messages, + Module::Events, + Module::Appointments, + Module::Courses, + Module::CourseNotes, + Module::Classes, + Module::Sessions, + Module::Exams, + Module::Marks, + Module::Meals, + Module::Payments, + Module::Work, + Module::Pomodoro, + Module::Questions, + Module::BankQuestions, + Module::Attendance, + Module::Subjects, + Module::Homework, + Module::Boards, + ]; + + pub fn as_str(self) -> &'static str { + match self { + Module::Chatbot => "chatbot", + Module::Notes => "notes", + Module::Messages => "messages", + Module::Events => "events", + Module::Appointments => "appointments", + Module::Courses => "courses", + Module::CourseNotes => "course_notes", + Module::Classes => "classes", + Module::Sessions => "sessions", + Module::Exams => "exams", + Module::Marks => "marks", + Module::Meals => "meals", + Module::Payments => "payments", + Module::Work => "work", + Module::Pomodoro => "pomodoro", + Module::Questions => "questions", + Module::BankQuestions => "bank_questions", + Module::Attendance => "attendance", + Module::Subjects => "subjects", + Module::Homework => "homework", + Module::Boards => "boards", + } + } + + pub fn try_from_str(value: &str) -> Result { + Module::ALL + .into_iter() + .find(|m| m.as_str() == value) + .ok_or_else(|| ValidationError::Unknown { + field: "module", + value: value.to_string(), + }) + } + + /// The modules this one cannot work without. Every edge is a hard + /// structural reference — a `record<…>` field in + /// [`crate::migration_sql`] or a handler that reads the other module's row + /// — never a merely-nicer-together pairing; the evidence is on each line. + pub fn requires(self) -> &'static [Module] { + match self { + // `DEFINE FIELD course ON subject TYPE record` + Module::Subjects => &[Module::Courses], + // `DEFINE FIELD course ON course_note TYPE record` + Module::CourseNotes => &[Module::Courses], + // `DEFINE FIELD course ON course_session TYPE record` + Module::Sessions => &[Module::Courses], + // `DEFINE FIELD course ON exam TYPE record` + + // `DEFINE FIELD subject ON exam_question TYPE record` + Module::Exams => &[Module::Courses, Module::Subjects], + // `DEFINE FIELD course ON homework TYPE record` + + // `DEFINE FIELD subject ON homework TYPE record` + Module::Homework => &[Module::Courses, Module::Subjects], + // `DEFINE FIELD course ON class_course TYPE record` — a + // class is bulk enrollment into courses. + Module::Classes => &[Module::Courses], + // `DEFINE FIELD exam ON exam_result TYPE record`; the marks + // report is a weighted read of exam results. + Module::Marks => &[Module::Exams], + // The report tallies both halves: `attendance.event + // record` and `session_attendance.session + // record`. + Module::Attendance => &[Module::Events, Module::Sessions], + // No edge: `bank_question.subject` is `option>`, + // so a bank question stands on its own. + _ => &[], + } + } + + pub fn package(self) -> Package { + match self { + Module::Courses + | Module::Subjects + | Module::Sessions + | Module::Exams + | Module::Marks + | Module::Homework + | Module::Classes + | Module::CourseNotes + | Module::Attendance + | Module::BankQuestions => Package::Academics, + Module::Notes + | Module::Messages + | Module::Events + | Module::Appointments + | Module::Questions + | Module::Boards => Package::Communication, + Module::Meals | Module::Payments | Module::Work | Module::Pomodoro => { + Package::Operations + } + Module::Chatbot => Package::Ai, + } + } + + /// The modules that require this one — the reverse of [`Module::requires`], + /// derived rather than written down, so the two can never disagree. + pub fn dependents(self) -> Vec { + Module::ALL + .into_iter() + .filter(|other| other.requires().contains(&self)) + .collect() + } +} + +impl std::fmt::Display for Module { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +impl Package { + pub const ALL: [Package; 4] = [ + Package::Academics, + Package::Communication, + Package::Operations, + Package::Ai, + ]; + + pub fn as_str(self) -> &'static str { + match self { + Package::Academics => "academics", + Package::Communication => "communication", + Package::Operations => "operations", + Package::Ai => "ai", + } + } + + pub fn try_from_str(value: &str) -> Result { + Package::ALL + .into_iter() + .find(|p| p.as_str() == value) + .ok_or_else(|| ValidationError::Unknown { + field: "package", + value: value.to_string(), + }) + } + + /// The modules this package sells, derived from [`Module::package`]. + pub fn modules(self) -> Vec { + Module::ALL + .into_iter() + .filter(|m| m.package() == self) + .collect() + } +} + +/// What one school has switched on. Ordered, so a set has exactly one +/// serialization and a diff between two schools reads the same every time. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ModuleSet(BTreeSet); + +impl ModuleSet { + pub fn all() -> Self { + ModuleSet(Module::ALL.into_iter().collect()) + } + + pub fn empty() -> Self { + ModuleSet(BTreeSet::new()) + } + + pub fn contains(&self, module: Module) -> bool { + self.0.contains(&module) + } + + pub fn insert(&mut self, module: Module) { + self.0.insert(module); + } + + pub fn remove(&mut self, module: Module) { + self.0.remove(&module); + } + + pub fn iter(&self) -> impl Iterator + '_ { + self.0.iter().copied() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Parse a client-supplied list. An unknown name is refused by name rather + /// than dropped: silently ignoring it would sell a school a module that + /// does not exist and report success. + pub fn from_names(names: &[String]) -> Result { + let mut set = BTreeSet::new(); + for name in names { + set.insert(Module::try_from_str(name)?); + } + Ok(ModuleSet(set)) + } + + /// The stored form: sorted, so the row is byte-stable. + pub fn names(&self) -> Vec { + let mut names: Vec = self.iter().map(|m| m.as_str().to_string()).collect(); + names.sort(); + names + } + + /// Every `(module, missing requirement)` pair this set holds, in a stable + /// order. + pub fn missing_requirements(&self) -> Vec<(Module, Module)> { + self.iter() + .flat_map(|module| { + module + .requires() + .iter() + .filter(|needed| !self.contains(**needed)) + .map(move |needed| (module, *needed)) + }) + .collect() + } + + /// Refuse a set that switches a module on without what it structurally + /// needs. One `409` naming **every** violation, so a caller fixing a set + /// does not discover them one round trip at a time. + pub fn validate(&self) -> Result<(), AppError> { + let missing = self.missing_requirements(); + if missing.is_empty() { + return Ok(()); + } + let message = missing + .into_iter() + .map(|(module, needed)| format!("{module} requires {needed}, which is not enabled")) + .collect::>() + .join("; "); + Err(AppError::ConflictOwned(message)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_module_names_itself_and_round_trips() { + assert_eq!(Module::ALL.len(), 21); + let mut seen = BTreeSet::new(); + for module in Module::ALL { + assert!(seen.insert(module.as_str()), "duplicate {module}"); + assert_eq!(Module::try_from_str(module.as_str()).unwrap(), module); + } + assert!(Module::try_from_str("course-notes").is_err(), "snake_case"); + assert!(Module::try_from_str("").is_err()); + } + + /// A cycle would make some set of modules unsatisfiable — every member + /// would need another member that needs it back. + #[test] + fn the_dependency_graph_is_acyclic() { + fn depth(module: Module, seen: &mut Vec) { + assert!(!seen.contains(&module), "cycle through {module}: {seen:?}"); + seen.push(module); + for needed in module.requires() { + depth(*needed, seen); + } + seen.pop(); + } + for module in Module::ALL { + depth(module, &mut Vec::new()); + } + } + + #[test] + fn every_module_is_sold_in_exactly_one_package() { + let packaged: Vec = Package::ALL + .into_iter() + .flat_map(Package::modules) + .collect(); + assert_eq!(packaged.len(), Module::ALL.len()); + for module in Module::ALL { + assert_eq!( + packaged.iter().filter(|m| **m == module).count(), + 1, + "{module} is not in exactly one package" + ); + } + } + + #[test] + fn dependents_is_the_exact_reverse_of_requires() { + for module in Module::ALL { + for dependent in module.dependents() { + assert!(dependent.requires().contains(&module)); + } + for needed in module.requires() { + assert!(needed.dependents().contains(&module)); + } + } + // The phrasing a caller builds from the reverse edges. + assert_eq!(Module::Exams.dependents(), vec![Module::Marks]); + assert_eq!( + Module::Courses.dependents(), + vec![ + Module::CourseNotes, + Module::Classes, + Module::Sessions, + Module::Exams, + Module::Subjects, + Module::Homework, + ] + ); + } + + #[test] + fn a_full_set_is_valid_and_a_lone_module_names_all_it_misses() { + assert!(ModuleSet::all().validate().is_ok()); + assert!(ModuleSet::empty().validate().is_ok()); + + let mut lone = ModuleSet::empty(); + lone.insert(Module::Exams); + let err = lone.validate().expect_err("exams alone is unsatisfiable"); + let message = err.to_string(); + assert!( + message.contains("exams requires courses, which is not enabled"), + "{message}" + ); + assert!( + message.contains("exams requires subjects, which is not enabled"), + "both misses in one message: {message}" + ); + assert!(matches!(err, AppError::ConflictOwned(_))); + } + + #[test] + fn names_round_trip_and_an_unknown_name_is_refused() { + let all = ModuleSet::all(); + let names = all.names(); + assert_eq!(names.len(), 21); + assert!(names.windows(2).all(|w| w[0] < w[1]), "sorted: {names:?}"); + assert_eq!(ModuleSet::from_names(&names).unwrap(), all); + + let err = ModuleSet::from_names(&["meals".into(), "kantin".into()]).unwrap_err(); + assert!( + err.to_string().contains("`kantin`"), + "names the offender: {err}" + ); + } +} diff --git a/src/tenant.rs b/src/tenant.rs index 66363d2..fd0beb1 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -33,6 +33,8 @@ use crate::database::{Database, lost_the_race, migrate, migrate_control}; use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; +use crate::module::ModuleSet; +use crate::web::tenant_state::ResolvedTenant; pub(crate) const SCHOOL_TABLE: &str = "school"; @@ -169,6 +171,11 @@ pub struct School { name: String, status: SchoolStatus, created_at: Timestamp, + /// Which product modules this school has bought, as their stored names. + /// Kept as strings rather than a [`ModuleSet`] so a name this binary does + /// not know (an older deploy reading a newer row) is data to ignore, not a + /// deserialization failure that would lock the school out entirely. + modules: Vec, } impl School { @@ -192,6 +199,23 @@ impl School { self.created_at } + /// The stored names as modules. An unknown name is dropped with a warning + /// — see the field's comment: a school must never become unreachable + /// because of a word this binary has not heard of. + pub fn modules(&self) -> ModuleSet { + let mut set = ModuleSet::empty(); + for name in &self.modules { + match crate::module::Module::try_from_str(name) { + Ok(module) => set.insert(module), + Err(_) => tracing::warn!( + "school {} has an unknown module `{name}` — ignoring it", + self.slug + ), + } + } + set + } + pub async fn read(slug: &Slug, control: &Database) -> Result, AppError> { Ok(control.select(SchoolId::from_slug(slug).record()).await?) } @@ -296,6 +320,7 @@ impl Tenants { name: name.to_string(), status: SchoolStatus::Active, created_at: Timestamp::now(), + modules: ModuleSet::all().names(), }; let _: Option = tenants .control @@ -326,13 +351,24 @@ impl Tenants { /// if it ever shows up in a profile — the eviction in [`Tenants::set_status`] /// is already there to make a cached decision safe. pub async fn get(&self, slug: &Slug) -> Result { + Ok(self.resolve(slug).await?.db) + } + + /// [`Tenants::get`] plus what that one registry read already knew: the + /// school's module entitlements. Same verdicts, same single read — a + /// caller that needs both must never pay for two. + pub async fn resolve(&self, slug: &Slug) -> Result { match School::read(slug, &self.control).await? { None => Err(AppError::Unauthorized), Some(school) if school.status == SchoolStatus::Suspended => { self.evict(slug); Err(AppError::Forbidden("school is suspended")) } - Some(_) => self.handle(slug).await, + Some(school) => Ok(ResolvedTenant { + slug: slug.clone(), + db: self.handle(slug).await?, + modules: school.modules(), + }), } } @@ -349,13 +385,19 @@ impl Tenants { /// Register a school and bring its database into being: registry row first /// (so a lost race is a `409` and not a half-made database), then /// `DEFINE DATABASE`, then the school schema. - pub async fn create(&self, slug: &Slug, name: &str) -> Result { + pub async fn create( + &self, + slug: &Slug, + name: &str, + modules: ModuleSet, + ) -> Result { let school = School { id: SchoolId::from_slug(slug), slug: slug.clone(), name: name.to_string(), status: SchoolStatus::Active, created_at: Timestamp::now(), + modules: modules.names(), }; let created: Result, surrealdb::Error> = self .control @@ -437,6 +479,25 @@ impl Tenants { Ok(()) } + /// Sell (or take back) modules. Mirrors [`Tenants::set_status`] minus the + /// eviction: entitlements are read off the registry row on every request, + /// so a change takes effect on the next call and no cached handle carries a + /// stale answer. + pub async fn set_modules(&self, slug: &Slug, modules: &ModuleSet) -> Result<(), AppError> { + let updated: Vec = self + .control + .query("UPDATE $id SET modules = $modules RETURN AFTER") + .bind(("id", SchoolId::from_slug(slug).record())) + .bind(("modules", modules.names())) + .await? + .check()? + .take(0)?; + if updated.is_empty() { + return Err(AppError::NotFound); + } + Ok(()) + } + /// Delete a school outright: its data, then its registry row, then its /// handle. Irreversible on purpose — there is no soft-delete state, that is /// what [`SchoolStatus::Suspended`] is for. @@ -580,8 +641,8 @@ mod tests { async fn two_schools_do_not_see_each_others_rows() { let tenants = Tenants::new_mem().await.unwrap(); let (a, b) = (slug("alpha"), slug("beta")); - let one = tenants.create(&a, "Alpha").await.unwrap(); - let two = tenants.create(&b, "Beta").await.unwrap(); + let one = tenants.create(&a, "Alpha", ModuleSet::all()).await.unwrap(); + let two = tenants.create(&b, "Beta", ModuleSet::all()).await.unwrap(); one.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") .await @@ -596,7 +657,7 @@ mod tests { ); // A second `create` on a taken slug is a conflict, not a second school. assert!(matches!( - tenants.create(&a, "Alpha again").await, + tenants.create(&a, "Alpha again", ModuleSet::all()).await, Err(AppError::Conflict(_)) )); } @@ -605,7 +666,7 @@ mod tests { async fn suspending_refuses_the_school_and_the_handle_it_already_had() { let tenants = Tenants::new_mem().await.unwrap(); let s = slug("alpha"); - tenants.create(&s, "Alpha").await.unwrap(); + tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); // Cached by the first resolve; the suspension must beat the cache. tenants.get(&s).await.expect("active school resolves"); @@ -638,7 +699,7 @@ mod tests { async fn dropping_a_school_takes_its_rows_with_it() { let tenants = Tenants::new_mem().await.unwrap(); let s = slug("alpha"); - let db = tenants.create(&s, "Alpha").await.unwrap(); + let db = tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); db.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") .await .unwrap() @@ -649,7 +710,10 @@ mod tests { tenants.drop(&s).await.unwrap(); assert!(matches!(tenants.get(&s).await, Err(AppError::Unauthorized))); - let fresh = tenants.create(&s, "Alpha reborn").await.unwrap(); + let fresh = tenants + .create(&s, "Alpha reborn", ModuleSet::all()) + .await + .unwrap(); assert_eq!( count(&fresh, "user").await, 0, @@ -660,8 +724,14 @@ mod tests { #[tokio::test] async fn the_registry_lists_and_renames() { let tenants = Tenants::new_mem().await.unwrap(); - tenants.create(&slug("alpha"), "Alpha").await.unwrap(); - tenants.create(&slug("beta"), "Beta").await.unwrap(); + tenants + .create(&slug("alpha"), "Alpha", ModuleSet::all()) + .await + .unwrap(); + tenants + .create(&slug("beta"), "Beta", ModuleSet::all()) + .await + .unwrap(); let (rows, total) = School::list(None, 0, tenants.control()).await.unwrap(); assert_eq!(total, 2); diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index a520a86..90b6c90 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -581,6 +581,8 @@ fn error_frame(err: &AppError, client_seq: Option) -> Value { AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict", AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid", AppError::NotFound => "not_found", + // See `room::public_message`: the gate refuses the upgrade first. + AppError::ModuleDisabled(_) => "module_disabled", AppError::Unauthorized => "unauthorized", AppError::TooManyRequests { .. } => "too_many_requests", AppError::DbUnavailable | AppError::DbTimeout | AppError::Db(_) | AppError::Internal(_) => { diff --git a/src/web/builder.rs b/src/web/builder.rs index 9bff111..64ba997 100644 --- a/src/web/builder.rs +++ b/src/web/builder.rs @@ -294,7 +294,12 @@ async fn create_school( let username = Username::try_new(&req.admin_username)?; let password_hash = Password::try_new(&req.admin_password)?.hash_async().await?; - let db = st.tenants.create(&slug, &name).await?; + // Everything, for now: choosing a school's modules is the next lane's + // HTTP surface (`crate::module` is the foundation it will call). + let db = st + .tenants + .create(&slug, &name, crate::module::ModuleSet::all()) + .await?; if let Err(err) = User::create_with_role(username, password_hash, Role::Admin, &db).await { // A school nobody can log into is worse than no school: take the // database back so the very same request can simply be retried. diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 22649dc..09b06a3 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -20,7 +20,7 @@ use std::time::Duration; -use crate::web::tenant_state::{SchoolSlug, State, TenantExt}; +use crate::web::tenant_state::{ResolvedTenant, SchoolSlug, State, TenantExt}; use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; @@ -378,6 +378,7 @@ async fn list_messages( async fn send_message( State(st): State, SchoolSlug(slug): SchoolSlug, + tenant: ResolvedTenant, CurrentUser(user): CurrentUser, Path(id): Path, Json(req): Json, @@ -444,6 +445,7 @@ async fn send_message( TenantExt { slug, db: st.db.clone(), + modules: tenant.modules, }, bridge, prompt.get_id().clone(), diff --git a/src/web/courses.rs b/src/web/courses.rs index c926353..18aeb65 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -50,10 +50,27 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(unassign_teacher)) .routes(routes!(enroll, list_roster)) .routes(routes!(unenroll)) - .routes(routes!(create_exam_in_course, list_course_exams)) - .routes(routes!(create_session_in_course, list_course_sessions)) - .routes(routes!(create_subject_in_course, list_course_subjects)) - .routes(routes!(create_homework_in_course, list_course_homework)) +} + +// The four route pairs below are mounted under `/courses` but *belong* to +// another module, so each is split out to carry that module's gate as well as +// the course one — see `crate::web::module_gate`. They are merged back in +// `build_router`, so the URL space is unchanged. + +pub fn exam_routes() -> OpenApiRouter { + OpenApiRouter::new().routes(routes!(create_exam_in_course, list_course_exams)) +} + +pub fn session_routes() -> OpenApiRouter { + OpenApiRouter::new().routes(routes!(create_session_in_course, list_course_sessions)) +} + +pub fn subject_routes() -> OpenApiRouter { + OpenApiRouter::new().routes(routes!(create_subject_in_course, list_course_subjects)) +} + +pub fn homework_routes() -> OpenApiRouter { + OpenApiRouter::new().routes(routes!(create_homework_in_course, list_course_homework)) } #[derive(Deserialize, ToSchema)] diff --git a/src/web/extractor.rs b/src/web/extractor.rs index 9ad6d50..ba4c63b 100644 --- a/src/web/extractor.rs +++ b/src/web/extractor.rs @@ -35,7 +35,7 @@ where return Ok(principal.0.clone()); } - let (_, db) = resolve_tenant(parts, state).await?; + let db = resolve_tenant(parts, state).await?.db; let jar = CookieJar::from_request_parts(parts, state) .await diff --git a/src/web/mod.rs b/src/web/mod.rs index 6e20ef2..dd38d22 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -24,6 +24,7 @@ pub mod limits; pub mod marks; pub mod meals; pub mod messages; +pub mod module_gate; pub mod notes; pub mod payments; pub mod pomodoro; diff --git a/src/web/module_gate.rs b/src/web/module_gate.rs new file mode 100644 index 0000000..f6b8ba2 --- /dev/null +++ b/src/web/module_gate.rs @@ -0,0 +1,71 @@ +//! The structural half of module entitlements: one gate per router nest. +//! +//! A module *is* a nest, so the gate is applied once where the nest is mounted +//! (`crate::build_router`) rather than route by route — there is no list of +//! guarded routes to keep in step with a list of routes, and a route added to +//! a gated nest is gated by construction. +//! +//! It goes on with `route_layer`, not `layer`: an unmatched path inside a +//! disabled nest must still be a `404`. A disabled module is not a wall around +//! a URL space, it is a refusal on the routes that exist. +//! +//! # The nested exceptions +//! +//! Four route pairs live under `/courses` but belong to another module, and so +//! carry a second gate of their own ([`crate::web::courses`] splits them out +//! for exactly this): +//! +//! - `/courses/{id}/exams` → `Module::Exams` +//! - `/courses/{id}/sessions` → `Module::Sessions` +//! - `/courses/{id}/subjects` → `Module::Subjects` +//! - `/courses/{id}/homework` → `Module::Homework` +//! +//! Both gates run (the child's, then the outer `/courses` one), so either +//! module being off refuses — which is right: `POST /courses/{id}/exams` is an +//! exams feature reached through a course. +//! +//! One surface this cannot reach: `crate::ai::server`'s blob stream, which +//! answers `BlobRequest`s without going through the router at all. It checks +//! `Module::CourseNotes` itself. + +use axum::extract::{Request, State}; +use axum::middleware::{Next, from_fn_with_state}; +use axum::response::{IntoResponse, Response}; +use utoipa_axum::router::OpenApiRouter; + +use crate::error::AppError; +use crate::module::Module; +use crate::state::AppState; +use crate::web::tenant_state::resolve_tenant; + +/// Wrap every route currently in `router` in `module`'s entitlement check. +/// +/// Takes and returns the router rather than handing back a bare `Layer`: the +/// `from_fn_with_state` layer's type is unnameable (it wraps an async closure), +/// so a function returning it could not be written down without boxing. The +/// call site reads the same either way — `gate(notes::routes(), &state, +/// Module::Notes)`. +pub fn gate( + router: OpenApiRouter, + state: &AppState, + module: Module, +) -> OpenApiRouter { + router.route_layer(from_fn_with_state((state.clone(), module), check)) +} + +async fn check( + State((state, module)): State<(AppState, Module)>, + request: Request, + next: Next, +) -> Response { + let (mut parts, body) = request.into_parts(); + match resolve_tenant(&mut parts, &state).await { + Err(err) => err.into_response(), + Ok(tenant) if !tenant.modules.contains(module) => { + AppError::ModuleDisabled(module).into_response() + } + // `resolve_tenant` memoized the school on `parts`, so the handler's own + // extractors reuse this read instead of making a second one. + Ok(_) => next.run(Request::from_parts(parts, body)).await, + } +} diff --git a/src/web/room.rs b/src/web/room.rs index a91a3b5..15415d6 100644 --- a/src/web/room.rs +++ b/src/web/room.rs @@ -91,6 +91,10 @@ pub(crate) fn public_message(err: &AppError, room: &str) -> String { message.clone() } AppError::PayloadTooLarge(message) => message.clone(), + // Unreachable in practice: the module gate refuses the upgrade before + // a socket exists. Spelled out anyway so a new refusal never falls + // into "internal server error" by default. + AppError::ModuleDisabled(module) => format!("module disabled: {module}"), AppError::TooManyRequests { .. } => "too many requests".to_string(), AppError::DbUnavailable => { tracing::warn!("{room}: database reconnecting"); diff --git a/src/web/tenant_state.rs b/src/web/tenant_state.rs index 53b8e16..7b4ab16 100644 --- a/src/web/tenant_state.rs +++ b/src/web/tenant_state.rs @@ -19,9 +19,22 @@ use axum_extra::extract::CookieJar; use crate::database::Database; use crate::error::AppError; +use crate::module::ModuleSet; use crate::state::AppState; use crate::tenant::Slug; +/// Everything one registry read tells us about the school behind a request: +/// its handle and what it has bought. Cached in the request's extensions by +/// [`resolve_tenant`], so a request that needs the school twice (the shadow +/// [`State`] *and* [`crate::web::CurrentUser`], which is most of them) reads +/// the registry once. +#[derive(Clone)] +pub struct ResolvedTenant { + pub slug: Slug, + pub db: Database, + pub modules: ModuleSet, +} + /// The school a request has already been resolved into, injected as a request /// extension by an in-process caller that has no cookie — today only the AI /// bridge. Extensions cannot be set from outside the process, so this is @@ -31,6 +44,7 @@ use crate::tenant::Slug; pub struct TenantExt { pub slug: Slug, pub db: Database, + pub modules: ModuleSet, } /// Split a `session` cookie into its school part and its token. `builder` in @@ -52,13 +66,20 @@ pub fn split_cookie(value: &str) -> Option<(&str, &str)> { pub(crate) async fn resolve_tenant( parts: &mut Parts, state: &S, -) -> Result<(Slug, Database), AppError> +) -> Result where S: Send + Sync, AppState: FromRef, { + if let Some(tenant) = parts.extensions.get::() { + return Ok(tenant.clone()); + } if let Some(tenant) = parts.extensions.get::() { - return Ok((tenant.slug.clone(), tenant.db.clone())); + return Ok(ResolvedTenant { + slug: tenant.slug.clone(), + db: tenant.db.clone(), + modules: tenant.modules.clone(), + }); } let jar = CookieJar::from_request_parts(parts, state) .await @@ -71,8 +92,12 @@ where let slug = Slug::try_new(prefix).map_err(|_| AppError::Unauthorized)?; let app = AppState::from_ref(state); - let db = app.tenants.get(&slug).await?; - Ok((slug, db)) + let resolved = app.tenants.resolve(&slug).await?; + // Memoized on the request, not just returned: the next extractor on this + // same request (and the module gate ahead of both) reuses this verdict + // instead of re-reading the registry row. + parts.extensions.insert(resolved.clone()); + Ok(resolved) } /// The application state, narrowed to the caller's school. Drop-in for @@ -91,16 +116,31 @@ where type Rejection = AppError; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - let (slug, db) = resolve_tenant(parts, state).await?; + let tenant = resolve_tenant(parts, state).await?; let app = AppState::from_ref(state); Ok(State(AppState { - db, - files_path: school_files_path(&app.files_path, &slug), + db: tenant.db, + files_path: school_files_path(&app.files_path, &tenant.slug), ..app })) } } +/// The resolved school itself, for a handler that must carry it somewhere the +/// request does not reach — today the chatbot's detached answer task, which +/// hands it back to the bridge as a [`TenantExt`]. +impl FromRequestParts for ResolvedTenant +where + S: Send + Sync, + AppState: FromRef, +{ + type Rejection = AppError; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + resolve_tenant(parts, state).await + } +} + /// Just the school, for the handlers that need it as a key prefix (the exam /// presence map, the whiteboard hub) rather than as a database handle. pub struct SchoolSlug(pub Slug); @@ -113,7 +153,7 @@ where type Rejection = AppError; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - Ok(SchoolSlug(resolve_tenant(parts, state).await?.0)) + Ok(SchoolSlug(resolve_tenant(parts, state).await?.slug)) } } @@ -290,6 +330,51 @@ mod tests { ); } + /// One request, one registry read. Measured by making the registry answer + /// *differently* the second time: the school is suspended between the two + /// extractor calls on the same request, so a second read would refuse. It + /// still passes — the verdict came from the memoized extension. + #[tokio::test] + async fn a_request_resolves_its_school_exactly_once() { + let tenants = init_mem_tenants().await.expect("in-memory deployment"); + let demo = Slug::try_new(DEMO_SLUG).unwrap(); + let state = AppState { + db: tenants.control().clone(), + tenants: tenants.clone(), + files_path: std::env::temp_dir(), + cookie_secure: false, + rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + exam_presence: Default::default(), + board_hub: Default::default(), + db_up: Default::default(), + ai: None, + }; + let request = Request::builder() + .uri("/school") + .header("cookie", format!("session={DEMO_SLUG}.whatever")) + .body(Body::empty()) + .unwrap(); + let (mut parts, _) = request.into_parts(); + + resolve_tenant(&mut parts, &state) + .await + .expect("the first resolve reads the registry"); + assert!( + parts.extensions.get::().is_some(), + "the first resolve must memoize its verdict on the request" + ); + + tenants + .set_status(&demo, crate::tenant::SchoolStatus::Suspended) + .await + .unwrap(); + let second = resolve_tenant(&mut parts, &state) + .await + .expect("a second read would have seen the suspension and refused"); + assert_eq!(second.slug, demo); + } + #[test] fn a_cookie_splits_at_its_first_dot_or_not_at_all() { assert_eq!(split_cookie("demo.abc123"), Some(("demo", "abc123"))); diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 702cfe6..804986f 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -18,6 +18,7 @@ use hezarfen_backend::ai::protocol::{ }; use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; use hezarfen_backend::constant::{AI_ALPN, AI_MAX_CONCURRENT_PER_WORKER, AI_PROTOCOL}; +use hezarfen_backend::module::ModuleSet; use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; use serde_json::{Value, json}; @@ -1772,7 +1773,10 @@ async fn an_index_dispatch_names_the_notes_own_school_and_stores_the_answer_ther let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; let beta = Slug::try_new("beta").unwrap(); - let beta_db = tenants.create(&beta, "Beta College").await.expect("beta"); + let beta_db = tenants + .create(&beta, "Beta College", ModuleSet::all()) + .await + .expect("beta"); let cookie = common::login_as_school(&app, &beta_db, "beta", "ogretmen", "teacher").await; let course = common::create_course(&app, &cookie, "fizik").await; diff --git a/tests/ai_protocol.rs b/tests/ai_protocol.rs index fb37cf5..e855879 100644 --- a/tests/ai_protocol.rs +++ b/tests/ai_protocol.rs @@ -23,6 +23,7 @@ use std::sync::Arc; use std::time::Duration; use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; +use hezarfen_backend::module::ModuleSet; use hezarfen_backend::tenant::{SchoolStatus, Slug, Tenants}; use serde_json::{Value, json}; @@ -1208,7 +1209,11 @@ async fn an_api_read_answers_a_named_user_with_that_users_own_data() { async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, String) { let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; let beta_db = tenants - .create(&Slug::try_new("beta").unwrap(), "Beta College") + .create( + &Slug::try_new("beta").unwrap(), + "Beta College", + ModuleSet::all(), + ) .await .expect("a second school"); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 0dff586..fa4ada7 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -10,6 +10,7 @@ use axum::body::Body; use axum::http::{HeaderMap, Request, StatusCode}; use hezarfen_backend::ai::AiBridge; use hezarfen_backend::database::Database; +use hezarfen_backend::module::ModuleSet; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::{AppState, DbHealth}; use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; @@ -664,7 +665,11 @@ pub async fn remote_deployment(schools: &[(&str, &str)]) -> Option ( let (app, db_a, tenants) = common::app_and_tenants().await; let slug_b = Slug::try_new("beta").expect("slug"); let db_b = tenants - .create(&slug_b, "Beta Koleji") + .create(&slug_b, "Beta Koleji", ModuleSet::all()) .await .expect("school B"); (app, db_a, db_b, tenants) @@ -28647,3 +28648,126 @@ async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() { res.body ); } + +// --- module entitlements ------------------------------------------------- +// +// Foundation-level only: one nest proves the gate, one child route proves the +// `/courses` exceptions, and the two WebSocket nests prove an upgrade is +// refused like any other GET. The full per-module sweep is a later lane. + +use hezarfen_backend::module::Module; + +/// Turning a module off refuses **its** nest and nothing else — with the same +/// cookie, and with the URL space untouched (an unmatched path inside the +/// disabled nest is still a `404`, which is what `route_layer` buys). +#[tokio::test] +async fn a_disabled_module_refuses_its_nest_and_leaves_the_rest_alone() { + let (app, db, tenants) = common::app_and_tenants().await; + let slug = Slug::try_new(DEMO_SLUG).unwrap(); + let cookie = login_as(&app, &db, "ada", "admin").await; + + let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let mut without_meals = ModuleSet::all(); + without_meals.remove(Module::Meals); + tenants + .set_modules(&slug, &without_meals) + .await + .expect("take the meals module back"); + + let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + assert_eq!( + res.body, + json!({ "error": "module disabled", "module": "meals" }), + "the refusal body is contract" + ); + + for route in ["/auth/me", "/limits", "/settings"] { + let res = send(&app, "GET", route, Some(&cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{route}: {}", res.body); + } + + let res = send(&app, "GET", "/meals/does-not-exist", Some(&cookie), None).await; + assert_eq!( + res.status, + StatusCode::NOT_FOUND, + "a disabled module must not swallow the 404: {}", + res.body + ); + + tenants + .set_modules(&slug, &ModuleSet::all()) + .await + .expect("sell it back"); + let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; + assert_eq!( + res.status, + StatusCode::OK, + "the very same cookie after re-enabling: {}", + res.body + ); +} + +/// The four route pairs mounted under `/courses` that belong to another +/// module answer for *that* module: exams off refuses +/// `POST /courses/{id}/exams` while the course itself stays reachable. +#[tokio::test] +async fn a_course_child_route_is_gated_by_its_own_module() { + let (app, db, tenants) = common::app_and_tenants().await; + let slug = Slug::try_new(DEMO_SLUG).unwrap(); + let cookie = login_as(&app, &db, "ada", "admin").await; + let course = create_course(&app, &cookie, "Fizik").await; + + let mut without_exams = ModuleSet::all(); + without_exams.remove(Module::Exams); + tenants.set_modules(&slug, &without_exams).await.unwrap(); + + // An empty body: the gate must answer before the payload is even parsed. + let res = send( + &app, + "POST", + &format!("/courses/{course}/exams"), + Some(&cookie), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + assert_eq!(res.body["module"], "exams"); + + let res = send( + &app, + "GET", + &format!("/courses/{course}"), + Some(&cookie), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::OK, + "courses itself is still enabled: {}", + res.body + ); +} + +/// A WebSocket upgrade is a `GET` inside its nest, so it is gated by +/// construction — proven for both rooms rather than assumed. +#[tokio::test] +async fn a_disabled_module_refuses_its_websocket_upgrade() { + let (app, db, tenants) = common::app_and_tenants().await; + let slug = Slug::try_new(DEMO_SLUG).unwrap(); + let cookie = login_as(&app, &db, "ada", "admin").await; + + let mut without = ModuleSet::all(); + without.remove(Module::Boards); + without.remove(Module::Exams); + tenants.set_modules(&slug, &without).await.unwrap(); + + for (route, module) in [("/boards/x/ws", "boards"), ("/exams/x/attempt/ws", "exams")] { + let res = send(&app, "GET", route, Some(&cookie), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{route}: {}", res.body); + assert_eq!(res.body["module"], module, "{route}"); + } +} diff --git a/tests/persistence.rs b/tests/persistence.rs index fc5df3d..89f576b 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -11,6 +11,7 @@ use axum::http::StatusCode; use common::{create_course, create_exam, create_subject, enroll, me_id, send, set_role}; use hezarfen_backend::database::Database; use hezarfen_backend::domain::timestamp::Timestamp; +use hezarfen_backend::module::ModuleSet; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::AppState; use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; @@ -2371,3 +2372,74 @@ async fn pre_class_enrollments_keep_their_absent_source() { "and no seat was given back" ); } + +/// A school row written before module entitlements existed has no `modules` +/// field at all. The control migration must read that — and only that — as +/// "everything", because a school that predates the idea of buying modules had +/// all of them. +#[tokio::test] +async fn a_school_row_without_modules_backfills_to_every_module() { + let db = surrealdb::engine::any::connect("memory") + .await + .expect("an in-memory control store"); + db.use_ns("hezarfen").use_db("control").await.unwrap(); + // The control schema as it stood before `modules`, so the row really is + // the shape an older binary left behind. + db.query( + "DEFINE TABLE school SCHEMAFULL; + DEFINE FIELD slug ON school TYPE string; + DEFINE FIELD name ON school TYPE string; + DEFINE FIELD status ON school TYPE string; + DEFINE FIELD created_at ON school TYPE int; + CREATE school:legacy SET slug = 'legacy', name = 'Legacy', \ + status = 'active', created_at = 1;", + ) + .await + .expect("the pre-modules control schema") + .check() + .expect("the pre-modules control schema"); + + database::migrate_control(&db).await.expect("a newer boot"); + + let stored: Vec> = db + .query("SELECT VALUE modules FROM school:legacy") + .await + .expect("read the row back") + .take(0) + .expect("modules column"); + assert_eq!( + stored.first().cloned().unwrap_or_default(), + ModuleSet::all().names(), + "a row that predates entitlements owns every module" + ); +} + +/// The other half of that rule: `[]` is a deliberate "nothing enabled", not a +/// missing value, so a second boot must leave it alone. Widening it would hand +/// a school modules it never bought. +#[tokio::test] +async fn an_empty_module_list_survives_a_second_boot() { + let tenants = Tenants::new_mem().await.expect("a control database"); + let slug = Slug::try_new("bare").unwrap(); + tenants + .create(&slug, "Bare School", ModuleSet::empty()) + .await + .expect("a school with nothing switched on"); + + database::migrate_control(tenants.control()) + .await + .expect("a second boot"); + + let stored: Vec> = tenants + .control() + .query("SELECT VALUE modules FROM school:bare") + .await + .expect("read the row back") + .take(0) + .expect("modules column"); + assert_eq!( + stored.first().cloned().unwrap_or_default(), + Vec::::new(), + "an empty list is a decision, never a hole to fill" + ); +}