Cotton code
267 lines · 14.5 KB · RustRaw
//! THE GUARD: a Cotton Dev process resolves no identifier of the real//! household — not its data folder, not its port, not its relay name, not its//! server. The real identifiers are written out below as literals on purpose://! a change to `Flavor::Real` that drags `Flavor::Dev` along with it must go//! red here, not agree with itself.use super::*;/// The real household's identifiers, as the frozen CottonDB knows them.const REAL_DATA_DIR_NAME: &str = "CottonDB";const REAL_PORT: u16 = 8790;/// Synthetic: any name without the dev suffix is the real app's, and nothing/// real goes in the public tree.const REAL_RELAY_NAME: &str = "harbour";#[test]fn the_real_flavor_keeps_the_frozen_identity() {    assert_eq!(Flavor::Real.data_dir_name(), REAL_DATA_DIR_NAME);    assert_eq!(Flavor::Real.default_port(), REAL_PORT);    assert!(Flavor::Real.admits_relay_name(REAL_RELAY_NAME));    assert_eq!(Flavor::Real.refusal_for_server(None), None, "the frozen server says nothing");}#[test]fn a_dev_build_resolves_no_real_identifier() {    let home = Path::new("/Users/someone");    assert_ne!(Flavor::Dev.data_dir_name(), REAL_DATA_DIR_NAME);    assert_eq!(Flavor::Dev.home_data_dir(home), home.join("CottonDev"));    assert_ne!(Flavor::Dev.home_data_dir(home), home.join(REAL_DATA_DIR_NAME));    assert_ne!(Flavor::Dev.default_port(), REAL_PORT);    assert!(!Flavor::Dev.admits_relay_name(REAL_RELAY_NAME));    assert!(Flavor::Dev.refusal_for_server(None).is_some(), "a server that says nothing is the real one");    assert!(Flavor::Dev.refusal_for_server(Some("real")).is_some());}#[test]fn anything_but_the_word_real_is_dev() {    for declared in [None, Some(""), Some("  "), Some("Real"), Some("REAL"), Some("prod"), Some("release"), Some("dev")] {        assert_eq!(Flavor::from_declared(declared), Flavor::Dev, "{declared:?}");    }    assert_eq!(Flavor::from_declared(Some("real")), Flavor::Real);    assert_eq!(Flavor::from_declared(Some(" real\n")), Flavor::Real);    assert_eq!(Flavor::from_env(&|_| None), Flavor::Dev);    assert_eq!(Flavor::from_env(&|k| (k == FLAVOR_ENV).then(|| "real".to_string())), Flavor::Real);}#[test]fn relay_names_are_disjoint_between_the_two_apps() {    for name in ["harbour", "studio", "a", "dev", "harbour-devs", "dev-harbour", "harbour-dev-1"] {        assert!(!Flavor::Dev.admits_relay_name(name), "dev admitted {name}");        assert!(Flavor::Real.admits_relay_name(name), "real refused {name}");    }    for name in ["harbour-dev", "studio-dev", " harbour-dev "] {        assert!(Flavor::Dev.admits_relay_name(name), "dev refused {name}");        assert!(!Flavor::Real.admits_relay_name(name), "real admitted {name}");    }    for name in ["harbour", "x", "harbour-dev", ""] {        assert_ne!(            Flavor::Dev.admits_relay_name(name),            Flavor::Real.admits_relay_name(name),            "{name} is usable by both apps or by neither"        );    }}#[test]fn a_dev_build_refuses_the_real_data_folder_in_every_spelling() {    let home = Path::new("/Users/someone");    for dir in [        home.join("CottonDB"),        home.join("CottonDB/"),        home.join("CottonDB/."),        home.join("./CottonDB"),        home.join("Library/Application Support/CottonDB"),    ] {        let refusal = Flavor::Dev.refusal_for_data_dir(home, &dir);        assert!(refusal.is_some(), "dev would open {}", dir.display());        assert!(refusal.unwrap().contains("CottonDB"));    }    assert_eq!(Flavor::Dev.refusal_for_data_dir(home, &home.join("CottonDev")), None);    assert_eq!(Flavor::Dev.refusal_for_data_dir(home, Path::new("/tmp/rehearsal")), None);}#[test]fn a_dev_build_refuses_a_symlink_to_the_real_data_folder() {    let scratch = std::env::temp_dir().join(format!("cotton-flavor-{}", std::process::id()));    let home = scratch.join("home");    std::fs::create_dir_all(home.join("CottonDB")).unwrap();    let link = scratch.join("looks-harmless");    let _ = std::fs::remove_file(&link);    #[cfg(unix)]    std::os::unix::fs::symlink(home.join("CottonDB"), &link).unwrap();    #[cfg(unix)]    assert!(Flavor::Dev.refusal_for_data_dir(&home, &link).is_some());    std::fs::remove_dir_all(&scratch).unwrap();}#[test]fn the_real_build_refuses_the_dev_folder_but_not_its_own() {    let home = Path::new("/Users/someone");    assert!(Flavor::Real.refusal_for_data_dir(home, &home.join("CottonDev")).is_some());    assert_eq!(Flavor::Real.refusal_for_data_dir(home, &home.join("CottonDB")), None);    assert_eq!(        Flavor::Real.refusal_for_data_dir(home, &home.join("Library/Application Support/CottonDB")),        None,        "the legacy folder is the real app's own"    );}#[test]fn each_app_joins_only_its_own_servers() {    assert_eq!(Flavor::Dev.refusal_for_server(Some("dev")), None);    assert!(Flavor::Real.refusal_for_server(Some("dev")).is_some());    assert_eq!(Flavor::Real.refusal_for_server(Some("real")), None);    for odd in ["", "staging", "Dev"] {        assert!(Flavor::Dev.refusal_for_server(Some(odd)).is_some(), "{odd:?}");        assert!(Flavor::Real.refusal_for_server(Some(odd)).is_some(), "{odd:?}");    }}#[test]fn a_dev_build_refuses_the_real_folder_spelt_with_dot_dot_in_another_case_or_anything_inside_it() {    let home = Path::new("/Users/someone");    for dir in [        // `..` through a folder that need not exist — `create_dir_all` would        // make it and then land in the real one.        home.join("CottonDev/../CottonDB"),        home.join("nowhere/../CottonDB"),        // The Mac's disk is case-insensitive.        home.join("cottondb"),        home.join("COTTONDB"),        home.join("library/application support/cottondb"),        // Inside the real folder is the real folder's.        home.join("CottonDB/scratch"),        home.join("CottonDB/a/b"),    ] {        assert!(Flavor::Dev.refusal_for_data_dir(home, &dir).is_some(), "dev would open {}", dir.display());    }    // A neighbour whose name merely STARTS with the real one is not inside it.    assert_eq!(Flavor::Dev.refusal_for_data_dir(home, &home.join("CottonDBX")), None);    assert_eq!(Flavor::Dev.refusal_for_data_dir(home, &home.join("CottonDev/data")), None);}#[cfg(unix)]#[test]fn a_dev_build_refuses_a_path_through_a_link_into_the_real_folder_even_before_it_exists() {    let scratch = std::env::temp_dir().join(format!("cotton-flavor-inside-{}", std::process::id()));    let home = scratch.join("home");    std::fs::create_dir_all(home.join("CottonDB").join("sub")).unwrap();    let link = scratch.join("shortcut");    let _ = std::fs::remove_file(&link);    std::os::unix::fs::symlink(home.join("CottonDB"), &link).unwrap();    let inside = scratch.join("into-sub");    let _ = std::fs::remove_file(&inside);    std::os::unix::fs::symlink(home.join("CottonDB").join("sub"), &inside).unwrap();    for dir in [link.join("not-yet"), link.join("a/b/c"), inside.clone(), inside.join("x")] {        assert!(Flavor::Dev.refusal_for_data_dir(&home, &dir).is_some(), "dev would open {}", dir.display());    }    assert_eq!(Flavor::Dev.refusal_for_data_dir(&home, &home.join("CottonDev")), None);    std::fs::remove_dir_all(&scratch).unwrap();}// RULE: A business installs only named, known tools; a typo must fail before a cut.#[test]fn business_manifest_validates_the_shipped_tools() {    use super::BusinessManifest;    let manifest = BusinessManifest::from_json(r#"{"name":"Fixture","icon":"fixture","theme":"plain","single_database":true,"tools":["people","notebook","todos"]}"#).unwrap();    assert_eq!(manifest.tools, ["people", "notebook", "todos"]);    assert!(BusinessManifest::from_json(r#"{"name":"Fixture","icon":"fixture","theme":"plain","single_database":true,"tools":["unknown-fixture"]}"#).is_err());    BusinessManifest::from_json(include_str!("../flavors/business.json")).unwrap();    // A manifest names its database (`shell::scope`); the strict schema reads it rather than refusing the app at open.    let named = BusinessManifest::from_json(r#"{"name":"Fixture","icon":"fixture","theme":"plain","single_database":true,"tools":["people"],"database":{"id":"db-fixture","host":"https://unit.example","named":"Fixture"}}"#).unwrap();    assert_eq!(named.database, Some(serde_json::json!({"id": "db-fixture", "host": "https://unit.example", "named": "Fixture"})));    if let Some(path) = std::env::var_os("COTTON_BUSINESS_MANIFEST") {        BusinessManifest::from_json(&std::fs::read_to_string(path).unwrap()).unwrap();    }    assert_eq!(super::Flavor::from_declared(Some("business")), super::Flavor::Business);    assert!(super::Flavor::Business.refusal_for_data_dir("/synthetic", std::path::Path::new("/synthetic/CottonDB")).is_some());}// RULE: there is no first-open choice (owner, 6 Nov 2026): every app that founds Personal starts its own database, so a manifest saying `first_open` is a broken one, refused as an unknown key.#[test]fn a_manifest_names_no_first_open() {    use super::BusinessManifest;    let base = r#""name":"Fixture","icon":"fixture","theme":"plain","single_database":true,"tools":["people"]"#;    assert!(BusinessManifest::from_json(&format!("{{{base}}}")).is_ok());    assert!(BusinessManifest::from_json(&format!(r#"{{{base},"first_open":"start"}}"#)).is_err());}// RULE: the manifest's `fan` key is add-only: absent, the dial holds Home and// Tools as Cotton's does, and a manifest that never says it serialises// without it; Rigby names both false (owner, 22 Oct 2026: no Home and no Tools// card in Rigby, Settings the last card in place of Tools); an unknown card is a broken manifest, refused before a cut.#[test]fn the_fan_key_is_add_only_and_absent_is_cottons_dial() {    use super::{BusinessManifest, FanCards};    let base = r#""name":"Fixture","icon":"fixture","theme":"plain","single_database":true,"tools":["people"]"#;    let plain = BusinessManifest::from_json(&format!("{{{base}}}")).unwrap();    assert_eq!(plain.fan, FanCards { home: true, tools: true, settings: false, opens: None, stream: false });    assert!(!serde_json::to_string(&plain).unwrap().contains("\"fan\""), "absent stays unsaid");    let rigby = BusinessManifest::from_json(&format!(r#"{{{base},"fan":{{"home":false,"tools":false,"settings":true,"opens":"todos"}}}}"#)).unwrap();    assert_eq!(rigby.fan, FanCards { home: false, tools: false, settings: true, opens: Some("todos".into()), stream: false });    let half = BusinessManifest::from_json(&format!(r#"{{{base},"fan":{{"tools":false}}}}"#)).unwrap();    assert_eq!(half.fan, FanCards { home: true, tools: false, settings: false, opens: None, stream: false });    assert!(BusinessManifest::from_json(&format!(r#"{{{base},"fan":{{"me":false}}}}"#)).is_err());}// RULE: the manifest's `sync` key is add-only: absent, the app syncs as Cotton// does and a manifest that never says it serialises without it; Rigby says// false (architect, 22 Oct 2026: one device, no Mac); a word that is not true// or false is a broken manifest, refused before a cut.#[test]fn the_sync_key_is_add_only_and_absent_syncs() {    use super::{syncs, BusinessManifest};    let base = r#""name":"Fixture","icon":"fixture","theme":"plain","single_database":true,"tools":["people"]"#;    let plain = BusinessManifest::from_json(&format!("{{{base}}}")).unwrap();    assert!(plain.sync);    assert!(!serde_json::to_string(&plain).unwrap().contains("\"sync\""), "absent stays unsaid");    assert!(!BusinessManifest::from_json(&format!(r#"{{{base},"sync":false}}"#)).unwrap().sync);    assert_eq!(syncs(None), Ok(true));    assert_eq!(syncs(Some(&serde_json::json!({"name": "Fixture"}))), Ok(true));    assert_eq!(syncs(Some(&serde_json::json!({"sync": false}))), Ok(false));    assert!(syncs(Some(&serde_json::json!({"sync": "no"}))).is_err());}// RULE: A business build cannot address either Cotton identity's data or relay.#[test]fn business_identity_is_separate_from_both_cottons() {    let home = Path::new("/synthetic/home");    for other in [Flavor::Real, Flavor::Dev] {        assert_ne!(Flavor::Business.default_port(), other.default_port());        assert!(Flavor::Business.refusal_for_data_dir(home, &other.home_data_dir(home)).is_some());        assert!(other.refusal_for_data_dir(home, &Flavor::Business.home_data_dir(home)).is_some());        assert!(Flavor::Business.refusal_for_server(Some(other.as_str())).is_some());        assert!(other.refusal_for_server(Some("business")).is_some());    }    for name in ["fixture", "fixture-dev", "fixture-business"] { assert!(!Flavor::Business.admits_relay_name(name)); }    assert!(Flavor::Business.refusal_for_data_dir(home, &home.join("Library/Application Support/CottonDB")).is_some());}/// RULE (owner, 24 Oct 2026): a business app names its object — the Worker and/// its slug — and the core opens it: a business flavour parses, validates, and/// carries `business`; the old Rust-served web face is gone. No business app/// ships now (Sharmila's and Nancy's left the tree, 22 Nov 2026), so the/// manifest is a synthetic one shaped as they shipped.#[test]fn a_business_flavour_names_its_object() {    use super::BusinessManifest;    for (file, slug) in [        (r#"{"genesis":"none","flavour":"kitchen","name":"Synthetic Kitchen","databases":"single","fan":{"tools":false},"tools":["people","messages","kitchen"],"business":{"server":"https://cotton-business.synthetic.workers.dev","slug":"kitchen"}}"#, "kitchen"),    ] {        let manifest = BusinessManifest::from_json(file).unwrap_or_else(|e| panic!("{slug}: {e}"));        manifest.validate().unwrap_or_else(|e| panic!("{slug}: {e}"));        let business = manifest.business.as_ref().unwrap_or_else(|| panic!("{slug} names no business object"));        assert_eq!(business.slug, slug);        assert!(business.server.starts_with("https://"), "{slug}: {}", business.server);    }    // The old stack's blocks are no manifest's words: a manifest naming one is refused.    for gone in [r#""customers":{"database":"x"}"#, r#""web":{"database":"x","relay":"x","pages":{}}"#, r#""owner":{"name":"x","phone":"+1"}"#] {        let json = format!(r#"{{"name":"F","icon":"f","theme":"plain","single_database":true,"tools":["people"],{gone}}}"#);        assert!(BusinessManifest::from_json(&json).is_err(), "{gone}");    }    // Reading a manifest validates it: a wrong address or slug never reaches the app.    assert!(BusinessManifest::from_json(r#"{"name":"F","icon":"f","theme":"plain","single_database":true,"tools":["people"],"business":{"server":"ftp://x","slug":"f"}}"#).is_err());    assert!(BusinessManifest::from_json(r#"{"name":"F","icon":"f","theme":"plain","single_database":true,"tools":["people"],"business":{"server":"https://x","slug":"Not A Slug"}}"#).is_err());}