diff --git a/crates/analysis/src/web_har.rs b/crates/analysis/src/web_har.rs index a2db96163..f155303bf 100644 --- a/crates/analysis/src/web_har.rs +++ b/crates/analysis/src/web_har.rs @@ -70,13 +70,45 @@ pub(crate) struct Redactor { log: Vec, } -fn percent_encode(s: &str) -> String { +/// Percent-encode `s`; when `form` is true, spaces serialize as `+` (`application/x-www-form-urlencoded`). +fn encode_query(s: &str, form: bool, upper_hex: bool) -> String { let mut out = String::new(); for b in s.bytes() { - if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + if form && b == b' ' { + out.push('+'); + } else if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { out.push(char::from(b)); - } else { + } else if upper_hex { out.push_str(&format!("%{b:02X}")); + } else { + out.push_str(&format!("%{b:02x}")); + } + } + out +} + +/// Percent-encode `s` using uppercase hexadecimal escapes (`%20` for spaces). +fn percent_encode(s: &str) -> String { + encode_query(s, false, true) +} + +/// True when `haystack` contains `needle` under ASCII case-insensitive comparison. +fn contains_ascii_ci(haystack: &str, needle: &str) -> bool { + !needle.is_empty() && haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle.as_bytes())) +} + +/// Replace non-overlapping ASCII case-insensitive occurrences of `needles` (longest first) with `[redacted]`. +fn replace_needles(s: &str, needles: &[String]) -> String { + let mut out = String::with_capacity(s.len()); + let mut i = 0usize; + while let Some(tail) = s.get(i..) { + let Some(ch) = tail.chars().next() else { break }; + if let Some(hit) = needles.iter().find(|n| !n.is_empty() && tail.as_bytes().get(..n.len()).is_some_and(|w| w.eq_ignore_ascii_case(n.as_bytes()))) { + out.push_str("[redacted]"); + i += hit.len(); + } else { + out.push(ch); + i += ch.len_utf8(); } } out @@ -87,7 +119,23 @@ impl Redactor { let mut needles: Vec = Vec::new(); for v in values.iter().filter(|v| !v.is_empty()) { let json_escaped = serde_json::to_string(v).ok().and_then(|q| q.get(1..q.len().saturating_sub(1)).map(String::from)).unwrap_or_default(); - for form in [v.clone(), v.to_ascii_lowercase(), percent_encode(v), percent_encode(v).to_ascii_lowercase(), json_escaped, v.replace(' ', "+")] { + let pct_up = percent_encode(v); + let pct_lo = encode_query(v, false, false); + let form_up = encode_query(v, true, true); + let form_lo = encode_query(v, true, false); + for form in [ + v.clone(), + v.to_ascii_lowercase(), + v.to_ascii_uppercase(), + pct_up.clone(), + pct_lo, + pct_up.to_ascii_lowercase(), + form_up.clone(), + form_lo, + form_up.to_ascii_lowercase(), + json_escaped, + v.replace(' ', "+"), + ] { if !form.is_empty() && !needles.contains(&form) { needles.push(form); } @@ -98,7 +146,7 @@ impl Redactor { } fn contains(&self, s: &str) -> bool { - self.needles.iter().any(|n| s.contains(n.as_str())) + self.needles.iter().any(|n| contains_ascii_ci(s, n)) } /// Replace declared values in kept text. @@ -106,10 +154,7 @@ impl Redactor { if !self.contains(s) { return s.to_string(); } - let mut out = s.to_string(); - for n in &self.needles { - out = out.replace(n.as_str(), "[redacted]"); - } + let out = replace_needles(s, &self.needles); self.log.push(json!({"pointer": pointer, "reason": "secret-value"})); out } @@ -278,7 +323,7 @@ pub struct OutlineRedactions<'r> { impl OutlineRedactions<'_> { fn names_hit(&self, k: &str) -> bool { - self.needles.iter().any(|n| k.contains(n.as_str())) + self.needles.iter().any(|n| contains_ascii_ci(k, n)) } } @@ -334,17 +379,28 @@ fn body_outline( red.log.extend(sr.log); return json!({"kind": "json", "bytes": bytes, "outline": outline}); } + let filter_form_fields = |names: Vec, red: &mut Redactor| -> Vec { + let mut kept = Vec::with_capacity(names.len()); + for n in names { + if red.contains(&n) || red.contains(&decode_query_name(&n)) { + red.log.push(json!({"pointer": pointer, "reason": "secret-value", "scope": "form-field"})); + } else { + kept.push(n); + } + } + kept + }; if mime_l.contains("x-www-form-urlencoded") { let names: Vec = if params.is_empty() { decoded.as_deref().unwrap_or("").split('&').filter_map(|p| p.split('=').next()).filter(|k| !k.is_empty()).map(String::from).take(200).collect() } else { params.iter().map(|(k, _)| k.clone()).take(200).collect() }; - let names: Vec = names.into_iter().filter(|n| !red.contains(n)).collect(); - return json!({"kind": "form", "bytes": bytes, "fields": names}); + return json!({"kind": "form", "bytes": bytes, "fields": filter_form_fields(names, red)}); } if mime_l.contains("multipart") { - return json!({"kind": "multipart", "bytes": bytes, "fields": params.iter().map(|(k, _)| k.clone()).filter(|n| !red.contains(n)).take(200).collect::>()}); + let names: Vec = params.iter().map(|(k, _)| k.clone()).take(200).collect(); + return json!({"kind": "multipart", "bytes": bytes, "fields": filter_form_fields(names, red)}); } if decoded.is_none() { return Value::Null; diff --git a/crates/analysis/tests/har_secret_encodings.rs b/crates/analysis/tests/har_secret_encodings.rs new file mode 100644 index 000000000..1ae4584ca --- /dev/null +++ b/crates/analysis/tests/har_secret_encodings.rs @@ -0,0 +1,114 @@ +//! Regression tests for form-encoded and mixed-case percent-escaped secret redaction in HAR inspection. + +use craft_anything_analysis::web_har::{HarOptions, all_strings, inspect_har}; +use serde_json::json; +use std::collections::BTreeSet; + +/// Standard credential headers and exact literal secrets continue to be scrubbed. +#[test] +fn exact_literal_and_auth_header_redaction_works() { + let har = serde_json::to_vec(&json!({ + "log": { + "version": "1.2", + "entries": [{ + "request": { + "method": "GET", + "url": "https://api.example.test/v1/ping?note=PlainSecret", + "headers": [{"name": "Authorization", "value": "Bearer tok"}] + }, + "response": { "status": 200, "headers": [], "content": { "size": 0, "mimeType": "" } } + }] + } + })) + .unwrap(); + let out = inspect_har(&har, &HarOptions { hidden_values: vec!["PlainSecret".into()], limit: 10, max_entries: 100, ..Default::default() }).unwrap(); + assert_eq!(out["entries"][0]["url"], "https://api.example.test/v1/ping?note=[redacted]"); + assert_eq!(out["entries"][0]["request_headers"][0]["value"], serde_json::Value::Null); +} + +/// `application/x-www-form-urlencoded` (`+` plus `%XX`) and mixed-case `%xx` hex escapes must be redacted everywhere. +#[test] +fn form_urlencoded_and_mixed_case_percent_escaped_secrets_never_leak() { + // `URLSearchParams({ auth: "Bearer tok==" })` serializes space as `+` and `=` as `%3D`. + // Many clients also emit lowercase hex escapes (`%2f`, `%3d`) while preserving mixed-case ASCII letters. + let har = serde_json::to_vec(&json!({ + "log": { + "version": "1.2", + "entries": [{ + "request": { + "method": "POST", + "url": "https://api.example.test/v1/callback?state=Bearer+tok%3D%3D&next=MySecret%2f1&upper=MYSECRET/1", + "headers": [ + {"name": "X-Custom-Trace", "value": "hint=Bearer+tok%3d%3d; path=MySecret%2f1"}, + {"name": "Referer", "value": "https://app.example.test/cb?s=MySecret%2f1"} + ], + "postData": { + "mimeType": "application/x-www-form-urlencoded", + "text": "safe_field=1&MySecret%2f1=val&Bearer+tok%3D%3D=2" + } + }, + "response": { + "status": 200, + "headers": [], + "content": { + "size": 32, + "mimeType": "application/json", + "text": "{\"ok\":true,\"MYSECRET/1\":\"v\"}" + } + } + }] + } + })) + .unwrap(); + + let out = + inspect_har(&har, &HarOptions { hidden_values: vec!["Bearer tok==".into(), "MySecret/1".into()], limit: 10, max_entries: 100, ..Default::default() }) + .unwrap(); + + let mut strings = BTreeSet::new(); + all_strings(&out, &mut strings); + for s in &strings { + let low = s.to_ascii_lowercase(); + for forbidden in ["tok==", "tok%3d%3d", "mysecret/1", "mysecret%2f1"] { + assert!(!low.contains(forbidden), "secret spelling `{forbidden}` leaked in `{s}`"); + } + } + + assert_eq!(out["entries"][0]["request_body"]["fields"], json!(["safe_field"])); + assert!( + out["redactions"].as_array().unwrap().iter().any(|r| r["scope"] == "form-field"), + "dropping secret form field names should record a redaction entry: {}", + out["redactions"] + ); +} + +/// Multipart `params` field names carrying percent-encoded or uppercase spellings of declared secrets are dropped and logged. +#[test] +fn multipart_encoded_secret_field_names_are_filtered_and_logged() { + let har = serde_json::to_vec(&json!({ + "log": { + "version": "1.2", + "entries": [{ + "request": { + "method": "POST", + "url": "https://api.example.test/v1/upload", + "headers": [], + "postData": { + "mimeType": "multipart/form-data; boundary=---x", + "params": [ + {"name": "avatar", "value": "file"}, + {"name": "Key%20One", "value": "x"}, + {"name": "KEY ONE", "value": "y"} + ] + } + }, + "response": { "status": 200, "headers": [], "content": { "size": 0, "mimeType": "" } } + }] + } + })) + .unwrap(); + + let out = inspect_har(&har, &HarOptions { hidden_values: vec!["Key One".into()], limit: 10, max_entries: 100, ..Default::default() }).unwrap(); + assert_eq!(out["entries"][0]["request_body"]["fields"], json!(["avatar"])); + assert!(out["redactions"].as_array().unwrap().iter().any(|r| r["scope"] == "form-field")); +} diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index ff49217b6..29d747abd 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -3140,7 +3140,7 @@ Owner: open ยท Status: in progress backend matches older recordings the same way), redact declared secrets in every kept field (names, methods, hosts, versions, timings), count body bytes before text conversion, and template only real calendar dates in API paths (#602โ€“#605, by Afloat16) -- [ ] Redact declared HAR secrets in `application/x-www-form-urlencoded` spellings (`+` with `%XX`), mixed-case percent escapes and encoded form field names. +- [x] Redact declared HAR secrets in `application/x-www-form-urlencoded` spellings (`+` with `%XX`), mixed-case percent escapes and encoded form field names. โ€” claimed: Plastic-time, branch bugfix/r3.13-har-secret-encodings - [x] Preserve empty query pairs when matching older stand-in recordings, without treating raw query separators as pairs โ€” claimed: Afloat16, branch `bugfix/r3.13-preserve-empty-query-pairs-20261103` diff --git a/docs/STATUS.md b/docs/STATUS.md index bebcc1fec..4ac60ef8d 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -384,6 +384,7 @@ coverage and secrets passed. The companion CLI was built with locked dependencie | Require matching operands before reporting EVM dispatch facts | Require the selector division operand order, the Vyper memory load and the four-byte calldata threshold before reporting those dispatch patterns; invalid jump destinations retain unknown payability. | Regression fixtures cover unused and reversed selector divisors, unrelated arithmetic, different calldata thresholds and invalid jump targets. | | EVM metadata map identity | Duplicate keys and map keys outside the supported text-key representation leave the trailer in the analyzed bytecode instead of overwriting metadata entries. | Synthetic trailers cover duplicate compiler versions, identical duplicates, numeric/text collisions, non-text key forms, nested maps and ordinary compiler metadata. | | Stand-in backends | `web_standin_build` turns a HAR into `standin.json` (secrets dropped, varying path parts templated); `web_standin_start` answers from it on loopback; `web_standin_show` lists what it had no answer for. A 304 without a usable cached body is counted at build time and skipped during replay; if its matching group has no usable answer, requests get a 404 with `cached_body_unavailable`, also shown in the request log. Writes replay what was recorded and don't change later reads. Older saved query variants keep explicit empty pairs when credential rules are reapplied; raw separators remain ignored and the 200-pair limit matches capture. App maps list GraphQL and tRPC operations; `web_walkthrough_check` checks a scripted session without a browser. A Deep website study writes `capture/original.har` from the start page's traffic and the answers it gave (`analysis::web_har::har_from_network`), so a rebuilt front end can be given a stand-in from a recording the study made itself, and the brief then says so | Unit tests, real loopback requests, and a run with curl on a hand-written HAR. The 304 correction passes 99 analysis tests and a real-loopback regression, covering mixed samples, omitted bodies, matching boundaries and existing v1 files. [Hosted CI for #543](https://github.com/storytold/craft-anything/actions/runs/41585168291) also passed the full engine tests and workspace gates. Public capture/replay regressions cover legacy empty pairs, raw separators and the query-pair limit. A recording written from kept browser requests builds a stand-in in the tests, and the brief test writes its recording with the same function the study uses. No live study recording or real front end yet | +| HAR form-encoded and mixed-case secret redaction | Declared HAR secrets are redacted across `application/x-www-form-urlencoded` (`+` with `%XX`), ASCII case variants, mixed-case percent-hex escapes, and URL-encoded form or multipart field names, recording `form-field` redaction entries when field names are dropped. | Three regressions in `har_secret_encodings` (two failing before the fix) plus a Node.js `URLSearchParams` encoding check. | | Stand-in sample metadata | Consecutive samples compare all response fields before retained bytes are charged. Header comparison ignores name case and ordering between different names, while preserving repeated-value order and the stored headers. At capacity, a usable response replaces only an unavailable 304 for the same path, query and request key; refused bodies preserve existing evidence. | All 24 combined replay regressions pass locally on the refresh onto `cf414ff4`. The same replay implementation and four regression files passed in [frozen candidate `8758b6df`](https://github.com/Afloat16/craft-anything/actions/runs/41833977848) on base `b2d7e89e`. Historical standalone revision `f79dc0bd` passed its 14 metadata and header/capacity regressions in [full Linux CI](https://github.com/storytold/craft-anything/actions/runs/41793241151). See this PR's checks for the current revision's complete gate. | | Reject unsupported HTML script type suffixes | Match HTML script types against complete JavaScript MIME names and the exact module keyword. | JavaScript crate regression tests on Windows cover corrected behavior and retained controls. No browser or live application run. | | Exact HTML module script keyword | Whitespace around the module keyword and whitespace-only types stay out of script evidence. Classic MIME types still accept surrounding ASCII whitespace. | Fixtures cover padded keywords, a decoded line break, the empty type and classic MIME controls. |