Quote the school's database name
Browse files at this commitf82697756f9322429d187994abb9a78e348d4ff2Parent: 78fe8c7- fix
- quote the school's database name
- a failed create frees its slug
2 changed files +740 -9
- src/tenant.rs +38 -9
- tests/builder_api.rs +702 -0
src/tenant.rsmodified+38 -9
| @@ -102,6 +102,15 @@ impl std::fmt::Display for Slug { | |||
| 102 | /// [`Tenants::get`] refuses before any handler runs, and login is no exception. | 102 | /// [`Tenants::get`] refuses before any handler runs, and login is no exception. |
| 103 | /// | 103 | /// |
| 104 | /// Stored as a bare lowercase string, like [`crate::domain::role::Role`]. | 104 | /// Stored as a bare lowercase string, like [`crate::domain::role::Role`]. |
| 105 | +/// A school slug as a SurrealQL identifier. A database name cannot be bound | ||
| 106 | +/// as a parameter, so it is interpolated — and it MUST be backtick-quoted: an | ||
| 107 | +/// unquoted `ata-koleji` parses as a subtraction, `2024school` as a duration, | ||
| 108 | +/// `12345` as a number (SurrealDB 3.2). The `Slug` charset (`[a-z0-9-]`) can | ||
| 109 | +/// never contain a backtick, so the quoting cannot be escaped from. | ||
| 110 | +pub fn quoted_ident(slug: &Slug) -> String { | ||
| 111 | + format!("`{}`", slug.as_str()) | ||
| 112 | +} | ||
| 113 | + | ||
| 105 | #[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue, Serialize)] | 114 | #[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue, Serialize)] |
| 106 | #[surreal(untagged, rename_all = "lowercase")] | 115 | #[surreal(untagged, rename_all = "lowercase")] |
| 107 | #[serde(rename_all = "lowercase")] | 116 | #[serde(rename_all = "lowercase")] |
| @@ -364,12 +373,37 @@ impl Tenants { | |||
| 364 | Err(err) => return Err(err.into()), | 373 | Err(err) => return Err(err.into()), |
| 365 | } | 374 | } |
| 366 | 375 | ||
| 376 | + // Everything past the registry row rolls that row back on failure: | ||
| 377 | + // the row is what makes the slug "taken", and a slug taken by a | ||
| 378 | + // school that never came to exist is wedged for good (found by the | ||
| 379 | + // delete-path verifier: `ata-koleji` failed `DEFINE DATABASE` unquoted | ||
| 380 | + // and could then be neither re-created nor deleted). | ||
| 381 | + let db = match self.bring_up(slug).await { | ||
| 382 | + Ok(db) => db, | ||
| 383 | + Err(err) => { | ||
| 384 | + let _ = self | ||
| 385 | + .control | ||
| 386 | + .query("DELETE $id") | ||
| 387 | + .bind(("id", SchoolId::from_slug(slug).record())) | ||
| 388 | + .await; | ||
| 389 | + return Err(err); | ||
| 390 | + } | ||
| 391 | + }; | ||
| 392 | + self.cache | ||
| 393 | + .write() | ||
| 394 | + .expect("tenant cache lock") | ||
| 395 | + .insert(slug.as_str().to_string(), db.clone()); | ||
| 396 | + Ok(db) | ||
| 397 | + } | ||
| 398 | + | ||
| 399 | + /// Define (remote) or mint (memory) the school's database and apply the | ||
| 400 | + /// school schema to it. Split out of [`Tenants::create`] so one `?` chain | ||
| 401 | + /// can be rolled back as a unit. | ||
| 402 | + async fn bring_up(&self, slug: &Slug) -> Result<Database, AppError> { | ||
| 367 | let db = match &*self.mode { | 403 | let db = match &*self.mode { |
| 368 | Mode::Remote { .. } => { | 404 | Mode::Remote { .. } => { |
| 369 | - // `slug` is `Slug`-validated, so this interpolation carries only | ||
| 370 | - // `[a-z0-9-]` — SurrealQL cannot bind a database name. | ||
| 371 | self.control | 405 | self.control |
| 372 | - .query(format!("DEFINE DATABASE IF NOT EXISTS {slug}")) | 406 | + .query(format!("DEFINE DATABASE IF NOT EXISTS {}", quoted_ident(slug))) |
| 373 | .await? | 407 | .await? |
| 374 | .check()?; | 408 | .check()?; |
| 375 | self.connect(slug).await? | 409 | self.connect(slug).await? |
| @@ -377,10 +411,6 @@ impl Tenants { | |||
| 377 | Mode::Mem => self.connect(slug).await?, | 411 | Mode::Mem => self.connect(slug).await?, |
| 378 | }; | 412 | }; |
| 379 | migrate(&db).await?; | 413 | migrate(&db).await?; |
| 380 | - self.cache | ||
| 381 | - .write() | ||
| 382 | - .expect("tenant cache lock") | ||
| 383 | - .insert(slug.as_str().to_string(), db.clone()); | ||
| 384 | Ok(db) | 414 | Ok(db) |
| 385 | } | 415 | } |
| 386 | 416 | ||
| @@ -409,9 +439,8 @@ impl Tenants { | |||
| 409 | /// what [`SchoolStatus::Suspended`] is for. | 439 | /// what [`SchoolStatus::Suspended`] is for. |
| 410 | pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> { | 440 | pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> { |
| 411 | if let Mode::Remote { .. } = &*self.mode { | 441 | if let Mode::Remote { .. } = &*self.mode { |
| 412 | - // Interpolation, not a bind: see `create`. | ||
| 413 | self.control | 442 | self.control |
| 414 | - .query(format!("REMOVE DATABASE IF EXISTS {slug}")) | 443 | + .query(format!("REMOVE DATABASE IF EXISTS {}", quoted_ident(slug))) |
| 415 | .await? | 444 | .await? |
| 416 | .check()?; | 445 | .check()?; |
| 417 | } | 446 | } |
tests/builder_api.rsmodified+702 -0
| @@ -590,3 +590,705 @@ async fn deleting_a_school_takes_its_data_and_its_files() { | |||
| 590 | StatusCode::NOT_FOUND | 590 | StatusCode::NOT_FOUND |
| 591 | ); | 591 | ); |
| 592 | } | 592 | } |
| 593 | + | ||
| 594 | +// --------------------------------------------------------------------------- | ||
| 595 | +// REFUTE-mode probes on the irreversible paths (appended by a verifier). | ||
| 596 | +// --------------------------------------------------------------------------- | ||
| 597 | + | ||
| 598 | +use hezarfen_backend::tenant::Slug; | ||
| 599 | + | ||
| 600 | +/// Claim 1: no `/schools/{slug}` route can be aimed outside `FILES_PATH/<slug>`. | ||
| 601 | +/// Every hostile segment on every method, with canaries inside and outside the | ||
| 602 | +/// deployment's files root. | ||
| 603 | +#[tokio::test] | ||
| 604 | +async fn probe_hostile_slug_segments_never_delete_anything() { | ||
| 605 | + let (app, _db, _tenants) = deployment().await; | ||
| 606 | + let builder = builder_login(&app).await; | ||
| 607 | + | ||
| 608 | + // A school that must survive all of it, with real bytes on disk. | ||
| 609 | + create_school(&app, &builder, "p1keep", "secret1").await; | ||
| 610 | + let keep_dir = files_dir().join("p1keep"); | ||
| 611 | + std::fs::create_dir_all(&keep_dir).unwrap(); | ||
| 612 | + std::fs::write(keep_dir.join("keep.bin"), b"keep").unwrap(); | ||
| 613 | + // A canary at the files root itself: an escape by one `..` takes this. | ||
| 614 | + let root_canary = files_dir().join("p1_root_canary"); | ||
| 615 | + std::fs::write(&root_canary, b"canary").unwrap(); | ||
| 616 | + // …and one fully outside the deployment root. | ||
| 617 | + let outside = tempfile::tempdir().unwrap(); | ||
| 618 | + let outside_file = outside.path().join("outside.bin"); | ||
| 619 | + std::fs::write(&outside_file, b"outside").unwrap(); | ||
| 620 | + | ||
| 621 | + let hostile = [ | ||
| 622 | + "..", | ||
| 623 | + "%2e%2e", | ||
| 624 | + "%2E%2E%2F%2E%2E", | ||
| 625 | + "..%2f..%2fetc", | ||
| 626 | + "%2f", | ||
| 627 | + "p1keep%2f..", | ||
| 628 | + "p1keep..", | ||
| 629 | + ".", | ||
| 630 | + "%00", | ||
| 631 | + "DEMO", | ||
| 632 | + "Demo", | ||
| 633 | + "control", | ||
| 634 | + "builder", | ||
| 635 | + "%C4%B1demo", // dotless i, non-ascii | ||
| 636 | + "d%E2%80%8Bemo", // zero-width space | ||
| 637 | + "de%20mo", | ||
| 638 | + "a", | ||
| 639 | + "-lead", | ||
| 640 | + "demo%2e%2e%2f%2e%2e%2fp1keep", | ||
| 641 | + // 200 characters | ||
| 642 | + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", | ||
| 643 | + ]; | ||
| 644 | + | ||
| 645 | + for raw in hostile { | ||
| 646 | + for (method, suffix, body) in [ | ||
| 647 | + ("GET", "", None), | ||
| 648 | + ("DELETE", "", None), | ||
| 649 | + ("PATCH", "", Some(json!({ "name": "x" }))), | ||
| 650 | + ( | ||
| 651 | + "POST", | ||
| 652 | + "/admin-password", | ||
| 653 | + Some(json!({ "username": "admin", "password": "secret2" })), | ||
| 654 | + ), | ||
| 655 | + ("POST", "/enter", Some(json!({ "username": "admin" }))), | ||
| 656 | + ] { | ||
| 657 | + let uri = format!("/schools/{raw}{suffix}"); | ||
| 658 | + let res = send(&app, method, &uri, Some(&builder), body).await; | ||
| 659 | + assert!( | ||
| 660 | + res.status == StatusCode::NOT_FOUND | ||
| 661 | + || res.status == StatusCode::METHOD_NOT_ALLOWED | ||
| 662 | + || res.status == StatusCode::BAD_REQUEST | ||
| 663 | + || res.status == StatusCode::UNAUTHORIZED, | ||
| 664 | + "{method} {uri} answered {} — a hostile slug must be refused", | ||
| 665 | + res.status | ||
| 666 | + ); | ||
| 667 | + assert!( | ||
| 668 | + !res.status.is_success(), | ||
| 669 | + "{method} {uri} SUCCEEDED ({})", | ||
| 670 | + res.status | ||
| 671 | + ); | ||
| 672 | + } | ||
| 673 | + } | ||
| 674 | + | ||
| 675 | + // Also the empty segment, which is a different route shape entirely. | ||
| 676 | + for method in ["GET", "DELETE", "PATCH"] { | ||
| 677 | + let res = send(&app, method, "/schools/", Some(&builder), None).await; | ||
| 678 | + assert!(!res.status.is_success() || method == "GET", "{method} /schools/ -> {}", res.status); | ||
| 679 | + } | ||
| 680 | + | ||
| 681 | + assert!(keep_dir.join("keep.bin").exists(), "a bystander school lost its bytes"); | ||
| 682 | + assert!(root_canary.exists(), "the FILES_PATH root canary was deleted"); | ||
| 683 | + assert!(outside_file.exists(), "a file outside FILES_PATH was deleted"); | ||
| 684 | + assert!( | ||
| 685 | + files_dir().exists() && outside.path().exists(), | ||
| 686 | + "a directory root was removed" | ||
| 687 | + ); | ||
| 688 | + std::fs::remove_file(&root_canary).ok(); | ||
| 689 | +} | ||
| 690 | + | ||
| 691 | +/// Claim 2: `drop` takes exactly the named school; a neighbour's cached handle | ||
| 692 | +/// keeps working; a re-created slug is an *empty* school. | ||
| 693 | +#[tokio::test] | ||
| 694 | +async fn probe_drop_is_scoped_and_recreation_is_empty() { | ||
| 695 | + let (app, _db, _tenants) = deployment().await; | ||
| 696 | + let builder = builder_login(&app).await; | ||
| 697 | + create_school(&app, &builder, "p2a", "secret1").await; | ||
| 698 | + create_school(&app, &builder, "p2b", "secret1").await; | ||
| 699 | + | ||
| 700 | + let a = school_login(&app, "p2a", "admin", "secret1") | ||
| 701 | + .await | ||
| 702 | + .cookie | ||
| 703 | + .expect("p2a cookie"); | ||
| 704 | + let b = school_login(&app, "p2b", "admin", "secret1") | ||
| 705 | + .await | ||
| 706 | + .cookie | ||
| 707 | + .expect("p2b cookie"); | ||
| 708 | + // A row only p2a has. | ||
| 709 | + let note = send( | ||
| 710 | + &app, | ||
| 711 | + "POST", | ||
| 712 | + "/notes", | ||
| 713 | + Some(&a), | ||
| 714 | + Some(json!({ "title": "secret", "content": "x" })), | ||
| 715 | + ) | ||
| 716 | + .await; | ||
| 717 | + assert_eq!(note.status, StatusCode::CREATED); | ||
| 718 | + // A second user only p2a has. | ||
| 719 | + let _ = send( | ||
| 720 | + &app, | ||
| 721 | + "POST", | ||
| 722 | + "/auth/register", | ||
| 723 | + None, | ||
| 724 | + Some(json!({ "school": "p2a", "username": "ali", "password": "secret1" })), | ||
| 725 | + ) | ||
| 726 | + .await; | ||
| 727 | + | ||
| 728 | + assert_eq!( | ||
| 729 | + send(&app, "DELETE", "/schools/p2a", Some(&builder), None) | ||
| 730 | + .await | ||
| 731 | + .status, | ||
| 732 | + StatusCode::NO_CONTENT | ||
| 733 | + ); | ||
| 734 | + | ||
| 735 | + // The neighbour's already-resolved handle is untouched. | ||
| 736 | + assert_eq!( | ||
| 737 | + send(&app, "GET", "/auth/me", Some(&b), None).await.status, | ||
| 738 | + StatusCode::OK, | ||
| 739 | + "dropping p2a disturbed p2b's cached handle" | ||
| 740 | + ); | ||
| 741 | + // The dropped school is unknown, not forbidden. | ||
| 742 | + assert_eq!( | ||
| 743 | + send(&app, "GET", "/auth/me", Some(&a), None).await.status, | ||
| 744 | + StatusCode::UNAUTHORIZED | ||
| 745 | + ); | ||
| 746 | + assert_eq!( | ||
| 747 | + school_login(&app, "p2a", "admin", "secret1").await.status, | ||
| 748 | + StatusCode::UNAUTHORIZED | ||
| 749 | + ); | ||
| 750 | + | ||
| 751 | + // Re-created with the same slug: nothing of the old school comes back. | ||
| 752 | + let again = create_school(&app, &builder, "p2a", "secret2").await; | ||
| 753 | + assert_eq!(again.status, StatusCode::CREATED, "{:?}", again.body); | ||
| 754 | + assert_eq!( | ||
| 755 | + school_login(&app, "p2a", "admin", "secret1").await.status, | ||
| 756 | + StatusCode::UNAUTHORIZED, | ||
| 757 | + "the OLD admin credential still opens the re-created school" | ||
| 758 | + ); | ||
| 759 | + let fresh = school_login(&app, "p2a", "admin", "secret2") | ||
| 760 | + .await | ||
| 761 | + .cookie | ||
| 762 | + .expect("fresh admin cookie"); | ||
| 763 | + let users = send(&app, "GET", "/users", Some(&fresh), None).await; | ||
| 764 | + assert_eq!(users.status, StatusCode::OK, "{:?}", users.body); | ||
| 765 | + assert_eq!( | ||
| 766 | + total(&users.body), | ||
| 767 | + 1, | ||
| 768 | + "a re-created school carries users from the dropped one: {:?}", | ||
| 769 | + users.body | ||
| 770 | + ); | ||
| 771 | + let notes = send(&app, "GET", "/notes", Some(&fresh), None).await; | ||
| 772 | + assert_eq!(notes.status, StatusCode::OK); | ||
| 773 | + assert_eq!(total(¬es.body), 0, "old rows survived the drop"); | ||
| 774 | +} | ||
| 775 | + | ||
| 776 | +/// Claim 2, remote mode: `Tenants::create`/`drop` interpolate the slug into | ||
| 777 | +/// `DEFINE DATABASE` / `REMOVE DATABASE`. Not injectable — but the statements | ||
| 778 | +/// must at least *execute* for every slug `Slug::try_new` accepts. Run the exact | ||
| 779 | +/// production statements against a live SurrealDB parser. | ||
| 780 | +#[tokio::test] | ||
| 781 | +async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug() { | ||
| 782 | + let tenants = Tenants::new_mem().await.expect("control db"); | ||
| 783 | + let control = tenants.control(); | ||
| 784 | + let mut broken: Vec<String> = Vec::new(); | ||
| 785 | + | ||
| 786 | + for raw in [ | ||
| 787 | + "demo", "abc", "ata-koleji", "x-y", "trail-", "2024school", "12345", "a1", | ||
| 788 | + ] { | ||
| 789 | + let Ok(slug) = Slug::try_new(raw) else { | ||
| 790 | + continue; | ||
| 791 | + }; | ||
| 792 | + // The exact statements `Tenants::create` / `drop` send, via the same | ||
| 793 | + // identifier quoting they use. | ||
| 794 | + let ident = hezarfen_backend::tenant::quoted_ident(&slug); | ||
| 795 | + let define = control | ||
| 796 | + .query(format!("DEFINE DATABASE IF NOT EXISTS {ident}")) | ||
| 797 | + .await | ||
| 798 | + .map_err(|e| e.to_string()) | ||
| 799 | + .and_then(|r| r.check().map(|_| ()).map_err(|e| e.to_string())); | ||
| 800 | + let remove = control | ||
| 801 | + .query(format!("REMOVE DATABASE IF EXISTS {ident}")) | ||
| 802 | + .await | ||
| 803 | + .map_err(|e| e.to_string()) | ||
| 804 | + .and_then(|r| r.check().map(|_| ()).map_err(|e| e.to_string())); | ||
| 805 | + if let Err(err) = define { | ||
| 806 | + broken.push(format!("DEFINE DATABASE {raw} -> {err}")); | ||
| 807 | + } | ||
| 808 | + if let Err(err) = remove { | ||
| 809 | + broken.push(format!("REMOVE DATABASE {raw} -> {err}")); | ||
| 810 | + } | ||
| 811 | + } | ||
| 812 | + assert!( | ||
| 813 | + broken.is_empty(), | ||
| 814 | + "slugs accepted by Slug::try_new whose remote-mode statements do not execute:\n{}", | ||
| 815 | + broken.join("\n") | ||
| 816 | + ); | ||
| 817 | +} | ||
| 818 | + | ||
| 819 | +/// Claim 3: the accept set, and the reserved list `GET /limits` publishes. | ||
| 820 | +#[tokio::test] | ||
| 821 | +async fn probe_slug_accept_set_and_published_reserved_list() { | ||
| 822 | + for bad in [ | ||
| 823 | + "control", "builder", "Demo", "DEMO", "..", "", "a", "-lead", "de mo", "de.mo", "de_mo", | ||
| 824 | + "demo/", "demo\\", "٢٣demo", "démo", "demo\u{200b}", "demo\n", | ||
| 825 | + // 33 characters | ||
| 826 | + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", | ||
| 827 | + ] { | ||
| 828 | + assert!( | ||
| 829 | + Slug::try_new(bad).is_err(), | ||
| 830 | + "Slug::try_new accepted {bad:?}" | ||
| 831 | + ); | ||
| 832 | + } | ||
| 833 | + for good in ["ab", "demo", "a1", "2024", "ata-koleji"] { | ||
| 834 | + assert!(Slug::try_new(good).is_ok(), "Slug::try_new rejected {good:?}"); | ||
| 835 | + } | ||
| 836 | + // Documented boundary: a trailing hyphen IS accepted today. | ||
| 837 | + assert!( | ||
| 838 | + Slug::try_new("trail-").is_ok(), | ||
| 839 | + "trailing hyphen behaviour changed" | ||
| 840 | + ); | ||
| 841 | + | ||
| 842 | + // The published list must be the enforced list. | ||
| 843 | + let (app, _db, _tenants) = deployment().await; | ||
| 844 | + let student = login(&app, "ali").await; | ||
| 845 | + let limits = send(&app, "GET", "/limits", Some(&student), None).await; | ||
| 846 | + assert_eq!(limits.status, StatusCode::OK, "{:?}", limits.body); | ||
| 847 | + let published: Vec<String> = limits.body["school"]["reserved_slugs"] | ||
| 848 | + .as_array() | ||
| 849 | + .or_else(|| { | ||
| 850 | + limits | ||
| 851 | + .body | ||
| 852 | + .as_object() | ||
| 853 | + .and_then(|o| o.values().find_map(|v| v["reserved_slugs"].as_array())) | ||
| 854 | + }) | ||
| 855 | + .unwrap_or_else(|| panic!("no reserved_slugs in /limits: {}", limits.body)) | ||
| 856 | + .iter() | ||
| 857 | + .map(|v| v.as_str().unwrap().to_string()) | ||
| 858 | + .collect(); | ||
| 859 | + let mut enforced: Vec<String> = hezarfen_backend::tenant::RESERVED_SLUGS | ||
| 860 | + .iter() | ||
| 861 | + .map(|s| s.to_string()) | ||
| 862 | + .collect(); | ||
| 863 | + enforced.sort(); | ||
| 864 | + let mut published_sorted = published.clone(); | ||
| 865 | + published_sorted.sort(); | ||
| 866 | + assert_eq!( | ||
| 867 | + published_sorted, enforced, | ||
| 868 | + "GET /limits publishes a different reserved list than Slug::try_new enforces" | ||
| 869 | + ); | ||
| 870 | + for name in &published { | ||
| 871 | + assert!( | ||
| 872 | + Slug::try_new(name).is_err(), | ||
| 873 | + "{name} is published as reserved but Slug::try_new accepts it" | ||
| 874 | + ); | ||
| 875 | + } | ||
| 876 | +} | ||
| 877 | + | ||
| 878 | +/// Claim 4: `admin-password` and `enter` cannot be aimed at a non-admin, at a | ||
| 879 | +/// stranger's account, or (for `enter`) at a suspended school; and a reset kills | ||
| 880 | +/// **every** live session of that account. | ||
| 881 | +#[tokio::test] | ||
| 882 | +async fn probe_admin_targets_and_reset_revokes_all_sessions() { | ||
| 883 | + let (app, _db, tenants) = deployment().await; | ||
| 884 | + let builder = builder_login(&app).await; | ||
| 885 | + create_school(&app, &builder, "p4a", "secret1").await; | ||
| 886 | + create_school(&app, &builder, "p4b", "secret1").await; | ||
| 887 | + let a_db = tenants.get(&Slug::try_new("p4a").unwrap()).await.unwrap(); | ||
| 888 | + | ||
| 889 | + // Three non-admins in p4a, and a name that only exists in p4b. | ||
| 890 | + for (name, role) in [("tea", "teacher"), ("stu", "student"), ("par", "parent")] { | ||
| 891 | + let reg = send( | ||
| 892 | + &app, | ||
| 893 | + "POST", | ||
| 894 | + "/auth/register", | ||
| 895 | + None, | ||
| 896 | + Some(json!({ "school": "p4a", "username": name, "password": "secret1" })), | ||
| 897 | + ) | ||
| 898 | + .await; | ||
| 899 | + assert_eq!(reg.status, StatusCode::CREATED, "register {name}"); | ||
| 900 | + set_role(&a_db, name, role).await; | ||
| 901 | + } | ||
| 902 | + let reg = send( | ||
| 903 | + &app, | ||
| 904 | + "POST", | ||
| 905 | + "/auth/register", | ||
| 906 | + None, | ||
| 907 | + Some(json!({ "school": "p4b", "username": "onlyb", "password": "secret1" })), | ||
| 908 | + ) | ||
| 909 | + .await; | ||
| 910 | + assert_eq!(reg.status, StatusCode::CREATED); | ||
| 911 | + | ||
| 912 | + for target in ["tea", "stu", "par"] { | ||
| 913 | + for (path, body) in [ | ||
| 914 | + ( | ||
| 915 | + "/schools/p4a/admin-password", | ||
| 916 | + json!({ "username": target, "password": "secret2" }), | ||
| 917 | + ), | ||
| 918 | + ("/schools/p4a/enter", json!({ "username": target })), | ||
| 919 | + ] { | ||
| 920 | + let res = send(&app, "POST", path, Some(&builder), Some(body)).await; | ||
| 921 | + assert_eq!( | ||
| 922 | + res.status, | ||
| 923 | + StatusCode::CONFLICT, | ||
| 924 | + "{path} accepted the non-admin {target}: {} {:?}", | ||
| 925 | + res.status, | ||
| 926 | + res.body | ||
| 927 | + ); | ||
| 928 | + } | ||
| 929 | + } | ||
| 930 | + // A user of the school next door is not reachable from this school. | ||
| 931 | + for (path, body) in [ | ||
| 932 | + ( | ||
| 933 | + "/schools/p4a/admin-password", | ||
| 934 | + json!({ "username": "onlyb", "password": "secret2" }), | ||
| 935 | + ), | ||
| 936 | + ("/schools/p4a/enter", json!({ "username": "onlyb" })), | ||
| 937 | + ] { | ||
| 938 | + let res = send(&app, "POST", path, Some(&builder), Some(body)).await; | ||
| 939 | + assert_eq!( | ||
| 940 | + res.status, | ||
| 941 | + StatusCode::NOT_FOUND, | ||
| 942 | + "{path} reached across schools: {:?}", | ||
| 943 | + res.body | ||
| 944 | + ); | ||
| 945 | + } | ||
| 946 | + | ||
| 947 | + // Two live sessions for the same admin; a reset must kill both. | ||
| 948 | + let s1 = school_login(&app, "p4a", "admin", "secret1") | ||
| 949 | + .await | ||
| 950 | + .cookie | ||
| 951 | + .expect("session 1"); | ||
| 952 | + let s2 = school_login(&app, "p4a", "admin", "secret1") | ||
| 953 | + .await | ||
| 954 | + .cookie | ||
| 955 | + .expect("session 2"); | ||
| 956 | + assert_ne!(s1, s2, "the harness reused one session"); | ||
| 957 | + // A bystander session in the same school must survive. | ||
| 958 | + let tea = school_login(&app, "p4a", "tea", "secret1") | ||
| 959 | + .await | ||
| 960 | + .cookie | ||
| 961 | + .expect("teacher session"); | ||
| 962 | + | ||
| 963 | + let reset = send( | ||
| 964 | + &app, | ||
| 965 | + "POST", | ||
| 966 | + "/schools/p4a/admin-password", | ||
| 967 | + Some(&builder), | ||
| 968 | + Some(json!({ "username": "admin", "password": "secret2" })), | ||
| 969 | + ) | ||
| 970 | + .await; | ||
| 971 | + assert_eq!(reset.status, StatusCode::NO_CONTENT); | ||
| 972 | + for (n, cookie) in [(1, &s1), (2, &s2)] { | ||
| 973 | + assert_eq!( | ||
| 974 | + send(&app, "GET", "/auth/me", Some(cookie), None).await.status, | ||
| 975 | + StatusCode::UNAUTHORIZED, | ||
| 976 | + "session {n} survived the password reset" | ||
| 977 | + ); | ||
| 978 | + } | ||
| 979 | + assert_eq!( | ||
| 980 | + send(&app, "GET", "/auth/me", Some(&tea), None).await.status, | ||
| 981 | + StatusCode::OK, | ||
| 982 | + "the reset revoked a bystander's session" | ||
| 983 | + ); | ||
| 984 | + | ||
| 985 | + // `enter` on a suspended school is 403; `admin-password` still works. | ||
| 986 | + assert_eq!( | ||
| 987 | + send( | ||
| 988 | + &app, | ||
| 989 | + "PATCH", | ||
| 990 | + "/schools/p4a", | ||
| 991 | + Some(&builder), | ||
| 992 | + Some(json!({ "status": "suspended" })), | ||
| 993 | + ) | ||
| 994 | + .await | ||
| 995 | + .status, | ||
| 996 | + StatusCode::OK | ||
| 997 | + ); | ||
| 998 | + let entered = send( | ||
| 999 | + &app, | ||
| 1000 | + "POST", | ||
| 1001 | + "/schools/p4a/enter", | ||
| 1002 | + Some(&builder), | ||
| 1003 | + Some(json!({ "username": "admin" })), | ||
| 1004 | + ) | ||
| 1005 | + .await; | ||
| 1006 | + assert_eq!( | ||
| 1007 | + entered.status, | ||
| 1008 | + StatusCode::FORBIDDEN, | ||
| 1009 | + "enter opened a suspended school: {:?}", | ||
| 1010 | + entered.body | ||
| 1011 | + ); | ||
| 1012 | + assert!( | ||
| 1013 | + entered.cookie.is_none(), | ||
| 1014 | + "a refused enter still set a school cookie" | ||
| 1015 | + ); | ||
| 1016 | + assert_eq!( | ||
| 1017 | + send( | ||
| 1018 | + &app, | ||
| 1019 | + "POST", | ||
| 1020 | + "/schools/p4a/admin-password", | ||
| 1021 | + Some(&builder), | ||
| 1022 | + Some(json!({ "username": "admin", "password": "secret3" })), | ||
| 1023 | + ) | ||
| 1024 | + .await | ||
| 1025 | + .status, | ||
| 1026 | + StatusCode::NO_CONTENT, | ||
| 1027 | + "a lockout fix must still work on a suspended school" | ||
| 1028 | + ); | ||
| 1029 | +} | ||
| 1030 | + | ||
| 1031 | +/// Claim 5: builder session hygiene — logout is a revocation, and neither | ||
| 1032 | +/// principal's token works under the other's prefix. | ||
| 1033 | +#[tokio::test] | ||
| 1034 | +async fn probe_builder_session_hygiene() { | ||
| 1035 | + let (app, _db, _tenants) = deployment().await; | ||
| 1036 | + let builder = builder_login(&app).await; | ||
| 1037 | + let student = login(&app, "veli").await; | ||
| 1038 | + | ||
| 1039 | + let builder_token = builder | ||
| 1040 | + .trim_start_matches("session=builder.") | ||
| 1041 | + .to_string(); | ||
| 1042 | + let student_token = cookie_token(&student).to_string(); | ||
| 1043 | + | ||
| 1044 | + // The builder's own token, worn as a school cookie. | ||
| 1045 | + for uri in ["/auth/me", "/users", "/notes"] { | ||
| 1046 | + let res = send( | ||
| 1047 | + &app, | ||
| 1048 | + "GET", | ||
| 1049 | + uri, | ||
| 1050 | + Some(&format!("session={DEMO_SLUG}.{builder_token}")), | ||
| 1051 | + None, | ||
| 1052 | + ) | ||
| 1053 | + .await; | ||
| 1054 | + assert_eq!( | ||
| 1055 | + res.status, | ||
| 1056 | + StatusCode::UNAUTHORIZED, | ||
| 1057 | + "{uri} accepted a builder token under a school prefix" | ||
| 1058 | + ); | ||
| 1059 | + } | ||
| 1060 | + // And a school token worn as a builder cookie. | ||
| 1061 | + for uri in ["/builder/me", "/schools"] { | ||
| 1062 | + let res = send( | ||
| 1063 | + &app, | ||
| 1064 | + "GET", | ||
| 1065 | + uri, | ||
| 1066 | + Some(&format!("session=builder.{student_token}")), | ||
| 1067 | + None, | ||
| 1068 | + ) | ||
| 1069 | + .await; | ||
| 1070 | + assert_eq!( | ||
| 1071 | + res.status, | ||
| 1072 | + StatusCode::UNAUTHORIZED, | ||
| 1073 | + "{uri} accepted a school token under the builder prefix" | ||
| 1074 | + ); | ||
| 1075 | + } | ||
| 1076 | + | ||
| 1077 | + // Logout is a server-side revocation: the same cookie is dead everywhere. | ||
| 1078 | + assert_eq!( | ||
| 1079 | + send(&app, "POST", "/builder/logout", Some(&builder), None) | ||
| 1080 | + .await | ||
| 1081 | + .status, | ||
| 1082 | + StatusCode::NO_CONTENT | ||
| 1083 | + ); | ||
| 1084 | + for (method, uri, body) in [ | ||
| 1085 | + ("GET", "/builder/me", None), | ||
| 1086 | + ("GET", "/schools", None), | ||
| 1087 | + ( | ||
| 1088 | + "POST", | ||
| 1089 | + "/schools", | ||
| 1090 | + Some(json!({ | ||
| 1091 | + "slug": "p5ghost", | ||
| 1092 | + "name": "ghost", | ||
| 1093 | + "admin_username": "admin", | ||
| 1094 | + "admin_password": "secret1" | ||
| 1095 | + })), | ||
| 1096 | + ), | ||
| 1097 | + ("DELETE", "/schools/demo", None), | ||
| 1098 | + ] { | ||
| 1099 | + let res = send(&app, method, uri, Some(&builder), body).await; | ||
| 1100 | + assert_eq!( | ||
| 1101 | + res.status, | ||
| 1102 | + StatusCode::UNAUTHORIZED, | ||
| 1103 | + "{method} {uri} accepted a logged-out builder cookie" | ||
| 1104 | + ); | ||
| 1105 | + } | ||
| 1106 | + // …and nothing was created or destroyed by those calls. | ||
| 1107 | + let fresh = builder_login(&app).await; | ||
| 1108 | + let list = send(&app, "GET", "/schools", Some(&fresh), None).await; | ||
| 1109 | + assert!( | ||
| 1110 | + !slugs(&list.body).contains(&"p5ghost".to_string()), | ||
| 1111 | + "a logged-out builder created a school" | ||
| 1112 | + ); | ||
| 1113 | + assert!( | ||
| 1114 | + slugs(&list.body).contains(&DEMO_SLUG.to_string()), | ||
| 1115 | + "a logged-out builder deleted the demo school" | ||
| 1116 | + ); | ||
| 1117 | + // Logout is idempotent and safe without a cookie. | ||
| 1118 | + assert_eq!( | ||
| 1119 | + send(&app, "POST", "/builder/logout", None, None).await.status, | ||
| 1120 | + StatusCode::NO_CONTENT | ||
| 1121 | + ); | ||
| 1122 | +} | ||
| 1123 | + | ||
| 1124 | +/// Claim 6: two creates of one slug, concurrently, leave exactly one school. | ||
| 1125 | +#[tokio::test] | ||
| 1126 | +async fn probe_concurrent_creates_of_one_slug_leave_one_school() { | ||
| 1127 | + let (app, _db, _tenants) = deployment().await; | ||
| 1128 | + let builder = builder_login(&app).await; | ||
| 1129 | + | ||
| 1130 | + let (first, second) = tokio::join!( | ||
| 1131 | + create_school(&app, &builder, "p6race", "secret1"), | ||
| 1132 | + create_school(&app, &builder, "p6race", "secret2"), | ||
| 1133 | + ); | ||
| 1134 | + let statuses = [first.status, second.status]; | ||
| 1135 | + let created = statuses | ||
| 1136 | + .iter() | ||
| 1137 | + .filter(|s| **s == StatusCode::CREATED) | ||
| 1138 | + .count(); | ||
| 1139 | + assert_eq!( | ||
| 1140 | + created, 1, | ||
| 1141 | + "concurrent creates of one slug: {statuses:?} ({:?} / {:?})", | ||
| 1142 | + first.body, second.body | ||
| 1143 | + ); | ||
| 1144 | + | ||
| 1145 | + let list = send(&app, "GET", "/schools", Some(&builder), None).await; | ||
| 1146 | + let count = slugs(&list.body) | ||
| 1147 | + .iter() | ||
| 1148 | + .filter(|s| s.as_str() == "p6race") | ||
| 1149 | + .count(); | ||
| 1150 | + assert_eq!(count, 1, "the registry holds {count} rows for p6race"); | ||
| 1151 | + | ||
| 1152 | + // Exactly one of the two admin passwords opens it. | ||
| 1153 | + let mut opens = 0; | ||
| 1154 | + for pass in ["secret1", "secret2"] { | ||
| 1155 | + if school_login(&app, "p6race", "admin", pass).await.status == StatusCode::OK { | ||
| 1156 | + opens += 1; | ||
| 1157 | + } | ||
| 1158 | + } | ||
| 1159 | + assert_eq!(opens, 1, "{opens} of the two admin passwords open p6race"); | ||
| 1160 | +} | ||
| 1161 | + | ||
| 1162 | +/// A `surreal start` child that dies with the test. | ||
| 1163 | +struct Server(std::process::Child); | ||
| 1164 | +impl Drop for Server { | ||
| 1165 | + fn drop(&mut self) { | ||
| 1166 | + let _ = self.0.kill(); | ||
| 1167 | + let _ = self.0.wait(); | ||
| 1168 | + } | ||
| 1169 | +} | ||
| 1170 | + | ||
| 1171 | +/// Claim 1/2 driven against a **real remote deployment** — the mode every test | ||
| 1172 | +/// above skips, and the only one where `DEFINE DATABASE` / `REMOVE DATABASE` | ||
| 1173 | +/// actually run. `ata-koleji` is the slug the OpenAPI schema advertises. | ||
| 1174 | +#[tokio::test] | ||
| 1175 | +async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() { | ||
| 1176 | + let bin = std::path::PathBuf::from(std::env::var("HOME").unwrap()).join(".surrealdb/surreal"); | ||
| 1177 | + if !bin.exists() { | ||
| 1178 | + eprintln!("skipped: no surreal binary at {}", bin.display()); | ||
| 1179 | + return; | ||
| 1180 | + } | ||
| 1181 | + let port = 18441u16; | ||
| 1182 | + let _server = Server( | ||
| 1183 | + std::process::Command::new(&bin) | ||
| 1184 | + .args([ | ||
| 1185 | + "start", | ||
| 1186 | + "--user", | ||
| 1187 | + "root", | ||
| 1188 | + "--pass", | ||
| 1189 | + "root", | ||
| 1190 | + "--bind", | ||
| 1191 | + &format!("127.0.0.1:{port}"), | ||
| 1192 | + "memory", | ||
| 1193 | + ]) | ||
| 1194 | + .stdout(std::process::Stdio::null()) | ||
| 1195 | + .stderr(std::process::Stdio::null()) | ||
| 1196 | + .spawn() | ||
| 1197 | + .expect("spawn surreal"), | ||
| 1198 | + ); | ||
| 1199 | + for _ in 0..100 { | ||
| 1200 | + if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() { | ||
| 1201 | + break; | ||
| 1202 | + } | ||
| 1203 | + tokio::time::sleep(std::time::Duration::from_millis(100)).await; | ||
| 1204 | + } | ||
| 1205 | + | ||
| 1206 | + let files = tempfile::tempdir().unwrap(); | ||
| 1207 | + let cfg = hezarfen_backend::config::Config { | ||
| 1208 | + host: "127.0.0.1".into(), | ||
| 1209 | + port: 0, | ||
| 1210 | + db_url: format!("ws://127.0.0.1:{port}"), | ||
| 1211 | + db_user: "root".into(), | ||
| 1212 | + db_pass: "root".into(), | ||
| 1213 | + db_ns: "hezarfen".into(), | ||
| 1214 | + db_name: "control".into(), | ||
| 1215 | + files_path: files.path().display().to_string(), | ||
| 1216 | + cookie_secure: false, | ||
| 1217 | + rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), | ||
| 1218 | + chatbot_per_minute: 0, | ||
| 1219 | + builder_username: Some(BUILDER_USER.into()), | ||
| 1220 | + builder_password: Some(BUILDER_PASS.into()), | ||
| 1221 | + ai_quic_addr: None, | ||
| 1222 | + ai_shared_token: None, | ||
| 1223 | + ai_tls_cert: None, | ||
| 1224 | + ai_tls_key: None, | ||
| 1225 | + ai_request_timeout_secs: 30, | ||
| 1226 | + }; | ||
| 1227 | + let tenants = hezarfen_backend::database::init(&cfg) | ||
| 1228 | + .await | ||
| 1229 | + .expect("remote deployment"); | ||
| 1230 | + let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { | ||
| 1231 | + db: tenants.control().clone(), | ||
| 1232 | + tenants: tenants.clone(), | ||
| 1233 | + files_path: files.path().to_path_buf(), | ||
| 1234 | + cookie_secure: false, | ||
| 1235 | + rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), | ||
| 1236 | + chatbot_limit: Default::default(), | ||
| 1237 | + exam_presence: Default::default(), | ||
| 1238 | + board_hub: Default::default(), | ||
| 1239 | + db_up: Default::default(), | ||
| 1240 | + ai: None, | ||
| 1241 | + }); | ||
| 1242 | + | ||
| 1243 | + let builder = builder_login(&app).await; | ||
| 1244 | + // A plain slug proves the harness itself works. | ||
| 1245 | + let plain = create_school(&app, &builder, "atakoleji", "secret1").await; | ||
| 1246 | + assert_eq!( | ||
| 1247 | + plain.status, | ||
| 1248 | + StatusCode::CREATED, | ||
| 1249 | + "plain slug: {:?}", | ||
| 1250 | + plain.body | ||
| 1251 | + ); | ||
| 1252 | + assert_eq!( | ||
| 1253 | + school_login(&app, "atakoleji", "admin", "secret1") | ||
| 1254 | + .await | ||
| 1255 | + .status, | ||
| 1256 | + StatusCode::OK | ||
| 1257 | + ); | ||
| 1258 | + | ||
| 1259 | + // The advertised, hyphenated slug. Collect the whole chain before asserting, | ||
| 1260 | + // so a failure reports the state the deployment is left in. | ||
| 1261 | + let made = create_school(&app, &builder, "ata-koleji", "secret1").await; | ||
| 1262 | + let listed = |body: &Value| slugs(body).contains(&"ata-koleji".to_string()); | ||
| 1263 | + let after_create = send(&app, "GET", "/schools", Some(&builder), None).await; | ||
| 1264 | + let retry = create_school(&app, &builder, "ata-koleji", "secret1").await; | ||
| 1265 | + let login = school_login(&app, "ata-koleji", "admin", "secret1").await; | ||
| 1266 | + let deleted = send(&app, "DELETE", "/schools/ata-koleji", Some(&builder), None).await; | ||
| 1267 | + let after_delete = send(&app, "GET", "/schools", Some(&builder), None).await; | ||
| 1268 | + let login_after_delete = school_login(&app, "ata-koleji", "admin", "secret1").await; | ||
| 1269 | + | ||
| 1270 | + assert_eq!( | ||
| 1271 | + made.status, | ||
| 1272 | + StatusCode::CREATED, | ||
| 1273 | + "POST /schools ata-koleji (the slug the OpenAPI example advertises) -> {} {:?}; \ | ||
| 1274 | + registry lists it: {}; retry -> {}; DELETE -> {} {:?}; still listed after DELETE: {}; \ | ||
| 1275 | + admin login -> {}", | ||
| 1276 | + made.status, | ||
| 1277 | + made.body, | ||
| 1278 | + listed(&after_create.body), | ||
| 1279 | + retry.status, | ||
| 1280 | + deleted.status, | ||
| 1281 | + deleted.body, | ||
| 1282 | + listed(&after_delete.body), | ||
| 1283 | + login.status, | ||
| 1284 | + ); | ||
| 1285 | + assert_eq!(retry.status, StatusCode::CONFLICT, "a made school is taken"); | ||
| 1286 | + assert_eq!(login.status, StatusCode::OK, "the admin logs into the hyphenated school"); | ||
| 1287 | + assert_eq!(deleted.status, StatusCode::NO_CONTENT); | ||
| 1288 | + assert!(!listed(&after_delete.body)); | ||
| 1289 | + assert_eq!( | ||
| 1290 | + login_after_delete.status, | ||
| 1291 | + StatusCode::UNAUTHORIZED, | ||
| 1292 | + "a deleted school is unknown at login" | ||
| 1293 | + ); | ||
| 1294 | +} | ||