forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

builder.rs810 lines, 33.2 KiBHistoryRawDownload
1//! The vendor's surface: the operator who owns the deployment, not anybody's
2//! school. Every handler here takes `axum::extract::State` (the **control**
3//! database) rather than `web::tenant_state::State`, because these routes are
4//! *about* schools instead of inside one — the school a request touches is
5//! named in its path and resolved through [`crate::tenant::Tenants`].
6//!
7//! The two principals never mix: [`RequireBuilder`] takes only a
8//! `builder.<token>` cookie, and that cookie is `401` on every school surface
9//! (see `web::tenant_state::resolve_tenant`). `POST /schools/{slug}/enter` is
10//! the one bridge, and it does not blur the line — it mints an ordinary school
11//! session for an admin account that already exists there.
12//!
13//! A suspended school is closed to *its users*, not to its vendor: every route
14//! here keeps working on one (that is how it gets un-suspended) except `enter`,
15//! so "suspended blocks everything" stays true of the school's own doors.
16
17use axum::Json;
18use axum::extract::{Path, Query, Request, State};
19use axum::http::StatusCode;
20use axum::middleware::{self, Next};
21use axum_extra::extract::CookieJar;
22use axum_extra::extract::cookie::Cookie;
23use serde::{Deserialize, Serialize};
24use utoipa::ToSchema;
25use utoipa_axum::router::OpenApiRouter;
26use utoipa_axum::routes;
27
28use crate::constant::MAX_SCHOOL_NAME_LEN;
29use crate::domain::builder::Builder;
30use crate::domain::role::Role;
31use crate::domain::user::{Password, PasswordHash, User, Username};
32use crate::error::{AppError, ErrorResponse, ValidationError};
33use crate::module::{Module, ModuleSet, Package};
34use crate::rate_limit::{RateLimitConfig, RateLimiter};
35use crate::service;
36use crate::state::AppState;
37use crate::tenant::{School, SchoolStatus, Slug};
38use crate::validate::validate_required;
39use crate::web::tenant_state::school_files_path;
40
41use super::auth::session_cookie;
42use super::modules::ModulesResponse;
43use super::{BUILDER_COOKIE_PREFIX, Page, PageParams, RequireBuilder, UserResponse};
44
45pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
46 // The builder credential is the most valuable one in the deployment, so its
47 // login sits behind the same strict per-IP tier `/auth/login` uses — its own
48 // budget, since a school's brute-forcer must not spend the vendor's.
49 let rate_limit: &RateLimitConfig = &state.rate_limit;
50 let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy);
51 limiter.share("builder", state.db.clone(), state.db_up.clone());
52 OpenApiRouter::new()
53 .routes(routes!(builder_login))
54 .route_layer(middleware::from_fn(move |req: Request, next: Next| {
55 let limiter = limiter.clone();
56 async move { limiter.enforce(req, next).await }
57 }))
58 .routes(routes!(builder_logout))
59 .routes(routes!(builder_me))
60 .routes(routes!(create_school, list_schools))
61 .routes(routes!(get_school, update_school, delete_school))
62 .routes(routes!(list_school_modules, patch_school_modules))
63 .routes(routes!(enable_school_module, disable_school_module))
64 .routes(routes!(reset_admin_password))
65 .routes(routes!(enter_school))
66}
67
68#[derive(Deserialize, ToSchema)]
69struct BuilderCredentials {
70 #[schema(example = "operator", min_length = 3, max_length = 32)]
71 username: String,
72 #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
73 password: String,
74}
75
76/// The operator behind the cookie. Deliberately not [`UserResponse`]: a builder
77/// has no role, no profile and no school.
78#[derive(Serialize, ToSchema)]
79struct BuilderResponse {
80 id: String,
81 #[schema(example = "operator")]
82 username: String,
83}
84
85impl BuilderResponse {
86 fn new(builder: &Builder) -> Self {
87 Self {
88 id: builder.get_id().key().to_string(),
89 username: builder.get_username().as_str().to_string(),
90 }
91 }
92}
93
94#[derive(Serialize, ToSchema)]
95struct SchoolResponse {
96 #[schema(example = "ata-koleji")]
97 slug: String,
98 #[schema(example = "Ata Koleji")]
99 name: String,
100 /// `active` or `suspended`. A suspended school refuses every one of its own
101 /// users, login included.
102 #[schema(example = "active")]
103 status: String,
104 /// Registered at, UTC unix-milliseconds.
105 created_at: i64,
106 /// The modules this school has bought, sorted by name. The other half of
107 /// the catalog is on `GET /schools/{slug}/modules`.
108 #[schema(example = json!(["courses", "meals", "notes"]))]
109 modules: Vec<String>,
110}
111
112impl SchoolResponse {
113 fn new(school: &School) -> Self {
114 Self {
115 slug: school.slug().as_str().to_string(),
116 name: school.name().to_string(),
117 status: school.status().as_str().to_string(),
118 created_at: school.created_at().as_millis(),
119 modules: school.modules().names(),
120 }
121 }
122}
123
124#[derive(Deserialize, ToSchema)]
125struct CreateSchool {
126 /// Lowercase `a-z`, `0-9` and `-`, starting with a letter or digit. Names
127 /// the school's database, its blob directory and its cookie prefix, so it
128 /// is immutable once taken.
129 #[schema(example = "ata-koleji", min_length = 2, max_length = 32)]
130 slug: String,
131 #[schema(example = "Ata Koleji", max_length = 120)]
132 name: String,
133 /// The school's first admin, created inside the new school's database.
134 #[schema(example = "admin", min_length = 3, max_length = 32)]
135 admin_username: String,
136 #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
137 admin_password: String,
138 /// What the school buys. Omitted sells it everything — the deployment's
139 /// whole catalog, which `GET /modules/catalog` publishes. A set that
140 /// switches a module on without what it structurally needs is refused
141 /// before anything is created.
142 #[schema(example = json!(["courses", "subjects", "exams"]))]
143 modules: Option<Vec<String>>,
144}
145
146#[derive(Deserialize, ToSchema)]
147struct UpdateSchool {
148 #[schema(example = "Ata Koleji", max_length = 120)]
149 name: Option<String>,
150 /// `active` or `suspended`.
151 #[schema(example = "suspended")]
152 status: Option<String>,
153}
154
155/// One side of a [`patch_school_modules`] request is a list of modules, a list
156/// of packages, or both — a package is only a name for its modules, so the two
157/// are expanded into the same set.
158#[derive(Deserialize, ToSchema)]
159struct PatchModules {
160 /// Module names to switch on.
161 #[schema(example = json!(["exams", "subjects"]))]
162 enable: Option<Vec<String>>,
163 /// Module names to switch off.
164 #[schema(example = json!(["payments"]))]
165 disable: Option<Vec<String>>,
166 /// Package names to switch on, every module in them.
167 #[schema(example = json!(["academics"]))]
168 enable_packages: Option<Vec<String>>,
169 /// Package names to switch off, every module in them.
170 #[schema(example = json!(["ai"]))]
171 disable_packages: Option<Vec<String>>,
172}
173
174impl PatchModules {
175 /// The modules one direction asks for. An unknown name in either list is a
176 /// `400` naming it rather than a silent drop — the same rule
177 /// [`ModuleSet::from_names`] keeps.
178 fn side(
179 &self,
180 modules: Option<&[String]>,
181 packages: Option<&[String]>,
182 ) -> Result<ModuleSet, AppError> {
183 let mut set = ModuleSet::from_names(modules.unwrap_or_default())?;
184 for name in packages.unwrap_or_default() {
185 for module in Package::try_from_str(name)?.modules() {
186 set.insert(module);
187 }
188 }
189 Ok(set)
190 }
191}
192
193#[derive(Deserialize, ToSchema)]
194struct AdminPassword {
195 /// The admin account in that school whose password is being reset.
196 #[schema(example = "admin", min_length = 3, max_length = 32)]
197 username: String,
198 #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
199 password: String,
200}
201
202#[derive(Deserialize, ToSchema)]
203struct EnterSchool {
204 /// The admin account to enter as. It must already exist in that school.
205 #[schema(example = "admin", min_length = 3, max_length = 32)]
206 username: String,
207}
208
209/// A school's display name: free text, unlike its slug.
210fn school_name(value: &str) -> Result<String, AppError> {
211 validate_required("name", value, MAX_SCHOOL_NAME_LEN)?;
212 Ok(value.trim().to_string())
213}
214
215/// The slug in a path. Anything that is not a slug names no school, so it is
216/// the same `404` an unknown one gets — and it never reaches
217/// [`school_files_path`], which is exactly why that path is built from a
218/// validated [`Slug`] and never from the raw segment.
219fn path_slug(raw: &str) -> Result<Slug, AppError> {
220 Slug::try_new(raw).map_err(|_| AppError::NotFound)
221}
222
223/// The named account in `db`, which must be an admin of that school: unknown →
224/// `404` (a builder is authenticated, there is nothing to hide), present but
225/// below admin → `409`, the repo's verdict for "the row exists, its state
226/// refuses this".
227async fn school_admin(username: &str, db: &crate::database::Database) -> Result<User, AppError> {
228 let user = crate::service::user::find_by_username(db, username.trim())
229 .await?
230 .ok_or(AppError::NotFound)?;
231 if user.get_role() != Role::Admin {
232 return Err(AppError::Conflict(
233 "that account is not an admin of this school",
234 ));
235 }
236 Ok(user)
237}
238
239/// Log in as the deployment's builder. Sets a `session` cookie
240/// (`builder.<token>`) that works on this surface and nowhere else.
241#[utoipa::path(
242 post,
243 path = "/builder/login",
244 tag = "builder",
245 request_body = BuilderCredentials,
246 responses(
247 (status = 200, description = "Logged in; builder session cookie set", body = BuilderResponse),
248 (status = 401, description = "Bad credentials", body = ErrorResponse),
249 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
250 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
251 ),
252)]
253async fn builder_login(
254 State(st): State<AppState>,
255 jar: CookieJar,
256 Json(req): Json<BuilderCredentials>,
257) -> Result<(CookieJar, Json<BuilderResponse>), AppError> {
258 let control = st.tenants.control();
259 let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?;
260 let builder =
261 match crate::service::builder::find_by_username(control, req.username.trim()).await? {
262 Some(builder) => {
263 if !builder.get_password_hash().verify_async(&password).await {
264 return Err(AppError::Unauthorized);
265 }
266 builder
267 }
268 None => {
269 // The same decoy hash `/auth/login` runs: a wrong name and a wrong
270 // password must cost the same, or the reply time enumerates the
271 // operator accounts.
272 PasswordHash::verify_decoy_async(&password).await;
273 return Err(AppError::Unauthorized);
274 }
275 };
276
277 let session = crate::service::builder::create_session(control, builder.get_id()).await?;
278 let cookie = session_cookie(
279 format!("{BUILDER_COOKIE_PREFIX}.{}", session.token().as_str()),
280 st.cookie_secure,
281 );
282 Ok((jar.add(cookie), Json(BuilderResponse::new(&builder))))
283}
284
285/// Log out a builder: revoke the session (if any) and clear the cookie.
286/// Idempotent — answers `204` either way.
287#[utoipa::path(
288 post,
289 path = "/builder/logout",
290 tag = "builder",
291 responses((status = 204, description = "Logged out (no-op without a builder session)")),
292)]
293async fn builder_logout(
294 State(st): State<AppState>,
295 jar: CookieJar,
296) -> Result<(CookieJar, StatusCode), AppError> {
297 if let Some((BUILDER_COOKIE_PREFIX, token)) = jar
298 .get("session")
299 .and_then(|cookie| super::tenant_state::split_cookie(cookie.value()))
300 {
301 crate::service::builder::delete_by_token(st.tenants.control(), token).await?;
302 }
303 let jar = jar.remove(Cookie::build(("session", "")).path("/").build());
304 Ok((jar, StatusCode::NO_CONTENT))
305}
306
307/// The current builder.
308#[utoipa::path(
309 get,
310 path = "/builder/me",
311 tag = "builder",
312 security(("session_cookie" = [])),
313 responses(
314 (status = 200, description = "The current builder", body = BuilderResponse),
315 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
316 ),
317)]
318async fn builder_me(RequireBuilder(builder): RequireBuilder) -> Json<BuilderResponse> {
319 Json(BuilderResponse::new(&builder))
320}
321
322/// Create a school: its registry row, its database, its schema, and its first
323/// admin account — one call, or none of it.
324#[utoipa::path(
325 post,
326 path = "/schools",
327 tag = "builder",
328 security(("session_cookie" = [])),
329 request_body = CreateSchool,
330 responses(
331 (status = 201, description = "School created, with its first admin", body = SchoolResponse),
332 (status = 400, description = "Invalid slug, name, admin credentials, or module name", body = ErrorResponse, example = json!({"error": "module: `kantin` is not a known module"})),
333 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
334 (status = 409, description = "That slug is already taken, or the module set is unsatisfiable", body = ErrorResponse, example = json!({"error": "conflict: exams requires subjects, which is not enabled"})),
335 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
336 ),
337)]
338async fn create_school(
339 State(st): State<AppState>,
340 RequireBuilder(_builder): RequireBuilder,
341 Json(req): Json<CreateSchool>,
342) -> Result<(StatusCode, Json<SchoolResponse>), AppError> {
343 // Everything the request must get right is checked (and the admin password
344 // hashed) *before* a database is defined, so the ordinary rejection never
345 // creates anything to clean up.
346 let slug = Slug::try_new(&req.slug)?;
347 let name = school_name(&req.name)?;
348 let username = Username::try_new(&req.admin_username)?;
349 let password_hash = Password::try_new(&req.admin_password)?.hash_async().await?;
350
351 let modules = match req.modules.as_deref() {
352 Some(names) => ModuleSet::from_names(names)?,
353 None => ModuleSet::all(),
354 };
355 // Before `create`, so an unsatisfiable set is a refusal and not a school
356 // that has to be deleted again.
357 modules.validate()?;
358
359 let db = st.tenants.create(&slug, &name, modules).await?;
360 if let Err(err) =
361 crate::service::user::create_with_role(&db, username, password_hash, Role::Admin).await
362 {
363 // A school nobody can log into is worse than no school: take the
364 // database back so the very same request can simply be retried.
365 if let Err(cleanup) = st.tenants.drop(&slug).await {
366 tracing::error!("failed to drop {slug} after its admin seed failed: {cleanup}");
367 }
368 return Err(err);
369 }
370
371 let school = School::read(&slug, st.tenants.control())
372 .await?
373 .ok_or_else(|| AppError::Internal("the school vanished as it was created".into()))?;
374 Ok((StatusCode::CREATED, Json(SchoolResponse::new(&school))))
375}
376
377/// Every school this deployment serves, newest first. Paged via
378/// `?limit=&offset=` (omit `limit` for the full list).
379#[utoipa::path(
380 get,
381 path = "/schools",
382 tag = "builder",
383 security(("session_cookie" = [])),
384 params(PageParams),
385 responses(
386 (status = 200, description = "A page of schools (the full list when unpaged)", body = Page<SchoolResponse>),
387 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
388 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
389 ),
390)]
391async fn list_schools(
392 State(st): State<AppState>,
393 RequireBuilder(_builder): RequireBuilder,
394 Query(page): Query<PageParams>,
395) -> Result<Json<Page<SchoolResponse>>, AppError> {
396 let (limit, offset) = page.resolve()?;
397 let (schools, total) = School::list(limit, offset, st.tenants.control()).await?;
398 let items = schools.iter().map(SchoolResponse::new).collect();
399 Ok(Json(Page::new(items, total, limit, offset)))
400}
401
402/// One school by slug.
403#[utoipa::path(
404 get,
405 path = "/schools/{slug}",
406 tag = "builder",
407 security(("session_cookie" = [])),
408 params(("slug" = String, Path, description = "School slug")),
409 responses(
410 (status = 200, description = "The school", body = SchoolResponse),
411 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
412 (status = 404, description = "No such school", body = ErrorResponse),
413 ),
414)]
415async fn get_school(
416 State(st): State<AppState>,
417 RequireBuilder(_builder): RequireBuilder,
418 Path(slug): Path<String>,
419) -> Result<Json<SchoolResponse>, AppError> {
420 let school = School::read(&path_slug(&slug)?, st.tenants.control())
421 .await?
422 .ok_or(AppError::NotFound)?;
423 Ok(Json(SchoolResponse::new(&school)))
424}
425
426/// Rename a school and/or flip it between `active` and `suspended`. Omitted
427/// fields keep their value. The slug itself is immutable — it names a database
428/// and a directory.
429///
430/// Suspending is immediate and total for the school's own users: their next
431/// request is a `403`, live session or not.
432#[utoipa::path(
433 patch,
434 path = "/schools/{slug}",
435 tag = "builder",
436 security(("session_cookie" = [])),
437 params(("slug" = String, Path, description = "School slug")),
438 request_body = UpdateSchool,
439 responses(
440 (status = 200, description = "The updated school", body = SchoolResponse),
441 (status = 400, description = "Invalid name or status", body = ErrorResponse),
442 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
443 (status = 404, description = "No such school", body = ErrorResponse),
444 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
445 ),
446)]
447async fn update_school(
448 State(st): State<AppState>,
449 RequireBuilder(_builder): RequireBuilder,
450 Path(slug): Path<String>,
451 Json(req): Json<UpdateSchool>,
452) -> Result<Json<SchoolResponse>, AppError> {
453 let slug = path_slug(&slug)?;
454 let name = req.name.as_deref().map(school_name).transpose()?;
455 let status = req
456 .status
457 .as_deref()
458 .map(SchoolStatus::try_from_str)
459 .transpose()?;
460
461 let control = st.tenants.control();
462 // An empty patch on an unknown school is still a 404, so the existence
463 // check is not left to whichever field happened to be present.
464 School::read(&slug, control)
465 .await?
466 .ok_or(AppError::NotFound)?;
467 if let Some(name) = name {
468 School::update_name(&slug, &name, control).await?;
469 }
470 if let Some(status) = status {
471 st.tenants.set_status(&slug, status).await?;
472 }
473 let school = School::read(&slug, control)
474 .await?
475 .ok_or(AppError::NotFound)?;
476 Ok(Json(SchoolResponse::new(&school)))
477}
478
479/// Delete a school: its database, its registry row, and its uploaded files.
480/// Irreversible — suspension is the reversible door.
481#[utoipa::path(
482 delete,
483 path = "/schools/{slug}",
484 tag = "builder",
485 security(("session_cookie" = [])),
486 params(("slug" = String, Path, description = "School slug")),
487 responses(
488 (status = 204, description = "Deleted"),
489 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
490 (status = 404, description = "No such school", body = ErrorResponse),
491 ),
492)]
493async fn delete_school(
494 State(st): State<AppState>,
495 RequireBuilder(_builder): RequireBuilder,
496 Path(slug): Path<String>,
497) -> Result<StatusCode, AppError> {
498 let slug = path_slug(&slug)?;
499 School::read(&slug, st.tenants.control())
500 .await?
501 .ok_or(AppError::NotFound)?;
502 st.tenants.drop(&slug).await?;
503
504 // Rows first, bytes second — the same order every blob delete here keeps, so
505 // a crash between them strands unreachable files rather than rows pointing
506 // at nothing. The directory is built from the validated `Slug`, never from
507 // the raw path segment.
508 let dir = school_files_path(&st.files_path, &slug);
509 if let Err(err) = tokio::fs::remove_dir_all(&dir).await
510 && err.kind() != std::io::ErrorKind::NotFound
511 {
512 tracing::warn!(
513 "failed to remove the files of {slug} at {}: {err}",
514 dir.display()
515 );
516 }
517 Ok(StatusCode::NO_CONTENT)
518}
519
520/// A module named in a path segment. Unknown → `404`, the same verdict an
521/// unknown slug gets: the segment names nothing this deployment sells, so
522/// there is no resource to act on. Inside a *body* the same name is a `400`
523/// instead — a bad field, not a bad address.
524fn path_module(raw: &str) -> Result<Module, AppError> {
525 Module::try_from_str(raw).map_err(|_| AppError::NotFound)
526}
527
528/// A school's entitlements, off the registry row. Deliberately not
529/// [`Tenants::resolve`]: that one is the school's own door and refuses a
530/// suspended school, and every route here keeps working on one.
531async fn school_modules(
532 slug: &Slug,
533 control: &crate::database::Database,
534) -> Result<ModuleSet, AppError> {
535 Ok(School::read(slug, control)
536 .await?
537 .ok_or(AppError::NotFound)?
538 .modules())
539}
540
541/// Refuse taking `module` back while something the school still has needs it,
542/// naming every such module — the reverse direction of
543/// [`ModuleSet::validate`], which speaks for the modules that are on.
544fn refuse_if_needed(module: Module, set: &ModuleSet) -> Result<(), AppError> {
545 let needed_by: Vec<String> = module
546 .dependents()
547 .into_iter()
548 .filter(|dependent| set.contains(*dependent))
549 .map(|dependent| dependent.as_str().to_string())
550 .collect();
551 if needed_by.is_empty() {
552 return Ok(());
553 }
554 Err(AppError::ConflictOwned(format!(
555 "{module} is required by {}",
556 needed_by.join(", ")
557 )))
558}
559
560/// Write a school's new set and answer with it. One write, or none — every
561/// caller here has already decided.
562async fn store_modules(
563 st: &AppState,
564 slug: &Slug,
565 modules: ModuleSet,
566) -> Result<Json<ModulesResponse>, AppError> {
567 st.tenants.set_modules(slug, &modules).await?;
568 Ok(Json(ModulesResponse::new(&modules)))
569}
570
571/// What a school has bought, and what is left to sell it. Works on a suspended
572/// school — entitlements are the vendor's ledger, not one of the school's doors.
573#[utoipa::path(
574 get,
575 path = "/schools/{slug}/modules",
576 tag = "builder",
577 security(("session_cookie" = [])),
578 params(("slug" = String, Path, description = "School slug")),
579 responses(
580 (status = 200, description = "The school's enabled and disabled modules", body = ModulesResponse),
581 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
582 (status = 404, description = "No such school", body = ErrorResponse),
583 ),
584)]
585async fn list_school_modules(
586 State(st): State<AppState>,
587 RequireBuilder(_builder): RequireBuilder,
588 Path(slug): Path<String>,
589) -> Result<Json<ModulesResponse>, AppError> {
590 let modules = school_modules(&path_slug(&slug)?, st.tenants.control()).await?;
591 Ok(Json(ModulesResponse::new(&modules)))
592}
593
594/// Sell a school one module. Idempotent: a module it already has is a `200`
595/// with the unchanged set. Refused while what the module structurally needs is
596/// off — enable those in the same `PATCH` instead.
597#[utoipa::path(
598 post,
599 path = "/schools/{slug}/modules/{module}",
600 tag = "builder",
601 security(("session_cookie" = [])),
602 params(
603 ("slug" = String, Path, description = "School slug"),
604 ("module" = String, Path, description = "Module name, as `GET /modules/catalog` publishes it"),
605 ),
606 responses(
607 (status = 200, description = "The school's modules after the change", body = ModulesResponse),
608 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
609 (status = 404, description = "No such school, or no such module", body = ErrorResponse, example = json!({"error": "not found"})),
610 (status = 409, description = "That module needs another this school does not have", body = ErrorResponse, example = json!({"error": "conflict: exams requires subjects, which is not enabled"})),
611 ),
612)]
613async fn enable_school_module(
614 State(st): State<AppState>,
615 RequireBuilder(_builder): RequireBuilder,
616 Path((slug, module)): Path<(String, String)>,
617) -> Result<Json<ModulesResponse>, AppError> {
618 let slug = path_slug(&slug)?;
619 let module = path_module(&module)?;
620 let mut modules = school_modules(&slug, st.tenants.control()).await?;
621 if modules.contains(module) {
622 return Ok(Json(ModulesResponse::new(&modules)));
623 }
624 modules.insert(module);
625 modules.validate()?;
626 store_modules(&st, &slug, modules).await
627}
628
629/// Take one module back. Idempotent, and refused while a module the school
630/// still has depends on it — the mirror of the enable direction.
631///
632/// The school's data is untouched: a disabled module's rows stay put and come
633/// back with it. Only its routes stop answering.
634#[utoipa::path(
635 delete,
636 path = "/schools/{slug}/modules/{module}",
637 tag = "builder",
638 security(("session_cookie" = [])),
639 params(
640 ("slug" = String, Path, description = "School slug"),
641 ("module" = String, Path, description = "Module name, as `GET /modules/catalog` publishes it"),
642 ),
643 responses(
644 (status = 200, description = "The school's modules after the change", body = ModulesResponse),
645 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
646 (status = 404, description = "No such school, or no such module", body = ErrorResponse, example = json!({"error": "not found"})),
647 (status = 409, description = "Another module the school has requires this one", body = ErrorResponse, example = json!({"error": "conflict: courses is required by exams, subjects"})),
648 ),
649)]
650async fn disable_school_module(
651 State(st): State<AppState>,
652 RequireBuilder(_builder): RequireBuilder,
653 Path((slug, module)): Path<(String, String)>,
654) -> Result<Json<ModulesResponse>, AppError> {
655 let slug = path_slug(&slug)?;
656 let module = path_module(&module)?;
657 let mut modules = school_modules(&slug, st.tenants.control()).await?;
658 if !modules.contains(module) {
659 return Ok(Json(ModulesResponse::new(&modules)));
660 }
661 refuse_if_needed(module, &modules)?;
662 modules.remove(module);
663 store_modules(&st, &slug, modules).await
664}
665
666/// Re-sell a school's whole shelf in one call: any mix of modules and packages,
667/// in either direction. Every list is optional and an empty body is a no-op.
668///
669/// The four lists are expanded into one resulting set, which is then checked
670/// once — so a `PATCH` that enables `exams` and `subjects` together is fine
671/// where two single calls would refuse the first, and a `409` names every
672/// violation at once instead of one per round trip. Nothing is written unless
673/// the whole request is accepted.
674#[utoipa::path(
675 patch,
676 path = "/schools/{slug}/modules",
677 tag = "builder",
678 security(("session_cookie" = [])),
679 params(("slug" = String, Path, description = "School slug")),
680 request_body = PatchModules,
681 responses(
682 (status = 200, description = "The school's modules after the change", body = ModulesResponse),
683 (status = 400, description = "An unknown module or package name, or one asked for in both directions", body = ErrorResponse, example = json!({"error": "package: `kantin` is not a known package"})),
684 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
685 (status = 404, description = "No such school", body = ErrorResponse),
686 (status = 409, description = "The resulting set breaks a dependency", body = ErrorResponse, example = json!({"error": "conflict: marks requires exams, which is not enabled"})),
687 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
688 ),
689)]
690async fn patch_school_modules(
691 State(st): State<AppState>,
692 RequireBuilder(_builder): RequireBuilder,
693 Path(slug): Path<String>,
694 Json(req): Json<PatchModules>,
695) -> Result<Json<ModulesResponse>, AppError> {
696 let slug = path_slug(&slug)?;
697 let enable = req.side(req.enable.as_deref(), req.enable_packages.as_deref())?;
698 let disable = req.side(req.disable.as_deref(), req.disable_packages.as_deref())?;
699 // A name pulled both ways has no defensible resolution, and picking one
700 // silently would sell (or unsell) a module the caller also asked for the
701 // opposite of.
702 if let Some(module) = enable.iter().find(|module| disable.contains(*module)) {
703 return Err(ValidationError::Contradictory {
704 field: "module",
705 value: module.as_str().to_string(),
706 }
707 .into());
708 }
709
710 let current = school_modules(&slug, st.tenants.control()).await?;
711 let mut result = current.clone();
712 for module in enable.iter() {
713 result.insert(module);
714 }
715 for module in disable.iter() {
716 result.remove(module);
717 }
718 // One check for both directions: a disable that strands a dependent shows
719 // up here as that dependent missing its requirement.
720 result.validate()?;
721
722 if result == current {
723 return Ok(Json(ModulesResponse::new(&current)));
724 }
725 store_modules(&st, &slug, result).await
726}
727
728/// Reset an admin's password inside a school — the "we are locked out" call.
729/// Every session that account held is revoked with it, so a stolen cookie does
730/// not survive the reset. Works on a suspended school.
731#[utoipa::path(
732 post,
733 path = "/schools/{slug}/admin-password",
734 tag = "builder",
735 security(("session_cookie" = [])),
736 params(("slug" = String, Path, description = "School slug")),
737 request_body = AdminPassword,
738 responses(
739 (status = 204, description = "Password reset; that account's sessions are revoked"),
740 (status = 400, description = "Invalid password", body = ErrorResponse),
741 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
742 (status = 404, description = "No such school, or no such account in it", body = ErrorResponse),
743 (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse),
744 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
745 ),
746)]
747async fn reset_admin_password(
748 State(st): State<AppState>,
749 RequireBuilder(_builder): RequireBuilder,
750 Path(slug): Path<String>,
751 Json(req): Json<AdminPassword>,
752) -> Result<StatusCode, AppError> {
753 let slug = path_slug(&slug)?;
754 // `get_any_status`, not `get`: a lockout is exactly the situation a school
755 // may be suspended in, and the vendor must still be able to fix it.
756 let (db, _status) = st.tenants.get_any_status(&slug).await?;
757 let user = school_admin(&req.username, &db).await?;
758 let password_hash = Password::try_new(&req.password)?.hash_async().await?;
759
760 crate::service::user::set_password_hash(&db, user.get_id(), password_hash)
761 .await?
762 .ok_or(AppError::NotFound)?;
763 // The other half: the new password means nothing while a cookie minted
764 // under the old one still authenticates.
765 service::session::delete_by_user(&db, user.get_id()).await?;
766 Ok(StatusCode::NO_CONTENT)
767}
768
769/// Enter a school as one of its admins — support access, with the school's own
770/// session cookie (`<slug>.<token>`) and no builder power inside it.
771///
772/// Refused on a suspended school (`403`): a suspension closes the school's
773/// doors, and this is one of them. Un-suspend it first.
774#[utoipa::path(
775 post,
776 path = "/schools/{slug}/enter",
777 tag = "builder",
778 security(("session_cookie" = [])),
779 params(("slug" = String, Path, description = "School slug")),
780 request_body = EnterSchool,
781 responses(
782 (status = 200, description = "Entered; that school's session cookie is set", body = UserResponse),
783 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
784 (status = 403, description = "The school is suspended", body = ErrorResponse),
785 (status = 404, description = "No such school, or no such account in it", body = ErrorResponse),
786 (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse),
787 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
788 ),
789)]
790async fn enter_school(
791 State(st): State<AppState>,
792 RequireBuilder(_builder): RequireBuilder,
793 jar: CookieJar,
794 Path(slug): Path<String>,
795 Json(req): Json<EnterSchool>,
796) -> Result<(CookieJar, Json<UserResponse>), AppError> {
797 let slug = path_slug(&slug)?;
798 let (db, status) = st.tenants.get_any_status(&slug).await?;
799 if status == SchoolStatus::Suspended {
800 return Err(AppError::Forbidden("school is suspended"));
801 }
802 let user = school_admin(&req.username, &db).await?;
803
804 let session = service::session::create(&db, user.get_id()).await?;
805 let cookie = session_cookie(
806 format!("{slug}.{}", session.token().as_str()),
807 st.cookie_secure,
808 );
809 Ok((jar.add(cookie), Json(UserResponse::new(&user))))
810}