Cotton code
607 lines · 24.9 KB · RustRaw
//! Read one database backup through the phone's `read.home` boundary.//!//! `cotton-home-probe SOURCE` never opens SOURCE for writing. It first makes//! a disposable SQLite copy, then gives only that copy to a phone-mode FFI handle. The command prints no records;//! an error is passed through the application's reported-state redactor.use std::path::Path;use cotton_client::replica::{open_replica_with, OpenReplicaInput, ReplicaError};use cotton_client::seams::{Clock, FixedClock, Random, SeededRandom};use cotton_ffi::{dispatch, CottonHandle, OpenConfig};use cotton_store::meta::read_meta;use serde_json::json;const USAGE: &str =    "usage: cotton-home-probe [--json] [--device-copy] FILE [OTHER_FILE ...] | --data-dir";const PHONE_SNAPSHOT_DEVICE: &str = "probe-phone";#[derive(Debug)]struct ProbeReport {    file: String,    schema: Option<u32>,    error: Option<String>,}fn main() {    let mut args = std::env::args_os().skip(1).collect::<Vec<_>>();    if args.as_slice() == ["--data-dir"] {        let home = std::env::var_os("HOME").expect("HOME is required");        let over = std::env::var(cotton_client::data_dir::DATA_DIR_ENV).ok();        println!(            "{}",            cotton_client::data_dir::resolve_data_dir(                cotton_core::flavor::Flavor::Real,                home,                over.as_deref()            )            .path            .display()        );        return;    }    let json_output = args.first().is_some_and(|arg| arg == "--json");    if json_output {        args.remove(0);    }    let device_copy = args.first().is_some_and(|arg| arg == "--device-copy");    if device_copy {        args.remove(0);    }    if args.is_empty()        || args            .iter()            .any(|arg| arg.to_string_lossy().starts_with("--"))    {        eprintln!("{USAGE}");        std::process::exit(2);    }    let paths = args.iter().map(Path::new).collect::<Vec<_>>();    match probe_reports(&paths, device_copy, false) {        Ok(reports) => {            for report in &reports {                if json_output {                    println!(                        "{}",                        json!({"file": report.file, "schema": report.schema, "ok": report.error.is_none(), "error": report.error})                    );                } else {                    println!(                        "{} · schema {} · {}",                        report.file,                        report                            .schema                            .map_or_else(|| "unreadable".into(), |v| v.to_string()),                        report.error.as_deref().unwrap_or("ok")                    );                }            }            if reports.iter().any(|report| report.error.is_some()) {                std::process::exit(1);            }        }        Err(error) => {            eprintln!("read.home: {}", redact(&error));            std::process::exit(1);        }    }}#[cfg(test)]fn probe_files(sources: &[&Path]) -> Result<(), String> {    let reports = probe_reports(sources, false, false)?;    reports        .into_iter()        .find_map(|report| {            report                .error                .map(|error| format!("{}: {error}", report.file))        })        .map_or(Ok(()), Err)}fn probe_reports(    sources: &[&Path],    device_copy: bool,    bypass_mover: bool,) -> Result<Vec<ProbeReport>, String> {    let scratch =        tempfile::tempdir().map_err(|error| format!("scratch cannot be made: {error}"))?;    let container = scratch.path().join("phone");    let layout = cotton_client::layout::Layout::new(&container);    let mut reports = Vec::new();    let mut workspaces = Vec::new();    for (index, source) in sources.iter().enumerate() {        let mut report = ProbeReport {            file: source.display().to_string(),            schema: None,            error: None,        };        let prepare = || -> Result<String, String> {            let info = std::fs::metadata(source).map_err(|error| {                if error.kind() == std::io::ErrorKind::NotFound {                    "absent".into()                } else {                    format!("source cannot be read: {error}")                }            })?;            if !info.is_file() {                return Err("source is not a database file".into());            }            let snapshot = scratch.path().join(format!("snapshot-{index}.db"));            // Production snapshot writer, immutable source: no backup sidecars.            copy_of_backup(source, &snapshot)?;            let db = cotton_store::Driver::open(&snapshot).map_err(|e| e.to_string())?;            report.schema =                Some(cotton_store::migrate::current_version(&db).map_err(|e| e.to_string())?);            // A test seam reproduces the former refusal before the phone's mover.            if bypass_mover {                cotton_store::migrate::migration_plan(&db).map_err(|e| e.to_string())?;            }            drop(db);            if !device_copy {                strip_snapshot(                    &snapshot,                    PHONE_SNAPSHOT_DEVICE,                    FixedClock::default_start().now().timestamp_millis(),                )?;            }            let workspace = workspace_id(&snapshot)?;            if workspaces.iter().any(|(_, id)| id == &workspace) {                return Err("two supplied files name the same database".into());            }            let replica = layout.replica(&workspace);            std::fs::create_dir_all(replica.parent().ok_or("replica has no folder")?)                .map_err(|error| format!("phone scratch cannot be made: {error}"))?;            std::fs::rename(&snapshot, &replica)                .map_err(|error| format!("snapshot cannot be placed: {error}"))?;            if device_copy {                open_as_phone(&layout, &workspace)?;            } else {                claim_as_phone(&layout, &workspace, &replica)?;            }            Ok(workspace)        };        let mut prepare = prepare;        match prepare() {            Ok(workspace) => workspaces.push((index, workspace)),            Err(error) => report.error = Some(redact(&error)),        }        reports.push(report);    }    if workspaces.is_empty() {        return Ok(reports);    }    let read = (|| -> Result<(), String> {        write_connection(            &layout,            &workspaces                .iter()                .map(|(_, id)| id.clone())                .collect::<Vec<_>>(),        )?;        let config: OpenConfig = serde_json::from_value(            json!({"containerPath": container, "flavor": "dev", "timeZone": "Etc/UTC"}),        )        .map_err(|error| format!("phone configuration: {error}"))?;        let phone =            CottonHandle::open(config).map_err(|error| format!("phone open: {}", error.message))?;        // Home is a one-database read. Ask it for EVERY file, then use the phone's        // aggregate feeds (Today, Asked of you, Find) to catch cross-file refusals.        for (index, workspace) in &workspaces {            if let Err(error) = dispatch(&phone, "read.home", &json!({"database": workspace})) {                reports[*index].error = Some(redact(&format!("{}: {}", error.code, error.message)));            }        }        let now = chrono::Utc::now();        let from = now.format("%Y-%m-%dT00:00:00Z").to_string();        let to = (now + chrono::Duration::days(1))            .format("%Y-%m-%dT00:00:00Z")            .to_string();        for method in ["read.day", "read.decide", "read.find"] {            let answer = dispatch(&phone, method, &json!({"database":"all", "query":"probe", "timezone":"Etc/UTC", "from": from, "to": to, "now": now.to_rfc3339()})).map_err(|error| format!("{method}: {}: {}", error.code, error.message))?;            for refusal in answer["skippedDatabases"].as_array().into_iter().flatten() {                if let Some((index, _)) = workspaces                    .iter()                    .find(|(_, id)| Some(id.as_str()) == refusal["databaseId"].as_str())                {                    reports[*index].error = Some(redact(&format!(                        "{method}: {}: {}",                        refusal["refusal"]                            .as_str()                            .unwrap_or("Could not read this database."),                        refusal["reason"].as_str().unwrap_or("unreadable")                    )));                } else {                    return Err(format!("{method}: an unrecognized database was refused"));                }            }            for arrival in answer["arrivingDatabases"].as_array().into_iter().flatten() {                if let Some((index, _)) = workspaces                    .iter()                    .find(|(_, id)| Some(id.as_str()) == arrival["databaseId"].as_str())                {                    reports[*index].error = Some(format!("{method}: the copy has not arrived"));                }            }        }        Ok(())    })();    if let Err(error) = read {        for report in &mut reports {            if report.error.is_none() {                report.error = Some(redact(&error));            }        }    }    Ok(reports)}/// A previous build's already claimed copy opens without snapshot stripping/// or re-claiming, preserving its outbox for the phone's migration refusal.fn open_as_phone(layout: &cotton_client::layout::Layout, workspace: &str) -> Result<(), String> {    let clock = FixedClock::default_start();    let random = SeededRandom::default();    let mut no_fetch = |_destination: &Path| Err("absent".to_string());    open_replica_with(OpenReplicaInput {        layout,        workspace_id: workspace,        clock: &clock,        random: &random,        judge: None,        bootstrap: &mut no_fetch,        on_migration: None,        on_bootstrapped: None,        receipt_signer: cotton_store::signed::SignerSlot::default(),    })    .map(|_| ())    .map_err(|e| format!("phone open: {e}"))}/// Claim a delivered snapshot through the same `open_replica_with` bootstrap/// seam the phone uses before a handle is allowed to read it.fn claim_as_phone(    layout: &cotton_client::layout::Layout,    workspace: &str,    replica: &Path,) -> Result<(), String> {    let mark = replica.with_file_name(format!(        "{}.unclaimed",        replica            .file_name()            .and_then(|name| name.to_str())            .unwrap_or("replica.db")    ));    std::fs::write(&mark, b"").map_err(|error| format!("snapshot cannot be marked: {error}"))?;    let clock = FixedClock::default_start();    let random = SeededRandom::default();    let claim_random = random.clone();    let mut ids =        cotton_store::protocol::ulid::Monotonic::new(move |out: &mut [u8]| claim_random.fill(out));    let mut no_fetch =        |_destination: &Path| Err("the probe snapshot is already placed".to_string());    let mut claim = |driver: &cotton_store::driver::Driver, device_id: &str| {        cotton_client::bootstrap::claim_snapshot(            driver,            device_id,            0,            clock.now().timestamp_millis(),            &mut ids,        )        .map(|_| ())        .map_err(ReplicaError::Store)    };    open_replica_with(OpenReplicaInput {        layout,        workspace_id: workspace,        clock: &clock,        random: &random,        judge: None,        bootstrap: &mut no_fetch,        on_migration: None,        on_bootstrapped: Some(&mut claim),        receipt_signer: cotton_store::signed::SignerSlot::default(),    })    .map_err(|error| format!("phone bootstrap: {error}"))?;    // The hand-off mark is cleared once the claim callback commits. This probe    // drives the low-level bootstrap seam without a transport, so it clears    // the mark itself.    std::fs::remove_file(&mark)        .map_err(|error| format!("phone bootstrap cannot clear its mark: {error}"))?;    if mark.exists() {        return Err("phone bootstrap did not clear its unclaimed mark".to_string());    }    Ok(())}fn workspace_id(snapshot: &Path) -> Result<String, String> {    let driver = cotton_store::driver::Driver::open(snapshot).map_err(|error| error.to_string())?;    read_meta(&driver)        .map_err(|error| error.to_string())?        .map(|meta| meta.workspace_id)        .ok_or_else(|| "snapshot names no database".to_string())}fn write_connection(    layout: &cotton_client::layout::Layout,    workspaces: &[String],) -> Result<(), String> {    let record = cotton_client::connection::ConnectionRecord {        mine: cotton_client::connection::StoredConnection {            device_scope: None,            takes_placements: false,            mode: cotton_client::connection::ConnectionMode::Local,            base_url: String::new(),            workspace_id: workspaces.first().cloned(),            owner_id: None,            connected_at: None,        },        places: workspaces            .iter()            .skip(1)            .enumerate()            .map(|(index, id)| cotton_client::connection::PlaceEntry {                id: id.clone(),                name: Some(format!("Synthetic database {}", index + 1)),                available: true,                unavailable_since: None,                origin: None,                server_device_id: None,                removed_at: None,                removed_by: None,                pending: false,                toolkit: None,            })            .collect(),        left_databases: Vec::new(),        pending_leaves: Vec::new(),    };    cotton_client::connection::write_record(&layout.connection_json(), &record)        .map_err(|error| error.to_string())}/// A consistent copy of an immutable source, with no backup sidecars: `VACUUM/// INTO` from a read-only, `immutable=1` connection.fn copy_of_backup(source: &Path, destination: &Path) -> Result<(), String> {    let absolute = std::fs::canonicalize(source).map_err(|error| format!("backup path: {error}"))?;    let mut uri =        url::Url::from_file_path(absolute).map_err(|_| "backup is not a file path".to_string())?;    uri.query_pairs_mut().append_pair("immutable", "1");    let reader = rusqlite::Connection::open_with_flags(        uri.as_str(),        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY            | rusqlite::OpenFlags::SQLITE_OPEN_URI            | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,    )    .map_err(|error| error.to_string())?;    reader        .execute("VACUUM INTO ?", [destination.display().to_string()])        .map_err(|error| error.to_string())?;    Ok(())}/// The copy cut for one phone by its keep rules, its pages given back.fn strip_snapshot(path: &Path, device_id: &str, now_ms: i64) -> Result<(), String> {    let db = cotton_store::Driver::open(path).map_err(|error| error.to_string())?;    cotton_store::snapshot::strip_for_device(&db, device_id, now_ms)        .map_err(|error| error.to_string())?;    db.exec("VACUUM").map_err(|error| error.to_string())?;    Ok(())}fn redact(line: &str) -> String {    cotton_core::device::reported_state::redact_line(line)}#[cfg(test)]mod tests {    use super::*;    use cotton_core::definitions::{builtin_table_definitions, BUILTIN_DEFINITIONS_STAMP};    use cotton_store::meta::Meta;    use rusqlite::types::Value as SqlValue;    /// RULE: A phone holding thirteen arrived schema-135 snapshots with stored Mac definitions reads Personal Home; other held files cannot turn that single-file read into a cross-file failure.    #[test]    fn thirteen_arrived_snapshots_with_stored_definitions_read_personal_home() {        let dir = tempfile::tempdir().expect("scratch");        let mut sources = Vec::new();        for index in 1..=13 {            let workspace = format!("{index:08}-1111-4111-8111-111111111111");            let source = dir.path().join(format!("source-{index}.db"));            let db = cotton_store::driver::Driver::open(&source).expect("source");            cotton_store::create::create_workspace(                &db,                &Meta {                    workspace_id: workspace.clone(),                    owner_id: "synthetic-owner".into(),                    device_id: "device:synthetic".into(),                    last_server_seq: 0,                    last_hlc: None,                },            )            .expect("schema");            db.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, 'Synthetic', 'synthetic-owner', '2026-10-12T00:00:00.000Z')", &[SqlValue::Text(workspace.clone())]).expect("workspace");            for definition in builtin_table_definitions() {                db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, instructions_edited, builtin_stamp, created_at, updated_at, _hlc) VALUES (?, ?, ?, 1, 0, ?, ?, ?, '')", &[                    SqlValue::Text(definition.id.clone()), SqlValue::Text(workspace.clone()),                    SqlValue::Text(serde_json::to_string(&definition).expect("definition")),                    SqlValue::Integer(BUILTIN_DEFINITIONS_STAMP),                    SqlValue::Text("2026-10-12T00:00:00.000Z".into()), SqlValue::Text("2026-10-12T00:00:00.000Z".into()),                ]).expect("stored Mac definition");            }            drop(db);            sources.push(source);        }        probe_files(            &sources                .iter()                .map(|source| source.as_path())                .collect::<Vec<_>>(),        )        .expect("the complete phone state reads");    }    /// RULE: The owner-file probe cuts its own snapshot and opens it through the phone FFI, so checking a backup can never write the supplied database.    #[test]    fn a_synthetic_backup_reads_through_the_phone_boundary_without_changing_source() {        let dir = tempfile::tempdir().expect("scratch");        let source = dir.path().join("source.db");        let db = cotton_store::driver::Driver::open(&source).expect("source opens");        cotton_store::create::create_workspace(            &db,            &Meta {                workspace_id: "11111111-1111-4111-8111-111111111111".to_string(),                owner_id: "synthetic-owner".to_string(),                device_id: "device:synthetic".to_string(),                last_server_seq: 0,                last_hlc: None,            },        )        .expect("workspace");        db.run(            "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, ?, ?, ?)",            &[                SqlValue::Text("11111111-1111-4111-8111-111111111111".to_string()),                SqlValue::Text("Synthetic".to_string()),                SqlValue::Text("synthetic-owner".to_string()),                SqlValue::Text("2026-10-12T00:00:00.000Z".to_string()),            ],        )        .expect("workspace row");        // This is the reported phone failure's shape: a stored built-in from        // the serving Mac names a column this copied file does not have. The        // source is otherwise a normal snapshot, so this specifically proves        // the phone FFI gets the definitions fallback before `read.home`.        let mut definition = serde_json::to_value(            builtin_table_definitions()                .into_iter()                .find(|definition| definition.id == "todo")                .expect("the todo built-in ships"),        )        .expect("definition JSON");        definition["columns"]            .as_array_mut()            .expect("definition columns")            .push(json!({"key": "later_reading", "name": "Later reading", "type": "text"}));        db.run(            "INSERT INTO cotton_table_definitions \             (id, workspace_id, definition, builtin, instructions_edited, builtin_stamp, created_at, updated_at, _hlc) \             VALUES (?, ?, ?, 1, 0, ?, ?, ?, '')",            &[                SqlValue::Text("todo".to_string()),                SqlValue::Text("11111111-1111-4111-8111-111111111111".to_string()),                SqlValue::Text(definition.to_string()),                SqlValue::Integer(BUILTIN_DEFINITIONS_STAMP),                SqlValue::Text("2026-10-12T00:00:00.000Z".to_string()),                SqlValue::Text("2026-10-12T00:00:00.000Z".to_string()),            ],        )        .expect("stored newer definition");        drop(db);        let before = std::fs::read(&source).expect("source bytes");        let mtime = std::fs::metadata(&source).unwrap().modified().unwrap();        probe_files(&[&source]).expect("phone home reads copied snapshot");        assert_eq!(std::fs::read(&source).expect("source remains"), before);        assert_eq!(            std::fs::metadata(&source).unwrap().modified().unwrap(),            mtime        );        assert!(            !source.with_extension("db-wal").exists(),            "a backup probe must not create a WAL"        );        assert!(            !source.with_extension("db-shm").exists(),            "a backup probe must not create shared memory"        );    }    /// RULE: An absent household copy fails by filename; a successful read of the other copies must never hide a missing database.    #[test]    fn absent_file_is_a_named_failure() {        let dir = tempfile::tempdir().unwrap();        let missing = dir.path().join("absent.db");        let reports = probe_reports(&[&missing], false, false).unwrap();        assert_eq!(reports[0].file, missing.display().to_string());        assert_eq!(reports[0].error.as_deref(), Some("absent"));    }    /// RULE: Twelve previous-schema household copies must migrate through the phone path; bypassing that mover refuses each old file by name, and probing leaves every backup's bytes and mtime unchanged.    #[test]    fn thirteen_files_move_through_phone_and_bypassing_mover_is_red() {        let dir = tempfile::tempdir().unwrap();        let mut sources = Vec::new();        for index in 1..=13 {            let path = dir.path().join(format!("household-{index}.db"));            let db = cotton_store::Driver::open(&path).unwrap();            let version = if index == 1 {                cotton_store::schema::ddl::SCHEMA_VERSION            } else {                141            };            if index == 1 {                cotton_store::create::apply_schema(&db).unwrap();            } else {                let mut objects: Vec<cotton_store::create::SchemaObject> = serde_json::from_str(                    include_str!("../../cotton-store/tests/fixtures/schema-v141.json"),                )                .unwrap();                objects.sort_by_key(|o| match o.kind.as_str() {                    "table" if o.is_fts5_virtual() => 1,                    "table" => 0,                    "index" => 2,                    _ => 3,                });                for object in objects {                    db.exec(&object.sql).unwrap();                }            }            let workspace = format!("{index:08}-1111-4111-8111-111111111111");            cotton_store::meta::seed_meta(                &db,                &Meta {                    workspace_id: workspace.clone(),                    owner_id: "synthetic-owner".into(),                    device_id: "device:synthetic".into(),                    last_server_seq: 0,                    last_hlc: None,                },                version,            )            .unwrap();            db.exec(&format!("PRAGMA user_version={version}")).unwrap();            db.run("INSERT INTO cotton_workspaces (id,name,owner_user_id,created_at) VALUES (?,'Synthetic','synthetic-owner','2026-10-12T00:00:00Z')", &[SqlValue::Text(workspace)]).unwrap();            db.checkpoint_truncate().unwrap();            drop(db);            sources.push(path);        }        let before: Vec<_> = sources            .iter()            .map(|p| {                (                    std::fs::read(p).unwrap(),                    std::fs::metadata(p).unwrap().modified().unwrap(),                )            })            .collect();        let paths: Vec<_> = sources.iter().map(|p| p.as_path()).collect();        let reports = probe_reports(&paths, false, false).unwrap();        assert!(reports.iter().all(|r| r.error.is_none()), "{reports:?}");        let bypassed = probe_reports(&paths, false, true).unwrap();        for report in bypassed.iter().skip(1) {            assert!(                report.error.as_deref().unwrap().contains("schema 141"),                "{report:?}"            );            assert!(report.file.contains("household-"));        }        let device = probe_reports(&[paths[1]], true, false).unwrap();        assert!(device[0].error.is_none(), "{device:?}");        assert_eq!(device[0].schema, Some(141));        for (path, (bytes, mtime)) in sources.iter().zip(before) {            assert_eq!(std::fs::read(path).unwrap(), bytes);            assert_eq!(std::fs::metadata(path).unwrap().modified().unwrap(), mtime);            assert!(!path.with_extension("db-wal").exists());            assert!(!path.with_extension("db-shm").exists());        }    }}