Files
wanderbooks/crates/ledger-vault/tests/vault.rs
T
swaitsandClaude Fable 5.2 98cbabde8e fix(mcp,vault,store): the tax-id vault is inside the transaction; a read never sees an open call; the commit outcome is told truthfully (P15 T1 review)
The vault wrote a tax id before its journal line, so a call that failed or
was cut left the new tax id (and lost the old) with no line to say so. A
vault write made for a call is now staged under a name no reader opens
(.staged-TAG, .purging-TAG) and is made final, or dropped, only when the
call closes: a purge is set aside and put back if the call fails. A crash
between the closing line and the settle is finished at the next start by
what the journal says of the call. The readers that check a vault record
against the party's committed vault_record hash (the 1099 and CPA package
paths) therefore only ever see committed records; the filing scan reads
every final record on purpose (more tax ids scanned is safer).

close_call(Done) told the caller none of a call counted when its closing
line was on disk and only SQLite failed. It counted: the store now heals
from the journal where it can, and otherwise says the call counts, stops
taking writes and rebuilds at the next open.

A call whose begin line the projection refused left its frame open, so the
next call began inside it (a corrupt journal): the frame is now closed
failed.

A read arriving between a call's return and its closing line waits for the
close (a call that has written no line leaves reads free), so no read shows
what a call did before it committed.

Tests added through the tools: a call that writes lines and fails, a repeat
arriving while its original runs, the same key under two tokens, a crash
with the ok close on disk and SQLite behind, the vault under a failed and a
crashed call, a key reused for another tax id. The helpers that drop frame
lines no longer back the checks that a refusal or a preview wrote nothing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 10:19:26 -07:00

380 lines
12 KiB
Rust

