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_api.rs2120 lines, 69.9 KiBHistoryRawDownload
1//! The vendor surface (`web::builder`): the one principal that is not a user of
2//! any school. Everything here is about the line between the two — a builder
3//! cookie must never act inside a school, a school cookie must never manage
4//! schools, and a session minted by `enter` must act in exactly one school.
5
6mod common;
7
8use axum::Router;
9use axum::http::StatusCode;
10use common::*;
11use hezarfen_backend::domain::user::{Password, Username};
12use hezarfen_backend::service::builder;
13use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId, Tenants};
14use serde_json::{Value, json};
15
16const BUILDER_USER: &str = "operator";
17const BUILDER_PASS: &str = "secret1";
18
19/// A deployment with the demo school, plus a builder account to drive it —
20/// production's `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed, by the same path.
21async fn deployment() -> (Router, hezarfen_backend::database::Database, Tenants) {
22 let (app, db, tenants) = app_and_tenants().await;
23 builder::ensure(
24 tenants.control(),
25 Username::try_new(BUILDER_USER).unwrap(),
26 Password::try_new(BUILDER_PASS).unwrap(),
27 )
28 .await
29 .expect("seed the builder");
30 (app, db, tenants)
31}
32
33async fn builder_login(app: &Router) -> String {
34 let res = bsend(
35 app,
36 "POST",
37 "/builder/login",
38 None,
39 Some(json!({ "username": BUILDER_USER, "password": BUILDER_PASS })),
40 )
41 .await;
42 assert_eq!(res.status, StatusCode::OK, "builder login: {:?}", res.body);
43 res.cookie.expect("builder cookie set on login")
44}
45
46/// Create a school as the builder. `label` is only the display-name prefix
47/// (`"{label} school"`); the identity comes back as `id`.
48async fn create_school(app: &Router, cookie: &str, label: &str, admin_pass: &str) -> Res {
49 bsend(
50 app,
51 "POST",
52 "/schools",
53 Some(cookie),
54 Some(json!({
55 "name": format!("{label} school"),
56 "admin_username": "admin",
57 "admin_password": admin_pass,
58 })),
59 )
60 .await
61}
62
63fn created_id(res: &Res) -> String {
64 res.body["id"].as_str().expect("created school id").to_string()
65}
66
67/// Pick `label` out of a login choice list: a uuid is used as-is, otherwise
68/// the school whose name is `{label} school` (the name [`create_school`] writes).
69fn school_choice(body: &Value, label: &str) -> String {
70 if hezarfen_backend::tenant::SchoolId::try_parse(label).is_ok() {
71 return label.to_string();
72 }
73 let want = format!("{label} school");
74 body["schools"]
75 .as_array()
76 .into_iter()
77 .flatten()
78 .find(|s| s["name"].as_str() == Some(want.as_str()) || s["name"].as_str() == Some(label))
79 .and_then(|s| s["id"].as_str())
80 .unwrap_or(label)
81 .to_string()
82}
83
84/// Log `username` into the school named `slug`. The login itself names no
85/// school any more — the admin fixtures reuse one username across many
86/// schools, which makes that admin one *person* with several memberships —
87/// so when login answers a choice list, bind the requested school before
88/// returning. The result is whatever a plain school login would have said.
89async fn school_login(app: &Router, slug: &str, username: &str, password: &str) -> Res {
90 let res = bsend(
91 app,
92 "POST",
93 "/auth/login",
94 None,
95 Some(json!({ "username": username, "password": password })),
96 )
97 .await;
98 if res.body["schools"].is_array() {
99 assert_eq!(res.status, StatusCode::OK, "choice login {username}");
100 let selected = bsend(
101 app,
102 "POST",
103 "/auth/school",
104 res.cookie.as_deref(),
105 Some(json!({ "school": school_choice(&res.body, slug) })),
106 )
107 .await;
108 assert_eq!(
109 selected.status,
110 StatusCode::OK,
111 "select {slug} for {username}"
112 );
113 return selected;
114 }
115 res
116}
117
118fn school_ids(body: &Value) -> Vec<String> {
119 items(body)
120 .iter()
121 .map(|item| item["id"].as_str().expect("id").to_string())
122 .collect()
123}
124
125fn school_names(body: &Value) -> Vec<&str> {
126 items(body)
127 .iter()
128 .map(|item| item["name"].as_str().expect("name"))
129 .collect()
130}
131
132
133/// Rewrite `/schools/{label}` to `/schools/{id}` when `label` is a school this
134/// deployment created (`"{label} school"`). A segment that is already a uuid,
135/// or that names no school, is left alone so a 404 stays a 404.
136async fn bsend(
137 app: &Router,
138 method: &str,
139 path: &str,
140 cookie: Option<&str>,
141 body: Option<Value>,
142) -> Res {
143 let path = rewrite_school_path(app, cookie, path).await;
144 common::send(app, method, &path, cookie, body).await
145}
146
147async fn rewrite_school_path(app: &Router, cookie: Option<&str>, path: &str) -> String {
148 let Some(rest) = path.strip_prefix("/schools/") else {
149 return path.to_string();
150 };
151 if rest.is_empty() || rest.contains('{') {
152 return path.to_string();
153 }
154 let (seg, tail) = match rest.split_once('/') {
155 Some((seg, tail)) => (seg, format!("/{tail}")),
156 None => (rest, String::new()),
157 };
158 if hezarfen_backend::tenant::SchoolId::try_parse(seg).is_ok() {
159 return path.to_string();
160 }
161 let Some(cookie) = cookie else {
162 return path.to_string();
163 };
164 let list = common::send(app, "GET", "/schools", Some(cookie), None).await;
165 let Some(rows) = list.body.get("items").and_then(|v| v.as_array()) else {
166 return path.to_string();
167 };
168 let want = format!("{seg} school");
169 let id = rows.iter().find_map(|row| {
170 let name = row["name"].as_str()?;
171 if name == want || name == seg {
172 row["id"].as_str().map(str::to_string)
173 } else {
174 None
175 }
176 });
177 match id {
178 Some(id) => format!("/schools/{id}{tail}"),
179 None => path.to_string(),
180 }
181}
182
183/// The two cookies share a name and nothing else. This is the whole point of
184/// the split: neither principal may ever be accepted where the other belongs.
185#[tokio::test]
186async fn a_builder_logs_in_and_its_cookie_works_here_and_nowhere_else() {
187 let (app, _db, _tenants) = deployment().await;
188 let builder = builder_login(&app).await;
189
190 let me = bsend(&app, "GET", "/builder/me", Some(&builder), None).await;
191 assert_eq!(me.status, StatusCode::OK);
192 assert_eq!(me.body["username"], BUILDER_USER);
193 assert!(me.body["id"].as_str().is_some_and(|id| !id.is_empty()));
194
195 // A school user's cookie is not a builder's…
196 let student = login(&app, "ali").await;
197 assert_eq!(
198 bsend(&app, "GET", "/builder/me", Some(&student), None)
199 .await
200 .status,
201 StatusCode::UNAUTHORIZED,
202 "a school cookie reached the builder surface"
203 );
204 assert_eq!(
205 bsend(&app, "GET", "/schools", Some(&student), None)
206 .await
207 .status,
208 StatusCode::UNAUTHORIZED
209 );
210 // …and a builder's is not a school user's.
211 assert_eq!(
212 bsend(&app, "GET", "/auth/me", Some(&builder), None)
213 .await
214 .status,
215 StatusCode::UNAUTHORIZED,
216 "a builder cookie reached a school surface"
217 );
218
219 // Bad credentials, both shapes.
220 for bad in [
221 json!({ "username": BUILDER_USER, "password": "wrongpass" }),
222 json!({ "username": "ghost", "password": BUILDER_PASS }),
223 ] {
224 assert_eq!(
225 bsend(&app, "POST", "/builder/login", None, Some(bad))
226 .await
227 .status,
228 StatusCode::UNAUTHORIZED
229 );
230 }
231
232 let out = bsend(&app, "POST", "/builder/logout", Some(&builder), None).await;
233 assert_eq!(out.status, StatusCode::NO_CONTENT);
234 assert_eq!(
235 bsend(&app, "GET", "/builder/me", Some(&builder), None)
236 .await
237 .status,
238 StatusCode::UNAUTHORIZED,
239 "logout must revoke the session, not just clear the cookie"
240 );
241}
242
243/// One call brings a whole school into being: registry row, database, schema,
244/// and an admin who can actually log into it.
245#[tokio::test]
246async fn creating_a_school_seeds_an_admin_who_can_log_in() {
247 let (app, _db, _tenants) = deployment().await;
248 let builder = builder_login(&app).await;
249
250 let created = create_school(&app, &builder, "ata-koleji", "secret1").await;
251 assert_eq!(
252 created.status,
253 StatusCode::CREATED,
254 "create school: {:?}",
255 created.body
256 );
257 let id = created_id(&created);
258 assert_eq!(created.body["name"], "ata-koleji school");
259 assert_eq!(created.body["status"], "active");
260 assert!(
261 hezarfen_backend::tenant::SchoolId::try_parse(&id).is_ok(),
262 "the identity is a hyphenated uuid: {id}"
263 );
264
265 let login = school_login(&app, &id, "admin", "secret1").await;
266 assert_eq!(login.status, StatusCode::OK, "seeded admin logs in");
267 let cookie = login.cookie.expect("school cookie");
268 assert!(
269 cookie.starts_with(&format!("session={id}.")),
270 "the cookie names its school: {cookie}"
271 );
272 let me = bsend(&app, "GET", "/auth/me", Some(&cookie), None).await;
273 assert_eq!(me.status, StatusCode::OK);
274 assert_eq!(
275 me.body["role"], "admin",
276 "the seed is an admin, not a student"
277 );
278
279 // A blank name and a too-short admin password are refused before a
280 // database exists. Same name as an existing school is allowed — the id
281 // is the identity, not the display name.
282 for body in [
283 json!({ "name": " ", "admin_username": "admin", "admin_password": "secret1" }),
284 json!({ "name": "Yeni", "admin_username": "admin", "admin_password": "x" }),
285 ] {
286 assert_eq!(
287 bsend(&app, "POST", "/schools", Some(&builder), Some(body))
288 .await
289 .status,
290 StatusCode::BAD_REQUEST
291 );
292 }
293 let again = school_login(&app, &id, "admin", "secret1").await;
294 assert_eq!(again.status, StatusCode::OK);
295 let cookie = again.cookie.expect("cookie");
296 assert!(
297 cookie.starts_with(&format!("session={id}.")),
298 "a refused create must not have made a school: {cookie:?}"
299 );
300}
301
302/// Listing, reading and patching the registry — and the suspension that closes
303/// a school to its own users while the builder keeps managing it.
304#[tokio::test]
305async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
306 let (app, _db, _tenants) = deployment().await;
307 let builder = builder_login(&app).await;
308 let created = create_school(&app, &builder, "beta", "secret1").await;
309 assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body);
310 let beta = created_id(&created);
311
312 let list = bsend(&app, "GET", "/schools", Some(&builder), None).await;
313 assert_eq!(list.status, StatusCode::OK);
314 let listed = school_ids(&list.body);
315 assert!(listed.contains(&DEMO_SCHOOL_ID.to_string()) && listed.contains(&beta));
316 assert_eq!(total(&list.body), 2);
317 // The envelope pages like every other list.
318 let page = bsend(&app, "GET", "/schools?limit=1", Some(&builder), None).await;
319 assert_eq!(items(&page.body).len(), 1);
320 assert_eq!(total(&page.body), 2);
321
322 assert_eq!(
323 bsend(&app, "GET", "/schools/ghost", Some(&builder), None)
324 .await
325 .status,
326 StatusCode::NOT_FOUND
327 );
328
329 // A partial patch touches only what it names: the name moves, the status
330 // and the created stamp stay.
331 let before = bsend(&app, "GET", &format!("/schools/{beta}"), Some(&builder), None).await;
332 let renamed = bsend(
333 &app,
334 "PATCH",
335 &format!("/schools/{beta}"),
336 Some(&builder),
337 Some(json!({ "name": "Beta Koleji" })),
338 )
339 .await;
340 assert_eq!(renamed.status, StatusCode::OK);
341 assert_eq!(renamed.body["name"], "Beta Koleji");
342 assert_eq!(renamed.body["status"], "active");
343 assert_eq!(renamed.body["id"], beta);
344 assert_eq!(renamed.body["created_at"], before.body["created_at"]);
345 // An empty patch is a no-op read, and a bad status is a 400 — including
346 // `provisioning`, which is the boot's own word for a school that is still
347 // being made and not a state a vendor can ask for.
348 let untouched = bsend(
349 &app,
350 "PATCH",
351 &format!("/schools/{beta}"),
352 Some(&builder),
353 Some(json!({})),
354 )
355 .await;
356 assert_eq!(untouched.body["name"], "Beta Koleji");
357 for refused in ["closed", "provisioning"] {
358 assert_eq!(
359 bsend(
360 &app,
361 "PATCH",
362 &format!("/schools/{beta}"),
363 Some(&builder),
364 Some(json!({ "status": refused })),
365 )
366 .await
367 .status,
368 StatusCode::BAD_REQUEST,
369 "status {refused:?}"
370 );
371 }
372
373 // A live cookie, taken out before the suspension.
374 let live = school_login(&app, &beta, "admin", "secret1")
375 .await
376 .cookie
377 .expect("school cookie");
378 let suspended = bsend(
379 &app,
380 "PATCH",
381 &format!("/schools/{beta}"),
382 Some(&builder),
383 Some(json!({ "status": "suspended" })),
384 )
385 .await;
386 assert_eq!(suspended.status, StatusCode::OK);
387 assert_eq!(suspended.body["status"], "suspended");
388
389 assert_eq!(
390 school_login(&app, &beta, "admin", "secret1").await.status,
391 StatusCode::FORBIDDEN,
392 "a suspended school refuses login"
393 );
394 assert_eq!(
395 bsend(&app, "GET", "/auth/me", Some(&live), None)
396 .await
397 .status,
398 StatusCode::FORBIDDEN,
399 "…and the cookie it had already issued, on its very next call"
400 );
401 // The builder still manages it — that is how it gets un-suspended.
402 assert_eq!(
403 bsend(&app, "GET", &format!("/schools/{beta}"), Some(&builder), None)
404 .await
405 .status,
406 StatusCode::OK
407 );
408 // …except entering it, the one door a suspension must also close.
409 assert_eq!(
410 bsend(
411 &app,
412 "POST",
413 &format!("/schools/{beta}/enter"),
414 Some(&builder),
415 Some(json!({ "username": "admin" })),
416 )
417 .await
418 .status,
419 StatusCode::FORBIDDEN
420 );
421
422 bsend(
423 &app,
424 "PATCH",
425 &format!("/schools/{beta}"),
426 Some(&builder),
427 Some(json!({ "status": "active" })),
428 )
429 .await;
430 assert_eq!(
431 bsend(&app, "GET", "/auth/me", Some(&live), None)
432 .await
433 .status,
434 StatusCode::OK,
435 "resuming restores the very same session"
436 );
437}
438
439/// The lockout fix: re-key an admin, and take every session minted under the
440/// old password with it.
441#[tokio::test]
442async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions() {
443 let (app, _db, _tenants) = deployment().await;
444 let builder = builder_login(&app).await;
445 create_school(&app, &builder, "gamma", "secret1").await;
446 create_school(&app, &builder, "delta", "secret1").await;
447 let old_cookie = school_login(&app, "gamma", "admin", "secret1")
448 .await
449 .cookie
450 .expect("school cookie");
451 let person_cookie = bsend(
452 &app,
453 "POST",
454 "/auth/login",
455 None,
456 Some(json!({ "username": "admin", "password": "secret1" })),
457 )
458 .await
459 .cookie
460 .expect("person cookie from a two-school login");
461
462 // An account that is not an admin of that school, and one that is not there
463 // at all, are told apart.
464 assert_eq!(
465 bsend(
466 &app,
467 "POST",
468 "/schools/gamma/admin-password",
469 Some(&builder),
470 Some(json!({ "username": "ghost", "password": "secret2" })),
471 )
472 .await
473 .status,
474 StatusCode::NOT_FOUND
475 );
476 let gamma_id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'gamma school'")
477 .fetch_one(_tenants.control())
478 .await
479 .expect("gamma row");
480 let gamma_db = _tenants
481 .get(&hezarfen_backend::tenant::SchoolId::from_uuid(gamma_id))
482 .await
483 .unwrap();
484 hezarfen_backend::db::user::create(&gamma_db, Username::try_new("veli").unwrap(), None)
485 .await
486 .unwrap();
487 assert_eq!(
488 bsend(
489 &app,
490 "POST",
491 "/schools/gamma/admin-password",
492 Some(&builder),
493 Some(json!({ "username": "veli", "password": "secret2" })),
494 )
495 .await
496 .status,
497 StatusCode::CONFLICT,
498 "a student is not the school's admin"
499 );
500
501 let reset = bsend(
502 &app,
503 "POST",
504 "/schools/gamma/admin-password",
505 Some(&builder),
506 Some(json!({ "username": "admin", "password": "secret2" })),
507 )
508 .await;
509 assert_eq!(reset.status, StatusCode::NO_CONTENT);
510
511 assert_eq!(
512 school_login(&app, "gamma", "admin", "secret1").await.status,
513 StatusCode::UNAUTHORIZED,
514 "the old password must be dead"
515 );
516 assert_eq!(
517 school_login(&app, "gamma", "admin", "secret2").await.status,
518 StatusCode::OK
519 );
520 assert_eq!(
521 bsend(&app, "GET", "/auth/me", Some(&old_cookie), None)
522 .await
523 .status,
524 StatusCode::UNAUTHORIZED,
525 "a reset that leaves the old cookie working resets nothing"
526 );
527 assert_eq!(
528 bsend(
529 &app,
530 "POST",
531 "/auth/school",
532 Some(&person_cookie),
533 Some(json!({ "school": gamma_id.to_string() })),
534 )
535 .await
536 .status,
537 StatusCode::UNAUTHORIZED,
538 "a person cookie minted under the old password must die too"
539 );
540}
541
542/// `enter` mints an ordinary school session: full admin power inside that
543/// school, none at all in the school next door.
544#[tokio::test]
545async fn entering_a_school_acts_in_that_school_and_no_other() {
546 let (app, _db, _tenants) = deployment().await;
547 let builder = builder_login(&app).await;
548 create_school(&app, &builder, "alpha", "secret1").await;
549 create_school(&app, &builder, "beta", "secret1").await;
550
551 let entered = bsend(
552 &app,
553 "POST",
554 "/schools/alpha/enter",
555 Some(&builder),
556 Some(json!({ "username": "admin" })),
557 )
558 .await;
559 assert_eq!(entered.status, StatusCode::OK, "enter: {:?}", entered.body);
560 assert_eq!(entered.body["username"], "admin");
561 assert_eq!(entered.body["role"], "admin");
562 let alpha = entered.cookie.expect("a school cookie");
563 assert!(alpha.trim_start_matches("session=").split_once('.').unwrap().0.len() == 36, "{alpha}");
564
565 // It is an ordinary school session — and only a school session.
566 let me = bsend(&app, "GET", "/auth/me", Some(&alpha), None).await;
567 assert_eq!(me.status, StatusCode::OK);
568 assert_eq!(me.body["role"], "admin");
569 assert_eq!(
570 bsend(&app, "GET", "/builder/me", Some(&alpha), None)
571 .await
572 .status,
573 StatusCode::UNAUTHORIZED,
574 "entering a school must not hand back builder power"
575 );
576
577 // A row written in alpha is invisible from beta — the isolation the whole
578 // per-school database exists for.
579 let note = bsend(
580 &app,
581 "POST",
582 "/notes",
583 Some(&alpha),
584 Some(json!({ "title": "alpha only", "content": "mine" })),
585 )
586 .await;
587 assert_eq!(note.status, StatusCode::CREATED);
588 let note_id = id_of(&note.body);
589 let beta = bsend(
590 &app,
591 "POST",
592 "/schools/beta/enter",
593 Some(&builder),
594 Some(json!({ "username": "admin" })),
595 )
596 .await
597 .cookie
598 .expect("beta cookie");
599 assert_eq!(
600 bsend(&app, "GET", &format!("/notes/{note_id}"), Some(&beta), None)
601 .await
602 .status,
603 StatusCode::NOT_FOUND,
604 "a note written in alpha was reachable under beta's cookie"
605 );
606
607 // Unknown school, unknown account, non-admin account.
608 assert_eq!(
609 bsend(
610 &app,
611 "POST",
612 "/schools/ghost/enter",
613 Some(&builder),
614 Some(json!({ "username": "admin" })),
615 )
616 .await
617 .status,
618 StatusCode::NOT_FOUND
619 );
620 assert_eq!(
621 bsend(
622 &app,
623 "POST",
624 "/schools/alpha/enter",
625 Some(&builder),
626 Some(json!({ "username": "nobody" })),
627 )
628 .await
629 .status,
630 StatusCode::NOT_FOUND
631 );
632}
633
634/// Deleting a school takes its rows *and* its bytes — and only its own.
635#[tokio::test]
636async fn deleting_a_school_takes_its_data_and_its_files() {
637 let (app, _db, _tenants) = deployment().await;
638 let builder = builder_login(&app).await;
639 create_school(&app, &builder, "delta", "secret1").await;
640 create_school(&app, &builder, "epsilon", "secret1").await;
641
642 // A note with a file in each school, so the delete has bytes to take.
643 let mut blobs = Vec::new();
644 for slug in ["delta", "epsilon"] {
645 let cookie = school_login(&app, slug, "admin", "secret1")
646 .await
647 .cookie
648 .expect("school cookie");
649 let note = bsend(
650 &app,
651 "POST",
652 "/notes",
653 Some(&cookie),
654 Some(json!({ "title": "with a file", "content": "x" })),
655 )
656 .await;
657 assert_eq!(note.status, StatusCode::CREATED);
658 let up = upload_file(
659 &app,
660 &cookie,
661 &id_of(&note.body),
662 "plan.pdf",
663 "application/pdf",
664 b"bytes",
665 )
666 .await;
667 assert_eq!(up.status, StatusCode::CREATED, "upload: {:?}", up.body);
668 // One directory per school under `FILES_PATH`, named by the school uuid.
669 let school = cookie.trim_start_matches("session=").split_once('.').unwrap().0;
670 let blob = files_dir().join(school).join(id_of(&up.body));
671 assert!(blob.exists(), "{} should exist", blob.display());
672 blobs.push(blob);
673 }
674
675 let deleted = bsend(&app, "DELETE", "/schools/delta", Some(&builder), None).await;
676 assert_eq!(deleted.status, StatusCode::NO_CONTENT);
677
678 assert_eq!(
679 bsend(&app, "GET", "/schools/delta", Some(&builder), None)
680 .await
681 .status,
682 StatusCode::NOT_FOUND
683 );
684 // A deleted school is not a door any more. The person's login has only
685 // `epsilon` left to enter — the dropped slug is neither offered nor 403'd.
686 let after_delete = school_login(&app, "delta", "admin", "secret1").await;
687 assert_eq!(after_delete.status, StatusCode::OK);
688 {
689 let kept = after_delete.cookie.expect("cookie");
690 let prefix = kept.trim_start_matches("session=").split_once('.').unwrap().0;
691 assert_eq!(prefix.len(), 36, "remaining school uuid: {kept}");
692 assert!(!blobs[0].parent().unwrap().exists(), "deleted school files dir must be gone");
693 }
694 assert!(
695 blobs[1].exists(),
696 "the school next door must keep every byte it owns"
697 );
698 // Its neighbour is untouched all the way through the API.
699 assert_eq!(
700 school_login(&app, "epsilon", "admin", "secret1")
701 .await
702 .status,
703 StatusCode::OK
704 );
705 // Deleting it again is a 404, not a second destruction.
706 assert_eq!(
707 bsend(&app, "DELETE", "/schools/delta", Some(&builder), None)
708 .await
709 .status,
710 StatusCode::NOT_FOUND
711 );
712}
713
714// ---------------------------------------------------------------------------
715// REFUTE-mode probes on the irreversible paths (appended by a verifier).
716// ---------------------------------------------------------------------------
717
718
719/// Claim 1: no `/schools/{slug}` route can be aimed outside `FILES_PATH/<slug>`.
720/// Every hostile segment on every method, with canaries inside and outside the
721/// deployment's files root.
722#[tokio::test]
723async fn probe_hostile_slug_segments_never_delete_anything() {
724 let (app, _db, _tenants) = deployment().await;
725 let builder = builder_login(&app).await;
726
727 // A school that must survive all of it, with real bytes on disk.
728 create_school(&app, &builder, "p1keep", "secret1").await;
729 let keep_dir = files_dir().join("p1keep");
730 std::fs::create_dir_all(&keep_dir).unwrap();
731 std::fs::write(keep_dir.join("keep.bin"), b"keep").unwrap();
732 // A canary at the files root itself: an escape by one `..` takes this.
733 let root_canary = files_dir().join("p1_root_canary");
734 std::fs::write(&root_canary, b"canary").unwrap();
735 // …and one fully outside the deployment root.
736 let outside = tempfile::tempdir().unwrap();
737 let outside_file = outside.path().join("outside.bin");
738 std::fs::write(&outside_file, b"outside").unwrap();
739
740 let hostile = [
741 "..",
742 "%2e%2e",
743 "%2E%2E%2F%2E%2E",
744 "..%2f..%2fetc",
745 "%2f",
746 "p1keep%2f..",
747 "p1keep..",
748 ".",
749 "%00",
750 "DEMO",
751 "Demo",
752 "control",
753 "builder",
754 "%C4%B1demo", // dotless i, non-ascii
755 "d%E2%80%8Bemo", // zero-width space
756 "de%20mo",
757 "a",
758 "-lead",
759 "demo%2e%2e%2f%2e%2e%2fp1keep",
760 // 200 characters
761 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
762 ];
763
764 for raw in hostile {
765 for (method, suffix, body) in [
766 ("GET", "", None),
767 ("DELETE", "", None),
768 ("PATCH", "", Some(json!({ "name": "x" }))),
769 (
770 "POST",
771 "/admin-password",
772 Some(json!({ "username": "admin", "password": "secret2" })),
773 ),
774 ("POST", "/enter", Some(json!({ "username": "admin" }))),
775 ] {
776 let uri = format!("/schools/{raw}{suffix}");
777 let res = bsend(&app, method, &uri, Some(&builder), body).await;
778 assert!(
779 res.status == StatusCode::NOT_FOUND
780 || res.status == StatusCode::METHOD_NOT_ALLOWED
781 || res.status == StatusCode::BAD_REQUEST
782 || res.status == StatusCode::UNAUTHORIZED,
783 "{method} {uri} answered {} — a hostile slug must be refused",
784 res.status
785 );
786 assert!(
787 !res.status.is_success(),
788 "{method} {uri} SUCCEEDED ({})",
789 res.status
790 );
791 }
792 }
793
794 // Also the empty segment, which is a different route shape entirely.
795 for method in ["GET", "DELETE", "PATCH"] {
796 let res = bsend(&app, method, "/schools/", Some(&builder), None).await;
797 assert!(
798 !res.status.is_success() || method == "GET",
799 "{method} /schools/ -> {}",
800 res.status
801 );
802 }
803
804 assert!(
805 keep_dir.join("keep.bin").exists(),
806 "a bystander school lost its bytes"
807 );
808 assert!(
809 root_canary.exists(),
810 "the FILES_PATH root canary was deleted"
811 );
812 assert!(
813 outside_file.exists(),
814 "a file outside FILES_PATH was deleted"
815 );
816 assert!(
817 files_dir().exists() && outside.path().exists(),
818 "a directory root was removed"
819 );
820 std::fs::remove_file(&root_canary).ok();
821}
822
823/// Claim 2: `drop` takes exactly the named school; a neighbour's cached handle
824/// keeps working; a re-created slug is an *empty* school.
825#[tokio::test]
826async fn probe_drop_is_scoped_and_recreation_is_empty() {
827 let (app, _db, tenants) = deployment().await;
828 let builder = builder_login(&app).await;
829 create_school(&app, &builder, "p2a", "secret1").await;
830 create_school(&app, &builder, "p2b", "secret1").await;
831
832 let a = school_login(&app, "p2a", "admin", "secret1")
833 .await
834 .cookie
835 .expect("p2a cookie");
836 let b = school_login(&app, "p2b", "admin", "secret1")
837 .await
838 .cookie
839 .expect("p2b cookie");
840 // A row only p2a has.
841 let note = bsend(
842 &app,
843 "POST",
844 "/notes",
845 Some(&a),
846 Some(json!({ "title": "secret", "content": "x" })),
847 )
848 .await;
849 assert_eq!(note.status, StatusCode::CREATED);
850 // A second user only p2a has.
851 let p2a_id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'p2a school'")
852 .fetch_one(tenants.control())
853 .await
854 .expect("p2a");
855 let _ = bsend(
856 &app,
857 "POST",
858 "/auth/register",
859 None,
860 Some(json!({ "school": p2a_id.to_string(), "username": "ali", "password": "secret1" })),
861 )
862 .await;
863
864 assert_eq!(
865 bsend(&app, "DELETE", "/schools/p2a", Some(&builder), None)
866 .await
867 .status,
868 StatusCode::NO_CONTENT
869 );
870
871 // The neighbour's already-resolved handle is untouched.
872 assert_eq!(
873 bsend(&app, "GET", "/auth/me", Some(&b), None).await.status,
874 StatusCode::OK,
875 "dropping p2a disturbed p2b's cached handle"
876 );
877 // The dropped school is unknown, not forbidden.
878 assert_eq!(
879 bsend(&app, "GET", "/auth/me", Some(&a), None).await.status,
880 StatusCode::UNAUTHORIZED
881 );
882 // The person behind `admin` still belongs to p2b: the login has that
883 // school left to enter, and the dropped slug is not among the choices.
884 let after_drop = school_login(&app, "p2a", "admin", "secret1").await;
885 assert_eq!(after_drop.status, StatusCode::OK);
886 let kept = after_drop.cookie.expect("cookie");
887 assert!(
888 kept.trim_start_matches("session=").split_once('.').unwrap().0.len() == 36,
889 "login must enter the remaining school by uuid: {kept}"
890 );
891
892 // Re-created with the same slug. `admin` is one *person*: the same
893 // username under the same password links that person into the new
894 // school, and under a *different* password the create itself refuses
895 // with a 409 — a builder is authenticated, there is nothing to enumerate.
896 let again = create_school(&app, &builder, "p2a", "secret1").await;
897 assert_eq!(again.status, StatusCode::CREATED, "{:?}", again.body);
898 let fresh = school_login(&app, "p2a", "admin", "secret1")
899 .await
900 .cookie
901 .expect("fresh admin cookie");
902 let users = bsend(&app, "GET", "/users", Some(&fresh), None).await;
903 assert_eq!(users.status, StatusCode::OK, "{:?}", users.body);
904 assert_eq!(
905 total(&users.body),
906 1,
907 "a re-created school carries users from the dropped one: {:?}",
908 users.body
909 );
910 let notes = bsend(&app, "GET", "/notes", Some(&fresh), None).await;
911 assert_eq!(notes.status, StatusCode::OK);
912 assert_eq!(total(&notes.body), 0, "old rows survived the drop");
913
914 // A *different* password for an existing person is a plain 409, and no
915 // school is left behind by the refusal.
916 let mismatched = create_school(&app, &builder, "p2c", "secret9").await;
917 assert_eq!(
918 mismatched.status,
919 StatusCode::CONFLICT,
920 "{:?}",
921 mismatched.body
922 );
923 assert_eq!(
924 bsend(&app, "GET", "/schools/p2c", Some(&builder), None)
925 .await
926 .status,
927 StatusCode::NOT_FOUND,
928 "a refused create must not leave a school behind"
929 );
930}
931
932/// Claim 4: `admin-password` and `enter` cannot be aimed at a non-admin, at a
933/// stranger's account, or (for `enter`) at a suspended school; and a reset kills
934/// **every** live session of that account.
935#[tokio::test]
936async fn probe_admin_targets_and_reset_revokes_all_sessions() {
937 let (app, _db, tenants) = deployment().await;
938 let builder = builder_login(&app).await;
939 create_school(&app, &builder, "p4a", "secret1").await;
940 create_school(&app, &builder, "p4b", "secret1").await;
941 let p4a_id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'p4a school'")
942 .fetch_one(tenants.control()).await.expect("p4a");
943 let p4b_id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'p4b school'")
944 .fetch_one(tenants.control())
945 .await
946 .expect("p4b");
947 let a_db = tenants.get(&SchoolId::from_uuid(p4a_id)).await.unwrap();
948
949 // Three non-admins in p4a, and a name that only exists in p4b.
950 for (name, role) in [("tea", "teacher"), ("stu", "student"), ("par", "parent")] {
951 let reg = bsend(
952 &app,
953 "POST",
954 "/auth/register",
955 None,
956 Some(json!({ "school": p4a_id.to_string(), "username": name, "password": "secret1" })),
957 )
958 .await;
959 assert_eq!(reg.status, StatusCode::CREATED, "register {name}");
960 set_role(&a_db, name, role).await;
961 }
962 let reg = bsend(
963 &app,
964 "POST",
965 "/auth/register",
966 None,
967 Some(json!({ "school": p4b_id.to_string(), "username": "onlyb", "password": "secret1" })),
968 )
969 .await;
970 assert_eq!(reg.status, StatusCode::CREATED);
971
972 for target in ["tea", "stu", "par"] {
973 for (path, body) in [
974 (
975 "/schools/p4a/admin-password",
976 json!({ "username": target, "password": "secret2" }),
977 ),
978 ("/schools/p4a/enter", json!({ "username": target })),
979 ] {
980 let res = bsend(&app, "POST", path, Some(&builder), Some(body)).await;
981 assert_eq!(
982 res.status,
983 StatusCode::CONFLICT,
984 "{path} accepted the non-admin {target}: {} {:?}",
985 res.status,
986 res.body
987 );
988 }
989 }
990 // A user of the school next door is not reachable from this school.
991 for (path, body) in [
992 (
993 "/schools/p4a/admin-password",
994 json!({ "username": "onlyb", "password": "secret2" }),
995 ),
996 ("/schools/p4a/enter", json!({ "username": "onlyb" })),
997 ] {
998 let res = bsend(&app, "POST", path, Some(&builder), Some(body)).await;
999 assert_eq!(
1000 res.status,
1001 StatusCode::NOT_FOUND,
1002 "{path} reached across schools: {:?}",
1003 res.body
1004 );
1005 }
1006
1007 // Two live sessions for the same admin; a reset must kill both.
1008 let s1 = school_login(&app, "p4a", "admin", "secret1")
1009 .await
1010 .cookie
1011 .expect("session 1");
1012 let s2 = school_login(&app, "p4a", "admin", "secret1")
1013 .await
1014 .cookie
1015 .expect("session 2");
1016 assert_ne!(s1, s2, "the harness reused one session");
1017 // A bystander session in the same school must survive.
1018 let tea = school_login(&app, "p4a", "tea", "secret1")
1019 .await
1020 .cookie
1021 .expect("teacher session");
1022
1023 let reset = bsend(
1024 &app,
1025 "POST",
1026 "/schools/p4a/admin-password",
1027 Some(&builder),
1028 Some(json!({ "username": "admin", "password": "secret2" })),
1029 )
1030 .await;
1031 assert_eq!(reset.status, StatusCode::NO_CONTENT);
1032 for (n, cookie) in [(1, &s1), (2, &s2)] {
1033 assert_eq!(
1034 bsend(&app, "GET", "/auth/me", Some(cookie), None)
1035 .await
1036 .status,
1037 StatusCode::UNAUTHORIZED,
1038 "session {n} survived the password reset"
1039 );
1040 }
1041 assert_eq!(
1042 bsend(&app, "GET", "/auth/me", Some(&tea), None).await.status,
1043 StatusCode::OK,
1044 "the reset revoked a bystander's session"
1045 );
1046
1047 // `enter` on a suspended school is 403; `admin-password` still works.
1048 assert_eq!(
1049 bsend(
1050 &app,
1051 "PATCH",
1052 "/schools/p4a",
1053 Some(&builder),
1054 Some(json!({ "status": "suspended" })),
1055 )
1056 .await
1057 .status,
1058 StatusCode::OK
1059 );
1060 let entered = bsend(
1061 &app,
1062 "POST",
1063 "/schools/p4a/enter",
1064 Some(&builder),
1065 Some(json!({ "username": "admin" })),
1066 )
1067 .await;
1068 assert_eq!(
1069 entered.status,
1070 StatusCode::FORBIDDEN,
1071 "enter opened a suspended school: {:?}",
1072 entered.body
1073 );
1074 assert!(
1075 entered.cookie.is_none(),
1076 "a refused enter still set a school cookie"
1077 );
1078 assert_eq!(
1079 bsend(
1080 &app,
1081 "POST",
1082 "/schools/p4a/admin-password",
1083 Some(&builder),
1084 Some(json!({ "username": "admin", "password": "secret3" })),
1085 )
1086 .await
1087 .status,
1088 StatusCode::NO_CONTENT,
1089 "a lockout fix must still work on a suspended school"
1090 );
1091}
1092
1093/// Claim 5: builder session hygiene — logout is a revocation, and neither
1094/// principal's token works under the other's prefix.
1095#[tokio::test]
1096async fn probe_builder_session_hygiene() {
1097 let (app, _db, _tenants) = deployment().await;
1098 let builder = builder_login(&app).await;
1099 let student = login(&app, "veli").await;
1100
1101 let builder_token = builder.trim_start_matches("session=builder.").to_string();
1102 let student_token = cookie_token(&student).to_string();
1103
1104 // The builder's own token, worn as a school cookie.
1105 for uri in ["/auth/me", "/users", "/notes"] {
1106 let res = bsend(
1107 &app,
1108 "GET",
1109 uri,
1110 Some(&format!("session={DEMO_SCHOOL_ID}.{builder_token}")),
1111 None,
1112 )
1113 .await;
1114 assert_eq!(
1115 res.status,
1116 StatusCode::UNAUTHORIZED,
1117 "{uri} accepted a builder token under a school prefix"
1118 );
1119 }
1120 // And a school token worn as a builder cookie.
1121 for uri in ["/builder/me", "/schools"] {
1122 let res = bsend(
1123 &app,
1124 "GET",
1125 uri,
1126 Some(&format!("session=builder.{student_token}")),
1127 None,
1128 )
1129 .await;
1130 assert_eq!(
1131 res.status,
1132 StatusCode::UNAUTHORIZED,
1133 "{uri} accepted a school token under the builder prefix"
1134 );
1135 }
1136
1137 // Logout is a server-side revocation: the same cookie is dead everywhere.
1138 assert_eq!(
1139 bsend(&app, "POST", "/builder/logout", Some(&builder), None)
1140 .await
1141 .status,
1142 StatusCode::NO_CONTENT
1143 );
1144 for (method, uri, body) in [
1145 ("GET", "/builder/me", None),
1146 ("GET", "/schools", None),
1147 (
1148 "POST",
1149 "/schools",
1150 Some(json!({
1151 "slug": "p5ghost",
1152 "name": "p5ghost school",
1153 "admin_username": "admin",
1154 "admin_password": "secret1"
1155 })),
1156 ),
1157 ("DELETE", "/schools/demo", None),
1158 ] {
1159 let res = bsend(&app, method, uri, Some(&builder), body).await;
1160 assert_eq!(
1161 res.status,
1162 StatusCode::UNAUTHORIZED,
1163 "{method} {uri} accepted a logged-out builder cookie"
1164 );
1165 }
1166 // …and nothing was created or destroyed by those calls.
1167 let fresh = builder_login(&app).await;
1168 let list = bsend(&app, "GET", "/schools", Some(&fresh), None).await;
1169 assert!(
1170 !school_names(&list.body).contains(&"p5ghost school"),
1171 "a logged-out builder created a school"
1172 );
1173 assert!(
1174 school_ids(&list.body).contains(&DEMO_SCHOOL_ID.to_string()),
1175 "a logged-out builder deleted the demo school"
1176 );
1177 // Logout is idempotent and safe without a cookie.
1178 assert_eq!(
1179 bsend(&app, "POST", "/builder/logout", None, None)
1180 .await
1181 .status,
1182 StatusCode::NO_CONTENT
1183 );
1184}
1185
1186/// Create, enter, and delete a school by its minted uuid. A second create
1187/// with the same display name is a new school — the name is not the identity.
1188#[tokio::test]
1189async fn probe_remote_deployment_creates_and_deletes_a_school() {
1190 let deployment = common::deployment_with(&[]).await;
1191 let app = deployment.app;
1192 builder::ensure(
1193 deployment.tenants.control(),
1194 Username::try_new(BUILDER_USER).unwrap(),
1195 Password::try_new(BUILDER_PASS).unwrap(),
1196 )
1197 .await
1198 .expect("seed the builder");
1199
1200 let builder = builder_login(&app).await;
1201 let plain = create_school(&app, &builder, "atakoleji", "secret1").await;
1202 assert_eq!(plain.status, StatusCode::CREATED, "{:?}", plain.body);
1203 let plain_id = created_id(&plain);
1204 assert_eq!(
1205 school_login(&app, &plain_id, "admin", "secret1")
1206 .await
1207 .status,
1208 StatusCode::OK
1209 );
1210
1211 let made = create_school(&app, &builder, "ata-koleji", "secret1").await;
1212 assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
1213 let made_id = created_id(&made);
1214 let listed = |body: &Value, id: &str| school_ids(body).contains(&id.to_string());
1215 let after_create = bsend(&app, "GET", "/schools", Some(&builder), None).await;
1216 assert!(listed(&after_create.body, &made_id));
1217 let login = school_login(&app, &made_id, "admin", "secret1").await;
1218 assert_eq!(login.status, StatusCode::OK, "the admin logs into the new school");
1219 let deleted = bsend(
1220 &app,
1221 "DELETE",
1222 &format!("/schools/{made_id}"),
1223 Some(&builder),
1224 None,
1225 )
1226 .await;
1227 assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body);
1228 let after_delete = bsend(&app, "GET", "/schools", Some(&builder), None).await;
1229 assert!(!listed(&after_delete.body, &made_id));
1230 // The person still has the first school to enter.
1231 let login_after_delete = school_login(&app, &plain_id, "admin", "secret1").await;
1232 assert_eq!(login_after_delete.status, StatusCode::OK);
1233 assert!(
1234 login_after_delete
1235 .cookie
1236 .expect("cookie")
1237 .contains(&format!("{plain_id}.")),
1238 "the deleted school must not come back at login"
1239 );
1240}
1241
1242
1243
1244// ---------------------------------------------------------------------------
1245// Module entitlements: the vendor's shelf. Every assertion here is about the
1246// same two things — the set a school ends up with, and the fact that a refused
1247// request leaves it exactly as it was.
1248// ---------------------------------------------------------------------------
1249
1250/// The `enabled` list of a modules response, as owned strings.
1251fn enabled(body: &Value) -> Vec<String> {
1252 body["enabled"]
1253 .as_array()
1254 .expect("enabled list")
1255 .iter()
1256 .map(|v| v.as_str().expect("module name").to_string())
1257 .collect()
1258}
1259
1260async fn school_modules(app: &Router, cookie: &str, slug: &str) -> Res {
1261 bsend(
1262 app,
1263 "GET",
1264 &format!("/schools/{slug}/modules"),
1265 Some(cookie),
1266 None,
1267 )
1268 .await
1269}
1270
1271#[tokio::test]
1272async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth() {
1273 let (app, _db, _tenants) = deployment().await;
1274 let builder = builder_login(&app).await;
1275
1276 let listed = school_modules(&app, &builder, DEMO_SCHOOL_ID).await;
1277 assert_eq!(listed.status, StatusCode::OK, "{:?}", listed.body);
1278 assert_eq!(enabled(&listed.body).len(), 21, "{:?}", listed.body);
1279 assert_eq!(
1280 listed.body["disabled"].as_array().expect("disabled"),
1281 &[] as &[Value]
1282 );
1283
1284 let off = bsend(
1285 &app,
1286 "DELETE",
1287 &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"),
1288 Some(&builder),
1289 None,
1290 )
1291 .await;
1292 assert_eq!(off.status, StatusCode::OK, "{:?}", off.body);
1293 assert_eq!(off.body["disabled"], json!(["notes"]));
1294 assert!(!enabled(&off.body).contains(&"notes".to_string()));
1295 assert_eq!(
1296 school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body,
1297 off.body,
1298 "the GET must show what the DELETE answered"
1299 );
1300
1301 // Idempotent both ways: taking back what is already gone changes nothing.
1302 let again = bsend(
1303 &app,
1304 "DELETE",
1305 &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"),
1306 Some(&builder),
1307 None,
1308 )
1309 .await;
1310 assert_eq!(again.status, StatusCode::OK);
1311 assert_eq!(again.body, off.body);
1312
1313 let on = bsend(
1314 &app,
1315 "POST",
1316 &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"),
1317 Some(&builder),
1318 None,
1319 )
1320 .await;
1321 assert_eq!(on.status, StatusCode::OK, "{:?}", on.body);
1322 assert_eq!(on.body, listed.body, "back to the full shelf");
1323 let once_more = bsend(
1324 &app,
1325 "POST",
1326 &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"),
1327 Some(&builder),
1328 None,
1329 )
1330 .await;
1331 assert_eq!(once_more.status, StatusCode::OK);
1332 assert_eq!(once_more.body, listed.body);
1333
1334 // A name nobody sells addresses nothing.
1335 let ghost = bsend(
1336 &app,
1337 "POST",
1338 &format!("/schools/{DEMO_SCHOOL_ID}/modules/kantin"),
1339 Some(&builder),
1340 None,
1341 )
1342 .await;
1343 assert_eq!(ghost.status, StatusCode::NOT_FOUND);
1344}
1345
1346#[tokio::test]
1347async fn a_dependency_is_named_whichever_direction_breaks_it() {
1348 let (app, _db, _tenants) = deployment().await;
1349 let builder = builder_login(&app).await;
1350
1351 // Enabling: a lone school that bought only notes cannot take exams alone.
1352 let created = bsend(
1353 &app,
1354 "POST",
1355 "/schools",
1356 Some(&builder),
1357 Some(json!({
1358 "slug": "lone",
1359 "name": "lone school",
1360 "admin_username": "admin",
1361 "admin_password": "secret1",
1362 "modules": ["notes"],
1363 })),
1364 )
1365 .await;
1366 assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body);
1367 let refused = bsend(
1368 &app,
1369 "POST",
1370 "/schools/lone/modules/exams",
1371 Some(&builder),
1372 None,
1373 )
1374 .await;
1375 assert_eq!(refused.status, StatusCode::CONFLICT, "{:?}", refused.body);
1376 let message = refused.body["error"].as_str().expect("error message");
1377 assert!(message.contains("courses"), "{message}");
1378 assert!(message.contains("subjects"), "names every miss: {message}");
1379 assert_eq!(
1380 enabled(&school_modules(&app, &builder, "lone").await.body),
1381 ["notes"]
1382 );
1383
1384 // Disabling: what is still needed says so, by name.
1385 let held = bsend(
1386 &app,
1387 "DELETE",
1388 &format!("/schools/{DEMO_SCHOOL_ID}/modules/exams"),
1389 Some(&builder),
1390 None,
1391 )
1392 .await;
1393 assert_eq!(held.status, StatusCode::CONFLICT, "{:?}", held.body);
1394 assert_eq!(held.body["error"], json!("exams is required by marks"));
1395
1396 let courses = bsend(
1397 &app,
1398 "DELETE",
1399 &format!("/schools/{DEMO_SCHOOL_ID}/modules/courses"),
1400 Some(&builder),
1401 None,
1402 )
1403 .await;
1404 assert_eq!(courses.status, StatusCode::CONFLICT);
1405 let message = courses.body["error"].as_str().expect("error message");
1406 for dependent in [
1407 "course_notes",
1408 "classes",
1409 "sessions",
1410 "exams",
1411 "subjects",
1412 "homework",
1413 ] {
1414 assert!(
1415 message.contains(dependent),
1416 "{dependent} missing from {message}"
1417 );
1418 }
1419 assert_eq!(
1420 enabled(&school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body).len(),
1421 21
1422 );
1423}
1424
1425#[tokio::test]
1426async fn a_batch_is_all_or_nothing_and_packages_round_trip() {
1427 let (app, _db, _tenants) = deployment().await;
1428 let builder = builder_login(&app).await;
1429 let before = school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body.clone();
1430
1431 // One bad name in a list voids the whole request.
1432 for (body, field) in [
1433 (
1434 json!({ "enable": ["notes"], "disable": ["kantin"] }),
1435 "module",
1436 ),
1437 (json!({ "enable_packages": ["kantin"] }), "package"),
1438 ] {
1439 let bad = bsend(
1440 &app,
1441 "PATCH",
1442 &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
1443 Some(&builder),
1444 Some(body),
1445 )
1446 .await;
1447 assert_eq!(bad.status, StatusCode::BAD_REQUEST, "{:?}", bad.body);
1448 let message = bad.body["error"].as_str().expect("error message");
1449 assert!(
1450 message.contains("kantin") && message.contains(field),
1451 "{message}"
1452 );
1453 assert_eq!(school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body, before);
1454 }
1455
1456 // A name pulled both ways at once has no answer.
1457 let both = bsend(
1458 &app,
1459 "PATCH",
1460 &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
1461 Some(&builder),
1462 Some(json!({ "enable": ["meals"], "disable": ["meals"] })),
1463 )
1464 .await;
1465 assert_eq!(both.status, StatusCode::BAD_REQUEST, "{:?}", both.body);
1466 assert!(
1467 both.body["error"]
1468 .as_str()
1469 .expect("error")
1470 .contains("meals"),
1471 "{:?}",
1472 both.body
1473 );
1474 assert_eq!(school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body, before);
1475
1476 // A resulting set that breaks a dependency is refused as a whole.
1477 let orphaned = bsend(
1478 &app,
1479 "PATCH",
1480 &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
1481 Some(&builder),
1482 Some(json!({ "disable": ["exams"] })),
1483 )
1484 .await;
1485 assert_eq!(orphaned.status, StatusCode::CONFLICT, "{:?}", orphaned.body);
1486 assert!(
1487 orphaned.body["error"]
1488 .as_str()
1489 .expect("error")
1490 .contains("marks requires exams"),
1491 "{:?}",
1492 orphaned.body
1493 );
1494 assert_eq!(school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body, before);
1495
1496 // An empty body is a no-op, not an error.
1497 let empty = bsend(
1498 &app,
1499 "PATCH",
1500 &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
1501 Some(&builder),
1502 Some(json!({})),
1503 )
1504 .await;
1505 assert_eq!(empty.status, StatusCode::OK);
1506 assert_eq!(empty.body, before);
1507
1508 // A whole package off and back on again, each in one call.
1509 let sold_back = bsend(
1510 &app,
1511 "PATCH",
1512 &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
1513 Some(&builder),
1514 Some(json!({ "disable_packages": ["academics"] })),
1515 )
1516 .await;
1517 assert_eq!(sold_back.status, StatusCode::OK, "{:?}", sold_back.body);
1518 assert_eq!(
1519 enabled(&sold_back.body),
1520 [
1521 "appointments",
1522 "boards",
1523 "chatbot",
1524 "events",
1525 "meals",
1526 "messages",
1527 "notes",
1528 "payments",
1529 "pomodoro",
1530 "questions",
1531 "work"
1532 ]
1533 );
1534 assert_eq!(
1535 school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body,
1536 sold_back.body
1537 );
1538
1539 let resold = bsend(
1540 &app,
1541 "PATCH",
1542 &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
1543 Some(&builder),
1544 Some(json!({ "enable_packages": ["academics"] })),
1545 )
1546 .await;
1547 assert_eq!(resold.status, StatusCode::OK, "{:?}", resold.body);
1548 assert_eq!(resold.body, before, "the shelf came back exactly as it was");
1549}
1550
1551/// The entitlement surface is the vendor's alone, and what it writes is read on
1552/// the school's very next request — no re-login, same cookie.
1553#[tokio::test]
1554async fn only_a_builder_sells_modules_and_the_school_feels_it_at_once() {
1555 let (app, _db, _tenants) = deployment().await;
1556 let builder = builder_login(&app).await;
1557 let student = login(&app, "ali").await;
1558
1559 for (method, uri) in [
1560 ("GET", format!("/schools/{DEMO_SCHOOL_ID}/modules")),
1561 ("POST", format!("/schools/{DEMO_SCHOOL_ID}/modules/notes")),
1562 ("DELETE", format!("/schools/{DEMO_SCHOOL_ID}/modules/notes")),
1563 ("PATCH", format!("/schools/{DEMO_SCHOOL_ID}/modules")),
1564 ] {
1565 let body = (method == "PATCH").then(|| json!({}));
1566 let res = bsend(&app, method, &uri, Some(&student), body).await;
1567 assert_eq!(
1568 res.status,
1569 StatusCode::UNAUTHORIZED,
1570 "a school cookie reached {method} {uri}"
1571 );
1572 }
1573
1574 let menus = bsend(&app, "GET", "/meals/menus", Some(&student), None).await;
1575 assert_eq!(menus.status, StatusCode::OK, "{:?}", menus.body);
1576
1577 let off = bsend(
1578 &app,
1579 "DELETE",
1580 &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"),
1581 Some(&builder),
1582 None,
1583 )
1584 .await;
1585 assert_eq!(off.status, StatusCode::OK, "{:?}", off.body);
1586
1587 let refused = bsend(&app, "GET", "/meals/menus", Some(&student), None).await;
1588 assert_eq!(refused.status, StatusCode::FORBIDDEN, "{:?}", refused.body);
1589 assert_eq!(refused.body["module"], "meals");
1590
1591 let on = bsend(
1592 &app,
1593 "POST",
1594 &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"),
1595 Some(&builder),
1596 None,
1597 )
1598 .await;
1599 assert_eq!(on.status, StatusCode::OK, "{:?}", on.body);
1600 assert_eq!(
1601 bsend(&app, "GET", "/meals/menus", Some(&student), None)
1602 .await
1603 .status,
1604 StatusCode::OK,
1605 "the same cookie works again the moment the module is back"
1606 );
1607}
1608
1609/// A school is sold its shelf as it is created, and an unsatisfiable order
1610/// creates nothing at all.
1611#[tokio::test]
1612async fn a_school_is_created_with_the_modules_it_bought() {
1613 let (app, _db, _tenants) = deployment().await;
1614 let builder = builder_login(&app).await;
1615
1616 let created = bsend(
1617 &app,
1618 "POST",
1619 "/schools",
1620 Some(&builder),
1621 Some(json!({
1622 "slug": "notes-only",
1623 "name": "notes-only school",
1624 "admin_username": "admin",
1625 "admin_password": "secret1",
1626 "modules": ["notes"],
1627 })),
1628 )
1629 .await;
1630 assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body);
1631 assert_eq!(created.body["modules"], json!(["notes"]));
1632 let read = bsend(&app, "GET", "/schools/notes-only", Some(&builder), None).await;
1633 assert_eq!(read.body["modules"], json!(["notes"]));
1634 assert_eq!(
1635 enabled(&school_modules(&app, &builder, "notes-only").await.body),
1636 ["notes"]
1637 );
1638
1639 for (body, status) in [
1640 (json!({ "modules": ["kantin"] }), StatusCode::BAD_REQUEST),
1641 (json!({ "modules": ["exams"] }), StatusCode::CONFLICT),
1642 ] {
1643 let mut request = json!({
1644 "slug": "doomed",
1645 "name": "doomed school",
1646 "admin_username": "admin",
1647 "admin_password": "secret1",
1648 });
1649 request["modules"] = body["modules"].clone();
1650 let res = bsend(&app, "POST", "/schools", Some(&builder), Some(request)).await;
1651 assert_eq!(res.status, status, "{:?}", res.body);
1652 assert_eq!(
1653 bsend(&app, "GET", "/schools/doomed", Some(&builder), None)
1654 .await
1655 .status,
1656 StatusCode::NOT_FOUND,
1657 "a refused order must not leave a school behind"
1658 );
1659 }
1660
1661 // Omitted still means everything.
1662 let full = create_school(&app, &builder, "full-shelf", "secret1").await;
1663 assert_eq!(full.status, StatusCode::CREATED, "{:?}", full.body);
1664 assert_eq!(full.body["modules"].as_array().expect("modules").len(), 21);
1665}
1666
1667/// The catalog is the client's map of the product, and `/modules` is where a
1668/// school user reads its own square of it.
1669#[tokio::test]
1670async fn the_catalog_is_public_and_a_school_user_reads_its_own_set() {
1671 let (app, _db, _tenants) = deployment().await;
1672
1673 let catalog = bsend(&app, "GET", "/modules/catalog", None, None).await;
1674 assert_eq!(catalog.status, StatusCode::OK, "{:?}", catalog.body);
1675 let modules = catalog.body["modules"].as_array().expect("modules").clone();
1676 assert_eq!(modules.len(), 21);
1677 let names: Vec<&str> = modules
1678 .iter()
1679 .map(|m| m["module"].as_str().expect("module name"))
1680 .collect();
1681 assert!(names.windows(2).all(|w| w[0] < w[1]), "sorted: {names:?}");
1682 let packages = catalog.body["packages"].as_array().expect("packages");
1683 assert_eq!(packages.len(), 4);
1684 for module in &modules {
1685 assert!(
1686 packages.iter().any(|p| p["package"] == module["package"]),
1687 "{} is sold in a package nobody lists",
1688 module["module"]
1689 );
1690 for needed in module["requires"].as_array().expect("requires") {
1691 assert!(
1692 names.contains(&needed.as_str().expect("requirement name")),
1693 "{module:?} requires something the catalog does not sell"
1694 );
1695 }
1696 }
1697
1698 let student = login(&app, "ali").await;
1699 let mine = bsend(&app, "GET", "/modules", Some(&student), None).await;
1700 assert_eq!(mine.status, StatusCode::OK, "{:?}", mine.body);
1701 assert_eq!(enabled(&mine.body), names);
1702 assert_eq!(
1703 bsend(&app, "GET", "/modules", None, None).await.status,
1704 StatusCode::UNAUTHORIZED
1705 );
1706}
1707
1708// ===================== REFUTE probes (verifier, 2026-09-06) =====================
1709// Appended by an adversarial verification pass. These probe the module
1710// entitlement package's stated invariants; they touch no src/.
1711
1712/// P1: a school that bought nothing can still reach every ungated surface.
1713#[tokio::test]
1714async fn probe_a_module_less_school_still_works() {
1715 let (app, _db, _tenants) = deployment().await;
1716 let builder = builder_login(&app).await;
1717 let created = bsend(
1718 &app,
1719 "POST",
1720 "/schools",
1721 Some(&builder),
1722 Some(json!({
1723 "slug": "bare",
1724 "name": "bare school",
1725 "admin_username": "admin",
1726 "admin_password": "secret1",
1727 "modules": [],
1728 })),
1729 )
1730 .await;
1731 assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body);
1732 assert_eq!(created.body["modules"], json!([]));
1733
1734 let login = school_login(&app, "bare", "admin", "secret1").await;
1735 assert_eq!(login.status, StatusCode::OK, "login: {:?}", login.body);
1736 let cookie = login.cookie.expect("session cookie");
1737
1738 for path in [
1739 "/auth/me",
1740 "/limits",
1741 "/settings",
1742 "/terms",
1743 "/users/me/profile",
1744 "/modules",
1745 "/modules/catalog",
1746 ] {
1747 let res = bsend(&app, "GET", path, Some(&cookie), None).await;
1748 assert_eq!(
1749 res.status,
1750 StatusCode::OK,
1751 "GET {path} on a module-less school -> {} {:?}",
1752 res.status,
1753 res.body
1754 );
1755 }
1756 let mine = bsend(&app, "GET", "/modules", Some(&cookie), None).await;
1757 assert_eq!(mine.body["enabled"], json!([]));
1758
1759 let prefs = bsend(
1760 &app,
1761 "PATCH",
1762 "/users/me/preferences",
1763 Some(&cookie),
1764 Some(json!({ "theme": "dark" })),
1765 )
1766 .await;
1767 assert_eq!(
1768 prefs.status,
1769 StatusCode::OK,
1770 "PATCH /users/me/preferences -> {:?}",
1771 prefs.body
1772 );
1773}
1774
1775/// P1b: the same, reached by narrowing a full school with `disable_packages`.
1776#[tokio::test]
1777async fn probe_narrowing_every_package_away_leaves_the_school_usable() {
1778 let (app, db, _tenants) = deployment().await;
1779 let builder = builder_login(&app).await;
1780 let cookie = login_as(&app, &db, "boss", "admin").await;
1781
1782 let res = bsend(
1783 &app,
1784 "PATCH",
1785 &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
1786 Some(&builder),
1787 Some(json!({
1788 "disable_packages": ["academics", "communication", "operations", "ai"],
1789 })),
1790 )
1791 .await;
1792 assert_eq!(res.status, StatusCode::OK, "{:?}", res.body);
1793 assert_eq!(res.body["enabled"], json!([]), "{:?}", res.body);
1794
1795 for path in [
1796 "/auth/me",
1797 "/limits",
1798 "/settings",
1799 "/terms",
1800 "/users/me/profile",
1801 "/modules",
1802 ] {
1803 let r = bsend(&app, "GET", path, Some(&cookie), None).await;
1804 assert_eq!(
1805 r.status,
1806 StatusCode::OK,
1807 "GET {path} -> {} {:?}",
1808 r.status,
1809 r.body
1810 );
1811 }
1812 assert_eq!(
1813 bsend(&app, "GET", "/modules", Some(&cookie), None)
1814 .await
1815 .body["enabled"],
1816 json!([])
1817 );
1818}
1819
1820/// P2: a fully-enabled school must never meet `module disabled` anywhere.
1821#[tokio::test]
1822async fn probe_no_route_refuses_a_module_a_school_has() {
1823 let (app, db, _tenants) = deployment().await;
1824 let cookie = login_as(&app, &db, "boss", "admin").await;
1825
1826 let spec = bsend(&app, "GET", "/api-docs/openapi.json", None, None).await;
1827 assert_eq!(spec.status, StatusCode::OK, "openapi spec");
1828 let paths = spec.body["paths"].as_object().expect("paths object");
1829 assert!(paths.len() > 50, "only {} paths in the spec", paths.len());
1830
1831 let mut refused = Vec::new();
1832 let mut swept = 0usize;
1833 for path in paths.keys() {
1834 if !paths[path].get("get").is_some() {
1835 continue;
1836 }
1837 let concrete = path
1838 .split('/')
1839 .map(|seg| {
1840 if seg.starts_with('{') && seg.ends_with('}') {
1841 "x"
1842 } else {
1843 seg
1844 }
1845 })
1846 .collect::<Vec<_>>()
1847 .join("/");
1848 let res = bsend(&app, "GET", &concrete, Some(&cookie), None).await;
1849 swept += 1;
1850 if res.body.get("error").and_then(|e| e.as_str()) == Some("module disabled") {
1851 refused.push(format!("{concrete} -> {} {:?}", res.status, res.body));
1852 }
1853 }
1854 assert!(swept > 50, "only {swept} GET routes swept");
1855 assert!(
1856 refused.is_empty(),
1857 "{} of {swept} GET routes answered `module disabled` on a fully enabled school: {:#?}",
1858 refused.len(),
1859 refused
1860 );
1861}
1862
1863/// P6: the gate must not answer before authentication — no cookie means no
1864/// school, so nothing about a school's shelf may leak.
1865#[tokio::test]
1866async fn probe_gate_ordering_versus_auth() {
1867 let (app, _db, _tenants) = deployment().await;
1868 let builder = builder_login(&app).await;
1869 let off = bsend(
1870 &app,
1871 "DELETE",
1872 &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"),
1873 Some(&builder),
1874 None,
1875 )
1876 .await;
1877 assert_eq!(off.status, StatusCode::OK, "{:?}", off.body);
1878
1879 let anon = bsend(&app, "GET", "/meals/menus", None, None).await;
1880 assert_eq!(
1881 anon.status,
1882 StatusCode::UNAUTHORIZED,
1883 "cookie-less request to a disabled nest -> {} {:?}",
1884 anon.status,
1885 anon.body
1886 );
1887 assert_ne!(
1888 anon.body.get("error").and_then(|e| e.as_str()),
1889 Some("module disabled"),
1890 "a cookie-less caller learned a school's entitlements: {:?}",
1891 anon.body
1892 );
1893
1894 let as_builder = bsend(&app, "GET", "/meals/menus", Some(&builder), None).await;
1895 assert_eq!(
1896 as_builder.status,
1897 StatusCode::UNAUTHORIZED,
1898 "builder cookie inside a school nest -> {} {:?}",
1899 as_builder.status,
1900 as_builder.body
1901 );
1902}
1903
1904/// P7: one school's disabled module says nothing about another's.
1905#[tokio::test]
1906async fn probe_disabling_in_one_school_leaves_the_other_alone() {
1907 let (app, _db, tenants) = deployment().await;
1908 let builder = builder_login(&app).await;
1909 for slug in ["alpha", "beta"] {
1910 let res = create_school(&app, &builder, slug, "secret1").await;
1911 assert_eq!(res.status, StatusCode::CREATED, "{slug}: {:?}", res.body);
1912 }
1913 async fn named(tenants: &Tenants, label: &str) -> (hezarfen_backend::tenant::SchoolId, hezarfen_backend::database::Database) {
1914 let id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = $1")
1915 .bind(format!("{label} school"))
1916 .fetch_one(tenants.control())
1917 .await
1918 .unwrap_or_else(|err| panic!("{label}: {err}"));
1919 let id = hezarfen_backend::tenant::SchoolId::from_uuid(id);
1920 let db = tenants.get(&id).await.unwrap();
1921 (id, db)
1922 }
1923 let (alpha_id, alpha_db) = named(&tenants, "alpha").await;
1924 let (beta_id, beta_db) = named(&tenants, "beta").await;
1925 let alpha_wire = alpha_id.as_str();
1926 let beta_wire = beta_id.as_str();
1927 let alpha = login_as_school(&app, &alpha_db, &alpha_wire, "ada", "manager").await;
1928 let beta = login_as_school(&app, &beta_db, &beta_wire, "ada", "manager").await;
1929
1930 let off = bsend(
1931 &app,
1932 "DELETE",
1933 "/schools/alpha/modules/meals",
1934 Some(&builder),
1935 None,
1936 )
1937 .await;
1938 assert_eq!(off.status, StatusCode::OK, "{:?}", off.body);
1939
1940 let a = bsend(&app, "GET", "/meals/menus", Some(&alpha), None).await;
1941 assert_eq!(a.status, StatusCode::FORBIDDEN, "{:?}", a.body);
1942 assert_eq!(a.body["module"], "meals");
1943 let b = bsend(&app, "GET", "/meals/menus", Some(&beta), None).await;
1944 assert_eq!(
1945 b.status,
1946 StatusCode::OK,
1947 "school B lost meals with school A: {} {:?}",
1948 b.status,
1949 b.body
1950 );
1951}
1952
1953/// P5: a contradictory batch is a refusal that writes nothing — checked on the
1954/// registry row itself, not through the API's own read.
1955#[tokio::test]
1956async fn probe_a_refused_batch_leaves_the_row_byte_identical() {
1957 let (app, _db, tenants) = deployment().await;
1958 let builder = builder_login(&app).await;
1959
1960 async fn raw_row(tenants: &Tenants) -> Vec<String> {
1961 sqlx::query_scalar(
1962 "SELECT sm.module FROM school_module sm
1963 JOIN school s ON s.id = sm.school
1964 WHERE s.id = $1 ORDER BY sm.module",
1965 )
1966 .bind(hezarfen_backend::tenant::SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap().uuid())
1967 .fetch_all(tenants.control())
1968 .await
1969 .expect("raw read")
1970 }
1971
1972 let before = raw_row(&tenants).await;
1973 let res = bsend(
1974 &app,
1975 "PATCH",
1976 &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
1977 Some(&builder),
1978 Some(json!({ "enable": ["exams"], "disable": ["courses"] })),
1979 )
1980 .await;
1981 assert_eq!(
1982 res.status,
1983 StatusCode::CONFLICT,
1984 "enable exams + disable courses -> {} {:?}",
1985 res.status,
1986 res.body
1987 );
1988 let after = raw_row(&tenants).await;
1989 assert_eq!(before, after, "the refused batch moved the stored row");
1990}
1991
1992/// P4 (attempt): count the control database's reads for one gated request by
1993/// counting the SDK's own tracing spans. Prints the figure; asserts only that
1994/// the instrumentation saw *something*, so a zero is reported as UNMEASURED
1995/// rather than as a passing measurement.
1996///
1997/// The subscriber is **global**, not `set_default`'s thread-local one, because
1998/// a thread-local subscriber cannot measure this reliably: `tracing` caches a
1999/// callsite's interest process-wide the first time any thread reaches it, and
2000/// with tests running in parallel that thread is usually a sibling with no
2001/// subscriber — the sqlx callsites are then disabled for the whole process
2002/// before this test ever asks, and the count is 0. Global is safe here because
2003/// this subscriber only counts: it stores nothing, prints nothing, and its
2004/// `enabled` refuses every callsite that is not a sqlx one on *this* test's
2005/// thread, so a sibling test neither pays for it nor lands in the figure.
2006#[tokio::test]
2007async fn probe_registry_reads_per_request() {
2008 use std::sync::Arc;
2009 use std::sync::atomic::{AtomicUsize, Ordering};
2010 use tracing::span;
2011
2012 struct Counter {
2013 thread: std::thread::ThreadId,
2014 count: Arc<AtomicUsize>,
2015 }
2016 impl tracing::Subscriber for Counter {
2017 // Never `always`/`never`: those are cached per callsite, and this
2018 // subscriber's answer depends on which thread is asking.
2019 fn register_callsite(&self, _: &tracing::Metadata<'_>) -> tracing::subscriber::Interest {
2020 tracing::subscriber::Interest::sometimes()
2021 }
2022 fn enabled(&self, meta: &tracing::Metadata<'_>) -> bool {
2023 meta.target().starts_with("sqlx") && std::thread::current().id() == self.thread
2024 }
2025 fn new_span(&self, _: &span::Attributes<'_>) -> span::Id {
2026 self.count.fetch_add(1, Ordering::Relaxed);
2027 span::Id::from_u64(1)
2028 }
2029 fn event(&self, _: &tracing::Event<'_>) {
2030 self.count.fetch_add(1, Ordering::Relaxed);
2031 }
2032 fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
2033 fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
2034 fn enter(&self, _: &span::Id) {}
2035 fn exit(&self, _: &span::Id) {}
2036 }
2037
2038 let count = Arc::new(AtomicUsize::new(0));
2039 tracing::subscriber::set_global_default(Counter {
2040 thread: std::thread::current().id(),
2041 count: count.clone(),
2042 })
2043 .expect("no other test in this binary installs a global subscriber");
2044
2045 let (app, db, _tenants) = deployment().await;
2046 let cookie = login_as(&app, &db, "boss", "admin").await;
2047 count.store(0, Ordering::Relaxed);
2048 let res = bsend(&app, "GET", "/notes", Some(&cookie), None).await;
2049 assert_eq!(res.status, StatusCode::OK, "{:?}", res.body);
2050 let seen = count.load(Ordering::Relaxed);
2051 println!("PROBE sqlx spans/events for GET /notes = {seen}");
2052 assert!(
2053 seen > 0,
2054 "UNMEASURED: sqlx emitted no tracing spans, so per-request \
2055 registry reads cannot be counted this way"
2056 );
2057}
2058
2059/// P8: the foreign route pairs nested under another module's nest carry both
2060/// gates, and a disabled nest still `404`s an unmatched path inside it.
2061#[tokio::test]
2062async fn probe_child_gates_under_courses_and_the_404_inside_a_disabled_nest() {
2063 let (app, db, _tenants) = deployment().await;
2064 let builder = builder_login(&app).await;
2065 let cookie = login_as(&app, &db, "boss", "admin").await;
2066
2067 // Exams off, courses still on: the child pair must refuse as `exams`.
2068 for module in ["marks", "exams"] {
2069 let off = bsend(
2070 &app,
2071 "DELETE",
2072 &format!("/schools/{DEMO_SCHOOL_ID}/modules/{module}"),
2073 Some(&builder),
2074 None,
2075 )
2076 .await;
2077 assert_eq!(off.status, StatusCode::OK, "{module}: {:?}", off.body);
2078 }
2079 let child = bsend(&app, "GET", "/instances/x/exams", Some(&cookie), None).await;
2080 assert_eq!(
2081 child.status,
2082 StatusCode::FORBIDDEN,
2083 "/instances/x/exams with exams off -> {} {:?}",
2084 child.status,
2085 child.body
2086 );
2087 assert_eq!(child.body["module"], "exams", "{:?}", child.body);
2088 // …while the course routes themselves keep answering.
2089 let parent = bsend(&app, "GET", "/courses", Some(&cookie), None).await;
2090 assert_eq!(parent.status, StatusCode::OK, "{:?}", parent.body);
2091 // A sibling child pair whose own module is still on is untouched.
2092 let sibling = bsend(&app, "GET", "/courses/x/subjects", Some(&cookie), None).await;
2093 assert_ne!(
2094 sibling.status,
2095 StatusCode::FORBIDDEN,
2096 "/courses/x/subjects lost its own gate: {:?}",
2097 sibling.body
2098 );
2099
2100 // A disabled nest is a refusal on the routes that exist, not a wall.
2101 let off = bsend(
2102 &app,
2103 "DELETE",
2104 &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"),
2105 Some(&builder),
2106 None,
2107 )
2108 .await;
2109 assert_eq!(off.status, StatusCode::OK, "{:?}", off.body);
2110 let ghost = bsend(&app, "GET", "/meals/no-such-route", Some(&cookie), None).await;
2111 assert_eq!(
2112 ghost.status,
2113 StatusCode::NOT_FOUND,
2114 "an unmatched path inside a disabled nest -> {} {:?}",
2115 ghost.status,
2116 ghost.body
2117 );
2118 let real = bsend(&app, "GET", "/meals/menus", Some(&cookie), None).await;
2119 assert_eq!(real.status, StatusCode::FORBIDDEN, "{:?}", real.body);
2120}