forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB69d4295Ahmet Kaan Gümüş2 months ago536 commits

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