//! The vault against its spec (crates/ledger-vault/src/lib.rs).
use ledger_vault::{Error, Tin, TinType, Vault, W9File};
use std::path::PathBuf;
/// A test's dir, removed when the test ends, pass or panic.
struct TestDir(PathBuf);
impl std::ops::Deref for TestDir {
type Target = std::path::Path;
fn deref(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn dir(tag: &str) -> TestDir {
let d = std::env::temp_dir().join(format!("wb-vault-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
TestDir(d)
}
fn vault(d: &std::path::Path) -> Vault {
Vault::open(&d.join("vault"), &d.join("keys/vault.key"), true).unwrap()
}
/// INVARIANT 3: nine digits, hyphens allowed; ITINs start with 9 and SSNs
/// and EINs don't.
#[test]
fn tins_are_nine_digits_of_their_type() {
assert_eq!(
Tin::new("123-45-6789", TinType::Ssn).unwrap().digits(),
"123456789"
);
assert_eq!(
Tin::new("12-3456789", TinType::Ein).unwrap().last4(),
"6789"
);
// Pub. 1915: fourth and fifth digits 50-65, 70-88, 90-92, 94-99.
for ok in [
"900-50-0000",
"903-53-0000",
"900-70-0000",
"950-57-0000",
"900-90-0000",
"923-51-0000",
"982-95-0000",
"992-55-0000",
] {
assert!(Tin::new(ok, TinType::Itin).is_ok(), "{ok}");
}
for bad in [
"938-69-0000",
"931-43-0000",
"907-43-0000",
"941-35-0000",
"900-19-0000",
"900-00-0000",
] {
assert!(Tin::new(bad, TinType::Itin).is_err(), "{bad}");
}
for (bad, kind) in [
("12345678", TinType::Ssn),
("1234567890", TinType::Ssn),
("12345678a", TinType::Ein),
("123 45 6789", TinType::Ssn),
("937-57-1234", TinType::Ssn),
("985196789", TinType::Ein),
("123456789", TinType::Itin),
] {
assert!(Tin::new(bad, kind).is_err(), "{bad} as {kind:?}");
}
assert_eq!(
Tin::new("123456789", TinType::Ssn).unwrap().formatted(),
"123-45-6789"
);
assert_eq!(
Tin::new("123456789", TinType::Ein).unwrap().formatted(),
"12-3456789"
);
}
/// INVARIANT 4: Debug and errors never show the digits.
#[test]
fn a_tin_never_prints() {
let tin = Tin::new("123-45-6789", TinType::Ssn).unwrap();
let shown = format!("{tin:?}");
assert!(
!shown.contains("12345") && shown.contains("6789"),
"{shown}"
);
let err = Tin::new("123-45-678", TinType::Ssn)
.unwrap_err()
.to_string();
assert!(!err.contains("12345678"), "{err}");
}
/// INVARIANT 1, 5: a TIN and a W-9 round-trip; the record on disk holds
/// neither in the clear; record_hash matches the bytes.
#[test]
fn records_round_trip_encrypted() {
let d = dir("roundtrip");
let v = vault(&d);
let tin = Tin::new("12-3456789", TinType::Ein).unwrap();
let hash = v.put_tin(7, &tin).unwrap();
let back = v.tin(7).unwrap().unwrap();
assert_eq!(back.digits(), "123456789");
assert_eq!(back.kind, TinType::Ein);
let raw = std::fs::read(d.join("vault/tin-7.bin")).unwrap();
assert!(
!raw.windows(9).any(|w| w == b"123456789"),
"TIN in the clear"
);
assert_eq!(v.record_hash(7).unwrap().as_deref(), Some(hash.as_str()));
let w9 = W9File {
file_name: "w9.pdf".into(),
mime_type: "application/pdf".into(),
bytes: b"%PDF secret 123456789".to_vec(),
};
v.put_w9(7, &w9).unwrap();
assert_eq!(v.w9(7).unwrap().unwrap(), w9);
assert!(v.tin(8).unwrap().is_none(), "SCENARIO 2: missing is None");
// A fresh nonce each write: the same TIN twice is two different records.
let again = v.put_tin(7, &tin).unwrap();
assert_ne!(again, hash);
}
/// INVARIANT 2 and SCENARIO 3: a record moved to another party, altered,
/// or opened with another key is unreadable, never another party's TIN.
#[test]
fn moved_altered_or_foreign_records_refuse() {
let d = dir("tamper");
let v = vault(&d);
v.put_tin(1, &Tin::new("710-77-3333", TinType::Ssn).unwrap())
.unwrap();
std::fs::copy(d.join("vault/tin-1.bin"), d.join("vault/tin-2.bin")).unwrap();
assert!(matches!(v.tin(2), Err(Error::Unreadable { party: 2, .. })));
let mut raw = std::fs::read(d.join("vault/tin-1.bin")).unwrap();
let last = raw.len() - 1;
raw[last] ^= 1;
std::fs::write(d.join("vault/tin-1.bin"), &raw).unwrap();
assert!(matches!(v.tin(1), Err(Error::Unreadable { party: 1, .. })));
let other = Vault::open(&d.join("vault"), &d.join("other.key"), true).unwrap();
v.put_tin(3, &Tin::new("710-77-3333", TinType::Ssn).unwrap())
.unwrap();
assert!(matches!(other.tin(3), Err(Error::Unreadable { .. })));
}
/// SCENARIO 1: no key file and no permission to create one is a locked
/// vault; a created key file is 0600 and survives reopening.
#[test]
fn the_key_file() {
let d = dir("key");
assert!(matches!(
Vault::open(&d.join("vault"), &d.join("missing.key"), false),
Err(Error::NoKey(_))
));
let v = vault(&d);
v.put_tin(1, &Tin::new("123456789", TinType::Ein).unwrap())
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(d.join("keys/vault.key"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600);
}
let reopened = Vault::open(&d.join("vault"), &d.join("keys/vault.key"), false).unwrap();
assert_eq!(reopened.tin(1).unwrap().unwrap().digits(), "123456789");
std::fs::write(d.join("bad.key"), "not hex").unwrap();
assert!(matches!(
Vault::open(&d.join("vault"), &d.join("bad.key"), false),
Err(Error::BadKey(_))
));
}
/// INVARIANT 6: purge deletes the party's records and only theirs.
#[test]
fn purge_removes_a_party() {
let d = dir("purge");
let v = vault(&d);
let tin = Tin::new("123456789", TinType::Ein).unwrap();
v.put_tin(1, &tin).unwrap();
v.put_tin(2, &tin).unwrap();
assert!(v.purge(1).unwrap());
assert!(v.tin(1).unwrap().is_none());
assert!(!d.join("vault/tin-1.bin").exists());
assert!(v.tin(2).unwrap().is_some());
assert!(!v.purge(1).unwrap(), "nothing left to purge");
}
/// INVARIANT 6, without the key: `records_held` says what a party has on
/// disk and `purge_records` deletes it, so a vault whose key is lost can
/// still be purged.
#[test]
fn purge_and_holdings_need_no_key() {
let d = dir("keyless");
let v = vault(&d);
let tin = Tin::new("123456789", TinType::Ssn).unwrap();
v.put_tin(1, &tin).unwrap();
v.put_w9(
1,
&W9File {
file_name: "w9.pdf".into(),
mime_type: "application/pdf".into(),
bytes: b"%PDF".to_vec(),
},
)
.unwrap();
v.put_tin(2, &tin).unwrap();
std::fs::remove_file(d.join("keys/vault.key")).unwrap();
let vdir = d.join("vault");
assert_eq!(ledger_vault::records_held(&vdir, 1).unwrap(), (true, true));
assert_eq!(ledger_vault::records_held(&vdir, 2).unwrap(), (true, false));
assert_eq!(
ledger_vault::records_held(&vdir, 3).unwrap(),
(false, false)
);
assert!(ledger_vault::purge_records(&vdir, 1).unwrap());
assert_eq!(
ledger_vault::records_held(&vdir, 1).unwrap(),
(false, false)
);
assert_eq!(ledger_vault::records_held(&vdir, 2).unwrap(), (true, false));
assert!(!ledger_vault::purge_records(&vdir, 1).unwrap());
// A vault directory that doesn't exist holds nothing.
assert_eq!(
ledger_vault::records_held(&d.join("nowhere"), 1).unwrap(),
(false, false)
);
}
const TAG: &str = "0123456789abcdef";
const OTHER: &str = "fedcba9876543210";
fn tin_a() -> Tin {
Tin::new("123-45-6789", TinType::Ssn).unwrap()
}
fn tin_b() -> Tin {
Tin::new("765-43-2109", TinType::Ssn).unwrap()
}
/// INVARIANT 7: a staged record is not the party's record: a reader sees
/// the old one (or none) until `settle` says the call committed.
#[test]
fn a_staged_record_is_read_by_no_one_until_its_call_commits() {
let d = dir("stage-commit");
let v = vault(&d);
let old_hash = v.put_tin(7, &tin_a()).unwrap();
let new_hash = v.stage_tin(7, &tin_b(), TAG).unwrap();
assert_ne!(old_hash, new_hash);
// Nothing changed for a reader.
assert_eq!(v.tin(7).unwrap().unwrap().last4(), "6789");
assert_eq!(
v.record_hash(7).unwrap().as_deref(),
Some(old_hash.as_str())
);
assert_eq!(
ledger_vault::pending_tags(&d.join("vault")).unwrap(),
[TAG.to_string()]
);
let done = ledger_vault::settle(&d.join("vault"), TAG, true).unwrap();
assert_eq!(done.promoted, 1);
assert_eq!(v.tin(7).unwrap().unwrap().last4(), "2109");
assert_eq!(
v.record_hash(7).unwrap().as_deref(),
Some(new_hash.as_str())
);
assert!(
ledger_vault::pending_tags(&d.join("vault"))
.unwrap()
.is_empty()
);
// Settling again changes nothing.
assert_eq!(
ledger_vault::settle(&d.join("vault"), TAG, true).unwrap(),
Default::default()
);
}
/// INVARIANT 7: a call that did not commit leaves the old record whole,
/// and nothing of the new one.
#[test]
fn a_call_that_did_not_commit_leaves_the_old_record_whole() {
let d = dir("stage-drop");
let v = vault(&d);
let old_hash = v.put_tin(7, &tin_a()).unwrap();
v.stage_tin(7, &tin_b(), TAG).unwrap();
// Another call's staged file is not this call's to settle.
v.stage_tin(8, &tin_b(), OTHER).unwrap();
let done = ledger_vault::settle(&d.join("vault"), TAG, false).unwrap();
assert_eq!(done.dropped, 1);
assert_eq!(v.tin(7).unwrap().unwrap().last4(), "6789");
assert_eq!(
v.record_hash(7).unwrap().as_deref(),
Some(old_hash.as_str())
);
assert_eq!(
ledger_vault::pending_tags(&d.join("vault")).unwrap(),
[OTHER.to_string()]
);
assert!(v.tin(8).unwrap().is_none());
}
/// INVARIANT 7: a purge is destroyed only when its call commits; if it
/// doesn't, every record is put back, byte for byte.
#[test]
fn a_purge_is_final_only_when_its_call_commits() {
let d = dir("stage-purge");
let v = vault(&d);
let hash = v.put_tin(7, &tin_a()).unwrap();
v.put_w9(
7,
&W9File {
file_name: "w9.pdf".into(),
mime_type: "application/pdf".into(),
bytes: b"%PDF fake".to_vec(),
},
)
.unwrap();
assert!(ledger_vault::stage_purge(&d.join("vault"), 7, TAG).unwrap());
// Out of sight at once ...
assert_eq!(
ledger_vault::records_held(&d.join("vault"), 7).unwrap(),
(false, false)
);
// ... and back if the call didn't commit.
let undone = ledger_vault::settle(&d.join("vault"), TAG, false).unwrap();
assert_eq!(undone.restored, 2);
assert_eq!(v.record_hash(7).unwrap().as_deref(), Some(hash.as_str()));
assert!(v.w9(7).unwrap().is_some());
// Committed: gone for good.
ledger_vault::stage_purge(&d.join("vault"), 7, TAG).unwrap();
let gone = ledger_vault::settle(&d.join("vault"), TAG, true).unwrap();
assert_eq!(gone.purged, 2);
assert_eq!(
ledger_vault::records_held(&d.join("vault"), 7).unwrap(),
(false, false)
);
assert!(
ledger_vault::pending_tags(&d.join("vault"))
.unwrap()
.is_empty()
);
}
/// A tag names a call in a file name: anything else is refused, so it can't
/// name a path.
#[test]
fn a_tag_that_is_not_sixteen_hex_digits_is_refused() {
let d = dir("stage-tag");
let v = vault(&d);
for bad in [
"",
"../x",
"0123456789ABCDEF",
"0123456789abcde",
"0123456789abcdefg",
] {
assert!(v.stage_tin(7, &tin_a(), bad).is_err(), "{bad}");
assert!(
ledger_vault::stage_purge(&d.join("vault"), 7, bad).is_err(),
"{bad}"
);
assert!(
ledger_vault::settle(&d.join("vault"), bad, true).is_err(),
"{bad}"
);
}
}