forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

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