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