Craft Anything: understand how any software works, and craft your own.
Rust
Apply replay body limits after redaction (R3.11) (#717)
Afloatcf414ff4b936
diff --git a/crates/analysis/src/standin.rs b/crates/analysis/src/standin.rsindex 40356bcb..c2c4541b 100644--- a/crates/analysis/src/standin.rs+++ b/crates/analysis/src/standin.rs@@ -850,20 +850,38 @@ pub fn build(har: &Har, opts: &BuildOptions) -> StandIn {note_status(route, u16::try_from(s.entry.response.status).unwrap_or(500), s.entry.response.mime.as_deref(), &mut scrub);continue;}- let sample = make_sample(s, opts, &mut scrub, &mut body_bytes);- note_status(route, sample.status, sample.content_type.as_deref(), &mut scrub);+ let mut sample = make_sample(s, opts, &mut scrub);// A request polled over and over gives the same answer many times; one is enough.- let repeat = route.samples.last().is_some_and(|p| {- p.path == sample.path- && p.query == sample.query- && p.request_key == sample.request_key- && p.status == sample.status- && p.text == sample.text- && p.base64 == sample.base64- });- if repeat {- body_bytes = body_bytes.saturating_sub(sample.text.as_ref().map_or(0, String::len) + sample.base64.as_ref().map_or(0, String::len));- } else {+ let repeats_last = |sample: &Sample| {+ route.samples.last().is_some_and(|p| {+ p.path == sample.path+ && p.query == sample.query+ && p.request_key == sample.request_key+ && p.status == sample.status+ && p.text == sample.text+ && p.base64 == sample.base64+ })+ };+ let mut repeat = repeats_last(&sample);+ if !repeat {+ let size = sample.text.as_ref().map_or(0, String::len).saturating_add(sample.base64.as_ref().map_or(0, String::len));+ if let Some(total) = body_bytes.checked_add(size).filter(|total| *total <= opts.max_total_body_bytes) {+ body_bytes = total;+ } else {+ sample.text = None;+ sample.base64 = None;+ sample.body_left_out = Some(BodyLeftOut::FileLimit);+ // A 304 without its cached body must remain unavailable to a fresh client.+ if sample.was_not_modified {+ sample.status = 304;+ sample.was_not_modified = false;+ }+ // Leaving a body out can make it identical to the previous omitted answer.+ repeat = repeats_last(&sample);+ }+ }+ note_status(route, sample.status, sample.content_type.as_deref(), &mut scrub);+ if !repeat {route.samples.push(sample);}}@@ -911,7 +929,7 @@ fn note_status(route: &mut StandInRoute, status: u16, mime: Option<&str>, scrub:}}-fn make_sample(s: &Seen<'_>, opts: &BuildOptions, scrub: &mut Scrub, body_bytes: &mut usize) -> Sample {+fn make_sample(s: &Seen<'_>, opts: &BuildOptions, scrub: &mut Scrub) -> Sample {let r = &s.entry.response;let mut sample = Sample {path: s.path.clone(),@@ -966,26 +984,24 @@ fn make_sample(s: &Seen<'_>, opts: &BuildOptions, scrub: &mut Scrub, body_bytes:} else {(Some(raw.to_string()), None)};- let size = text.as_ref().map_or(0, String::len) + binary.map_or(0, str::len);if text.as_ref().is_some_and(|t| t.len() > opts.max_body_bytes) {sample.body_left_out = Some(BodyLeftOut::TooLarge);return sample;}- if body_bytes.saturating_add(size) > opts.max_total_body_bytes {- sample.body_left_out = Some(BodyLeftOut::FileLimit);- return sample;- }if let Some(t) = text {if t.contains("PRIVATE KEY-----") {scrub.dropped.body_values = scrub.dropped.body_values.saturating_add(1);sample.body_left_out = Some(BodyLeftOut::HeldSecret);return sample;}- sample.text = Some(clean_text(t, sample.content_type.as_deref(), scrub));- *body_bytes = body_bytes.saturating_add(sample.text.as_ref().map_or(0, String::len));+ let clean = clean_text(t, sample.content_type.as_deref(), scrub);+ if clean.len() > opts.max_body_bytes {+ sample.body_left_out = Some(BodyLeftOut::TooLarge);+ return sample;+ }+ sample.text = Some(clean);} else {sample.base64 = binary.map(String::from);- *body_bytes = body_bytes.saturating_add(size);}// The answer a 304 stands for: the body the browser had cached.if sample.status == 304 {diff --git a/crates/analysis/tests/regression_standin_deduplicated_budget.rs b/crates/analysis/tests/regression_standin_deduplicated_budget.rsnew file mode 100644index 00000000..9bcd914a--- /dev/null+++ b/crates/analysis/tests/regression_standin_deduplicated_budget.rs@@ -0,0 +1,131 @@+use craft_anything_analysis::standin::{Answer, BodyLeftOut, BuildOptions, NoMatchReason, StandIn, Turns, answer, build_from_bytes};+use serde_json::json;++fn capture(responses: &[(u16, &str, Option<&str>)], max_total: usize) -> StandIn {+ let entries: Vec<_> = responses+ .iter()+ .map(|(status, body, encoding)| {+ json!({+ "request": {"method": "GET", "url": "https://example.test/resource"},+ "response": {"status": status, "content": {"mimeType": "text/plain", "text": body, "encoding": encoding}}+ })+ })+ .collect();+ let options = BuildOptions { hidden_values: vec!["x".into()], max_body_bytes: 100, max_total_body_bytes: max_total, ..Default::default() };+ build_from_bytes(&serde_json::to_vec(&json!({"log": {"entries": entries}})).unwrap(), &options).unwrap()+}++fn retained_bytes(standin: &StandIn) -> usize {+ standin.routes.iter().flat_map(|r| &r.samples).map(|s| s.text.as_ref().map_or(0, String::len) + s.base64.as_ref().map_or(0, String::len)).sum()+}++#[test]+fn repeated_redacted_bodies_replay_at_the_exact_total_limit() {+ for total in [9, 10] {+ let standin = capture(&[(200, "x", None); 2], total);+ assert_eq!(standin.routes[0].requests, 2);+ assert_eq!(standin.routes[0].samples.len(), 1);+ assert_eq!(retained_bytes(&standin), 9);+ let mut turns = Turns::default();+ for _ in 0..4 {+ let Answer::Found(found) = answer(&standin, &mut turns, "GET", "/resource", "", b"") else {+ panic!("missing repeated response");+ };+ assert_eq!(found.status, 200);+ assert_eq!(found.body.as_slice(), b"[dropped]");+ assert_eq!(found.body_left_out, None);+ assert_eq!(found.of, 1);+ }+ }+}++#[test]+fn duplicate_bodies_leave_the_remaining_budget_for_distinct_samples() {+ for (body, retained) in [("x", "[dropped]"), ("hello", "hello")] {+ let total = retained.len() + 2;+ let standin = capture(&[(200, body, None), (200, body, None), (200, "ok", None)], total);+ let samples = &standin.routes[0].samples;+ assert_eq!(standin.routes[0].requests, 3);+ assert_eq!(samples.len(), 2);+ assert_eq!(samples[0].text.as_deref(), Some(retained));+ assert_eq!(samples[1].text.as_deref(), Some("ok"));+ assert!(samples.iter().all(|sample| sample.body_left_out.is_none()));+ assert_eq!(retained_bytes(&standin), total);+ }+}++#[test]+fn distinct_over_budget_bodies_leave_no_charge_or_duplicate_omission() {+ let standin = capture(&[(200, "x", None), (200, "xx", None), (200, "xxx", None), (200, "ok", None)], 11);+ let samples = &standin.routes[0].samples;+ assert_eq!(standin.routes[0].requests, 4);+ assert_eq!(samples.len(), 3);+ assert_eq!(samples[0].text.as_deref(), Some("[dropped]"));+ assert_eq!(samples[1].body_left_out, Some(BodyLeftOut::FileLimit));+ assert!(samples[1].text.is_none());+ assert!(samples[1].base64.is_none());+ assert_eq!(samples[2].text.as_deref(), Some("ok"));+ assert_eq!(retained_bytes(&standin), 11);+}++#[test]+fn budget_rejected_cached_304s_remain_unavailable_and_deduplicated() {+ for total in [0, 8] {+ let standin = capture(&[(304, "x", None); 2], total);+ let route = &standin.routes[0];+ assert_eq!(route.statuses, vec![304]);+ assert_eq!(route.samples.len(), 1);+ assert_eq!(route.samples[0].status, 304);+ assert!(!route.samples[0].was_not_modified);+ assert_eq!(route.samples[0].body_left_out, Some(BodyLeftOut::FileLimit));+ assert!(route.samples[0].text.is_none());+ assert_eq!(retained_bytes(&standin), 0);+ let result = answer(&standin, &mut Turns::default(), "GET", "/resource", "", b"");+ assert!(matches!(result, Answer::NoMatch(missing) if missing.reason == NoMatchReason::CachedBodyUnavailable));+ }+}++#[test]+fn repeated_cached_304_bodies_keep_their_usable_replay() {+ let standin = capture(&[(304, "x", None); 2], 9);+ let route = &standin.routes[0];+ assert_eq!(route.statuses, vec![200]);+ assert_eq!(route.samples.len(), 1);+ assert!(route.samples[0].was_not_modified);+ assert_eq!(route.samples[0].text.as_deref(), Some("[dropped]"));+ let mut turns = Turns::default();+ for _ in 0..3 {+ let Answer::Found(found) = answer(&standin, &mut turns, "GET", "/resource", "", b"") else {+ panic!("missing cached response");+ };+ assert_eq!(found.status, 200);+ assert_eq!(found.body.as_slice(), b"[dropped]");+ assert_eq!(found.body_left_out, None);+ }+}++#[test]+fn duplicate_binary_samples_charge_only_the_retained_encoded_bytes() {+ let duplicate = capture(&[(200, "/w==", Some("base64")); 2], 4);+ assert_eq!(duplicate.routes[0].samples.len(), 1);+ assert_eq!(retained_bytes(&duplicate), 4);+ let mut turns = Turns::default();+ for _ in 0..2 {+ let Answer::Found(found) = answer(&duplicate, &mut turns, "GET", "/resource", "", b"") else {+ panic!("missing binary response");+ };+ assert_eq!(found.status, 200);+ assert_eq!(found.body.as_slice(), &[0xff]);+ assert_eq!(found.body_left_out, None);+ }+ let standin = capture(&[(200, "/w==", Some("base64")), (200, "/w==", Some("base64")), (200, "/g==", Some("base64")), (200, "ok", None)], 6);+ let samples = &standin.routes[0].samples;+ assert_eq!(standin.routes[0].requests, 4);+ assert_eq!(samples.len(), 3);+ assert_eq!(samples[0].base64.as_deref(), Some("/w=="));+ assert_eq!(samples[1].body_left_out, Some(BodyLeftOut::FileLimit));+ assert!(samples[1].text.is_none());+ assert!(samples[1].base64.is_none());+ assert_eq!(samples[2].text.as_deref(), Some("ok"));+ assert_eq!(retained_bytes(&standin), 6);+}diff --git a/crates/analysis/tests/regression_standin_redacted_budget.rs b/crates/analysis/tests/regression_standin_redacted_budget.rsnew file mode 100644index 00000000..cbb944f7--- /dev/null+++ b/crates/analysis/tests/regression_standin_redacted_budget.rs@@ -0,0 +1,51 @@+use craft_anything_analysis::standin::{BodyLeftOut, BuildOptions, StandIn, build_from_bytes};+use serde_json::json;++fn capture(bodies: &[&str], max_body: usize, max_total: usize) -> StandIn {+ let entries: Vec<_> = bodies+ .iter()+ .enumerate()+ .map(|(i, body)| {+ json!({+ "request": {"method": "GET", "url": format!("https://example.test/data/{i}")},+ "response": {"status": 200, "content": {"mimeType": "text/plain", "text": body}}+ })+ })+ .collect();+ let options = BuildOptions { hidden_values: vec!["x".into()], max_body_bytes: max_body, max_total_body_bytes: max_total, ..Default::default() };+ build_from_bytes(&serde_json::to_vec(&json!({"log": {"entries": entries}})).unwrap(), &options).unwrap()+}++#[test]+fn redaction_cannot_expand_a_body_beyond_its_limit() {+ let standin = capture(&["x", "ok"], 8, 8);+ let samples = &standin.routes[0].samples;+ assert_eq!(samples[0].body_left_out, Some(BodyLeftOut::TooLarge));+ assert!(samples[0].text.is_none());+ assert_eq!(samples[1].text.as_deref(), Some("ok"), "a rejected body must not consume the remaining budget");+}++#[test]+fn redaction_cannot_expand_a_capture_beyond_its_total_limit() {+ let standin = capture(&["x", "ok"], 100, 8);+ let samples = &standin.routes[0].samples;+ assert_eq!(samples[0].body_left_out, Some(BodyLeftOut::FileLimit));+ assert!(samples[0].text.is_none());+ assert_eq!(samples[1].text.as_deref(), Some("ok"), "a rejected body must not consume the remaining budget");+}++#[test]+fn the_exact_retained_size_fits_and_leaves_no_space_for_another_body() {+ let standin = capture(&["x", "ok"], 100, 9);+ let samples = &standin.routes[0].samples;+ assert_eq!(samples[0].text.as_deref(), Some("[dropped]"));+ assert_eq!(samples[1].body_left_out, Some(BodyLeftOut::FileLimit));+ assert_eq!(samples.iter().filter_map(|s| s.text.as_ref()).map(String::len).sum::<usize>(), 9);+}++#[test]+fn an_ordinary_body_at_the_limit_is_retained() {+ let standin = capture(&["hello"], 5, 5);+ assert_eq!(standin.routes[0].samples[0].text.as_deref(), Some("hello"));+ assert_eq!(standin.routes[0].samples[0].body_left_out, None);+}diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex de6dc5c3..3033e257 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -809,6 +809,11 @@ Owner: open · Status: in progressit's there- [ ] `native_publisher_show` hashes the file minus the signature fields, not section by section;a file with unusual gaps between sections can read as different+- [x] Enforce stand-in per-body and total byte budgets on the text that is actually retained after redaction;+ deduplicate consecutive samples before charging the capture budget.+ — claimed: Afloat16, branch bugfix/r3.11-standin-redacted-budget-20261103b+ Revision `d601bc4e` passed [full Linux CI](https://github.com/storytold/craft-anything/actions/runs/41788735130):+ all four retained-budget regressions and six deduplication regressions passed.### R3.12 Format parser correctnessOwner: open · Status: in progressdiff --git a/docs/STATUS.md b/docs/STATUS.mdindex 37c5b5b1..d6a754a6 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -54,6 +54,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| SQLite WITHOUT ROWID tables | Read from the index b-tree, interior records and overflow included; rows in primary-key order, values in declaration order, `rowid` null | Hand-built fixtures; generated files compared with the official SQLite library || Builder discovery smoke fixture | The missing-builder smoke fixture controls discovery state and supplies a synthetic result. | All original warning, modal, action and build-availability assertions are retained. Source inspection only; automated validation has not yet run for this change. || Parser review follow-ups | Java reference scans retain partial coverage; DEX signed LEB128 enforces 32-bit values; legacy AAPT strings stay inside their pool with a shared recovery probe limit; missing classic ext indirect metadata is not recovered as zeros. | Shared-budget revision `29c48e03` passed [full Linux CI](https://github.com/storytold/craft-anything/actions/runs/41762780268). The merge with main `41d2175e` awaits a new CI run. Extent-tree metadata handling is unchanged. |+| Stand-in retained body budgets | Check per-body limits after redaction and charge the capture budget only for distinct retained samples. Budget-rejected cached 304 responses remain unavailable. | All four original capture regressions and six deduplication regressions passed in [full Linux CI](https://github.com/storytold/craft-anything/actions/runs/41788735130) at revision `d601bc4e`. Workspace tests, strict Clippy, formatting, layers, locks, secrets, wasm-plugin checks, shared WASM compilation and the lockfile check passed. |### Builder retry policydiff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 6bb29639..5da5cd8e 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -742,3 +742,8 @@ arrived as fragments that never parsed and the plugin failed as a `tools/list` tsame server answered a direct probe in under a second. A cap protects memory, but a JSON-RPC linemust arrive whole to parse at all: keep the cap at the size the MCP client already allows, and testwith a multi-megabyte line, not a short one.++**A capture budget checked before deduplication changed the replay.** Redaction expanded a repeated+body, so its second copy was rejected before it could be discarded as a duplicate. Apply aggregate+budgets only to distinct bodies actually retained. When a budget removes a body, preserve unavailable+cached 304 responses and deduplicate identical omitted samples.