Per-school modules
Browse files at this commit5d7f87ca136849ee5310cdbd60055db690e95bdfParent: 7d4bd21- feat
- per-school modules
- a disabled module answers 403 on every route in its nest
22 changed files +1101 -63
- README.md +7 -1
- src/ai/server.rs +24 -8
- src/database.rs +11 -4
- src/error.rs +34 -0
- src/lib.rs +96 -21
- src/migration_sql.rs +8 -0
- src/module.rs +425 -0
- src/tenant.rs +80 -10
- src/web/board_ws.rs +2 -0
- src/web/builder.rs +6 -1
- src/web/chatbot.rs +3 -1
- src/web/courses.rs +21 -4
- src/web/extractor.rs +1 -1
- src/web/mod.rs +1 -0
- src/web/module_gate.rs +71 -0
- src/web/room.rs +4 -0
- src/web/tenant_state.rs +93 -8
- tests/ai_bridge.rs +5 -1
- tests/ai_protocol.rs +6 -1
- tests/common/mod.rs +6 -1
- tests/integration.rs +125 -1
- tests/persistence.rs +72 -0
README.mdmodified+7 -1
| @@ -3816,6 +3816,7 @@ slow-but-reading service is never cut off. | |||
| 3816 | | `not_found` | No `course_note_file` with that key *in that school*, or its note or course is gone | | 3816 | | `not_found` | No `course_note_file` with that key *in that school*, or its note or course is gone | |
| 3817 | | `forbidden` | The principal may not view that file's course | | 3817 | | `forbidden` | The principal may not view that file's course | |
| 3818 | | `unknown_school` / `school_suspended` | As for an api read | | 3818 | | `unknown_school` / `school_suspended` | As for an api read | |
| 3819 | +| `module_disabled` | That school has no `course_notes` module — this stream bypasses the router, so it checks the entitlement itself | | ||
| 3819 | | `unknown_user` | `on_behalf_of` names no user of that school | | 3820 | | `unknown_user` | `on_behalf_of` names no user of that school | |
| 3820 | | `unavailable` | The api is not serving yet, the database socket is down, or the row's blob is missing from disk — retryable | | 3821 | | `unavailable` | The api is not serving yet, the database socket is down, or the row's blob is missing from disk — retryable | |
| 3821 | 3822 | ||
| @@ -4502,6 +4503,8 @@ src/ | |||
| 4502 | migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR, | 4503 | migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR, |
| 4503 | MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them, | 4504 | MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them, |
| 4504 | and CONTROL_MIGRATION_BATCHES for the control database | 4505 | and CONTROL_MIGRATION_BATCHES for the control database |
| 4506 | + module.rs Module (one router nest a school may buy) · Package · | ||
| 4507 | + ModuleSet: dependency edges, validation, stored names | ||
| 4505 | rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier | 4508 | rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier |
| 4506 | state.rs AppState { db, tenants, files_path, cookie_secure, rate_limit, | 4509 | state.rs AppState { db, tenants, files_path, cookie_secure, rate_limit, |
| 4507 | chatbot_limit, exam_presence, board_hub, db_up, ai } | 4510 | chatbot_limit, exam_presence, board_hub, db_up, ai } |
| @@ -4660,7 +4663,10 @@ src/ | |||
| 4660 | tenant_state.rs State<AppState>: the shadow of axum's State that resolves the | 4663 | tenant_state.rs State<AppState>: the shadow of axum's State that resolves the |
| 4661 | caller's school from the `<slug>.<token>` cookie, so every | 4664 | caller's school from the `<slug>.<token>` cookie, so every |
| 4662 | handler that imports it is school-scoped by construction | 4665 | handler that imports it is school-scoped by construction |
| 4663 | - (TenantExt · SchoolSlug · split_cookie) | 4666 | + (ResolvedTenant · TenantExt · SchoolSlug · split_cookie) |
| 4667 | + module_gate.rs one route_layer per nest: a module the school has not bought | ||
| 4668 | + answers 403 {error, module} on every route in it, while an | ||
| 4669 | + unmatched path inside it still 404s | ||
| 4664 | builder.rs the vendor surface: /builder/login|logout|me and /schools/* | 4670 | builder.rs the vendor surface: /builder/login|logout|me and /schools/* |
| 4665 | (create · list · rename/suspend · delete · admin-password · enter) | 4671 | (create · list · rename/suspend · delete · admin-password · enter) |
| 4666 | image.rs the halves every image upload shares: the `file` part under the | 4672 | image.rs the halves every image upload shares: the `file` part under the |
src/ai/server.rsmodified+24 -8
| @@ -29,12 +29,13 @@ use crate::domain::course_note::CourseNote; | |||
| 29 | use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; | 29 | use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; |
| 30 | use crate::domain::user::{User, UserId}; | 30 | use crate::domain::user::{User, UserId}; |
| 31 | use crate::error::AppError; | 31 | use crate::error::AppError; |
| 32 | +use crate::module::Module; | ||
| 32 | use crate::state::DbHealth; | 33 | use crate::state::DbHealth; |
| 33 | use crate::tenant::{Slug, Tenants}; | 34 | use crate::tenant::{Slug, Tenants}; |
| 34 | use crate::web::blob_path; | 35 | use crate::web::blob_path; |
| 35 | use crate::web::courses::can_view_course; | 36 | use crate::web::courses::can_view_course; |
| 36 | use crate::web::extractor::AiPrincipal; | 37 | use crate::web::extractor::AiPrincipal; |
| 37 | -use crate::web::tenant_state::{TenantExt, school_files_path}; | 38 | +use crate::web::tenant_state::{ResolvedTenant, TenantExt, school_files_path}; |
| 38 | 39 | ||
| 39 | /// What the bridge needs to come up. | 40 | /// What the bridge needs to come up. |
| 40 | #[derive(Clone, Debug)] | 41 | #[derive(Clone, Debug)] |
| @@ -74,14 +75,14 @@ impl ApiHandle { | |||
| 74 | /// has no such customer, and `school_suspended` means it has one that is | 75 | /// has no such customer, and `school_suspended` means it has one that is |
| 75 | /// switched off — a service that retries the first two forever learns | 76 | /// switched off — a service that retries the first two forever learns |
| 76 | /// nothing, while the third is worth retrying later. | 77 | /// nothing, while the third is worth retrying later. |
| 77 | - async fn school(&self, school: &str) -> Result<(Slug, Database), (&'static str, String)> { | 78 | + async fn school(&self, school: &str) -> Result<ResolvedTenant, (&'static str, String)> { |
| 78 | let slug = Slug::try_new(school).map_err(|err| { | 79 | let slug = Slug::try_new(school).map_err(|err| { |
| 79 | ( | 80 | ( |
| 80 | "malformed", | 81 | "malformed", |
| 81 | format!("`{school}` is not a school slug: {err}"), | 82 | format!("`{school}` is not a school slug: {err}"), |
| 82 | ) | 83 | ) |
| 83 | })?; | 84 | })?; |
| 84 | - let db = self.tenants.get(&slug).await.map_err(|err| match err { | 85 | + self.tenants.resolve(&slug).await.map_err(|err| match err { |
| 85 | AppError::Unauthorized => ( | 86 | AppError::Unauthorized => ( |
| 86 | "unknown_school", | 87 | "unknown_school", |
| 87 | format!("this deployment serves no `{slug}` school"), | 88 | format!("this deployment serves no `{slug}` school"), |
| @@ -94,8 +95,7 @@ impl ApiHandle { | |||
| 94 | "unavailable", | 95 | "unavailable", |
| 95 | format!("the `{slug}` school is not reachable: {other}"), | 96 | format!("the `{slug}` school is not reachable: {other}"), |
| 96 | ), | 97 | ), |
| 97 | - })?; | 98 | + }) |
| 98 | - Ok((slug, db)) | ||
| 99 | } | 99 | } |
| 100 | 100 | ||
| 101 | /// One school's blob directory. | 101 | /// One school's blob directory. |
| @@ -531,7 +531,16 @@ async fn open_blob( | |||
| 531 | "the database socket is down — retry".to_string(), | 531 | "the database socket is down — retry".to_string(), |
| 532 | )); | 532 | )); |
| 533 | } | 533 | } |
| 534 | - let (slug, db) = api.school(&request.school).await?; | 534 | + let tenant = api.school(&request.school).await?; |
| 535 | + let (slug, db) = (tenant.slug, tenant.db); | ||
| 536 | + // This stream bypasses the router, so it also bypasses the route_layer the | ||
| 537 | + // module gate is — the entitlement is checked here by hand instead. | ||
| 538 | + if !tenant.modules.contains(Module::CourseNotes) { | ||
| 539 | + return Err(( | ||
| 540 | + "module_disabled", | ||
| 541 | + format!("the `{slug}` school has no `course_notes` module"), | ||
| 542 | + )); | ||
| 543 | + } | ||
| 535 | let user = principal(&db, request.on_behalf_of.as_deref()).await?; | 544 | let user = principal(&db, request.on_behalf_of.as_deref()).await?; |
| 536 | 545 | ||
| 537 | let missing = || { | 546 | let missing = || { |
| @@ -695,7 +704,8 @@ async fn dispatch_api( | |||
| 695 | // The school comes off the frame, so this is where a service naming a | 704 | // The school comes off the frame, so this is where a service naming a |
| 696 | // stranger's slug (or a suspended school's) is stopped — before a row of | 705 | // stranger's slug (or a suspended school's) is stopped — before a row of |
| 697 | // anyone's data is read. | 706 | // anyone's data is read. |
| 698 | - let (slug, db) = api.school(&school).await?; | 707 | + let tenant = api.school(&school).await?; |
| 708 | + let db = tenant.db.clone(); | ||
| 699 | // The role itself is re-read again by the extractor on the dispatched | 709 | // The role itself is re-read again by the extractor on the dispatched |
| 700 | // request; see [`principal`] for why it is never taken from the frame. | 710 | // request; see [`principal`] for why it is never taken from the frame. |
| 701 | let user = principal(&db, on_behalf_of.as_deref()).await?; | 711 | let user = principal(&db, on_behalf_of.as_deref()).await?; |
| @@ -719,7 +729,13 @@ async fn dispatch_api( | |||
| 719 | dispatched.extensions_mut().insert(AiPrincipal(user)); | 729 | dispatched.extensions_mut().insert(AiPrincipal(user)); |
| 720 | // The dispatched request carries no cookie, so the school is handed over | 730 | // The dispatched request carries no cookie, so the school is handed over |
| 721 | // in the extension the shadow `State` reads first. | 731 | // in the extension the shadow `State` reads first. |
| 722 | - dispatched.extensions_mut().insert(TenantExt { slug, db }); | 732 | + // Carries the school's entitlements too, so the router's module gate |
| 733 | + // refuses a disabled nest on this path exactly as it does over HTTP. | ||
| 734 | + dispatched.extensions_mut().insert(TenantExt { | ||
| 735 | + slug: tenant.slug, | ||
| 736 | + db, | ||
| 737 | + modules: tenant.modules, | ||
| 738 | + }); | ||
| 723 | 739 | ||
| 724 | let response = tokio::time::timeout( | 740 | let response = tokio::time::timeout( |
| 725 | Duration::from_secs(REQUEST_TIMEOUT_SECS), | 741 | Duration::from_secs(REQUEST_TIMEOUT_SECS), |
src/database.rsmodified+11 -4
| @@ -273,7 +273,9 @@ pub async fn init_mem_tenants() -> Result<Tenants, AppError> { | |||
| 273 | let tenants = Tenants::new_mem().await?; | 273 | let tenants = Tenants::new_mem().await?; |
| 274 | let demo = crate::tenant::Slug::try_new(crate::tenant::DEMO_SLUG) | 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}")))?; | 275 | .map_err(|err| AppError::Internal(format!("the demo slug is a slug: {err}")))?; |
| 276 | - tenants.create(&demo, "Demo School").await?; | 276 | + tenants |
| 277 | + .create(&demo, "Demo School", crate::module::ModuleSet::all()) | ||
| 278 | + .await?; | ||
| 277 | Ok(tenants) | 279 | Ok(tenants) |
| 278 | } | 280 | } |
| 279 | 281 | ||
| @@ -374,11 +376,16 @@ pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { | |||
| 374 | } | 376 | } |
| 375 | 377 | ||
| 376 | /// Apply the **control** schema (schools, builders, the shared rate-limit | 378 | /// Apply the **control** schema (schools, builders, the shared rate-limit |
| 377 | -/// window). Idempotent, like [`migrate`], and takes no bound parameters — | 379 | +/// window). Idempotent, like [`migrate`]. |
| 378 | -/// nothing in the control batch is data-driven. | ||
| 379 | pub async fn migrate_control(db: &Surreal<Any>) -> Result<(), AppError> { | 380 | pub async fn migrate_control(db: &Surreal<Any>) -> Result<(), AppError> { |
| 381 | + // The one data-driven parameter in this batch: the module list a school | ||
| 382 | + // written before entitlements existed is backfilled to. | ||
| 383 | + let all_modules = crate::module::ModuleSet::all().names(); | ||
| 380 | for sql in CONTROL_MIGRATION_BATCHES { | 384 | for sql in CONTROL_MIGRATION_BATCHES { |
| 381 | - db.query(sql).await?.check()?; | 385 | + db.query(sql) |
| 386 | + .bind(("all_modules", all_modules.clone())) | ||
| 387 | + .await? | ||
| 388 | + .check()?; | ||
| 382 | } | 389 | } |
| 383 | Ok(()) | 390 | Ok(()) |
| 384 | } | 391 | } |
src/error.rsmodified+34 -0
| @@ -42,6 +42,12 @@ pub enum ValidationError { | |||
| 42 | field: &'static str, | 42 | field: &'static str, |
| 43 | reason: &'static str, | 43 | reason: &'static str, |
| 44 | }, | 44 | }, |
| 45 | + /// A closed value set refused a name it does not contain — and says which | ||
| 46 | + /// name, which [`ValidationError::Invalid`] cannot: its `reason` is | ||
| 47 | + /// `&'static str`, so the offending value could only be described, never | ||
| 48 | + /// quoted. | ||
| 49 | + #[error("{field}: `{value}` is not a known {field}")] | ||
| 50 | + Unknown { field: &'static str, value: String }, | ||
| 45 | } | 51 | } |
| 46 | 52 | ||
| 47 | /// The single error type every fallible operation returns. | 53 | /// The single error type every fallible operation returns. |
| @@ -55,6 +61,11 @@ pub enum AppError { | |||
| 55 | Unauthorized, | 61 | Unauthorized, |
| 56 | #[error("forbidden: {0}")] | 62 | #[error("forbidden: {0}")] |
| 57 | Forbidden(&'static str), | 63 | Forbidden(&'static str), |
| 64 | + /// The school has not bought this module. A dedicated arm because the body | ||
| 65 | + /// carries a second key — the module's name — so a client can tell "your | ||
| 66 | + /// school does not have this" from every other `403` without parsing prose. | ||
| 67 | + #[error("module disabled: {0}")] | ||
| 68 | + ModuleDisabled(crate::module::Module), | ||
| 58 | #[error("conflict: {0}")] | 69 | #[error("conflict: {0}")] |
| 59 | Conflict(&'static str), | 70 | Conflict(&'static str), |
| 60 | /// A 409 whose message is only known at runtime — e.g. the specific | 71 | /// A 409 whose message is only known at runtime — e.g. the specific |
| @@ -168,6 +179,14 @@ impl IntoResponse for AppError { | |||
| 168 | ) | 179 | ) |
| 169 | .into_response(); | 180 | .into_response(); |
| 170 | } | 181 | } |
| 182 | + // Also carries a second key: which module was refused. | ||
| 183 | + AppError::ModuleDisabled(module) => { | ||
| 184 | + return ( | ||
| 185 | + StatusCode::FORBIDDEN, | ||
| 186 | + Json(json!({ "error": "module disabled", "module": module.as_str() })), | ||
| 187 | + ) | ||
| 188 | + .into_response(); | ||
| 189 | + } | ||
| 171 | AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()), | 190 | AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()), |
| 172 | AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), | 191 | AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()), |
| 173 | AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), | 192 | AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), |
| @@ -219,6 +238,21 @@ mod tests { | |||
| 219 | assert!(matches!(AppError::from(e), AppError::DbUnavailable)); | 238 | assert!(matches!(AppError::from(e), AppError::DbUnavailable)); |
| 220 | } | 239 | } |
| 221 | 240 | ||
| 241 | + /// The refusal a gated nest answers with. Both keys, and the `403` — a | ||
| 242 | + /// client switches on `module`, so neither may drift. | ||
| 243 | + #[tokio::test] | ||
| 244 | + async fn a_disabled_module_is_a_403_naming_itself() { | ||
| 245 | + use crate::module::Module; | ||
| 246 | + let response = AppError::ModuleDisabled(Module::CourseNotes).into_response(); | ||
| 247 | + assert_eq!(response.status(), StatusCode::FORBIDDEN); | ||
| 248 | + let body = axum::body::to_bytes(response.into_body(), 4096) | ||
| 249 | + .await | ||
| 250 | + .unwrap(); | ||
| 251 | + let body: serde_json::Value = serde_json::from_slice(&body).unwrap(); | ||
| 252 | + assert_eq!(body["error"], "module disabled"); | ||
| 253 | + assert_eq!(body["module"], "course_notes"); | ||
| 254 | + } | ||
| 255 | + | ||
| 222 | #[test] | 256 | #[test] |
| 223 | fn real_errors_stay_db_errors() { | 257 | fn real_errors_stay_db_errors() { |
| 224 | // A genuine authorization verdict shares the suffix but must not match. | 258 | // A genuine authorization verdict shares the suffix but must not match. |
src/lib.rsmodified+96 -21
| @@ -5,6 +5,7 @@ pub mod database; | |||
| 5 | pub mod domain; | 5 | pub mod domain; |
| 6 | pub mod error; | 6 | pub mod error; |
| 7 | pub mod migration_sql; | 7 | pub mod migration_sql; |
| 8 | +pub mod module; | ||
| 8 | pub mod rate_limit; | 9 | pub mod rate_limit; |
| 9 | pub mod state; | 10 | pub mod state; |
| 10 | pub mod tenant; | 11 | pub mod tenant; |
| @@ -27,8 +28,10 @@ use utoipa_axum::routes; | |||
| 27 | use utoipa_swagger_ui::SwaggerUi; | 28 | use utoipa_swagger_ui::SwaggerUi; |
| 28 | 29 | ||
| 29 | use crate::error::AppError; | 30 | use crate::error::AppError; |
| 31 | +use crate::module::Module; | ||
| 30 | use crate::rate_limit::RateLimiter; | 32 | use crate::rate_limit::RateLimiter; |
| 31 | use crate::state::AppState; | 33 | use crate::state::AppState; |
| 34 | +use crate::web::module_gate::gate; | ||
| 32 | 35 | ||
| 33 | /// Top-level OpenAPI document. Per-path operations and schemas are collected | 36 | /// Top-level OpenAPI document. Per-path operations and schemas are collected |
| 34 | /// automatically from the `#[utoipa::path]`-annotated handlers via `utoipa-axum`. | 37 | /// automatically from the `#[utoipa::path]`-annotated handlers via `utoipa-axum`. |
| @@ -88,6 +91,33 @@ impl Modify for SecurityAddon { | |||
| 88 | } | 91 | } |
| 89 | } | 92 | } |
| 90 | 93 | ||
| 94 | +/// `/courses` and the four foreign-module route pairs mounted inside it. The | ||
| 95 | +/// children carry their own module's gate *and*, through the outer one applied | ||
| 96 | +/// here, the course gate — so either module being off refuses them. | ||
| 97 | +fn courses_router(state: &AppState) -> OpenApiRouter<AppState> { | ||
| 98 | + let children = gate(web::courses::exam_routes(), state, Module::Exams) | ||
| 99 | + .merge(gate( | ||
| 100 | + web::courses::session_routes(), | ||
| 101 | + state, | ||
| 102 | + Module::Sessions, | ||
| 103 | + )) | ||
| 104 | + .merge(gate( | ||
| 105 | + web::courses::subject_routes(), | ||
| 106 | + state, | ||
| 107 | + Module::Subjects, | ||
| 108 | + )) | ||
| 109 | + .merge(gate( | ||
| 110 | + web::courses::homework_routes(), | ||
| 111 | + state, | ||
| 112 | + Module::Homework, | ||
| 113 | + )); | ||
| 114 | + gate( | ||
| 115 | + web::courses::routes().merge(children), | ||
| 116 | + state, | ||
| 117 | + Module::Courses, | ||
| 118 | + ) | ||
| 119 | +} | ||
| 120 | + | ||
| 91 | /// Assemble the full application router. Shared by `main` and the test suites. | 121 | /// Assemble the full application router. Shared by `main` and the test suites. |
| 92 | /// | 122 | /// |
| 93 | /// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at | 123 | /// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at |
| @@ -101,30 +131,75 @@ pub fn build_router(state: AppState) -> Router { | |||
| 101 | .nest("/ai", web::ai::routes()) | 131 | .nest("/ai", web::ai::routes()) |
| 102 | .nest("/auth", web::auth::routes(&state)) | 132 | .nest("/auth", web::auth::routes(&state)) |
| 103 | .merge(web::builder::routes(&state)) | 133 | .merge(web::builder::routes(&state)) |
| 104 | - .nest("/chatbot", web::chatbot::routes()) | 134 | + .nest( |
| 135 | + "/chatbot", | ||
| 136 | + gate(web::chatbot::routes(), &state, Module::Chatbot), | ||
| 137 | + ) | ||
| 105 | .nest("/users", web::users::routes()) | 138 | .nest("/users", web::users::routes()) |
| 106 | - .nest("/notes", web::notes::routes()) | 139 | + .nest("/notes", gate(web::notes::routes(), &state, Module::Notes)) |
| 107 | - .nest("/messages", web::messages::routes()) | 140 | + .nest( |
| 108 | - .nest("/events", web::events::routes()) | 141 | + "/messages", |
| 109 | - .nest("/appointments", web::appointments::routes()) | 142 | + gate(web::messages::routes(), &state, Module::Messages), |
| 110 | - .nest("/courses", web::courses::routes()) | 143 | + ) |
| 111 | - .nest("/course-notes", web::course_notes::routes()) | 144 | + .nest( |
| 112 | - .nest("/classes", web::classes::routes()) | 145 | + "/events", |
| 113 | - .nest("/sessions", web::sessions::routes()) | 146 | + gate(web::events::routes(), &state, Module::Events), |
| 114 | - .nest("/exams", web::exams::routes()) | 147 | + ) |
| 115 | - .nest("/marks", web::marks::routes()) | 148 | + .nest( |
| 116 | - .nest("/meals", web::meals::routes()) | 149 | + "/appointments", |
| 117 | - .nest("/payments", web::payments::routes()) | 150 | + gate(web::appointments::routes(), &state, Module::Appointments), |
| 118 | - .nest("/work", web::work::routes()) | 151 | + ) |
| 119 | - .nest("/pomodoro", web::pomodoro::routes()) | 152 | + .nest("/courses", courses_router(&state)) |
| 120 | - .nest("/questions", web::questions::routes()) | 153 | + .nest( |
| 121 | - .nest("/bank-questions", web::bank_questions::routes()) | 154 | + "/course-notes", |
| 122 | - .nest("/attendance", web::attendance::routes()) | 155 | + gate(web::course_notes::routes(), &state, Module::CourseNotes), |
| 156 | + ) | ||
| 157 | + .nest( | ||
| 158 | + "/classes", | ||
| 159 | + gate(web::classes::routes(), &state, Module::Classes), | ||
| 160 | + ) | ||
| 161 | + .nest( | ||
| 162 | + "/sessions", | ||
| 163 | + gate(web::sessions::routes(), &state, Module::Sessions), | ||
| 164 | + ) | ||
| 165 | + .nest("/exams", gate(web::exams::routes(), &state, Module::Exams)) | ||
| 166 | + .nest("/marks", gate(web::marks::routes(), &state, Module::Marks)) | ||
| 167 | + .nest("/meals", gate(web::meals::routes(), &state, Module::Meals)) | ||
| 168 | + .nest( | ||
| 169 | + "/payments", | ||
| 170 | + gate(web::payments::routes(), &state, Module::Payments), | ||
| 171 | + ) | ||
| 172 | + .nest("/work", gate(web::work::routes(), &state, Module::Work)) | ||
| 173 | + .nest( | ||
| 174 | + "/pomodoro", | ||
| 175 | + gate(web::pomodoro::routes(), &state, Module::Pomodoro), | ||
| 176 | + ) | ||
| 177 | + .nest( | ||
| 178 | + "/questions", | ||
| 179 | + gate(web::questions::routes(), &state, Module::Questions), | ||
| 180 | + ) | ||
| 181 | + .nest( | ||
| 182 | + "/bank-questions", | ||
| 183 | + gate(web::bank_questions::routes(), &state, Module::BankQuestions), | ||
| 184 | + ) | ||
| 185 | + .nest( | ||
| 186 | + "/attendance", | ||
| 187 | + gate(web::attendance::routes(), &state, Module::Attendance), | ||
| 188 | + ) | ||
| 123 | .nest("/settings", web::settings::routes()) | 189 | .nest("/settings", web::settings::routes()) |
| 124 | - .nest("/subjects", web::subjects::routes()) | 190 | + .nest( |
| 125 | - .nest("/homework", web::homework::routes()) | 191 | + "/subjects", |
| 192 | + gate(web::subjects::routes(), &state, Module::Subjects), | ||
| 193 | + ) | ||
| 194 | + .nest( | ||
| 195 | + "/homework", | ||
| 196 | + gate(web::homework::routes(), &state, Module::Homework), | ||
| 197 | + ) | ||
| 126 | .nest("/terms", web::terms::routes()) | 198 | .nest("/terms", web::terms::routes()) |
| 127 | - .nest("/boards", web::boards::routes()) | 199 | + .nest( |
| 200 | + "/boards", | ||
| 201 | + gate(web::boards::routes(), &state, Module::Boards), | ||
| 202 | + ) | ||
| 128 | .split_for_parts(); | 203 | .split_for_parts(); |
| 129 | 204 | ||
| 130 | // Catch-all per-IP limit over every route (Swagger included). Kept inside | 205 | // Catch-all per-IP limit over every route (Swagger included). Kept inside |
src/migration_sql.rsmodified+8 -0
| @@ -1477,6 +1477,14 @@ pub const CONTROL_MIGRATION: &str = " | |||
| 1477 | DEFINE FIELD IF NOT EXISTS name 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; | 1478 | DEFINE FIELD IF NOT EXISTS status ON school TYPE string; |
| 1479 | DEFINE FIELD IF NOT EXISTS created_at ON school TYPE int; | 1479 | DEFINE FIELD IF NOT EXISTS created_at ON school TYPE int; |
| 1480 | + -- Which product modules this school has bought (see `crate::module`). The | ||
| 1481 | + -- names are bound from `Module::ALL`, never spelled here, so a new module | ||
| 1482 | + -- cannot be forgotten in this string. | ||
| 1483 | + DEFINE FIELD IF NOT EXISTS modules ON school TYPE array<string> DEFAULT []; | ||
| 1484 | + -- Only `NONE` — a row written before the field existed, which predates the | ||
| 1485 | + -- idea of buying modules and so had all of them. An empty array is a | ||
| 1486 | + -- deliberate \"nothing enabled\" and must never be re-widened by a boot. | ||
| 1487 | + UPDATE school SET modules = $all_modules WHERE modules = NONE; | ||
| 1480 | -- Redundant with the `school:<slug>` id, and kept anyway: the id is the | 1488 | -- 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 | 1489 | -- 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. | 1490 | -- impossible if a future write ever mints an id some other way. |
src/module.rsadded+425 -0
| @@ -0,0 +1,425 @@ | |||
| 1 | +//! Per-school **module entitlements**: which parts of the product a school has | ||
| 2 | +//! bought. A module is exactly one router nest (`/meals`, `/exams`, …), so the | ||
| 3 | +//! unit a school is sold and the unit the router refuses are the same thing — | ||
| 4 | +//! there is no per-route entitlement to keep in sync with a per-route guard. | ||
| 5 | +//! | ||
| 6 | +//! A disabled module answers `403 {"error":"module disabled","module":"<name>"}` | ||
| 7 | +//! on every route in its nest ([`crate::web::module_gate`]), while an unmatched | ||
| 8 | +//! path inside it still `404`s, because the gate is a `route_layer`. | ||
| 9 | +//! | ||
| 10 | +//! Stored on the school registry row as bare lowercase strings, like | ||
| 11 | +//! [`crate::tenant::SchoolStatus`] — see [`crate::tenant::School::modules`]. | ||
| 12 | + | ||
| 13 | +use std::collections::BTreeSet; | ||
| 14 | + | ||
| 15 | +use serde::Serialize; | ||
| 16 | + | ||
| 17 | +use crate::error::{AppError, ValidationError}; | ||
| 18 | + | ||
| 19 | +/// One router nest a school may have switched on or off. | ||
| 20 | +/// | ||
| 21 | +/// `Ord` is the declaration order and is only ever used to key the | ||
| 22 | +/// [`ModuleSet`] — every user-visible ordering goes through | ||
| 23 | +/// [`ModuleSet::names`], which sorts the strings. | ||
| 24 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)] | ||
| 25 | +#[serde(rename_all = "snake_case")] | ||
| 26 | +pub enum Module { | ||
| 27 | + Chatbot, | ||
| 28 | + Notes, | ||
| 29 | + Messages, | ||
| 30 | + Events, | ||
| 31 | + Appointments, | ||
| 32 | + Courses, | ||
| 33 | + CourseNotes, | ||
| 34 | + Classes, | ||
| 35 | + Sessions, | ||
| 36 | + Exams, | ||
| 37 | + Marks, | ||
| 38 | + Meals, | ||
| 39 | + Payments, | ||
| 40 | + Work, | ||
| 41 | + Pomodoro, | ||
| 42 | + Questions, | ||
| 43 | + BankQuestions, | ||
| 44 | + Attendance, | ||
| 45 | + Subjects, | ||
| 46 | + Homework, | ||
| 47 | + Boards, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// The commercial bundle a module is sold in. A package is a name for a set of | ||
| 51 | +/// modules and nothing more — entitlement is always stored per module, so a | ||
| 52 | +/// re-packaging never has to migrate a school's row. | ||
| 53 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] | ||
| 54 | +#[serde(rename_all = "snake_case")] | ||
| 55 | +pub enum Package { | ||
| 56 | + Academics, | ||
| 57 | + Communication, | ||
| 58 | + Operations, | ||
| 59 | + Ai, | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +impl Module { | ||
| 63 | + pub const ALL: [Module; 21] = [ | ||
| 64 | + Module::Chatbot, | ||
| 65 | + Module::Notes, | ||
| 66 | + Module::Messages, | ||
| 67 | + Module::Events, | ||
| 68 | + Module::Appointments, | ||
| 69 | + Module::Courses, | ||
| 70 | + Module::CourseNotes, | ||
| 71 | + Module::Classes, | ||
| 72 | + Module::Sessions, | ||
| 73 | + Module::Exams, | ||
| 74 | + Module::Marks, | ||
| 75 | + Module::Meals, | ||
| 76 | + Module::Payments, | ||
| 77 | + Module::Work, | ||
| 78 | + Module::Pomodoro, | ||
| 79 | + Module::Questions, | ||
| 80 | + Module::BankQuestions, | ||
| 81 | + Module::Attendance, | ||
| 82 | + Module::Subjects, | ||
| 83 | + Module::Homework, | ||
| 84 | + Module::Boards, | ||
| 85 | + ]; | ||
| 86 | + | ||
| 87 | + pub fn as_str(self) -> &'static str { | ||
| 88 | + match self { | ||
| 89 | + Module::Chatbot => "chatbot", | ||
| 90 | + Module::Notes => "notes", | ||
| 91 | + Module::Messages => "messages", | ||
| 92 | + Module::Events => "events", | ||
| 93 | + Module::Appointments => "appointments", | ||
| 94 | + Module::Courses => "courses", | ||
| 95 | + Module::CourseNotes => "course_notes", | ||
| 96 | + Module::Classes => "classes", | ||
| 97 | + Module::Sessions => "sessions", | ||
| 98 | + Module::Exams => "exams", | ||
| 99 | + Module::Marks => "marks", | ||
| 100 | + Module::Meals => "meals", | ||
| 101 | + Module::Payments => "payments", | ||
| 102 | + Module::Work => "work", | ||
| 103 | + Module::Pomodoro => "pomodoro", | ||
| 104 | + Module::Questions => "questions", | ||
| 105 | + Module::BankQuestions => "bank_questions", | ||
| 106 | + Module::Attendance => "attendance", | ||
| 107 | + Module::Subjects => "subjects", | ||
| 108 | + Module::Homework => "homework", | ||
| 109 | + Module::Boards => "boards", | ||
| 110 | + } | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + pub fn try_from_str(value: &str) -> Result<Self, ValidationError> { | ||
| 114 | + Module::ALL | ||
| 115 | + .into_iter() | ||
| 116 | + .find(|m| m.as_str() == value) | ||
| 117 | + .ok_or_else(|| ValidationError::Unknown { | ||
| 118 | + field: "module", | ||
| 119 | + value: value.to_string(), | ||
| 120 | + }) | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + /// The modules this one cannot work without. Every edge is a hard | ||
| 124 | + /// structural reference — a `record<…>` field in | ||
| 125 | + /// [`crate::migration_sql`] or a handler that reads the other module's row | ||
| 126 | + /// — never a merely-nicer-together pairing; the evidence is on each line. | ||
| 127 | + pub fn requires(self) -> &'static [Module] { | ||
| 128 | + match self { | ||
| 129 | + // `DEFINE FIELD course ON subject TYPE record<course>` | ||
| 130 | + Module::Subjects => &[Module::Courses], | ||
| 131 | + // `DEFINE FIELD course ON course_note TYPE record<course>` | ||
| 132 | + Module::CourseNotes => &[Module::Courses], | ||
| 133 | + // `DEFINE FIELD course ON course_session TYPE record<course>` | ||
| 134 | + Module::Sessions => &[Module::Courses], | ||
| 135 | + // `DEFINE FIELD course ON exam TYPE record<course>` + | ||
| 136 | + // `DEFINE FIELD subject ON exam_question TYPE record<subject>` | ||
| 137 | + Module::Exams => &[Module::Courses, Module::Subjects], | ||
| 138 | + // `DEFINE FIELD course ON homework TYPE record<course>` + | ||
| 139 | + // `DEFINE FIELD subject ON homework TYPE record<subject>` | ||
| 140 | + Module::Homework => &[Module::Courses, Module::Subjects], | ||
| 141 | + // `DEFINE FIELD course ON class_course TYPE record<course>` — a | ||
| 142 | + // class is bulk enrollment into courses. | ||
| 143 | + Module::Classes => &[Module::Courses], | ||
| 144 | + // `DEFINE FIELD exam ON exam_result TYPE record<exam>`; the marks | ||
| 145 | + // report is a weighted read of exam results. | ||
| 146 | + Module::Marks => &[Module::Exams], | ||
| 147 | + // The report tallies both halves: `attendance.event | ||
| 148 | + // record<event>` and `session_attendance.session | ||
| 149 | + // record<course_session>`. | ||
| 150 | + Module::Attendance => &[Module::Events, Module::Sessions], | ||
| 151 | + // No edge: `bank_question.subject` is `option<record<subject>>`, | ||
| 152 | + // so a bank question stands on its own. | ||
| 153 | + _ => &[], | ||
| 154 | + } | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + pub fn package(self) -> Package { | ||
| 158 | + match self { | ||
| 159 | + Module::Courses | ||
| 160 | + | Module::Subjects | ||
| 161 | + | Module::Sessions | ||
| 162 | + | Module::Exams | ||
| 163 | + | Module::Marks | ||
| 164 | + | Module::Homework | ||
| 165 | + | Module::Classes | ||
| 166 | + | Module::CourseNotes | ||
| 167 | + | Module::Attendance | ||
| 168 | + | Module::BankQuestions => Package::Academics, | ||
| 169 | + Module::Notes | ||
| 170 | + | Module::Messages | ||
| 171 | + | Module::Events | ||
| 172 | + | Module::Appointments | ||
| 173 | + | Module::Questions | ||
| 174 | + | Module::Boards => Package::Communication, | ||
| 175 | + Module::Meals | Module::Payments | Module::Work | Module::Pomodoro => { | ||
| 176 | + Package::Operations | ||
| 177 | + } | ||
| 178 | + Module::Chatbot => Package::Ai, | ||
| 179 | + } | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + /// The modules that require this one — the reverse of [`Module::requires`], | ||
| 183 | + /// derived rather than written down, so the two can never disagree. | ||
| 184 | + pub fn dependents(self) -> Vec<Module> { | ||
| 185 | + Module::ALL | ||
| 186 | + .into_iter() | ||
| 187 | + .filter(|other| other.requires().contains(&self)) | ||
| 188 | + .collect() | ||
| 189 | + } | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +impl std::fmt::Display for Module { | ||
| 193 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 194 | + f.write_str(self.as_str()) | ||
| 195 | + } | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +impl Package { | ||
| 199 | + pub const ALL: [Package; 4] = [ | ||
| 200 | + Package::Academics, | ||
| 201 | + Package::Communication, | ||
| 202 | + Package::Operations, | ||
| 203 | + Package::Ai, | ||
| 204 | + ]; | ||
| 205 | + | ||
| 206 | + pub fn as_str(self) -> &'static str { | ||
| 207 | + match self { | ||
| 208 | + Package::Academics => "academics", | ||
| 209 | + Package::Communication => "communication", | ||
| 210 | + Package::Operations => "operations", | ||
| 211 | + Package::Ai => "ai", | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + pub fn try_from_str(value: &str) -> Result<Self, ValidationError> { | ||
| 216 | + Package::ALL | ||
| 217 | + .into_iter() | ||
| 218 | + .find(|p| p.as_str() == value) | ||
| 219 | + .ok_or_else(|| ValidationError::Unknown { | ||
| 220 | + field: "package", | ||
| 221 | + value: value.to_string(), | ||
| 222 | + }) | ||
| 223 | + } | ||
| 224 | + | ||
| 225 | + /// The modules this package sells, derived from [`Module::package`]. | ||
| 226 | + pub fn modules(self) -> Vec<Module> { | ||
| 227 | + Module::ALL | ||
| 228 | + .into_iter() | ||
| 229 | + .filter(|m| m.package() == self) | ||
| 230 | + .collect() | ||
| 231 | + } | ||
| 232 | +} | ||
| 233 | + | ||
| 234 | +/// What one school has switched on. Ordered, so a set has exactly one | ||
| 235 | +/// serialization and a diff between two schools reads the same every time. | ||
| 236 | +#[derive(Debug, Clone, PartialEq, Eq, Default)] | ||
| 237 | +pub struct ModuleSet(BTreeSet<Module>); | ||
| 238 | + | ||
| 239 | +impl ModuleSet { | ||
| 240 | + pub fn all() -> Self { | ||
| 241 | + ModuleSet(Module::ALL.into_iter().collect()) | ||
| 242 | + } | ||
| 243 | + | ||
| 244 | + pub fn empty() -> Self { | ||
| 245 | + ModuleSet(BTreeSet::new()) | ||
| 246 | + } | ||
| 247 | + | ||
| 248 | + pub fn contains(&self, module: Module) -> bool { | ||
| 249 | + self.0.contains(&module) | ||
| 250 | + } | ||
| 251 | + | ||
| 252 | + pub fn insert(&mut self, module: Module) { | ||
| 253 | + self.0.insert(module); | ||
| 254 | + } | ||
| 255 | + | ||
| 256 | + pub fn remove(&mut self, module: Module) { | ||
| 257 | + self.0.remove(&module); | ||
| 258 | + } | ||
| 259 | + | ||
| 260 | + pub fn iter(&self) -> impl Iterator<Item = Module> + '_ { | ||
| 261 | + self.0.iter().copied() | ||
| 262 | + } | ||
| 263 | + | ||
| 264 | + pub fn is_empty(&self) -> bool { | ||
| 265 | + self.0.is_empty() | ||
| 266 | + } | ||
| 267 | + | ||
| 268 | + /// Parse a client-supplied list. An unknown name is refused by name rather | ||
| 269 | + /// than dropped: silently ignoring it would sell a school a module that | ||
| 270 | + /// does not exist and report success. | ||
| 271 | + pub fn from_names(names: &[String]) -> Result<Self, ValidationError> { | ||
| 272 | + let mut set = BTreeSet::new(); | ||
| 273 | + for name in names { | ||
| 274 | + set.insert(Module::try_from_str(name)?); | ||
| 275 | + } | ||
| 276 | + Ok(ModuleSet(set)) | ||
| 277 | + } | ||
| 278 | + | ||
| 279 | + /// The stored form: sorted, so the row is byte-stable. | ||
| 280 | + pub fn names(&self) -> Vec<String> { | ||
| 281 | + let mut names: Vec<String> = self.iter().map(|m| m.as_str().to_string()).collect(); | ||
| 282 | + names.sort(); | ||
| 283 | + names | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + /// Every `(module, missing requirement)` pair this set holds, in a stable | ||
| 287 | + /// order. | ||
| 288 | + pub fn missing_requirements(&self) -> Vec<(Module, Module)> { | ||
| 289 | + self.iter() | ||
| 290 | + .flat_map(|module| { | ||
| 291 | + module | ||
| 292 | + .requires() | ||
| 293 | + .iter() | ||
| 294 | + .filter(|needed| !self.contains(**needed)) | ||
| 295 | + .map(move |needed| (module, *needed)) | ||
| 296 | + }) | ||
| 297 | + .collect() | ||
| 298 | + } | ||
| 299 | + | ||
| 300 | + /// Refuse a set that switches a module on without what it structurally | ||
| 301 | + /// needs. One `409` naming **every** violation, so a caller fixing a set | ||
| 302 | + /// does not discover them one round trip at a time. | ||
| 303 | + pub fn validate(&self) -> Result<(), AppError> { | ||
| 304 | + let missing = self.missing_requirements(); | ||
| 305 | + if missing.is_empty() { | ||
| 306 | + return Ok(()); | ||
| 307 | + } | ||
| 308 | + let message = missing | ||
| 309 | + .into_iter() | ||
| 310 | + .map(|(module, needed)| format!("{module} requires {needed}, which is not enabled")) | ||
| 311 | + .collect::<Vec<_>>() | ||
| 312 | + .join("; "); | ||
| 313 | + Err(AppError::ConflictOwned(message)) | ||
| 314 | + } | ||
| 315 | +} | ||
| 316 | + | ||
| 317 | +#[cfg(test)] | ||
| 318 | +mod tests { | ||
| 319 | + use super::*; | ||
| 320 | + | ||
| 321 | + #[test] | ||
| 322 | + fn every_module_names_itself_and_round_trips() { | ||
| 323 | + assert_eq!(Module::ALL.len(), 21); | ||
| 324 | + let mut seen = BTreeSet::new(); | ||
| 325 | + for module in Module::ALL { | ||
| 326 | + assert!(seen.insert(module.as_str()), "duplicate {module}"); | ||
| 327 | + assert_eq!(Module::try_from_str(module.as_str()).unwrap(), module); | ||
| 328 | + } | ||
| 329 | + assert!(Module::try_from_str("course-notes").is_err(), "snake_case"); | ||
| 330 | + assert!(Module::try_from_str("").is_err()); | ||
| 331 | + } | ||
| 332 | + | ||
| 333 | + /// A cycle would make some set of modules unsatisfiable — every member | ||
| 334 | + /// would need another member that needs it back. | ||
| 335 | + #[test] | ||
| 336 | + fn the_dependency_graph_is_acyclic() { | ||
| 337 | + fn depth(module: Module, seen: &mut Vec<Module>) { | ||
| 338 | + assert!(!seen.contains(&module), "cycle through {module}: {seen:?}"); | ||
| 339 | + seen.push(module); | ||
| 340 | + for needed in module.requires() { | ||
| 341 | + depth(*needed, seen); | ||
| 342 | + } | ||
| 343 | + seen.pop(); | ||
| 344 | + } | ||
| 345 | + for module in Module::ALL { | ||
| 346 | + depth(module, &mut Vec::new()); | ||
| 347 | + } | ||
| 348 | + } | ||
| 349 | + | ||
| 350 | + #[test] | ||
| 351 | + fn every_module_is_sold_in_exactly_one_package() { | ||
| 352 | + let packaged: Vec<Module> = Package::ALL | ||
| 353 | + .into_iter() | ||
| 354 | + .flat_map(Package::modules) | ||
| 355 | + .collect(); | ||
| 356 | + assert_eq!(packaged.len(), Module::ALL.len()); | ||
| 357 | + for module in Module::ALL { | ||
| 358 | + assert_eq!( | ||
| 359 | + packaged.iter().filter(|m| **m == module).count(), | ||
| 360 | + 1, | ||
| 361 | + "{module} is not in exactly one package" | ||
| 362 | + ); | ||
| 363 | + } | ||
| 364 | + } | ||
| 365 | + | ||
| 366 | + #[test] | ||
| 367 | + fn dependents_is_the_exact_reverse_of_requires() { | ||
| 368 | + for module in Module::ALL { | ||
| 369 | + for dependent in module.dependents() { | ||
| 370 | + assert!(dependent.requires().contains(&module)); | ||
| 371 | + } | ||
| 372 | + for needed in module.requires() { | ||
| 373 | + assert!(needed.dependents().contains(&module)); | ||
| 374 | + } | ||
| 375 | + } | ||
| 376 | + // The phrasing a caller builds from the reverse edges. | ||
| 377 | + assert_eq!(Module::Exams.dependents(), vec![Module::Marks]); | ||
| 378 | + assert_eq!( | ||
| 379 | + Module::Courses.dependents(), | ||
| 380 | + vec![ | ||
| 381 | + Module::CourseNotes, | ||
| 382 | + Module::Classes, | ||
| 383 | + Module::Sessions, | ||
| 384 | + Module::Exams, | ||
| 385 | + Module::Subjects, | ||
| 386 | + Module::Homework, | ||
| 387 | + ] | ||
| 388 | + ); | ||
| 389 | + } | ||
| 390 | + | ||
| 391 | + #[test] | ||
| 392 | + fn a_full_set_is_valid_and_a_lone_module_names_all_it_misses() { | ||
| 393 | + assert!(ModuleSet::all().validate().is_ok()); | ||
| 394 | + assert!(ModuleSet::empty().validate().is_ok()); | ||
| 395 | + | ||
| 396 | + let mut lone = ModuleSet::empty(); | ||
| 397 | + lone.insert(Module::Exams); | ||
| 398 | + let err = lone.validate().expect_err("exams alone is unsatisfiable"); | ||
| 399 | + let message = err.to_string(); | ||
| 400 | + assert!( | ||
| 401 | + message.contains("exams requires courses, which is not enabled"), | ||
| 402 | + "{message}" | ||
| 403 | + ); | ||
| 404 | + assert!( | ||
| 405 | + message.contains("exams requires subjects, which is not enabled"), | ||
| 406 | + "both misses in one message: {message}" | ||
| 407 | + ); | ||
| 408 | + assert!(matches!(err, AppError::ConflictOwned(_))); | ||
| 409 | + } | ||
| 410 | + | ||
| 411 | + #[test] | ||
| 412 | + fn names_round_trip_and_an_unknown_name_is_refused() { | ||
| 413 | + let all = ModuleSet::all(); | ||
| 414 | + let names = all.names(); | ||
| 415 | + assert_eq!(names.len(), 21); | ||
| 416 | + assert!(names.windows(2).all(|w| w[0] < w[1]), "sorted: {names:?}"); | ||
| 417 | + assert_eq!(ModuleSet::from_names(&names).unwrap(), all); | ||
| 418 | + | ||
| 419 | + let err = ModuleSet::from_names(&["meals".into(), "kantin".into()]).unwrap_err(); | ||
| 420 | + assert!( | ||
| 421 | + err.to_string().contains("`kantin`"), | ||
| 422 | + "names the offender: {err}" | ||
| 423 | + ); | ||
| 424 | + } | ||
| 425 | +} | ||
src/tenant.rsmodified+80 -10
| @@ -33,6 +33,8 @@ use crate::database::{Database, lost_the_race, migrate, migrate_control}; | |||
| 33 | use crate::domain::page::PagedList; | 33 | use crate::domain::page::PagedList; |
| 34 | use crate::domain::timestamp::Timestamp; | 34 | use crate::domain::timestamp::Timestamp; |
| 35 | use crate::error::{AppError, ValidationError}; | 35 | use crate::error::{AppError, ValidationError}; |
| 36 | +use crate::module::ModuleSet; | ||
| 37 | +use crate::web::tenant_state::ResolvedTenant; | ||
| 36 | 38 | ||
| 37 | pub(crate) const SCHOOL_TABLE: &str = "school"; | 39 | pub(crate) const SCHOOL_TABLE: &str = "school"; |
| 38 | 40 | ||
| @@ -169,6 +171,11 @@ pub struct School { | |||
| 169 | name: String, | 171 | name: String, |
| 170 | status: SchoolStatus, | 172 | status: SchoolStatus, |
| 171 | created_at: Timestamp, | 173 | created_at: Timestamp, |
| 174 | + /// Which product modules this school has bought, as their stored names. | ||
| 175 | + /// Kept as strings rather than a [`ModuleSet`] so a name this binary does | ||
| 176 | + /// not know (an older deploy reading a newer row) is data to ignore, not a | ||
| 177 | + /// deserialization failure that would lock the school out entirely. | ||
| 178 | + modules: Vec<String>, | ||
| 172 | } | 179 | } |
| 173 | 180 | ||
| 174 | impl School { | 181 | impl School { |
| @@ -192,6 +199,23 @@ impl School { | |||
| 192 | self.created_at | 199 | self.created_at |
| 193 | } | 200 | } |
| 194 | 201 | ||
| 202 | + /// The stored names as modules. An unknown name is dropped with a warning | ||
| 203 | + /// — see the field's comment: a school must never become unreachable | ||
| 204 | + /// because of a word this binary has not heard of. | ||
| 205 | + pub fn modules(&self) -> ModuleSet { | ||
| 206 | + let mut set = ModuleSet::empty(); | ||
| 207 | + for name in &self.modules { | ||
| 208 | + match crate::module::Module::try_from_str(name) { | ||
| 209 | + Ok(module) => set.insert(module), | ||
| 210 | + Err(_) => tracing::warn!( | ||
| 211 | + "school {} has an unknown module `{name}` — ignoring it", | ||
| 212 | + self.slug | ||
| 213 | + ), | ||
| 214 | + } | ||
| 215 | + } | ||
| 216 | + set | ||
| 217 | + } | ||
| 218 | + | ||
| 195 | pub async fn read(slug: &Slug, control: &Database) -> Result<Option<School>, AppError> { | 219 | pub async fn read(slug: &Slug, control: &Database) -> Result<Option<School>, AppError> { |
| 196 | Ok(control.select(SchoolId::from_slug(slug).record()).await?) | 220 | Ok(control.select(SchoolId::from_slug(slug).record()).await?) |
| 197 | } | 221 | } |
| @@ -296,6 +320,7 @@ impl Tenants { | |||
| 296 | name: name.to_string(), | 320 | name: name.to_string(), |
| 297 | status: SchoolStatus::Active, | 321 | status: SchoolStatus::Active, |
| 298 | created_at: Timestamp::now(), | 322 | created_at: Timestamp::now(), |
| 323 | + modules: ModuleSet::all().names(), | ||
| 299 | }; | 324 | }; |
| 300 | let _: Option<School> = tenants | 325 | let _: Option<School> = tenants |
| 301 | .control | 326 | .control |
| @@ -326,13 +351,24 @@ impl Tenants { | |||
| 326 | /// if it ever shows up in a profile — the eviction in [`Tenants::set_status`] | 351 | /// if it ever shows up in a profile — the eviction in [`Tenants::set_status`] |
| 327 | /// is already there to make a cached decision safe. | 352 | /// is already there to make a cached decision safe. |
| 328 | pub async fn get(&self, slug: &Slug) -> Result<Database, AppError> { | 353 | pub async fn get(&self, slug: &Slug) -> Result<Database, AppError> { |
| 354 | + Ok(self.resolve(slug).await?.db) | ||
| 355 | + } | ||
| 356 | + | ||
| 357 | + /// [`Tenants::get`] plus what that one registry read already knew: the | ||
| 358 | + /// school's module entitlements. Same verdicts, same single read — a | ||
| 359 | + /// caller that needs both must never pay for two. | ||
| 360 | + pub async fn resolve(&self, slug: &Slug) -> Result<ResolvedTenant, AppError> { | ||
| 329 | match School::read(slug, &self.control).await? { | 361 | match School::read(slug, &self.control).await? { |
| 330 | None => Err(AppError::Unauthorized), | 362 | None => Err(AppError::Unauthorized), |
| 331 | Some(school) if school.status == SchoolStatus::Suspended => { | 363 | Some(school) if school.status == SchoolStatus::Suspended => { |
| 332 | self.evict(slug); | 364 | self.evict(slug); |
| 333 | Err(AppError::Forbidden("school is suspended")) | 365 | Err(AppError::Forbidden("school is suspended")) |
| 334 | } | 366 | } |
| 335 | - Some(_) => self.handle(slug).await, | 367 | + Some(school) => Ok(ResolvedTenant { |
| 368 | + slug: slug.clone(), | ||
| 369 | + db: self.handle(slug).await?, | ||
| 370 | + modules: school.modules(), | ||
| 371 | + }), | ||
| 336 | } | 372 | } |
| 337 | } | 373 | } |
| 338 | 374 | ||
| @@ -349,13 +385,19 @@ impl Tenants { | |||
| 349 | /// Register a school and bring its database into being: registry row first | 385 | /// Register a school and bring its database into being: registry row first |
| 350 | /// (so a lost race is a `409` and not a half-made database), then | 386 | /// (so a lost race is a `409` and not a half-made database), then |
| 351 | /// `DEFINE DATABASE`, then the school schema. | 387 | /// `DEFINE DATABASE`, then the school schema. |
| 352 | - pub async fn create(&self, slug: &Slug, name: &str) -> Result<Database, AppError> { | 388 | + pub async fn create( |
| 389 | + &self, | ||
| 390 | + slug: &Slug, | ||
| 391 | + name: &str, | ||
| 392 | + modules: ModuleSet, | ||
| 393 | + ) -> Result<Database, AppError> { | ||
| 353 | let school = School { | 394 | let school = School { |
| 354 | id: SchoolId::from_slug(slug), | 395 | id: SchoolId::from_slug(slug), |
| 355 | slug: slug.clone(), | 396 | slug: slug.clone(), |
| 356 | name: name.to_string(), | 397 | name: name.to_string(), |
| 357 | status: SchoolStatus::Active, | 398 | status: SchoolStatus::Active, |
| 358 | created_at: Timestamp::now(), | 399 | created_at: Timestamp::now(), |
| 400 | + modules: modules.names(), | ||
| 359 | }; | 401 | }; |
| 360 | let created: Result<Option<School>, surrealdb::Error> = self | 402 | let created: Result<Option<School>, surrealdb::Error> = self |
| 361 | .control | 403 | .control |
| @@ -437,6 +479,25 @@ impl Tenants { | |||
| 437 | Ok(()) | 479 | Ok(()) |
| 438 | } | 480 | } |
| 439 | 481 | ||
| 482 | + /// Sell (or take back) modules. Mirrors [`Tenants::set_status`] minus the | ||
| 483 | + /// eviction: entitlements are read off the registry row on every request, | ||
| 484 | + /// so a change takes effect on the next call and no cached handle carries a | ||
| 485 | + /// stale answer. | ||
| 486 | + pub async fn set_modules(&self, slug: &Slug, modules: &ModuleSet) -> Result<(), AppError> { | ||
| 487 | + let updated: Vec<School> = self | ||
| 488 | + .control | ||
| 489 | + .query("UPDATE $id SET modules = $modules RETURN AFTER") | ||
| 490 | + .bind(("id", SchoolId::from_slug(slug).record())) | ||
| 491 | + .bind(("modules", modules.names())) | ||
| 492 | + .await? | ||
| 493 | + .check()? | ||
| 494 | + .take(0)?; | ||
| 495 | + if updated.is_empty() { | ||
| 496 | + return Err(AppError::NotFound); | ||
| 497 | + } | ||
| 498 | + Ok(()) | ||
| 499 | + } | ||
| 500 | + | ||
| 440 | /// Delete a school outright: its data, then its registry row, then its | 501 | /// Delete a school outright: its data, then its registry row, then its |
| 441 | /// handle. Irreversible on purpose — there is no soft-delete state, that is | 502 | /// handle. Irreversible on purpose — there is no soft-delete state, that is |
| 442 | /// what [`SchoolStatus::Suspended`] is for. | 503 | /// what [`SchoolStatus::Suspended`] is for. |
| @@ -580,8 +641,8 @@ mod tests { | |||
| 580 | async fn two_schools_do_not_see_each_others_rows() { | 641 | async fn two_schools_do_not_see_each_others_rows() { |
| 581 | let tenants = Tenants::new_mem().await.unwrap(); | 642 | let tenants = Tenants::new_mem().await.unwrap(); |
| 582 | let (a, b) = (slug("alpha"), slug("beta")); | 643 | let (a, b) = (slug("alpha"), slug("beta")); |
| 583 | - let one = tenants.create(&a, "Alpha").await.unwrap(); | 644 | + let one = tenants.create(&a, "Alpha", ModuleSet::all()).await.unwrap(); |
| 584 | - let two = tenants.create(&b, "Beta").await.unwrap(); | 645 | + let two = tenants.create(&b, "Beta", ModuleSet::all()).await.unwrap(); |
| 585 | 646 | ||
| 586 | one.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") | 647 | one.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") |
| 587 | .await | 648 | .await |
| @@ -596,7 +657,7 @@ mod tests { | |||
| 596 | ); | 657 | ); |
| 597 | // A second `create` on a taken slug is a conflict, not a second school. | 658 | // A second `create` on a taken slug is a conflict, not a second school. |
| 598 | assert!(matches!( | 659 | assert!(matches!( |
| 599 | - tenants.create(&a, "Alpha again").await, | 660 | + tenants.create(&a, "Alpha again", ModuleSet::all()).await, |
| 600 | Err(AppError::Conflict(_)) | 661 | Err(AppError::Conflict(_)) |
| 601 | )); | 662 | )); |
| 602 | } | 663 | } |
| @@ -605,7 +666,7 @@ mod tests { | |||
| 605 | async fn suspending_refuses_the_school_and_the_handle_it_already_had() { | 666 | async fn suspending_refuses_the_school_and_the_handle_it_already_had() { |
| 606 | let tenants = Tenants::new_mem().await.unwrap(); | 667 | let tenants = Tenants::new_mem().await.unwrap(); |
| 607 | let s = slug("alpha"); | 668 | let s = slug("alpha"); |
| 608 | - tenants.create(&s, "Alpha").await.unwrap(); | 669 | + tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); |
| 609 | // Cached by the first resolve; the suspension must beat the cache. | 670 | // Cached by the first resolve; the suspension must beat the cache. |
| 610 | tenants.get(&s).await.expect("active school resolves"); | 671 | tenants.get(&s).await.expect("active school resolves"); |
| 611 | 672 | ||
| @@ -638,7 +699,7 @@ mod tests { | |||
| 638 | async fn dropping_a_school_takes_its_rows_with_it() { | 699 | async fn dropping_a_school_takes_its_rows_with_it() { |
| 639 | let tenants = Tenants::new_mem().await.unwrap(); | 700 | let tenants = Tenants::new_mem().await.unwrap(); |
| 640 | let s = slug("alpha"); | 701 | let s = slug("alpha"); |
| 641 | - let db = tenants.create(&s, "Alpha").await.unwrap(); | 702 | + let db = tenants.create(&s, "Alpha", ModuleSet::all()).await.unwrap(); |
| 642 | db.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") | 703 | db.query("CREATE user SET username = 'ada', password_hash = 'x', role = 'student'") |
| 643 | .await | 704 | .await |
| 644 | .unwrap() | 705 | .unwrap() |
| @@ -649,7 +710,10 @@ mod tests { | |||
| 649 | tenants.drop(&s).await.unwrap(); | 710 | tenants.drop(&s).await.unwrap(); |
| 650 | assert!(matches!(tenants.get(&s).await, Err(AppError::Unauthorized))); | 711 | assert!(matches!(tenants.get(&s).await, Err(AppError::Unauthorized))); |
| 651 | 712 | ||
| 652 | - let fresh = tenants.create(&s, "Alpha reborn").await.unwrap(); | 713 | + let fresh = tenants |
| 714 | + .create(&s, "Alpha reborn", ModuleSet::all()) | ||
| 715 | + .await | ||
| 716 | + .unwrap(); | ||
| 653 | assert_eq!( | 717 | assert_eq!( |
| 654 | count(&fresh, "user").await, | 718 | count(&fresh, "user").await, |
| 655 | 0, | 719 | 0, |
| @@ -660,8 +724,14 @@ mod tests { | |||
| 660 | #[tokio::test] | 724 | #[tokio::test] |
| 661 | async fn the_registry_lists_and_renames() { | 725 | async fn the_registry_lists_and_renames() { |
| 662 | let tenants = Tenants::new_mem().await.unwrap(); | 726 | let tenants = Tenants::new_mem().await.unwrap(); |
| 663 | - tenants.create(&slug("alpha"), "Alpha").await.unwrap(); | 727 | + tenants |
| 664 | - tenants.create(&slug("beta"), "Beta").await.unwrap(); | 728 | + .create(&slug("alpha"), "Alpha", ModuleSet::all()) |
| 729 | + .await | ||
| 730 | + .unwrap(); | ||
| 731 | + tenants | ||
| 732 | + .create(&slug("beta"), "Beta", ModuleSet::all()) | ||
| 733 | + .await | ||
| 734 | + .unwrap(); | ||
| 665 | 735 | ||
| 666 | let (rows, total) = School::list(None, 0, tenants.control()).await.unwrap(); | 736 | let (rows, total) = School::list(None, 0, tenants.control()).await.unwrap(); |
| 667 | assert_eq!(total, 2); | 737 | assert_eq!(total, 2); |
src/web/board_ws.rsmodified+2 -0
| @@ -581,6 +581,8 @@ fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value { | |||
| 581 | AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict", | 581 | AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict", |
| 582 | AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid", | 582 | AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid", |
| 583 | AppError::NotFound => "not_found", | 583 | AppError::NotFound => "not_found", |
| 584 | + // See `room::public_message`: the gate refuses the upgrade first. | ||
| 585 | + AppError::ModuleDisabled(_) => "module_disabled", | ||
| 584 | AppError::Unauthorized => "unauthorized", | 586 | AppError::Unauthorized => "unauthorized", |
| 585 | AppError::TooManyRequests { .. } => "too_many_requests", | 587 | AppError::TooManyRequests { .. } => "too_many_requests", |
| 586 | AppError::DbUnavailable | AppError::DbTimeout | AppError::Db(_) | AppError::Internal(_) => { | 588 | AppError::DbUnavailable | AppError::DbTimeout | AppError::Db(_) | AppError::Internal(_) => { |
src/web/builder.rsmodified+6 -1
| @@ -294,7 +294,12 @@ async fn create_school( | |||
| 294 | let username = Username::try_new(&req.admin_username)?; | 294 | let username = Username::try_new(&req.admin_username)?; |
| 295 | let password_hash = Password::try_new(&req.admin_password)?.hash_async().await?; | 295 | let password_hash = Password::try_new(&req.admin_password)?.hash_async().await?; |
| 296 | 296 | ||
| 297 | - let db = st.tenants.create(&slug, &name).await?; | 297 | + // Everything, for now: choosing a school's modules is the next lane's |
| 298 | + // HTTP surface (`crate::module` is the foundation it will call). | ||
| 299 | + let db = st | ||
| 300 | + .tenants | ||
| 301 | + .create(&slug, &name, crate::module::ModuleSet::all()) | ||
| 302 | + .await?; | ||
| 298 | if let Err(err) = User::create_with_role(username, password_hash, Role::Admin, &db).await { | 303 | if let Err(err) = User::create_with_role(username, password_hash, Role::Admin, &db).await { |
| 299 | // A school nobody can log into is worse than no school: take the | 304 | // A school nobody can log into is worse than no school: take the |
| 300 | // database back so the very same request can simply be retried. | 305 | // database back so the very same request can simply be retried. |
src/web/chatbot.rsmodified+3 -1
| @@ -20,7 +20,7 @@ | |||
| 20 | 20 | ||
| 21 | use std::time::Duration; | 21 | use std::time::Duration; |
| 22 | 22 | ||
| 23 | -use crate::web::tenant_state::{SchoolSlug, State, TenantExt}; | 23 | +use crate::web::tenant_state::{ResolvedTenant, SchoolSlug, State, TenantExt}; |
| 24 | use axum::Json; | 24 | use axum::Json; |
| 25 | use axum::extract::{Path, Query}; | 25 | use axum::extract::{Path, Query}; |
| 26 | use axum::http::StatusCode; | 26 | use axum::http::StatusCode; |
| @@ -378,6 +378,7 @@ async fn list_messages( | |||
| 378 | async fn send_message( | 378 | async fn send_message( |
| 379 | State(st): State<AppState>, | 379 | State(st): State<AppState>, |
| 380 | SchoolSlug(slug): SchoolSlug, | 380 | SchoolSlug(slug): SchoolSlug, |
| 381 | + tenant: ResolvedTenant, | ||
| 381 | CurrentUser(user): CurrentUser, | 382 | CurrentUser(user): CurrentUser, |
| 382 | Path(id): Path<String>, | 383 | Path(id): Path<String>, |
| 383 | Json(req): Json<SendChatbotMessage>, | 384 | Json(req): Json<SendChatbotMessage>, |
| @@ -444,6 +445,7 @@ async fn send_message( | |||
| 444 | TenantExt { | 445 | TenantExt { |
| 445 | slug, | 446 | slug, |
| 446 | db: st.db.clone(), | 447 | db: st.db.clone(), |
| 448 | + modules: tenant.modules, | ||
| 447 | }, | 449 | }, |
| 448 | bridge, | 450 | bridge, |
| 449 | prompt.get_id().clone(), | 451 | prompt.get_id().clone(), |
src/web/courses.rsmodified+21 -4
| @@ -50,10 +50,27 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 50 | .routes(routes!(unassign_teacher)) | 50 | .routes(routes!(unassign_teacher)) |
| 51 | .routes(routes!(enroll, list_roster)) | 51 | .routes(routes!(enroll, list_roster)) |
| 52 | .routes(routes!(unenroll)) | 52 | .routes(routes!(unenroll)) |
| 53 | - .routes(routes!(create_exam_in_course, list_course_exams)) | 53 | +} |
| 54 | - .routes(routes!(create_session_in_course, list_course_sessions)) | 54 | + |
| 55 | - .routes(routes!(create_subject_in_course, list_course_subjects)) | 55 | +// The four route pairs below are mounted under `/courses` but *belong* to |
| 56 | - .routes(routes!(create_homework_in_course, list_course_homework)) | 56 | +// another module, so each is split out to carry that module's gate as well as |
| 57 | +// the course one — see `crate::web::module_gate`. They are merged back in | ||
| 58 | +// `build_router`, so the URL space is unchanged. | ||
| 59 | + | ||
| 60 | +pub fn exam_routes() -> OpenApiRouter<AppState> { | ||
| 61 | + OpenApiRouter::new().routes(routes!(create_exam_in_course, list_course_exams)) | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +pub fn session_routes() -> OpenApiRouter<AppState> { | ||
| 65 | + OpenApiRouter::new().routes(routes!(create_session_in_course, list_course_sessions)) | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +pub fn subject_routes() -> OpenApiRouter<AppState> { | ||
| 69 | + OpenApiRouter::new().routes(routes!(create_subject_in_course, list_course_subjects)) | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +pub fn homework_routes() -> OpenApiRouter<AppState> { | ||
| 73 | + OpenApiRouter::new().routes(routes!(create_homework_in_course, list_course_homework)) | ||
| 57 | } | 74 | } |
| 58 | 75 | ||
| 59 | #[derive(Deserialize, ToSchema)] | 76 | #[derive(Deserialize, ToSchema)] |
src/web/extractor.rsmodified+1 -1
| @@ -35,7 +35,7 @@ where | |||
| 35 | return Ok(principal.0.clone()); | 35 | return Ok(principal.0.clone()); |
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | - let (_, db) = resolve_tenant(parts, state).await?; | 38 | + let db = resolve_tenant(parts, state).await?.db; |
| 39 | 39 | ||
| 40 | let jar = CookieJar::from_request_parts(parts, state) | 40 | let jar = CookieJar::from_request_parts(parts, state) |
| 41 | .await | 41 | .await |
src/web/mod.rsmodified+1 -0
| @@ -24,6 +24,7 @@ pub mod limits; | |||
| 24 | pub mod marks; | 24 | pub mod marks; |
| 25 | pub mod meals; | 25 | pub mod meals; |
| 26 | pub mod messages; | 26 | pub mod messages; |
| 27 | +pub mod module_gate; | ||
| 27 | pub mod notes; | 28 | pub mod notes; |
| 28 | pub mod payments; | 29 | pub mod payments; |
| 29 | pub mod pomodoro; | 30 | pub mod pomodoro; |
src/web/module_gate.rsadded+71 -0
| @@ -0,0 +1,71 @@ | |||
| 1 | +//! The structural half of module entitlements: one gate per router nest. | ||
| 2 | +//! | ||
| 3 | +//! A module *is* a nest, so the gate is applied once where the nest is mounted | ||
| 4 | +//! (`crate::build_router`) rather than route by route — there is no list of | ||
| 5 | +//! guarded routes to keep in step with a list of routes, and a route added to | ||
| 6 | +//! a gated nest is gated by construction. | ||
| 7 | +//! | ||
| 8 | +//! It goes on with `route_layer`, not `layer`: an unmatched path inside a | ||
| 9 | +//! disabled nest must still be a `404`. A disabled module is not a wall around | ||
| 10 | +//! a URL space, it is a refusal on the routes that exist. | ||
| 11 | +//! | ||
| 12 | +//! # The nested exceptions | ||
| 13 | +//! | ||
| 14 | +//! Four route pairs live under `/courses` but belong to another module, and so | ||
| 15 | +//! carry a second gate of their own ([`crate::web::courses`] splits them out | ||
| 16 | +//! for exactly this): | ||
| 17 | +//! | ||
| 18 | +//! - `/courses/{id}/exams` → `Module::Exams` | ||
| 19 | +//! - `/courses/{id}/sessions` → `Module::Sessions` | ||
| 20 | +//! - `/courses/{id}/subjects` → `Module::Subjects` | ||
| 21 | +//! - `/courses/{id}/homework` → `Module::Homework` | ||
| 22 | +//! | ||
| 23 | +//! Both gates run (the child's, then the outer `/courses` one), so either | ||
| 24 | +//! module being off refuses — which is right: `POST /courses/{id}/exams` is an | ||
| 25 | +//! exams feature reached through a course. | ||
| 26 | +//! | ||
| 27 | +//! One surface this cannot reach: `crate::ai::server`'s blob stream, which | ||
| 28 | +//! answers `BlobRequest`s without going through the router at all. It checks | ||
| 29 | +//! `Module::CourseNotes` itself. | ||
| 30 | + | ||
| 31 | +use axum::extract::{Request, State}; | ||
| 32 | +use axum::middleware::{Next, from_fn_with_state}; | ||
| 33 | +use axum::response::{IntoResponse, Response}; | ||
| 34 | +use utoipa_axum::router::OpenApiRouter; | ||
| 35 | + | ||
| 36 | +use crate::error::AppError; | ||
| 37 | +use crate::module::Module; | ||
| 38 | +use crate::state::AppState; | ||
| 39 | +use crate::web::tenant_state::resolve_tenant; | ||
| 40 | + | ||
| 41 | +/// Wrap every route currently in `router` in `module`'s entitlement check. | ||
| 42 | +/// | ||
| 43 | +/// Takes and returns the router rather than handing back a bare `Layer`: the | ||
| 44 | +/// `from_fn_with_state` layer's type is unnameable (it wraps an async closure), | ||
| 45 | +/// so a function returning it could not be written down without boxing. The | ||
| 46 | +/// call site reads the same either way — `gate(notes::routes(), &state, | ||
| 47 | +/// Module::Notes)`. | ||
| 48 | +pub fn gate( | ||
| 49 | + router: OpenApiRouter<AppState>, | ||
| 50 | + state: &AppState, | ||
| 51 | + module: Module, | ||
| 52 | +) -> OpenApiRouter<AppState> { | ||
| 53 | + router.route_layer(from_fn_with_state((state.clone(), module), check)) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +async fn check( | ||
| 57 | + State((state, module)): State<(AppState, Module)>, | ||
| 58 | + request: Request, | ||
| 59 | + next: Next, | ||
| 60 | +) -> Response { | ||
| 61 | + let (mut parts, body) = request.into_parts(); | ||
| 62 | + match resolve_tenant(&mut parts, &state).await { | ||
| 63 | + Err(err) => err.into_response(), | ||
| 64 | + Ok(tenant) if !tenant.modules.contains(module) => { | ||
| 65 | + AppError::ModuleDisabled(module).into_response() | ||
| 66 | + } | ||
| 67 | + // `resolve_tenant` memoized the school on `parts`, so the handler's own | ||
| 68 | + // extractors reuse this read instead of making a second one. | ||
| 69 | + Ok(_) => next.run(Request::from_parts(parts, body)).await, | ||
| 70 | + } | ||
| 71 | +} | ||
src/web/room.rsmodified+4 -0
| @@ -91,6 +91,10 @@ pub(crate) fn public_message(err: &AppError, room: &str) -> String { | |||
| 91 | message.clone() | 91 | message.clone() |
| 92 | } | 92 | } |
| 93 | AppError::PayloadTooLarge(message) => message.clone(), | 93 | AppError::PayloadTooLarge(message) => message.clone(), |
| 94 | + // Unreachable in practice: the module gate refuses the upgrade before | ||
| 95 | + // a socket exists. Spelled out anyway so a new refusal never falls | ||
| 96 | + // into "internal server error" by default. | ||
| 97 | + AppError::ModuleDisabled(module) => format!("module disabled: {module}"), | ||
| 94 | AppError::TooManyRequests { .. } => "too many requests".to_string(), | 98 | AppError::TooManyRequests { .. } => "too many requests".to_string(), |
| 95 | AppError::DbUnavailable => { | 99 | AppError::DbUnavailable => { |
| 96 | tracing::warn!("{room}: database reconnecting"); | 100 | tracing::warn!("{room}: database reconnecting"); |
src/web/tenant_state.rsmodified+93 -8
| @@ -19,9 +19,22 @@ use axum_extra::extract::CookieJar; | |||
| 19 | 19 | ||
| 20 | use crate::database::Database; | 20 | use crate::database::Database; |
| 21 | use crate::error::AppError; | 21 | use crate::error::AppError; |
| 22 | +use crate::module::ModuleSet; | ||
| 22 | use crate::state::AppState; | 23 | use crate::state::AppState; |
| 23 | use crate::tenant::Slug; | 24 | use crate::tenant::Slug; |
| 24 | 25 | ||
| 26 | +/// Everything one registry read tells us about the school behind a request: | ||
| 27 | +/// its handle and what it has bought. Cached in the request's extensions by | ||
| 28 | +/// [`resolve_tenant`], so a request that needs the school twice (the shadow | ||
| 29 | +/// [`State`] *and* [`crate::web::CurrentUser`], which is most of them) reads | ||
| 30 | +/// the registry once. | ||
| 31 | +#[derive(Clone)] | ||
| 32 | +pub struct ResolvedTenant { | ||
| 33 | + pub slug: Slug, | ||
| 34 | + pub db: Database, | ||
| 35 | + pub modules: ModuleSet, | ||
| 36 | +} | ||
| 37 | + | ||
| 25 | /// The school a request has already been resolved into, injected as a request | 38 | /// 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 | 39 | /// 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 | 40 | /// bridge. Extensions cannot be set from outside the process, so this is |
| @@ -31,6 +44,7 @@ use crate::tenant::Slug; | |||
| 31 | pub struct TenantExt { | 44 | pub struct TenantExt { |
| 32 | pub slug: Slug, | 45 | pub slug: Slug, |
| 33 | pub db: Database, | 46 | pub db: Database, |
| 47 | + pub modules: ModuleSet, | ||
| 34 | } | 48 | } |
| 35 | 49 | ||
| 36 | /// Split a `session` cookie into its school part and its token. `builder` in | 50 | /// 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)> { | |||
| 52 | pub(crate) async fn resolve_tenant<S>( | 66 | pub(crate) async fn resolve_tenant<S>( |
| 53 | parts: &mut Parts, | 67 | parts: &mut Parts, |
| 54 | state: &S, | 68 | state: &S, |
| 55 | -) -> Result<(Slug, Database), AppError> | 69 | +) -> Result<ResolvedTenant, AppError> |
| 56 | where | 70 | where |
| 57 | S: Send + Sync, | 71 | S: Send + Sync, |
| 58 | AppState: FromRef<S>, | 72 | AppState: FromRef<S>, |
| 59 | { | 73 | { |
| 74 | + if let Some(tenant) = parts.extensions.get::<ResolvedTenant>() { | ||
| 75 | + return Ok(tenant.clone()); | ||
| 76 | + } | ||
| 60 | if let Some(tenant) = parts.extensions.get::<TenantExt>() { | 77 | if let Some(tenant) = parts.extensions.get::<TenantExt>() { |
| 61 | - return Ok((tenant.slug.clone(), tenant.db.clone())); | 78 | + return Ok(ResolvedTenant { |
| 79 | + slug: tenant.slug.clone(), | ||
| 80 | + db: tenant.db.clone(), | ||
| 81 | + modules: tenant.modules.clone(), | ||
| 82 | + }); | ||
| 62 | } | 83 | } |
| 63 | let jar = CookieJar::from_request_parts(parts, state) | 84 | let jar = CookieJar::from_request_parts(parts, state) |
| 64 | .await | 85 | .await |
| @@ -71,8 +92,12 @@ where | |||
| 71 | let slug = Slug::try_new(prefix).map_err(|_| AppError::Unauthorized)?; | 92 | let slug = Slug::try_new(prefix).map_err(|_| AppError::Unauthorized)?; |
| 72 | 93 | ||
| 73 | let app = AppState::from_ref(state); | 94 | let app = AppState::from_ref(state); |
| 74 | - let db = app.tenants.get(&slug).await?; | 95 | + let resolved = app.tenants.resolve(&slug).await?; |
| 75 | - Ok((slug, db)) | 96 | + // Memoized on the request, not just returned: the next extractor on this |
| 97 | + // same request (and the module gate ahead of both) reuses this verdict | ||
| 98 | + // instead of re-reading the registry row. | ||
| 99 | + parts.extensions.insert(resolved.clone()); | ||
| 100 | + Ok(resolved) | ||
| 76 | } | 101 | } |
| 77 | 102 | ||
| 78 | /// The application state, narrowed to the caller's school. Drop-in for | 103 | /// The application state, narrowed to the caller's school. Drop-in for |
| @@ -91,16 +116,31 @@ where | |||
| 91 | type Rejection = AppError; | 116 | type Rejection = AppError; |
| 92 | 117 | ||
| 93 | async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | 118 | async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { |
| 94 | - let (slug, db) = resolve_tenant(parts, state).await?; | 119 | + let tenant = resolve_tenant(parts, state).await?; |
| 95 | let app = AppState::from_ref(state); | 120 | let app = AppState::from_ref(state); |
| 96 | Ok(State(AppState { | 121 | Ok(State(AppState { |
| 97 | - db, | 122 | + db: tenant.db, |
| 98 | - files_path: school_files_path(&app.files_path, &slug), | 123 | + files_path: school_files_path(&app.files_path, &tenant.slug), |
| 99 | ..app | 124 | ..app |
| 100 | })) | 125 | })) |
| 101 | } | 126 | } |
| 102 | } | 127 | } |
| 103 | 128 | ||
| 129 | +/// The resolved school itself, for a handler that must carry it somewhere the | ||
| 130 | +/// request does not reach — today the chatbot's detached answer task, which | ||
| 131 | +/// hands it back to the bridge as a [`TenantExt`]. | ||
| 132 | +impl<S> FromRequestParts<S> for ResolvedTenant | ||
| 133 | +where | ||
| 134 | + S: Send + Sync, | ||
| 135 | + AppState: FromRef<S>, | ||
| 136 | +{ | ||
| 137 | + type Rejection = AppError; | ||
| 138 | + | ||
| 139 | + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | ||
| 140 | + resolve_tenant(parts, state).await | ||
| 141 | + } | ||
| 142 | +} | ||
| 143 | + | ||
| 104 | /// Just the school, for the handlers that need it as a key prefix (the exam | 144 | /// 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. | 145 | /// presence map, the whiteboard hub) rather than as a database handle. |
| 106 | pub struct SchoolSlug(pub Slug); | 146 | pub struct SchoolSlug(pub Slug); |
| @@ -113,7 +153,7 @@ where | |||
| 113 | type Rejection = AppError; | 153 | type Rejection = AppError; |
| 114 | 154 | ||
| 115 | async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | 155 | async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { |
| 116 | - Ok(SchoolSlug(resolve_tenant(parts, state).await?.0)) | 156 | + Ok(SchoolSlug(resolve_tenant(parts, state).await?.slug)) |
| 117 | } | 157 | } |
| 118 | } | 158 | } |
| 119 | 159 | ||
| @@ -290,6 +330,51 @@ mod tests { | |||
| 290 | ); | 330 | ); |
| 291 | } | 331 | } |
| 292 | 332 | ||
| 333 | + /// One request, one registry read. Measured by making the registry answer | ||
| 334 | + /// *differently* the second time: the school is suspended between the two | ||
| 335 | + /// extractor calls on the same request, so a second read would refuse. It | ||
| 336 | + /// still passes — the verdict came from the memoized extension. | ||
| 337 | + #[tokio::test] | ||
| 338 | + async fn a_request_resolves_its_school_exactly_once() { | ||
| 339 | + let tenants = init_mem_tenants().await.expect("in-memory deployment"); | ||
| 340 | + let demo = Slug::try_new(DEMO_SLUG).unwrap(); | ||
| 341 | + let state = AppState { | ||
| 342 | + db: tenants.control().clone(), | ||
| 343 | + tenants: tenants.clone(), | ||
| 344 | + files_path: std::env::temp_dir(), | ||
| 345 | + cookie_secure: false, | ||
| 346 | + rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), | ||
| 347 | + chatbot_limit: Default::default(), | ||
| 348 | + exam_presence: Default::default(), | ||
| 349 | + board_hub: Default::default(), | ||
| 350 | + db_up: Default::default(), | ||
| 351 | + ai: None, | ||
| 352 | + }; | ||
| 353 | + let request = Request::builder() | ||
| 354 | + .uri("/school") | ||
| 355 | + .header("cookie", format!("session={DEMO_SLUG}.whatever")) | ||
| 356 | + .body(Body::empty()) | ||
| 357 | + .unwrap(); | ||
| 358 | + let (mut parts, _) = request.into_parts(); | ||
| 359 | + | ||
| 360 | + resolve_tenant(&mut parts, &state) | ||
| 361 | + .await | ||
| 362 | + .expect("the first resolve reads the registry"); | ||
| 363 | + assert!( | ||
| 364 | + parts.extensions.get::<ResolvedTenant>().is_some(), | ||
| 365 | + "the first resolve must memoize its verdict on the request" | ||
| 366 | + ); | ||
| 367 | + | ||
| 368 | + tenants | ||
| 369 | + .set_status(&demo, crate::tenant::SchoolStatus::Suspended) | ||
| 370 | + .await | ||
| 371 | + .unwrap(); | ||
| 372 | + let second = resolve_tenant(&mut parts, &state) | ||
| 373 | + .await | ||
| 374 | + .expect("a second read would have seen the suspension and refused"); | ||
| 375 | + assert_eq!(second.slug, demo); | ||
| 376 | + } | ||
| 377 | + | ||
| 293 | #[test] | 378 | #[test] |
| 294 | fn a_cookie_splits_at_its_first_dot_or_not_at_all() { | 379 | fn a_cookie_splits_at_its_first_dot_or_not_at_all() { |
| 295 | assert_eq!(split_cookie("demo.abc123"), Some(("demo", "abc123"))); | 380 | assert_eq!(split_cookie("demo.abc123"), Some(("demo", "abc123"))); |
tests/ai_bridge.rsmodified+5 -1
| @@ -18,6 +18,7 @@ use hezarfen_backend::ai::protocol::{ | |||
| 18 | }; | 18 | }; |
| 19 | use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; | 19 | use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; |
| 20 | use hezarfen_backend::constant::{AI_ALPN, AI_MAX_CONCURRENT_PER_WORKER, AI_PROTOCOL}; | 20 | use hezarfen_backend::constant::{AI_ALPN, AI_MAX_CONCURRENT_PER_WORKER, AI_PROTOCOL}; |
| 21 | +use hezarfen_backend::module::ModuleSet; | ||
| 21 | use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; | 22 | use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; |
| 22 | use serde_json::{Value, json}; | 23 | use serde_json::{Value, json}; |
| 23 | 24 | ||
| @@ -1772,7 +1773,10 @@ async fn an_index_dispatch_names_the_notes_own_school_and_stores_the_answer_ther | |||
| 1772 | 1773 | ||
| 1773 | let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; | 1774 | let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; |
| 1774 | let beta = Slug::try_new("beta").unwrap(); | 1775 | let beta = Slug::try_new("beta").unwrap(); |
| 1775 | - let beta_db = tenants.create(&beta, "Beta College").await.expect("beta"); | 1776 | + let beta_db = tenants |
| 1777 | + .create(&beta, "Beta College", ModuleSet::all()) | ||
| 1778 | + .await | ||
| 1779 | + .expect("beta"); | ||
| 1776 | 1780 | ||
| 1777 | let cookie = common::login_as_school(&app, &beta_db, "beta", "ogretmen", "teacher").await; | 1781 | let cookie = common::login_as_school(&app, &beta_db, "beta", "ogretmen", "teacher").await; |
| 1778 | let course = common::create_course(&app, &cookie, "fizik").await; | 1782 | let course = common::create_course(&app, &cookie, "fizik").await; |
tests/ai_protocol.rsmodified+6 -1
| @@ -23,6 +23,7 @@ use std::sync::Arc; | |||
| 23 | use std::time::Duration; | 23 | use std::time::Duration; |
| 24 | 24 | ||
| 25 | use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; | 25 | use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; |
| 26 | +use hezarfen_backend::module::ModuleSet; | ||
| 26 | use hezarfen_backend::tenant::{SchoolStatus, Slug, Tenants}; | 27 | use hezarfen_backend::tenant::{SchoolStatus, Slug, Tenants}; |
| 27 | use serde_json::{Value, json}; | 28 | use serde_json::{Value, json}; |
| 28 | 29 | ||
| @@ -1208,7 +1209,11 @@ async fn an_api_read_answers_a_named_user_with_that_users_own_data() { | |||
| 1208 | async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, String) { | 1209 | async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, String) { |
| 1209 | let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; | 1210 | let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; |
| 1210 | let beta_db = tenants | 1211 | let beta_db = tenants |
| 1211 | - .create(&Slug::try_new("beta").unwrap(), "Beta College") | 1212 | + .create( |
| 1213 | + &Slug::try_new("beta").unwrap(), | ||
| 1214 | + "Beta College", | ||
| 1215 | + ModuleSet::all(), | ||
| 1216 | + ) | ||
| 1212 | .await | 1217 | .await |
| 1213 | .expect("a second school"); | 1218 | .expect("a second school"); |
| 1214 | 1219 | ||
tests/common/mod.rsmodified+6 -1
| @@ -10,6 +10,7 @@ use axum::body::Body; | |||
| 10 | use axum::http::{HeaderMap, Request, StatusCode}; | 10 | use axum::http::{HeaderMap, Request, StatusCode}; |
| 11 | use hezarfen_backend::ai::AiBridge; | 11 | use hezarfen_backend::ai::AiBridge; |
| 12 | use hezarfen_backend::database::Database; | 12 | use hezarfen_backend::database::Database; |
| 13 | +use hezarfen_backend::module::ModuleSet; | ||
| 13 | use hezarfen_backend::rate_limit::RateLimitConfig; | 14 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 14 | use hezarfen_backend::state::{AppState, DbHealth}; | 15 | use hezarfen_backend::state::{AppState, DbHealth}; |
| 15 | use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; | 16 | use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; |
| @@ -664,7 +665,11 @@ pub async fn remote_deployment(schools: &[(&str, &str)]) -> Option<RemoteDeploym | |||
| 664 | let tenants = database::init(&cfg).await.expect("remote control database"); | 665 | let tenants = database::init(&cfg).await.expect("remote control database"); |
| 665 | for (slug, name) in schools { | 666 | for (slug, name) in schools { |
| 666 | tenants | 667 | tenants |
| 667 | - .create(&Slug::try_new(slug).expect("a school slug"), name) | 668 | + .create( |
| 669 | + &Slug::try_new(slug).expect("a school slug"), | ||
| 670 | + name, | ||
| 671 | + ModuleSet::all(), | ||
| 672 | + ) | ||
| 668 | .await | 673 | .await |
| 669 | .unwrap_or_else(|err| panic!("create school {slug}: {err}")); | 674 | .unwrap_or_else(|err| panic!("create school {slug}: {err}")); |
| 670 | } | 675 | } |
tests/integration.rsmodified+125 -1
| @@ -28,6 +28,7 @@ use hezarfen_backend::domain::rag_output::RagOutput; | |||
| 28 | use hezarfen_backend::domain::session::Session; | 28 | use hezarfen_backend::domain::session::Session; |
| 29 | use hezarfen_backend::domain::timestamp::Timestamp; | 29 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 30 | use hezarfen_backend::domain::user::{Password, User, UserId, Username}; | 30 | use hezarfen_backend::domain::user::{Password, User, UserId, Username}; |
| 31 | +use hezarfen_backend::module::ModuleSet; | ||
| 31 | use hezarfen_backend::state::AppState; | 32 | use hezarfen_backend::state::AppState; |
| 32 | use serde_json::json; | 33 | use serde_json::json; |
| 33 | use tower::ServiceExt; | 34 | use tower::ServiceExt; |
| @@ -27374,7 +27375,7 @@ async fn two_schools() -> ( | |||
| 27374 | let (app, db_a, tenants) = common::app_and_tenants().await; | 27375 | let (app, db_a, tenants) = common::app_and_tenants().await; |
| 27375 | let slug_b = Slug::try_new("beta").expect("slug"); | 27376 | let slug_b = Slug::try_new("beta").expect("slug"); |
| 27376 | let db_b = tenants | 27377 | let db_b = tenants |
| 27377 | - .create(&slug_b, "Beta Koleji") | 27378 | + .create(&slug_b, "Beta Koleji", ModuleSet::all()) |
| 27378 | .await | 27379 | .await |
| 27379 | .expect("school B"); | 27380 | .expect("school B"); |
| 27380 | (app, db_a, db_b, tenants) | 27381 | (app, db_a, db_b, tenants) |
| @@ -28647,3 +28648,126 @@ async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() { | |||
| 28647 | res.body | 28648 | res.body |
| 28648 | ); | 28649 | ); |
| 28649 | } | 28650 | } |
| 28651 | + | ||
| 28652 | +// --- module entitlements ------------------------------------------------- | ||
| 28653 | +// | ||
| 28654 | +// Foundation-level only: one nest proves the gate, one child route proves the | ||
| 28655 | +// `/courses` exceptions, and the two WebSocket nests prove an upgrade is | ||
| 28656 | +// refused like any other GET. The full per-module sweep is a later lane. | ||
| 28657 | + | ||
| 28658 | +use hezarfen_backend::module::Module; | ||
| 28659 | + | ||
| 28660 | +/// Turning a module off refuses **its** nest and nothing else — with the same | ||
| 28661 | +/// cookie, and with the URL space untouched (an unmatched path inside the | ||
| 28662 | +/// disabled nest is still a `404`, which is what `route_layer` buys). | ||
| 28663 | +#[tokio::test] | ||
| 28664 | +async fn a_disabled_module_refuses_its_nest_and_leaves_the_rest_alone() { | ||
| 28665 | + let (app, db, tenants) = common::app_and_tenants().await; | ||
| 28666 | + let slug = Slug::try_new(DEMO_SLUG).unwrap(); | ||
| 28667 | + let cookie = login_as(&app, &db, "ada", "admin").await; | ||
| 28668 | + | ||
| 28669 | + let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; | ||
| 28670 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 28671 | + | ||
| 28672 | + let mut without_meals = ModuleSet::all(); | ||
| 28673 | + without_meals.remove(Module::Meals); | ||
| 28674 | + tenants | ||
| 28675 | + .set_modules(&slug, &without_meals) | ||
| 28676 | + .await | ||
| 28677 | + .expect("take the meals module back"); | ||
| 28678 | + | ||
| 28679 | + let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; | ||
| 28680 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 28681 | + assert_eq!( | ||
| 28682 | + res.body, | ||
| 28683 | + json!({ "error": "module disabled", "module": "meals" }), | ||
| 28684 | + "the refusal body is contract" | ||
| 28685 | + ); | ||
| 28686 | + | ||
| 28687 | + for route in ["/auth/me", "/limits", "/settings"] { | ||
| 28688 | + let res = send(&app, "GET", route, Some(&cookie), None).await; | ||
| 28689 | + assert_eq!(res.status, StatusCode::OK, "{route}: {}", res.body); | ||
| 28690 | + } | ||
| 28691 | + | ||
| 28692 | + let res = send(&app, "GET", "/meals/does-not-exist", Some(&cookie), None).await; | ||
| 28693 | + assert_eq!( | ||
| 28694 | + res.status, | ||
| 28695 | + StatusCode::NOT_FOUND, | ||
| 28696 | + "a disabled module must not swallow the 404: {}", | ||
| 28697 | + res.body | ||
| 28698 | + ); | ||
| 28699 | + | ||
| 28700 | + tenants | ||
| 28701 | + .set_modules(&slug, &ModuleSet::all()) | ||
| 28702 | + .await | ||
| 28703 | + .expect("sell it back"); | ||
| 28704 | + let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; | ||
| 28705 | + assert_eq!( | ||
| 28706 | + res.status, | ||
| 28707 | + StatusCode::OK, | ||
| 28708 | + "the very same cookie after re-enabling: {}", | ||
| 28709 | + res.body | ||
| 28710 | + ); | ||
| 28711 | +} | ||
| 28712 | + | ||
| 28713 | +/// The four route pairs mounted under `/courses` that belong to another | ||
| 28714 | +/// module answer for *that* module: exams off refuses | ||
| 28715 | +/// `POST /courses/{id}/exams` while the course itself stays reachable. | ||
| 28716 | +#[tokio::test] | ||
| 28717 | +async fn a_course_child_route_is_gated_by_its_own_module() { | ||
| 28718 | + let (app, db, tenants) = common::app_and_tenants().await; | ||
| 28719 | + let slug = Slug::try_new(DEMO_SLUG).unwrap(); | ||
| 28720 | + let cookie = login_as(&app, &db, "ada", "admin").await; | ||
| 28721 | + let course = create_course(&app, &cookie, "Fizik").await; | ||
| 28722 | + | ||
| 28723 | + let mut without_exams = ModuleSet::all(); | ||
| 28724 | + without_exams.remove(Module::Exams); | ||
| 28725 | + tenants.set_modules(&slug, &without_exams).await.unwrap(); | ||
| 28726 | + | ||
| 28727 | + // An empty body: the gate must answer before the payload is even parsed. | ||
| 28728 | + let res = send( | ||
| 28729 | + &app, | ||
| 28730 | + "POST", | ||
| 28731 | + &format!("/courses/{course}/exams"), | ||
| 28732 | + Some(&cookie), | ||
| 28733 | + Some(json!({})), | ||
| 28734 | + ) | ||
| 28735 | + .await; | ||
| 28736 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 28737 | + assert_eq!(res.body["module"], "exams"); | ||
| 28738 | + | ||
| 28739 | + let res = send( | ||
| 28740 | + &app, | ||
| 28741 | + "GET", | ||
| 28742 | + &format!("/courses/{course}"), | ||
| 28743 | + Some(&cookie), | ||
| 28744 | + None, | ||
| 28745 | + ) | ||
| 28746 | + .await; | ||
| 28747 | + assert_eq!( | ||
| 28748 | + res.status, | ||
| 28749 | + StatusCode::OK, | ||
| 28750 | + "courses itself is still enabled: {}", | ||
| 28751 | + res.body | ||
| 28752 | + ); | ||
| 28753 | +} | ||
| 28754 | + | ||
| 28755 | +/// A WebSocket upgrade is a `GET` inside its nest, so it is gated by | ||
| 28756 | +/// construction — proven for both rooms rather than assumed. | ||
| 28757 | +#[tokio::test] | ||
| 28758 | +async fn a_disabled_module_refuses_its_websocket_upgrade() { | ||
| 28759 | + let (app, db, tenants) = common::app_and_tenants().await; | ||
| 28760 | + let slug = Slug::try_new(DEMO_SLUG).unwrap(); | ||
| 28761 | + let cookie = login_as(&app, &db, "ada", "admin").await; | ||
| 28762 | + | ||
| 28763 | + let mut without = ModuleSet::all(); | ||
| 28764 | + without.remove(Module::Boards); | ||
| 28765 | + without.remove(Module::Exams); | ||
| 28766 | + tenants.set_modules(&slug, &without).await.unwrap(); | ||
| 28767 | + | ||
| 28768 | + for (route, module) in [("/boards/x/ws", "boards"), ("/exams/x/attempt/ws", "exams")] { | ||
| 28769 | + let res = send(&app, "GET", route, Some(&cookie), None).await; | ||
| 28770 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{route}: {}", res.body); | ||
| 28771 | + assert_eq!(res.body["module"], module, "{route}"); | ||
| 28772 | + } | ||
| 28773 | +} | ||
tests/persistence.rsmodified+72 -0
| @@ -11,6 +11,7 @@ use axum::http::StatusCode; | |||
| 11 | use common::{create_course, create_exam, create_subject, enroll, me_id, send, set_role}; | 11 | use common::{create_course, create_exam, create_subject, enroll, me_id, send, set_role}; |
| 12 | use hezarfen_backend::database::Database; | 12 | use hezarfen_backend::database::Database; |
| 13 | use hezarfen_backend::domain::timestamp::Timestamp; | 13 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 14 | +use hezarfen_backend::module::ModuleSet; | ||
| 14 | use hezarfen_backend::rate_limit::RateLimitConfig; | 15 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 15 | use hezarfen_backend::state::AppState; | 16 | use hezarfen_backend::state::AppState; |
| 16 | use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; | 17 | use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; |
| @@ -2371,3 +2372,74 @@ async fn pre_class_enrollments_keep_their_absent_source() { | |||
| 2371 | "and no seat was given back" | 2372 | "and no seat was given back" |
| 2372 | ); | 2373 | ); |
| 2373 | } | 2374 | } |
| 2375 | + | ||
| 2376 | +/// A school row written before module entitlements existed has no `modules` | ||
| 2377 | +/// field at all. The control migration must read that — and only that — as | ||
| 2378 | +/// "everything", because a school that predates the idea of buying modules had | ||
| 2379 | +/// all of them. | ||
| 2380 | +#[tokio::test] | ||
| 2381 | +async fn a_school_row_without_modules_backfills_to_every_module() { | ||
| 2382 | + let db = surrealdb::engine::any::connect("memory") | ||
| 2383 | + .await | ||
| 2384 | + .expect("an in-memory control store"); | ||
| 2385 | + db.use_ns("hezarfen").use_db("control").await.unwrap(); | ||
| 2386 | + // The control schema as it stood before `modules`, so the row really is | ||
| 2387 | + // the shape an older binary left behind. | ||
| 2388 | + db.query( | ||
| 2389 | + "DEFINE TABLE school SCHEMAFULL; | ||
| 2390 | + DEFINE FIELD slug ON school TYPE string; | ||
| 2391 | + DEFINE FIELD name ON school TYPE string; | ||
| 2392 | + DEFINE FIELD status ON school TYPE string; | ||
| 2393 | + DEFINE FIELD created_at ON school TYPE int; | ||
| 2394 | + CREATE school:legacy SET slug = 'legacy', name = 'Legacy', \ | ||
| 2395 | + status = 'active', created_at = 1;", | ||
| 2396 | + ) | ||
| 2397 | + .await | ||
| 2398 | + .expect("the pre-modules control schema") | ||
| 2399 | + .check() | ||
| 2400 | + .expect("the pre-modules control schema"); | ||
| 2401 | + | ||
| 2402 | + database::migrate_control(&db).await.expect("a newer boot"); | ||
| 2403 | + | ||
| 2404 | + let stored: Vec<Vec<String>> = db | ||
| 2405 | + .query("SELECT VALUE modules FROM school:legacy") | ||
| 2406 | + .await | ||
| 2407 | + .expect("read the row back") | ||
| 2408 | + .take(0) | ||
| 2409 | + .expect("modules column"); | ||
| 2410 | + assert_eq!( | ||
| 2411 | + stored.first().cloned().unwrap_or_default(), | ||
| 2412 | + ModuleSet::all().names(), | ||
| 2413 | + "a row that predates entitlements owns every module" | ||
| 2414 | + ); | ||
| 2415 | +} | ||
| 2416 | + | ||
| 2417 | +/// The other half of that rule: `[]` is a deliberate "nothing enabled", not a | ||
| 2418 | +/// missing value, so a second boot must leave it alone. Widening it would hand | ||
| 2419 | +/// a school modules it never bought. | ||
| 2420 | +#[tokio::test] | ||
| 2421 | +async fn an_empty_module_list_survives_a_second_boot() { | ||
| 2422 | + let tenants = Tenants::new_mem().await.expect("a control database"); | ||
| 2423 | + let slug = Slug::try_new("bare").unwrap(); | ||
| 2424 | + tenants | ||
| 2425 | + .create(&slug, "Bare School", ModuleSet::empty()) | ||
| 2426 | + .await | ||
| 2427 | + .expect("a school with nothing switched on"); | ||
| 2428 | + | ||
| 2429 | + database::migrate_control(tenants.control()) | ||
| 2430 | + .await | ||
| 2431 | + .expect("a second boot"); | ||
| 2432 | + | ||
| 2433 | + let stored: Vec<Vec<String>> = tenants | ||
| 2434 | + .control() | ||
| 2435 | + .query("SELECT VALUE modules FROM school:bare") | ||
| 2436 | + .await | ||
| 2437 | + .expect("read the row back") | ||
| 2438 | + .take(0) | ||
| 2439 | + .expect("modules column"); | ||
| 2440 | + assert_eq!( | ||
| 2441 | + stored.first().cloned().unwrap_or_default(), | ||
| 2442 | + Vec::<String>::new(), | ||
| 2443 | + "an empty list is a decision, never a hole to fill" | ||
| 2444 | + ); | ||
| 2445 | +} | ||