Cotton code
291 lines · 17.0 KB · RustRaw
//! The vectors under `crates/cotton-conformance/vectors/seal/`, shared with//! the TypeScript twin (`apps/business/src/seal.ts`) and every lane that reads//! the formats. Each file is rebuilt here from the fixed inputs in//! `fixtures_tests.rs` and must equal what is committed, so the Rust and the//! file cannot drift. To rewrite them after a deliberate format change://!//! ```text//! COTTON_WRITE_SEAL_VECTORS=1 cargo test -p cotton-core --lib seal::vectors_tests//! ```use std::path::PathBuf;use serde_json::{json, Value};use super::agent::{agent_statement, build_agent_grant_with};use super::allowlist::{allowlist_statement, canonical_list, sign_allowlist, Entry};use super::blind::{self, exact_token, query_tokens, text_tokens, wire};use super::fixtures_tests::*;use super::grant::{build_grant_with, bundle, bundle_json, unlock_statement};use super::keys::{blind_key, seal_dk_with, table_key, BLIND_INFO, DK_SEAL_ID, TABLE_INFO};use super::row::{body_aad, bucket, dek_aad, seal_row_with, split};use super::share::{seal_share_private_with, wrap_dek_for_with};use super::{b64, canonical_json};use crate::vault::wrap::public_of;fn dir() -> PathBuf {    cotton_store::manifest_dir().join("../cotton-conformance/vectors/seal")}fn check(name: &str, built: Value) {    let path = dir().join(format!("{name}.json"));    let text = format!("{}\n", serde_json::to_string_pretty(&built).unwrap());    if std::env::var_os("COTTON_WRITE_SEAL_VECTORS").is_some() {        std::fs::create_dir_all(dir()).unwrap();        std::fs::write(&path, &text).unwrap();        return;    }    let committed = std::fs::read_to_string(&path).unwrap_or_else(|_| panic!("{} is missing; write it with COTTON_WRITE_SEAL_VECTORS=1", path.display()));    assert_eq!(serde_json::from_str::<Value>(&committed).unwrap(), built, "{name}.json differs from what the Rust makes");}fn hex32(bytes: &[u8]) -> String {    hex::encode(bytes)}#[test]fn keys_vector() {    let tables = [("message", 1), ("message", 2), ("note", 1)];    check(        "keys",        json!({            "about": "TK(t,v) = HKDF-SHA256(ikm=DK, salt=utf8(database_id), info=utf8(table_info t \":\" v)); BK(t) likewise with blind_info t; dk_enc = vault v2 seal of DK under the VMK with id dk_seal_id",            "table_info": TABLE_INFO, "blind_info": BLIND_INFO, "dk_seal_id": DK_SEAL_ID,            "database_id": DATABASE, "dk_hex": hex32(&dk_bytes()),            "table_keys": tables.iter().map(|(t, v)| json!({ "table": t, "v": v, "tk_hex": hex32(table_key(&dk(), DATABASE, t, *v).unwrap().as_slice()) })).collect::<Vec<_>>(),            "blind_keys": (["message", "note"]).iter().map(|t| json!({ "table": t, "bk_hex": hex32(blind_key(&dk(), DATABASE, t).unwrap().as_slice()) })).collect::<Vec<_>>(),            "dk_enc": { "vmk_hex": hex32(&[0x42; 32]), "vmk_version": 3, "nonce_hex": hex32(&nonce(4)), "dk_enc": seal_dk_with(&nonce(4), &vmk(), 3, &dk()).unwrap() },        }),    );}#[test]fn row_vector() {    let spec = message_spec();    let row = message_row();    let (_, sealed) = split(&spec, &row).unwrap();    let plaintext = canonical_json(&Value::Object(sealed));    let stored = seal_row_with(&nonce(1), &nonce(2), &dek(), &dk(), DATABASE, "message", ROW_ID, 7, &spec, &row).unwrap();    let wrong = |what: &str, database: &str, table: &str, id: &str, v: u32| json!({ "what": what, "database_id": database, "table": table, "id": id, "seal_v": v });    check(        "row",        json!({            "about": "sealed_enc = \"s1:\" b64url(nonce || AES-256-GCM(DEK, pad(canonical JSON of the sealed columns), body_aad)); dek_enc = \"d1:\" b64url(nonce || AES-256-GCM(TK(table, seal_v), DEK, dek_aad)); pad = ASCII spaces to 64, 256, 1024, 4096, then multiples of 4096; canonical JSON sorts keys by UTF-8 bytes",            "database_id": DATABASE, "table": "message", "id": ROW_ID, "seal_v": 7,            "dk_hex": hex32(&dk_bytes()), "dek_hex": hex32(dek().expose()),            "body_nonce_hex": hex32(&nonce(1)), "dek_nonce_hex": hex32(&nonce(2)),            "spec": spec, "row": row,            "body_aad": body_aad(DATABASE, "message", ROW_ID).unwrap(),            "dek_aad": dek_aad(DATABASE, "message", ROW_ID, 7).unwrap(),            "sealed_plaintext": plaintext, "padded_len": bucket(plaintext.len()),            "stored": stored,            "refusals": [                wrong("another row", DATABASE, "message", "5b1c0e7a-0000-4000-8000-000000000002", 7),                wrong("another database", OTHER_DATABASE, "message", ROW_ID, 7),                wrong("another table", DATABASE, "thread", ROW_ID, 7),                wrong("another version", DATABASE, "message", ROW_ID, 6),            ],            "buckets": ([0usize, 64, 65, 1000, 4097]).iter().map(|n| json!([n, bucket(*n)])).collect::<Vec<_>>(),        }),    );}#[test]fn blind_vector() {    let bk = blind_key(&dk(), DATABASE, "message").unwrap();    let texts = [        "Zanzibar ferry tickets for Thursday, café near the jetty",        "मैं कल दिल्ली में हूँ और तुम?",        "Meeting @ 5pm, कल मिलते हैं 🙏",        "👍🎉🙏",        "FULL width ÅNGSTRÖM naïve",    ];    let queries = ["zanz", "ferry tick", "tickets", "go", "the a", "दिल्", "कल मिल", "Café"];    check(        "blind",        json!({            "about": "see crates/cotton-core/src/seal/blind.rs: normalise = NFC(drop U+0300-036F,1AB0-1AFF,1DC0-1DFF,20D0-20FF,FE20-FE2F from NFD(lowercase(NFKC))); words = runs of [\\p{Alphabetic}\\p{N}\\p{M}], >= 2 scalars, not a stopword; tokens = first 8 bytes of HMAC-SHA256(BK, kind \"|\" column \"|\" value) as signed big-endian i64 in decimal; kinds w (word), p (prefixes 3..=min(6,len)), x (exact, NFKC+trim); a query's last word of >= 3 is its prefix token (up to 6)",            "database_id": DATABASE, "table": "message", "bk_hex": hex32(bk.as_slice()),            "stopwords": serde_json::from_str::<Value>(blind::STOPWORDS_JSON).unwrap(),            "texts": texts.iter().map(|t| json!({ "column": "body", "text": t, "normalised": blind::normalise(t), "words": blind::words(t), "tokens": wire(&text_tokens(&bk, "body", t)) })).collect::<Vec<_>>(),            "queries": queries.iter().map(|q| json!({ "column": "body", "query": q, "tokens": wire(&query_tokens(&bk, "body", q)) })).collect::<Vec<_>>(),            "exact": (["wamid.HBgMOTE5ODc2NTQzMjEwFQIAEhgg", "+919876543210", " Someone@Example.com "]).iter().map(|v| json!({ "column": "external_id", "value": v, "token": exact_token(&bk, "external_id", v).map(|t| t.wire()) })).collect::<Vec<_>>(),        }),    );}#[test]fn grant_vector() {    let tables = vec![("note".to_string(), 1), ("message".to_string(), 3)];    let worker_pub = public_of(&WORKER_SECRET);    let g = build_grant_with(&EPHEMERAL, &nonce(3), &dk(), DATABASE, "req-1", "tok-1", &tables, 15, &worker_pub, &person()).unwrap();    let statement = unlock_statement(DATABASE, "req-1", "tok-1", &g.tables, g.minutes, &g.wrapped).unwrap();    let b = bundle(&dk(), DATABASE, "req-1", "tok-1", &tables).unwrap();    check(        "grant",        json!({            "about": "bundle = canonical JSON {blind:{t:b64url BK}, files:{message:b64url TFR(message)} (only when message is granted; see table_file.json), keys:{t:{v:b64url TK}} for v in 1..=seal_v, request_id, token_id}; wrapped = w1 wrap (crate::vault::wrap) to worker_pub; statement = \"cotton-unlock-v1\\n\" database_id \\n request_id \\n token_id \\n sorted tables joined \",\" \\n minutes \\n hex(sha256(utf8(wrapped))); sig = b64url Ed25519 by the person key; signer = its fingerprint",            "database_id": DATABASE, "request_id": "req-1", "token_id": "tok-1", "minutes": 15,            "dk_hex": hex32(&dk_bytes()),            "tables": tables.iter().map(|(t, v)| json!({ "table": t, "seal_v": v })).collect::<Vec<_>>(),            "worker_secret_hex": hex32(&WORKER_SECRET), "worker_pub": b64(&worker_pub),            "ephemeral_hex": hex32(&EPHEMERAL), "nonce_hex": hex32(&nonce(3)),            "person_seed_hex": hex32(&[7; 32]), "person_public_key": person().public_key(),            "bundle": bundle_json(&b).as_str(),            "wrapped": g.wrapped, "statement": String::from_utf8(statement).unwrap(),            "signer": g.signer, "sig": g.sig, "granted_tables": g.tables,        }),    );}/// The standing grant (ruling R4): minutes 0, printed as 0 in the statement.#[test]fn grant_standing_vector() {    let tables = vec![("note".to_string(), 1)];    let worker_pub = public_of(&WORKER_SECRET);    let g = build_grant_with(&EPHEMERAL, &nonce(3), &dk(), DATABASE, "req-2", "tok-1", &tables, super::grant::STANDING, &worker_pub, &person()).unwrap();    let statement = unlock_statement(DATABASE, "req-2", "tok-1", &g.tables, g.minutes, &g.wrapped).unwrap();    let b = bundle(&dk(), DATABASE, "req-2", "tok-1", &tables).unwrap();    check(        "grant_standing",        json!({            "about": "as grant.json, for a standing grant: minutes 0 (until the person turns it off; the object stamps ends_at 9999-12-31T23:59:59.999Z); the statement's minutes line is 0",            "database_id": DATABASE, "request_id": "req-2", "token_id": "tok-1", "minutes": 0,            "dk_hex": hex32(&dk_bytes()),            "tables": tables.iter().map(|(t, v)| json!({ "table": t, "seal_v": v })).collect::<Vec<_>>(),            "worker_secret_hex": hex32(&WORKER_SECRET), "worker_pub": b64(&worker_pub),            "ephemeral_hex": hex32(&EPHEMERAL), "nonce_hex": hex32(&nonce(3)),            "person_seed_hex": hex32(&[7; 32]), "person_public_key": person().public_key(),            "bundle": bundle_json(&b).as_str(),            "wrapped": g.wrapped, "statement": String::from_utf8(statement).unwrap(),            "signer": g.signer, "sig": g.sig, "granted_tables": g.tables,        }),    );}/// The standing grant to the person's Claude: the bundle/// names the member as request and token, the wrap is to the member key, the/// statement signs the policy.#[test]fn agent_grant_vector() {    let tables = vec![("note".to_string(), 2), ("message".to_string(), 1)];    let member_pub = public_of(&WORKER_SECRET);    let withheld = vec!["code_credential".to_string(), "money_entry".to_string(), "passkey".to_string(), "secret".to_string()];    let g = build_agent_grant_with(&EPHEMERAL, &nonce(3), &dk(), DATABASE, "mem-1", &member_pub, &tables, &["money_entry".to_string()], &person()).unwrap();    let statement = agent_statement(DATABASE, "mem-1", &member_pub, &withheld, &g.wrapped).unwrap();    let b = bundle(&dk(), DATABASE, "mem-1", "mem-1", &tables).unwrap();    check(        "agent_grant",        json!({            "about": "bundle = the unlock bundle with request_id = token_id = member_id; wrapped = w1 wrap to member_pub; statement = \"cotton-agent-grant-v1\\n\" database_id \\n member_id \\n b64url(member_pub) \\n sorted withheld (always holding code_credential, passkey, secret) joined \",\" \\n hex(sha256(utf8(wrapped))); sig = b64url Ed25519 by the person key",            "database_id": DATABASE, "member_id": "mem-1",            "dk_hex": hex32(&dk_bytes()),            "tables": tables.iter().map(|(t, v)| json!({ "table": t, "seal_v": v })).collect::<Vec<_>>(),            "member_secret_hex": hex32(&WORKER_SECRET), "member_pub": b64(&member_pub),            "ephemeral_hex": hex32(&EPHEMERAL), "nonce_hex": hex32(&nonce(3)),            "person_public_key": person().public_key(),            "bundle": bundle_json(&b).as_str(),            "withheld": g.withheld,            "wrapped": g.wrapped, "statement": String::from_utf8(statement).unwrap(),            "signer": g.signer, "sig": g.sig,        }),    );}#[test]fn share_vector() {    let share_pub = public_of(&SHARE_SECRET);    check(        "share",        json!({            "about": "wrapped_dek = w1 wrap to share_pub of DEK(32 bytes) || utf8(table \"\\n\" row_id); sealed_private = vault v2 seal under the VMK with id \"share-key:\" fingerprint",            "share_secret_hex": hex32(&SHARE_SECRET), "share_pub": b64(&share_pub),            "dek_hex": hex32(dek().expose()), "table": "note", "row_id": "n1",            "ephemeral_hex": hex32(&EPHEMERAL), "nonce_hex": hex32(&nonce(5)),            "wrapped_dek": wrap_dek_for_with(&EPHEMERAL, &nonce(5), &share_pub, &dek(), "note", "n1").unwrap(),            "sealed_private": { "vmk_hex": hex32(&[0x42; 32]), "vmk_version": 2, "fingerprint": person().fingerprint(), "nonce_hex": hex32(&nonce(6)),                "sealed": seal_share_private_with(&nonce(6), &vmk(), 2, &person().fingerprint(), &SHARE_SECRET).unwrap() },        }),    );}#[test]fn allowlist_vector() {    let entries = vec![Entry { cidr: "203.0.113.7/32".into(), label: "box".into() }, Entry { cidr: "198.51.100.0/24".into(), label: "home".into() }];    let at = "2026-11-11T10:00:00.000Z";    check(        "allowlist",        json!({            "about": "list = canonical JSON array of {cidr,label} sorted by cidr; statement = \"cotton-allowlist-v1\\n\" database_id \\n hex(sha256(utf8(list))) \\n nonce \\n issued_at; sig = b64url Ed25519 by the person key; fresh within 300000 ms either side",            "database_id": DATABASE, "entries": entries, "nonce": "n-1", "issued_at": at,            "list": canonical_list(&entries).unwrap(),            "statement": String::from_utf8(allowlist_statement(DATABASE, &entries, "n-1", at).unwrap()).unwrap(),            "person_public_key": person().public_key(),            "sig": sign_allowlist(&person(), DATABASE, &entries, "n-1", at).unwrap(),            "empty_list": { "list": canonical_list(&[]).unwrap(), "statement": String::from_utf8(allowlist_statement(DATABASE, &[], "n-2", at).unwrap()).unwrap(), "sig": sign_allowlist(&person(), DATABASE, &[], "n-2", at).unwrap() },        }),    );}/// What a blind search holds an opened hit to (`blind::matches`), shared with/// the TypeScript twin's `blindMatches`.#[test]fn blind_match_vector() {    let cases = [        ("Zanzibar ferry tickets", "zanz"),        ("Zanzibar ferry tickets", "ferry tick"),        ("Zanzibar ferry tickets", "zanz ferry"),        ("Zanzibar ferry tickets", "tickets ferry"),        ("the conference was long", "conference"),        ("the talk was conferred", "conference"),        ("the talk was conferred", "confer"),        ("we go home", "go"),        ("we going home", "go"),        ("the a of", "the"),        ("x marks", "x"),        ("Café naïve", "cafe"),        ("CAFE", "Café"),        ("मैं कल दिल्ली में हूँ", "दिल्"),        ("मैं कल दिल्ली में हूँ", "कल दिल्ली"),        ("बाज़ार", "बाजार"),        ("₹7,250.50 paid", "7250"),        ("₹7,250.50 paid", "250"),        ("", "anything"),    ];    check(        "blind_match",        json!({            "about": "see crates/cotton-core/src/seal/blind.rs `matches`: over blind words, every query word but the last is a word of the text and the last starts one (is one at 2 scalars); a query with no word holds nothing",            "cases": cases.iter().map(|(text, query)| json!({ "text": text, "query": query, "matches": blind::matches(text, query) })).collect::<Vec<_>>(),        }),    );}/// A message's kept chat picture, sealed on the device under TFR(message) (owner's decision, 22 Nov 2026); the/// Worker, handed TFR in a window over messages, makes FK and opens it (apps/business src/table_files.ts).#[test]fn table_file_vector() {    use super::file::{person_file_key, seal_file_with};    use super::keys::{table_file_root, TABLE_FILE_INFO};    let root = table_file_root(&dk(), DATABASE, "message").unwrap();    let key = format!("{DATABASE}/messages/thread-1/{}.png", "ab".repeat(32));    let fk = person_file_key(&root, &key);    // Two parts and a little: every part but the last whole, so a reader is checked across a part's edge.    let plain: Vec<u8> = (0..(64 * 1024 * 2 + 37)).map(|i| (i % 251) as u8).collect();    let mut sealed = Vec::new();    seal_file_with([9u8; 7], &fk, &key, &mut plain.as_slice(), &mut sealed).unwrap();    let small = b"an invented picture".to_vec();    let mut sealed_small = Vec::new();    seal_file_with([5u8; 7], &fk, &key, &mut small.as_slice(), &mut sealed_small).unwrap();    use sha2::Digest as _;    check(        "table_file",        json!({            "about": "TFR(t) = HKDF-SHA256(salt = database_id, ikm = DK, info = \"cotton-table-file-v1:\" t), handed in a window over t (grant bundle \"files\"); FK = HMAC-SHA256(TFR, \"pf|\" object_key), said b64url; f1 = \"CTF1\" || prefix(7) || parts of 64 KiB, AES-256-GCM under FK, nonce prefix || be32(i) || last, aad \"f1|\" object_key",            "info": TABLE_FILE_INFO, "database_id": DATABASE, "table": "message", "dk_hex": hex32(&dk_bytes()),            "root_hex": hex32(root.as_slice()), "object_key": key, "fk": fk.text(),            "plain_sha256": hex::encode(sha2::Sha256::digest(&plain)), "plain_len": plain.len(), "sealed_hex": hex::encode(&sealed),            "small_plain": String::from_utf8(small).unwrap(), "small_sealed_hex": hex::encode(&sealed_small),        }),    );}