Production-mode isolation runs by default against a throwaway SurrealDB
Browse files at this commit7d4bd21ec37cede73586369ea18ad473556e37faParent: 2bf64d3- test
- production-mode isolation runs by default against a throwaway SurrealDB
4 changed files +643 -216
- README.md +9 -0
- tests/builder_api.rs +13 -75
- tests/common/mod.rs +171 -0
- tests/integration.rs +450 -141
README.mdmodified+9 -0
| @@ -4694,3 +4694,12 @@ limits over every route, two limiters sharing one budget over one db), e2e | |||
| 4694 | (tempfile file engine, including close + reopen), ai-bridge (real QUIC on | 4694 | (tempfile file engine, including close + reopen), ai-bridge (real QUIC on |
| 4695 | loopback against a fake AI service), ai-protocol (the `hab/2` wire contract, | 4695 | loopback against a fake AI service), ai-protocol (the `hab/2` wire contract, |
| 4696 | driven by a client that shares no code with the backend). | 4696 | driven by a client that shares no code with the backend). |
| 4697 | + | ||
| 4698 | +The cross-school isolation probes run twice: once in memory mode, once against | ||
| 4699 | +a **real** SurrealDB, because production is remote mode and there a school is a | ||
| 4700 | +database inside one namespace rather than its own datastore. So `cargo test` | ||
| 4701 | +starts a throwaway `surreal start … memory` server on a free port, taken from | ||
| 4702 | +`~/.surrealdb/surreal`, and kills it when the last test using it finishes. A | ||
| 4703 | +missing binary is a hard failure, not a skip — install it with | ||
| 4704 | +`curl -sSf https://install.surrealdb.com | sh`, or set `HEZARFEN_SKIP_REMOTE=1` | ||
| 4705 | +to skip the remote half deliberately. | ||
tests/builder_api.rsmodified+13 -75
| @@ -811,8 +811,10 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { | |||
| 811 | /// production statements against a live SurrealDB parser. | 811 | /// production statements against a live SurrealDB parser. |
| 812 | #[tokio::test] | 812 | #[tokio::test] |
| 813 | async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug() { | 813 | async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug() { |
| 814 | - let tenants = Tenants::new_mem().await.expect("control db"); | 814 | + let Some(deployment) = common::remote_deployment(&[]).await else { |
| 815 | - let control = tenants.control(); | 815 | + return; |
| 816 | + }; | ||
| 817 | + let control = deployment.tenants.control(); | ||
| 816 | let mut broken: Vec<String> = Vec::new(); | 818 | let mut broken: Vec<String> = Vec::new(); |
| 817 | 819 | ||
| 818 | for raw in [ | 820 | for raw in [ |
| @@ -1218,86 +1220,22 @@ async fn probe_concurrent_creates_of_one_slug_leave_one_school() { | |||
| 1218 | assert_eq!(opens, 1, "{opens} of the two admin passwords open p6race"); | 1220 | assert_eq!(opens, 1, "{opens} of the two admin passwords open p6race"); |
| 1219 | } | 1221 | } |
| 1220 | 1222 | ||
| 1221 | -/// A `surreal start` child that dies with the test. | ||
| 1222 | -struct Server(std::process::Child); | ||
| 1223 | -impl Drop for Server { | ||
| 1224 | - fn drop(&mut self) { | ||
| 1225 | - let _ = self.0.kill(); | ||
| 1226 | - let _ = self.0.wait(); | ||
| 1227 | - } | ||
| 1228 | -} | ||
| 1229 | - | ||
| 1230 | /// Claim 1/2 driven against a **real remote deployment** — the mode every test | 1223 | /// Claim 1/2 driven against a **real remote deployment** — the mode every test |
| 1231 | /// above skips, and the only one where `DEFINE DATABASE` / `REMOVE DATABASE` | 1224 | /// above skips, and the only one where `DEFINE DATABASE` / `REMOVE DATABASE` |
| 1232 | /// actually run. `ata-koleji` is the slug the OpenAPI schema advertises. | 1225 | /// actually run. `ata-koleji` is the slug the OpenAPI schema advertises. |
| 1233 | #[tokio::test] | 1226 | #[tokio::test] |
| 1234 | async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() { | 1227 | async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() { |
| 1235 | - let bin = std::path::PathBuf::from(std::env::var("HOME").unwrap()).join(".surrealdb/surreal"); | 1228 | + let Some(deployment) = common::remote_deployment(&[]).await else { |
| 1236 | - if !bin.exists() { | ||
| 1237 | - eprintln!("skipped: no surreal binary at {}", bin.display()); | ||
| 1238 | return; | 1229 | return; |
| 1239 | - } | ||
| 1240 | - let port = 18441u16; | ||
| 1241 | - let _server = Server( | ||
| 1242 | - std::process::Command::new(&bin) | ||
| 1243 | - .args([ | ||
| 1244 | - "start", | ||
| 1245 | - "--user", | ||
| 1246 | - "root", | ||
| 1247 | - "--pass", | ||
| 1248 | - "root", | ||
| 1249 | - "--bind", | ||
| 1250 | - &format!("127.0.0.1:{port}"), | ||
| 1251 | - "memory", | ||
| 1252 | - ]) | ||
| 1253 | - .stdout(std::process::Stdio::null()) | ||
| 1254 | - .stderr(std::process::Stdio::null()) | ||
| 1255 | - .spawn() | ||
| 1256 | - .expect("spawn surreal"), | ||
| 1257 | - ); | ||
| 1258 | - for _ in 0..100 { | ||
| 1259 | - if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() { | ||
| 1260 | - break; | ||
| 1261 | - } | ||
| 1262 | - tokio::time::sleep(std::time::Duration::from_millis(100)).await; | ||
| 1263 | - } | ||
| 1264 | - | ||
| 1265 | - let files = tempfile::tempdir().unwrap(); | ||
| 1266 | - let cfg = hezarfen_backend::config::Config { | ||
| 1267 | - host: "127.0.0.1".into(), | ||
| 1268 | - port: 0, | ||
| 1269 | - db_url: format!("ws://127.0.0.1:{port}"), | ||
| 1270 | - db_user: "root".into(), | ||
| 1271 | - db_pass: "root".into(), | ||
| 1272 | - db_ns: "hezarfen".into(), | ||
| 1273 | - db_name: "control".into(), | ||
| 1274 | - files_path: files.path().display().to_string(), | ||
| 1275 | - cookie_secure: false, | ||
| 1276 | - rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), | ||
| 1277 | - chatbot_per_minute: 0, | ||
| 1278 | - builder_username: Some(BUILDER_USER.into()), | ||
| 1279 | - builder_password: Some(BUILDER_PASS.into()), | ||
| 1280 | - ai_quic_addr: None, | ||
| 1281 | - ai_shared_token: None, | ||
| 1282 | - ai_tls_cert: None, | ||
| 1283 | - ai_tls_key: None, | ||
| 1284 | - ai_request_timeout_secs: 30, | ||
| 1285 | }; | 1230 | }; |
| 1286 | - let tenants = hezarfen_backend::database::init(&cfg) | 1231 | + let app = deployment.app; |
| 1287 | - .await | 1232 | + Builder::ensure( |
| 1288 | - .expect("remote deployment"); | 1233 | + Username::try_new(BUILDER_USER).unwrap(), |
| 1289 | - let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { | 1234 | + Password::try_new(BUILDER_PASS).unwrap(), |
| 1290 | - db: tenants.control().clone(), | 1235 | + deployment.tenants.control(), |
| 1291 | - tenants: tenants.clone(), | 1236 | + ) |
| 1292 | - files_path: files.path().to_path_buf(), | 1237 | + .await |
| 1293 | - cookie_secure: false, | 1238 | + .expect("seed the builder"); |
| 1294 | - rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), | ||
| 1295 | - chatbot_limit: Default::default(), | ||
| 1296 | - exam_presence: Default::default(), | ||
| 1297 | - board_hub: Default::default(), | ||
| 1298 | - db_up: Default::default(), | ||
| 1299 | - ai: None, | ||
| 1300 | - }); | ||
| 1301 | 1239 | ||
| 1302 | let builder = builder_login(&app).await; | 1240 | let builder = builder_login(&app).await; |
| 1303 | // A plain slug proves the harness itself works. | 1241 | // A plain slug proves the harness itself works. |
tests/common/mod.rsmodified+171 -0
| @@ -518,3 +518,174 @@ pub async fn enroll(app: &Router, cookie: &str, course: &str, user_id: &str) { | |||
| 518 | .await; | 518 | .await; |
| 519 | assert_eq!(res.status, StatusCode::OK, "enroll {user_id}"); | 519 | assert_eq!(res.status, StatusCode::OK, "enroll {user_id}"); |
| 520 | } | 520 | } |
| 521 | + | ||
| 522 | +// ---- remote (production) mode ------------------------------------------- | ||
| 523 | +// | ||
| 524 | +// `Mode::Mem` gives every school its own embedded datastore, so cross-school | ||
| 525 | +// isolation *cannot* fail there. Production is `Mode::Remote`: one server, one | ||
| 526 | +// namespace, a database per school, isolation resting entirely on each | ||
| 527 | +// connection's `use_db` pin. The isolation probes therefore run in both modes, | ||
| 528 | +// and the remote half needs a real server — this is it. | ||
| 529 | + | ||
| 530 | +/// A throwaway `surreal start … memory` server. Owned by the deployments using | ||
| 531 | +/// it: killed as soon as the last one drops, which is what keeps both runners | ||
| 532 | +/// clean — `cargo test` (one process, many tests, one shared server) and | ||
| 533 | +/// `cargo nextest` (process per test, so the kill has to happen inside the | ||
| 534 | +/// test, not at some exit hook the harness never runs). | ||
| 535 | +pub struct RemoteServer { | ||
| 536 | + child: std::sync::Mutex<std::process::Child>, | ||
| 537 | + pub url: String, | ||
| 538 | +} | ||
| 539 | + | ||
| 540 | +impl Drop for RemoteServer { | ||
| 541 | + fn drop(&mut self) { | ||
| 542 | + let mut child = self.child.lock().expect("server lock"); | ||
| 543 | + let _ = child.kill(); | ||
| 544 | + let _ = child.wait(); | ||
| 545 | + } | ||
| 546 | +} | ||
| 547 | + | ||
| 548 | +/// The live server, if one is still held; otherwise the next call spawns a new | ||
| 549 | +/// one. A `Weak` and not the server itself: a `&'static` could never be | ||
| 550 | +/// dropped, and an un-dropped child is a leaked `surreal` per test process. | ||
| 551 | +static REMOTE: OnceLock<std::sync::Mutex<std::sync::Weak<RemoteServer>>> = OnceLock::new(); | ||
| 552 | + | ||
| 553 | +const SURREAL_BIN: &str = ".surrealdb/surreal"; | ||
| 554 | +const SURREAL_HINT: &str = "install it with `curl -sSf https://install.surrealdb.com | sh`, \ | ||
| 555 | + or set HEZARFEN_SKIP_REMOTE=1 to skip the production-mode isolation tests"; | ||
| 556 | + | ||
| 557 | +/// The shared server, or `None` when `HEZARFEN_SKIP_REMOTE=1` says to skip. | ||
| 558 | +/// A missing binary is a **panic**: remote-mode isolation is the mode | ||
| 559 | +/// production runs in, so it must never quietly not-run. | ||
| 560 | +pub fn remote_server() -> Option<std::sync::Arc<RemoteServer>> { | ||
| 561 | + if std::env::var("HEZARFEN_SKIP_REMOTE").as_deref() == Ok("1") { | ||
| 562 | + eprintln!("HEZARFEN_SKIP_REMOTE=1 — remote-mode isolation NOT exercised"); | ||
| 563 | + return None; | ||
| 564 | + } | ||
| 565 | + let mut slot = REMOTE | ||
| 566 | + .get_or_init(Default::default) | ||
| 567 | + .lock() | ||
| 568 | + .expect("remote server slot"); | ||
| 569 | + if let Some(server) = slot.upgrade() { | ||
| 570 | + return Some(server); | ||
| 571 | + } | ||
| 572 | + let bin = PathBuf::from(std::env::var("HOME").expect("HOME")).join(SURREAL_BIN); | ||
| 573 | + assert!( | ||
| 574 | + bin.exists(), | ||
| 575 | + "no surreal binary at {} — {SURREAL_HINT}", | ||
| 576 | + bin.display() | ||
| 577 | + ); | ||
| 578 | + // Pick the port by binding and releasing it: two test *processes* (nextest) | ||
| 579 | + // each want a server of their own, and a fixed port would collide. | ||
| 580 | + let port = std::net::TcpListener::bind("127.0.0.1:0") | ||
| 581 | + .expect("a free port") | ||
| 582 | + .local_addr() | ||
| 583 | + .expect("the bound address") | ||
| 584 | + .port(); | ||
| 585 | + let child = std::process::Command::new(&bin) | ||
| 586 | + .args([ | ||
| 587 | + "start", | ||
| 588 | + "--user", | ||
| 589 | + "root", | ||
| 590 | + "--pass", | ||
| 591 | + "root", | ||
| 592 | + "--bind", | ||
| 593 | + &format!("127.0.0.1:{port}"), | ||
| 594 | + "memory", | ||
| 595 | + ]) | ||
| 596 | + .stdout(std::process::Stdio::null()) | ||
| 597 | + .stderr(std::process::Stdio::null()) | ||
| 598 | + .spawn() | ||
| 599 | + .unwrap_or_else(|err| panic!("spawn {}: {err}", bin.display())); | ||
| 600 | + let server = std::sync::Arc::new(RemoteServer { | ||
| 601 | + child: std::sync::Mutex::new(child), | ||
| 602 | + url: format!("ws://127.0.0.1:{port}"), | ||
| 603 | + }); | ||
| 604 | + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); | ||
| 605 | + while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() { | ||
| 606 | + assert!( | ||
| 607 | + std::time::Instant::now() < deadline, | ||
| 608 | + "surreal never listened on 127.0.0.1:{port}" | ||
| 609 | + ); | ||
| 610 | + std::thread::sleep(std::time::Duration::from_millis(20)); | ||
| 611 | + } | ||
| 612 | + *slot = std::sync::Arc::downgrade(&server); | ||
| 613 | + Some(server) | ||
| 614 | +} | ||
| 615 | + | ||
| 616 | +/// A deployment on the shared server: its own namespace, its own blob | ||
| 617 | +/// directory, and the server handle that must outlive both. | ||
| 618 | +pub struct RemoteDeployment { | ||
| 619 | + pub app: Router, | ||
| 620 | + pub tenants: Tenants, | ||
| 621 | + /// The scratch namespace this deployment owns, so a test can name it. | ||
| 622 | + pub ns: String, | ||
| 623 | + /// `FILES_PATH` — one per deployment, never the shared [`files_dir`], so a | ||
| 624 | + /// remote run's uploads cannot be counted by a memory-mode probe. | ||
| 625 | + pub files: PathBuf, | ||
| 626 | + _files: TempDir, | ||
| 627 | + _server: std::sync::Arc<RemoteServer>, | ||
| 628 | +} | ||
| 629 | + | ||
| 630 | +/// The remote twin of [`app_and_tenants`]: a real control database in a | ||
| 631 | +/// namespace of its own, the named schools created in it, and the same router | ||
| 632 | +/// over the same `AppState`. `None` when the remote lane is skipped. | ||
| 633 | +pub async fn remote_deployment(schools: &[(&str, &str)]) -> Option<RemoteDeployment> { | ||
| 634 | + let server = remote_server()?; | ||
| 635 | + let files = tempfile::tempdir().expect("files tempdir"); | ||
| 636 | + // Unique per call: every test in a process shares one server, and a | ||
| 637 | + // namespace collision would put two deployments on one control database. | ||
| 638 | + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); | ||
| 639 | + let ns = format!( | ||
| 640 | + "t{}x{}", | ||
| 641 | + std::process::id(), | ||
| 642 | + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) | ||
| 643 | + ); | ||
| 644 | + let cfg = hezarfen_backend::config::Config { | ||
| 645 | + host: "127.0.0.1".into(), | ||
| 646 | + port: 0, | ||
| 647 | + db_url: server.url.clone(), | ||
| 648 | + db_user: "root".into(), | ||
| 649 | + db_pass: "root".into(), | ||
| 650 | + db_ns: ns.clone(), | ||
| 651 | + db_name: "control".into(), | ||
| 652 | + files_path: files.path().display().to_string(), | ||
| 653 | + cookie_secure: false, | ||
| 654 | + rate_limit: RateLimitConfig::unlimited(), | ||
| 655 | + chatbot_per_minute: 0, | ||
| 656 | + builder_username: None, | ||
| 657 | + builder_password: None, | ||
| 658 | + ai_quic_addr: None, | ||
| 659 | + ai_shared_token: None, | ||
| 660 | + ai_tls_cert: None, | ||
| 661 | + ai_tls_key: None, | ||
| 662 | + ai_request_timeout_secs: 30, | ||
| 663 | + }; | ||
| 664 | + let tenants = database::init(&cfg).await.expect("remote control database"); | ||
| 665 | + for (slug, name) in schools { | ||
| 666 | + tenants | ||
| 667 | + .create(&Slug::try_new(slug).expect("a school slug"), name) | ||
| 668 | + .await | ||
| 669 | + .unwrap_or_else(|err| panic!("create school {slug}: {err}")); | ||
| 670 | + } | ||
| 671 | + let app = build_router(AppState { | ||
| 672 | + db: tenants.control().clone(), | ||
| 673 | + tenants: tenants.clone(), | ||
| 674 | + files_path: files.path().to_path_buf(), | ||
| 675 | + cookie_secure: false, | ||
| 676 | + rate_limit: RateLimitConfig::unlimited(), | ||
| 677 | + chatbot_limit: Default::default(), | ||
| 678 | + exam_presence: Default::default(), | ||
| 679 | + board_hub: Default::default(), | ||
| 680 | + db_up: Default::default(), | ||
| 681 | + ai: None, | ||
| 682 | + }); | ||
| 683 | + Some(RemoteDeployment { | ||
| 684 | + app, | ||
| 685 | + tenants, | ||
| 686 | + ns, | ||
| 687 | + files: files.path().to_path_buf(), | ||
| 688 | + _files: files, | ||
| 689 | + _server: server, | ||
| 690 | + }) | ||
| 691 | +} | ||
tests/integration.rsmodified+450 -141
| @@ -27380,6 +27380,19 @@ async fn two_schools() -> ( | |||
| 27380 | (app, db_a, db_b, tenants) | 27380 | (app, db_a, db_b, tenants) |
| 27381 | } | 27381 | } |
| 27382 | 27382 | ||
| 27383 | +/// The same two schools for a remote deployment: [`common::remote_deployment`] | ||
| 27384 | +/// creates them itself, since there is no `init_mem_tenants` to seed a demo. | ||
| 27385 | +const TWO_SCHOOLS: &[(&str, &str)] = &[(DEMO_SLUG, "Demo School"), ("beta", "Beta Koleji")]; | ||
| 27386 | + | ||
| 27387 | +/// One school's handle out of the registry — the one lookup that works in both | ||
| 27388 | +/// modes, where `two_schools()`'s return values are memory-mode only. | ||
| 27389 | +async fn school_db(tenants: &Tenants, slug: &str) -> hezarfen_backend::database::Database { | ||
| 27390 | + tenants | ||
| 27391 | + .get(&Slug::try_new(slug).expect("a school slug")) | ||
| 27392 | + .await | ||
| 27393 | + .unwrap_or_else(|err| panic!("the {slug} handle: {err}")) | ||
| 27394 | +} | ||
| 27395 | + | ||
| 27383 | /// Every list surface that takes no path parameter — the sweep target. | 27396 | /// Every list surface that takes no path parameter — the sweep target. |
| 27384 | const LIST_ROUTES: [&str; 19] = [ | 27397 | const LIST_ROUTES: [&str; 19] = [ |
| 27385 | "/users", | 27398 | "/users", |
| @@ -27505,21 +27518,37 @@ async fn seed_school_b(app: &axum::Router, cookie: &str) -> serde_json::Value { | |||
| 27505 | /// own rows only — the totals do not move when B fills up. | 27518 | /// own rows only — the totals do not move when B fills up. |
| 27506 | #[tokio::test] | 27519 | #[tokio::test] |
| 27507 | async fn probe_cross_school_lists_show_only_own_rows() { | 27520 | async fn probe_cross_school_lists_show_only_own_rows() { |
| 27508 | - let (app, db_a, db_b, _tenants) = two_schools().await; | 27521 | + let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 27509 | - let a = common::login_as_school(&app, &db_a, DEMO_SLUG, "ada", "admin").await; | 27522 | + probe_cross_school_lists_show_only_own_rows_on(&app, &tenants).await; |
| 27510 | - let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | 27523 | +} |
| 27524 | + | ||
| 27525 | +/// [`probe_cross_school_lists_show_only_own_rows`] on a **real remote deployment** — production's `Mode::Remote`, | ||
| 27526 | +/// where isolation rests on each connection's `use_db` pin. | ||
| 27527 | +#[tokio::test] | ||
| 27528 | +async fn remote_probe_cross_school_lists_show_only_own_rows() { | ||
| 27529 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 27530 | + return; | ||
| 27531 | + }; | ||
| 27532 | + probe_cross_school_lists_show_only_own_rows_on(&d.app, &d.tenants).await; | ||
| 27533 | +} | ||
| 27534 | + | ||
| 27535 | +async fn probe_cross_school_lists_show_only_own_rows_on(app: &axum::Router, tenants: &Tenants) { | ||
| 27536 | + let db_a = school_db(tenants, DEMO_SLUG).await; | ||
| 27537 | + let db_b = school_db(tenants, "beta").await; | ||
| 27538 | + let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await; | ||
| 27539 | + let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; | ||
| 27511 | 27540 | ||
| 27512 | let mut before = Vec::new(); | 27541 | let mut before = Vec::new(); |
| 27513 | for route in LIST_ROUTES { | 27542 | for route in LIST_ROUTES { |
| 27514 | - let res = send(&app, "GET", route, Some(&a), None).await; | 27543 | + let res = send(app, "GET", route, Some(&a), None).await; |
| 27515 | assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); | 27544 | assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); |
| 27516 | before.push(common::total(&res.body)); | 27545 | before.push(common::total(&res.body)); |
| 27517 | } | 27546 | } |
| 27518 | 27547 | ||
| 27519 | - let ids = seed_school_b(&app, &b).await; | 27548 | + let ids = seed_school_b(app, &b).await; |
| 27520 | 27549 | ||
| 27521 | for (i, route) in LIST_ROUTES.iter().enumerate() { | 27550 | for (i, route) in LIST_ROUTES.iter().enumerate() { |
| 27522 | - let res = send(&app, "GET", route, Some(&a), None).await; | 27551 | + let res = send(app, "GET", route, Some(&a), None).await; |
| 27523 | assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); | 27552 | assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); |
| 27524 | assert_eq!( | 27553 | assert_eq!( |
| 27525 | common::total(&res.body), | 27554 | common::total(&res.body), |
| @@ -27540,7 +27569,7 @@ async fn probe_cross_school_lists_show_only_own_rows() { | |||
| 27540 | } | 27569 | } |
| 27541 | } | 27570 | } |
| 27542 | // and B still sees its own. | 27571 | // and B still sees its own. |
| 27543 | - let res = send(&app, "GET", "/notes", Some(&b), None).await; | 27572 | + let res = send(app, "GET", "/notes", Some(&b), None).await; |
| 27544 | assert_eq!(common::total(&res.body), 1, "{}", res.body); | 27573 | assert_eq!(common::total(&res.body), 1, "{}", res.body); |
| 27545 | assert!(ids["note"].is_string()); | 27574 | assert!(ids["note"].is_string()); |
| 27546 | } | 27575 | } |
| @@ -27549,10 +27578,29 @@ async fn probe_cross_school_lists_show_only_own_rows() { | |||
| 27549 | /// every verb — never a 200, never a 500. | 27578 | /// every verb — never a 200, never a 500. |
| 27550 | #[tokio::test] | 27579 | #[tokio::test] |
| 27551 | async fn probe_cross_school_ids_are_not_found_under_the_other_cookie() { | 27580 | async fn probe_cross_school_ids_are_not_found_under_the_other_cookie() { |
| 27552 | - let (app, db_a, db_b, _t) = two_schools().await; | 27581 | + let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 27553 | - let a = common::login_as_school(&app, &db_a, DEMO_SLUG, "ada", "admin").await; | 27582 | + probe_cross_school_ids_are_not_found_under_the_other_cookie_on(&app, &tenants).await; |
| 27554 | - let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | 27583 | +} |
| 27555 | - let ids = seed_school_b(&app, &b).await; | 27584 | + |
| 27585 | +/// [`probe_cross_school_ids_are_not_found_under_the_other_cookie`] on a **real remote deployment** — production's `Mode::Remote`, | ||
| 27586 | +/// where isolation rests on each connection's `use_db` pin. | ||
| 27587 | +#[tokio::test] | ||
| 27588 | +async fn remote_probe_cross_school_ids_are_not_found_under_the_other_cookie() { | ||
| 27589 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 27590 | + return; | ||
| 27591 | + }; | ||
| 27592 | + probe_cross_school_ids_are_not_found_under_the_other_cookie_on(&d.app, &d.tenants).await; | ||
| 27593 | +} | ||
| 27594 | + | ||
| 27595 | +async fn probe_cross_school_ids_are_not_found_under_the_other_cookie_on( | ||
| 27596 | + app: &axum::Router, | ||
| 27597 | + tenants: &Tenants, | ||
| 27598 | +) { | ||
| 27599 | + let db_a = school_db(tenants, DEMO_SLUG).await; | ||
| 27600 | + let db_b = school_db(tenants, "beta").await; | ||
| 27601 | + let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await; | ||
| 27602 | + let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; | ||
| 27603 | + let ids = seed_school_b(app, &b).await; | ||
| 27556 | let s = |k: &str| ids[k].as_str().unwrap().to_string(); | 27604 | let s = |k: &str| ids[k].as_str().unwrap().to_string(); |
| 27557 | 27605 | ||
| 27558 | let targets: Vec<(String, serde_json::Value)> = vec![ | 27606 | let targets: Vec<(String, serde_json::Value)> = vec![ |
| @@ -27582,7 +27630,7 @@ async fn probe_cross_school_ids_are_not_found_under_the_other_cookie() { | |||
| 27582 | ("PATCH", Some(patch.clone())), | 27630 | ("PATCH", Some(patch.clone())), |
| 27583 | ("DELETE", None), | 27631 | ("DELETE", None), |
| 27584 | ] { | 27632 | ] { |
| 27585 | - let res = send(&app, method, &uri, Some(&a), body).await; | 27633 | + let res = send(app, method, &uri, Some(&a), body).await; |
| 27586 | assert_ne!( | 27634 | assert_ne!( |
| 27587 | res.status, | 27635 | res.status, |
| 27588 | StatusCode::OK, | 27636 | StatusCode::OK, |
| @@ -27606,7 +27654,7 @@ async fn probe_cross_school_ids_are_not_found_under_the_other_cookie() { | |||
| 27606 | // The one list surface that takes its scope from a query parameter: B's | 27654 | // The one list surface that takes its scope from a query parameter: B's |
| 27607 | // course id under A's cookie must not open B's notes. | 27655 | // course id under A's cookie must not open B's notes. |
| 27608 | let res = send( | 27656 | let res = send( |
| 27609 | - &app, | 27657 | + app, |
| 27610 | "GET", | 27658 | "GET", |
| 27611 | &format!("/course-notes?course={}", s("course")), | 27659 | &format!("/course-notes?course={}", s("course")), |
| 27612 | Some(&a), | 27660 | Some(&a), |
| @@ -27627,7 +27675,7 @@ async fn probe_cross_school_ids_are_not_found_under_the_other_cookie() { | |||
| 27627 | (format!("/courses/{}", s("course")), ()), | 27675 | (format!("/courses/{}", s("course")), ()), |
| 27628 | (format!("/boards/{}", s("board")), ()), | 27676 | (format!("/boards/{}", s("board")), ()), |
| 27629 | ] { | 27677 | ] { |
| 27630 | - let res = send(&app, "GET", &uri, Some(&b), None).await; | 27678 | + let res = send(app, "GET", &uri, Some(&b), None).await; |
| 27631 | assert_eq!( | 27679 | assert_eq!( |
| 27632 | res.status, | 27680 | res.status, |
| 27633 | StatusCode::OK, | 27681 | StatusCode::OK, |
| @@ -27641,23 +27689,39 @@ async fn probe_cross_school_ids_are_not_found_under_the_other_cookie() { | |||
| 27641 | /// cookie must be refused, never silently linked. | 27689 | /// cookie must be refused, never silently linked. |
| 27642 | #[tokio::test] | 27690 | #[tokio::test] |
| 27643 | async fn probe_cross_school_ids_in_bodies_are_refused() { | 27691 | async fn probe_cross_school_ids_in_bodies_are_refused() { |
| 27644 | - let (app, db_a, db_b, _t) = two_schools().await; | 27692 | + let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 27645 | - let a_admin = common::login_as_school(&app, &db_a, DEMO_SLUG, "ada", "admin").await; | 27693 | + probe_cross_school_ids_in_bodies_are_refused_on(&app, &tenants).await; |
| 27646 | - let a_student = common::login_as_school(&app, &db_a, DEMO_SLUG, "ali", "student").await; | 27694 | +} |
| 27647 | - let a_parent = common::login_as_school(&app, &db_a, DEMO_SLUG, "veli", "parent").await; | 27695 | + |
| 27648 | - let b_admin = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | 27696 | +/// [`probe_cross_school_ids_in_bodies_are_refused`] on a **real remote deployment** — production's `Mode::Remote`, |
| 27649 | - common::login_as_school(&app, &db_b, "beta", "bstudent", "student").await; | 27697 | +/// where isolation rests on each connection's `use_db` pin. |
| 27698 | +#[tokio::test] | ||
| 27699 | +async fn remote_probe_cross_school_ids_in_bodies_are_refused() { | ||
| 27700 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 27701 | + return; | ||
| 27702 | + }; | ||
| 27703 | + probe_cross_school_ids_in_bodies_are_refused_on(&d.app, &d.tenants).await; | ||
| 27704 | +} | ||
| 27705 | + | ||
| 27706 | +async fn probe_cross_school_ids_in_bodies_are_refused_on(app: &axum::Router, tenants: &Tenants) { | ||
| 27707 | + let db_a = school_db(tenants, DEMO_SLUG).await; | ||
| 27708 | + let db_b = school_db(tenants, "beta").await; | ||
| 27709 | + let a_admin = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await; | ||
| 27710 | + let a_student = common::login_as_school(app, &db_a, DEMO_SLUG, "ali", "student").await; | ||
| 27711 | + let a_parent = common::login_as_school(app, &db_a, DEMO_SLUG, "veli", "parent").await; | ||
| 27712 | + let b_admin = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; | ||
| 27713 | + common::login_as_school(app, &db_b, "beta", "bstudent", "student").await; | ||
| 27650 | 27714 | ||
| 27651 | let b_user = { | 27715 | let b_user = { |
| 27652 | - let res = send(&app, "GET", "/users", Some(&b_admin), None).await; | 27716 | + let res = send(app, "GET", "/users", Some(&b_admin), None).await; |
| 27653 | assert_eq!(res.status, StatusCode::OK); | 27717 | assert_eq!(res.status, StatusCode::OK); |
| 27654 | id_of(&common::items(&res.body)[0]) | 27718 | id_of(&common::items(&res.body)[0]) |
| 27655 | }; | 27719 | }; |
| 27656 | - let a_parent_id = common::me_id(&app, &a_parent).await; | 27720 | + let a_parent_id = common::me_id(app, &a_parent).await; |
| 27657 | - let a_course = create_course(&app, &a_admin, "A Course").await; | 27721 | + let a_course = create_course(app, &a_admin, "A Course").await; |
| 27658 | let a_board = { | 27722 | let a_board = { |
| 27659 | let res = send( | 27723 | let res = send( |
| 27660 | - &app, | 27724 | + app, |
| 27661 | "POST", | 27725 | "POST", |
| 27662 | "/boards", | 27726 | "/boards", |
| 27663 | Some(&a_admin), | 27727 | Some(&a_admin), |
| @@ -27708,7 +27772,7 @@ async fn probe_cross_school_ids_in_bodies_are_refused() { | |||
| 27708 | ]; | 27772 | ]; |
| 27709 | 27773 | ||
| 27710 | for (what, uri, cookie, body) in cases { | 27774 | for (what, uri, cookie, body) in cases { |
| 27711 | - let res = send(&app, "POST", &uri, Some(cookie), Some(body)).await; | 27775 | + let res = send(app, "POST", &uri, Some(cookie), Some(body)).await; |
| 27712 | assert!( | 27776 | assert!( |
| 27713 | res.status.is_client_error(), | 27777 | res.status.is_client_error(), |
| 27714 | "{what}: POST {uri} answered {} (expected a 4xx refusal): {}", | 27778 | "{what}: POST {uri} answered {} (expected a 4xx refusal): {}", |
| @@ -27727,12 +27791,32 @@ async fn probe_cross_school_ids_in_bodies_are_refused() { | |||
| 27727 | /// the *same* cookie back to life. | 27791 | /// the *same* cookie back to life. |
| 27728 | #[tokio::test] | 27792 | #[tokio::test] |
| 27729 | async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it() { | 27793 | async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it() { |
| 27730 | - let (app, _db_a, db_b, tenants) = two_schools().await; | 27794 | + let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 27795 | + probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it_on(&app, &tenants) | ||
| 27796 | + .await; | ||
| 27797 | +} | ||
| 27798 | + | ||
| 27799 | +/// [`probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it`] on a **real remote deployment** — production's `Mode::Remote`, | ||
| 27800 | +/// where isolation rests on each connection's `use_db` pin. | ||
| 27801 | +#[tokio::test] | ||
| 27802 | +async fn remote_probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it() { | ||
| 27803 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 27804 | + return; | ||
| 27805 | + }; | ||
| 27806 | + probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it_on(&d.app, &d.tenants) | ||
| 27807 | + .await; | ||
| 27808 | +} | ||
| 27809 | + | ||
| 27810 | +async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it_on( | ||
| 27811 | + app: &axum::Router, | ||
| 27812 | + tenants: &Tenants, | ||
| 27813 | +) { | ||
| 27814 | + let db_b = school_db(tenants, "beta").await; | ||
| 27731 | let slug_b = Slug::try_new("beta").unwrap(); | 27815 | let slug_b = Slug::try_new("beta").unwrap(); |
| 27732 | - let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | 27816 | + let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 27733 | 27817 | ||
| 27734 | // Alive first. | 27818 | // Alive first. |
| 27735 | - let res = send(&app, "GET", "/auth/me", Some(&b), None).await; | 27819 | + let res = send(app, "GET", "/auth/me", Some(&b), None).await; |
| 27736 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 27820 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 27737 | 27821 | ||
| 27738 | tenants | 27822 | tenants |
| @@ -27742,7 +27826,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | |||
| 27742 | 27826 | ||
| 27743 | // The already-issued cookie, on the very next request. | 27827 | // The already-issued cookie, on the very next request. |
| 27744 | for route in ["/auth/me", "/users", "/notes", "/courses", "/settings"] { | 27828 | for route in ["/auth/me", "/users", "/notes", "/courses", "/settings"] { |
| 27745 | - let res = send(&app, "GET", route, Some(&b), None).await; | 27829 | + let res = send(app, "GET", route, Some(&b), None).await; |
| 27746 | assert_eq!( | 27830 | assert_eq!( |
| 27747 | res.status, | 27831 | res.status, |
| 27748 | StatusCode::FORBIDDEN, | 27832 | StatusCode::FORBIDDEN, |
| @@ -27753,7 +27837,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | |||
| 27753 | } | 27837 | } |
| 27754 | // A write too. | 27838 | // A write too. |
| 27755 | let res = send( | 27839 | let res = send( |
| 27756 | - &app, | 27840 | + app, |
| 27757 | "POST", | 27841 | "POST", |
| 27758 | "/notes", | 27842 | "/notes", |
| 27759 | Some(&b), | 27843 | Some(&b), |
| @@ -27764,7 +27848,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | |||
| 27764 | 27848 | ||
| 27765 | // Login is no exception. | 27849 | // Login is no exception. |
| 27766 | let res = send( | 27850 | let res = send( |
| 27767 | - &app, | 27851 | + app, |
| 27768 | "POST", | 27852 | "POST", |
| 27769 | "/auth/login", | 27853 | "/auth/login", |
| 27770 | None, | 27854 | None, |
| @@ -27780,7 +27864,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | |||
| 27780 | 27864 | ||
| 27781 | // Register into it is refused too. | 27865 | // Register into it is refused too. |
| 27782 | let res = send( | 27866 | let res = send( |
| 27783 | - &app, | 27867 | + app, |
| 27784 | "POST", | 27868 | "POST", |
| 27785 | "/auth/register", | 27869 | "/auth/register", |
| 27786 | None, | 27870 | None, |
| @@ -27799,7 +27883,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | |||
| 27799 | .set_status(&slug_b, SchoolStatus::Active) | 27883 | .set_status(&slug_b, SchoolStatus::Active) |
| 27800 | .await | 27884 | .await |
| 27801 | .expect("resume"); | 27885 | .expect("resume"); |
| 27802 | - let res = send(&app, "GET", "/auth/me", Some(&b), None).await; | 27886 | + let res = send(app, "GET", "/auth/me", Some(&b), None).await; |
| 27803 | assert_eq!( | 27887 | assert_eq!( |
| 27804 | res.status, | 27888 | res.status, |
| 27805 | StatusCode::OK, | 27889 | StatusCode::OK, |
| @@ -27814,9 +27898,25 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | |||
| 27814 | /// that would be a full takeover. | 27898 | /// that would be a full takeover. |
| 27815 | #[tokio::test] | 27899 | #[tokio::test] |
| 27816 | async fn probe_cookie_confusion_is_impossible_both_ways() { | 27900 | async fn probe_cookie_confusion_is_impossible_both_ways() { |
| 27817 | - let (app, db_a, db_b, tenants) = two_schools().await; | 27901 | + let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 27818 | - let a = common::login_as_school(&app, &db_a, DEMO_SLUG, "ada", "admin").await; | 27902 | + probe_cookie_confusion_is_impossible_both_ways_on(&app, &tenants).await; |
| 27819 | - let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | 27903 | +} |
| 27904 | + | ||
| 27905 | +/// [`probe_cookie_confusion_is_impossible_both_ways`] on a **real remote deployment** — production's `Mode::Remote`, | ||
| 27906 | +/// where isolation rests on each connection's `use_db` pin. | ||
| 27907 | +#[tokio::test] | ||
| 27908 | +async fn remote_probe_cookie_confusion_is_impossible_both_ways() { | ||
| 27909 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 27910 | + return; | ||
| 27911 | + }; | ||
| 27912 | + probe_cookie_confusion_is_impossible_both_ways_on(&d.app, &d.tenants).await; | ||
| 27913 | +} | ||
| 27914 | + | ||
| 27915 | +async fn probe_cookie_confusion_is_impossible_both_ways_on(app: &axum::Router, tenants: &Tenants) { | ||
| 27916 | + let db_a = school_db(tenants, DEMO_SLUG).await; | ||
| 27917 | + let db_b = school_db(tenants, "beta").await; | ||
| 27918 | + let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await; | ||
| 27919 | + let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; | ||
| 27820 | let token_a = common::cookie_token(&a).to_string(); | 27920 | let token_a = common::cookie_token(&a).to_string(); |
| 27821 | 27921 | ||
| 27822 | hezarfen_backend::domain::builder::Builder::ensure( | 27922 | hezarfen_backend::domain::builder::Builder::ensure( |
| @@ -27827,7 +27927,7 @@ async fn probe_cookie_confusion_is_impossible_both_ways() { | |||
| 27827 | .await | 27927 | .await |
| 27828 | .expect("seed the builder"); | 27928 | .expect("seed the builder"); |
| 27829 | let res = send( | 27929 | let res = send( |
| 27830 | - &app, | 27930 | + app, |
| 27831 | "POST", | 27931 | "POST", |
| 27832 | "/builder/login", | 27932 | "/builder/login", |
| 27833 | None, | 27933 | None, |
| @@ -27840,7 +27940,7 @@ async fn probe_cookie_confusion_is_impossible_both_ways() { | |||
| 27840 | 27940 | ||
| 27841 | // (1) builder cookie on a school surface. | 27941 | // (1) builder cookie on a school surface. |
| 27842 | for route in ["/auth/me", "/users", "/notes"] { | 27942 | for route in ["/auth/me", "/users", "/notes"] { |
| 27843 | - let res = send(&app, "GET", route, Some(&builder_cookie), None).await; | 27943 | + let res = send(app, "GET", route, Some(&builder_cookie), None).await; |
| 27844 | assert_eq!( | 27944 | assert_eq!( |
| 27845 | res.status, | 27945 | res.status, |
| 27846 | StatusCode::UNAUTHORIZED, | 27946 | StatusCode::UNAUTHORIZED, |
| @@ -27852,7 +27952,7 @@ async fn probe_cookie_confusion_is_impossible_both_ways() { | |||
| 27852 | // (2) school cookie on the builder surface. | 27952 | // (2) school cookie on the builder surface. |
| 27853 | for cookie in [&a, &b] { | 27953 | for cookie in [&a, &b] { |
| 27854 | for route in ["/builder/me", "/schools"] { | 27954 | for route in ["/builder/me", "/schools"] { |
| 27855 | - let res = send(&app, "GET", route, Some(cookie), None).await; | 27955 | + let res = send(app, "GET", route, Some(cookie), None).await; |
| 27856 | assert_eq!( | 27956 | assert_eq!( |
| 27857 | res.status, | 27957 | res.status, |
| 27858 | StatusCode::UNAUTHORIZED, | 27958 | StatusCode::UNAUTHORIZED, |
| @@ -27871,7 +27971,7 @@ async fn probe_cookie_confusion_is_impossible_both_ways() { | |||
| 27871 | format!("session={token_a}."), | 27971 | format!("session={token_a}."), |
| 27872 | ] { | 27972 | ] { |
| 27873 | for route in ["/auth/me", "/builder/me"] { | 27973 | for route in ["/auth/me", "/builder/me"] { |
| 27874 | - let res = send(&app, "GET", route, Some(&raw), None).await; | 27974 | + let res = send(app, "GET", route, Some(&raw), None).await; |
| 27875 | assert_eq!( | 27975 | assert_eq!( |
| 27876 | res.status, | 27976 | res.status, |
| 27877 | StatusCode::UNAUTHORIZED, | 27977 | StatusCode::UNAUTHORIZED, |
| @@ -27886,7 +27986,7 @@ async fn probe_cookie_confusion_is_impossible_both_ways() { | |||
| 27886 | format!("session=demo.{builder_token}"), | 27986 | format!("session=demo.{builder_token}"), |
| 27887 | format!("session=beta.{builder_token}"), | 27987 | format!("session=beta.{builder_token}"), |
| 27888 | ] { | 27988 | ] { |
| 27889 | - let res = send(&app, "GET", "/auth/me", Some(&raw), None).await; | 27989 | + let res = send(app, "GET", "/auth/me", Some(&raw), None).await; |
| 27890 | assert_eq!( | 27990 | assert_eq!( |
| 27891 | res.status, | 27991 | res.status, |
| 27892 | StatusCode::UNAUTHORIZED, | 27992 | StatusCode::UNAUTHORIZED, |
| @@ -27902,7 +28002,7 @@ async fn probe_cookie_confusion_is_impossible_both_ways() { | |||
| 27902 | (format!("session=demo.{token_b}"), "B's token under A"), | 28002 | (format!("session=demo.{token_b}"), "B's token under A"), |
| 27903 | ] { | 28003 | ] { |
| 27904 | for route in ["/auth/me", "/users", "/notes", "/settings"] { | 28004 | for route in ["/auth/me", "/users", "/notes", "/settings"] { |
| 27905 | - let res = send(&app, "GET", route, Some(&raw), None).await; | 28005 | + let res = send(app, "GET", route, Some(&raw), None).await; |
| 27906 | assert_eq!( | 28006 | assert_eq!( |
| 27907 | res.status, | 28007 | res.status, |
| 27908 | StatusCode::UNAUTHORIZED, | 28008 | StatusCode::UNAUTHORIZED, |
| @@ -27914,7 +28014,7 @@ async fn probe_cookie_confusion_is_impossible_both_ways() { | |||
| 27914 | } | 28014 | } |
| 27915 | // (6) a school cookie naming a school that does not exist. | 28015 | // (6) a school cookie naming a school that does not exist. |
| 27916 | let res = send( | 28016 | let res = send( |
| 27917 | - &app, | 28017 | + app, |
| 27918 | "GET", | 28018 | "GET", |
| 27919 | "/auth/me", | 28019 | "/auth/me", |
| 27920 | Some(&format!("session=nosuchschool.{token_a}")), | 28020 | Some(&format!("session=nosuchschool.{token_a}")), |
| @@ -27928,11 +28028,27 @@ async fn probe_cookie_confusion_is_impossible_both_ways() { | |||
| 27928 | /// only, and an unknown school is indistinguishable from a bad credential. | 28028 | /// only, and an unknown school is indistinguishable from a bad credential. |
| 27929 | #[tokio::test] | 28029 | #[tokio::test] |
| 27930 | async fn probe_register_is_scoped_to_the_named_school() { | 28030 | async fn probe_register_is_scoped_to_the_named_school() { |
| 27931 | - let (app, db_a, db_b, _t) = two_schools().await; | 28031 | + let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 28032 | + probe_register_is_scoped_to_the_named_school_on(&app, &tenants).await; | ||
| 28033 | +} | ||
| 28034 | + | ||
| 28035 | +/// [`probe_register_is_scoped_to_the_named_school`] on a **real remote deployment** — production's `Mode::Remote`, | ||
| 28036 | +/// where isolation rests on each connection's `use_db` pin. | ||
| 28037 | +#[tokio::test] | ||
| 28038 | +async fn remote_probe_register_is_scoped_to_the_named_school() { | ||
| 28039 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 28040 | + return; | ||
| 28041 | + }; | ||
| 28042 | + probe_register_is_scoped_to_the_named_school_on(&d.app, &d.tenants).await; | ||
| 28043 | +} | ||
| 28044 | + | ||
| 28045 | +async fn probe_register_is_scoped_to_the_named_school_on(app: &axum::Router, tenants: &Tenants) { | ||
| 28046 | + let db_a = school_db(tenants, DEMO_SLUG).await; | ||
| 28047 | + let db_b = school_db(tenants, "beta").await; | ||
| 27932 | 28048 | ||
| 27933 | // Missing `school` is a 4xx, not a silent default. | 28049 | // Missing `school` is a 4xx, not a silent default. |
| 27934 | let res = send( | 28050 | let res = send( |
| 27935 | - &app, | 28051 | + app, |
| 27936 | "POST", | 28052 | "POST", |
| 27937 | "/auth/register", | 28053 | "/auth/register", |
| 27938 | None, | 28054 | None, |
| @@ -27949,7 +28065,7 @@ async fn probe_register_is_scoped_to_the_named_school() { | |||
| 27949 | // The same username in both schools, independently. | 28065 | // The same username in both schools, independently. |
| 27950 | for (slug, db) in [(DEMO_SLUG, &db_a), ("beta", &db_b)] { | 28066 | for (slug, db) in [(DEMO_SLUG, &db_a), ("beta", &db_b)] { |
| 27951 | let res = send( | 28067 | let res = send( |
| 27952 | - &app, | 28068 | + app, |
| 27953 | "POST", | 28069 | "POST", |
| 27954 | "/auth/register", | 28070 | "/auth/register", |
| 27955 | None, | 28071 | None, |
| @@ -27978,7 +28094,7 @@ async fn probe_register_is_scoped_to_the_named_school() { | |||
| 27978 | // Unknown school: same 401 and same body as a bad credential — no | 28094 | // Unknown school: same 401 and same body as a bad credential — no |
| 27979 | // enumeration of the customer list. | 28095 | // enumeration of the customer list. |
| 27980 | let unknown = send( | 28096 | let unknown = send( |
| 27981 | - &app, | 28097 | + app, |
| 27982 | "POST", | 28098 | "POST", |
| 27983 | "/auth/login", | 28099 | "/auth/login", |
| 27984 | None, | 28100 | None, |
| @@ -27986,7 +28102,7 @@ async fn probe_register_is_scoped_to_the_named_school() { | |||
| 27986 | ) | 28102 | ) |
| 27987 | .await; | 28103 | .await; |
| 27988 | let bad_pass = send( | 28104 | let bad_pass = send( |
| 27989 | - &app, | 28105 | + app, |
| 27990 | "POST", | 28106 | "POST", |
| 27991 | "/auth/login", | 28107 | "/auth/login", |
| 27992 | None, | 28108 | None, |
| @@ -28003,7 +28119,7 @@ async fn probe_register_is_scoped_to_the_named_school() { | |||
| 28003 | 28119 | ||
| 28004 | // Register against an unknown school: same treatment. | 28120 | // Register against an unknown school: same treatment. |
| 28005 | let reg_unknown = send( | 28121 | let reg_unknown = send( |
| 28006 | - &app, | 28122 | + app, |
| 28007 | "POST", | 28123 | "POST", |
| 28008 | "/auth/register", | 28124 | "/auth/register", |
| 28009 | None, | 28125 | None, |
| @@ -28023,12 +28139,32 @@ async fn probe_register_is_scoped_to_the_named_school() { | |||
| 28023 | /// under B's cookie even with the exact ids. | 28139 | /// under B's cookie even with the exact ids. |
| 28024 | #[tokio::test] | 28140 | #[tokio::test] |
| 28025 | async fn probe_uploaded_files_are_school_scoped() { | 28141 | async fn probe_uploaded_files_are_school_scoped() { |
| 28026 | - let (app, db_a, db_b, _t) = two_schools().await; | 28142 | + let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 28027 | - let a = common::login_as_school(&app, &db_a, DEMO_SLUG, "ali", "student").await; | 28143 | + probe_uploaded_files_are_school_scoped_on(&app, &tenants, common::files_dir().as_path()).await; |
| 28028 | - let b = common::login_as_school(&app, &db_b, "beta", "ali", "student").await; | 28144 | +} |
| 28145 | + | ||
| 28146 | +/// [`probe_uploaded_files_are_school_scoped`] on a **real remote deployment** — production's `Mode::Remote`, | ||
| 28147 | +/// where isolation rests on each connection's `use_db` pin. | ||
| 28148 | +#[tokio::test] | ||
| 28149 | +async fn remote_probe_uploaded_files_are_school_scoped() { | ||
| 28150 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 28151 | + return; | ||
| 28152 | + }; | ||
| 28153 | + probe_uploaded_files_are_school_scoped_on(&d.app, &d.tenants, &d.files).await; | ||
| 28154 | +} | ||
| 28155 | + | ||
| 28156 | +async fn probe_uploaded_files_are_school_scoped_on( | ||
| 28157 | + app: &axum::Router, | ||
| 28158 | + tenants: &Tenants, | ||
| 28159 | + files: &std::path::Path, | ||
| 28160 | +) { | ||
| 28161 | + let db_a = school_db(tenants, DEMO_SLUG).await; | ||
| 28162 | + let db_b = school_db(tenants, "beta").await; | ||
| 28163 | + let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ali", "student").await; | ||
| 28164 | + let b = common::login_as_school(app, &db_b, "beta", "ali", "student").await; | ||
| 28029 | 28165 | ||
| 28030 | let note = send( | 28166 | let note = send( |
| 28031 | - &app, | 28167 | + app, |
| 28032 | "POST", | 28168 | "POST", |
| 28033 | "/notes", | 28169 | "/notes", |
| 28034 | Some(&a), | 28170 | Some(&a), |
| @@ -28038,13 +28174,13 @@ async fn probe_uploaded_files_are_school_scoped() { | |||
| 28038 | assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); | 28174 | assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); |
| 28039 | let note_id = id_of(¬e.body); | 28175 | let note_id = id_of(¬e.body); |
| 28040 | 28176 | ||
| 28041 | - let up = common::upload_file(&app, &a, ¬e_id, "a.txt", "text/plain", b"A-ONLY-BYTES").await; | 28177 | + let up = common::upload_file(app, &a, ¬e_id, "a.txt", "text/plain", b"A-ONLY-BYTES").await; |
| 28042 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); | 28178 | assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); |
| 28043 | let file_id = id_of(&up.body); | 28179 | let file_id = id_of(&up.body); |
| 28044 | 28180 | ||
| 28045 | // It landed under the school's own directory, and nowhere else. | 28181 | // It landed under the school's own directory, and nowhere else. |
| 28046 | - let a_dir = common::files_dir().join(DEMO_SLUG); | 28182 | + let a_dir = files.join(DEMO_SLUG); |
| 28047 | - let b_dir = common::files_dir().join("beta"); | 28183 | + let b_dir = files.join("beta"); |
| 28048 | let count = |dir: &std::path::Path| { | 28184 | let count = |dir: &std::path::Path| { |
| 28049 | std::fs::read_dir(dir) | 28185 | std::fs::read_dir(dir) |
| 28050 | .map(|it| it.count()) | 28186 | .map(|it| it.count()) |
| @@ -28059,12 +28195,12 @@ async fn probe_uploaded_files_are_school_scoped() { | |||
| 28059 | 28195 | ||
| 28060 | // A reads it back. | 28196 | // A reads it back. |
| 28061 | let uri = format!("/notes/{note_id}/files/{file_id}"); | 28197 | let uri = format!("/notes/{note_id}/files/{file_id}"); |
| 28062 | - let (status, _, bytes) = common::send_raw(&app, "GET", &uri, Some(&a), None, Vec::new()).await; | 28198 | + let (status, _, bytes) = common::send_raw(app, "GET", &uri, Some(&a), None, Vec::new()).await; |
| 28063 | assert_eq!(status, StatusCode::OK, "A reads its own file"); | 28199 | assert_eq!(status, StatusCode::OK, "A reads its own file"); |
| 28064 | assert_eq!(bytes, b"A-ONLY-BYTES"); | 28200 | assert_eq!(bytes, b"A-ONLY-BYTES"); |
| 28065 | 28201 | ||
| 28066 | // B, with the exact ids, gets nothing — and no 500. | 28202 | // B, with the exact ids, gets nothing — and no 500. |
| 28067 | - let (status, _, bytes) = common::send_raw(&app, "GET", &uri, Some(&b), None, Vec::new()).await; | 28203 | + let (status, _, bytes) = common::send_raw(app, "GET", &uri, Some(&b), None, Vec::new()).await; |
| 28068 | assert_eq!( | 28204 | assert_eq!( |
| 28069 | status, | 28205 | status, |
| 28070 | StatusCode::NOT_FOUND, | 28206 | StatusCode::NOT_FOUND, |
| @@ -28073,9 +28209,9 @@ async fn probe_uploaded_files_are_school_scoped() { | |||
| 28073 | ); | 28209 | ); |
| 28074 | assert!(!bytes.windows(12).any(|w| w == b"A-ONLY-BYTES")); | 28210 | assert!(!bytes.windows(12).any(|w| w == b"A-ONLY-BYTES")); |
| 28075 | 28211 | ||
| 28076 | - let (status, _, _) = common::send_raw(&app, "DELETE", &uri, Some(&b), None, Vec::new()).await; | 28212 | + let (status, _, _) = common::send_raw(app, "DELETE", &uri, Some(&b), None, Vec::new()).await; |
| 28077 | assert_eq!(status, StatusCode::NOT_FOUND, "B deleted A's file"); | 28213 | assert_eq!(status, StatusCode::NOT_FOUND, "B deleted A's file"); |
| 28078 | - let (status, _, _) = common::send_raw(&app, "GET", &uri, Some(&a), None, Vec::new()).await; | 28214 | + let (status, _, _) = common::send_raw(app, "GET", &uri, Some(&a), None, Vec::new()).await; |
| 28079 | assert_eq!(status, StatusCode::OK, "A's file survived B's DELETE"); | 28215 | assert_eq!(status, StatusCode::OK, "A's file survived B's DELETE"); |
| 28080 | } | 28216 | } |
| 28081 | 28217 | ||
| @@ -28084,11 +28220,30 @@ async fn probe_uploaded_files_are_school_scoped() { | |||
| 28084 | /// (which are not paged lists) stay inside the caller's school. | 28220 | /// (which are not paged lists) stay inside the caller's school. |
| 28085 | #[tokio::test] | 28221 | #[tokio::test] |
| 28086 | async fn probe_school_rows_never_reach_the_control_database() { | 28222 | async fn probe_school_rows_never_reach_the_control_database() { |
| 28087 | - let (app, db_a, db_b, tenants) = two_schools().await; | 28223 | + let (app, _db_a, _db_b, tenants) = two_schools().await; |
| 28088 | - let a = common::login_as_school(&app, &db_a, DEMO_SLUG, "ada", "admin").await; | 28224 | + probe_school_rows_never_reach_the_control_database_on(&app, &tenants).await; |
| 28089 | - let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | 28225 | +} |
| 28090 | - common::login_as_school(&app, &db_b, "beta", "bstudent", "student").await; | 28226 | + |
| 28091 | - let ids = seed_school_b(&app, &b).await; | 28227 | +/// [`probe_school_rows_never_reach_the_control_database`] on a **real remote deployment** — production's `Mode::Remote`, |
| 28228 | +/// where isolation rests on each connection's `use_db` pin. | ||
| 28229 | +#[tokio::test] | ||
| 28230 | +async fn remote_probe_school_rows_never_reach_the_control_database() { | ||
| 28231 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 28232 | + return; | ||
| 28233 | + }; | ||
| 28234 | + probe_school_rows_never_reach_the_control_database_on(&d.app, &d.tenants).await; | ||
| 28235 | +} | ||
| 28236 | + | ||
| 28237 | +async fn probe_school_rows_never_reach_the_control_database_on( | ||
| 28238 | + app: &axum::Router, | ||
| 28239 | + tenants: &Tenants, | ||
| 28240 | +) { | ||
| 28241 | + let db_a = school_db(tenants, DEMO_SLUG).await; | ||
| 28242 | + let db_b = school_db(tenants, "beta").await; | ||
| 28243 | + let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await; | ||
| 28244 | + let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; | ||
| 28245 | + common::login_as_school(app, &db_b, "beta", "bstudent", "student").await; | ||
| 28246 | + let ids = seed_school_b(app, &b).await; | ||
| 28092 | assert!(ids["course"].is_string()); | 28247 | assert!(ids["course"].is_string()); |
| 28093 | 28248 | ||
| 28094 | // Nothing a school writes may appear in the control database. | 28249 | // Nothing a school writes may appear in the control database. |
| @@ -28132,7 +28287,7 @@ async fn probe_school_rows_never_reach_the_control_database() { | |||
| 28132 | for (cookie, forbidden) in [(&a, "boran"), (&b, "ada")] { | 28287 | for (cookie, forbidden) in [(&a, "boran"), (&b, "ada")] { |
| 28133 | for q in ["b", "a", "boran", "ada", "bstudent"] { | 28288 | for q in ["b", "a", "boran", "ada", "bstudent"] { |
| 28134 | let res = send( | 28289 | let res = send( |
| 28135 | - &app, | 28290 | + app, |
| 28136 | "GET", | 28291 | "GET", |
| 28137 | &format!("/users/search?q={q}"), | 28292 | &format!("/users/search?q={q}"), |
| 28138 | Some(cookie), | 28293 | Some(cookie), |
| @@ -28149,10 +28304,10 @@ async fn probe_school_rows_never_reach_the_control_database() { | |||
| 28149 | } | 28304 | } |
| 28150 | 28305 | ||
| 28151 | // Settings are the school's own: moving A's leaves B's alone. | 28306 | // Settings are the school's own: moving A's leaves B's alone. |
| 28152 | - let before = send(&app, "GET", "/settings", Some(&b), None).await; | 28307 | + let before = send(app, "GET", "/settings", Some(&b), None).await; |
| 28153 | assert_eq!(before.status, StatusCode::OK, "{}", before.body); | 28308 | assert_eq!(before.status, StatusCode::OK, "{}", before.body); |
| 28154 | let patched = send( | 28309 | let patched = send( |
| 28155 | - &app, | 28310 | + app, |
| 28156 | "PATCH", | 28311 | "PATCH", |
| 28157 | "/settings", | 28312 | "/settings", |
| 28158 | Some(&a), | 28313 | Some(&a), |
| @@ -28161,7 +28316,7 @@ async fn probe_school_rows_never_reach_the_control_database() { | |||
| 28161 | .await; | 28316 | .await; |
| 28162 | assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); | 28317 | assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); |
| 28163 | assert_eq!(patched.body["max_file_bytes"], 4096); | 28318 | assert_eq!(patched.body["max_file_bytes"], 4096); |
| 28164 | - let after = send(&app, "GET", "/settings", Some(&b), None).await; | 28319 | + let after = send(app, "GET", "/settings", Some(&b), None).await; |
| 28165 | assert_eq!( | 28320 | assert_eq!( |
| 28166 | after.body, before.body, | 28321 | after.body, before.body, |
| 28167 | "A's settings PATCH moved B's settings" | 28322 | "A's settings PATCH moved B's settings" |
| @@ -28170,7 +28325,7 @@ async fn probe_school_rows_never_reach_the_control_database() { | |||
| 28170 | // A cookie prefix that is not a well-formed slug is a 401, never a lookup. | 28325 | // A cookie prefix that is not a well-formed slug is a 401, never a lookup. |
| 28171 | for prefix in ["DEMO", "Demo", "de mo", "de/mo", "..", "demo%2e", "control"] { | 28326 | for prefix in ["DEMO", "Demo", "de mo", "de/mo", "..", "demo%2e", "control"] { |
| 28172 | let raw = format!("session={prefix}.{}", common::cookie_token(&a)); | 28327 | let raw = format!("session={prefix}.{}", common::cookie_token(&a)); |
| 28173 | - let res = send(&app, "GET", "/auth/me", Some(&raw), None).await; | 28328 | + let res = send(app, "GET", "/auth/me", Some(&raw), None).await; |
| 28174 | assert_eq!( | 28329 | assert_eq!( |
| 28175 | res.status, | 28330 | res.status, |
| 28176 | StatusCode::UNAUTHORIZED, | 28331 | StatusCode::UNAUTHORIZED, |
| @@ -28186,76 +28341,23 @@ async fn probe_school_rows_never_reach_the_control_database() { | |||
| 28186 | /// entirely on each connection's `use_db` pin — unlike `Mode::Mem`, where a | 28341 | /// entirely on each connection's `use_db` pin — unlike `Mode::Mem`, where a |
| 28187 | /// school is its own embedded datastore and isolation cannot fail. | 28342 | /// school is its own embedded datastore and isolation cannot fail. |
| 28188 | /// | 28343 | /// |
| 28189 | -/// Skipped unless `HEZARFEN_REMOTE_DB` names a live SurrealDB (e.g. | 28344 | +/// The two slugs are the ones that are not bare identifiers: `ata-koleji` parses |
| 28190 | -/// `surreal start --user root --pass root memory --bind 127.0.0.1:8123`), since | 28345 | +/// as a subtraction unquoted, `2024school` as a duration. |
| 28191 | -/// this suite must stay runnable with no server. | ||
| 28192 | #[tokio::test] | 28346 | #[tokio::test] |
| 28193 | -async fn probe_remote_mode_keeps_two_schools_apart() { | 28347 | +async fn remote_probe_remote_mode_keeps_two_schools_apart() { |
| 28194 | - let Ok(url) = std::env::var("HEZARFEN_REMOTE_DB") else { | 28348 | + let Some(d) = common::remote_deployment(&[("ata-koleji", "Ata"), ("2024school", "2024")]).await |
| 28195 | - eprintln!("HEZARFEN_REMOTE_DB unset — remote-mode isolation NOT exercised"); | 28349 | + else { |
| 28196 | return; | 28350 | return; |
| 28197 | }; | 28351 | }; |
| 28198 | - let ns = format!( | 28352 | + let (app, tenants) = (&d.app, &d.tenants); |
| 28199 | - "probe_{}", | ||
| 28200 | - std::time::SystemTime::now() | ||
| 28201 | - .duration_since(std::time::UNIX_EPOCH) | ||
| 28202 | - .unwrap() | ||
| 28203 | - .as_nanos() | ||
| 28204 | - ); | ||
| 28205 | - let cfg = hezarfen_backend::config::Config { | ||
| 28206 | - host: "127.0.0.1".into(), | ||
| 28207 | - port: 0, | ||
| 28208 | - db_url: url, | ||
| 28209 | - db_user: "root".into(), | ||
| 28210 | - db_pass: "root".into(), | ||
| 28211 | - db_ns: ns.clone(), | ||
| 28212 | - db_name: "control".into(), | ||
| 28213 | - files_path: common::files_dir().to_string_lossy().into_owned(), | ||
| 28214 | - cookie_secure: false, | ||
| 28215 | - rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), | ||
| 28216 | - chatbot_per_minute: 0, | ||
| 28217 | - builder_username: None, | ||
| 28218 | - builder_password: None, | ||
| 28219 | - ai_quic_addr: None, | ||
| 28220 | - ai_shared_token: None, | ||
| 28221 | - ai_tls_cert: None, | ||
| 28222 | - ai_tls_key: None, | ||
| 28223 | - ai_request_timeout_secs: 30, | ||
| 28224 | - }; | ||
| 28225 | - let tenants = hezarfen_backend::database::init(&cfg) | ||
| 28226 | - .await | ||
| 28227 | - .expect("remote control database"); | ||
| 28228 | - | ||
| 28229 | - // Two schools, one with a slug that is not a bare identifier. | ||
| 28230 | let slug_a = Slug::try_new("ata-koleji").unwrap(); | 28353 | let slug_a = Slug::try_new("ata-koleji").unwrap(); |
| 28231 | let slug_b = Slug::try_new("2024school").unwrap(); | 28354 | let slug_b = Slug::try_new("2024school").unwrap(); |
| 28232 | - tenants | ||
| 28233 | - .create(&slug_a, "Ata") | ||
| 28234 | - .await | ||
| 28235 | - .expect("school ata-koleji"); | ||
| 28236 | - tenants | ||
| 28237 | - .create(&slug_b, "2024") | ||
| 28238 | - .await | ||
| 28239 | - .expect("school 2024school"); | ||
| 28240 | - | ||
| 28241 | - let app = build_router(AppState { | ||
| 28242 | - db: tenants.control().clone(), | ||
| 28243 | - tenants: tenants.clone(), | ||
| 28244 | - files_path: common::files_dir(), | ||
| 28245 | - cookie_secure: false, | ||
| 28246 | - rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), | ||
| 28247 | - chatbot_limit: Default::default(), | ||
| 28248 | - exam_presence: Default::default(), | ||
| 28249 | - board_hub: Default::default(), | ||
| 28250 | - db_up: Default::default(), | ||
| 28251 | - ai: None, | ||
| 28252 | - }); | ||
| 28253 | 28355 | ||
| 28254 | // The same username in both schools, over the real router. | 28356 | // The same username in both schools, over the real router. |
| 28255 | let mut cookies = Vec::new(); | 28357 | let mut cookies = Vec::new(); |
| 28256 | for slug in [&slug_a, &slug_b] { | 28358 | for slug in [&slug_a, &slug_b] { |
| 28257 | let creds = json!({ "school": slug.as_str(), "username": "ada", "password": "secret1" }); | 28359 | let creds = json!({ "school": slug.as_str(), "username": "ada", "password": "secret1" }); |
| 28258 | - let reg = send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; | 28360 | + let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; |
| 28259 | assert_eq!( | 28361 | assert_eq!( |
| 28260 | reg.status, | 28362 | reg.status, |
| 28261 | StatusCode::CREATED, | 28363 | StatusCode::CREATED, |
| @@ -28264,16 +28366,16 @@ async fn probe_remote_mode_keeps_two_schools_apart() { | |||
| 28264 | ); | 28366 | ); |
| 28265 | let db = tenants.get(slug).await.unwrap(); | 28367 | let db = tenants.get(slug).await.unwrap(); |
| 28266 | common::set_role(&db, "ada", "admin").await; | 28368 | common::set_role(&db, "ada", "admin").await; |
| 28267 | - let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; | 28369 | + let res = send(app, "POST", "/auth/login", None, Some(creds)).await; |
| 28268 | assert_eq!(res.status, StatusCode::OK, "login in {slug}: {}", res.body); | 28370 | assert_eq!(res.status, StatusCode::OK, "login in {slug}: {}", res.body); |
| 28269 | cookies.push(res.cookie.expect("cookie")); | 28371 | cookies.push(res.cookie.expect("cookie")); |
| 28270 | } | 28372 | } |
| 28271 | let (a, b) = (cookies[0].clone(), cookies[1].clone()); | 28373 | let (a, b) = (cookies[0].clone(), cookies[1].clone()); |
| 28272 | 28374 | ||
| 28273 | // B fills up; A must not see a single row of it. | 28375 | // B fills up; A must not see a single row of it. |
| 28274 | - let ids = seed_school_b(&app, &b).await; | 28376 | + let ids = seed_school_b(app, &b).await; |
| 28275 | for route in LIST_ROUTES { | 28377 | for route in LIST_ROUTES { |
| 28276 | - let res = send(&app, "GET", route, Some(&a), None).await; | 28378 | + let res = send(app, "GET", route, Some(&a), None).await; |
| 28277 | assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); | 28379 | assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); |
| 28278 | let dump = res.body.to_string(); | 28380 | let dump = res.body.to_string(); |
| 28279 | for key in [ | 28381 | for key in [ |
| @@ -28289,7 +28391,7 @@ async fn probe_remote_mode_keeps_two_schools_apart() { | |||
| 28289 | } | 28391 | } |
| 28290 | // Each school sees exactly its own user, and only one. | 28392 | // Each school sees exactly its own user, and only one. |
| 28291 | for cookie in [&a, &b] { | 28393 | for cookie in [&a, &b] { |
| 28292 | - let res = send(&app, "GET", "/users", Some(cookie), None).await; | 28394 | + let res = send(app, "GET", "/users", Some(cookie), None).await; |
| 28293 | assert_eq!(common::total(&res.body), 1, "{}", res.body); | 28395 | assert_eq!(common::total(&res.body), 1, "{}", res.body); |
| 28294 | } | 28396 | } |
| 28295 | // A row minted in B is a 404 under A on every verb. | 28397 | // A row minted in B is a 404 under A on every verb. |
| @@ -28303,7 +28405,7 @@ async fn probe_remote_mode_keeps_two_schools_apart() { | |||
| 28303 | _ => format!("/classes/{id}"), | 28405 | _ => format!("/classes/{id}"), |
| 28304 | }; | 28406 | }; |
| 28305 | for method in ["GET", "DELETE"] { | 28407 | for method in ["GET", "DELETE"] { |
| 28306 | - let res = send(&app, method, &uri, Some(&a), None).await; | 28408 | + let res = send(app, method, &uri, Some(&a), None).await; |
| 28307 | assert_ne!( | 28409 | assert_ne!( |
| 28308 | res.status, | 28410 | res.status, |
| 28309 | StatusCode::OK, | 28411 | StatusCode::OK, |
| @@ -28318,7 +28420,7 @@ async fn probe_remote_mode_keeps_two_schools_apart() { | |||
| 28318 | res.body | 28420 | res.body |
| 28319 | ); | 28421 | ); |
| 28320 | } | 28422 | } |
| 28321 | - let res = send(&app, "GET", &uri, Some(&b), None).await; | 28423 | + let res = send(app, "GET", &uri, Some(&b), None).await; |
| 28322 | assert_eq!( | 28424 | assert_eq!( |
| 28323 | res.status, | 28425 | res.status, |
| 28324 | StatusCode::OK, | 28426 | StatusCode::OK, |
| @@ -28329,12 +28431,219 @@ async fn probe_remote_mode_keeps_two_schools_apart() { | |||
| 28329 | 28431 | ||
| 28330 | // A's token under B's prefix stays a 401 on a real server too. | 28432 | // A's token under B's prefix stays a 401 on a real server too. |
| 28331 | let raw = format!("session={}.{}", slug_b, common::cookie_token(&a)); | 28433 | let raw = format!("session={}.{}", slug_b, common::cookie_token(&a)); |
| 28332 | - let res = send(&app, "GET", "/auth/me", Some(&raw), None).await; | 28434 | + let res = send(app, "GET", "/auth/me", Some(&raw), None).await; |
| 28333 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); | 28435 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); |
| 28436 | +} | ||
| 28334 | 28437 | ||
| 28335 | - // Clean up after ourselves: the whole scratch namespace. | 28438 | +// ------------------------------------------------------------------------- |
| 28336 | - let _ = tenants | 28439 | +// Remote-only invariants: things `Mode::Mem` cannot even express, because a |
| 28440 | +// memory-mode school is its own datastore rather than a database on a server. | ||
| 28441 | +// ------------------------------------------------------------------------- | ||
| 28442 | + | ||
| 28443 | +/// The namespace's database list, out of `INFO FOR NS` on the control handle. | ||
| 28444 | +async fn namespace_databases(tenants: &Tenants) -> Vec<String> { | ||
| 28445 | + let mut info = tenants | ||
| 28337 | .control() | 28446 | .control() |
| 28338 | - .query(format!("REMOVE NAMESPACE IF EXISTS `{ns}`")) | 28447 | + .query("INFO FOR NS") |
| 28339 | - .await; | 28448 | + .await |
| 28449 | + .expect("INFO FOR NS"); | ||
| 28450 | + let info: serde_json::Value = info | ||
| 28451 | + .take::<Option<serde_json::Value>>(0) | ||
| 28452 | + .expect("INFO FOR NS row") | ||
| 28453 | + .expect("INFO FOR NS is never empty"); | ||
| 28454 | + let mut names: Vec<String> = info["databases"] | ||
| 28455 | + .as_object() | ||
| 28456 | + .unwrap_or_else(|| panic!("INFO FOR NS has no databases map: {info}")) | ||
| 28457 | + .keys() | ||
| 28458 | + .cloned() | ||
| 28459 | + .collect(); | ||
| 28460 | + names.sort(); | ||
| 28461 | + names | ||
| 28462 | +} | ||
| 28463 | + | ||
| 28464 | +/// Remote-only: a school **is** a database, so the namespace must hold exactly | ||
| 28465 | +/// the created schools plus `control` — and `DELETE /schools/{slug}` must | ||
| 28466 | +/// `REMOVE DATABASE`, not merely delete the registry row. | ||
| 28467 | +#[tokio::test] | ||
| 28468 | +async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { | ||
| 28469 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 28470 | + return; | ||
| 28471 | + }; | ||
| 28472 | + assert_eq!( | ||
| 28473 | + namespace_databases(&d.tenants).await, | ||
| 28474 | + vec![ | ||
| 28475 | + "beta".to_string(), | ||
| 28476 | + "control".to_string(), | ||
| 28477 | + "demo".to_string() | ||
| 28478 | + ], | ||
| 28479 | + "the namespace holds exactly the two schools and the control database" | ||
| 28480 | + ); | ||
| 28481 | + | ||
| 28482 | + hezarfen_backend::domain::builder::Builder::ensure( | ||
| 28483 | + Username::try_new("operator").unwrap(), | ||
| 28484 | + Password::try_new("secret1").unwrap(), | ||
| 28485 | + d.tenants.control(), | ||
| 28486 | + ) | ||
| 28487 | + .await | ||
| 28488 | + .expect("seed the builder"); | ||
| 28489 | + let res = send( | ||
| 28490 | + &d.app, | ||
| 28491 | + "POST", | ||
| 28492 | + "/builder/login", | ||
| 28493 | + None, | ||
| 28494 | + Some(json!({ "username": "operator", "password": "secret1" })), | ||
| 28495 | + ) | ||
| 28496 | + .await; | ||
| 28497 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 28498 | + let builder = res.cookie.expect("builder cookie"); | ||
| 28499 | + | ||
| 28500 | + let res = send(&d.app, "DELETE", "/schools/beta", Some(&builder), None).await; | ||
| 28501 | + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | ||
| 28502 | + assert_eq!( | ||
| 28503 | + namespace_databases(&d.tenants).await, | ||
| 28504 | + vec!["control".to_string(), "demo".to_string()], | ||
| 28505 | + "DELETE /schools/beta left beta's database standing" | ||
| 28506 | + ); | ||
| 28507 | +} | ||
| 28508 | + | ||
| 28509 | +/// Remote-only: raw SQL on a school's own handle sees that school's rows and | ||
| 28510 | +/// no others — the `use_db` pin, checked under the API rather than through it. | ||
| 28511 | +#[tokio::test] | ||
| 28512 | +async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() { | ||
| 28513 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 28514 | + return; | ||
| 28515 | + }; | ||
| 28516 | + // Different counts, so a leak cannot hide behind equal numbers. | ||
| 28517 | + for (slug, users) in [ | ||
| 28518 | + (DEMO_SLUG, ["ada", "ali", "ayse"].as_slice()), | ||
| 28519 | + ("beta", &["boran"]), | ||
| 28520 | + ] { | ||
| 28521 | + for username in users { | ||
| 28522 | + let res = send( | ||
| 28523 | + &d.app, | ||
| 28524 | + "POST", | ||
| 28525 | + "/auth/register", | ||
| 28526 | + None, | ||
| 28527 | + Some(json!({ "school": slug, "username": username, "password": "secret1" })), | ||
| 28528 | + ) | ||
| 28529 | + .await; | ||
| 28530 | + assert_eq!( | ||
| 28531 | + res.status, | ||
| 28532 | + StatusCode::CREATED, | ||
| 28533 | + "{slug}/{username}: {}", | ||
| 28534 | + res.body | ||
| 28535 | + ); | ||
| 28536 | + } | ||
| 28537 | + } | ||
| 28538 | + | ||
| 28539 | + let count = async |db: &hezarfen_backend::database::Database| -> i64 { | ||
| 28540 | + db.query("SELECT count() FROM user GROUP ALL") | ||
| 28541 | + .await | ||
| 28542 | + .expect("count query") | ||
| 28543 | + .take::<Vec<serde_json::Value>>(0) | ||
| 28544 | + .expect("count row") | ||
| 28545 | + .first() | ||
| 28546 | + .and_then(|row| row["count"].as_i64()) | ||
| 28547 | + .unwrap_or_default() | ||
| 28548 | + }; | ||
| 28549 | + let db_a = school_db(&d.tenants, DEMO_SLUG).await; | ||
| 28550 | + let db_b = school_db(&d.tenants, "beta").await; | ||
| 28551 | + assert_eq!(count(&db_a).await, 3, "demo's own users"); | ||
| 28552 | + assert_eq!(count(&db_b).await, 1, "beta's own users"); | ||
| 28553 | +} | ||
| 28554 | + | ||
| 28555 | +/// Remote-only: one namespace, so the *same record id string* exists in both | ||
| 28556 | +/// databases' address space. Selected on the other school's handle it must | ||
| 28557 | +/// still find nothing — record ids are not global. | ||
| 28558 | +#[tokio::test] | ||
| 28559 | +async fn remote_probe_a_record_id_minted_in_one_school_is_absent_in_the_other() { | ||
| 28560 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 28561 | + return; | ||
| 28562 | + }; | ||
| 28563 | + let res = send( | ||
| 28564 | + &d.app, | ||
| 28565 | + "POST", | ||
| 28566 | + "/auth/register", | ||
| 28567 | + None, | ||
| 28568 | + Some(json!({ "school": DEMO_SLUG, "username": "ada", "password": "secret1" })), | ||
| 28569 | + ) | ||
| 28570 | + .await; | ||
| 28571 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 28572 | + | ||
| 28573 | + let db_a = school_db(&d.tenants, DEMO_SLUG).await; | ||
| 28574 | + let db_b = school_db(&d.tenants, "beta").await; | ||
| 28575 | + let id: surrealdb::types::RecordId = db_a | ||
| 28576 | + .query("SELECT VALUE id FROM user LIMIT 1") | ||
| 28577 | + .await | ||
| 28578 | + .expect("A's user id") | ||
| 28579 | + .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 28580 | + .expect("id row") | ||
| 28581 | + .pop() | ||
| 28582 | + .expect("A minted exactly one user"); | ||
| 28583 | + | ||
| 28584 | + let mine: Option<serde_json::Value> = db_a.select(id.clone()).await.expect("select in A"); | ||
| 28585 | + assert!(mine.is_some(), "{id:?} is A's own row"); | ||
| 28586 | + let theirs: Option<serde_json::Value> = db_b.select(id.clone()).await.expect("select in B"); | ||
| 28587 | + assert!( | ||
| 28588 | + theirs.is_none(), | ||
| 28589 | + "{id:?} — minted in demo — resolved on beta's handle: {theirs:?}" | ||
| 28590 | + ); | ||
| 28591 | +} | ||
| 28592 | + | ||
| 28593 | +/// Remote-only: eviction really drops the socket here (in memory mode the | ||
| 28594 | +/// cached handle *is* the store, so it is never dropped). A suspend/resume must | ||
| 28595 | +/// therefore reconnect and find the school's rows exactly as they were. | ||
| 28596 | +#[tokio::test] | ||
| 28597 | +async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() { | ||
| 28598 | + let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | ||
| 28599 | + return; | ||
| 28600 | + }; | ||
| 28601 | + let slug = Slug::try_new(DEMO_SLUG).unwrap(); | ||
| 28602 | + let db = school_db(&d.tenants, DEMO_SLUG).await; | ||
| 28603 | + let cookie = common::login_as_school(&d.app, &db, DEMO_SLUG, "ada", "admin").await; | ||
| 28604 | + let note = send( | ||
| 28605 | + &d.app, | ||
| 28606 | + "POST", | ||
| 28607 | + "/notes", | ||
| 28608 | + Some(&cookie), | ||
| 28609 | + Some(json!({ "title": "before", "content": "kept" })), | ||
| 28610 | + ) | ||
| 28611 | + .await; | ||
| 28612 | + assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); | ||
| 28613 | + let note_id = id_of(¬e.body); | ||
| 28614 | + | ||
| 28615 | + d.tenants | ||
| 28616 | + .set_status(&slug, SchoolStatus::Suspended) | ||
| 28617 | + .await | ||
| 28618 | + .expect("suspend"); | ||
| 28619 | + let res = send(&d.app, "GET", "/auth/me", Some(&cookie), None).await; | ||
| 28620 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 28621 | + d.tenants | ||
| 28622 | + .set_status(&slug, SchoolStatus::Active) | ||
| 28623 | + .await | ||
| 28624 | + .expect("resume"); | ||
| 28625 | + | ||
| 28626 | + // A fresh connection (the old one was evicted) onto the same database. | ||
| 28627 | + let reconnected = school_db(&d.tenants, DEMO_SLUG).await; | ||
| 28628 | + let titles: Vec<String> = reconnected | ||
| 28629 | + .query("SELECT VALUE title FROM note") | ||
| 28630 | + .await | ||
| 28631 | + .expect("notes after the resume") | ||
| 28632 | + .take(0) | ||
| 28633 | + .expect("title rows"); | ||
| 28634 | + assert_eq!(titles, vec!["before".to_string()], "the rows survived"); | ||
| 28635 | + let res = send( | ||
| 28636 | + &d.app, | ||
| 28637 | + "GET", | ||
| 28638 | + &format!("/notes/{note_id}"), | ||
| 28639 | + Some(&cookie), | ||
| 28640 | + None, | ||
| 28641 | + ) | ||
| 28642 | + .await; | ||
| 28643 | + assert_eq!( | ||
| 28644 | + res.status, | ||
| 28645 | + StatusCode::OK, | ||
| 28646 | + "the same cookie and the same note after a resume: {}", | ||
| 28647 | + res.body | ||
| 28648 | + ); | ||
| 28340 | } | 28649 | } |