test(cli): a broad guard that a refusal writes nothing
Every test's books, when dropped, hold no failed call unless the test injected the fault on purpose (common::expect_failed_calls): a tool that writes a line and then refuses now fails every test that makes it refuse. hostile_args gains a guard that drives refused calls over every tool, and the same arguments with a made-up full tax id in each string in turn, and asserts the journal is byte for byte what it was after each refusal, with no trace of the tax id. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
a0fee420cd
commit
3f2ab70219
3 files changed
+202
No files matched your search
@@ -302,6 +302,8 @@ fn types(books: &Books) -> Vec<String> {
|
||||
/// corrupt page would.
|
||||
#[test]
|
||||
fn a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were() {
|
||||
// The fault is put there on purpose: this call fails part way.
|
||||
common::expect_failed_calls();
|
||||
let books = Books::new("calls-failed-lines");
|
||||
let mut w = books.session("test");
|
||||
let before = types(&books);
|
||||
@@ -675,6 +677,8 @@ fn set_tin(key: &str, tin: &str) -> Value {
|
||||
/// neither, and once the call can run again it is the new one that is kept.
|
||||
#[test]
|
||||
fn a_set_tin_that_fails_leaves_the_vault_as_it_was() {
|
||||
// The fault is put there on purpose: this call fails part way.
|
||||
common::expect_failed_calls();
|
||||
let books = Books::new("calls-vault-fail");
|
||||
let mut w = books.session("test");
|
||||
let party = answer_of(&w.call(
|
||||
|
||||
@@ -712,6 +712,46 @@ pub struct Books {
|
||||
pub currency: String,
|
||||
}
|
||||
|
||||
std::thread_local! {
|
||||
/// Whether this test means to leave a failed call in its books.
|
||||
static FAILED_CALLS_EXPECTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// This test makes a call fail part way on purpose (an injected fault):
|
||||
/// its books may end holding a `call.closed` with the outcome `failed`.
|
||||
/// No other test's may: see [`Books`]'s drop.
|
||||
#[allow(dead_code)]
|
||||
pub fn expect_failed_calls() {
|
||||
FAILED_CALLS_EXPECTED.with(|e| e.set(true));
|
||||
}
|
||||
|
||||
/// A refusal is decided before anything is written (D-88): a failed call
|
||||
/// on the record is for one that failed part way, which only a fault
|
||||
/// injected on purpose does. So when a test's books are dropped, none
|
||||
/// holds a failed call unless the test said it would
|
||||
/// ([`expect_failed_calls`]); a tool that writes a line and then refuses
|
||||
/// fails every test that makes it refuse, not only a test written for it.
|
||||
impl Drop for Books {
|
||||
fn drop(&mut self) {
|
||||
if std::thread::panicking() || FAILED_CALLS_EXPECTED.with(std::cell::Cell::get) {
|
||||
return;
|
||||
}
|
||||
let journal = self.journal_raw();
|
||||
let failed: Vec<String> = String::from_utf8_lossy(&journal)
|
||||
.lines()
|
||||
.filter(|l| {
|
||||
l.contains(r#""type":"call.closed""#) && l.contains(r#""outcome":"failed""#)
|
||||
})
|
||||
.filter_map(|l| serde_json::from_str::<Value>(l).ok())
|
||||
.map(|v| format!("{} (journal line {})", v["payload"]["tool"], v["seq"]))
|
||||
.collect();
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"a call failed after it began writing, and its failure is on the books' record; a refusal must be decided before anything is written: {failed:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Books {
|
||||
/// New books in a new home, kept in USD, with no settings set.
|
||||
pub fn new(tag: &str) -> Self {
|
||||
|
||||
@@ -896,6 +896,164 @@ fn hostile_tool_arguments_never_stop_the_server() {
|
||||
reopens(m, &p, "every tool");
|
||||
}
|
||||
|
||||
/// The journal's bytes, frame lines in: what "a refusal wrote nothing"
|
||||
/// is compared on, so a stray `call.begun` or `call.closed` is seen.
|
||||
fn journal_raw(p: &Places) -> Vec<u8> {
|
||||
std::fs::read(p.books.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The line types a journal gained, in order, and nothing of their
|
||||
/// payloads (the guard names what was written, never what it held).
|
||||
fn gained_types(before: &[u8], after: &[u8]) -> Vec<String> {
|
||||
let rest = after.strip_prefix(before).unwrap_or(after);
|
||||
String::from_utf8_lossy(rest)
|
||||
.lines()
|
||||
.filter_map(|l| serde_json::from_str::<Value>(l).ok())
|
||||
.map(|v| v["type"].as_str().unwrap_or("?").to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `v` with its `which`th string (counting in order) carrying a made-up
|
||||
/// full tax id (a 9xx area number: no one is issued one), so a refusal
|
||||
/// for a text that names one has something to leave out; the number of
|
||||
/// strings `v` holds is added to `seen`.
|
||||
fn with_tin_in_string(v: &Value, which: usize, seen: &mut usize) -> Value {
|
||||
match v {
|
||||
Value::String(s) => {
|
||||
*seen += 1;
|
||||
if *seen - 1 == which {
|
||||
Value::String(format!("{s} 987-65-4321"))
|
||||
} else {
|
||||
v.clone()
|
||||
}
|
||||
}
|
||||
Value::Array(a) => Value::Array(
|
||||
a.iter()
|
||||
.map(|x| with_tin_in_string(x, which, seen))
|
||||
.collect(),
|
||||
),
|
||||
Value::Object(o) => Value::Object(
|
||||
o.iter()
|
||||
.map(|(k, x)| (k.clone(), with_tin_in_string(x, which, seen)))
|
||||
.collect(),
|
||||
),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A refusal is decided before anything is written (D-88: a failed
|
||||
/// transaction is on the record, for a call that failed part way, not for
|
||||
/// a call that could have been refused up front): whatever a tool answers
|
||||
/// with an error to hostile arguments, the journal is byte for byte what
|
||||
/// it was before the call. Over every tool, at a small number of cases
|
||||
/// (`MCP_REFUSAL_CASES`, default 100), and again with a made-up tax id in
|
||||
/// each string of the arguments in turn: no journal line holds one
|
||||
/// (BS-partner-2).
|
||||
#[test]
|
||||
fn a_refused_call_leaves_the_journal_byte_for_byte_as_it_was() {
|
||||
let p = places("refusals");
|
||||
let mut m = Mcp::start(&p);
|
||||
fixture(&mut m, &p);
|
||||
let list = m.rpc("tools/list", json!({}));
|
||||
let tools: Vec<(String, Value)> = list["result"]["tools"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| {
|
||||
(
|
||||
t["name"].as_str().unwrap().to_string(),
|
||||
t["inputSchema"].clone(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let per_tool: Vec<BoxedStrategy<(String, Value)>> = tools
|
||||
.iter()
|
||||
.map(|(name, schema)| {
|
||||
let name = name.clone();
|
||||
args_for(schema, &p)
|
||||
.prop_map(move |a| (name.clone(), a))
|
||||
.boxed()
|
||||
})
|
||||
.collect();
|
||||
let call = proptest::strategy::Union::new(per_tool);
|
||||
let cases = std::env::var("MCP_REFUSAL_CASES")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(100);
|
||||
let mut runner = TestRunner::new(Config {
|
||||
cases,
|
||||
failure_persistence: None,
|
||||
max_shrink_iters: 0,
|
||||
..Config::default()
|
||||
});
|
||||
let m = std::cell::RefCell::new(m);
|
||||
// Every refusal that wrote: (tool, the line types it left).
|
||||
let found = std::cell::RefCell::new(Vec::<(String, Vec<String>)>::new());
|
||||
let refused = std::cell::Cell::new(0u32);
|
||||
let tried = |m: &mut Mcp, tool: &str, args: Value| {
|
||||
let before = journal_raw(&p);
|
||||
let r = m.rpc("tools/call", json!({"name": tool, "arguments": args}));
|
||||
let after = journal_raw(&p);
|
||||
let no = r.get("error").is_some() || r["result"]["isError"] == json!(true);
|
||||
if no {
|
||||
refused.set(refused.get() + 1);
|
||||
if before != after {
|
||||
found
|
||||
.borrow_mut()
|
||||
.push((tool.to_string(), gained_types(&before, &after)));
|
||||
}
|
||||
}
|
||||
// A refusal leaves no trace of a tax id it was given: not in a
|
||||
// line it wrote, not in the error a failed call's closing line
|
||||
// keeps (BS-partner-2). (What a call that succeeded keeps is the
|
||||
// tool's own text rules, not this guard's.)
|
||||
let gained = after.strip_prefix(before.as_slice()).unwrap_or(&after);
|
||||
let tin = no && String::from_utf8_lossy(gained).contains("987-65-4321");
|
||||
(no, tin)
|
||||
};
|
||||
runner
|
||||
.run(&call, |(tool, args)| {
|
||||
let mut m = m.borrow_mut();
|
||||
let (_, tin) = tried(&mut m, &tool, args);
|
||||
prop_assert!(!tin, "{} journaled a tax id", tool);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// Every tool a couple of times, each time with a tax id put in one
|
||||
// string of its arguments in turn: the refusals that name a text.
|
||||
let mut m = m.into_inner();
|
||||
let mut det = TestRunner::deterministic();
|
||||
for (tool, schema) in &tools {
|
||||
for _ in 0..2 {
|
||||
let args = args_for(schema, &p).new_tree(&mut det).unwrap().current();
|
||||
let (_, tin) = tried(&mut m, tool, args.clone());
|
||||
assert!(!tin, "{tool} journaled a tax id");
|
||||
let mut strings = 0;
|
||||
with_tin_in_string(&args, usize::MAX, &mut strings);
|
||||
for which in 0..strings.min(6) {
|
||||
let given = with_tin_in_string(&args, which, &mut 0);
|
||||
let (_, tin) = tried(&mut m, tool, given);
|
||||
assert!(!tin, "{tool} journaled a tax id it was given");
|
||||
}
|
||||
}
|
||||
}
|
||||
let found = found.into_inner();
|
||||
assert!(
|
||||
refused.get() >= 100,
|
||||
"the guard saw too few refusals: {}",
|
||||
refused.get()
|
||||
);
|
||||
let mut by_tool = std::collections::BTreeMap::<String, Vec<String>>::new();
|
||||
for (tool, types) in found {
|
||||
by_tool.entry(tool).or_default().push(types.join(","));
|
||||
}
|
||||
assert!(
|
||||
by_tool.is_empty(),
|
||||
"refusals that wrote to the journal (tool: line types left): {by_tool:#?}"
|
||||
);
|
||||
reopens(m, &p, "every refusal");
|
||||
}
|
||||
|
||||
/// INVARIANT 4: whatever the calls journaled, the books open again. A
|
||||
/// hostile call a command accepts but replay refuses would leave books
|
||||
/// that never reopen (BS-entry-4): the server is restarted on them and
|
||||
|
||||
Reference in new issue
Block a user