Cotton code
168 lines · 10.5 KB · RustRaw
//! The one question of a local vault key (KEPT FOUR 2): which rows depend on it, read from what the copies hold.//! Synthetic rows and keys only.use super::*;fn copy_at(dir: &Path, name: &str) -> PathBuf {    let path = dir.join(name);    let db = rusqlite::Connection::open(&path).unwrap();    db.execute_batch(        "CREATE TABLE cotton_vault_keys (id TEXT PRIMARY KEY, workspace_id TEXT, device_id TEXT, public_key TEXT, wrapped_vmk TEXT, vmk_version INTEGER);         CREATE TABLE cotton_secrets (id TEXT PRIMARY KEY, value_enc TEXT, history_enc TEXT, vmk_version INTEGER);         CREATE TABLE cotton_passkey (id TEXT PRIMARY KEY, private_key_enc TEXT, vmk_version INTEGER);",    )    .unwrap();    path}fn run(path: &Path, sql: &str) {    rusqlite::Connection::open(path).unwrap().execute_batch(sql).unwrap();}/// RULE (KEPT FOUR 2, "enumerate them"): every kit table holding a `vmk_version` is either in SEALED (it travels/// and seals a column under the vault key) or named in NOT_SEALED_HERE with why: a new one cannot be missed.#[test]fn every_table_sealed_under_the_vault_key_is_named() {    let kits = Path::new(env!("CARGO_MANIFEST_DIR")).join("../cotton-core/kits");    let mut found = Vec::new();    for kit in std::fs::read_dir(&kits).unwrap().flatten() {        for table in std::fs::read_dir(kit.path().join("tables")).into_iter().flatten().flatten() {            let text = std::fs::read_to_string(table.path()).unwrap_or_default();            if text.contains("\"vmk_version\"") {                found.push(table.path().file_stem().unwrap().to_string_lossy().into_owned());            }        }    }    found.sort();    found.dedup();    assert!(!found.is_empty(), "the kits were read");    for table in &found {        let sealed = SEALED.iter().any(|(store, _, _)| store.trim_start_matches("cotton_") == table || store.trim_start_matches("cotton_") == format!("{table}s"));        let named = NOT_SEALED_HERE.iter().any(|(name, _)| name == table);        assert!(sealed || named, "the kit table {table} holds a vmk_version: name it in SEALED or NOT_SEALED_HERE with why");    }}/// RULE: a copy with no vault key leaves nothing depending on it; one whose wrap the live copy holds founded the/// account; a row the live copy holds byte for byte as the copy sealed it depends on the key, and one sealed again/// (or written by a device holding only the account's key) does not./// A server read that answered every page: `rows` as (store table, id, version, deleted, sealed columns), `wraps`/// the live wraps.fn read_of(rows: &[(&str, &str, i64, bool, &[(&str, &str)])], wraps: &[&str]) -> ServerRead {    let mut reading = ServerReading::default();    for (table, id, version, deleted, sealed) in rows {        reading.row(table, id, ServerRow { version: *version, deleted: *deleted, sealed: sealed.iter().map(|(c, v)| ((*c).to_string(), (*v).to_string())).collect() });    }    for wrap in wraps {        reading.wrap(wrap);    }    reading.finish(true).expect("a complete read")}fn layout_in(dir: &Path) -> crate::layout::Layout {    crate::layout::Layout::new(dir.join("root"))}/// RULE (KEPT FOUR 3 B): the local key's wrap and the rows sealed under it are kept in a file of their own, from the/// local database's own copy (never a `.before-update` one), so removing every copy leaves the key.#[test]fn a_local_key_lives_in_its_own_file_and_outlives_every_copy() {    let dir = tempfile::tempdir().unwrap();    let layout = layout_in(dir.path());    let local = copy_at(dir.path(), "replica.db");    assert_eq!(secure(&layout, "local-db", &[local.clone()], None).unwrap(), 0, "no key: nothing written");    assert!(key_file(&layout, "local-db").unwrap().is_none());    run(&local, "INSERT INTO cotton_vault_keys VALUES ('founder:d', 'l', 'd', 'pub', 'w1:LOCAL', 1);                 INSERT INTO cotton_secrets VALUES ('s1', 'v2:LOCAL-ONE', NULL, 1);");    // A password deleted before sign-in is only in the copy an upgrade kept: never recorded.    let before = copy_at(dir.path(), "replica.db.before-update");    run(&before, "INSERT INTO cotton_vault_keys VALUES ('founder:d', 'l', 'd', 'pub', 'w1:LOCAL', 1);                  INSERT INTO cotton_secrets VALUES ('s1', 'v2:LOCAL-ONE', NULL, 1), ('deleted-before-sign-in', 'v2:LOCAL-GONE', NULL, 1);");    assert_eq!(secure(&layout, "local-db", &[local.clone(), before.clone()], Some("account")).unwrap(), 1);    let file = key_file(&layout, "local-db").unwrap().unwrap();    assert_eq!(file.keys.iter().map(|key| key.wrapped_vmk.as_str()).collect::<Vec<_>>(), vec!["w1:LOCAL"]);    assert_eq!(file.sealed.iter().map(|row| row.id.as_str()).collect::<Vec<_>>(), vec!["s1"], "never a .before-update copy's rows");    assert_eq!(file.account.as_deref(), Some("account"));    std::fs::remove_file(&local).unwrap();    std::fs::remove_file(&before).unwrap();    assert_eq!(key_files(&layout).unwrap()[0].keys[0].wrapped_vmk, "w1:LOCAL", "every copy gone, the key stays");}/// RULE (KEPT FOUR 3 C, the three cases): carried means the SERVER holds it. Offline (no read, the carry done in the/// copy only): the key and its folder stay; the push refused (the server does not hold the row): they stay; the push/// accepted (the server holds it sealed again, at its version): the key goes, written down, and the folder may go.#[test]fn a_local_key_goes_only_when_the_server_holds_every_row_sealed_again() {    let dir = tempfile::tempdir().unwrap();    let layout = layout_in(dir.path());    let local = copy_at(dir.path(), "replica.db");    run(&local, "INSERT INTO cotton_vault_keys VALUES ('founder:d', 'l', 'd', 'pub', 'w1:LOCAL', 1);                 INSERT INTO cotton_secrets VALUES ('s1', 'v2:LOCAL-ONE', 'v2:LOCAL-HISTORY', 1);");    secure(&layout, "local-db", &[local.clone()], Some("account")).unwrap();    assert!(!copies_may_go(&layout, &[local.clone()]).unwrap());    // Offline: the carry ran into the live copy, recovery runs before any push: no read, nothing settles.    assert_eq!(settle(&layout, "local-db", None).unwrap(), Evidence::NotRead);    assert!(key_file(&layout, "local-db").unwrap().is_some() && !copies_may_go(&layout, &[local.clone()]).unwrap());    // The push refused: the server holds no such row.    assert_eq!(settle(&layout, "local-db", Some(&read_of(&[], &["w1:ACCOUNT"]))).unwrap(), Evidence::Depends(vec![("cotton_secrets".into(), "s1".into())]));    assert!(!copies_may_go(&layout, &[local.clone()]).unwrap());    // Half sealed again on another phone (a new value, its history still the local key's): still depends.    let half = read_of(&[("cotton_secrets", "s1", 7, false, &[("value_enc", "v2:ACCOUNT-ONE"), ("history_enc", "v2:LOCAL-HISTORY")])], &["w1:ACCOUNT"]);    assert!(matches!(settle(&layout, "local-db", Some(&half)).unwrap(), Evidence::Depends(_)));    // The push accepted: the server holds it sealed again, at its version: the key goes, and the folder may.    let held = read_of(&[("cotton_secrets", "s1", 8, false, &[("value_enc", "v2:ACCOUNT-ONE"), ("history_enc", "v2:ACCOUNT-HISTORY")])], &["w1:ACCOUNT"]);    assert!(matches!(settle(&layout, "local-db", Some(&held)).unwrap(), Evidence::Settled(_)));    assert!(key_file(&layout, "local-db").unwrap().is_none());    assert!(copies_may_go(&layout, &[local.clone()]).unwrap());    // An unfinished read is no read.    let mut part = ServerReading::default();    part.wrap("w1:ACCOUNT");    assert!(part.finish(false).is_none());}/// RULE (KEPT FOUR 3 B): a key that founded the account (the server took its wrap) goes on that alone; a file made/// from a wrap alone, knowing no rows, goes only when the server holds that very wrap; a removal on the server counts.#[test]fn a_founding_key_goes_on_the_founding_and_a_wrap_alone_only_on_the_wrap() {    let dir = tempfile::tempdir().unwrap();    let layout = layout_in(dir.path());    let local = copy_at(dir.path(), "replica.db");    run(&local, "INSERT INTO cotton_vault_keys VALUES ('founder:d', 'l', 'd', 'pub', 'w1:LOCAL', 1); INSERT INTO cotton_secrets VALUES ('s1', 'v2:LOCAL-ONE', NULL, 1);");    secure(&layout, "founded-db", &[local.clone()], None).unwrap();    note_founded(&layout, "founded-db", "account").unwrap();    assert!(matches!(settle(&layout, "founded-db", None).unwrap(), Evidence::Settled(_)));    // The race walk against the real Worker (28 Nov): the copy still holds the founding wrap, and the adopt and the    // kept folder secure from it again; a wrap let go never comes back as a key file.    assert_eq!(secure(&layout, "founded-db", &[local.clone()], Some("account")).unwrap(), 0, "a let-go wrap is not secured again");    assert!(key_file(&layout, "founded-db").unwrap().is_none());    assert!(copies_may_go(&layout, &[local.clone()]).unwrap());    let wrap = HeldKey { id: "founder:e".into(), device_id: "e".into(), public_key: "pub-e".into(), wrapped_vmk: "w1:KEPT-ROW".into(), vmk_version: 1 };    secure_wrap(&layout, "kept-row:founder:e", wrap).unwrap();    assert_eq!(settle(&layout, "kept-row:founder:e", Some(&read_of(&[], &[]))).unwrap(), Evidence::NotRead, "no rows known: a read alone never lets it go");    assert!(matches!(settle(&layout, "kept-row:founder:e", Some(&read_of(&[], &["w1:KEPT-ROW"]))).unwrap(), Evidence::Settled(_)));    let other = copy_at(dir.path(), "other.db");    run(&other, "INSERT INTO cotton_vault_keys VALUES ('founder:f', 'o', 'f', 'pub-f', 'w1:OTHER', 1); INSERT INTO cotton_secrets VALUES ('s9', 'v2:OTHER-ONE', NULL, 1);");    secure(&layout, "other-db", &[other.clone()], Some("account")).unwrap();    assert!(matches!(settle(&layout, "other-db", Some(&read_of(&[("cotton_secrets", "s9", 3, true, &[])], &[]))).unwrap(), Evidence::Settled(_)), "removed on the server: nothing depends");}/// RULE (KEPT FOUR 3 LOW): a row linking to a row sealed under the local key is found, so it waits with it.#[test]fn a_row_naming_a_held_back_row_is_found() {    let dir = tempfile::tempdir().unwrap();    let local = copy_at(dir.path(), "replica.db");    run(&local, "CREATE TABLE cotton_vault_placements (id TEXT PRIMARY KEY, secret_id TEXT, site TEXT);                 INSERT INTO cotton_vault_placements VALUES ('pl1', 's1', 'example.com'), ('pl2', 'other', 'example.org');");    let ids: std::collections::BTreeSet<String> = ["s1".to_string()].into();    let candidates = vec![("cotton_vault_placements".to_string(), "pl1".to_string()), ("cotton_vault_placements".to_string(), "pl2".to_string()), ("cotton_missing".to_string(), "x".to_string())];    assert_eq!(rows_naming(&local, &ids, &candidates).unwrap(), [("cotton_vault_placements".to_string(), "pl1".to_string())].into());}