Isolation probes across two schools
Browse files at this commit1b12ff7dcf0c946e67771ded377b1322ce3a4e98Parent: f826977- test
- isolation probes across two schools
- the builder seed is both-or-neither
4 changed files +1140 -5
- src/database.rs +32 -0
- src/tenant.rs +8 -5
- tests/e2e.rs +119 -0
- tests/integration.rs +981 -0
src/database.rsmodified+32 -0
| @@ -297,6 +297,38 @@ pub async fn init_mem_tenants() -> Result<Tenants, AppError> { | |||
| 297 | /// sibling's burst pushes a delete clean out of the window it is meant to land | 297 | /// sibling's burst pushes a delete clean out of the window it is meant to land |
| 298 | /// in (measured 4 runs in 4 at 3 of 6 failing their own "the race was reached" | 298 | /// in (measured 4 runs in 4 at 3 of 6 failing their own "the race was reached" |
| 299 | /// guard). Serialized, the plain documented command works. | 299 | /// guard). Serialized, the plain documented command works. |
| 300 | +#[cfg(test)] | ||
| 301 | +mod builder_seed_tests { | ||
| 302 | + use super::builder_credentials; | ||
| 303 | + use crate::config::Config; | ||
| 304 | + | ||
| 305 | + fn cfg(username: Option<&str>, password: Option<&str>) -> Config { | ||
| 306 | + let mut cfg = Config::from_env(); | ||
| 307 | + cfg.builder_username = username.map(str::to_string); | ||
| 308 | + cfg.builder_password = password.map(str::to_string); | ||
| 309 | + cfg | ||
| 310 | + } | ||
| 311 | + | ||
| 312 | + #[tokio::test] | ||
| 313 | + async fn the_builder_seed_is_both_or_neither() { | ||
| 314 | + assert!(builder_credentials(&cfg(None, None)).unwrap().is_none()); | ||
| 315 | + assert!( | ||
| 316 | + builder_credentials(&cfg(Some("builder"), Some("secret1"))) | ||
| 317 | + .unwrap() | ||
| 318 | + .is_some() | ||
| 319 | + ); | ||
| 320 | + // Half a pair aborts startup: a deployment with no builder has nobody | ||
| 321 | + // who can create the first school, and a silent run would hide that. | ||
| 322 | + assert!(builder_credentials(&cfg(Some("builder"), None)).is_err()); | ||
| 323 | + assert!(builder_credentials(&cfg(None, Some("secret1"))).is_err()); | ||
| 324 | + // A pair that is set but invalid aborts too, naming the variable. | ||
| 325 | + match builder_credentials(&cfg(Some("!"), Some("secret1"))) { | ||
| 326 | + Err(err) => assert!(err.to_string().contains("BUILDER_USERNAME"), "{err}"), | ||
| 327 | + Ok(_) => panic!("an invalid BUILDER_USERNAME must abort startup"), | ||
| 328 | + } | ||
| 329 | + } | ||
| 330 | +} | ||
| 331 | + | ||
| 300 | #[cfg(test)] | 332 | #[cfg(test)] |
| 301 | pub(crate) static RACE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); | 333 | pub(crate) static RACE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); |
| 302 | 334 | ||
src/tenant.rsmodified+8 -5
| @@ -98,10 +98,6 @@ impl std::fmt::Display for Slug { | |||
| 98 | } | 98 | } |
| 99 | } | 99 | } |
| 100 | 100 | ||
| 101 | -/// Whether a school may be reached at all. Suspension is immediate and total: | ||
| 102 | -/// [`Tenants::get`] refuses before any handler runs, and login is no exception. | ||
| 103 | -/// | ||
| 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 | 101 | /// 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 | 102 | /// 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, | 103 | /// unquoted `ata-koleji` parses as a subtraction, `2024school` as a duration, |
| @@ -111,6 +107,10 @@ pub fn quoted_ident(slug: &Slug) -> String { | |||
| 111 | format!("`{}`", slug.as_str()) | 107 | format!("`{}`", slug.as_str()) |
| 112 | } | 108 | } |
| 113 | 109 | ||
| 110 | +/// Whether a school may be reached at all. Suspension is immediate and total: | ||
| 111 | +/// [`Tenants::get`] refuses before any handler runs, and login is no exception. | ||
| 112 | +/// | ||
| 113 | +/// Stored as a bare lowercase string, like [`crate::domain::role::Role`]. | ||
| 114 | #[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue, Serialize)] | 114 | #[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue, Serialize)] |
| 115 | #[surreal(untagged, rename_all = "lowercase")] | 115 | #[surreal(untagged, rename_all = "lowercase")] |
| 116 | #[serde(rename_all = "lowercase")] | 116 | #[serde(rename_all = "lowercase")] |
| @@ -403,7 +403,10 @@ impl Tenants { | |||
| 403 | let db = match &*self.mode { | 403 | let db = match &*self.mode { |
| 404 | Mode::Remote { .. } => { | 404 | Mode::Remote { .. } => { |
| 405 | self.control | 405 | self.control |
| 406 | - .query(format!("DEFINE DATABASE IF NOT EXISTS {}", quoted_ident(slug))) | 406 | + .query(format!( |
| 407 | + "DEFINE DATABASE IF NOT EXISTS {}", | ||
| 408 | + quoted_ident(slug) | ||
| 409 | + )) | ||
| 407 | .await? | 410 | .await? |
| 408 | .check()?; | 411 | .check()?; |
| 409 | self.connect(slug).await? | 412 | self.connect(slug).await? |
tests/e2e.rsmodified+119 -0
| @@ -3766,3 +3766,122 @@ async fn a_builder_creates_a_school_over_tcp_and_its_admin_logs_in() { | |||
| 3766 | StatusCode::UNAUTHORIZED | 3766 | StatusCode::UNAUTHORIZED |
| 3767 | ); | 3767 | ); |
| 3768 | } | 3768 | } |
| 3769 | + | ||
| 3770 | +// ---- multi-school: suspension refuses sockets too (REFUTE lane B) ----------- | ||
| 3771 | + | ||
| 3772 | +/// Open a board room, optionally authenticated. Same shape as [`ws_open`]. | ||
| 3773 | +async fn board_ws_open(base: &str, board_id: &str, cookie: Option<&str>) -> Result<WsStream, u16> { | ||
| 3774 | + let url = format!("{}/boards/{board_id}/ws", base.replace("http://", "ws://")); | ||
| 3775 | + let mut request = url.into_client_request().unwrap(); | ||
| 3776 | + if let Some(cookie) = cookie { | ||
| 3777 | + request | ||
| 3778 | + .headers_mut() | ||
| 3779 | + .insert("cookie", cookie.parse().unwrap()); | ||
| 3780 | + } | ||
| 3781 | + match connect_async(request).await { | ||
| 3782 | + Ok((ws, _)) => Ok(ws), | ||
| 3783 | + Err(tokio_tungstenite::tungstenite::Error::Http(response)) => { | ||
| 3784 | + Err(response.status().as_u16()) | ||
| 3785 | + } | ||
| 3786 | + Err(other) => panic!("unexpected handshake failure: {other}"), | ||
| 3787 | + } | ||
| 3788 | +} | ||
| 3789 | + | ||
| 3790 | +/// Invariant 2, socket half: after the vendor suspends a school over the real | ||
| 3791 | +/// builder API, its live cookies stop opening WebSockets — both the whiteboard | ||
| 3792 | +/// room and the exam room — and start working again on a resume. | ||
| 3793 | +#[tokio::test] | ||
| 3794 | +async fn probe_a_suspended_school_refuses_websocket_upgrades() { | ||
| 3795 | + let (base, db) = spawn_server().await; | ||
| 3796 | + | ||
| 3797 | + let teacher = client(); | ||
| 3798 | + register(&teacher, &base, "hoca").await; | ||
| 3799 | + promote(&db, "hoca", "teacher").await; | ||
| 3800 | + login(&teacher, &base, "hoca").await; | ||
| 3801 | + let cookie = raw_session_cookie(&base, "hoca").await; | ||
| 3802 | + | ||
| 3803 | + let res = teacher | ||
| 3804 | + .post(format!("{base}/boards")) | ||
| 3805 | + .json(&json!({ "title": "room", "participants": [] })) | ||
| 3806 | + .send() | ||
| 3807 | + .await | ||
| 3808 | + .unwrap(); | ||
| 3809 | + assert_eq!(res.status(), StatusCode::CREATED); | ||
| 3810 | + let board = res.json::<Value>().await.unwrap()["id"] | ||
| 3811 | + .as_str() | ||
| 3812 | + .unwrap() | ||
| 3813 | + .to_string(); | ||
| 3814 | + | ||
| 3815 | + // Alive: the socket opens. | ||
| 3816 | + let ws = board_ws_open(&base, &board, Some(&cookie)).await; | ||
| 3817 | + assert!(ws.is_ok(), "board socket before suspension: {:?}", ws.err()); | ||
| 3818 | + drop(ws); | ||
| 3819 | + | ||
| 3820 | + // The vendor suspends the school through its own API. | ||
| 3821 | + let vendor = client(); | ||
| 3822 | + let res = vendor | ||
| 3823 | + .post(format!("{base}/builder/login")) | ||
| 3824 | + .json(&json!({ "username": "operator", "password": "secret1" })) | ||
| 3825 | + .send() | ||
| 3826 | + .await | ||
| 3827 | + .unwrap(); | ||
| 3828 | + assert_eq!(res.status(), StatusCode::OK); | ||
| 3829 | + let res = vendor | ||
| 3830 | + .patch(format!("{base}/schools/demo")) | ||
| 3831 | + .json(&json!({ "status": "suspended" })) | ||
| 3832 | + .send() | ||
| 3833 | + .await | ||
| 3834 | + .unwrap(); | ||
| 3835 | + assert_eq!(res.status(), StatusCode::OK, "suspend demo"); | ||
| 3836 | + assert_eq!(res.json::<Value>().await.unwrap()["status"], "suspended"); | ||
| 3837 | + | ||
| 3838 | + // The very next HTTP request on the already-issued cookie. | ||
| 3839 | + assert_eq!( | ||
| 3840 | + teacher | ||
| 3841 | + .get(format!("{base}/auth/me")) | ||
| 3842 | + .send() | ||
| 3843 | + .await | ||
| 3844 | + .unwrap() | ||
| 3845 | + .status(), | ||
| 3846 | + StatusCode::FORBIDDEN, | ||
| 3847 | + "a live cookie after suspension" | ||
| 3848 | + ); | ||
| 3849 | + | ||
| 3850 | + // The whiteboard socket is refused before the upgrade. | ||
| 3851 | + assert_eq!( | ||
| 3852 | + board_ws_open(&base, &board, Some(&cookie)).await.err(), | ||
| 3853 | + Some(403), | ||
| 3854 | + "the board socket opened for a suspended school" | ||
| 3855 | + ); | ||
| 3856 | + // So is the exam room, on any id. | ||
| 3857 | + assert_eq!( | ||
| 3858 | + ws_open(&base, "01J8XZ0K3Q8G7X2M4N5P6R7S8T", Some(&cookie)) | ||
| 3859 | + .await | ||
| 3860 | + .err(), | ||
| 3861 | + Some(403), | ||
| 3862 | + "the exam socket opened for a suspended school" | ||
| 3863 | + ); | ||
| 3864 | + | ||
| 3865 | + // Resume: the same cookie, the same socket. | ||
| 3866 | + let res = vendor | ||
| 3867 | + .patch(format!("{base}/schools/demo")) | ||
| 3868 | + .json(&json!({ "status": "active" })) | ||
| 3869 | + .send() | ||
| 3870 | + .await | ||
| 3871 | + .unwrap(); | ||
| 3872 | + assert_eq!(res.status(), StatusCode::OK, "resume demo"); | ||
| 3873 | + assert_eq!( | ||
| 3874 | + teacher | ||
| 3875 | + .get(format!("{base}/auth/me")) | ||
| 3876 | + .send() | ||
| 3877 | + .await | ||
| 3878 | + .unwrap() | ||
| 3879 | + .status(), | ||
| 3880 | + StatusCode::OK, | ||
| 3881 | + "the same cookie after a resume" | ||
| 3882 | + ); | ||
| 3883 | + assert!( | ||
| 3884 | + board_ws_open(&base, &board, Some(&cookie)).await.is_ok(), | ||
| 3885 | + "the board socket after a resume" | ||
| 3886 | + ); | ||
| 3887 | +} | ||
tests/integration.rsmodified+981 -0
| @@ -27357,3 +27357,984 @@ async fn course_note_rag_outputs_read_and_delete() { | |||
| 27357 | .await; | 27357 | .await; |
| 27358 | assert_eq!(common::total(&list.body), 0, "{}", list.body); | 27358 | assert_eq!(common::total(&list.body), 0, "{}", list.body); |
| 27359 | } | 27359 | } |
| 27360 | + | ||
| 27361 | +// ========================================================================= | ||
| 27362 | +// Multi-school isolation probes (REFUTE lane B). Two schools, same usernames. | ||
| 27363 | +// ========================================================================= | ||
| 27364 | + | ||
| 27365 | +use hezarfen_backend::tenant::{DEMO_SLUG, SchoolStatus, Slug, Tenants}; | ||
| 27366 | + | ||
| 27367 | +/// Demo (school A) plus a second school "beta" (school B), and the registry. | ||
| 27368 | +async fn two_schools() -> ( | ||
| 27369 | + axum::Router, | ||
| 27370 | + hezarfen_backend::database::Database, | ||
| 27371 | + hezarfen_backend::database::Database, | ||
| 27372 | + Tenants, | ||
| 27373 | +) { | ||
| 27374 | + let (app, db_a, tenants) = common::app_and_tenants().await; | ||
| 27375 | + let slug_b = Slug::try_new("beta").expect("slug"); | ||
| 27376 | + let db_b = tenants | ||
| 27377 | + .create(&slug_b, "Beta Koleji") | ||
| 27378 | + .await | ||
| 27379 | + .expect("school B"); | ||
| 27380 | + (app, db_a, db_b, tenants) | ||
| 27381 | +} | ||
| 27382 | + | ||
| 27383 | +/// Every list surface that takes no path parameter — the sweep target. | ||
| 27384 | +const LIST_ROUTES: [&str; 19] = [ | ||
| 27385 | + "/users", | ||
| 27386 | + "/notes", | ||
| 27387 | + "/messages", | ||
| 27388 | + "/events", | ||
| 27389 | + "/appointments", | ||
| 27390 | + "/appointments/slots", | ||
| 27391 | + "/courses", | ||
| 27392 | + "/courses/me", | ||
| 27393 | + "/classes", | ||
| 27394 | + "/exams", | ||
| 27395 | + "/meals/menus", | ||
| 27396 | + "/payments/plans", | ||
| 27397 | + "/work/me", | ||
| 27398 | + "/pomodoro/me", | ||
| 27399 | + "/questions", | ||
| 27400 | + "/bank-questions", | ||
| 27401 | + "/terms", | ||
| 27402 | + "/boards", | ||
| 27403 | + "/chatbot/threads", | ||
| 27404 | +]; | ||
| 27405 | + | ||
| 27406 | +/// Fill school B with one row of as many kinds as a single admin can mint. | ||
| 27407 | +async fn seed_school_b(app: &axum::Router, cookie: &str) -> serde_json::Value { | ||
| 27408 | + let course = create_course(app, cookie, "B Course").await; | ||
| 27409 | + let subject = create_subject(app, cookie, &course, "B Subject").await; | ||
| 27410 | + let exam = create_exam(app, cookie, &course, "B Exam", "quiz").await; | ||
| 27411 | + let note = send( | ||
| 27412 | + app, | ||
| 27413 | + "POST", | ||
| 27414 | + "/notes", | ||
| 27415 | + Some(cookie), | ||
| 27416 | + Some(json!({ "title": "b-note", "content": "secret of B" })), | ||
| 27417 | + ) | ||
| 27418 | + .await; | ||
| 27419 | + assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); | ||
| 27420 | + let event = send( | ||
| 27421 | + app, | ||
| 27422 | + "POST", | ||
| 27423 | + "/events", | ||
| 27424 | + Some(cookie), | ||
| 27425 | + Some(json!({ "title": "b-event", "description": "B only" })), | ||
| 27426 | + ) | ||
| 27427 | + .await; | ||
| 27428 | + assert_eq!(event.status, StatusCode::CREATED, "{}", event.body); | ||
| 27429 | + let class = send( | ||
| 27430 | + app, | ||
| 27431 | + "POST", | ||
| 27432 | + "/classes", | ||
| 27433 | + Some(cookie), | ||
| 27434 | + Some(json!({ "name": "9-B" })), | ||
| 27435 | + ) | ||
| 27436 | + .await; | ||
| 27437 | + assert_eq!(class.status, StatusCode::CREATED, "{}", class.body); | ||
| 27438 | + let board = send( | ||
| 27439 | + app, | ||
| 27440 | + "POST", | ||
| 27441 | + "/boards", | ||
| 27442 | + Some(cookie), | ||
| 27443 | + Some(json!({ "title": "b-board", "participants": [] })), | ||
| 27444 | + ) | ||
| 27445 | + .await; | ||
| 27446 | + assert_eq!(board.status, StatusCode::CREATED, "{}", board.body); | ||
| 27447 | + let course_note = send( | ||
| 27448 | + app, | ||
| 27449 | + "POST", | ||
| 27450 | + "/course-notes", | ||
| 27451 | + Some(cookie), | ||
| 27452 | + Some(json!({ "course": course, "title": "b-cnote", "content": "body" })), | ||
| 27453 | + ) | ||
| 27454 | + .await; | ||
| 27455 | + assert_eq!( | ||
| 27456 | + course_note.status, | ||
| 27457 | + StatusCode::CREATED, | ||
| 27458 | + "{}", | ||
| 27459 | + course_note.body | ||
| 27460 | + ); | ||
| 27461 | + let bank = send( | ||
| 27462 | + app, | ||
| 27463 | + "POST", | ||
| 27464 | + "/bank-questions", | ||
| 27465 | + Some(cookie), | ||
| 27466 | + Some( | ||
| 27467 | + json!({ "subject_id": subject, "text": "B?", "kind": "choice", "points": 10, | ||
| 27468 | + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], | ||
| 27469 | + "correct": "c1" }), | ||
| 27470 | + ), | ||
| 27471 | + ) | ||
| 27472 | + .await; | ||
| 27473 | + assert_eq!(bank.status, StatusCode::CREATED, "{}", bank.body); | ||
| 27474 | + let thread = send( | ||
| 27475 | + app, | ||
| 27476 | + "POST", | ||
| 27477 | + "/chatbot/threads", | ||
| 27478 | + Some(cookie), | ||
| 27479 | + Some(json!({})), | ||
| 27480 | + ) | ||
| 27481 | + .await; | ||
| 27482 | + assert_eq!(thread.status, StatusCode::CREATED, "{}", thread.body); | ||
| 27483 | + | ||
| 27484 | + let idf = |what: &str, v: &serde_json::Value| -> String { | ||
| 27485 | + v["id"] | ||
| 27486 | + .as_str() | ||
| 27487 | + .unwrap_or_else(|| panic!("{what} response has no id: {v}")) | ||
| 27488 | + .to_string() | ||
| 27489 | + }; | ||
| 27490 | + json!({ | ||
| 27491 | + "course": course, | ||
| 27492 | + "subject": subject, | ||
| 27493 | + "exam": exam, | ||
| 27494 | + "note": idf("note", ¬e.body), | ||
| 27495 | + "event": idf("event", &event.body), | ||
| 27496 | + "class": idf("class", &class.body["class"]), | ||
| 27497 | + "board": idf("board", &board.body), | ||
| 27498 | + "course_note": idf("course_note", &course_note.body), | ||
| 27499 | + "bank": idf("bank", &bank.body), | ||
| 27500 | + "thread": idf("thread", &thread.body), | ||
| 27501 | + }) | ||
| 27502 | +} | ||
| 27503 | + | ||
| 27504 | +/// Invariant 1, read side: with A's cookie every list surface answers with A's | ||
| 27505 | +/// own rows only — the totals do not move when B fills up. | ||
| 27506 | +#[tokio::test] | ||
| 27507 | +async fn probe_cross_school_lists_show_only_own_rows() { | ||
| 27508 | + 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; | ||
| 27510 | + let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | ||
| 27511 | + | ||
| 27512 | + let mut before = Vec::new(); | ||
| 27513 | + for route in LIST_ROUTES { | ||
| 27514 | + let res = send(&app, "GET", route, Some(&a), None).await; | ||
| 27515 | + assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); | ||
| 27516 | + before.push(common::total(&res.body)); | ||
| 27517 | + } | ||
| 27518 | + | ||
| 27519 | + let ids = seed_school_b(&app, &b).await; | ||
| 27520 | + | ||
| 27521 | + for (i, route) in LIST_ROUTES.iter().enumerate() { | ||
| 27522 | + let res = send(&app, "GET", route, Some(&a), None).await; | ||
| 27523 | + assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); | ||
| 27524 | + assert_eq!( | ||
| 27525 | + common::total(&res.body), | ||
| 27526 | + before[i], | ||
| 27527 | + "GET {route} under A's cookie moved after B created rows: {}", | ||
| 27528 | + res.body | ||
| 27529 | + ); | ||
| 27530 | + let dump = res.body.to_string(); | ||
| 27531 | + for key in [ | ||
| 27532 | + "secret of B", | ||
| 27533 | + "b-note", | ||
| 27534 | + "b-event", | ||
| 27535 | + "9-B", | ||
| 27536 | + "b-board", | ||
| 27537 | + "B Course", | ||
| 27538 | + ] { | ||
| 27539 | + assert!(!dump.contains(key), "GET {route} leaked B's {key}: {dump}"); | ||
| 27540 | + } | ||
| 27541 | + } | ||
| 27542 | + // and B still sees its own. | ||
| 27543 | + let res = send(&app, "GET", "/notes", Some(&b), None).await; | ||
| 27544 | + assert_eq!(common::total(&res.body), 1, "{}", res.body); | ||
| 27545 | + assert!(ids["note"].is_string()); | ||
| 27546 | +} | ||
| 27547 | + | ||
| 27548 | +/// Invariant 1, id side: a record minted in B is a 404 under A's cookie on | ||
| 27549 | +/// every verb — never a 200, never a 500. | ||
| 27550 | +#[tokio::test] | ||
| 27551 | +async fn probe_cross_school_ids_are_not_found_under_the_other_cookie() { | ||
| 27552 | + let (app, db_a, db_b, _t) = two_schools().await; | ||
| 27553 | + let a = common::login_as_school(&app, &db_a, DEMO_SLUG, "ada", "admin").await; | ||
| 27554 | + let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | ||
| 27555 | + let ids = seed_school_b(&app, &b).await; | ||
| 27556 | + let s = |k: &str| ids[k].as_str().unwrap().to_string(); | ||
| 27557 | + | ||
| 27558 | + let targets: Vec<(String, serde_json::Value)> = vec![ | ||
| 27559 | + (format!("/notes/{}", s("note")), json!({ "title": "x" })), | ||
| 27560 | + (format!("/events/{}", s("event")), json!({ "title": "x" })), | ||
| 27561 | + (format!("/courses/{}", s("course")), json!({ "title": "x" })), | ||
| 27562 | + (format!("/exams/{}", s("exam")), json!({ "title": "x" })), | ||
| 27563 | + ( | ||
| 27564 | + format!("/subjects/{}", s("subject")), | ||
| 27565 | + json!({ "name": "x" }), | ||
| 27566 | + ), | ||
| 27567 | + (format!("/classes/{}", s("class")), json!({ "name": "x" })), | ||
| 27568 | + (format!("/boards/{}", s("board")), json!({ "title": "x" })), | ||
| 27569 | + ( | ||
| 27570 | + format!("/course-notes/{}", s("course_note")), | ||
| 27571 | + json!({ "title": "x" }), | ||
| 27572 | + ), | ||
| 27573 | + ( | ||
| 27574 | + format!("/bank-questions/{}", s("bank")), | ||
| 27575 | + json!({ "text": "x" }), | ||
| 27576 | + ), | ||
| 27577 | + ]; | ||
| 27578 | + | ||
| 27579 | + for (uri, patch) in targets { | ||
| 27580 | + for (method, body) in [ | ||
| 27581 | + ("GET", None), | ||
| 27582 | + ("PATCH", Some(patch.clone())), | ||
| 27583 | + ("DELETE", None), | ||
| 27584 | + ] { | ||
| 27585 | + let res = send(&app, method, &uri, Some(&a), body).await; | ||
| 27586 | + assert_ne!( | ||
| 27587 | + res.status, | ||
| 27588 | + StatusCode::OK, | ||
| 27589 | + "{method} {uri} under A returned 200 for a row that lives in B: {}", | ||
| 27590 | + res.body | ||
| 27591 | + ); | ||
| 27592 | + assert_ne!( | ||
| 27593 | + res.status, | ||
| 27594 | + StatusCode::NO_CONTENT, | ||
| 27595 | + "{method} {uri} under A deleted/updated a row that lives in B" | ||
| 27596 | + ); | ||
| 27597 | + assert!( | ||
| 27598 | + !res.status.is_server_error(), | ||
| 27599 | + "{method} {uri} under A: {} {}", | ||
| 27600 | + res.status, | ||
| 27601 | + res.body | ||
| 27602 | + ); | ||
| 27603 | + } | ||
| 27604 | + } | ||
| 27605 | + | ||
| 27606 | + // 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. | ||
| 27608 | + let res = send( | ||
| 27609 | + &app, | ||
| 27610 | + "GET", | ||
| 27611 | + &format!("/course-notes?course={}", s("course")), | ||
| 27612 | + Some(&a), | ||
| 27613 | + None, | ||
| 27614 | + ) | ||
| 27615 | + .await; | ||
| 27616 | + assert_ne!( | ||
| 27617 | + res.status, | ||
| 27618 | + StatusCode::OK, | ||
| 27619 | + "GET /course-notes?course=<B course> under A's cookie: {}", | ||
| 27620 | + res.body | ||
| 27621 | + ); | ||
| 27622 | + assert!(!res.status.is_server_error(), "{} {}", res.status, res.body); | ||
| 27623 | + | ||
| 27624 | + // B's rows survived every one of A's attempts. | ||
| 27625 | + for (uri, _) in [ | ||
| 27626 | + (format!("/notes/{}", s("note")), ()), | ||
| 27627 | + (format!("/courses/{}", s("course")), ()), | ||
| 27628 | + (format!("/boards/{}", s("board")), ()), | ||
| 27629 | + ] { | ||
| 27630 | + let res = send(&app, "GET", &uri, Some(&b), None).await; | ||
| 27631 | + assert_eq!( | ||
| 27632 | + res.status, | ||
| 27633 | + StatusCode::OK, | ||
| 27634 | + "B still owns {uri}: {}", | ||
| 27635 | + res.body | ||
| 27636 | + ); | ||
| 27637 | + } | ||
| 27638 | +} | ||
| 27639 | + | ||
| 27640 | +/// Invariant 1, body side: an id from B carried in a request *body* under A's | ||
| 27641 | +/// cookie must be refused, never silently linked. | ||
| 27642 | +#[tokio::test] | ||
| 27643 | +async fn probe_cross_school_ids_in_bodies_are_refused() { | ||
| 27644 | + let (app, db_a, db_b, _t) = two_schools().await; | ||
| 27645 | + let a_admin = common::login_as_school(&app, &db_a, DEMO_SLUG, "ada", "admin").await; | ||
| 27646 | + let a_student = common::login_as_school(&app, &db_a, DEMO_SLUG, "ali", "student").await; | ||
| 27647 | + let a_parent = common::login_as_school(&app, &db_a, DEMO_SLUG, "veli", "parent").await; | ||
| 27648 | + let b_admin = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | ||
| 27649 | + common::login_as_school(&app, &db_b, "beta", "bstudent", "student").await; | ||
| 27650 | + | ||
| 27651 | + let b_user = { | ||
| 27652 | + let res = send(&app, "GET", "/users", Some(&b_admin), None).await; | ||
| 27653 | + assert_eq!(res.status, StatusCode::OK); | ||
| 27654 | + id_of(&common::items(&res.body)[0]) | ||
| 27655 | + }; | ||
| 27656 | + let a_parent_id = common::me_id(&app, &a_parent).await; | ||
| 27657 | + let a_course = create_course(&app, &a_admin, "A Course").await; | ||
| 27658 | + let a_board = { | ||
| 27659 | + let res = send( | ||
| 27660 | + &app, | ||
| 27661 | + "POST", | ||
| 27662 | + "/boards", | ||
| 27663 | + Some(&a_admin), | ||
| 27664 | + Some(json!({ "title": "a-board", "participants": [] })), | ||
| 27665 | + ) | ||
| 27666 | + .await; | ||
| 27667 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 27668 | + id_of(&res.body) | ||
| 27669 | + }; | ||
| 27670 | + | ||
| 27671 | + let cases: Vec<(&str, String, &str, serde_json::Value)> = vec![ | ||
| 27672 | + ( | ||
| 27673 | + "message to a B recipient", | ||
| 27674 | + "/messages".into(), | ||
| 27675 | + &a_student, | ||
| 27676 | + json!({ "recipient_id": b_user, "subject": "hi", "body": "cross" }), | ||
| 27677 | + ), | ||
| 27678 | + ( | ||
| 27679 | + "enroll a B user into an A course", | ||
| 27680 | + format!("/courses/{a_course}/enrollments"), | ||
| 27681 | + &a_admin, | ||
| 27682 | + json!({ "user_id": b_user }), | ||
| 27683 | + ), | ||
| 27684 | + ( | ||
| 27685 | + "assign a B user as an A course teacher", | ||
| 27686 | + format!("/courses/{a_course}/teachers"), | ||
| 27687 | + &a_admin, | ||
| 27688 | + json!({ "user_id": b_user }), | ||
| 27689 | + ), | ||
| 27690 | + ( | ||
| 27691 | + "link a B student to an A parent", | ||
| 27692 | + format!("/users/{a_parent_id}/students"), | ||
| 27693 | + &a_admin, | ||
| 27694 | + json!({ "user_id": b_user }), | ||
| 27695 | + ), | ||
| 27696 | + ( | ||
| 27697 | + "invite a B user onto an A board", | ||
| 27698 | + format!("/boards/{a_board}/invite"), | ||
| 27699 | + &a_admin, | ||
| 27700 | + json!({ "participants": [b_user] }), | ||
| 27701 | + ), | ||
| 27702 | + ( | ||
| 27703 | + "create an A board with a B participant", | ||
| 27704 | + "/boards".into(), | ||
| 27705 | + &a_admin, | ||
| 27706 | + json!({ "title": "x", "participants": [b_user] }), | ||
| 27707 | + ), | ||
| 27708 | + ]; | ||
| 27709 | + | ||
| 27710 | + for (what, uri, cookie, body) in cases { | ||
| 27711 | + let res = send(&app, "POST", &uri, Some(cookie), Some(body)).await; | ||
| 27712 | + assert!( | ||
| 27713 | + res.status.is_client_error(), | ||
| 27714 | + "{what}: POST {uri} answered {} (expected a 4xx refusal): {}", | ||
| 27715 | + res.status, | ||
| 27716 | + res.body | ||
| 27717 | + ); | ||
| 27718 | + assert!( | ||
| 27719 | + !res.body.to_string().contains(&b_user), | ||
| 27720 | + "{what}: POST {uri} echoed B's user id back: {}", | ||
| 27721 | + res.body | ||
| 27722 | + ); | ||
| 27723 | + } | ||
| 27724 | +} | ||
| 27725 | + | ||
| 27726 | +/// Invariant 2: a suspended school is refused everywhere, and a resume brings | ||
| 27727 | +/// the *same* cookie back to life. | ||
| 27728 | +#[tokio::test] | ||
| 27729 | +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; | ||
| 27731 | + let slug_b = Slug::try_new("beta").unwrap(); | ||
| 27732 | + let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | ||
| 27733 | + | ||
| 27734 | + // Alive first. | ||
| 27735 | + let res = send(&app, "GET", "/auth/me", Some(&b), None).await; | ||
| 27736 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 27737 | + | ||
| 27738 | + tenants | ||
| 27739 | + .set_status(&slug_b, SchoolStatus::Suspended) | ||
| 27740 | + .await | ||
| 27741 | + .expect("suspend"); | ||
| 27742 | + | ||
| 27743 | + // The already-issued cookie, on the very next request. | ||
| 27744 | + for route in ["/auth/me", "/users", "/notes", "/courses", "/settings"] { | ||
| 27745 | + let res = send(&app, "GET", route, Some(&b), None).await; | ||
| 27746 | + assert_eq!( | ||
| 27747 | + res.status, | ||
| 27748 | + StatusCode::FORBIDDEN, | ||
| 27749 | + "GET {route} with a suspended school's live cookie: {} {}", | ||
| 27750 | + res.status, | ||
| 27751 | + res.body | ||
| 27752 | + ); | ||
| 27753 | + } | ||
| 27754 | + // A write too. | ||
| 27755 | + let res = send( | ||
| 27756 | + &app, | ||
| 27757 | + "POST", | ||
| 27758 | + "/notes", | ||
| 27759 | + Some(&b), | ||
| 27760 | + Some(json!({ "title": "t", "content": "c" })), | ||
| 27761 | + ) | ||
| 27762 | + .await; | ||
| 27763 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 27764 | + | ||
| 27765 | + // Login is no exception. | ||
| 27766 | + let res = send( | ||
| 27767 | + &app, | ||
| 27768 | + "POST", | ||
| 27769 | + "/auth/login", | ||
| 27770 | + None, | ||
| 27771 | + Some(json!({ "school": "beta", "username": "boran", "password": "secret1" })), | ||
| 27772 | + ) | ||
| 27773 | + .await; | ||
| 27774 | + assert_eq!( | ||
| 27775 | + res.status, | ||
| 27776 | + StatusCode::FORBIDDEN, | ||
| 27777 | + "login into a suspended school: {}", | ||
| 27778 | + res.body | ||
| 27779 | + ); | ||
| 27780 | + | ||
| 27781 | + // Register into it is refused too. | ||
| 27782 | + let res = send( | ||
| 27783 | + &app, | ||
| 27784 | + "POST", | ||
| 27785 | + "/auth/register", | ||
| 27786 | + None, | ||
| 27787 | + Some(json!({ "school": "beta", "username": "newcomer", "password": "secret1" })), | ||
| 27788 | + ) | ||
| 27789 | + .await; | ||
| 27790 | + assert_eq!( | ||
| 27791 | + res.status, | ||
| 27792 | + StatusCode::FORBIDDEN, | ||
| 27793 | + "register into a suspended school: {}", | ||
| 27794 | + res.body | ||
| 27795 | + ); | ||
| 27796 | + | ||
| 27797 | + // Resume: the same cookie works again — the session rows were not deleted. | ||
| 27798 | + tenants | ||
| 27799 | + .set_status(&slug_b, SchoolStatus::Active) | ||
| 27800 | + .await | ||
| 27801 | + .expect("resume"); | ||
| 27802 | + let res = send(&app, "GET", "/auth/me", Some(&b), None).await; | ||
| 27803 | + assert_eq!( | ||
| 27804 | + res.status, | ||
| 27805 | + StatusCode::OK, | ||
| 27806 | + "the same cookie after a resume: {}", | ||
| 27807 | + res.body | ||
| 27808 | + ); | ||
| 27809 | + assert_eq!(res.body["username"], "boran"); | ||
| 27810 | +} | ||
| 27811 | + | ||
| 27812 | +/// Invariant 3: no cookie is usable as another kind of cookie. The last case — | ||
| 27813 | +/// a real token from school A presented under school B's prefix — is the one | ||
| 27814 | +/// that would be a full takeover. | ||
| 27815 | +#[tokio::test] | ||
| 27816 | +async fn probe_cookie_confusion_is_impossible_both_ways() { | ||
| 27817 | + 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; | ||
| 27819 | + let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | ||
| 27820 | + let token_a = common::cookie_token(&a).to_string(); | ||
| 27821 | + | ||
| 27822 | + hezarfen_backend::domain::builder::Builder::ensure( | ||
| 27823 | + Username::try_new("operator").unwrap(), | ||
| 27824 | + Password::try_new("secret1").unwrap(), | ||
| 27825 | + tenants.control(), | ||
| 27826 | + ) | ||
| 27827 | + .await | ||
| 27828 | + .expect("seed the builder"); | ||
| 27829 | + let res = send( | ||
| 27830 | + &app, | ||
| 27831 | + "POST", | ||
| 27832 | + "/builder/login", | ||
| 27833 | + None, | ||
| 27834 | + Some(json!({ "username": "operator", "password": "secret1" })), | ||
| 27835 | + ) | ||
| 27836 | + .await; | ||
| 27837 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 27838 | + let builder_cookie = res.cookie.expect("builder cookie"); | ||
| 27839 | + let builder_token = common::cookie_token(&builder_cookie).to_string(); | ||
| 27840 | + | ||
| 27841 | + // (1) builder cookie on a school surface. | ||
| 27842 | + for route in ["/auth/me", "/users", "/notes"] { | ||
| 27843 | + let res = send(&app, "GET", route, Some(&builder_cookie), None).await; | ||
| 27844 | + assert_eq!( | ||
| 27845 | + res.status, | ||
| 27846 | + StatusCode::UNAUTHORIZED, | ||
| 27847 | + "builder cookie on GET {route}: {} {}", | ||
| 27848 | + res.status, | ||
| 27849 | + res.body | ||
| 27850 | + ); | ||
| 27851 | + } | ||
| 27852 | + // (2) school cookie on the builder surface. | ||
| 27853 | + for cookie in [&a, &b] { | ||
| 27854 | + for route in ["/builder/me", "/schools"] { | ||
| 27855 | + let res = send(&app, "GET", route, Some(cookie), None).await; | ||
| 27856 | + assert_eq!( | ||
| 27857 | + res.status, | ||
| 27858 | + StatusCode::UNAUTHORIZED, | ||
| 27859 | + "school cookie on GET {route}: {} {}", | ||
| 27860 | + res.status, | ||
| 27861 | + res.body | ||
| 27862 | + ); | ||
| 27863 | + } | ||
| 27864 | + } | ||
| 27865 | + // (3) bare token, no dot. | ||
| 27866 | + for raw in [ | ||
| 27867 | + format!("session={token_a}"), | ||
| 27868 | + format!("session={builder_token}"), | ||
| 27869 | + "session=.".to_string(), | ||
| 27870 | + format!("session=.{token_a}"), | ||
| 27871 | + format!("session={token_a}."), | ||
| 27872 | + ] { | ||
| 27873 | + for route in ["/auth/me", "/builder/me"] { | ||
| 27874 | + let res = send(&app, "GET", route, Some(&raw), None).await; | ||
| 27875 | + assert_eq!( | ||
| 27876 | + res.status, | ||
| 27877 | + StatusCode::UNAUTHORIZED, | ||
| 27878 | + "{raw} on GET {route}: {} {}", | ||
| 27879 | + res.status, | ||
| 27880 | + res.body | ||
| 27881 | + ); | ||
| 27882 | + } | ||
| 27883 | + } | ||
| 27884 | + // (4) a builder token wearing a school prefix. | ||
| 27885 | + for raw in [ | ||
| 27886 | + format!("session=demo.{builder_token}"), | ||
| 27887 | + format!("session=beta.{builder_token}"), | ||
| 27888 | + ] { | ||
| 27889 | + let res = send(&app, "GET", "/auth/me", Some(&raw), None).await; | ||
| 27890 | + assert_eq!( | ||
| 27891 | + res.status, | ||
| 27892 | + StatusCode::UNAUTHORIZED, | ||
| 27893 | + "{raw} on /auth/me: {} {}", | ||
| 27894 | + res.status, | ||
| 27895 | + res.body | ||
| 27896 | + ); | ||
| 27897 | + } | ||
| 27898 | + // (5) THE one: A's live token under B's prefix, and B's under A's. | ||
| 27899 | + let token_b = common::cookie_token(&b).to_string(); | ||
| 27900 | + for (raw, whose) in [ | ||
| 27901 | + (format!("session=beta.{token_a}"), "A's token under B"), | ||
| 27902 | + (format!("session=demo.{token_b}"), "B's token under A"), | ||
| 27903 | + ] { | ||
| 27904 | + for route in ["/auth/me", "/users", "/notes", "/settings"] { | ||
| 27905 | + let res = send(&app, "GET", route, Some(&raw), None).await; | ||
| 27906 | + assert_eq!( | ||
| 27907 | + res.status, | ||
| 27908 | + StatusCode::UNAUTHORIZED, | ||
| 27909 | + "{whose} on GET {route}: {} {}", | ||
| 27910 | + res.status, | ||
| 27911 | + res.body | ||
| 27912 | + ); | ||
| 27913 | + } | ||
| 27914 | + } | ||
| 27915 | + // (6) a school cookie naming a school that does not exist. | ||
| 27916 | + let res = send( | ||
| 27917 | + &app, | ||
| 27918 | + "GET", | ||
| 27919 | + "/auth/me", | ||
| 27920 | + Some(&format!("session=nosuchschool.{token_a}")), | ||
| 27921 | + None, | ||
| 27922 | + ) | ||
| 27923 | + .await; | ||
| 27924 | + assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); | ||
| 27925 | +} | ||
| 27926 | + | ||
| 27927 | +/// Invariant 4: `POST /auth/register` names its school, registers into that one | ||
| 27928 | +/// only, and an unknown school is indistinguishable from a bad credential. | ||
| 27929 | +#[tokio::test] | ||
| 27930 | +async fn probe_register_is_scoped_to_the_named_school() { | ||
| 27931 | + let (app, db_a, db_b, _t) = two_schools().await; | ||
| 27932 | + | ||
| 27933 | + // Missing `school` is a 4xx, not a silent default. | ||
| 27934 | + let res = send( | ||
| 27935 | + &app, | ||
| 27936 | + "POST", | ||
| 27937 | + "/auth/register", | ||
| 27938 | + None, | ||
| 27939 | + Some(json!({ "username": "noschool", "password": "secret1" })), | ||
| 27940 | + ) | ||
| 27941 | + .await; | ||
| 27942 | + assert!( | ||
| 27943 | + res.status.is_client_error(), | ||
| 27944 | + "register with no school: {} {}", | ||
| 27945 | + res.status, | ||
| 27946 | + res.body | ||
| 27947 | + ); | ||
| 27948 | + | ||
| 27949 | + // The same username in both schools, independently. | ||
| 27950 | + for (slug, db) in [(DEMO_SLUG, &db_a), ("beta", &db_b)] { | ||
| 27951 | + let res = send( | ||
| 27952 | + &app, | ||
| 27953 | + "POST", | ||
| 27954 | + "/auth/register", | ||
| 27955 | + None, | ||
| 27956 | + Some(json!({ "school": slug, "username": "ayse", "password": "secret1" })), | ||
| 27957 | + ) | ||
| 27958 | + .await; | ||
| 27959 | + assert_eq!( | ||
| 27960 | + res.status, | ||
| 27961 | + StatusCode::CREATED, | ||
| 27962 | + "register into {slug}: {}", | ||
| 27963 | + res.body | ||
| 27964 | + ); | ||
| 27965 | + let found: Vec<String> = db | ||
| 27966 | + .query("SELECT VALUE username FROM user WHERE username = 'ayse'") | ||
| 27967 | + .await | ||
| 27968 | + .unwrap() | ||
| 27969 | + .take(0) | ||
| 27970 | + .unwrap(); | ||
| 27971 | + assert_eq!( | ||
| 27972 | + found, | ||
| 27973 | + vec!["ayse".to_string()], | ||
| 27974 | + "exactly one 'ayse' in {slug}" | ||
| 27975 | + ); | ||
| 27976 | + } | ||
| 27977 | + | ||
| 27978 | + // Unknown school: same 401 and same body as a bad credential — no | ||
| 27979 | + // enumeration of the customer list. | ||
| 27980 | + let unknown = send( | ||
| 27981 | + &app, | ||
| 27982 | + "POST", | ||
| 27983 | + "/auth/login", | ||
| 27984 | + None, | ||
| 27985 | + Some(json!({ "school": "not-a-school", "username": "ayse", "password": "secret1" })), | ||
| 27986 | + ) | ||
| 27987 | + .await; | ||
| 27988 | + let bad_pass = send( | ||
| 27989 | + &app, | ||
| 27990 | + "POST", | ||
| 27991 | + "/auth/login", | ||
| 27992 | + None, | ||
| 27993 | + Some(json!({ "school": DEMO_SLUG, "username": "ayse", "password": "wrongpw1" })), | ||
| 27994 | + ) | ||
| 27995 | + .await; | ||
| 27996 | + assert_eq!(unknown.status, StatusCode::UNAUTHORIZED, "{}", unknown.body); | ||
| 27997 | + assert_eq!(unknown.status, bad_pass.status, "status differs"); | ||
| 27998 | + assert_eq!( | ||
| 27999 | + unknown.body, bad_pass.body, | ||
| 28000 | + "an unknown school answers differently from a bad password: {} vs {}", | ||
| 28001 | + unknown.body, bad_pass.body | ||
| 28002 | + ); | ||
| 28003 | + | ||
| 28004 | + // Register against an unknown school: same treatment. | ||
| 28005 | + let reg_unknown = send( | ||
| 28006 | + &app, | ||
| 28007 | + "POST", | ||
| 28008 | + "/auth/register", | ||
| 28009 | + None, | ||
| 28010 | + Some(json!({ "school": "not-a-school", "username": "zeynep", "password": "secret1" })), | ||
| 28011 | + ) | ||
| 28012 | + .await; | ||
| 28013 | + assert_eq!( | ||
| 28014 | + reg_unknown.status, | ||
| 28015 | + StatusCode::UNAUTHORIZED, | ||
| 28016 | + "register into an unknown school: {} {}", | ||
| 28017 | + reg_unknown.status, | ||
| 28018 | + reg_unknown.body | ||
| 28019 | + ); | ||
| 28020 | +} | ||
| 28021 | + | ||
| 28022 | +/// Invariant 5: an upload under A lands under `FILES_PATH/A/` and is a 404 | ||
| 28023 | +/// under B's cookie even with the exact ids. | ||
| 28024 | +#[tokio::test] | ||
| 28025 | +async fn probe_uploaded_files_are_school_scoped() { | ||
| 28026 | + let (app, db_a, db_b, _t) = two_schools().await; | ||
| 28027 | + let a = common::login_as_school(&app, &db_a, DEMO_SLUG, "ali", "student").await; | ||
| 28028 | + let b = common::login_as_school(&app, &db_b, "beta", "ali", "student").await; | ||
| 28029 | + | ||
| 28030 | + let note = send( | ||
| 28031 | + &app, | ||
| 28032 | + "POST", | ||
| 28033 | + "/notes", | ||
| 28034 | + Some(&a), | ||
| 28035 | + Some(json!({ "title": "n", "content": "c" })), | ||
| 28036 | + ) | ||
| 28037 | + .await; | ||
| 28038 | + assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); | ||
| 28039 | + let note_id = id_of(¬e.body); | ||
| 28040 | + | ||
| 28041 | + 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); | ||
| 28043 | + let file_id = id_of(&up.body); | ||
| 28044 | + | ||
| 28045 | + // It landed under the school's own directory, and nowhere else. | ||
| 28046 | + let a_dir = common::files_dir().join(DEMO_SLUG); | ||
| 28047 | + let b_dir = common::files_dir().join("beta"); | ||
| 28048 | + let count = |dir: &std::path::Path| { | ||
| 28049 | + std::fs::read_dir(dir) | ||
| 28050 | + .map(|it| it.count()) | ||
| 28051 | + .unwrap_or_default() | ||
| 28052 | + }; | ||
| 28053 | + assert!(count(&a_dir) >= 1, "A's blob directory {a_dir:?} is empty"); | ||
| 28054 | + assert_eq!( | ||
| 28055 | + count(&b_dir), | ||
| 28056 | + 0, | ||
| 28057 | + "B's blob directory {b_dir:?} is not empty" | ||
| 28058 | + ); | ||
| 28059 | + | ||
| 28060 | + // A reads it back. | ||
| 28061 | + 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; | ||
| 28063 | + assert_eq!(status, StatusCode::OK, "A reads its own file"); | ||
| 28064 | + assert_eq!(bytes, b"A-ONLY-BYTES"); | ||
| 28065 | + | ||
| 28066 | + // 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; | ||
| 28068 | + assert_eq!( | ||
| 28069 | + status, | ||
| 28070 | + StatusCode::NOT_FOUND, | ||
| 28071 | + "B read A's file: {}", | ||
| 28072 | + String::from_utf8_lossy(&bytes) | ||
| 28073 | + ); | ||
| 28074 | + assert!(!bytes.windows(12).any(|w| w == b"A-ONLY-BYTES")); | ||
| 28075 | + | ||
| 28076 | + 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"); | ||
| 28078 | + 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"); | ||
| 28080 | +} | ||
| 28081 | + | ||
| 28082 | +/// Invariant 1, the leak that would be invisible from the API: no school row | ||
| 28083 | +/// may land in the **control** database, and the search + settings surfaces | ||
| 28084 | +/// (which are not paged lists) stay inside the caller's school. | ||
| 28085 | +#[tokio::test] | ||
| 28086 | +async fn probe_school_rows_never_reach_the_control_database() { | ||
| 28087 | + 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; | ||
| 28089 | + let b = common::login_as_school(&app, &db_b, "beta", "boran", "admin").await; | ||
| 28090 | + common::login_as_school(&app, &db_b, "beta", "bstudent", "student").await; | ||
| 28091 | + let ids = seed_school_b(&app, &b).await; | ||
| 28092 | + assert!(ids["course"].is_string()); | ||
| 28093 | + | ||
| 28094 | + // Nothing a school writes may appear in the control database. | ||
| 28095 | + let control = tenants.control(); | ||
| 28096 | + for table in [ | ||
| 28097 | + "user", | ||
| 28098 | + "session", | ||
| 28099 | + "note", | ||
| 28100 | + "course", | ||
| 28101 | + "event", | ||
| 28102 | + "message", | ||
| 28103 | + "class_group", | ||
| 28104 | + "board", | ||
| 28105 | + "course_note", | ||
| 28106 | + "bank_question", | ||
| 28107 | + "chatbot_thread", | ||
| 28108 | + "exam", | ||
| 28109 | + ] { | ||
| 28110 | + let rows: Vec<surrealdb::types::RecordId> = control | ||
| 28111 | + .query(format!("SELECT VALUE id FROM {table}")) | ||
| 28112 | + .await | ||
| 28113 | + .expect("control query") | ||
| 28114 | + .take(0) | ||
| 28115 | + .unwrap_or_default(); | ||
| 28116 | + assert!( | ||
| 28117 | + rows.is_empty(), | ||
| 28118 | + "the control database holds {} `{table}` row(s): {rows:?}", | ||
| 28119 | + rows.len() | ||
| 28120 | + ); | ||
| 28121 | + } | ||
| 28122 | + // And the control database does hold the two schools. | ||
| 28123 | + let schools: Vec<String> = control | ||
| 28124 | + .query("SELECT VALUE slug FROM school ORDER BY slug") | ||
| 28125 | + .await | ||
| 28126 | + .unwrap() | ||
| 28127 | + .take(0) | ||
| 28128 | + .unwrap(); | ||
| 28129 | + assert_eq!(schools, vec!["beta".to_string(), "demo".to_string()]); | ||
| 28130 | + | ||
| 28131 | + // User search never crosses the wall. | ||
| 28132 | + for (cookie, forbidden) in [(&a, "boran"), (&b, "ada")] { | ||
| 28133 | + for q in ["b", "a", "boran", "ada", "bstudent"] { | ||
| 28134 | + let res = send( | ||
| 28135 | + &app, | ||
| 28136 | + "GET", | ||
| 28137 | + &format!("/users/search?q={q}"), | ||
| 28138 | + Some(cookie), | ||
| 28139 | + None, | ||
| 28140 | + ) | ||
| 28141 | + .await; | ||
| 28142 | + assert_eq!(res.status, StatusCode::OK, "search {q}: {}", res.body); | ||
| 28143 | + assert!( | ||
| 28144 | + !res.body.to_string().contains(forbidden), | ||
| 28145 | + "GET /users/search?q={q} returned the other school's `{forbidden}`: {}", | ||
| 28146 | + res.body | ||
| 28147 | + ); | ||
| 28148 | + } | ||
| 28149 | + } | ||
| 28150 | + | ||
| 28151 | + // Settings are the school's own: moving A's leaves B's alone. | ||
| 28152 | + let before = send(&app, "GET", "/settings", Some(&b), None).await; | ||
| 28153 | + assert_eq!(before.status, StatusCode::OK, "{}", before.body); | ||
| 28154 | + let patched = send( | ||
| 28155 | + &app, | ||
| 28156 | + "PATCH", | ||
| 28157 | + "/settings", | ||
| 28158 | + Some(&a), | ||
| 28159 | + Some(json!({ "max_file_bytes": 4096 })), | ||
| 28160 | + ) | ||
| 28161 | + .await; | ||
| 28162 | + assert_eq!(patched.status, StatusCode::OK, "{}", patched.body); | ||
| 28163 | + assert_eq!(patched.body["max_file_bytes"], 4096); | ||
| 28164 | + let after = send(&app, "GET", "/settings", Some(&b), None).await; | ||
| 28165 | + assert_eq!( | ||
| 28166 | + after.body, before.body, | ||
| 28167 | + "A's settings PATCH moved B's settings" | ||
| 28168 | + ); | ||
| 28169 | + | ||
| 28170 | + // 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"] { | ||
| 28172 | + let raw = format!("session={prefix}.{}", common::cookie_token(&a)); | ||
| 28173 | + let res = send(&app, "GET", "/auth/me", Some(&raw), None).await; | ||
| 28174 | + assert_eq!( | ||
| 28175 | + res.status, | ||
| 28176 | + StatusCode::UNAUTHORIZED, | ||
| 28177 | + "prefix `{prefix}`: {} {}", | ||
| 28178 | + res.status, | ||
| 28179 | + res.body | ||
| 28180 | + ); | ||
| 28181 | + } | ||
| 28182 | +} | ||
| 28183 | + | ||
| 28184 | +/// Invariant 1 on the path production actually uses: `Mode::Remote`, where every | ||
| 28185 | +/// school is a *database inside one namespace on one server* and isolation rests | ||
| 28186 | +/// entirely on each connection's `use_db` pin — unlike `Mode::Mem`, where a | ||
| 28187 | +/// school is its own embedded datastore and isolation cannot fail. | ||
| 28188 | +/// | ||
| 28189 | +/// Skipped unless `HEZARFEN_REMOTE_DB` names a live SurrealDB (e.g. | ||
| 28190 | +/// `surreal start --user root --pass root memory --bind 127.0.0.1:8123`), since | ||
| 28191 | +/// this suite must stay runnable with no server. | ||
| 28192 | +#[tokio::test] | ||
| 28193 | +async fn probe_remote_mode_keeps_two_schools_apart() { | ||
| 28194 | + let Ok(url) = std::env::var("HEZARFEN_REMOTE_DB") else { | ||
| 28195 | + eprintln!("HEZARFEN_REMOTE_DB unset — remote-mode isolation NOT exercised"); | ||
| 28196 | + return; | ||
| 28197 | + }; | ||
| 28198 | + let ns = format!( | ||
| 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(); | ||
| 28231 | + 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 | + | ||
| 28254 | + // The same username in both schools, over the real router. | ||
| 28255 | + let mut cookies = Vec::new(); | ||
| 28256 | + for slug in [&slug_a, &slug_b] { | ||
| 28257 | + let creds = json!({ "school": slug.as_str(), "username": "ada", "password": "secret1" }); | ||
| 28258 | + let reg = send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; | ||
| 28259 | + assert_eq!( | ||
| 28260 | + reg.status, | ||
| 28261 | + StatusCode::CREATED, | ||
| 28262 | + "register in {slug}: {}", | ||
| 28263 | + reg.body | ||
| 28264 | + ); | ||
| 28265 | + let db = tenants.get(slug).await.unwrap(); | ||
| 28266 | + common::set_role(&db, "ada", "admin").await; | ||
| 28267 | + let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; | ||
| 28268 | + assert_eq!(res.status, StatusCode::OK, "login in {slug}: {}", res.body); | ||
| 28269 | + cookies.push(res.cookie.expect("cookie")); | ||
| 28270 | + } | ||
| 28271 | + let (a, b) = (cookies[0].clone(), cookies[1].clone()); | ||
| 28272 | + | ||
| 28273 | + // B fills up; A must not see a single row of it. | ||
| 28274 | + let ids = seed_school_b(&app, &b).await; | ||
| 28275 | + for route in LIST_ROUTES { | ||
| 28276 | + let res = send(&app, "GET", route, Some(&a), None).await; | ||
| 28277 | + assert_eq!(res.status, StatusCode::OK, "GET {route} as A: {}", res.body); | ||
| 28278 | + let dump = res.body.to_string(); | ||
| 28279 | + for key in [ | ||
| 28280 | + "secret of B", | ||
| 28281 | + "b-note", | ||
| 28282 | + "b-event", | ||
| 28283 | + "9-B", | ||
| 28284 | + "b-board", | ||
| 28285 | + "B Course", | ||
| 28286 | + ] { | ||
| 28287 | + assert!(!dump.contains(key), "GET {route} leaked B's {key}: {dump}"); | ||
| 28288 | + } | ||
| 28289 | + } | ||
| 28290 | + // Each school sees exactly its own user, and only one. | ||
| 28291 | + for cookie in [&a, &b] { | ||
| 28292 | + let res = send(&app, "GET", "/users", Some(cookie), None).await; | ||
| 28293 | + assert_eq!(common::total(&res.body), 1, "{}", res.body); | ||
| 28294 | + } | ||
| 28295 | + // A row minted in B is a 404 under A on every verb. | ||
| 28296 | + for key in ["note", "course", "board", "event", "class"] { | ||
| 28297 | + let id = ids[key].as_str().unwrap(); | ||
| 28298 | + let uri = match key { | ||
| 28299 | + "note" => format!("/notes/{id}"), | ||
| 28300 | + "course" => format!("/courses/{id}"), | ||
| 28301 | + "board" => format!("/boards/{id}"), | ||
| 28302 | + "event" => format!("/events/{id}"), | ||
| 28303 | + _ => format!("/classes/{id}"), | ||
| 28304 | + }; | ||
| 28305 | + for method in ["GET", "DELETE"] { | ||
| 28306 | + let res = send(&app, method, &uri, Some(&a), None).await; | ||
| 28307 | + assert_ne!( | ||
| 28308 | + res.status, | ||
| 28309 | + StatusCode::OK, | ||
| 28310 | + "{method} {uri} as A: {}", | ||
| 28311 | + res.body | ||
| 28312 | + ); | ||
| 28313 | + assert_ne!(res.status, StatusCode::NO_CONTENT, "{method} {uri} as A"); | ||
| 28314 | + assert!( | ||
| 28315 | + !res.status.is_server_error(), | ||
| 28316 | + "{method} {uri}: {} {}", | ||
| 28317 | + res.status, | ||
| 28318 | + res.body | ||
| 28319 | + ); | ||
| 28320 | + } | ||
| 28321 | + let res = send(&app, "GET", &uri, Some(&b), None).await; | ||
| 28322 | + assert_eq!( | ||
| 28323 | + res.status, | ||
| 28324 | + StatusCode::OK, | ||
| 28325 | + "B still owns {uri}: {}", | ||
| 28326 | + res.body | ||
| 28327 | + ); | ||
| 28328 | + } | ||
| 28329 | + | ||
| 28330 | + // 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)); | ||
| 28332 | + let res = send(&app, "GET", "/auth/me", Some(&raw), None).await; | ||
| 28333 | + assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); | ||
| 28334 | + | ||
| 28335 | + // Clean up after ourselves: the whole scratch namespace. | ||
| 28336 | + let _ = tenants | ||
| 28337 | + .control() | ||
| 28338 | + .query(format!("REMOVE NAMESPACE IF EXISTS `{ns}`")) | ||
| 28339 | + .await; | ||
| 28340 | +} | ||