camel_api/redact.rs
1//! Canonical string-based URL redaction for diagnostic surfaces (ADR-0051).
2//!
3//! String surgery over raw URL bytes: userinfo in every authority window
4//! is masked as `***`, query/fragment content is replaced with
5//! `?[redacted]` / `#[redacted]` sentinels, and the result is capped at
6//! 256 bytes on a UTF-8 char boundary. Authority windows are enumerated
7//! over maximal runs of `/` and `\` characters: pure-slash runs (the
8//! landed `//` rule) open a window at two or more characters,
9//! backslash-bearing runs only behind an RFC 3986 scheme prefix. These
10//! helpers never parse — they are the strictest feasible handling for
11//! strings that may be malformed or hostile.
12//!
13//! Distinct from [`crate::endpoint_uri::EndpointUri::to_redacted_string`],
14//! which redacts the catalog-driven authored-URI layer (structured
15//! `EndpointUri` values) and is out of scope here.
16
17/// Return `input` with userinfo masked in every authority window. Windows
18/// are enumerated over maximal runs of `/` and `\` characters (see
19/// [`authority_windows`]); a window containing `@` carries userinfo, and
20/// the bytes from window start through the LAST `@` are replaced with
21/// `***` (over-masking is safe, under-masking is not). Windows are
22/// collected on the input and masked in reverse offset order (with
23/// duplicates deduped) so an edit never shifts a yet-to-be-processed
24/// window. Idempotent: an already-masked `***@host` window rewrites to
25/// itself.
26fn mask_authority_windows(input: &str) -> String {
27 let mut out = input.to_string();
28 let mut windows = authority_windows(input);
29 // The run scanner emits one window per maximal run in ascending order;
30 // sort+dedup are belt-and-braces.
31 windows.sort_unstable();
32 windows.dedup();
33 for (start, end) in windows.into_iter().rev() {
34 if let Some(at) = out[start..end].rfind('@') {
35 out.replace_range(start..start + at, "***");
36 }
37 }
38 out
39}
40
41/// Authority-window enumeration (bd rc-f05q8). Windows are derived from
42/// maximal runs of `/` and `\` characters, and a qualifying run opens
43/// exactly one window that ends at the next `/`, `?`, or `#` (or end of
44/// input). A pure-slash run qualifies at length >= 2 (the landed `//`
45/// rule) and its window starts at the run's end, keeping the slashes
46/// visible. A backslash-bearing run qualifies only behind an RFC 3986
47/// scheme prefix ending immediately before the run (see
48/// [`scheme_prefix_len`]): length >= 2 needs any scheme; a single `\`
49/// needs a scheme of two or more characters, or a one-character scheme
50/// whose candidate window content is credential-shaped (see
51/// [`single_backslash_credential_gate`]). Every qualifying window starts
52/// at the run's end — the spec's uniform rule: a window begins
53/// immediately after a maximal run of `/` and `\` — so the introducer
54/// slashes and backslashes stay visible. Scheme-less backslash runs —
55/// Windows drive paths and UNC paths — never open a window.
56fn authority_windows(input: &str) -> Vec<(usize, usize)> {
57 let bytes = input.as_bytes();
58 let mut windows = Vec::new();
59 let mut i = 0;
60 while i < bytes.len() {
61 if !matches!(bytes[i], b'/' | b'\\') {
62 i += 1;
63 continue;
64 }
65 let run_start = i;
66 let mut has_backslash = false;
67 while i < bytes.len() && matches!(bytes[i], b'/' | b'\\') {
68 has_backslash |= bytes[i] == b'\\';
69 i += 1;
70 }
71 let run_len = i - run_start;
72 let opens = if has_backslash {
73 match scheme_prefix_len(input, run_start) {
74 None => false,
75 Some(scheme_len) => {
76 run_len >= 2
77 || scheme_len >= 2
78 || (scheme_len == 1 && single_backslash_credential_gate(input, i))
79 }
80 }
81 } else {
82 run_len >= 2
83 };
84 if opens {
85 let end = input[i..]
86 .find(['/', '?', '#'])
87 .map_or(input.len(), |offset| i + offset);
88 // Every window starts at the run's end (spec: a window begins
89 // immediately after a maximal run of `/` and `\`), so the
90 // introducer slashes and backslashes stay visible.
91 let start = i;
92 windows.push((start, end));
93 }
94 }
95 windows
96}
97
98/// Length of the RFC 3986 scheme name (`[a-zA-Z][a-zA-Z0-9+.-]*`) whose
99/// `:` ends immediately before `run_start` — the LONGEST valid match, so
100/// the name is the maximal run of scheme characters directly before the
101/// colon and its first character must be alphabetic. `None` when
102/// `input[..run_start]` does not end with `scheme:`.
103fn scheme_prefix_len(input: &str, run_start: usize) -> Option<usize> {
104 let bytes = input.as_bytes();
105 if run_start < 2 || bytes[run_start - 1] != b':' {
106 return None;
107 }
108 let mut start = run_start - 1;
109 while start > 0
110 && (bytes[start - 1].is_ascii_alphanumeric()
111 || matches!(bytes[start - 1], b'+' | b'.' | b'-'))
112 {
113 start -= 1;
114 }
115 let len = run_start - 1 - start;
116 if len == 0 || !bytes[start].is_ascii_alphabetic() {
117 return None;
118 }
119 Some(len)
120}
121
122/// Credential-shaped content gate for a single `\` behind a
123/// one-character scheme (bd rc-f05q8): the candidate window content —
124/// from `content_start` (the run's end) to the next `/`, `?`, or `#` —
125/// must carry a `:` strictly before its LAST `@`. Without an `@` there is
126/// no userinfo to hide, so the gate fails.
127fn single_backslash_credential_gate(input: &str, content_start: usize) -> bool {
128 let end = input[content_start..]
129 .find(['/', '?', '#'])
130 .map_or(input.len(), |offset| content_start + offset);
131 let window = &input[content_start..end];
132 match window.rfind('@') {
133 Some(at) => window[..at].contains(':'),
134 None => false,
135 }
136}
137
138/// Truncate `s` to at most `max` bytes, walking the cut down to the nearest
139/// UTF-8 char boundary so a multibyte character straddling the cap cannot
140/// panic.
141fn truncate_utf8_safe(s: &mut String, max: usize) {
142 if s.len() <= max {
143 return;
144 }
145 let mut cut = max;
146 while !s.is_char_boundary(cut) {
147 cut -= 1;
148 }
149 s.truncate(cut);
150}
151
152/// Single left-to-right pass over `bytes` that decodes `%HH` sequences
153/// where `decode(hi, lo)` yields a byte; every other byte is copied
154/// through unchanged. `decode` is consulted only when `%` is followed by
155/// two bytes — a trailing `%`, a stray `%`, and an undecodable pair all
156/// fall through to the literal copy. The caller decides which escapes
157/// count (see [`minimal_decode_pair`] and [`decode_match_key`]).
158fn percent_scan(bytes: &[u8], decode: impl Fn(u8, u8) -> Option<u8>) -> Vec<u8> {
159 let mut out = Vec::with_capacity(bytes.len());
160 let mut i = 0;
161 while i < bytes.len() {
162 if bytes[i] == b'%'
163 && i + 2 < bytes.len()
164 && let Some(b) = decode(bytes[i + 1], bytes[i + 2])
165 {
166 out.push(b);
167 i += 3;
168 continue;
169 }
170 out.push(bytes[i]);
171 i += 1;
172 }
173 out
174}
175
176/// Single left-to-right pass over a query pair that decodes ONLY the three
177/// sequences a credential URL cannot be recognized without — `%40` → `@`,
178/// `%3a`/`%3A` → `:`, `%2f`/`%2F` → `/` — and copies every other byte
179/// through (other `%HH` escapes, stray `%`, and incomplete escapes
180/// included). Valid UTF-8 is preserved byte-for-byte; invalid bytes become
181/// `U+FFFD`, which cannot match an ASCII needle, so the shape checks below
182/// are unaffected. This "minimal decode" (bd rc-r7v8s) is deliberately
183/// weaker than a full percent-decoder: it exists only so the allowlist
184/// redactor can recognize credential-shaped values hidden behind encoding,
185/// while never giving a benign pair a reason to change. Double-encoded
186/// input (`%2540`) stays encoded — out of scope by design.
187fn minimal_decode_pair(pair: &str) -> String {
188 let decoded = percent_scan(pair.as_bytes(), |hi, lo| match (hi, lo) {
189 (b'4', b'0') => Some(b'@'),
190 (b'3', b'a' | b'A') => Some(b':'),
191 (b'2', b'f' | b'F') => Some(b'/'),
192 _ => None,
193 });
194 String::from_utf8_lossy(&decoded).into_owned()
195}
196
197/// Credential-shape test shared by both query-pair positions (ADR-0076
198/// appendix, bd rc-yvjp3): an input whose minimal decode carries `@` and
199/// also `:` or `//` is treated as an embedded `user:pass@host` credential
200/// wherever it rides — key position or value position. One predicate, one
201/// invariant; a lone `@` (an email address) is not credential-shaped.
202fn is_credential_shaped(decoded: &str) -> bool {
203 decoded.contains('@') && (decoded.contains(':') || decoded.contains("//"))
204}
205
206/// Match key for the sensitive-substring check: a single left-to-right
207/// `%HH` decode over the raw key bytes (ANY two hex digits after `%`,
208/// case-insensitive; invalid sequences copied verbatim), then lowercased.
209/// Unlike [`minimal_decode_pair`] this is a full digit decode because the
210/// denylist matches literal text (`pass%77ord` must hit `password`), not
211/// credential shape. The result is only used for substring matching and is
212/// never rendered; invalid UTF-8 from a decoded byte becomes `U+FFFD`,
213/// which cannot match an ASCII needle.
214fn decode_match_key(raw_key: &str) -> String {
215 let decoded = percent_scan(raw_key.as_bytes(), |hi, lo| {
216 let hi = (hi as char).to_digit(16)?;
217 let lo = (lo as char).to_digit(16)?;
218 Some((hi * 16 + lo) as u8)
219 });
220 String::from_utf8_lossy(&decoded).to_lowercase()
221}
222
223/// Canonical strict redaction of a raw URL string for diagnostic surfaces
224/// (ADR-0051, bd rc-eh49): authority windows are enumerated over maximal
225/// runs of `/` and `\` characters — a pure-slash run of two or more
226/// characters opens a window, a backslash-bearing run opens one only
227/// behind an RFC 3986 scheme prefix (`[a-zA-Z][a-zA-Z0-9+.-]*:`) ending
228/// immediately before the run (a single `\` additionally needs a scheme of
229/// two-plus characters, or a one-character scheme whose candidate window
230/// content is credential-shaped) — and each window ends at the next `/`,
231/// `?`, or `#`. A window containing `@` carries userinfo,
232/// and the bytes from window start through the LAST `@` are masked in
233/// place as `***@` (over-masking is safe, under-masking is not). Every
234/// window is scanned, so credentials cannot hide in a later window behind
235/// a benign first one. Everything from the earliest `?` or `#` is dropped;
236/// the sentinels
237/// compose: each distinct introducer character (`?` and/or `#`) that occurs
238/// anywhere in the URL appends its matching `?[redacted]` / `#[redacted]`
239/// sentinel in first-occurrence order — queries and fragments routinely
240/// carry tokens. The result is capped at 256 bytes on a UTF-8 char
241/// boundary. There is no URL parser here, so in-place windowed masking is
242/// the strictest feasible handling. This is the string layer;
243/// [`crate::endpoint_uri::EndpointUri::to_redacted_string`] redacts the
244/// catalog-driven authored-URI surface instead.
245pub fn redact_url(raw: &str) -> String {
246 let mut out = mask_authority_windows(raw);
247 if let Some(i) = out.find(['?', '#']) {
248 // Compose-both: one sentinel per distinct introducer found in the
249 // raw URL, in first-occurrence order.
250 let query_pos = out.find('?');
251 let fragment_pos = out.find('#');
252 out.truncate(i);
253 // Reserve the sentinel bytes before truncating so the cap never
254 // splits an appended sentinel (e_gpt stage-4).
255 let sentinel_total = match (query_pos, fragment_pos) {
256 (Some(_), Some(_)) => 22,
257 (Some(_), None) | (None, Some(_)) => 11,
258 (None, None) => 0,
259 };
260 if sentinel_total > 0 {
261 truncate_utf8_safe(&mut out, 256 - sentinel_total);
262 }
263 match (query_pos, fragment_pos) {
264 (Some(q), Some(f)) if f < q => out.push_str("#[redacted]?[redacted]"),
265 (Some(_), Some(_)) => out.push_str("?[redacted]#[redacted]"),
266 (Some(_), None) => out.push_str("?[redacted]"),
267 (None, Some(_)) => out.push_str("#[redacted]"),
268 (None, None) => {}
269 }
270 }
271 truncate_utf8_safe(&mut out, 256);
272 out
273}
274
275/// Fail-closed variant of [`redact_url`]: when any authority window of
276/// `raw` carries an `@`, the whole string is replaced with `[redacted]` —
277/// a string with an unvalidated authority marker may carry credentials
278/// nothing validated, so nothing of it is rendered (deliberate fail-closed
279/// over-redaction per ADR-0051). Otherwise identical to [`redact_url`].
280pub fn redact_url_fail_closed(raw: &str) -> String {
281 if window_has_at_sign(raw) {
282 "[redacted]".to_string()
283 } else {
284 redact_url(raw)
285 }
286}
287
288/// Broker-style redaction: window-mask userinfo like [`redact_url`], then
289/// redact sensitive query params per key while keeping benign ones. A pair
290/// whose match key — the raw key single-pass `%HH`-decoded then lowercased
291/// (bd rc-r7v8s) — contains any of `sensitive_key_substrings` renders as
292/// `{raw_key}=<redacted>` (the key keeps its original encoded bytes),
293/// EXCEPT when the raw key's own single-pass minimal decode
294/// (see `minimal_decode_pair`) is credential-shaped — contains `@` and
295/// also `:` or `//`: then the pair renders as a bare `<redacted>` and the
296/// key never echoes (bd rc-yvjp3, ADR-0076 appendix: key-position
297/// credential-shape symmetry — the same predicate the benign-key branch
298/// applies to the whole pair; a key such as `user%3Asecret%40host` embeds
299/// the credential `user:secret@host` and must not render). Well-known
300/// broker parameter names never decode to that shape, so the
301/// transport-policy diagnostic value below is preserved. Otherwise, if the
302/// pair's `minimal_decode_pair` output is
303/// credential-shaped (contains `@` and also `:` or `//`), the whole pair is
304/// replaced with a bare `<redacted>`: encoded or literal
305/// `user:secret@host` values must not survive under a benign key, while a
306/// lone `@` (an email address) keeps the pair visible. Every other pair
307/// survives byte-for-byte, because
308/// non-secret transport policy in query params (ActiveMQ failover URIs) is
309/// the sole diagnostic value of logging the broker URL. Fragments are never
310/// echoed: everything from the first `#` is dropped and replaced with the
311/// `#[redacted]` sentinel. The result is capped at 256 bytes on a UTF-8
312/// char boundary. String-based; no URL parser.
313pub fn redact_url_with_query_allowlist(raw: &str, sensitive_key_substrings: &[&str]) -> String {
314 // 1) Mask userinfo in every authority window (see [`mask_authority_windows`]).
315 let after_userinfo = mask_authority_windows(raw);
316 // 2) Redact sensitive query params, keep the rest for diagnosability.
317 let mut out = match after_userinfo.split_once('?') {
318 Some((base, query)) => {
319 let redacted: Vec<String> = query
320 .split('&')
321 .map(|pair| {
322 let raw_key = pair.split('=').next().unwrap_or(pair);
323 let match_key = decode_match_key(raw_key);
324 if sensitive_key_substrings
325 .iter()
326 .any(|s| match_key.contains(s))
327 {
328 // Key-position symmetry (bd rc-yvjp3): a
329 // credential-shaped key is fully suppressed — the
330 // key bytes may themselves be the credential.
331 if is_credential_shaped(&minimal_decode_pair(raw_key)) {
332 "<redacted>".to_string()
333 } else {
334 format!("{raw_key}=<redacted>")
335 }
336 } else if is_credential_shaped(&minimal_decode_pair(pair)) {
337 "<redacted>".to_string()
338 } else {
339 pair.to_string()
340 }
341 })
342 .collect();
343 format!("{base}?{}", redacted.join("&"))
344 }
345 None => after_userinfo,
346 };
347 // 3) Fragments are never echoed. Reserve the sentinel bytes before
348 // truncating so the cap never splits the appended `#[redacted]`
349 // (e_gpt stage-4); the kept query content is part of the base.
350 if let Some(i) = out.find('#') {
351 out.truncate(i);
352 truncate_utf8_safe(&mut out, 256 - 11);
353 out.push_str("#[redacted]");
354 }
355 truncate_utf8_safe(&mut out, 256);
356 out
357}
358
359/// Whether a `@` appears in any authority window of `raw`. Windows come
360/// from maximal runs of `/` and `\` characters — the same enumeration the
361/// mask uses: pure-slash runs of two or more characters always open a
362/// window; backslash-bearing runs open one only behind an RFC 3986 scheme
363/// prefix ending immediately before the run. Every run is scanned, so
364/// credentials cannot hide in a later window behind a benign first one
365/// (`http://h/a//user:pass@e/`) or behind a scheme-prefixed backslash
366/// authority (`foo:\u:p@e/`), while scheme-less drive and UNC paths stay
367/// window-free.
368pub fn window_has_at_sign(raw: &str) -> bool {
369 authority_windows(raw)
370 .into_iter()
371 .any(|(start, end)| raw[start..end].contains('@'))
372}
373
374/// Redact a bare host value for logs (ADR-0076, `lint-log-redaction`).
375/// A bare host carries no `//` authority window, so [`redact_url`] is a
376/// semantic no-op on it; this helper masks everything before the LAST
377/// `@` instead (`***@host`). The host grammar carries no userinfo, but
378/// the value can be externally influenced (a config field the URI
379/// parser can route `user:pass@host` into), so userinfo-shaped input is
380/// masked defensively — through the LAST `@`, because over-masking is
381/// safe and under-masking is not. Clean hosts pass through unchanged
382/// for diagnosability. Canonical single source: components log `host`
383/// fields through this helper, not crate-local twins (bd rc-8bxeo).
384pub fn redact_host(host: &str) -> String {
385 match host.rsplit_once('@') {
386 Some((_, after)) => format!("***@{after}"),
387 None => host.to_string(),
388 }
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 /// Key denylist used by the camel-jms broker redactor (7 entries, same
396 /// order as the landed `redact_broker_url` list).
397 const JMS_KEYS: &[&str] = &[
398 "password",
399 "passwd",
400 "secret",
401 "credential",
402 "token",
403 "username",
404 "user",
405 ];
406
407 // ── Spec-pinned scenarios (redact2 security requirement) ─────────────
408
409 #[test]
410 fn strict_masks_windows_and_composes_sentinels() {
411 assert_eq!(
412 redact_url("https://user:pass@h/p?a=1#t=x"),
413 "https://***@h/p?[redacted]#[redacted]"
414 );
415 // A later `//` window is masked too: credentials cannot hide behind
416 // a benign first window.
417 assert_eq!(redact_url("https://h//u2:p2@evil/"), "https://h//***@evil/");
418 }
419
420 #[test]
421 fn fail_closed_suppresses_window_with_at() {
422 assert_eq!(
423 redact_url_fail_closed("http://u:secretpw@host:99999/x"),
424 "[redacted]"
425 );
426 }
427
428 #[test]
429 fn sentinel_never_splits_at_cap() {
430 // Pre-sentinel base (up to the earliest `?`) is 316 bytes; the
431 // 3-byte `日` straddles the reserved cut at byte 234, forcing the
432 // boundary walk. Both sentinels must render intact.
433 let mut url = format!("https://host/{}日{}", "x".repeat(220), "x".repeat(80));
434 url.push_str("?a=1#f");
435 assert!(url.len() > 300);
436 let redacted = redact_url(&url);
437 assert!(redacted.len() <= 256, "len={}", redacted.len());
438 assert!(
439 redacted.ends_with("?[redacted]#[redacted]"),
440 "sentinels must render intact: {redacted}"
441 );
442 assert!(std::str::from_utf8(redacted.as_bytes()).is_ok());
443 assert!(
444 !redacted.contains('日'),
445 "straddling char dropped whole: {redacted}"
446 );
447 assert!(
448 redacted.starts_with("https://host/"),
449 "host kept: {redacted}"
450 );
451 }
452
453 #[test]
454 fn idempotent_mask_composition_pin() {
455 // An already-masked window rewrites to itself and the sentinels
456 // still compose.
457 assert_eq!(
458 redact_url("https://***@host/p?a=1#f"),
459 "https://***@host/p?[redacted]#[redacted]"
460 );
461 }
462
463 #[test]
464 fn allowlist_keeps_benign_and_redacts_sensitive() {
465 assert_eq!(
466 redact_url_with_query_allowlist(
467 "tcp://host:61616?password=p&user=u&keepAlive=true",
468 JMS_KEYS
469 ),
470 "tcp://host:61616?password=<redacted>&user=<redacted>&keepAlive=true"
471 );
472 }
473
474 // ── Phase 2: minimal-decode rule (bd rc-r7v8s) ──────────────────────
475
476 /// Percent-encoded credentials under a benign key must not smuggle
477 /// through: the single-pass minimal decode of the pair carries `@` and
478 /// `//`, so the whole pair redacts. Uppercase hex form.
479 #[test]
480 fn allowlist_masks_percent_encoded_credentials_uppercase() {
481 let redacted = redact_url_with_query_allowlist(
482 "tcp://h:61616?redirect=http%3A%2F%2Fuser%3Asecret%40host",
483 JMS_KEYS,
484 );
485 assert!(
486 !redacted.contains("secret"),
487 "percent-encoded credential leaked: {redacted}"
488 );
489 assert!(
490 !redacted.contains("user%3Asecret%40"),
491 "encoded userinfo leaked: {redacted}"
492 );
493 assert_eq!(redacted, "tcp://h:61616?<redacted>");
494 }
495
496 /// Fully-lowercase hex variant of the same smuggling shape.
497 #[test]
498 fn allowlist_masks_percent_encoded_credentials_lowercase() {
499 let redacted = redact_url_with_query_allowlist(
500 "tcp://h:61616?redirect=http%3a%2f%2fuser%3asecret%40host",
501 JMS_KEYS,
502 );
503 assert_eq!(redacted, "tcp://h:61616?<redacted>");
504 assert!(
505 !redacted.contains("secret"),
506 "percent-encoded credential leaked: {redacted}"
507 );
508 }
509
510 /// bd rc-yvjp3 (ADR-0076 appendix, key-position symmetry): a pair
511 /// whose KEY embeds credentials (`user%3Asecret%40host` decodes to
512 /// `user:secret@host`) renders as a bare `<redacted>` — the key bytes
513 /// never echo, in either hex case.
514 #[test]
515 fn allowlist_suppresses_credential_shaped_key_uppercase() {
516 let redacted =
517 redact_url_with_query_allowlist("tcp://h:61616?user%3Asecret%40host=1", JMS_KEYS);
518 assert_eq!(redacted, "tcp://h:61616?<redacted>");
519 assert!(
520 !redacted.contains("user%3Asecret%40"),
521 "credential-shaped key leaked: {redacted}"
522 );
523 assert!(
524 !redacted.contains("secret"),
525 "key credential bytes leaked: {redacted}"
526 );
527 }
528
529 /// Fully-lowercase hex variant of the key-position shape.
530 #[test]
531 fn allowlist_suppresses_credential_shaped_key_lowercase() {
532 let redacted =
533 redact_url_with_query_allowlist("tcp://h:61616?user%3asecret%40host=1", JMS_KEYS);
534 assert_eq!(redacted, "tcp://h:61616?<redacted>");
535 }
536
537 /// Key-position symmetry, literal form: a fully literal
538 /// `user:pass@host` key is suppressed whole.
539 #[test]
540 fn allowlist_suppresses_literal_credential_shaped_key() {
541 let redacted = redact_url_with_query_allowlist("tcp://h:61616?user:pass@host=1", JMS_KEYS);
542 assert_eq!(redacted, "tcp://h:61616?<redacted>");
543 assert!(
544 !redacted.contains("user:pass"),
545 "literal key credentials leaked: {redacted}"
546 );
547 }
548
549 /// bd rc-yvjp3 non-regression: well-known sensitive keys that are NOT
550 /// credential-shaped keep echoing their names — the ADR-0076 exception
551 /// names transport-policy parameter visibility as the sole diagnostic
552 /// value of the broker URL, and no real parameter name decodes to an
553 /// `@`+`:`/`//` shape.
554 #[test]
555 fn allowlist_keeps_well_known_key_names_visible() {
556 let redacted = redact_url_with_query_allowlist(
557 "tcp://h:61616?password=p&jms.userName=admin&user=u&keepAlive=true",
558 JMS_KEYS,
559 );
560 assert_eq!(
561 redacted,
562 "tcp://h:61616?password=<redacted>&jms.userName=<redacted>&user=<redacted>&keepAlive=true"
563 );
564 }
565
566 /// bd rc-yvjp3 boundary pin: a denylist-matching key with a lone `@`
567 /// (no `:`, no `//`) is NOT credential-shaped — it renders
568 /// `user@host=<redacted>` and the key echoes, mirroring the lone-`@`
569 /// email rule of the benign-key branch.
570 #[test]
571 fn allowlist_keeps_lone_at_key_visible() {
572 let redacted = redact_url_with_query_allowlist("tcp://h:61616?user@host=1", JMS_KEYS);
573 assert_eq!(redacted, "tcp://h:61616?user@host=<redacted>");
574 }
575
576 /// bd rc-yvjp3 non-regression: an encoded-but-not-credential-shaped
577 /// key (`%77` is outside the minimal-decode triple) still echoes its
578 /// authored bytes when the decoded name hits the denylist — the
579 /// `pass%77ord` match rule (bd rc-r7v8s) is unchanged.
580 #[test]
581 fn allowlist_keeps_encoded_but_benign_shaped_key_visible() {
582 let redacted = redact_url_with_query_allowlist("tcp://h:61616?pass%77ord=p", JMS_KEYS);
583 assert_eq!(redacted, "tcp://h:61616?pass%77ord=<redacted>");
584 }
585
586 /// Encoded slashes plus a literal `@` decode to a `//`-bearing
587 /// credential shape under a benign key.
588 #[test]
589 fn allowlist_masks_literal_at_bypass() {
590 let redacted =
591 redact_url_with_query_allowlist("tcp://h:61616?next=%2F%2Fuser:pass@host", JMS_KEYS);
592 assert_eq!(redacted, "tcp://h:61616?<redacted>");
593 assert!(
594 !redacted.contains("pass"),
595 "literal credential leaked: {redacted}"
596 );
597 }
598
599 /// Fully literal `user:pass@host` under a benign key.
600 #[test]
601 fn allowlist_masks_fully_literal_credential_pair() {
602 let redacted =
603 redact_url_with_query_allowlist("tcp://h:61616?next=user:pass@host", JMS_KEYS);
604 assert_eq!(redacted, "tcp://h:61616?<redacted>");
605 assert!(
606 !redacted.contains("pass"),
607 "literal credential leaked: {redacted}"
608 );
609 }
610
611 /// Regression pin at the under-redaction boundary: `@` without `:` or
612 /// `//` is an email address, not a credential — the pair stays visible.
613 #[test]
614 fn allowlist_keeps_lone_email_value() {
615 assert_eq!(
616 redact_url_with_query_allowlist("tcp://h:61616?contact=admin%40corp.example", JMS_KEYS),
617 "tcp://h:61616?contact=admin%40corp.example"
618 );
619 }
620
621 /// Over-mask stance (ADR-0051): a value decoding to `user@host:port`
622 /// is credential-shaped even though no literal `//` or `:` is present.
623 #[test]
624 fn allowlist_masks_credential_shaped_userhostport() {
625 let redacted =
626 redact_url_with_query_allowlist("tcp://h:61616?next=user%40host%3Aport", JMS_KEYS);
627 assert_eq!(redacted, "tcp://h:61616?<redacted>");
628 }
629
630 /// A percent-encoded sensitive key decodes to `password` and must
631 /// redact; the rendered key keeps its original encoded bytes.
632 #[test]
633 fn allowlist_decodes_percent_encoded_sensitive_key() {
634 let redacted =
635 redact_url_with_query_allowlist("tcp://host:61616?pass%77ord=shortsecret", JMS_KEYS);
636 assert!(
637 redacted.contains("pass%77ord=<redacted>"),
638 "encoded key must redact keeping original bytes: {redacted}"
639 );
640 assert!(
641 !redacted.contains("shortsecret"),
642 "secret value leaked: {redacted}"
643 );
644 }
645
646 /// Regression pin (redact2): non-ASCII bytes in a pair are preserved
647 /// byte-for-byte (valid UTF-8), never Latin-1-transcoded, and a decoded
648 /// invalid byte becomes `U+FFFD` — the decoded output feeds only ASCII
649 /// shape checks, so neither case can flip a redaction decision.
650 #[test]
651 fn minimal_decode_preserves_non_ascii_bytes() {
652 // `é` (0xC3 0xA9) must survive as itself, not as `é`.
653 assert_eq!(minimal_decode_pair("café"), "café");
654 // Escapes still decode around non-ASCII bytes.
655 assert_eq!(minimal_decode_pair("café%40x"), "café@x");
656 // A decoded invalid byte (0xFF from `%FF`) becomes U+FFFD, which
657 // cannot match an ASCII needle (exercised via the full-hex decoder).
658 assert_eq!(decode_match_key("a%FFb"), "a\u{FFFD}b");
659 }
660
661 // ── Migrated: camel-config config_tests/url_redaction_tests.rs ──────
662
663 #[test]
664 fn redact_url_keeps_userinfo_mask_shape() {
665 assert_eq!(
666 redact_url("redis://user:secret@h:6379"),
667 "redis://***@h:6379"
668 );
669 }
670
671 /// Intentional semantic change: the query was previously echoed verbatim,
672 /// leaking `?password=...` cache credentials into Debug output.
673 #[test]
674 fn redact_url_drops_query_secrets() {
675 assert_eq!(
676 redact_url("redis://h:6379/0?password=hunter2"),
677 "redis://h:6379/0?[redacted]"
678 );
679 }
680
681 #[test]
682 fn redact_url_drops_fragment() {
683 assert_eq!(
684 redact_url("redis://h:6379/0#tok=x"),
685 "redis://h:6379/0#[redacted]"
686 );
687 }
688
689 /// Multiple `@` in the window: mask through the LAST one — over-masking is
690 /// safe, under-masking is not.
691 #[test]
692 fn redact_url_masks_through_last_at() {
693 assert_eq!(redact_url("redis://user:p@ss@h:6379"), "redis://***@h:6379");
694 }
695
696 /// Bare-host masking (bd rc-8bxeo, promoted from the camel-ws /
697 /// camel-http twins): clean hosts pass through unchanged for
698 /// diagnosability; userinfo-shaped values mask through the LAST `@`.
699 #[test]
700 fn redact_host_masks_userinfo_keeps_clean_hosts() {
701 assert_eq!(redact_host("localhost"), "localhost");
702 assert_eq!(redact_host("broker.example.com"), "broker.example.com");
703 assert_eq!(redact_host("host.example:8080"), "host.example:8080");
704 assert_eq!(redact_host("user:pass@host"), "***@host");
705 assert_eq!(redact_host("bob:p@ss@host"), "***@host");
706 assert_eq!(redact_host("a@b@c"), "***@c");
707 }
708
709 /// A slash run after `//` must not hide userinfo behind it; extra leading
710 /// slashes are kept byte-for-byte.
711 #[test]
712 fn redact_url_slash_run_evader_masked() {
713 assert_eq!(
714 redact_url("redis:////user:pass@h:6379/0"),
715 "redis:////***@h:6379/0"
716 );
717 }
718
719 /// An `@` outside any `//` window (path data here) is not userinfo.
720 #[test]
721 fn redact_url_at_outside_window_visible() {
722 assert_eq!(
723 redact_url("redis://h:6379/0/user@x"),
724 "redis://h:6379/0/user@x"
725 );
726 }
727
728 /// A `//` window after the first is scanned too: credentials cannot hide
729 /// behind a benign first window.
730 #[test]
731 fn redact_url_later_window_masked() {
732 assert_eq!(redact_url("redis://h//user:pass@x/"), "redis://h//***@x/");
733 }
734
735 /// Compose-both rule: one sentinel per distinct introducer found in the
736 /// raw URL, in first-occurrence order.
737 #[test]
738 fn redact_url_sentinels_compose_both() {
739 assert_eq!(
740 redact_url("redis://h:6379/0?password=x#tok=y"),
741 "redis://h:6379/0?[redacted]#[redacted]"
742 );
743 }
744
745 #[test]
746 fn redact_url_sentinels_compose_fragment_first() {
747 assert_eq!(
748 redact_url("redis://h:6379/0#tok=y?password=x"),
749 "redis://h:6379/0#[redacted]?[redacted]"
750 );
751 }
752
753 /// The 256-byte cap must land on a UTF-8 char boundary: a 3-byte char
754 /// straddling byte 256 forces the cut to walk back instead of panicking.
755 #[test]
756 fn redact_url_truncates_256_utf8_safe() {
757 let mut url = format!("redis://{}{}", "x".repeat(246), '日');
758 url.push_str(&"tail".repeat(20));
759 assert!(url.len() > 300);
760 let redacted = redact_url(&url);
761 assert!(redacted.len() <= 256, "len={}", redacted.len());
762 assert!(redacted.starts_with("redis://"));
763 }
764
765 /// e_gpt stage-4: the 256-byte cap must not split an appended sentinel.
766 /// The base is truncated at `256 - sentinel_len` BEFORE the sentinel is
767 /// appended, so the sentinel always renders intact and the total stays
768 /// ≤ 256.
769 #[test]
770 fn redact_url_keeps_sentinel_intact_under_256_cap() {
771 // Base (masked, cut at the `?`) is 248 bytes, so byte 256 lands inside
772 // the appended `?[redacted]` (starts at 248) pre-fix.
773 let url = format!("http://{}?x=1", "a".repeat(240));
774 let redacted = redact_url(&url);
775 assert!(redacted.len() <= 256, "len={}", redacted.len());
776 assert!(
777 redacted.ends_with("?[redacted]"),
778 "sentinel must render intact: {redacted}"
779 );
780 }
781
782 // ── Migrated: camel-jms config.rs broker allowlist tests ────────────
783
784 /// Audit 2026-08-31, F5-3: JMS broker URLs must not leak credentials
785 /// through Debug output.
786 #[test]
787 fn redact_broker_url_masks_userinfo_and_sensitive_query() {
788 // userinfo form
789 let redacted = redact_url_with_query_allowlist(
790 "tcp://admin:secretpass@broker.example.com:61616",
791 JMS_KEYS,
792 );
793 assert!(
794 !redacted.contains("secretpass"),
795 "password masked: {redacted}"
796 );
797 assert!(
798 redacted.contains("broker.example.com"),
799 "host visible: {redacted}"
800 );
801
802 // failover + query-param form (ActiveMQ style)
803 let redacted = redact_url_with_query_allowlist(
804 "failover:(tcp://host:61616)?jms.userName=admin&jms.password=secret&keepAlive=true",
805 JMS_KEYS,
806 );
807 assert!(
808 !redacted.contains("secret"),
809 "password param masked: {redacted}"
810 );
811 assert!(
812 !redacted.contains("=admin"),
813 "username param masked: {redacted}"
814 );
815 assert!(
816 redacted.contains("keepAlive=true"),
817 "benign param kept: {redacted}"
818 );
819
820 // clean URL untouched
821 assert_eq!(
822 redact_url_with_query_allowlist("tcp://host:61616", JMS_KEYS),
823 "tcp://host:61616"
824 );
825 }
826
827 /// Exact-output pin: userinfo is fully masked by `***`, never partially
828 /// truncated, in scheme://...@ authority position.
829 #[test]
830 fn redact_exact_userinfo_mask() {
831 assert_eq!(
832 redact_url_with_query_allowlist(
833 "tcp://admin:secretpass@broker.example.com:61616",
834 JMS_KEYS
835 ),
836 "tcp://***@broker.example.com:61616"
837 );
838 }
839
840 /// Exact-output pin: sensitive query params redact to `<redacted>`,
841 /// benign params survive byte-for-byte, `&` separators preserved.
842 #[test]
843 fn redact_exact_query_join() {
844 assert_eq!(
845 redact_url_with_query_allowlist(
846 "tcp://host:61616?password=p&user=u&keepAlive=true",
847 JMS_KEYS
848 ),
849 "tcp://host:61616?password=<redacted>&user=<redacted>&keepAlive=true"
850 );
851 }
852
853 /// Exact-output pin: a bare `user@host` (no scheme) is NOT an authority
854 /// position — passthrough untouched.
855 #[test]
856 fn redact_exact_bare_at_passthrough() {
857 assert_eq!(
858 redact_url_with_query_allowlist("admin@host", JMS_KEYS),
859 "admin@host"
860 );
861 }
862
863 /// Exact-output pin: delimiter-exact query redaction on the ActiveMQ
864 /// failover form — the whole query part after '?' must match verbatim,
865 /// no dropped params, no mangled separators.
866 #[test]
867 fn redact_exact_failover_param_boundaries() {
868 let redacted = redact_url_with_query_allowlist(
869 "failover:(tcp://host:61616)?jms.userName=admin&jms.password=secret&keepAlive=true",
870 JMS_KEYS,
871 );
872 let (_, query) = redacted.split_once('?').expect("query segment after '?'");
873 assert_eq!(
874 query,
875 "jms.userName=<redacted>&jms.password=<redacted>&keepAlive=true"
876 );
877 }
878
879 /// bd rc-eh49 exact pin: an `@` riding the query is NOT userinfo — the
880 /// URL must pass through byte-for-byte. The old whole-string
881 /// `split_once('@')` mangled this to `failover:(tcp://***@b`.
882 #[test]
883 fn redact_broker_url_query_at_no_misfire() {
884 assert_eq!(
885 redact_url_with_query_allowlist("failover:(tcp://h:61616)?x=a@b", JMS_KEYS),
886 "failover:(tcp://h:61616)?x=a@b"
887 );
888 }
889
890 /// bd rc-eh49 exact pin: a slash run after `//` is preserved
891 /// byte-for-byte and the windowed mask composes with the per-key query
892 /// allowlist. The old whole-string scan rewrote from the scheme's own
893 /// `://` and swallowed the extra slashes.
894 #[test]
895 fn redact_exact_slash_run_window_composition() {
896 assert_eq!(
897 redact_url_with_query_allowlist("tcp:////user:pass@h:61616?keepAlive=true", JMS_KEYS),
898 "tcp:////***@h:61616?keepAlive=true"
899 );
900 }
901
902 /// bd rc-eh49 exact pin: the window mask consumes through the LAST `@`
903 /// of the window, so an `@` embedded in the userinfo cannot keep a
904 /// spoofable prefix alive (the old first-`@` scan left `a@` visible).
905 #[test]
906 fn redact_exact_last_at_in_window() {
907 assert_eq!(
908 redact_url_with_query_allowlist("tcp://u:p@a@h:61616", JMS_KEYS),
909 "tcp://***@h:61616"
910 );
911 }
912
913 /// bd rc-eh49: the 256-byte cap cuts on a char boundary — a multibyte
914 /// character straddling byte 256 is dropped whole, never split
915 /// mid-encode.
916 #[test]
917 fn redact_broker_url_truncate_multibyte_boundary() {
918 let mut url = String::from("tcp://broker:61616/");
919 url.push_str(&"x".repeat(236)); // 255 ASCII bytes before the multibyte char
920 url.push('日'); // 3 bytes straddling the 256-byte cap
921 url.push_str(&"y".repeat(50)); // push the total past 300 bytes
922 assert!(url.len() > 300);
923 let redacted = redact_url_with_query_allowlist(&url, JMS_KEYS);
924 assert!(redacted.len() <= 256, "len={}", redacted.len());
925 assert!(std::str::from_utf8(redacted.as_bytes()).is_ok());
926 assert!(
927 !redacted.contains('日'),
928 "straddling char dropped whole: {redacted}"
929 );
930 }
931
932 /// bd rc-eh49: a `//` window after the first is scanned too; the
933 /// benign query stays visible per the broker allowlist exception.
934 #[test]
935 fn redact_broker_url_later_window_masked() {
936 assert_eq!(
937 redact_url_with_query_allowlist("tcp://h//user:pass@x/?keepAlive=true", JMS_KEYS),
938 "tcp://h//***@x/?keepAlive=true"
939 );
940 }
941
942 /// bd rc-eh49: fragments are never echoed — everything from the first
943 /// `#` is dropped and the `#[redacted]` sentinel appended; processed
944 /// query params stay visible.
945 #[test]
946 fn redact_broker_url_drops_fragment() {
947 assert_eq!(
948 redact_url_with_query_allowlist("tcp://h:61616?keepAlive=true#tok=x", JMS_KEYS),
949 "tcp://h:61616?keepAlive=true#[redacted]"
950 );
951 }
952
953 /// bd rc-eh49: broker URLs are capped at 256 bytes on a UTF-8 char
954 /// boundary.
955 #[test]
956 fn redact_broker_url_truncates() {
957 let mut url = format!("tcp://broker:61616/{}", "x".repeat(300));
958 url.push('日');
959 url.push_str(&"tail".repeat(20));
960 assert!(url.len() > 300);
961 let redacted = redact_url_with_query_allowlist(&url, JMS_KEYS);
962 assert!(redacted.len() <= 256, "len={}", redacted.len());
963 assert!(redacted.starts_with("tcp://broker:61616/"));
964 }
965
966 // ── Migrated: camel-jms component.rs redact_url_* block ─────────────
967
968 #[test]
969 fn redact_url_strips_userinfo_with_password() {
970 assert_eq!(
971 redact_url("tcp://admin:s3cret@broker:61616"),
972 "tcp://***@broker:61616"
973 );
974 }
975
976 #[test]
977 fn redact_url_strips_userinfo_without_password() {
978 assert_eq!(
979 redact_url("tcp://admin@broker:61616"),
980 "tcp://***@broker:61616"
981 );
982 }
983
984 #[test]
985 fn redact_url_passes_clean_url_unchanged() {
986 assert_eq!(redact_url("tcp://localhost:61616"), "tcp://localhost:61616");
987 }
988
989 #[test]
990 fn redact_url_handles_ssl_scheme() {
991 assert_eq!(
992 redact_url("ssl://user:pass@secure-broker:61617"),
993 "ssl://***@secure-broker:61617"
994 );
995 }
996
997 /// bd rc-eh49: the earliest `?`/`#` introducer wins; both sentinels
998 /// compose in first-occurrence order when the raw URL carries both
999 /// introducers, and fragment bytes after the cut are dropped with it.
1000 #[test]
1001 fn redact_url_drops_query_and_fragment() {
1002 assert_eq!(
1003 redact_url("tcp://broker:61616?user=a#tok=x"),
1004 "tcp://broker:61616?[redacted]#[redacted]"
1005 );
1006 }
1007
1008 /// bd rc-eh49 compose-both rule: a `#` before `?` flips the sentinel
1009 /// order accordingly. (Name prefixed `jms_`: the redis fixture from
1010 /// camel-config already owns the unprefixed name above.)
1011 #[test]
1012 fn jms_redact_url_sentinels_compose_fragment_first() {
1013 assert_eq!(
1014 redact_url("tcp://broker:61616#tok=x?user=a"),
1015 "tcp://broker:61616#[redacted]?[redacted]"
1016 );
1017 }
1018
1019 /// bd rc-eh49: a `//` window after the first is scanned too —
1020 /// credentials cannot hide behind a benign first window. (Name prefixed
1021 /// `jms_`: the redis fixture from camel-config already owns the
1022 /// unprefixed name above.)
1023 #[test]
1024 fn jms_redact_url_later_window_masked() {
1025 assert_eq!(redact_url("tcp://h//user:pass@x/"), "tcp://h//***@x/");
1026 }
1027
1028 /// bd rc-eh49: a slash run after `//` cannot hide userinfo from the
1029 /// window scan.
1030 #[test]
1031 fn redact_url_slash_run_masked() {
1032 let redacted = redact_url("tcp:////user:pass@broker:61616");
1033 assert!(!redacted.contains("user:pass"), "leaked: {redacted}");
1034 assert!(
1035 redacted.contains("***@broker:61616"),
1036 "masked in place: {redacted}"
1037 );
1038 }
1039
1040 /// bd rc-eh49: the old first-`@`-anywhere scan masked through an `@`
1041 /// riding the query (`tcp://***@b`); only a window `@` is userinfo.
1042 #[test]
1043 fn redact_url_at_in_query_not_userinfo_mask() {
1044 assert_eq!(
1045 redact_url("tcp://broker:61616?q=a@b"),
1046 "tcp://broker:61616?[redacted]"
1047 );
1048 }
1049
1050 /// bd rc-eh49: the 256-byte cap cuts on a char boundary — a multibyte
1051 /// character straddling byte 256 is dropped whole, never split
1052 /// mid-encode.
1053 #[test]
1054 fn redact_url_truncate_multibyte_boundary() {
1055 let mut url = String::from("tcp://broker:61616/");
1056 url.push_str(&"x".repeat(236)); // 255 ASCII bytes before the multibyte char
1057 url.push('日'); // 3 bytes straddling the 256-byte cap
1058 url.push_str(&"y".repeat(50)); // push the total past 300 bytes
1059 assert!(url.len() > 300);
1060 let redacted = redact_url(&url);
1061 assert!(redacted.len() <= 256, "len={}", redacted.len());
1062 assert!(std::str::from_utf8(redacted.as_bytes()).is_ok());
1063 assert!(
1064 !redacted.contains('日'),
1065 "straddling char dropped whole: {redacted}"
1066 );
1067 }
1068
1069 /// e_gpt stage-4: the 256-byte cap must not split an appended sentinel.
1070 /// The base is truncated at `256 - sentinel_len` BEFORE the sentinel is
1071 /// appended, so the sentinel always renders intact and the total stays
1072 /// ≤ 256. Covers both redactors: `redact_url` (compose sentinels) and
1073 /// `redact_url_with_query_allowlist` (fragment sentinel over kept query
1074 /// content).
1075 #[test]
1076 fn redact_url_keeps_sentinels_intact_under_256_cap() {
1077 // `redact_url`: base (masked, cut at the `?`) is 255 bytes, so byte
1078 // 256 lands inside the appended `?[redacted]` (starts at 255) pre-fix.
1079 let url = format!("tcp://{}?x=1", "a".repeat(250));
1080 let redacted = redact_url(&url);
1081 assert!(redacted.len() <= 256, "len={}", redacted.len());
1082 assert!(
1083 redacted.ends_with("?[redacted]"),
1084 "redact_url sentinel must render intact: {redacted}"
1085 );
1086
1087 // `redact_url_with_query_allowlist`: base + kept query is 252 bytes,
1088 // so byte 256 lands inside the appended `#[redacted]` (starts at
1089 // 252) pre-fix.
1090 let broker = format!("tcp://{}?keep=1#frag", "a".repeat(240));
1091 let redacted = redact_url_with_query_allowlist(&broker, JMS_KEYS);
1092 assert!(redacted.len() <= 256, "len={}", redacted.len());
1093 assert!(
1094 redacted.ends_with("#[redacted]"),
1095 "allowlist sentinel must render intact: {redacted}"
1096 );
1097 }
1098
1099 // ── Migrated: camel-http lib.rs pure-string redact tests ────────────
1100 // These landed against the Err arm of `redact_url_for_diagnostics`
1101 // (unparseable inputs); that arm delegates to `redact_url` /
1102 // `redact_url_fail_closed`, so the fixtures pin the canonical helpers
1103 // byte-identically. The `url::Url::parse` precondition asserts of the
1104 // landed tests do not apply here: this module never parses.
1105
1106 #[test]
1107 fn redact_url_unparseable_fragment_credentials_dropped() {
1108 let raw = "ht tps://app.example/cb#access_token=SECRET";
1109 let redacted = redact_url(raw);
1110 assert!(
1111 !redacted.contains("SECRET"),
1112 "unparseable fragment token leaked: {redacted}"
1113 );
1114 assert!(
1115 !redacted.contains("access_token"),
1116 "unparseable fragment bytes leaked: {redacted}"
1117 );
1118 assert!(
1119 redacted.contains("#[redacted]"),
1120 "unparseable fragment must end in the sentinel: {redacted}"
1121 );
1122 }
1123
1124 #[test]
1125 fn redact_url_empty_host_userinfo_sentinel() {
1126 // The landed http test drives this through the parse-failure arm;
1127 // the canonical helper fails closed on the window `@` directly.
1128 let redacted = redact_url_fail_closed("scheme://user@");
1129 assert_eq!(
1130 redacted, "[redacted]",
1131 "empty-host userinfo must fail closed: {redacted}"
1132 );
1133 }
1134
1135 #[test]
1136 fn redact_url_unparseable_slash_run_evader_sentinel() {
1137 let raw = "schem e:////user:pass@evil/";
1138 let redacted = redact_url_fail_closed(raw);
1139 assert_eq!(
1140 redacted, "[redacted]",
1141 "unparseable slash-run evader must fail closed: {redacted}"
1142 );
1143 }
1144
1145 #[test]
1146 fn redact_url_unparseable_later_window_userinfo_sentinel() {
1147 // The first `//` window ("ho st") carries no `@`, but a later
1148 // `//user:pass@evil/` window does. The scan must consider every
1149 // `//` window, not just the first, or the credentials echo.
1150 let raw = "http://ho st/a//user:pass@evil/";
1151 let redacted = redact_url_fail_closed(raw);
1152 assert_eq!(
1153 redacted, "[redacted]",
1154 "userinfo in a later // window must fail closed: {redacted}"
1155 );
1156 }
1157
1158 #[test]
1159 fn redact_url_truncates_unparseable() {
1160 let long = "x".repeat(1000);
1161 let redacted = redact_url(&long);
1162 assert_eq!(redacted.len(), 256, "unparseable URL must be truncated");
1163 }
1164
1165 #[test]
1166 fn redact_url_suppresses_unparseable_authority_credentials() {
1167 let fixtures = [
1168 "http://u:secretpw@/x",
1169 "http://u:secretpw@host:99999/x",
1170 "http://u:secretpw@host:99999",
1171 "//u:secretpw@h/x",
1172 ];
1173 for fixture in fixtures {
1174 assert_eq!(
1175 redact_url_fail_closed(fixture),
1176 "[redacted]",
1177 "credential-bearing authority must be suppressed: {fixture}"
1178 );
1179 }
1180 }
1181
1182 #[test]
1183 fn redact_url_unparseable_query_redacted_short_and_long() {
1184 let short = "http://host:99999/path?token=shortsecret";
1185 let redacted = redact_url(short);
1186 assert_eq!(
1187 redacted, "http://host:99999/path?[redacted]",
1188 "short unparseable query must end with the suffix: {redacted}"
1189 );
1190
1191 let mut long = String::from("http://host:99999/");
1192 long.push_str(&"a".repeat(300));
1193 long.push_str("?token=longsecret");
1194 let redacted = redact_url(&long);
1195 assert!(
1196 !redacted.contains("longsecret"),
1197 "long unparseable query leaked a query byte: {redacted}"
1198 );
1199 assert!(
1200 redacted.len() <= 256,
1201 "long unparseable query must be capped: {} bytes",
1202 redacted.len()
1203 );
1204 }
1205
1206 #[test]
1207 fn redact_url_unparseable_sentinels_compose_both() {
1208 // Compose-both rule: one sentinel per distinct introducer found in
1209 // the raw string, in first-occurrence order.
1210 let raw = "ht tp://h.example/p?a=1#tok=x";
1211 assert_eq!(
1212 redact_url(raw),
1213 "ht tp://h.example/p?[redacted]#[redacted]",
1214 "query and fragment sentinels must compose: {raw}"
1215 );
1216 }
1217
1218 #[test]
1219 fn redact_url_unparseable_sentinels_compose_fragment_first() {
1220 let raw = "ht tp://h.example/p#tok=x?a=1";
1221 assert_eq!(
1222 redact_url(raw),
1223 "ht tp://h.example/p#[redacted]?[redacted]",
1224 "sentinels must follow the introducers' first-occurrence order: {raw}"
1225 );
1226 }
1227
1228 #[test]
1229 fn redact_url_unparseable_utf8_straddle_no_panic() {
1230 let fixture = format!("a{}", "é".repeat(200));
1231 let redacted = redact_url(&fixture);
1232 assert!(
1233 redacted.len() <= 256,
1234 "straddle fixture must be capped: {} bytes",
1235 redacted.len()
1236 );
1237 assert!(
1238 redacted.len() >= 253,
1239 "straddle fixture must not over-truncate: {} bytes",
1240 redacted.len()
1241 );
1242 assert!(
1243 fixture.is_char_boundary(redacted.len()),
1244 "cut must land on a UTF-8 char boundary: {} bytes",
1245 redacted.len()
1246 );
1247 }
1248
1249 #[test]
1250 fn redact_url_at_sign_outside_authority_window_visible() {
1251 let at_sign_in_path = "http://host:99999/x@y";
1252 assert_eq!(
1253 redact_url_fail_closed(at_sign_in_path),
1254 at_sign_in_path,
1255 "at-sign in path must not be suppressed"
1256 );
1257 // Opaque non-hierarchical strings pass through byte-identically.
1258 assert_eq!(
1259 redact_url("mailto:user@example.com"),
1260 "mailto:user@example.com",
1261 "at-sign in mailto must round-trip byte-identically"
1262 );
1263 }
1264
1265 // ── Phase 3: scheme-gated backslash windows (rc-f05q8) ──────────────
1266
1267 /// A backslash authority after a non-special scheme opens a window:
1268 /// `foo:\user:pass@evil/` carries no `//` run, yet the scheme-prefixed
1269 /// backslash run must mask the userinfo. The fail-closed variant
1270 /// suppresses the whole string; the clean sibling stays visible.
1271 #[test]
1272 fn backslash_run_non_special_scheme_masked() {
1273 assert_eq!(
1274 redact_url("foo:\\user:pass@evil/"),
1275 "foo:\\***@evil/",
1276 "non-special-scheme backslash authority must mask userinfo"
1277 );
1278 assert_eq!(
1279 redact_url_fail_closed("foo:\\user:pass@evil/"),
1280 "[redacted]",
1281 "non-special-scheme backslash authority must fail closed"
1282 );
1283 assert_eq!(
1284 redact_url("foo:\\clean/path"),
1285 "foo:\\clean/path",
1286 "clean backslash sibling stays visible"
1287 );
1288 }
1289
1290 /// A single backslash after a multi-character scheme opens a window
1291 /// even though the run is one character long.
1292 #[test]
1293 fn backslash_single_after_multi_char_scheme_masked() {
1294 let redacted = redact_url("http:\\user:pass@evil\\path");
1295 assert!(
1296 !redacted.contains("user:pass"),
1297 "single-backslash authority leaked: {redacted}"
1298 );
1299 assert!(
1300 redacted.contains("***@"),
1301 "single-backslash authority must mask userinfo: {redacted}"
1302 );
1303 }
1304
1305 /// A single backslash after a one-character scheme opens a window when
1306 /// the candidate window content is credential-shaped (`:` before the
1307 /// last `@`).
1308 #[test]
1309 fn backslash_single_after_one_char_scheme_credential_shaped_masked() {
1310 let redacted = redact_url("x:\\user:pass@evil");
1311 assert!(
1312 !redacted.contains("user:pass"),
1313 "one-char-scheme backslash authority leaked: {redacted}"
1314 );
1315 assert!(
1316 redacted.contains("***@"),
1317 "one-char-scheme backslash authority must mask userinfo: {redacted}"
1318 );
1319 }
1320
1321 /// Windows drive path: single backslash after a one-character scheme
1322 /// with no `:` in the candidate window — no qualifying window, the
1323 /// string renders unchanged.
1324 #[test]
1325 fn drive_path_stays_visible() {
1326 assert_eq!(
1327 redact_url("C:\\Users\\x@corp\\file"),
1328 "C:\\Users\\x@corp\\file"
1329 );
1330 }
1331
1332 /// UNC path: no scheme prefix before the backslash run — no qualifying
1333 /// window, the string renders unchanged.
1334 #[test]
1335 fn unc_path_stays_visible() {
1336 assert_eq!(redact_url("\\\\server\\x@y"), "\\\\server\\x@y");
1337 }
1338
1339 /// The fail-closed window scan must see scheme-prefixed backslash
1340 /// windows, while drive paths stay window-free.
1341 #[test]
1342 fn window_has_at_sign_sees_backslash_windows() {
1343 assert!(
1344 window_has_at_sign("foo:\\u:p@e/"),
1345 "scheme-prefixed backslash window must carry the at-sign"
1346 );
1347 assert!(
1348 !window_has_at_sign("C:\\Users\\x@corp\\file"),
1349 "drive path must not open a backslash window"
1350 );
1351 }
1352
1353 /// Branch pins for the scheme-gated backslash window rule: a len-2
1354 /// backslash run behind a scheme prefix opens (introducer stays
1355 /// visible), a mixed `/`+`\` run of length 2 behind a 1-char scheme
1356 /// opens, an invalid scheme char before the run gates it off, a
1357 /// scheme-less mixed run stays closed, and a single `\` behind a
1358 /// 1-char scheme with no `:` in the candidate content stays closed.
1359 #[test]
1360 fn backslash_gate_branches_pinned() {
1361 assert_eq!(redact_url("foo:\\\\user:pass@evil/"), "foo:\\\\***@evil/");
1362 assert_eq!(redact_url("a:/\\user:pass@evil/"), "a:/\\***@evil/");
1363 assert_eq!(
1364 redact_url("notscheme%\\user:pass@evil/"),
1365 "notscheme%\\user:pass@evil/"
1366 );
1367 assert_eq!(redact_url("/\\user:pass@evil/"), "/\\user:pass@evil/");
1368 assert_eq!(redact_url("a:\\user@evil"), "a:\\user@evil");
1369 assert!(window_has_at_sign("foo:\\\\u:p@e/"));
1370 assert!(!window_has_at_sign("a:\\user@evil"));
1371 }
1372}