Merge branch 't3/refuse-tax-ids-in-free-text': free text refuses a tax id's shapes; references take nine digits; bank files mask (WB-partner-15)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 16:56:02 -07:00
commit e7d5e4b8cd
36 files changed
+4353 -113

No files matched your search

+1 -1
View File
@@ -677,7 +677,7 @@ fn update_party_sets_and_clears_the_contact_block() {
json!({"party": party.to_string(), "phone": "123-45-6789"}),
)
.unwrap_err();
assert!(why.contains("taxpayer"), "{why}");
assert!(why.contains("tax id"), "{why}");
let why = m
.try_call(
"books.update_party",
+1 -1
View File
@@ -482,7 +482,7 @@ fn update_project_checks_every_field_before_writing() {
),
(
json!({"project": "Harbor", "notes": "SSN 123-45-6789"}),
"TIN",
"tax id",
),
(
json!({"project": "Nowhere", "status": "paused"}),
+279
View File
@@ -0,0 +1,279 @@
//! No tax id in a tool's text, through the real server as an agent reaches it
//! (BS-partner-2, WB-partner-15; the owner's choice of 2026-11-21).
//!
//! The law: a string that looks like a tax id (nine digits standing alone, an
//! SSN's 3-2-4, an EIN's 2-7) is refused before any write tool runs, in words
//! that name the field and never the number, and the journal is byte for byte
//! what it was; an invoice number, a phone number and a reference of ten
//! digits or more are no tax id; a bank file's descriptions are kept with such
//! a number masked to its last four digits and the answer says so; a chart file
//! with one is refused, naming its row and column. The fake ids are
//! `000-00-0000` and `00-0000000`.
use common::{Books, Wire, answer_of};
use serde_json::json;
mod common;
const SSN: &str = "000-00-0000";
const EIN: &str = "00-0000000";
fn setup(w: &mut Wire) {
for (code, name, kind) in [("1000", "Bank", "asset"), ("6000", "Supplies", "expense")] {
answer_of(&w.call(
"books.add_account",
json!({"code": code, "name": name, "account_type": kind}),
))
.unwrap();
}
}
/// Free text with a tax id in it is refused by every tool that keeps text,
/// before it runs: the journal does not change by a byte.
#[test]
fn a_tax_id_in_a_tools_text_is_refused_and_nothing_is_written() {
let books = Books::new("tin-text-refused");
let mut w = books.session("test");
setup(&mut w);
let before = books.journal_raw();
for (tool, args, field) in [
(
"books.add_class",
json!({"name": format!("Rondo {SSN}")}),
"the name of books.add_class",
),
(
"books.add_project",
json!({"name": "Harbor", "notes": format!("ein {EIN}")}),
"the notes of books.add_project",
),
(
"books.draft_entry",
json!({"date": "2026-03-01", "description": format!("paid {SSN}"), "no_party_reason": "test"}),
"the description of books.draft_entry",
),
(
"books.draft_entry",
json!({"date": "2026-03-01", "description": "ok", "no_party_reason": format!("own account {EIN}")}),
"the no_party_reason of books.draft_entry",
),
// A party's own fields are strict: any run of nine digits.
(
"books.add_customer",
json!({"name": "Acme 123456789"}),
"the name of books.add_customer",
),
(
"books.add_party",
json!({"name": format!("Pat {SSN}"), "roles": ["contractor"]}),
"the name of books.add_party",
),
(
"books.set_setting",
json!({"changes": [{"key": "company.name", "value": "Acme"}], "note": format!("see {SSN}")}),
"the note of books.set_setting",
),
] {
let why = answer_of(&w.call(tool, args)).unwrap_err();
assert!(
why.starts_with(&format!("{field} looks like it holds a tax id")),
"{tool}: {why}"
);
assert!(
why.contains("books.set_tin") && why.contains("W-9"),
"{why}"
);
assert!(
!why.contains("0000") && !why.contains("123456789"),
"never the number: {why}"
);
assert_eq!(
books.journal_raw(),
before,
"{tool}: a refusal writes nothing"
);
}
}
/// What is no tax id is kept: an invoice number, a phone number, a long
/// reference, an amount and a date.
#[test]
fn a_reference_is_no_tax_id() {
let books = Books::new("tin-text-kept");
let mut w = books.session("test");
setup(&mut w);
let out = answer_of(&w.call(
"books.draft_entry",
json!({"date": "2026-03-01",
"description": "inv 2026-11-0042, call 801-555-0142, ref 1234567890, $1,234,567.89",
"no_party_reason": "test"}),
))
.unwrap();
assert!(out["entry_id"].is_u64(), "{out}");
}
/// A reference field (an account code, an instrument's label) keeps a bare
/// nine digits and refuses a printed tax id; free text refuses both.
#[test]
fn a_reference_field_keeps_nine_digits_and_refuses_a_printed_tax_id() {
let books = Books::new("tin-reference-field");
let mut w = books.session("test");
setup(&mut w);
let ok = answer_of(&w.call(
"books.add_account",
json!({"code": "123456789", "name": "Nine", "account_type": "asset"}),
))
.unwrap();
assert!(ok["account_id"].is_u64(), "{ok}");
answer_of(&w.call(
"books.add_instrument",
json!({"label": "Card 000000000", "kind": "business_card", "account": "1000"}),
))
.unwrap();
let before = books.journal_raw();
for (tool, args, field) in [
(
"books.add_account",
json!({"code": SSN, "name": "Odd", "account_type": "asset"}),
"the code of books.add_account",
),
(
"books.add_instrument",
json!({"label": format!("Card {EIN}"), "kind": "business_card", "account": "1000"}),
"the label of books.add_instrument",
),
(
"books.add_class",
json!({"name": "123456789"}),
"the name of books.add_class",
),
] {
let why = answer_of(&w.call(tool, args)).unwrap_err();
assert!(
why.starts_with(&format!("{field} looks like it holds a tax id")),
"{tool}: {why}"
);
assert_eq!(books.journal_raw(), before, "{tool}: nothing was written");
}
}
/// A rule keyed on a bank's nine-digit reference matches the bank's own
/// words, and the description that is kept is the masked one.
#[test]
fn a_bank_rule_keyed_on_a_nine_digit_reference_still_matches() {
let books = Books::new("tin-bank-rule");
let mut w = books.session("test");
setup(&mut w);
answer_of(&w.call(
"books.add_account",
json!({"code": "6100", "name": "Payroll costs", "account_type": "expense"}),
))
.unwrap();
let csv = "Date,Description,Amount\n2026-01-02,ACH 000000000 PAYROLL,-12.50\n2026-01-03,CHECK 1234567890,-3.25\n";
let up = w.upload(csv.as_bytes(), "bank.csv", "text/csv", "import");
let out = answer_of(&w.call(
"books.import_bank_csv",
json!({"upload_id": up, "bank_account_code": "1000", "default_offset_code": "6000",
"rules": {"000000000": "6100"}}),
))
.unwrap();
let imported = out["imported"].as_array().unwrap();
assert_eq!(imported[0]["offset_account"], "6100", "{out}");
assert_eq!(imported[1]["offset_account"], "6000", "{out}");
assert_eq!(
imported[0]["description"],
"ACH \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000 PAYROLL"
);
let journal = String::from_utf8(books.journal_raw()).unwrap();
assert!(
!journal.contains("ACH 000000000"),
"the journal holds the masked description only"
);
}
/// A bank file is kept whole with a nine-digit reference masked to its last
/// four digits; the answer says how many and where; the journal never holds
/// the number.
#[test]
fn a_bank_file_is_masked_not_refused() {
let books = Books::new("tin-bank-masked");
let mut w = books.session("test");
setup(&mut w);
let csv = format!(
"Date,Description,Amount\n2026-01-02,ACH {SSN} payroll,-12.50\n2026-01-03,CHECK 1234567890,-3.25\n2026-01-04,\"WIRE 000000000 and {EIN}\",-40.00\n"
);
let up = w.upload(csv.as_bytes(), "bank.csv", "text/csv", "import");
let out = answer_of(&w.call(
"books.import_bank_csv",
json!({"upload_id": up, "bank_account_code": "1000", "default_offset_code": "6000"}),
))
.unwrap();
assert_eq!(out["count"], 3, "{out}");
assert_eq!(out["masked_count"], 3, "{out}");
assert_eq!(
out["masked"],
json!([
{"row": 2, "column": "Description", "numbers": 1},
{"row": 4, "column": "Description", "numbers": 2},
])
);
let note = out["masked_note"].as_str().unwrap();
assert!(
note.starts_with("3 values in the Description column read as a tax id"),
"{note}"
);
assert!(
note.contains("lines 2, 4") && note.contains("books.set_tin"),
"{note}"
);
let descriptions: Vec<&str> = out["imported"]
.as_array()
.unwrap()
.iter()
.map(|t| t["description"].as_str().unwrap())
.collect();
assert_eq!(
descriptions,
[
"ACH \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 payroll",
"CHECK 1234567890",
"WIRE \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000 and \u{2022}\u{2022}-\u{2022}\u{2022}\u{2022}0000",
]
);
let journal = String::from_utf8(books.journal_raw()).unwrap();
for needle in [SSN, EIN, "000000000"] {
for line in journal.lines().filter(|l| l.contains(needle)) {
let kind = serde_json::from_str::<serde_json::Value>(line).unwrap()["type"].clone();
// The line that makes the books holds zeros of its own (a hash).
assert_eq!(
kind, "store.created",
"the journal holds a tax id in a {kind} line"
);
}
}
assert!(
journal.contains("Bank import \u{2014} ACH \u{2022}"),
"the drafts are kept masked"
);
}
/// A chart file is typed by a person: a cell that looks like a tax id
/// refuses it whole, naming its row and column, and nothing is imported.
#[test]
fn a_chart_file_with_a_tax_id_is_refused_naming_its_row_and_column() {
let books = Books::new("tin-chart-refused");
let mut w = books.session("test");
let csv =
format!("code,name,type,parent_code\n1000,Cash,asset,\n1010,Payroll {SSN},asset,1000\n");
let up = w.upload(csv.as_bytes(), "chart.csv", "text/csv", "import");
let before = books.journal_raw();
let why = answer_of(&w.call("books.import_chart_csv", json!({"upload_id": up}))).unwrap_err();
assert!(
why.starts_with("the name cell of row 3 looks like it holds a tax id"),
"{why}"
);
assert!(!why.contains("0000"), "never the number: {why}");
assert_eq!(books.journal_raw(), before, "nothing was imported");
let chart = answer_of(&w.call("books.chart", json!({}))).unwrap();
assert!(!chart.to_string().contains("Payroll"), "{chart}");
}
+78 -10
View File
@@ -399,24 +399,32 @@ pub const MAX_REFERENCE_CHARS: usize = 200;
impl PaymentDetails {
/// The payment entry's description: `base`, then the reference when
/// there is one (`base (ref R)`).
/// there is one (`base (ref R)`), with a run of nine digits in it masked
/// to its last four: the reference is kept whole in the payment's own
/// record, and an entry's description is free text, which holds no
/// number that reads as a tax id (WB-partner-15).
pub fn description(&self, base: &str) -> String {
match self.reference.as_deref().map(str::trim) {
Some(r) if !r.is_empty() => format!("{base} (ref {r})"),
Some(r) if !r.is_empty() => {
format!("{base} (ref {})", crate::settings::mask_printed_tins(r))
}
_ => base.to_string(),
}
}
/// Refuse a reference that isn't one line of at most
/// [`MAX_REFERENCE_CHARS`] characters. A blank one is none. (A bank
/// trace number is fifteen digits, so no nine-digit scan here.)
/// [`MAX_REFERENCE_CHARS`] characters, or one that looks like a tax id's
/// printed SSN or EIN (a bare nine digits is a check or confirmation
/// number: a reference's reading, WB-partner-15; not in a replay,
/// BS-entry-4). A blank one is none.
pub fn check(&self) -> Result<(), LedgerError> {
if let Some(r) = &self.reference
&& (r.contains(['\n', '\r']) || r.chars().count() > MAX_REFERENCE_CHARS)
{
return Err(LedgerError::InvalidPayment(format!(
"a payment's reference is one line of at most {MAX_REFERENCE_CHARS} characters"
)));
if let Some(r) = &self.reference {
if r.contains(['\n', '\r']) || r.chars().count() > MAX_REFERENCE_CHARS {
return Err(LedgerError::InvalidPayment(format!(
"a payment's reference is one line of at most {MAX_REFERENCE_CHARS} characters"
)));
}
LedgerError::reference_text("the payment reference", r)?;
}
Ok(())
}
@@ -1253,6 +1261,65 @@ impl Bill {
}
}
/// A new document's free text may not look like a tax id (BS-partner-2):
/// the customer's or the vendor's own reference, the memo, and why a
/// repeated vendor invoice number is entered anyway. For new documents;
/// replay restores them as journaled (BS-entry-4).
pub fn check_document_text(
reference: Option<&str>,
memo: Option<&str>,
duplicate_reason: Option<&str>,
) -> Result<(), LedgerError> {
for (field, text) in [
("the memo", memo),
("the duplicate reason", duplicate_reason),
] {
if let Some(t) = text {
LedgerError::free_text(field, t)?;
}
}
if let Some(t) = reference {
LedgerError::reference_text("the reference", t)?;
}
Ok(())
}
/// The party details a new invoice prints: the customer's (a party's
/// fields: strict, no run of nine digits, [`crate::parties::check_text`])
/// and the seller's (the company's own, free text: no tax id's shape).
pub fn check_snapshots(
bill_to: Option<&PartySnapshot>,
seller: Option<&PartySnapshot>,
) -> Result<(), LedgerError> {
let fields = |s: &'_ PartySnapshot| -> [(&'static str, Option<String>); 8] {
[
("the bill-to name", Some(s.name.clone())),
("the bill-to address", s.address.clone()),
("the bill-to email", s.email.clone()),
("the bill-to phone", s.phone.clone()),
("the bill-to contact", s.contact.clone()),
("the billing address", s.billing_address.clone()),
("the shipping address", s.shipping_address.clone()),
("the billing email", s.billing_email.clone()),
]
};
if let Some(s) = bill_to {
for (field, text) in fields(s) {
if let Some(t) = text {
crate::parties::check_text(field, &t).map_err(LedgerError::InvalidParty)?;
}
}
}
if let Some(s) = seller {
for (field, text) in fields(s) {
if let Some(t) = text {
LedgerError::free_text(&field.replace("bill-to", "seller"), &t)?;
}
}
}
Ok(())
}
/// Validate document lines: at least one, all positive amounts, each in a
/// journal line's range, and a quantity and unit price that multiply to
/// the amount exactly (plan P4b S4.1). For new documents; replay restores
@@ -1262,6 +1329,7 @@ pub fn validate_lines(lines: &[DocumentLine]) -> Result<(), LedgerError> {
return Err(LedgerError::EmptyDocumentLines);
}
for line in lines {
LedgerError::free_text("a line's description", &line.description)?;
if line.amount <= Decimal::ZERO {
return Err(LedgerError::InvalidDocumentLineAmount(line.amount));
}
+24
View File
@@ -367,6 +367,13 @@ pub enum LedgerError {
)]
AccountNameHoldsTin,
/// Free text (a memo, a note, a reason, a description, a tag) that
/// looks like it holds a tax id: nine digits standing alone, or an
/// SSN's 3-2-4 or an EIN's 2-7 grouping (BS-partner-2). The words name
/// the field and where a tax id goes, never the number.
#[error("{0}")]
FreeTextHoldsTin(String),
/// A new account name (a new account's, or a rename's) that isn't one
/// line of text within the bound ([`crate::account::MAX_ACCOUNT_NAME`]
/// characters): every report, export and the IIF print it on one line.
@@ -993,6 +1000,23 @@ pub enum LedgerError {
ApprovalNeedsDraft(String),
}
impl LedgerError {
/// Free text a command may keep: it must not look like a tax id
/// ([`crate::settings::check_free_text`]; never refused in a replay).
/// `field` is how the refusal names it ("the memo", "the entry
/// description").
pub fn free_text(field: &str, text: &str) -> Result<(), LedgerError> {
crate::settings::check_free_text(field, text).map_err(LedgerError::FreeTextHoldsTin)
}
/// [`Self::free_text`] for a reference (a tag, a serial, a payment's or
/// an invoice's reference, an account code, a file name): a bare nine
/// digits is allowed ([`crate::settings::check_reference_text`]).
pub fn reference_text(field: &str, text: &str) -> Result<(), LedgerError> {
crate::settings::check_reference_text(field, text).map_err(LedgerError::FreeTextHoldsTin)
}
}
/// The refusal [`LedgerError::TaxCategoryRequired`] gives: what to pass,
/// and where the categories are listed.
fn tax_category_required_text(account: &str, clearing: bool) -> String {
+16
View File
@@ -74,6 +74,19 @@ impl AnnotationFields {
self.category = trim(self.category);
self.source = trim(self.source);
self.reimbursable_to = trim(self.reimbursable_to);
// Who, what and where in words: no tax id among them (BS-partner-2;
// not in a replay, which keeps the journal as written).
for (field, text) in [
("the payee", &self.payee),
("the payment method", &self.instrument),
("the category", &self.category),
("the source", &self.source),
("who is to be reimbursed", &self.reimbursable_to),
] {
if let Some(t) = text {
LedgerError::free_text(field, t)?;
}
}
if self.receipt_number == Some(0) {
return Err(LedgerError::InvalidEvidence(
"a receipt number is positive".into(),
@@ -111,6 +124,9 @@ impl Annotation {
.note
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty());
if let Some(n) = &self.note {
LedgerError::free_text("the note", n)?;
}
if self.fields.is_empty() && self.note.is_none() {
return Err(LedgerError::InvalidEvidence(
"an annotation records at least one field or a note".into(),
+4 -3
View File
@@ -127,10 +127,11 @@ pub struct Instrument {
pub account: AccountId,
}
/// Check a label: one line, at most `MAX_TEXT` characters, no full TIN
/// (INVARIANT 1, all but uniqueness). Returns it trimmed.
/// Check a label: one line, at most `MAX_TEXT` characters, no printed SSN or
/// EIN (INVARIANT 1, all but uniqueness; a label is a reference, so a bare
/// nine digits is allowed, WB-partner-15). Returns it trimmed.
pub fn check_label(label: &str) -> Result<String, String> {
crate::settings::line_text("label", label, crate::settings::MAX_TEXT)
crate::settings::reference_line_text("label", label, crate::settings::MAX_TEXT)
}
/// Check a last four (INVARIANT 2).
+36 -14
View File
@@ -1024,6 +1024,7 @@ impl Ledger {
if code.trim().is_empty() {
return Err(LedgerError::EmptyAccountCode);
}
LedgerError::reference_text("the account code", code)?;
let name = name.trim();
if name.is_empty() {
return Err(LedgerError::EmptyAccountName);
@@ -1226,14 +1227,8 @@ impl Ledger {
/// allowed but no other control character, and no full TIN (
/// BS-partner-2). Returns it trimmed.
pub fn check_rename_reason(reason: &str) -> Result<String, LedgerError> {
let r = crate::settings::long_text("reason", reason, crate::settings::MAX_LONG_TEXT)
.map_err(LedgerError::InvalidRenameReason)?;
if crate::parties::has_full_tin(&r) {
return Err(LedgerError::InvalidRenameReason(
"reason holds nine digits in a row, which read as a full SSN or EIN: write only the last four".into(),
));
}
Ok(r)
crate::settings::long_text("reason", reason, crate::settings::MAX_LONG_TEXT)
.map_err(LedgerError::InvalidRenameReason)
}
/// Whether `policy.require_tax_category` lets an account be created
@@ -1300,6 +1295,7 @@ impl Ledger {
if code.trim().is_empty() {
return Err(LedgerError::EmptyAccountCode);
}
LedgerError::reference_text("the account code", code)?;
if self.chart.find_by_code(code).is_some() {
return Err(LedgerError::DuplicateAccountCode(code.to_string()));
}
@@ -1575,6 +1571,9 @@ impl Ledger {
/// - NEVER create a draft there
/// BECAUSE a closed period takes no new entries.
/// 2. Otherwise: SHOULD return a fresh id, one past the last.
/// 3. IF the description looks like it holds a tax id (nine digits
/// standing alone, an SSN's 3-2-4 or an EIN's 2-7: BS-partner-2):
/// SHOULD refuse (FreeTextHoldsTin).
/// ```
pub fn try_create_entry(
&mut self,
@@ -1582,6 +1581,7 @@ impl Ledger {
description: &str,
) -> Result<EntryId, LedgerError> {
crate::calendar::check(date)?;
LedgerError::free_text("the entry description", description)?;
if let Some(pid) = self.closed_period_containing(date) {
return Err(LedgerError::ClosedPeriod(pid, date.to_string()));
}
@@ -2086,7 +2086,7 @@ impl Ledger {
state: crate::DraftState,
) -> Result<(), LedgerError> {
if let crate::DraftState::AwaitingEvidence { note } = &state {
crate::parties::check_text("the note", note).map_err(LedgerError::InvalidDraft)?;
crate::parties::check_note("the note", note).map_err(LedgerError::InvalidDraft)?;
}
self.draft_mut(entry)?.set_draft_state(state);
Ok(())
@@ -2135,7 +2135,7 @@ impl Ledger {
"a discarded draft needs a reason".to_string(),
));
}
crate::parties::check_text("the reason", reason).map_err(LedgerError::InvalidDraft)?;
crate::parties::check_note("the reason", reason).map_err(LedgerError::InvalidDraft)?;
self.replay_discard_draft(entry)
}
@@ -2505,6 +2505,7 @@ impl Ledger {
description: &str,
) -> Result<EntryId, LedgerError> {
self.check_reversal(entry, date)?;
LedgerError::free_text("the reversal's description", description)?;
let original = self
.entries
.get(&entry)
@@ -2606,6 +2607,11 @@ impl Ledger {
if new.description.trim().is_empty() {
return Err(LedgerError::EmptyAssetDescription);
}
// New work only: a journaled description replays as written
// (BS-entry-4).
if strict {
LedgerError::free_text("the asset description", &new.description)?;
}
if new.cost.amount <= Decimal::ZERO {
return Err(LedgerError::InvalidAssetCost(new.cost.amount));
}
@@ -2767,6 +2773,7 @@ impl Ledger {
tag: tag.to_string(),
why,
})?;
LedgerError::reference_text("the asset tag", tag)?;
match self.asset_tags.get(&assets::tag_key(tag)) {
Some(&holder) if Some(holder) != id => Err(LedgerError::AssetTagTaken {
tag: tag.to_string(),
@@ -2803,6 +2810,7 @@ impl Ledger {
}
if let Some(s) = serial {
assets::check_serial(s).map_err(LedgerError::InvalidSerial)?;
LedgerError::reference_text("the serial number", s)?;
}
Ok(())
}
@@ -3012,6 +3020,7 @@ impl Ledger {
if description.trim().is_empty() {
return Err(LedgerError::EmptyAssetDescription);
}
LedgerError::free_text("the asset description", description)?;
Ok(())
}
@@ -3581,6 +3590,7 @@ impl Ledger {
end: NaiveDate,
) -> Result<PeriodId, LedgerError> {
periods::validate_period_range(start, end)?;
LedgerError::free_text("the period name", name)?;
let nested = |a: (NaiveDate, NaiveDate), b: (NaiveDate, NaiveDate)| {
(a.0 >= b.0 && a.1 <= b.1) || (b.0 >= a.0 && b.1 <= a.1)
};
@@ -5596,7 +5606,7 @@ impl Ledger {
"say why the entry has no counterparty".into(),
));
}
crate::parties::check_text("reason", reason).map_err(LedgerError::InvalidParty)
crate::parties::check_note("the reason", reason).map_err(LedgerError::InvalidParty)
}
/// Why an entry has no counterparty, when it was marked so.
@@ -5892,6 +5902,8 @@ impl Ledger {
}
arap::validate_lines(&lines)?;
arap::validate_due_date(date, due_date)?;
arap::check_document_text(fields.customer_ref.as_deref(), fields.memo.as_deref(), None)?;
arap::check_snapshots(fields.bill_to.as_ref(), fields.seller.as_ref())?;
if let Some(number) = &fields.number
&& self
.invoices
@@ -6029,6 +6041,11 @@ impl Ledger {
if let Some(received_on) = fields.received_on {
crate::calendar::check(received_on)?;
}
arap::check_document_text(
fields.vendor_ref.as_deref(),
fields.memo.as_deref(),
fields.duplicate_reason.as_deref(),
)?;
if let Some(vendor_ref) = fields.vendor_ref.as_deref() {
self.check_vendor_ref(vendor_id, vendor_ref, fields.duplicate_reason.as_deref())?;
}
@@ -6203,11 +6220,11 @@ impl Ledger {
crate::parties::check_text("a recipient", to).map_err(LedgerError::InvalidSend)?;
}
if let Some(reference) = &sent.reference {
crate::parties::check_text("the reference", reference)
crate::parties::check_reference_note("the reference", reference)
.map_err(LedgerError::InvalidSend)?;
}
if let Some(note) = &sent.note {
crate::parties::check_text("the note", note).map_err(LedgerError::InvalidSend)?;
crate::parties::check_note("the note", note).map_err(LedgerError::InvalidSend)?;
}
self.invoices
.get_mut(&invoice)
@@ -6768,6 +6785,9 @@ impl Ledger {
arap::MAX_REFERENCE_CHARS,
));
}
if let Some(reason) = &app.discount_reason {
LedgerError::free_text("the discount reason", reason)?;
}
if app.discount > Decimal::ZERO {
self.check_discount(app, kind, total, doc_date, params.date)?;
}
@@ -7262,6 +7282,7 @@ impl Ledger {
arap::MAX_REFERENCE_CHARS
)));
}
LedgerError::free_text("the reason", reason)?;
if amount <= Decimal::ZERO {
return Err(LedgerError::InvalidWriteOff(format!(
"a write-off's amount must be above zero, got {amount}"
@@ -7373,6 +7394,7 @@ impl Ledger {
arap::MAX_REFERENCE_CHARS
)));
}
LedgerError::free_text("the reason", reason)?;
let (_, _, origin, _) = self.doc_header(doc)?;
let chain = self.reversal_chain(origin);
let target = *chain.last().unwrap_or(&origin);
@@ -8732,7 +8754,7 @@ impl Ledger {
&mut self,
annotation: crate::evidence::Annotation,
) -> Result<(), LedgerError> {
self.annotate_attachment(annotation)
crate::parties::replaying(|| self.annotate_attachment(annotation))
}
/// The entries `entry` records settling (`entry.settles`, plan P6).
+33 -3
View File
@@ -416,7 +416,7 @@ fn tin_separator(c: char) -> bool {
/// right-to-left marks and the other directional formatting characters,
/// the word joiner, the byte-order mark, the variation selectors, the tags
/// and the fillers. None is ASCII.
fn tin_invisible(c: char) -> bool {
pub(crate) fn tin_invisible(c: char) -> bool {
matches!(
c,
'\u{AD}'
@@ -717,6 +717,34 @@ pub fn check_text(field: &str, text: &str) -> Result<(), String> {
Ok(())
}
/// Check a free text field: no tax id's shape (a nine-digit number standing
/// alone, an SSN's 3-2-4, an EIN's 2-7: [`crate::settings::check_free_text`]),
/// at most 500 characters, no control characters except newline. For a
/// memo, a note or a reason; a party's own fields keep the strict
/// [`check_text`] (BS-partner-2; the owner's choice, 2026-11-21).
pub fn check_note(field: &str, text: &str) -> Result<(), String> {
crate::settings::check_free_text(field, text)?;
check_note_form(field, text)
}
/// [`check_note`] for a reference (a payment's or a send's reference, a
/// file's location): only the grouped shapes are refused, a bare nine
/// digits is allowed ([`crate::settings::check_reference_text`]).
pub fn check_reference_note(field: &str, text: &str) -> Result<(), String> {
crate::settings::check_reference_text(field, text)?;
check_note_form(field, text)
}
fn check_note_form(field: &str, text: &str) -> Result<(), String> {
if text.chars().count() > 500 {
return Err(format!("{field} is at most 500 characters"));
}
if text.chars().any(|c| c.is_control() && c != '\n') {
return Err(format!("{field} can't contain control characters"));
}
Ok(())
}
/// Check an email address: one line of party text ([`check_text`], which
/// refuses a full TIN) in a plain address shape, one `@` and no spaces. Not
/// an RFC grammar test: the books only print it, they never send (A-4).
@@ -746,12 +774,14 @@ impl W9Facts {
("entity_type", Some(self.entity_type.as_str())),
("exempt_payee_code", self.exempt_payee_code.as_deref()),
("fatca_code", self.fatca_code.as_deref()),
("kept_at", Some(self.kept_at.as_str())),
] {
if let Some(t) = t {
check_text(f, t)?;
}
}
// Where the paper is kept is a reference (a binder, a portal, a
// file name): a bare nine digits is allowed (WB-partner-15).
check_reference_note("kept_at", &self.kept_at)?;
if let Some(h) = &self.vault_record
&& (h.len() != 64 || !h.chars().all(|c| c.is_ascii_hexdigit()))
{
@@ -770,7 +800,7 @@ impl W4Facts {
if self.kept_at.trim().is_empty() {
return Err("say where the W-4 itself is kept".into());
}
check_text("kept_at", &self.kept_at)
check_reference_note("kept_at", &self.kept_at)
}
}
+1
View File
@@ -109,6 +109,7 @@ pub fn validate_payroll_lines(lines: &[PayrollLine]) -> Result<(), LedgerError>
return Err(LedgerError::EmptyPayroll);
}
for line in lines {
LedgerError::free_text("the employee name", &line.employee_name)?;
for amount in [
line.gross_pay,
line.federal_withholding,
+2
View File
@@ -508,6 +508,7 @@ pub fn validate_schedule_under(
chart: &ChartOfAccounts,
) -> Result<(), LedgerError> {
validate_schedule_shape(new, chart)?;
LedgerError::free_text("the schedule's description", &new.description)?;
crate::calendar::check(new.start)?;
let past_the_calendar = || {
Err(LedgerError::InvalidSchedule(format!(
@@ -773,6 +774,7 @@ pub fn validate_recurring(new: &NewRecurring, chart: &ChartOfAccounts) -> Result
return Err(LedgerError::AmountOutOfRange);
}
validate_recurring_journaled(new, chart)?;
LedgerError::free_text("the recurring entry's description", &new.description)?;
crate::calendar::check(new.start)?;
if let Some(end) = new.end {
crate::calendar::check(end)?;
+279 -40
View File
@@ -713,10 +713,50 @@ pub fn decimal(s: &str) -> Option<Decimal> {
/// Whether `text` holds a number that reads as a full TIN (INVARIANT 4):
/// nine digits standing alone (no digit right before or after), bare or
/// printed the way an SSN (3-2-4) or an EIN (2-7) is, the groups joined by
/// a hyphen or any other dash, a dot, or a space (or a dash with spaces
/// around it); full-width digits count as digits.
/// a hyphen or any other dash, or a space (or a dash with spaces around
/// it), whatever Unicode form the dash, space or digit takes (full-width,
/// Arabic-Indic, no-break space, en space, a line break, ...), with
/// zero-width and soft-hyphen characters not counted. A dot joins an SSN's
/// groups only when it joins both (`000.00.0000`), never an EIN's, so a
/// coordinate (`47.6062095`) is no tax id.
///
/// ```text
/// GOAL: the one test free text meets before it is kept: it refuses what
/// looks like a tax id and nothing else.
/// SOURCE: BS-partner-2 (no full TIN in the books); wanderbooks' CHOICE on
/// it (the owner, 2026-11-21: shapes on free text, strict on party
/// fields, masking on bank imports; a reference field allows a
/// bare nine digits, decided by the lead the same day within that
/// choice), WB-partner-15.
/// INVARIANTS:
/// 1. Nine digits standing alone, an SSN's 3-2-4 and an EIN's 2-7 are
/// found, with any dash or space (Unicode forms and line breaks
/// too) between the groups, and a dot between all of an SSN's.
/// 2. An invoice number (`2026-11-0042`), a phone number, an order
/// number, a reference of ten digits or more, an amount with comma
/// groups, a date, a date followed by a reference
/// (`2026-11-21 0001234`) and a decimal (`47.6062095`) are not found.
/// 3. A group that starts or ends inside a longer run of digits and
/// dashes (a digit and a dash before its first digit, or a dash and a
/// digit after its last) is part of that run, not a tax id.
/// 4. During a replay ([`crate::parties::replaying`]) the Unicode forms,
/// line breaks and invisible characters are not read, so a line an
/// earlier version took still replays (BS-entry-4).
/// SCENARIOS:
/// 1. IF a memo says `paid 000-00-0000`: SHOULD be found.
/// 2. IF it says `inv 2026-11-0042`: SHOULD NOT be.
/// 3. IF it says `at 47.6062095`: SHOULD NOT be.
/// ```
pub fn holds_printed_tin(text: &str) -> bool {
printed_tin(text, false)
!printed_tin_spans(text, Reading::Free).1.is_empty()
}
/// [`holds_printed_tin`] for a reference (an asset tag, a serial number, an
/// invoice or bill number, a payment reference, an account code, a file
/// name): a bare run of nine digits is a legitimate number there, so only
/// the printed SSN (3-2-4) and EIN (2-7) forms count (WB-partner-15).
pub fn holds_printed_tin_in_reference(text: &str) -> bool {
!printed_tin_spans(text, Reading::Reference).1.is_empty()
}
/// [`holds_printed_tin`] for a web address: the printed SSN (3-2-4) and
@@ -725,44 +765,154 @@ pub fn holds_printed_tin(text: &str) -> bool {
/// id in a path or query (an app store listing's `id284882215`), not a
/// TIN someone wrote down (BS-partner-2).
pub fn holds_printed_tin_in_link(text: &str) -> bool {
printed_tin(text, true)
!printed_tin_spans(text, Reading::Link).1.is_empty()
}
/// [`holds_printed_tin`], with a link's bare runs let through when `link`.
fn printed_tin(text: &str, link: bool) -> bool {
// Full-width digits read as the digits they are.
let c: Vec<char> = text
.chars()
.map(|ch| match ch {
'\u{ff10}'..='\u{ff19}' => char::from_digit(ch as u32 - 0xff10, 10).unwrap_or(ch),
_ => ch,
})
/// `text` with every number [`holds_printed_tin`] finds masked down to its
/// last four digits: every other digit becomes `•`, the separators stay
/// (`•••-••-0000`), the form the books show a TIN in everywhere else. For
/// text that is not typed by a person and must be kept (a bank's
/// description of a transaction, a line the program composes from text the
/// books already hold), never for a refusal's words.
pub fn mask_printed_tins(text: &str) -> std::borrow::Cow<'_, str> {
mask_spans(text, Reading::Free)
}
/// [`mask_printed_tins`] for a reference ([`holds_printed_tin_in_reference`]):
/// a bare run of nine digits stays.
pub fn mask_printed_tins_in_reference(text: &str) -> std::borrow::Cow<'_, str> {
mask_spans(text, Reading::Reference)
}
fn mask_spans(text: &str, reading: Reading) -> std::borrow::Cow<'_, str> {
let (mut chars, spans) = printed_tin_spans(text, reading);
if spans.is_empty() {
return std::borrow::Cow::Borrowed(text);
}
for (from, to) in spans {
let digits: Vec<usize> = (from..to).filter(|&i| chars[i].is_numeric()).collect();
let keep = digits.len().saturating_sub(4);
for &i in &digits[..keep] {
chars[i] = '\u{2022}';
}
}
std::borrow::Cow::Owned(chars.into_iter().collect())
}
/// How many numbers [`holds_printed_tin`] finds in `text`.
pub fn count_printed_tins(text: &str) -> usize {
printed_tin_spans(text, Reading::Free).1.len()
}
/// What [`printed_tin_spans`] looks for.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Reading {
/// Free text: nine digits alone, an SSN's 3-2-4, an EIN's 2-7.
Free,
/// A reference: the grouped shapes only.
Reference,
/// A web address: free text, but a bare nine digits joined to a letter
/// or URL punctuation is an id in a path.
Link,
}
/// A character that stands for a digit: ASCII, full-width, or any other
/// script's numeral (outside a replay, which reads ASCII and full-width
/// only).
fn digit_like(ch: char, extended: bool) -> bool {
ch.is_ascii_digit() || matches!(ch, '\u{ff10}'..='\u{ff19}') || (extended && ch.is_numeric())
}
/// A space between a TIN's groups: the plain one, and outside a replay
/// the tab, a line break and every Unicode space separator.
fn tin_space(ch: char, extended: bool) -> bool {
ch == ' '
|| (extended
&& matches!(
ch,
'\t' | '\n'
| '\r'
| '\u{85}'
| '\u{2028}'
| '\u{2029}'
| '\u{a0}'
| '\u{1680}'
| '\u{2000}'
..='\u{200a}' | '\u{202f}' | '\u{205f}' | '\u{3000}'
))
}
/// A dash or dot between a TIN's groups: the hyphen, the dashes U+2010 to
/// U+2015, the minus sign and the dot, and outside a replay every other
/// Unicode dash and dot form.
fn tin_dash(ch: char, extended: bool) -> bool {
matches!(ch, '-' | '\u{2010}'..='\u{2015}' | '\u{2212}' | '.')
|| (extended
&& matches!(
ch,
'\u{58a}'
| '\u{1806}'
| '\u{2024}'
| '\u{2043}'
| '\u{2e3a}'
| '\u{2e3b}'
| '\u{fe58}'
| '\u{fe63}'
| '\u{ff0d}'
| '\u{ff0e}'
))
}
/// The dots among [`tin_dash`]'s characters.
fn tin_dot(ch: char) -> bool {
matches!(ch, '.' | '\u{2024}' | '\u{ff0e}')
}
/// The characters of `text` and the runs ([from, to) in characters) of it
/// that read as a full TIN, non-overlapping, left to right.
fn printed_tin_spans(text: &str, reading: Reading) -> (Vec<char>, Vec<(usize, usize)>) {
let extended = !crate::parties::is_replaying();
let all: Vec<char> = text.chars().collect();
// What is read: outside a replay, the zero-width and soft-hyphen
// characters are not there (`1\u{200B}2` shows as `12`). `seen[i]` is
// where the i-th character read sits in `all`.
let seen: Vec<usize> = (0..all.len())
.filter(|&i| !(extended && crate::parties::tin_invisible(all[i])))
.collect();
let digit = |i: usize| c.get(i).is_some_and(char::is_ascii_digit);
let dash = |ch: char| matches!(ch, '-' | '\u{2010}'..='\u{2015}' | '\u{2212}' | '.');
let c: Vec<char> = seen.iter().map(|&i| all[i]).collect();
let digit = |i: usize| c.get(i).is_some_and(|&ch| digit_like(ch, extended));
// A hyphen or other dash, the dot not counted.
let hyphen = |i: usize| {
c.get(i)
.is_some_and(|&ch| tin_dash(ch, extended) && !tin_dot(ch))
};
// A joiner at `i`: a dash, dot or space, or a dash with spaces around
// it; returns where the next group starts.
let joiner = |i: usize| -> Option<usize> {
// it; returns where the next group starts, and whether it is a dot.
let joiner = |i: usize| -> Option<(usize, bool)> {
let mut j = i;
while c.get(j) == Some(&' ') {
while c.get(j).is_some_and(|&ch| tin_space(ch, extended)) {
j += 1;
}
let mut dashes = 0;
while c.get(j).copied().is_some_and(dash) {
let (mut dashes, mut dotted) = (0, false);
while c.get(j).is_some_and(|&ch| tin_dash(ch, extended)) {
dotted |= tin_dot(c[j]);
j += 1;
dashes += 1;
}
while c.get(j) == Some(&' ') {
while c.get(j).is_some_and(|&ch| tin_space(ch, extended)) {
j += 1;
}
let spaces = j - i - dashes;
(j > i && dashes <= 1 && spaces <= 2).then_some(j)
(j > i && dashes <= 1 && spaces <= 2).then_some((j, dotted))
};
let groups_at = |at: usize, groups: &[usize]| -> Option<usize> {
let mut i = at;
// Where `groups` of digits end from `at`, and how many joiners were dots.
let groups_at = |at: usize, groups: &[usize]| -> Option<(usize, usize)> {
let (mut i, mut dots) = (at, 0);
for (n, g) in groups.iter().enumerate() {
if n > 0 {
i = joiner(i)?;
let (next, dotted) = joiner(i)?;
i = next;
dots += usize::from(dotted);
}
for _ in 0..*g {
if !digit(i) {
@@ -771,29 +921,101 @@ fn printed_tin(text: &str, link: bool) -> bool {
i += 1;
}
}
Some(i)
Some((i, dots))
};
let url_joined = |i: Option<usize>| {
i.and_then(|i| c.get(i))
.is_some_and(|ch| ch.is_alphabetic() || matches!(ch, '/' | '=' | '?' | '&' | '#'))
};
(0..c.len()).any(|at| {
(at == 0 || !digit(at - 1))
&& [&[9][..], &[3, 2, 4][..], &[2, 7][..]].iter().any(|g| {
groups_at(at, g).is_some_and(|end| {
!digit(end)
&& !(link
&& g.len() == 1
&& (url_joined(at.checked_sub(1)) || url_joined(Some(end))))
})
})
})
// The text before `at` ends in a digit and a dash: the group is the
// tail of a longer number (a date's day, a part number).
let digit_dash_before = |at: usize| at >= 2 && hyphen(at - 1) && digit(at - 2);
// The text from `end` is a dash and a digit: the group is the head of a
// longer number.
let dash_digit_after = |end: usize| hyphen(end) && digit(end + 1);
// A dot with a digit on each side: a decimal point.
let decimal_point = |i: usize| c.get(i) == Some(&'.') && i >= 1 && digit(i - 1) && digit(i + 1);
let shapes: &[&[usize]] = match reading {
Reading::Reference => &[&[3, 2, 4], &[2, 7]],
Reading::Free | Reading::Link => &[&[9], &[3, 2, 4], &[2, 7]],
};
let mut spans = Vec::new();
let mut at = 0;
while at < c.len() {
if at > 0 && digit(at - 1) {
at += 1;
continue;
}
let found = shapes.iter().find_map(|g| {
let (end, dots) = groups_at(at, g)?;
if digit(end) {
return None;
}
match g.len() {
// Nine digits alone: not a number in a path (a link), not
// the digits of a decimal.
1 => {
let in_a_path = reading == Reading::Link
&& (url_joined(at.checked_sub(1)) || url_joined(Some(end)));
let in_a_decimal = (at >= 1 && decimal_point(at - 1)) || decimal_point(end);
(!in_a_path && !in_a_decimal).then_some(end)
}
// An EIN: never joined by a dot.
2 => (dots == 0 && !digit_dash_before(at) && !dash_digit_after(end)).then_some(end),
// An SSN: dots at both joiners or at neither.
_ => ((dots == 0 || dots == 2) && !digit_dash_before(at) && !dash_digit_after(end))
.then_some(end),
}
});
match found {
Some(end) => {
spans.push((seen[at], seen[end - 1] + 1));
at = end;
}
None => at += 1,
}
}
(all, spans)
}
/// What a refusal says of a field that looks like it holds a tax id
/// (BS-partner-2): which field, why, where a tax id goes instead. Never
/// the number.
pub fn tin_refusal(field: &str) -> String {
format!(
"{field} looks like it holds a tax id (a full SSN or EIN: nine digits, bare or written 3-2-4 or 2-7), so nothing was changed. Tax ids are stored only with books.set_tin or a W-9 (books.set_w9), never in a name, note or description; to mention a number, write only its last four digits"
)
}
/// Free text (a memo, a note, a reason, a description, a name) that may be
/// kept: it must not look like a tax id ([`holds_printed_tin`]). Returns
/// why not, in [`tin_refusal`]'s words. Never refuses during a replay
/// ([`crate::parties::replaying`]): the journal holds what it holds, and
/// books an earlier version wrote open (BS-entry-4).
pub fn check_free_text(field: &str, text: &str) -> Result<(), String> {
if !crate::parties::is_replaying() && holds_printed_tin(text) {
return Err(tin_refusal(field));
}
Ok(())
}
/// A reference (an asset tag, a serial number, an invoice or bill number, a
/// payment reference, an account code, a file name, a label) that may be
/// kept: it must not look like a tax id's *printed* shapes
/// ([`holds_printed_tin_in_reference`]), a bare run of nine digits being a
/// legitimate number there. Returns why not, in [`tin_refusal`]'s words.
/// Never refuses during a replay (BS-entry-4).
pub fn check_reference_text(field: &str, text: &str) -> Result<(), String> {
if !crate::parties::is_replaying() && holds_printed_tin_in_reference(text) {
return Err(tin_refusal(field));
}
Ok(())
}
fn no_tin(what: &str, s: &str) -> Result<(), String> {
if holds_printed_tin(s) {
return Err(format!(
"{what} holds a number that reads as a full SSN or EIN (nine digits, bare or printed 3-2-4 or 2-7): a full TIN goes only into the vault (books.set_tin), the company's EIN into company.ein and its D-U-N-S number into company.duns; for any other nine-digit number, write its last four"
"{what} holds a number that reads as a full SSN or EIN (nine digits, bare or printed 3-2-4 or 2-7): a full TIN goes only into the vault (books.set_tin or a W-9, books.set_w9), the company's EIN into company.ein and its D-U-N-S number into company.duns; for any other nine-digit number, write its last four"
));
}
Ok(())
@@ -807,6 +1029,19 @@ pub fn line_text(what: &str, s: &str, max: usize) -> Result<String, String> {
Ok(t)
}
/// [`line_text`] for a reference (a label): one line, with only the printed
/// SSN and EIN shapes refused, a bare nine digits allowed
/// ([`holds_printed_tin_in_reference`]).
pub fn reference_line_text(what: &str, s: &str, max: usize) -> Result<String, String> {
let t = bare_line_text(what, s, max)?;
if holds_printed_tin_in_reference(&t) {
return Err(format!(
"{what} holds a number that reads as a full SSN or EIN (printed 3-2-4 or 2-7): a full TIN goes only into the vault (books.set_tin or a W-9, books.set_w9); for any other number, write it without that grouping"
));
}
Ok(t)
}
/// [`line_text`] without the full-TIN check: for the one place a nine-digit
/// number is legitimate (an `ach` or `wire` payment method's bank-detail
/// line, where it is a routing number: A-3).
@@ -2090,8 +2325,6 @@ mod tests {
"123-45-6789",
"a 12-3456789.",
"(123-45-6789)",
"1-123-45-6789",
"12-3456789-0",
"123\u{2010}45\u{2010}6789",
"123 45 6789",
"SSN 123456789",
@@ -2105,6 +2338,12 @@ mod tests {
"12-34567890",
"1234567890",
"14745117-0160",
// the tail or head of a longer run of digits and dashes
"1-123-45-6789",
"12-3456789-0",
// a decimal, a date and its reference
"47.6062095",
"2026-11-21 0001234",
"801-555-0142",
"2026-10-04",
"100 Example Way, Midvale, UT 84047",
+946
View File
@@ -0,0 +1,946 @@
//! Free text never holds a tax id (BS-partner-2): the one detector free
//! text meets (`ledger_core::settings::holds_printed_tin`), the masking a
//! bank's description gets, and the engine commands that take free text.
//!
//! Oracle: the owner's decision of 2026-11-21 (docs/spec/claims/partner.md,
//! the CHOICE on BS-partner-2): free text refuses what looks like a tax id,
//! that is nine digits standing alone, an SSN's 3-2-4 and an EIN's 2-7, with
//! any dash, dot or space between the groups; it lets an invoice number, a
//! phone number, an order number, a reference of ten digits or more, an
//! amount and a date through. The fake ids are `000-00-0000` and
//! `00-0000000`; no real one appears here.
use ledger_core::settings::{
check_free_text, check_reference_text, count_printed_tins, holds_printed_tin,
holds_printed_tin_in_reference, mask_printed_tins, mask_printed_tins_in_reference, tin_refusal,
};
use proptest::prelude::*;
/// Every separator the detector reads between a TIN's groups, the dot
/// aside (a dot joins only the three groups of an SSN, both: `DOTS`).
const SEPARATORS: &[&str] = &[
"-",
"\u{2010}",
"\u{2011}",
"\u{2012}",
"\u{2013}",
"\u{2014}",
"\u{2015}",
"\u{2212}",
"\u{fe58}",
"\u{fe63}",
"\u{ff0d}",
" ",
" ",
"\t",
"\u{a0}",
"\u{2002}",
"\u{2003}",
"\u{2009}",
"\u{202f}",
"\u{3000}",
" - ",
" \u{2013} ",
"\u{a0}\u{2014}\u{a0}",
// a line break reads as a space
"\n",
"\r\n",
];
/// The dots: they join an SSN's groups when they join both of them.
const DOTS: &[&str] = &[".", "\u{ff0e}", "\u{2024}"];
/// Text around a number that has no digit at its edge.
const CONTEXTS: &[(&str, &str)] = &[
("", ""),
("paid ", ""),
("", " paid"),
("SSN ", "."),
("(", ")"),
("ref: ", ", thanks"),
("a\u{e9}", "z"),
];
fn digits(n: usize) -> impl Strategy<Value = String> {
prop::collection::vec(0u8..10, n)
.prop_map(|d| d.into_iter().map(|x| char::from(b'0' + x)).collect())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(512))]
/// Every 3-2-4 grouping with any listed separator is found.
#[test]
fn every_ssn_grouping_is_found(
a in digits(3), b in digits(2), c in digits(4),
s1 in 0..SEPARATORS.len(), s2 in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(),
) {
let text = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[s1], SEPARATORS[s2], CONTEXTS[ctx].1);
prop_assert!(holds_printed_tin(&text), "{text:?}");
}
/// An SSN written with a dot at both joiners (`000.00.0000`) is found.
#[test]
fn a_dotted_ssn_is_found(
a in digits(3), b in digits(2), c in digits(4),
s1 in 0..DOTS.len(), s2 in 0..DOTS.len(), ctx in 0..CONTEXTS.len(),
) {
let text = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, DOTS[s1], DOTS[s2], CONTEXTS[ctx].1);
prop_assert!(holds_printed_tin(&text), "{text:?}");
}
/// A dot at one joiner only, or between an EIN's groups, is a decimal or
/// a version, not a tax id (a coordinate: `47.6062095`).
#[test]
fn a_dot_alone_is_not_a_joiner(
a in digits(3), b in digits(2), c in digits(4), e in digits(7),
dot in 0..DOTS.len(), sep in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(),
) {
let ein = format!("{}{}{}{e}{}", CONTEXTS[ctx].0, &a[..2], DOTS[dot], CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&ein), "{ein:?}");
let first = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, DOTS[dot], SEPARATORS[sep], CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&first), "{first:?}");
let second = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[sep], DOTS[dot], CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&second), "{second:?}");
}
/// A date followed by a seven-digit reference is a date and a
/// reference, whatever stands between them, and a decimal with seven
/// digits after its point is a number (`47.6062095`).
#[test]
fn a_date_then_a_reference_and_a_decimal_are_no_tax_id(
y in 1990u32..2100, m in 1u32..13, d in 1u32..29, r in digits(7),
whole in digits(2), sep in 0..4usize, ctx in 0..CONTEXTS.len(),
) {
let between = [" ", "\t", "\n", " "][sep];
let date = format!("{}{y}-{m:02}-{d:02}{between}{r}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&date), "{date:?}");
let decimal = format!("{}{whole}.{r}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&decimal), "{decimal:?}");
}
/// Every 2-7 grouping with any listed separator is found.
#[test]
fn every_ein_grouping_is_found(
a in digits(2), b in digits(7), s in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(),
) {
let text = format!("{}{a}{}{b}{}", CONTEXTS[ctx].0, SEPARATORS[s], CONTEXTS[ctx].1);
prop_assert!(holds_printed_tin(&text), "{text:?}");
}
/// Nine digits standing alone are found.
#[test]
fn nine_digits_alone_are_found(a in digits(9), ctx in 0..CONTEXTS.len()) {
let text = format!("{}{a}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1);
prop_assert!(holds_printed_tin(&text), "{text:?}");
}
/// Ten digits or more are a reference, never a tax id: one digit more
/// before, after or inside a shape takes it out of the reading.
#[test]
fn ten_or_more_digits_are_a_reference(a in digits(10), extra in 0usize..6, ctx in 0..CONTEXTS.len()) {
let tail: String = "7".repeat(extra);
let text = format!("{}{a}{tail}{}", CONTEXTS[ctx].0, CONTEXTS[ctx].1);
prop_assert!(!holds_printed_tin(&text), "{text:?}");
}
/// Masking leaves nothing for the detector to find, keeps the last four
/// digits of each number and its length, and changes nothing else.
#[test]
fn masking_keeps_the_last_four_and_the_rest(
a in digits(3), b in digits(2), c in digits(4), s1 in 0..SEPARATORS.len(),
s2 in 0..SEPARATORS.len(), ctx in 0..CONTEXTS.len(),
) {
let text = format!("{}{a}{}{b}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[s1], SEPARATORS[s2], CONTEXTS[ctx].1);
let masked = mask_printed_tins(&text).into_owned();
prop_assert!(!holds_printed_tin(&masked), "{masked:?}");
prop_assert_eq!(masked.chars().count(), text.chars().count());
prop_assert_eq!(count_printed_tins(&text), 1);
let expect = format!("{}\u{2022}\u{2022}\u{2022}{}\u{2022}\u{2022}{}{c}{}", CONTEXTS[ctx].0, SEPARATORS[s1], SEPARATORS[s2], CONTEXTS[ctx].1);
prop_assert_eq!(masked, expect);
}
}
/// What must go through: the allow-list of the owner's table.
#[test]
fn the_allow_list_passes() {
for fine in [
// invoice numbers
"INV-2026-11-0042",
"2026-11-0042",
"invoice 2026-0042",
"INV 20261121",
// phone numbers
"801-555-0142",
"(801) 555-0142",
"+1 801 555 0142",
"+44 20 7946 0958",
// order numbers
"ORD-48213-7",
"order 4821-3377-12",
"PO 12-345",
// references of ten digits or more
"1234567890",
"REF 202611210042",
"000000000000",
"12345678901234567890",
// amounts
"$1,234,567.89",
"1,234,567",
"$12,345,678.00",
"USD 1 234 567,89",
// dates
"2026-11-21",
"11/21/2026",
"21.11.2026",
"2026-11-21T10:30:00Z",
// decimals: a coordinate, a version, an amount
"47.6062095",
"at 47.6062095, -122.3321",
"17.2345678",
"v 12.3456789",
"$1234567.8901234",
// a date followed by, or inside, a longer number
"2026-11-21 0001234",
"on 2026-11-21 0001234 paid",
"2026-11-0001234",
"55-1234567-001",
"part 5-000-00-0000",
// plain words
"Office rent, November",
"",
] {
assert!(!holds_printed_tin(fine), "{fine:?} must pass");
assert!(check_free_text("memo", fine).is_ok(), "{fine:?} must pass");
}
}
/// What must be found, written out: the shapes with the fake ids.
#[test]
fn the_shapes_are_found() {
for caught in [
"000-00-0000",
"00-0000000",
"000000000",
"tin 000 00 0000",
"ein 00 0000000",
"000\u{2013}00\u{2013}0000",
"000\u{a0}00\u{a0}0000",
"\u{ff10}\u{ff10}\u{ff10}-\u{ff10}\u{ff10}-\u{ff10}\u{ff10}\u{ff10}\u{ff10}",
"\u{660}\u{660}\u{660}-\u{660}\u{660}-\u{660}\u{660}\u{660}\u{660}",
"pay 00-0000000 now",
"SSN: 000.00.0000.",
// a line break between the groups reads as a space
"000\n00\n0000",
"000\r\n00\r\n0000",
"ein 00\n0000000",
"ein 00\r0000000",
// zero-width and soft-hyphen characters between digits are not there
"000\u{200b}-00-0000",
"0\u{200b}0\u{200c}0\u{200d}-0\u{2060}0-00\u{feff}00",
"00\u{ad}-0000000",
"00-000\u{ad}0\u{ad}000",
"0\u{200b}00000000",
"\u{200b}000000000\u{200b}",
// the text around a number
"words 000-00-0000 words",
"(00-0000000)",
] {
assert!(holds_printed_tin(caught), "{caught:?} must be found");
let why = check_free_text("the memo", caught).unwrap_err();
assert!(
why.starts_with("the memo looks like it holds a tax id"),
"{why}"
);
assert!(why.contains("books.set_tin"), "{why}");
assert!(why.contains("W-9"), "{why}");
assert!(
!why.contains("0000"),
"a refusal never repeats the number: {why}"
);
}
}
/// What the shapes do not take for a tax id: a dot is no joiner but between
/// both groups of an SSN, and a group that is the tail or head of a longer
/// run of digits and dashes belongs to that run.
#[test]
fn a_dot_and_a_longer_run_are_no_tax_id() {
for fine in [
"47.6062095",
"17.2345678",
"12.3456789",
"000.00 0000",
"000 00.0000",
"000.00-0000",
"000-00.0000",
"2026-11-21 0001234",
"2026-11-21\n0001234",
"12-3456789-0",
"1-123-45-6789",
"0000-00-0000000",
"123456789.5",
"0.123456789",
] {
assert!(!holds_printed_tin(fine), "{fine:?} must pass");
assert!(check_free_text("memo", fine).is_ok(), "{fine:?} must pass");
}
// ... while the shapes, with words around them, are still found.
for caught in [
"2026-11-21 paid 00-0000000",
"on 2026-11-21: 000-00-0000",
"47.6062095 and then 00-0000000",
"ref 12-3456789.",
"123456789.",
] {
assert!(holds_printed_tin(caught), "{caught:?} must be found");
}
// The line break and the invisible characters are read only outside a
// replay, as the Unicode forms are (BS-entry-4).
let broken = "000\n00\n0000";
assert!(holds_printed_tin(broken));
ledger_core::parties::replaying(|| {
assert!(!holds_printed_tin(broken));
assert!(!holds_printed_tin("0\u{200b}00000000"));
});
}
/// Letters between digits, and a number split across two fields, are an
/// accident and not a way to hide one: the reading leaves them (WB-partner-15).
#[test]
fn letters_between_digits_are_left_alone() {
for fine in ["000a00b0000", "00-0000 000", "000-00x0000"] {
assert!(!holds_printed_tin(fine), "{fine:?}");
}
}
/// A reference's reading (an asset tag, a serial, an invoice or bill
/// number, a payment reference, an account code, a file name): a bare nine
/// digits is a number there; the printed shapes are still refused.
#[test]
fn a_reference_may_be_nine_digits_but_not_a_printed_tax_id() {
for fine in [
"123456789",
"SN 000000000",
"tag 000000000.",
"000000000",
"INV-2026-11-0042",
"1234567890",
"scan 000000000.pdf",
] {
assert!(!holds_printed_tin_in_reference(fine), "{fine:?}");
assert!(check_reference_text("the tag", fine).is_ok(), "{fine:?}");
assert_eq!(
mask_printed_tins_in_reference(fine),
fine,
"a bare nine digits stays in a reference"
);
}
for caught in [
"000-00-0000",
"00-0000000",
"SN 000 00 0000",
"w9 00\u{2013}0000000.pdf",
"000.00.0000",
"000\n00\n0000",
"0\u{200b}0-0000000",
] {
assert!(holds_printed_tin_in_reference(caught), "{caught:?}");
let why = check_reference_text("the tag", caught).unwrap_err();
assert!(
why.starts_with("the tag looks like it holds a tax id") && !why.contains("0000"),
"{why}"
);
}
// Free text says the same of the same bare run: refused.
assert!(holds_printed_tin("123456789"));
// A mask of a reference keeps its bare run and covers its shapes.
assert_eq!(
mask_printed_tins_in_reference("SN 123456789 / 000-00-0000"),
"SN 123456789 / \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000"
);
}
/// Two numbers in one text are two finds, each masked to its last four.
#[test]
fn masking_masks_each_number() {
let text = "ACH 000-00-0000 and ref 00-0000000, then 1234567890";
assert_eq!(count_printed_tins(text), 2);
assert_eq!(
mask_printed_tins(text),
"ACH \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 and ref \u{2022}\u{2022}-\u{2022}\u{2022}\u{2022}0000, then 1234567890"
);
// Nothing to mask: the text comes back as it was.
assert!(matches!(
mask_printed_tins("Whole Foods #1234"),
std::borrow::Cow::Borrowed(_)
));
}
#[test]
fn the_refusal_names_the_field_and_never_a_number() {
let why = tin_refusal("books.add_class name");
assert!(why.starts_with("books.add_class name looks like it holds a tax id"));
assert!(why.contains("books.set_tin") && why.contains("books.set_w9"));
}
// ---------------------------------------------------------------------
// The engine: a caller other than the MCP layer meets the same check.
// ---------------------------------------------------------------------
mod engine {
use chrono::NaiveDate;
use ledger_core::arap::{BillFields, DocumentLine, InvoiceFields, PartySnapshot};
use ledger_core::schedules::{
Frequency, NewRecurring, NewSchedule, ScheduleConvention, ScheduleKind,
};
use ledger_core::{
AccountId, AccountType, Currency, Ledger, LedgerError, Money, NewAsset, Side,
};
use rust_decimal::Decimal;
use std::str::FromStr;
const TIN: &str = "000-00-0000";
fn day(d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(2026, 3, d).unwrap()
}
fn usd(s: &str) -> Money {
Money::new(Decimal::from_str(s).unwrap(), Currency::USD)
}
struct Fx {
l: Ledger,
cash: AccountId,
revenue: AccountId,
expense: AccountId,
asset: AccountId,
accum: AccountId,
liability: AccountId,
}
fn fx() -> Fx {
let mut l = Ledger::new(Currency::USD);
let mut add = |code: &str, name: &str, t: AccountType| {
l.add_account(code, name, t, None, false).unwrap()
};
let cash = add("1000", "Cash", AccountType::Asset);
let asset = add("1500", "Equipment", AccountType::Asset);
let accum = add("1590", "Accumulated depreciation", AccountType::Asset);
let liability = add("2500", "Deferred", AccountType::Liability);
let revenue = add("4000", "Sales", AccountType::Revenue);
let expense = add("6000", "Supplies", AccountType::Expense);
Fx {
l,
cash,
revenue,
expense,
asset,
accum,
liability,
}
}
fn line(desc: &str) -> DocumentLine {
DocumentLine {
description: desc.into(),
amount: Decimal::from(10),
class_id: None,
account: None,
quantity: None,
unit_price: None,
}
}
fn holds_tin(r: Result<impl std::fmt::Debug, LedgerError>, field: &str) {
match r {
Err(LedgerError::FreeTextHoldsTin(why)) => {
assert!(
why.starts_with(&format!("{field} looks like it holds a tax id")),
"{why}"
);
assert!(
why.contains("books.set_tin") && why.contains("W-9"),
"{why}"
);
assert!(!why.contains("0000"), "never the number: {why}");
}
other => panic!("{field}: expected FreeTextHoldsTin, got {other:?}"),
}
}
/// An entry's description, a reversal's, a write-off's and a void's
/// reason, a period's name, an account's code.
#[test]
fn entries_periods_and_codes() {
let mut f = fx();
holds_tin(
f.l.try_create_entry(day(1), &format!("paid {TIN}")),
"the entry description",
);
// Nothing was made: the next entry is still the first.
let e =
f.l.try_create_entry(day(1), "inv 2026-11-0042, ref 1234567890")
.unwrap();
f.l.add_line(e, f.cash, Side::Debit, usd("5.00")).unwrap();
f.l.add_line(e, f.revenue, Side::Credit, usd("5.00"))
.unwrap();
f.l.post_entry(e).unwrap();
let before = f.l.clone();
holds_tin(
f.l.reverse_entry(e, day(2), &format!("oops {TIN}")),
"the reversal's description",
);
assert_eq!(f.l, before, "a refusal changes nothing");
holds_tin(
f.l.create_period(&format!("P {TIN}"), day(1), day(31)),
"the period name",
);
// An account code is a reference: its printed shape is refused, a
// bare nine digits is a code (WB-partner-15).
holds_tin(
f.l.add_account(TIN, "Odd", AccountType::Asset, None, false),
"the account code",
);
let nine =
f.l.add_account("123456789", "Nine", AccountType::Asset, None, false);
assert!(nine.is_ok(), "{nine:?}");
holds_tin(
f.l.renumber_account(f.cash, "00-0000000"),
"the account code",
);
f.l.renumber_account(f.cash, "000000000").unwrap();
f.l.create_period("2026-03", day(1), day(31)).unwrap();
}
/// A document's memo, references, duplicate reason, lines and the
/// customer's printed details.
#[test]
fn documents() {
let mut f = fx();
let c = f.l.add_customer("Acme").unwrap();
let v = f.l.add_vendor("Beta").unwrap();
let inv = |l: &mut Ledger, lines: Vec<DocumentLine>, fields: InvoiceFields| {
l.create_invoice_with(c, day(1), day(31), lines, fields)
};
holds_tin(
inv(
&mut f.l,
vec![line(&format!("work {TIN}"))],
InvoiceFields::default(),
),
"a line's description",
);
holds_tin(
inv(
&mut f.l,
vec![line("ok")],
InvoiceFields {
memo: Some(format!("see {TIN}")),
..Default::default()
},
),
"the memo",
);
holds_tin(
inv(
&mut f.l,
vec![line("ok")],
InvoiceFields {
customer_ref: Some("PO 00-0000000".into()),
..Default::default()
},
),
"the reference",
);
let snap = |name: &str| PartySnapshot {
name: name.into(),
address: None,
email: None,
phone: None,
contact: None,
billing_address: None,
shipping_address: None,
billing_email: None,
};
// The customer's printed details are a party's: any nine digits.
let strict = inv(
&mut f.l,
vec![line("ok")],
InvoiceFields {
bill_to: Some(snap("Acme 1234 56789")),
..Default::default()
},
);
assert!(
matches!(strict, Err(LedgerError::InvalidParty(_))),
"{strict:?}"
);
// The company's own details are free text: its shapes only.
holds_tin(
inv(
&mut f.l,
vec![line("ok")],
InvoiceFields {
seller: Some(snap(&format!("Us {TIN}"))),
..Default::default()
},
),
"the seller name",
);
// Neither a 10-digit PO nor a ZIP+4 in the company's address is a tax id.
let mut us = snap("Us");
us.address = Some("1 Main St, Midvale UT 84047-1234".into());
inv(
&mut f.l,
vec![line("ok")],
InvoiceFields {
customer_ref: Some("1234567890".into()),
memo: Some("2026-11-0042".into()),
seller: Some(us),
..Default::default()
},
)
.unwrap();
let bill = |l: &mut Ledger, fields: BillFields| {
l.create_bill_with(v, day(1), day(31), vec![line("ok")], fields)
};
holds_tin(
bill(
&mut f.l,
BillFields {
vendor_ref: Some(TIN.into()),
..Default::default()
},
),
"the reference",
);
// A bare nine digits is a vendor's invoice number, and a customer's
// purchase order: references.
bill(
&mut f.l,
BillFields {
vendor_ref: Some("000000000".into()),
..Default::default()
},
)
.unwrap();
inv(
&mut f.l,
vec![line("ok")],
InvoiceFields {
customer_ref: Some("PO 123456789".into()),
..Default::default()
},
)
.unwrap();
holds_tin(
bill(
&mut f.l,
BillFields {
memo: Some(TIN.into()),
..Default::default()
},
),
"the memo",
);
holds_tin(
bill(
&mut f.l,
BillFields {
duplicate_reason: Some(format!("again {TIN}")),
..Default::default()
},
),
"the duplicate reason",
);
bill(
&mut f.l,
BillFields {
vendor_ref: Some("INV-2026-11-0042".into()),
..Default::default()
},
)
.unwrap();
}
/// A payment's reference is the engine's to check, as the tools check
/// it: a printed SSN or EIN is refused, a bare nine digits (a check or
/// a confirmation number) is kept, and the entry's description, which
/// is free text, shows it masked. A discount's reason is free text.
#[test]
fn payments_check_their_reference_and_discount_reason() {
use ledger_core::{Application, DocRef, PaymentDetails, SettleParams};
let mut f = fx();
let c = f.l.add_customer("Acme").unwrap();
let v = f.l.add_vendor("Beta").unwrap();
let invoice =
f.l.create_invoice_with(
c,
day(1),
day(31),
vec![line("work")],
InvoiceFields::default(),
)
.unwrap();
let bill =
f.l.create_bill_with(
v,
day(1),
day(31),
vec![line("parts")],
BillFields::default(),
)
.unwrap();
let pay = |l: &mut Ledger, reference: &str| {
l.receive_payment_with(
invoice,
day(5),
Decimal::from(1),
f.cash,
&PaymentDetails {
instrument: None,
reference: Some(reference.into()),
},
)
};
holds_tin(pay(&mut f.l, TIN), "the payment reference");
holds_tin(pay(&mut f.l, "check 00-0000000"), "the payment reference");
let before = f.l.clone();
holds_tin(
f.l.pay_bill_with(
bill,
day(5),
Decimal::from(1),
f.cash,
&PaymentDetails {
instrument: None,
reference: Some(format!("wire {TIN}")),
},
),
"the payment reference",
);
assert_eq!(f.l, before, "a refusal changes nothing");
// A bare nine digits is a reference ...
let e = pay(&mut f.l, "123456789").unwrap();
// ... and the entry's description, free text, holds it masked.
assert_eq!(
f.l.get_entry(e).unwrap().description(),
"Payment on invoice 1 (ref \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}6789)"
);
// A ten-digit trace number is kept as it is.
let e = pay(&mut f.l, "1234567890").unwrap();
assert_eq!(
f.l.get_entry(e).unwrap().description(),
"Payment on invoice 1 (ref 1234567890)"
);
// The discount reason of a settlement.
let settle = |l: &mut Ledger, why: &str| {
l.settle(SettleParams {
date: day(6),
description: "Payment".into(),
cash_account: f.cash,
party: c,
applications: vec![Application {
doc: DocRef::Invoice(invoice),
cash: Decimal::from(1),
discount: Decimal::ZERO,
discount_reason: Some(why.into()),
}],
fee: None,
instrument: None,
reference: None,
})
};
holds_tin(
settle(&mut f.l, &format!("early {TIN}")),
"the discount reason",
);
settle(&mut f.l, "paid within 10 days, ref 1234567890").unwrap();
// A replay reads none of it.
ledger_core::parties::replaying(|| {
let d = PaymentDetails {
instrument: None,
reference: Some(TIN.into()),
};
d.check().unwrap();
});
}
/// A project's fields are refused by the engine itself, whoever calls
/// (the tools' own check runs before it, and says it first).
#[test]
fn a_project_field_is_refused_by_the_engine() {
use ledger_core::classes::ProjectFacts;
let mut f = fx();
let id = f.l.add_class("Harbor").unwrap();
let facts = |notes: Option<&str>, description: Option<&str>, links: &[&str]| ProjectFacts {
notes: notes.map(Into::into),
description: description.map(Into::into),
links: links.iter().map(|l| (*l).to_string()).collect(),
..Default::default()
};
let engine_refusal = |r: Result<(String, ProjectFacts), LedgerError>, field: &str| match r {
Err(LedgerError::InvalidProject(why)) => {
assert!(why.contains(field), "{why}");
assert!(why.contains("full SSN or EIN"), "{why}");
assert!(!why.contains("0000"), "never the number: {why}");
}
other => panic!("{field}: expected the engine's refusal, got {other:?}"),
};
engine_refusal(
f.l.check_set_project(id, "Harbor", &facts(Some(&format!("ssn {TIN}")), None, &[])),
"notes",
);
engine_refusal(
f.l.check_set_project(id, "Harbor", &facts(None, Some("ein 00-0000000"), &[])),
"description",
);
engine_refusal(
f.l.check_set_project(
id,
"Harbor",
&facts(None, None, &["https://x.test/000-00-0000"]),
),
"link",
);
match f
.l
.set_project(id, &format!("Harbor {TIN}"), facts(None, None, &[]))
{
Err(LedgerError::InvalidProject(why)) => {
assert!(why.contains("full SSN or EIN"), "{why}");
}
other => panic!("the name: {other:?}"),
}
// A reference of ten digits, an invoice number and a store listing's
// id are no tax id.
f.l.set_project(
id,
"Harbor 2026-11-0042",
facts(
Some("ref 1234567890"),
Some("PO 2026-0042"),
&["https://apps.example.com/app/id284882215"],
),
)
.unwrap();
}
/// Assets, schedules, recurring entries and payroll names.
#[test]
fn assets_schedules_and_payroll() {
let mut f = fx();
let new = |d: &str| NewAsset {
description: d.into(),
in_service_date: day(1),
cost: usd("1200.00"),
salvage_value: usd("0"),
useful_life_months: 12,
cost_account: f.asset,
accum_depr_account: f.accum,
expense_account: f.expense,
};
holds_tin(
f.l.register_asset(new(&format!("van {TIN}"))),
"the asset description",
);
let a = f.l.register_asset(new("van 1234567890")).unwrap();
holds_tin(
f.l.set_asset_serial(a, Some("SN 00-0000000")),
"the serial number",
);
holds_tin(
f.l.set_asset_description(a, "000000000"),
"the asset description",
);
holds_tin(f.l.set_asset_tag(a, "T-000-00-0000"), "the asset tag");
f.l.set_asset_serial(a, Some("C02XK1ABCDEF")).unwrap();
// A tag and a serial number are references: a bare nine digits
// is one.
f.l.set_asset_serial(a, Some("000000000")).unwrap();
f.l.set_asset_tag(a, "123456789").unwrap();
let sched = |d: &str| NewSchedule {
description: d.into(),
kind: ScheduleKind::PrepaidExpense,
total: usd("1200.00"),
start: day(1),
months: 12,
balance_account: f.asset,
pl_account: f.expense,
convention: ScheduleConvention::Daily,
};
holds_tin(
f.l.register_schedule(sched(&format!("rent {TIN}"))),
"the schedule's description",
);
let _ = f.liability;
let rec = |d: &str| NewRecurring {
description: d.into(),
lines: vec![
(f.expense, Side::Debit, usd("5.00")),
(f.cash, Side::Credit, usd("5.00")),
],
frequency: Frequency::Monthly,
start: day(1),
end: None,
};
holds_tin(
f.l.register_recurring(rec(&format!("fee {TIN}"))),
"the recurring entry's description",
);
f.l.register_recurring(rec("fee 2026-11-0042")).unwrap();
}
/// A draft's note, a discard's reason and a no-party reason: free
/// text now, no longer the strict nine-digit reading.
#[test]
fn notes_and_reasons_use_the_shapes() {
let mut f = fx();
let e = f.l.try_create_entry(day(1), "x").unwrap();
let wait = |n: &str| ledger_core::DraftState::AwaitingEvidence { note: n.into() };
assert!(
f.l.set_draft_state(e, wait(&format!("waiting {TIN}")))
.is_err()
);
f.l.set_draft_state(e, wait("waiting on ref 1234567890, inv 2026-11-0042"))
.unwrap();
assert!(Ledger::check_no_party_reason(&format!("own account {TIN}")).is_err());
Ledger::check_no_party_reason("own account 1234567890").unwrap();
assert!(f.l.discard_draft(e, &format!("dup {TIN}")).is_err());
f.l.discard_draft(e, "entered twice, ref 1234567890")
.unwrap();
}
/// BS-entry-4: a journal line an earlier version took replays, whatever
/// it holds; the books open on it. (A replay is the only way such a
/// line is ever applied: every command refuses it.)
#[test]
fn a_journaled_line_replays_whatever_it_holds() {
let mut f = fx();
let e = f.l.create_entry(day(1), &format!("paid {TIN}"));
f.l.add_line(e, f.cash, Side::Debit, usd("5.00")).unwrap();
f.l.add_line(e, f.revenue, Side::Credit, usd("5.00"))
.unwrap();
f.l.post_entry(e).unwrap();
let r =
f.l.replay_reverse_entry(e, day(2), &format!("undo {TIN}"))
.unwrap();
assert_eq!(
f.l.get_entry(r).unwrap().description(),
format!("undo {TIN}")
);
let ann = ledger_core::Annotation {
attachment_id: 1,
fields: ledger_core::AnnotationFields {
payee: Some(format!("Pat {TIN}")),
..Default::default()
},
note: Some(format!("see {TIN}")),
};
f.l.replay_annotate_attachment(ann.clone()).unwrap();
// The same annotation as a command is refused.
holds_tin(f.l.annotate_attachment(ann), "the payee");
}
}
+7 -1
View File
@@ -444,9 +444,15 @@ fn w9_check_refuses_full_tin_in_any_text() {
let mut f = w9("6789");
f.entity_type = "LLC 12-3456789".to_string();
assert!(f.check().is_err());
// Where the paper is kept is a reference, not a name or a detail: its
// printed shapes are refused, and a bare nine digits (a binder's or a
// file's number) is a number there (WB-partner-15).
let mut f = w9("6789");
f.kept_at = "drawer 123-45-6789".to_string();
assert!(f.check().is_err());
let mut f = w9("6789");
f.kept_at = "drawer 123456789".to_string();
assert!(f.check().is_err());
assert!(f.check().is_ok());
let mut f = w9("6789");
f.exempt_payee_code = Some("123-45-6789".to_string());
assert!(f.check().is_err());
+171 -9
View File
@@ -84,6 +84,86 @@ pub enum BankCsvError {
Csv(String),
}
/// A bank's description cell that held a number reading as a tax id (a
/// nine-digit reference, say), kept masked to its last four digits.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MaskedCell {
/// The file's line the transaction is on (the first line is 1).
pub line: u64,
/// The column: always "Description".
pub column: &'static str,
/// How many numbers in the cell were masked.
pub numbers: usize,
}
/// A parsed bank CSV whose descriptions are safe to keep.
#[derive(Clone, Debug, PartialEq)]
pub struct MaskedBankImport {
/// The transactions in file order, a description that held a number
/// reading as a tax id masked to its last four digits.
pub transactions: Vec<BankTransaction>,
/// Which cells were masked, in file order.
pub masked: Vec<MaskedCell>,
/// Each transaction's description exactly as the bank wrote it, in the
/// same order as `transactions`: for matching a categorizing rule
/// against (a rule keyed on a reference of nine digits still matches),
/// never to be kept or shown.
pub as_written: Vec<String>,
}
/// [`parse_bank_csv_with`] for a file that is to be kept: a description a
/// bank wrote is not typed by a person and commonly carries a nine-digit
/// reference, so the file is not refused for one. A number in it that
/// reads as a tax id (`ledger_core::settings::holds_printed_tin`: nine
/// digits standing alone, an SSN's 3-2-4, an EIN's 2-7) is masked to its
/// last four digits (`•••-••-1234`) in the description, and the cell is
/// named in [`MaskedBankImport::masked`] (BS-partner-2; the owner's choice,
/// 2026-11-21).
///
/// ```text
/// GOAL: a bank file is journaled whole, and no full tax id is.
/// SOURCE: BS-partner-2; WB-partner-15 (the CHOICE: masking
/// on bank imports).
/// INVARIANTS:
/// 1. No kept description holds a number the detector finds.
/// 2. Every cell that was masked is named with its line; every other
/// cell is as the bank wrote it, and the transactions are
/// parse_bank_csv_with's, amounts and dates unchanged.
/// SCENARIOS:
/// 1. IF a description says `ACH 000-00-0000 payroll`: SHOULD keep
/// `ACH •••-••-0000 payroll` and name its line.
/// 2. IF it says `CHECK 1234567890`: SHOULD keep it as written.
/// ```
pub fn parse_bank_csv_masked(
text: &str,
order: Option<DateOrder>,
) -> Result<MaskedBankImport, BankCsvError> {
let mut masked = Vec::new();
let mut as_written = Vec::new();
let transactions = parse_rows(text, order)?
.into_iter()
.map(|(line, mut txn)| {
as_written.push(txn.description.clone());
let numbers = ledger_core::settings::count_printed_tins(&txn.description);
if numbers > 0 {
txn.description =
ledger_core::settings::mask_printed_tins(&txn.description).into_owned();
masked.push(MaskedCell {
line,
column: "Description",
numbers,
});
}
txn
})
.collect();
Ok(MaskedBankImport {
transactions,
masked,
as_written,
})
}
/// Parse a QBO bank CSV, reading slash dates in the order the file itself
/// settles. Returns transactions in file order.
pub fn parse_bank_csv(text: &str) -> Result<Vec<BankTransaction>, BankCsvError> {
@@ -96,11 +176,22 @@ pub fn parse_bank_csv_with(
text: &str,
order: Option<DateOrder>,
) -> Result<Vec<BankTransaction>, BankCsvError> {
Ok(parse_rows(text, order)?
.into_iter()
.map(|(_, txn)| txn)
.collect())
}
/// The transactions with the file line each came from.
fn parse_rows(
text: &str,
order: Option<DateOrder>,
) -> Result<Vec<(u64, BankTransaction)>, BankCsvError> {
let mut reader = csv::ReaderBuilder::new()
.has_headers(false)
.trim(csv::Trim::All)
.from_reader(text.as_bytes());
let mut rows: Vec<(String, String, Decimal)> = Vec::new();
let mut rows: Vec<(u64, String, String, Decimal)> = Vec::new();
let mut seen_row = false;
for (idx, record) in reader.records().enumerate() {
let record = record.map_err(|e| BankCsvError::Csv(e.to_string()))?;
@@ -134,16 +225,20 @@ pub fn parse_bank_csv_with(
if amount.is_zero() {
continue; // zero-amount rows carry no money
}
rows.push((fields[0].to_string(), fields[1].to_string(), amount));
let line = crate::line_of(text, &record, idx + 1);
rows.push((line, fields[0].to_string(), fields[1].to_string(), amount));
}
let order = date_order(rows.iter().map(|r| r.0.as_str()), order)?;
let order = date_order(rows.iter().map(|r| r.1.as_str()), order)?;
rows.into_iter()
.map(|(date, description, amount)| {
Ok(BankTransaction {
date: parse_date(&date, order)?,
description,
amount,
})
.map(|(line, date, description, amount)| {
Ok((
line,
BankTransaction {
date: parse_date(&date, order)?,
description,
amount,
},
))
})
.collect()
}
@@ -264,6 +359,73 @@ mod tests {
assert_eq!(txns[0].amount, Decimal::new(-123456, 2));
}
/// parse_bank_csv_masked SCENARIOS 1 and 2, INVARIANTS 1 and 2: a bank's
/// reference is masked to its last four and named by line; a long
/// reference stays; amounts and dates are unchanged.
#[test]
fn a_tax_id_shape_in_a_description_is_masked_and_named() {
let csv = "Date,Description,Amount\n\
2026-01-02,ACH 000-00-0000 payroll,-12.50\n\
2026-01-03,CHECK 1234567890,-3.25\n\
\n\
2026-01-04,\"WIRE 000000000, REF 00-0000000\",40.00\n";
let got = parse_bank_csv_masked(csv, None).unwrap();
let plain = parse_bank_csv_with(csv, None).unwrap();
assert_eq!(got.transactions.len(), 3);
assert_eq!(
got.transactions[0].description,
"ACH \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 payroll"
);
assert_eq!(got.transactions[1].description, "CHECK 1234567890");
assert_eq!(
got.transactions[2].description,
"WIRE \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000, REF \u{2022}\u{2022}-\u{2022}\u{2022}\u{2022}0000"
);
for (m, p) in got.transactions.iter().zip(&plain) {
assert_eq!((m.date, m.amount), (p.date, p.amount));
}
// The file's lines, the blank one counted: 2, and 5.
assert_eq!(
got.masked,
vec![
MaskedCell {
line: 2,
column: "Description",
numbers: 1
},
MaskedCell {
line: 5,
column: "Description",
numbers: 2
},
]
);
assert!(
got.transactions
.iter()
.all(|t| { !ledger_core::settings::holds_printed_tin(&t.description) })
);
// A file with none masks none.
let clean = parse_bank_csv_masked("2026-01-02,Rent,-1.00\n", None).unwrap();
assert!(clean.masked.is_empty());
assert_eq!(clean.as_written, ["Rent"]);
}
/// `as_written` is each description as the bank wrote it, in order,
/// for matching a rule against: a rule keyed on a nine-digit reference
/// still finds it, while the kept description is masked.
#[test]
fn the_bank_s_own_words_are_kept_for_matching_rules() {
let csv = "2026-01-02,ACH 000000000 payroll,-1.00\n2026-01-03,Rent,-2.00\n";
let got = parse_bank_csv_masked(csv, None).unwrap();
assert_eq!(got.as_written, ["ACH 000000000 payroll", "Rent"]);
assert_eq!(
got.transactions[0].description,
"ACH \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000 payroll"
);
assert_eq!(got.transactions.len(), got.as_written.len());
}
#[test]
fn bad_column_count_rejected() {
let csv = "a,b\n";
+87
View File
@@ -49,6 +49,10 @@ pub enum ChartCsvError {
/// "code" or "name".
field: &'static str,
},
/// A cell that looks like it holds a tax id: the words name the row
/// and column and never the number (BS-partner-2).
#[error("{0}")]
LooksLikeTin(String),
/// Malformed CSV.
#[error("csv error: {0}")]
Csv(String),
@@ -70,6 +74,10 @@ pub enum ChartCsvError {
/// (BadType), and a non-blank code and name (Blank, with its row).
/// 3. A blank parent or tax category is None; blank lines are skipped;
/// an empty file is no rows.
/// 4. A cell that looks like a tax id (a name with any run of nine
/// digits, any other cell with an SSN's or EIN's shape or nine
/// digits alone) refuses the file, naming its row (the file's line)
/// and column and never the number (LooksLikeTin; BS-partner-2).
/// ```
pub fn parse_chart_csv(text: &str) -> Result<Vec<ChartRow>, ChartCsvError> {
let mut reader = csv::ReaderBuilder::new()
@@ -109,6 +117,32 @@ pub fn parse_chart_csv(text: &str) -> Result<Vec<ChartRow>, ChartCsvError> {
});
}
}
// A chart is typed by a person, so a number that reads as a tax id
// in any cell is refused, naming the row and the column; the name
// is read as strictly as an account name is (any run of nine
// digits).
let line = crate::line_of(text, &record, idx + 1);
let columns = ["code", "name", "type", "parent_code", "tax_category"];
for (n, value) in fields.iter().enumerate() {
let looks = if n == 1 {
ledger_core::parties::has_full_tin(value)
} else if n == 0 || n == 3 {
// An account code (and its parent's) is a reference: a
// bare nine digits is a code, only the printed shapes
// read as a tax id (WB-partner-15).
ledger_core::settings::holds_printed_tin_in_reference(value)
} else {
ledger_core::settings::holds_printed_tin(value)
};
if looks {
return Err(ChartCsvError::LooksLikeTin(
ledger_core::settings::tin_refusal(&format!(
"the {} cell of row {line}",
columns[n]
)),
));
}
}
let account_type = fields[2].to_lowercase();
match account_type.as_str() {
"asset" | "liability" | "equity" | "revenue" | "expense" => {}
@@ -148,6 +182,30 @@ mod tests {
assert_eq!(rows[2].account_type, "revenue");
}
/// An account code is a reference: a bare nine digits is a code, a
/// printed SSN or EIN is refused, naming its row and column.
#[test]
fn a_code_may_be_nine_digits_but_not_a_printed_tax_id() {
let ok =
"code,name,type,parent_code\n123456789,Cash,asset,\n123456790,Bank,asset,123456789\n";
assert_eq!(parse_chart_csv(ok).unwrap().len(), 2);
for csv in [
"code,name,type,parent_code\n000-00-0000,Cash,asset,\n",
"code,name,type,parent_code\n1000,Cash,asset,\n1001,Bank,asset,00-0000000\n",
] {
assert!(
matches!(parse_chart_csv(csv), Err(ChartCsvError::LooksLikeTin(_))),
"{csv}"
);
}
// A name is a party-style field: any run of nine digits.
let name = "code,name,type,parent_code\n1000,Acct 123456789,asset,\n";
assert!(matches!(
parse_chart_csv(name),
Err(ChartCsvError::LooksLikeTin(_))
));
}
#[test]
fn parses_optional_tax_category_column() {
let csv = "code,name,type,parent_code,tax_category\n4000,Sales,revenue,,gross_receipts\n1000,Cash,asset,,\n";
@@ -171,6 +229,35 @@ mod tests {
));
}
/// INVARIANT 4: a cell that looks like a tax id refuses the file, naming
/// its row and column and never the number; a ten-digit code goes through
/// (a name is read strictly, as an account name is).
#[test]
fn a_tax_id_in_a_cell_is_refused_with_its_row_and_column() {
let header = "code,name,type,parent_code\n";
let why = |rows: &str| match parse_chart_csv(&format!("{header}{rows}")) {
Err(ChartCsvError::LooksLikeTin(why)) => why,
other => panic!("expected a refusal, got {other:?}"),
};
let w = why("1000,Cash,asset,\n1010,Payroll 000-00-0000,asset,1000\n");
assert!(
w.starts_with("the name cell of row 3 looks like it holds a tax id"),
"{w}"
);
assert!(w.contains("books.set_tin") && w.contains("W-9"), "{w}");
assert!(!w.contains("0000"), "never the number: {w}");
// A name is read strictly, as an account name is: any nine digits.
assert!(why("1000,Card 1234 56789,asset,\n").contains("name cell of row 2"));
// Another column is read by its shape.
assert!(why("000-00-0000,Cash,asset,\n").contains("code cell of row 2"));
assert!(why("1000,Cash,asset,00-0000000\n").contains("parent_code cell of row 2"));
// A blank line counts as a line of the file.
assert!(why("1000,Cash,asset,\n\n1010,Bad 000000000,asset,\n").contains("row 4"));
// What is no tax id goes through.
let ok = parse_chart_csv(&format!("{header}1234567890,Loan 2026,liability,\n"));
assert_eq!(ok.unwrap().len(), 1);
}
/// Found by fuzz_import_csv (2026-10-13): a row with a blank code or
/// name was accepted.
#[test]
+21 -1
View File
@@ -29,8 +29,28 @@ pub mod templates;
pub mod workpaper;
pub mod xlsx;
/// The line of `text` (the first is 1) a CSV record starts on, counted from
/// its byte offset: the csv reader reports a record's position from where
/// it began looking, before it skipped any blank lines, and a row is named
/// by the line a person sees it on.
pub(crate) fn line_of(text: &str, record: &csv::StringRecord, fallback: usize) -> u64 {
record.position().map_or(fallback as u64, |p| {
let bytes = text.as_bytes();
let mut at = usize::try_from(p.byte())
.unwrap_or(usize::MAX)
.min(bytes.len());
while bytes.get(at).is_some_and(|b| matches!(b, b'\n' | b'\r')) {
at += 1;
}
bytes[..at].iter().filter(|b| **b == b'\n').count() as u64 + 1
})
}
pub use asset_register::{asset_register_pdf, asset_register_xlsx};
pub use bank_csv::{BankCsvError, BankTransaction, DateOrder, parse_bank_csv, parse_bank_csv_with};
pub use bank_csv::{
BankCsvError, BankTransaction, DateOrder, MaskedBankImport, MaskedCell, parse_bank_csv,
parse_bank_csv_masked, parse_bank_csv_with,
};
pub use chart_csv::{ChartRow, parse_chart_csv};
pub use extract::{ExtractError, page_count, page_png, pdf_lines, pdf_text, text_of, xlsx_text};
pub use format::round_display;
@@ -8,7 +8,7 @@ The receipt rule in force: {evidence_rule}
- books.audit { through, scope } without confirmed lists the checks and changes nothing; show it to the human. Then call it again with confirmed: true and the preview. It files the workpaper (JSON and PDF, category workpaper) and journals the run. books.workpaper { id } gives it back: the JSON, and the PDF handed over (run its download command to save it).
- scope: month (a month-end), annual (a fiscal year), cpa_handoff (the year, for the CPA package), full (everything from the start of the books).
- It checks the trial balance, the accounting equation, the profit and loss against equity, the cash flow's footing, the A/R and A/P control accounts, closes, schedules and depreciation, the asset register, every posted entry against the receipt rule, open drafts, tax categories, 1099 decisions and the settings; then the journal's chain, the stored files, the access log and the backups. A finding is a failure (the books are wrong or cannot be shown right), a warning (unfinished or a rule not met) or a note (listed so the workpaper is whole: a reversal rests on its original's receipt).
- It checks the trial balance, the accounting equation, the profit and loss against equity, the cash flow's footing, the A/R and A/P control accounts, closes, schedules and depreciation, the asset register, every posted entry against the receipt rule, open drafts, tax categories, 1099 decisions and the settings; then the journal's chain, the stored files, the access log, a journal line whose text field looks like a tax id (a warning naming the line and the field, never the number; the journal is never rewritten, so correct it with a reversal and keep the tax id in the vault) and the backups. A finding is a failure (the books are wrong or cannot be shown right), a warning (unfinished or a rule not met) or a note (listed so the workpaper is whole: a reversal rests on its original's receipt).
- Fix findings with journaled corrections (a reversal, a receipt attached, a decision recorded), never by editing: posted entries stay as they are. Then audit again.
- The same books, day and scope give the run that exists: asking again files nothing. The books are "the same" while no entry, document, close, settings or role change has been made; filing a receipt, an audit or an attestation does not change them.
- Books that have not declared audits refuse a confirmed audit and every attestation with format_upgrade_pending until the owner's upgrade (books.start says so). Nothing else about them changes.
+1 -1
View File
@@ -8,7 +8,7 @@
## Importing a bank CSV (books.import_bank_csv)
A QuickBooks-style bank or credit-card CSV: 3 columns Date, Description, Amount (payments negative), or 4 columns Date, Description, money out, money in (Intuit heads them Credit, Debit). Slash dates must settle month-first or day-first from the file itself or from date_order ("month_first" for mm/dd, "day_first" for dd/mm); ask the human when the tool says the dates read either way. It creates one DRAFT entry per transaction, all or none: the bank account on one side, a categorized offset on the other (the longest matching rule pattern, else default_offset_code). Give the CSV as upload_id: upload it with books.begin_upload purpose import and `wanderbooks upload` (a file never passes through you). Review with books.digest, then post. File the export too (books.file_document category import_source) and pass source_attachment_id: it is linked to the bank account, so the import traces to its source (never to the drafts: a bank export is not a receipt).
A QuickBooks-style bank or credit-card CSV: 3 columns Date, Description, Amount (payments negative), or 4 columns Date, Description, money out, money in (Intuit heads them Credit, Debit). Slash dates must settle month-first or day-first from the file itself or from date_order ("month_first" for mm/dd, "day_first" for dd/mm); ask the human when the tool says the dates read either way. It creates one DRAFT entry per transaction, all or none: the bank account on one side, a categorized offset on the other (the longest matching rule pattern, else default_offset_code). Give the CSV as upload_id: upload it with books.begin_upload purpose import and `wanderbooks upload` (a file never passes through you). Review with books.digest, then post. File the export too (books.file_document category import_source) and pass source_attachment_id: it is linked to the bank account, so the import traces to its source (never to the drafts: a bank export is not a receipt). A bank's description often carries a nine-digit reference, so the file is not refused for one: a number in it that reads as a tax id is kept masked to its last four digits, and the answer says how many values were masked and on which lines (masked_count, masked, masked_note); tell the human, who can check the bank's own statement. A chart CSV (books.import_chart_csv) is refused whole if a cell looks like a tax id; the refusal names its row and column.
## Exporting a report (books.export)
@@ -11,7 +11,7 @@
- Every post_entry preview says where the entry stands (party_policy, party_missing, party_suggestions): under the `[books] parties` setting "suggest" (the default), when party_missing, name the likely party to the human and tag it (or add it) before confirming; under "require", posting is refused (party_required) until the entry names a party or is marked as having none (books.set_entry_party with party null and no_party_reason, or draft_entry no_party_reason: only for an entry with truly no counterparty, like a transfer between the company's own accounts); under "off", don't raise it.
- Record W-9 facts (books.set_w9) for contractors and landlords before paying them, and W-4 facts (books.set_w4) for employees before their first payroll; name the employee party on every books.run_payroll line.
- Never put a full TIN or SSN anywhere in the books, only the last four digits: the engine refuses any nine-digit number in a party field. The full TIN goes only to the encrypted TIN vault, and every member's and every 1099 payee's belongs there: books.set_tin (party, tin, tin_type: ssn, ein, itin; any role, so each member's SSN for their K-1) and books.set_w9 with tin and tin_type for a payee's W-9, and the signed form with w9_upload_id (books.begin_upload purpose w9; never books.file_document or books.attach_receipt: the form shows the TIN).
- A full TIN lives in the vault: keep it out of descriptions, notes, file names and version-history messages. books.get_w9 hands the signed form over (run its download command to save it for the human); books.purge_tin (preview, then confirmed, with a reason) deletes a TIN no longer needed.
- A full TIN lives in the vault: keep it out of descriptions, notes, file names and version-history messages. Every tool refuses a string that looks like a tax id (nine digits standing alone, or an SSN's 3-2-4 or an EIN's 2-7 grouping), whichever field it is in, before anything is written, and says which field; a party's own fields refuse any run of nine digits. A field that is an identifier by nature (an asset's tag or serial number, a vendor's or customer's reference, a payment's reference, an account code, a file name, an instrument's label, where a W-9 is kept) takes nine digits as a number and refuses only the grouped forms. An invoice number, a phone number, a coordinate or a reference of ten digits or more is no tax id. If a bank or vendor reference is nine digits and goes into a memo or a description, write its last four. books.get_w9 hands the signed form over (run its download command to save it for the human); books.purge_tin (preview, then confirmed, with a reason) deletes a TIN no longer needed.
- books.parties lists the directory (each party's TIN last four from its TIN or W-9 facts), books.party shows one party with the year's totals, and books.show party opens it in the viewer. Archive (books.update_party archived) parties no longer dealt with; never delete history.
## Tagging an entry with several parties (books.set_entry_party)
+3
View File
@@ -133,6 +133,9 @@ pub(crate) const STOPPED: &str = "stopped";
pub(crate) const STOPPED_BY_CLOSE: &str = "stopped_by_close";
/// A file's bytes or text came as an argument (D-46).
pub(crate) const INLINE_FILE: &str = "inline_file";
/// A call refused unrun because a string in it looks like a tax id
/// (text_fields.rs).
pub(crate) const TIN_IN_TEXT: &str = "tin_in_text";
/// What a refused call is told when its record couldn't be kept, or a
/// call that ran is told instead of its answer (INVARIANT 3).
+11
View File
@@ -1588,6 +1588,8 @@ mod next_steps;
mod projects;
#[path = "tools/prompts.rs"]
mod prompts;
#[path = "text_fields.rs"]
mod text_fields;
pub use kept::SettingKeyOut;
// The tool groups: one file each (plan/served.md 8.2 U0a). A unit adds a
@@ -1934,6 +1936,15 @@ impl ServerHandler for BooksServer {
}
calls::key_problem(request_key.as_ref())
.map(|why| (calls::MISSING_KEY, Ok(tool_error(why))))
})
// A string that looks like a tax id isn't run, whatever it was for:
// the vault is where one goes (text_fields.rs INVARIANT 5).
.or_else(|| {
if !calls::writes(&request.name) {
return None;
}
text_fields::refusal(&request.name, request.arguments.as_ref())
.map(|why| (access::TIN_IN_TEXT, Ok(tool_error(why))))
});
if let Some((code, answer)) = refusal {
call.digested(refused_digest(request.arguments.clone()).await);
+56
View File
@@ -1702,3 +1702,59 @@ fn the_envelope_keeps_what_a_tool_said_and_carries_a_refusal_guard() {
assert_eq!(g["code"], "approval_required");
assert_eq!(g["remedy_tool"], "books.approve_entry");
}
/// text_fields.rs INVARIANT 5 (WB-format-10): a call with a string that
/// looks like a tax id is refused before it runs, in words that name the
/// field and never repeat the number; the books are as they were and the
/// access record says why. A reference that is no tax id goes on to the tool.
#[test]
fn a_call_with_a_tax_id_in_free_text_is_refused_unrun_and_writes_nothing() {
rt().block_on(async {
let s = session("tin-text").await;
let (server, books) = logged("tin-text");
let key = "key-0123456789";
let add = |name: &str| {
tool_call(
"books.add_class",
serde_json::json!({"name": name, "request_key": key}),
)
};
let (refusal, text) = answer(
server
.call_tool(add("Rondo 000-00-0000"), context(&s.peer, Some(ALL)))
.await,
)
.unwrap();
assert!(refusal, "{text}");
assert!(
text.starts_with("the name of books.add_class looks like it holds a tax id"),
"{text}"
);
assert!(text.contains("books.set_tin") && text.contains("W-9"), "{text}");
assert!(!text.contains("000"), "never the number: {text}");
// A preview is refused too: its text would be shown to a person.
let draft = tool_call(
"books.draft_entry",
serde_json::json!({"date": "2026-11-21", "description": "pay 00-0000000", "request_key": key}),
);
let (refusal, text) =
answer(server.call_tool(draft, context(&s.peer, Some(ALL))).await).unwrap();
assert!(refusal && text.contains("the description of books.draft_entry"), "{text}");
// Nothing was made: no class, no entry.
let projects = tool_call("books.projects", serde_json::json!({}));
let (refusal, text) =
answer(server.call_tool(projects, context(&s.peer, Some(ALL))).await).unwrap();
assert!(!refusal && !text.contains("Rondo"), "{text}");
// A reference that is no tax id is not refused for being one.
let (_, text) = answer(
server
.call_tool(add("Rondo 2026-11-0042"), context(&s.peer, Some(ALL)))
.await,
)
.unwrap();
assert!(!text.contains("looks like it holds a tax id"), "{text}");
let log = records(&books);
assert_eq!(log[0], ("books.add_class".into(), refused("tin_in_text"), true));
assert_eq!(log[1], ("books.draft_entry".into(), refused("tin_in_text"), true));
});
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -371,7 +371,7 @@ impl BooksServer {
#[tool(
name = "books.import_chart_csv",
title = "Import a chart of accounts",
description = "Import a chart of accounts from CSV (header: code,name,type,parent_code,tax_category; the last is optional), as upload_id: upload it with books.begin_upload purpose import and `wanderbooks upload` (a file never passes through you). Types: asset, liability, equity, revenue, expense. Parents must come before children. Fails on the first bad row; nothing is half-imported. A revenue or expense row without a tax_category is listed in warnings, or, under policy.require_tax_category = refuse, refuses the file.",
description = "Import a chart of accounts from CSV (header: code,name,type,parent_code,tax_category; the last is optional), as upload_id: upload it with books.begin_upload purpose import and `wanderbooks upload` (a file never passes through you). Types: asset, liability, equity, revenue, expense. Parents must come before children. Fails on the first bad row, a cell that looks like a tax id included (it names the row and column); nothing is half-imported. A revenue or expense row without a tax_category is listed in warnings, or, under policy.require_tax_category = refuse, refuses the file.",
annotations(
read_only_hint = false,
destructive_hint = false,
+4 -4
View File
@@ -474,10 +474,10 @@ impl BooksServer {
"due_date, or terms, or the customer's default terms, or invoicing.default_terms",
)?;
if let Some(r) = &p.customer_ref {
ledger_core::parties::check_text("the customer reference", r)?;
ledger_core::parties::check_reference_note("the customer reference", r)?;
}
if let Some(m) = &p.memo {
ledger_core::parties::check_text("the memo", m)?;
ledger_core::parties::check_note("the memo", m)?;
}
let settings = self.settings();
let fields = arap::InvoiceFields {
@@ -616,10 +616,10 @@ impl BooksServer {
);
}
if let Some(m) = &p.memo {
ledger_core::parties::check_text("the memo", m)?;
ledger_core::parties::check_note("the memo", m)?;
}
if let Some(r) = &p.duplicate_reason {
ledger_core::parties::check_text("the duplicate reason", r)?;
ledger_core::parties::check_note("the duplicate reason", r)?;
}
// The file is taken before anything is written: an upload is used
// up only by the call that files it (files.rs INVARIANT 1).
+38 -6
View File
@@ -709,7 +709,7 @@ impl BooksServer {
#[tool(
name = "books.import_bank_csv",
title = "Import a bank CSV as drafts",
description = "Import a bank or card CSV (Date, Description, Amount; or Date, Description, money out, money in) as one DRAFT entry per transaction, all or none: the bank account on one side, a categorized offset on the other. Give the CSV as upload_id (books.begin_upload purpose import; a file never passes through you). Ambiguous slash dates need date_order. Review with books.digest, then post. Also file the export (books.file_document category import_source) and pass source_attachment_id. Details in books.handbook section files-in-out.",
description = "Import a bank or card CSV (Date, Description, Amount; or Date, Description, money out, money in) as one DRAFT entry per transaction, all or none: the bank account on one side, a categorized offset on the other. Give the CSV as upload_id (books.begin_upload purpose import; a file never passes through you). Ambiguous slash dates need date_order. A description holding a number that reads as a tax id is kept masked to its last four digits (masked_count, masked). Review with books.digest, then post. Also file the export (books.file_document category import_source) and pass source_attachment_id. Details in books.handbook section files-in-out.",
annotations(
read_only_hint = false,
destructive_hint = false,
@@ -732,7 +732,14 @@ impl BooksServer {
}
};
let (csv, claim) = self.csv_given(&p.upload_id)?;
let txns = ledger_import::parse_bank_csv_with(&csv, order).map_err(|e| e.to_string())?;
// A description a bank wrote is not typed by a person: a number in
// it that reads as a tax id is kept masked to its last four digits
// and named in the answer, never a reason to refuse the file.
let ledger_import::MaskedBankImport {
transactions: txns,
masked,
as_written,
} = ledger_import::parse_bank_csv_masked(&csv, order).map_err(|e| e.to_string())?;
let mut store = self.lock()?;
let bank = store
.ledger()
@@ -788,8 +795,10 @@ impl BooksServer {
// can't become a draft (a date in a closed period, say) refuses the
// file instead of leaving the ones before it behind.
let mut scratch = store.ledger().clone();
for txn in &txns {
let (offset_id, _) = offset_for(&txn.description);
for (txn, written) in txns.iter().zip(&as_written) {
// A rule reads the bank's own words, a nine-digit reference
// in them included; what is kept is the masked text.
let (offset_id, _) = offset_for(written);
let amount = Money::new(txn.amount.abs(), base);
let (bank_side, offset_side) = if txn.amount > Decimal::ZERO {
(Side::Debit, Side::Credit)
@@ -806,8 +815,8 @@ impl BooksServer {
// Rehearsed whole: the upload is used up as the writing begins.
files::filed(claim);
let mut imported = Vec::new();
for txn in txns {
let (offset_id, offset_code) = offset_for(&txn.description);
for (txn, written) in txns.into_iter().zip(&as_written) {
let (offset_id, offset_code) = offset_for(written);
let amount = Money::new(txn.amount.abs(), store.ledger().base_currency());
let entry_id = store
.create_entry(txn.date, &format!("Bank import — {}", txn.description))
@@ -838,11 +847,34 @@ impl BooksServer {
.map_err(|e| e.to_string())?;
}
let count = imported.len();
let masked_count: usize = masked
.iter()
.fold(0, |n: usize, m| n.saturating_add(m.numbers));
let masked_note = (masked_count > 0).then(|| {
let lines: Vec<String> = masked.iter().map(|m| m.line.to_string()).collect();
format!(
"{masked_count} value{} in the Description column read as a tax id (nine digits standing alone, or an SSN's or an EIN's shape) and {} kept masked to the last four digits, on line{} {}. A bank's description is not typed by a person and often carries a nine-digit reference, so the file was not refused; a tax id is stored only with books.set_tin or a W-9 (books.set_w9)",
if masked_count == 1 { "" } else { "s" },
if masked_count == 1 { "was" } else { "were" },
if lines.len() == 1 { "" } else { "s" },
lines.join(", ")
)
});
Ok(Json(ImportBankCsvOut {
imported,
count,
source_attachment_id: p.source_attachment_id,
source_linked: link_source,
masked_count,
masked: masked
.into_iter()
.map(|m| MaskedCellOut {
row: m.line,
column: m.column.to_string(),
numbers: m.numbers,
})
.collect(),
masked_note,
}))
}
}
+1 -1
View File
@@ -1550,7 +1550,7 @@ impl BooksServer {
if r.trim().is_empty() {
return Err("say why the entry has no counterparty".into());
}
ledger_core::parties::check_text("reason", r)?;
ledger_core::parties::check_note("the reason", r)?;
store
.set_entry_party(p.entry_id, None)
.map_err(|e| e.to_string())?;
+23
View File
@@ -1368,6 +1368,29 @@ pub struct ImportBankCsvOut {
/// True when this call linked it to the account (false when it already
/// was, or none was given).
pub source_linked: bool,
/// How many descriptions held a number that reads as a tax id (nine
/// digits standing alone, an SSN's or an EIN's shape) and were kept
/// masked to its last four digits: a bank's description is not typed by
/// a person and often carries a nine-digit reference, so the file is
/// not refused for one (BS-partner-2).
pub masked_count: usize,
/// Which descriptions were masked, by the file's line.
pub masked: Vec<MaskedCellOut>,
/// What masking did, in words; present when `masked_count` is above
/// zero.
#[serde(skip_serializing_if = "Option::is_none")]
pub masked_note: Option<String>,
}
/// One description of a bank file that was kept masked.
#[derive(Debug, Serialize, JsonSchema)]
pub struct MaskedCellOut {
/// The file's line (the first line is 1).
pub row: u64,
/// The column: "Description".
pub column: String,
/// How many numbers in the cell were masked.
pub numbers: usize,
}
/// Parameters for `books.import_chart_csv`. No other argument is taken: a
+145
View File
@@ -119,6 +119,11 @@ pub const CODES: &[ledger_core::audit::CodeRow] = &[
severity: Severity::Warning,
predicate: "two filed attachments, neither withdrawn, hold the same bytes",
},
ledger_core::audit::CodeRow {
code: "tax_id_in_journal",
severity: Severity::Warning,
predicate: "a journal line's text field holds a number that looks like a tax id (nine digits standing alone, an SSN's 3-2-4 or an EIN's 2-7)",
},
ledger_core::audit::CodeRow {
code: "backup_stale",
severity: Severity::Warning,
@@ -144,6 +149,84 @@ fn found(code: &'static str, subject: Subject, message: String) -> Finding {
}
}
/// How the audit reads one journal field for a tax id.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum TextClass {
/// Free words: nine digits standing alone, an SSN's 3-2-4 or an EIN's
/// 2-7 are found.
Free,
/// A reference (a tag, a serial, an invoice number, a file name, an
/// account code): only the grouped shapes are found, a bare nine digits
/// being a legitimate number there (WB-partner-15).
Reference,
}
/// The journal fields that hold words someone wrote (never an id, a digest
/// or an amount) and how each is read: what [`Store::integrity_findings`]
/// reads for a tax id.
const TEXT_KEYS: &[(&str, TextClass)] = &[
("description", TextClass::Free),
("memo", TextClass::Free),
("note", TextClass::Free),
("notes", TextClass::Free),
("reason", TextClass::Free),
("name", TextClass::Free),
("label", TextClass::Reference),
("title", TextClass::Free),
("citation", TextClass::Free),
("decided_by", TextClass::Free),
("detail", TextClass::Free),
("detail_md", TextClass::Free),
("resolution", TextClass::Free),
("decision_md", TextClass::Free),
("body_md", TextClass::Free),
("subject", TextClass::Free),
("reference", TextClass::Reference),
("customer_ref", TextClass::Reference),
("vendor_ref", TextClass::Reference),
("duplicate_reason", TextClass::Free),
("no_party_reason", TextClass::Free),
("payee", TextClass::Free),
("source", TextClass::Free),
("reimbursable_to", TextClass::Free),
("file_name", TextClass::Reference),
("serial", TextClass::Reference),
("tag", TextClass::Reference),
("code", TextClass::Reference),
("employee_name", TextClass::Free),
("display_name", TextClass::Free),
("address", TextClass::Free),
("contact", TextClass::Free),
("kept_at", TextClass::Reference),
("approver", TextClass::Free),
];
/// Every text field of `v` named by [`TEXT_KEYS`], as (its key, how it is
/// read, its text), at any depth; a list of texts under such a key counts
/// each.
fn text_fields_in(v: &Value, out: &mut Vec<(String, TextClass, String)>) {
match v {
Value::Object(m) => {
for (k, x) in m {
if let Some((_, class)) = TEXT_KEYS.iter().find(|(key, _)| *key == k.as_str()) {
match x {
Value::String(s) => out.push((k.clone(), *class, s.clone())),
Value::Array(a) => out.extend(
a.iter()
.filter_map(Value::as_str)
.map(|s| (k.clone(), *class, s.to_string())),
),
_ => {}
}
}
text_fields_in(x, out);
}
}
Value::Array(a) => a.iter().for_each(|x| text_fields_in(x, out)),
_ => {}
}
}
/// What the backups' standing says, one target at a time, for the audit
/// (the server reads the standing; the store does not know the backups).
#[derive(Clone, Debug)]
@@ -304,6 +387,20 @@ pub struct Claim {
}
impl Claim {
/// The words a claim keeps (the note, the model's name) hold no tax id
/// (BS-partner-2): checked before anything is journaled.
fn check(&self) -> Result<(), StoreError> {
for (field, text) in [
("the note", self.note.as_deref()),
("the model", self.method.model.as_deref()),
] {
if let Some(t) = text {
ledger_core::LedgerError::free_text(field, t)?;
}
}
Ok(())
}
fn into_attestation(self, what: Attested) -> Attestation {
Attestation {
seq: 0,
@@ -436,6 +533,51 @@ impl Store {
format!("attachments {ids} hold the same bytes ({sha})"),
));
}
out.extend(self.tax_id_findings());
out
}
/// The journal lines whose text fields hold what looks like a tax id
/// (BS-partner-2): a line an earlier version took, or one a caller
/// other than the tools wrote. The books open and replay as they are
/// and the journal is never rewritten; the audit says where each one
/// is, by line and field, and never what the number is.
fn tax_id_findings(&self) -> Vec<Finding> {
let rows: Vec<(u64, String, String)> = self
.conn
.prepare("SELECT seq, type, payload FROM events ORDER BY seq")
.and_then(|mut s| {
s.query_map([], |r| {
Ok((r.get::<_, i64>(0)? as u64, r.get(1)?, r.get(2)?))
})?
.collect::<Result<Vec<_>, _>>()
})
.unwrap_or_default();
let mut out = Vec::new();
for (seq, kind, payload) in rows {
let Ok(v) = serde_json::from_str::<Value>(&payload) else {
continue;
};
let mut fields = Vec::new();
text_fields_in(&v, &mut fields);
for (field, class, text) in fields {
let looks = match class {
TextClass::Free => ledger_core::settings::holds_printed_tin(&text),
TextClass::Reference => {
ledger_core::settings::holds_printed_tin_in_reference(&text)
}
};
if looks {
out.push(found(
"tax_id_in_journal",
Subject::Named(format!("journal line {seq}")),
format!(
"journal line {seq} ({kind}) holds, in its `{field}`, a number that looks like a tax id. The journal is never rewritten and the books open as they are: correct what it describes going forward (reverse the entry and enter it again without the number), and keep the tax id only in the vault (books.set_tin or a W-9, books.set_w9)"
),
));
}
}
}
out
}
@@ -624,6 +766,7 @@ impl Store {
date: NaiveDate,
claim: Claim,
) -> Result<Attestation, StoreError> {
claim.check()?;
self.ensure_feature(crate::format::AUDITS)?;
let entry = self
.ledger
@@ -668,6 +811,7 @@ impl Store {
/// Record that an entry was reviewed whole (`entry.reviewed`).
pub fn review_entry(&mut self, entry_id: u64, claim: Claim) -> Result<Attestation, StoreError> {
claim.check()?;
self.ensure_feature(crate::format::AUDITS)?;
let entry = self
.ledger
@@ -710,6 +854,7 @@ impl Store {
period_id: u64,
claim: Claim,
) -> Result<(Attestation, AuditRun), StoreError> {
claim.check()?;
self.ensure_feature(crate::format::AUDITS)?;
let run = self.run_for_period(period_id)?;
let a = self.journal_attestation(
+60 -10
View File
@@ -1350,16 +1350,19 @@ impl Store {
) -> Result<EntryId, StoreError> {
let (default_description, lines) =
self.ledger.template_lines(template_id, amount, slots)?;
let description = description
.map(str::to_string)
.or(default_description)
.unwrap_or_else(|| {
// The caller's words are checked as they come; a description the
// template or its convention's title gives is stored text, masked
// where an older version let it hold a tax id's shape.
let description = description.map(str::to_string).unwrap_or_else(|| {
let stored = default_description.unwrap_or_else(|| {
self.ledger
.conventions()
.convention(template_id)
.map(|c| c.title.clone())
.unwrap_or_default()
});
ledger_core::settings::mask_printed_tins(&stored).into_owned()
});
self.rehearse(|l| {
let e = l.try_create_entry(date, &description)?;
for (account, side, amount) in &lines {
@@ -1801,6 +1804,7 @@ impl Store {
// Every refusal before the journal: a journaled reversal the engine
// then refuses could never be replayed, and the books would not open.
self.check_reverse_entry(entry, date)?;
LedgerError::free_text("the reversal's description", description)?;
let new_id = self.ledger.next_entry_id();
let flipped: Vec<Value> = orig.lines().iter().map(flip_line_json).collect();
// Reversals journal a single entry.reversed line (no separate
@@ -2458,7 +2462,13 @@ impl Store {
});
}
let amount = due.amount;
let description = format!("Depreciation — {} — {period}", asset.description);
// Composed from the asset's own words, which the books may hold
// from before free text was read for a tax id's shape: a number
// that reads as one is masked, never refused (WB-partner-15).
let description = format!(
"Depreciation — {} — {period}",
ledger_core::settings::mask_printed_tins(&asset.description)
);
let money = Money::new(amount, self.base_currency);
// Every refusal before the first journaled line: the entry on a
// copy (and that it is the period's run, no more and no less:
@@ -2884,7 +2894,8 @@ impl Store {
(
format!(
"Depreciation — {} — {} (final)",
asset.description, preview.period
ledger_core::settings::mask_printed_tins(&asset.description),
preview.period
),
vec![
(
@@ -2901,7 +2912,11 @@ impl Store {
)
});
let disposal = (
format!("Disposal — {} — {}", asset.description, date),
format!(
"Disposal — {} — {}",
ledger_core::settings::mask_printed_tins(&asset.description),
date
),
Self::disposal_lines(
&asset,
&preview,
@@ -3585,8 +3600,14 @@ impl Store {
entry_id,
"invoice entry diverged from journal"
);
// The copy's name is composed from the invoice's number (a prefix
// the books' settings give, then digits): a number that reads as a
// tax id's printed shape is masked, never refused (WB-partner-15).
let file_name = match &fields.number {
Some(n) => format!("{n}.pdf"),
Some(n) => format!(
"{}.pdf",
ledger_core::settings::mask_printed_tins_in_reference(n)
),
None => format!("Invoice {live}.pdf"),
};
// The entry's and the invoice's lines apply first: they were
@@ -4172,6 +4193,20 @@ impl Store {
));
}
}
// The file's words, as `Self::attach_receipt` reads them, before
// the write-off's entry is journaled (a refusal after it would
// leave the entry without its evidence).
if let WriteOffEvidence::File {
file_name,
description,
..
} = evidence
{
LedgerError::reference_text("the file name", file_name)?;
if let Some(d) = description {
LedgerError::free_text("the description", d)?;
}
}
if let WriteOffEvidence::File { bytes, .. } = evidence
&& let Some(existing) = self.live_attachment_with_sha(&sha256_hex(bytes))?
{
@@ -4754,6 +4789,10 @@ impl Store {
bytes: &[u8],
description: Option<&str>,
) -> Result<(u64, String, bool), StoreError> {
LedgerError::reference_text("the file name", file_name)?;
if let Some(d) = description {
LedgerError::free_text("the description", d)?;
}
self.attach(AttachRequest {
line_type: "receipt.attached",
category: "receipts",
@@ -4794,6 +4833,10 @@ impl Store {
bytes: &[u8],
description: Option<&str>,
) -> Result<(u64, String, bool), StoreError> {
LedgerError::reference_text("the file name", file_name)?;
if let Some(d) = description {
LedgerError::free_text("the description", d)?;
}
self.attach(AttachRequest {
line_type: "document.filed",
category,
@@ -5691,6 +5734,7 @@ impl Store {
if reason.is_empty() {
return Err(StoreError::ReasonRequired);
}
LedgerError::free_text("the reason", reason)?;
let (entry_id, withdrawn) = self.attachment_state(attachment_id)?;
if withdrawn {
return Err(StoreError::AttachmentWithdrawn(attachment_id));
@@ -5759,6 +5803,7 @@ impl Store {
if reason.is_empty() {
return Err(StoreError::ReasonRequired);
}
LedgerError::free_text("the reason", reason)?;
self.check_linkable(attachment_id)?;
if let Some(sub) = self.attachment_links(attachment_id)?.first() {
return Err(StoreError::AlreadyLinked(attachment_id, sub.describe()));
@@ -5935,6 +5980,7 @@ impl Store {
if reason.is_empty() {
return Err(StoreError::ReasonRequired);
}
LedgerError::free_text("the reason", reason)?;
self.attachment_state(attachment_id)?;
let linked = self
.conn
@@ -6064,6 +6110,7 @@ impl Store {
if reason.is_empty() {
return Err(StoreError::ReasonRequired);
}
LedgerError::free_text("the reason", reason)?;
if self.statement(attachment_id)?.is_none() {
return Err(StoreError::InvalidStatement(format!(
"attachment {attachment_id} records no statement"
@@ -6214,6 +6261,7 @@ impl Store {
if reason.is_empty() {
return Err(StoreError::ReasonRequired);
}
LedgerError::free_text("the reason", reason)?;
let r = self
.reconciliations(None)?
.into_iter()
@@ -6813,9 +6861,11 @@ impl Store {
.conn
.prepare("SELECT asset_id, tag FROM asset_tags_log ORDER BY seq")?;
let tags = tstmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?;
// History is read, not asked for: a tag or a serial number the books
// hold reads back whatever shape it has (BS-entry-4; WB-partner-15).
for t in tags {
let (id, tag) = t?;
ledger.set_asset_tag(id as u64, &tag)?;
ledger_core::parties::replaying(|| ledger.set_asset_tag(id as u64, &tag))?;
}
let mut sstmt = self
.conn
@@ -6823,7 +6873,7 @@ impl Store {
let serials = sstmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?;
for row in serials {
let (id, serial) = row?;
ledger.set_asset_serial(id as u64, Some(&serial))?;
ledger_core::parties::replaying(|| ledger.set_asset_serial(id as u64, Some(&serial)))?;
}
// Basis records: a pre-P3 one (no value at contribution) as its
// event replays, a newer one with its facts.
+108
View File
@@ -301,6 +301,77 @@ fn stale_head_period_attestation_refused() {
s.verify().unwrap();
}
/// BS-partner-2 (WB-partner-15): the store's own texts (a file's name and
/// description, the reasons for unlinking, withdrawing and voiding, an
/// attestation's note, an entry's description) meet the one free-text check
/// before anything is journaled, whoever calls.
#[test]
fn the_store_refuses_text_that_looks_like_a_tax_id_and_journals_nothing() {
use ledger_core::LedgerError;
let dir = test_dir("tin-text");
let (mut s, fx) = books(&dir, None);
let tin = "000-00-0000";
let refused = |r: Result<(), StoreError>, what: &str| match r {
Err(StoreError::Ledger(LedgerError::FreeTextHoldsTin(why))) => {
assert!(!why.contains("0000"), "{what}: never the number: {why}");
}
other => panic!("{what}: expected a refusal for the tax id, got {other:?}"),
};
let (att, _, _) = s
.attach_receipt(Some(fx.entry), "r.txt", "text/plain", b"paper 40.00", None)
.unwrap();
let head = s.head();
refused(
s.attach_receipt(
None,
"s.txt",
"text/plain",
b"other",
Some(&format!("paid {tin}")),
)
.map(drop),
"a description",
);
refused(
s.attach_receipt(None, &format!("w9 {tin}.txt"), "text/plain", b"other", None)
.map(drop),
"a file name",
);
refused(
s.file_document(
"tax",
"t.txt",
"text/plain",
b"doc",
Some(&format!("ein {tin}")),
)
.map(drop),
"a document's description",
);
refused(
s.unlink_receipt(att, &format!("dup {tin}")).map(drop),
"an unlink reason",
);
refused(
s.withdraw_attachment(att, &format!("dup {tin}")),
"a withdraw reason",
);
refused(
s.create_entry(d(2, 1), &format!("x {tin}")).map(drop),
"an entry description",
);
refused(
s.reverse_entry(fx.entry, d(2, 1), &format!("x {tin}"))
.map(drop),
"a reversal",
);
let mut c = claim("high");
c.note = Some(format!("see {tin}"));
refused(s.review_entry(fx.entry, c).map(drop), "an attestation note");
assert_eq!(s.head(), head, "a refusal journals nothing");
s.verify().unwrap();
}
/// The integrity table: each code seeded alone.
#[test]
fn integrity_detects_each_seeded_defect() {
@@ -362,6 +433,43 @@ fn integrity_detects_each_seeded_defect() {
drop(w);
Store::open(&dir).unwrap().integrity_findings()
}
"tax_id_in_journal" => {
// A line an earlier version took: its description holds an
// SSN's shape. The books open on it all the same, and the
// audit says where it is, never what.
let next = s.ledger().next_entry_id();
drop(s);
let mut w = JournalWriter::open(&dir.join(JOURNAL_FILE)).unwrap();
w.append(
"entry.created",
json!({"id": next, "date": "2026-03-01", "description": "paid 000-00-0000 in cash"}),
)
.unwrap();
drop(w);
let s = Store::open(&dir).expect("books holding such a line still open");
s.verify().expect("and still verify");
let found = s.integrity_findings();
let f = found
.iter()
.find(|f| f.code == "tax_id_in_journal")
.expect("found");
assert!(f.message.contains("`description`"), "{}", f.message);
assert!(
f.message.contains(&format!(
"journal line {}",
f.subject.describe().rsplit(' ').next().unwrap()
)),
"{}",
f.message
);
assert!(
!f.message.contains("0000"),
"never the number: {}",
f.message
);
assert!(f.message.contains("books.set_tin"), "{}", f.message);
found
}
"access_log_damaged" => {
std::fs::write(
dir.join("access.jsonl"),
@@ -0,0 +1,288 @@
//! Text the books already hold is never refused when the program writes it
//! again (BS-partner-2, WB-partner-15; BS-entry-4): an asset an earlier
//! version took, whose description holds a number that reads as a tax id,
//! still depreciates and is still disposed of; the lines the program
//! composes from it hold the masked form. And a payment's reference of
//! nine digits is kept, shown masked in the entry's description, and is no
//! finding of the audit.
use chrono::NaiveDate;
use ledger_core::{AccountType, Currency, Money};
use ledger_store::{JOURNAL_FILE, JournalWriter, Store};
use rust_decimal::Decimal;
use serde_json::json;
use tempfile::tempdir;
fn usd(amount: &str) -> Money {
Money::new(amount.parse().unwrap(), Currency::USD)
}
fn date(y: i32, m: u32, d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(y, m, d).unwrap()
}
struct Accounts {
cost: u64,
accum: u64,
expense: u64,
bank: u64,
gain: u64,
}
fn accounts(store: &mut Store) -> Accounts {
let mut add = |code: &str, name: &str, t: AccountType| {
store.add_account(code, name, t, None, false).unwrap()
};
Accounts {
cost: add("1500", "Equipment", AccountType::Asset),
accum: add("1501", "Accumulated Depreciation", AccountType::Asset),
expense: add("6100", "Depreciation Expense", AccountType::Expense),
bank: add("1000", "Bank", AccountType::Asset),
gain: add("4900", "Gain on Disposal", AccountType::Revenue),
}
}
/// Books with two assets an earlier version took: one whose description
/// holds a bare run of nine digits (a serial number), one an SSN's shape.
/// They are written to the journal as that version wrote them: the engine
/// refuses such a description now, whoever asks.
fn old_books() -> (tempfile::TempDir, Store, Accounts, [u64; 2]) {
let dir = tempdir().unwrap();
let mut store = Store::create(dir.path(), Currency::USD).unwrap();
let a = accounts(&mut store);
let first = store.ledger().next_asset_id();
drop(store);
let mut w = JournalWriter::open(&dir.path().join(JOURNAL_FILE)).unwrap();
for (id, description) in [
(first, "MacBook SN 000000000"),
(first + 1, "Laptop 000-00-0000 kit"),
] {
w.append(
"asset.registered",
json!({
"id": id,
"description": description,
"purchase_date": "2026-01-15",
"cost": {"amount": "1200.00", "currency": "USD"},
"salvage_value": {"amount": "0", "currency": "USD"},
"useful_life_months": 12,
"method": "straight_line",
"cost_account": a.cost,
"accum_depr_account": a.accum,
"expense_account": a.expense,
}),
)
.unwrap();
}
drop(w);
let store = Store::open(dir.path()).expect("books holding such an asset open");
store.verify().expect("and verify");
(dir, store, a, [first, first + 1])
}
/// An asset whose description holds the shape depreciates: the entry is
/// written, its description holds the shape masked, and the books verify.
#[test]
fn an_old_asset_still_depreciates() {
let (_dir, mut store, _, [bare, grouped]) = old_books();
let run = store.run_depreciation(bare, "2026-02").unwrap();
let entry = store.ledger().get_entry(run.entry_id.unwrap()).unwrap();
assert_eq!(
entry.description(),
"Depreciation — MacBook SN \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000 — 2026-02"
);
let run = store.run_depreciation(grouped, "2026-02").unwrap();
let entry = store.ledger().get_entry(run.entry_id.unwrap()).unwrap();
assert_eq!(
entry.description(),
"Depreciation — Laptop \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 kit — 2026-02"
);
store.verify().unwrap();
}
/// ... and is disposed of: the final depreciation's entry and the
/// disposal's both hold the masked form.
#[test]
fn an_old_asset_is_still_disposed_of() {
let (dir, mut store, a, [bare, grouped]) = old_books();
for (id, masked) in [
(
bare,
"MacBook SN \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}0000",
),
(
grouped,
"Laptop \u{2022}\u{2022}\u{2022}-\u{2022}\u{2022}-0000 kit",
),
] {
store.run_depreciation(id, "2026-02").unwrap();
let on = date(2026, 3, 10);
let disposal = store
.dispose_asset(id, on, usd("100"), a.bank, a.gain)
.unwrap();
let disposal = store.ledger().get_entry(disposal).unwrap();
assert_eq!(
disposal.description(),
format!("Disposal — {masked} — {on}")
);
// The final depreciation is the entry just before it.
let final_run = store.ledger().get_entry(disposal.id() - 1).unwrap();
assert_eq!(
final_run.description(),
format!("Depreciation — {masked} — 2026-03 (final)")
);
assert!(matches!(
store.ledger().get_asset(id).unwrap().status,
ledger_core::AssetStatus::Disposed { .. }
));
}
store.verify().unwrap();
// The books open again, as they were written.
drop(store);
let again = Store::open(dir.path()).unwrap();
again.verify().unwrap();
assert_eq!(
again.ledger().get_asset(bare).unwrap().description,
"MacBook SN 000000000"
);
}
/// The text of such an asset is not repeated in a line the audit would
/// then name: the lines the program wrote hold no number that reads as a
/// tax id, so the audit names only the line an earlier version wrote.
#[test]
fn what_the_program_writes_again_is_no_finding() {
let (_dir, mut store, a, [bare, _]) = old_books();
store.run_depreciation(bare, "2026-02").unwrap();
store
.dispose_asset(bare, date(2026, 3, 10), usd("100"), a.bank, a.gain)
.unwrap();
let found: Vec<String> = store
.integrity_findings()
.into_iter()
.filter(|f| f.code == "tax_id_in_journal")
.map(|f| f.message)
.collect();
// Two lines are the earlier version's (the two assets, whose
// description the journal holds as written); none is the program's.
assert_eq!(found.len(), 2, "{found:?}");
assert!(
found.iter().all(|m| m.contains("(asset.registered)")),
"{found:?}"
);
}
/// A payment reference of nine digits is a check or confirmation number:
/// kept whole as the reference, shown masked in the entry's description,
/// and no finding of the audit; a printed tax id is refused before
/// anything is journaled.
#[test]
fn a_nine_digit_payment_reference_is_kept_and_is_no_finding() {
let dir = tempdir().unwrap();
let mut store = Store::create(dir.path(), Currency::USD).unwrap();
let a = accounts(&mut store);
let customer = store.add_customer("Acme").unwrap();
let invoice = store
.create_invoice(
customer,
date(2026, 3, 1),
date(2026, 3, 31),
vec![ledger_core::arap::DocumentLine {
description: "work".into(),
amount: Decimal::from(100),
class_id: None,
account: None,
quantity: None,
unit_price: None,
}],
)
.unwrap();
let head = store.head();
let pay = |store: &mut Store, reference: &str| {
store.receive_payment_with(
invoice,
date(2026, 3, 5),
Decimal::from(10),
a.bank,
&ledger_core::PaymentDetails {
instrument: None,
reference: Some(reference.into()),
},
)
};
assert!(pay(&mut store, "000-00-0000").is_err());
assert_eq!(store.head(), head, "a refusal journals nothing");
let entry = pay(&mut store, "123456789").unwrap();
assert_eq!(
store.ledger().get_entry(entry).unwrap().description(),
"Payment on invoice 1 (ref \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}6789)"
);
let found: Vec<String> = store
.integrity_findings()
.into_iter()
.filter(|f| f.code == "tax_id_in_journal")
.map(|f| f.message)
.collect();
assert!(found.is_empty(), "{found:?}");
store.verify().unwrap();
}
/// The audit reads each journal field as its class: a reference (a tag, a
/// serial, a file name, an invoice number) may be nine digits, free words
/// may not, and a printed shape is a finding in either.
#[test]
fn the_audit_reads_a_reference_as_a_reference() {
let dir = tempdir().unwrap();
let mut store = Store::create(dir.path(), Currency::USD).unwrap();
let a = accounts(&mut store);
let asset = store
.register_asset(ledger_core::NewAsset {
description: "Van".into(),
in_service_date: date(2026, 1, 15),
cost: usd("1200"),
salvage_value: usd("0"),
useful_life_months: 12,
cost_account: a.cost,
accum_depr_account: a.accum,
expense_account: a.expense,
})
.unwrap();
let next = store.ledger().next_entry_id();
drop(store);
let mut w = JournalWriter::open(&dir.path().join(JOURNAL_FILE)).unwrap();
// Nine digits as a tag: a reference. As the words of an entry: a finding.
w.append(
"asset.tagged",
json!({"asset_id": asset, "tag": "123456789", "previous_tag": null}),
)
.unwrap();
w.append(
"entry.created",
json!({"id": next, "date": "2026-03-01", "description": "paid 123456789"}),
)
.unwrap();
// A printed shape in a tag is a finding too.
w.append(
"asset.tagged",
json!({"asset_id": asset, "tag": "T-000-00-0000", "previous_tag": "123456789"}),
)
.unwrap();
drop(w);
let store = Store::open(dir.path()).unwrap();
store.verify().unwrap();
let fields: Vec<String> = store
.integrity_findings()
.into_iter()
.filter(|f| f.code == "tax_id_in_journal")
.map(|f| f.message)
.collect();
assert_eq!(fields.len(), 2, "{fields:?}");
assert!(
fields[0].contains("(entry.created)") && fields[0].contains("`description`"),
"{fields:?}"
);
assert!(
fields[1].contains("(asset.tagged)") && fields[1].contains("`tag`"),
"{fields:?}"
);
}