forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

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