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#[cfg(test)]
375mod tests {
376 use super::*;
377
378 /// Key denylist used by the camel-jms broker redactor (7 entries, same
379 /// order as the landed `redact_broker_url` list).
380 const JMS_KEYS: &[&str] = &[
381 "password",
382 "passwd",
383 "secret",
384 "credential",
385 "token",
386 "username",
387 "user",
388 ];
389
390 // ── Spec-pinned scenarios (redact2 security requirement) ─────────────
391
392 #[test]
393 fn strict_masks_windows_and_composes_sentinels() {
394 assert_eq!(
395 redact_url("https://user:pass@h/p?a=1#t=x"),
396 "https://***@h/p?[redacted]#[redacted]"
397 );
398 // A later `//` window is masked too: credentials cannot hide behind
399 // a benign first window.
400 assert_eq!(redact_url("https://h//u2:p2@evil/"), "https://h//***@evil/");
401 }
402
403 #[test]
404 fn fail_closed_suppresses_window_with_at() {
405 assert_eq!(
406 redact_url_fail_closed("http://u:secretpw@host:99999/x"),
407 "[redacted]"
408 );
409 }
410
411 #[test]
412 fn sentinel_never_splits_at_cap() {
413 // Pre-sentinel base (up to the earliest `?`) is 316 bytes; the
414 // 3-byte `日` straddles the reserved cut at byte 234, forcing the
415 // boundary walk. Both sentinels must render intact.
416 let mut url = format!("https://host/{}日{}", "x".repeat(220), "x".repeat(80));
417 url.push_str("?a=1#f");
418 assert!(url.len() > 300);
419 let redacted = redact_url(&url);
420 assert!(redacted.len() <= 256, "len={}", redacted.len());
421 assert!(
422 redacted.ends_with("?[redacted]#[redacted]"),
423 "sentinels must render intact: {redacted}"
424 );
425 assert!(std::str::from_utf8(redacted.as_bytes()).is_ok());
426 assert!(
427 !redacted.contains('日'),
428 "straddling char dropped whole: {redacted}"
429 );
430 assert!(
431 redacted.starts_with("https://host/"),
432 "host kept: {redacted}"
433 );
434 }
435
436 #[test]
437 fn idempotent_mask_composition_pin() {
438 // An already-masked window rewrites to itself and the sentinels
439 // still compose.
440 assert_eq!(
441 redact_url("https://***@host/p?a=1#f"),
442 "https://***@host/p?[redacted]#[redacted]"
443 );
444 }
445
446 #[test]
447 fn allowlist_keeps_benign_and_redacts_sensitive() {
448 assert_eq!(
449 redact_url_with_query_allowlist(
450 "tcp://host:61616?password=p&user=u&keepAlive=true",
451 JMS_KEYS
452 ),
453 "tcp://host:61616?password=<redacted>&user=<redacted>&keepAlive=true"
454 );
455 }
456
457 // ── Phase 2: minimal-decode rule (bd rc-r7v8s) ──────────────────────
458
459 /// Percent-encoded credentials under a benign key must not smuggle
460 /// through: the single-pass minimal decode of the pair carries `@` and
461 /// `//`, so the whole pair redacts. Uppercase hex form.
462 #[test]
463 fn allowlist_masks_percent_encoded_credentials_uppercase() {
464 let redacted = redact_url_with_query_allowlist(
465 "tcp://h:61616?redirect=http%3A%2F%2Fuser%3Asecret%40host",
466 JMS_KEYS,
467 );
468 assert!(
469 !redacted.contains("secret"),
470 "percent-encoded credential leaked: {redacted}"
471 );
472 assert!(
473 !redacted.contains("user%3Asecret%40"),
474 "encoded userinfo leaked: {redacted}"
475 );
476 assert_eq!(redacted, "tcp://h:61616?<redacted>");
477 }
478
479 /// Fully-lowercase hex variant of the same smuggling shape.
480 #[test]
481 fn allowlist_masks_percent_encoded_credentials_lowercase() {
482 let redacted = redact_url_with_query_allowlist(
483 "tcp://h:61616?redirect=http%3a%2f%2fuser%3asecret%40host",
484 JMS_KEYS,
485 );
486 assert_eq!(redacted, "tcp://h:61616?<redacted>");
487 assert!(
488 !redacted.contains("secret"),
489 "percent-encoded credential leaked: {redacted}"
490 );
491 }
492
493 /// bd rc-yvjp3 (ADR-0076 appendix, key-position symmetry): a pair
494 /// whose KEY embeds credentials (`user%3Asecret%40host` decodes to
495 /// `user:secret@host`) renders as a bare `<redacted>` — the key bytes
496 /// never echo, in either hex case.
497 #[test]
498 fn allowlist_suppresses_credential_shaped_key_uppercase() {
499 let redacted =
500 redact_url_with_query_allowlist("tcp://h:61616?user%3Asecret%40host=1", JMS_KEYS);
501 assert_eq!(redacted, "tcp://h:61616?<redacted>");
502 assert!(
503 !redacted.contains("user%3Asecret%40"),
504 "credential-shaped key leaked: {redacted}"
505 );
506 assert!(
507 !redacted.contains("secret"),
508 "key credential bytes leaked: {redacted}"
509 );
510 }
511
512 /// Fully-lowercase hex variant of the key-position shape.
513 #[test]
514 fn allowlist_suppresses_credential_shaped_key_lowercase() {
515 let redacted =
516 redact_url_with_query_allowlist("tcp://h:61616?user%3asecret%40host=1", JMS_KEYS);
517 assert_eq!(redacted, "tcp://h:61616?<redacted>");
518 }
519
520 /// Key-position symmetry, literal form: a fully literal
521 /// `user:pass@host` key is suppressed whole.
522 #[test]
523 fn allowlist_suppresses_literal_credential_shaped_key() {
524 let redacted = redact_url_with_query_allowlist("tcp://h:61616?user:pass@host=1", JMS_KEYS);
525 assert_eq!(redacted, "tcp://h:61616?<redacted>");
526 assert!(
527 !redacted.contains("user:pass"),
528 "literal key credentials leaked: {redacted}"
529 );
530 }
531
532 /// bd rc-yvjp3 non-regression: well-known sensitive keys that are NOT
533 /// credential-shaped keep echoing their names — the ADR-0076 exception
534 /// names transport-policy parameter visibility as the sole diagnostic
535 /// value of the broker URL, and no real parameter name decodes to an
536 /// `@`+`:`/`//` shape.
537 #[test]
538 fn allowlist_keeps_well_known_key_names_visible() {
539 let redacted = redact_url_with_query_allowlist(
540 "tcp://h:61616?password=p&jms.userName=admin&user=u&keepAlive=true",
541 JMS_KEYS,
542 );
543 assert_eq!(
544 redacted,
545 "tcp://h:61616?password=<redacted>&jms.userName=<redacted>&user=<redacted>&keepAlive=true"
546 );
547 }
548
549 /// bd rc-yvjp3 boundary pin: a denylist-matching key with a lone `@`
550 /// (no `:`, no `//`) is NOT credential-shaped — it renders
551 /// `user@host=<redacted>` and the key echoes, mirroring the lone-`@`
552 /// email rule of the benign-key branch.
553 #[test]
554 fn allowlist_keeps_lone_at_key_visible() {
555 let redacted = redact_url_with_query_allowlist("tcp://h:61616?user@host=1", JMS_KEYS);
556 assert_eq!(redacted, "tcp://h:61616?user@host=<redacted>");
557 }
558
559 /// bd rc-yvjp3 non-regression: an encoded-but-not-credential-shaped
560 /// key (`%77` is outside the minimal-decode triple) still echoes its
561 /// authored bytes when the decoded name hits the denylist — the
562 /// `pass%77ord` match rule (bd rc-r7v8s) is unchanged.
563 #[test]
564 fn allowlist_keeps_encoded_but_benign_shaped_key_visible() {
565 let redacted = redact_url_with_query_allowlist("tcp://h:61616?pass%77ord=p", JMS_KEYS);
566 assert_eq!(redacted, "tcp://h:61616?pass%77ord=<redacted>");
567 }
568
569 /// Encoded slashes plus a literal `@` decode to a `//`-bearing
570 /// credential shape under a benign key.
571 #[test]
572 fn allowlist_masks_literal_at_bypass() {
573 let redacted =
574 redact_url_with_query_allowlist("tcp://h:61616?next=%2F%2Fuser:pass@host", JMS_KEYS);
575 assert_eq!(redacted, "tcp://h:61616?<redacted>");
576 assert!(
577 !redacted.contains("pass"),
578 "literal credential leaked: {redacted}"
579 );
580 }
581
582 /// Fully literal `user:pass@host` under a benign key.
583 #[test]
584 fn allowlist_masks_fully_literal_credential_pair() {
585 let redacted =
586 redact_url_with_query_allowlist("tcp://h:61616?next=user:pass@host", JMS_KEYS);
587 assert_eq!(redacted, "tcp://h:61616?<redacted>");
588 assert!(
589 !redacted.contains("pass"),
590 "literal credential leaked: {redacted}"
591 );
592 }
593
594 /// Regression pin at the under-redaction boundary: `@` without `:` or
595 /// `//` is an email address, not a credential — the pair stays visible.
596 #[test]
597 fn allowlist_keeps_lone_email_value() {
598 assert_eq!(
599 redact_url_with_query_allowlist("tcp://h:61616?contact=admin%40corp.example", JMS_KEYS),
600 "tcp://h:61616?contact=admin%40corp.example"
601 );
602 }
603
604 /// Over-mask stance (ADR-0051): a value decoding to `user@host:port`
605 /// is credential-shaped even though no literal `//` or `:` is present.
606 #[test]
607 fn allowlist_masks_credential_shaped_userhostport() {
608 let redacted =
609 redact_url_with_query_allowlist("tcp://h:61616?next=user%40host%3Aport", JMS_KEYS);
610 assert_eq!(redacted, "tcp://h:61616?<redacted>");
611 }
612
613 /// A percent-encoded sensitive key decodes to `password` and must
614 /// redact; the rendered key keeps its original encoded bytes.
615 #[test]
616 fn allowlist_decodes_percent_encoded_sensitive_key() {
617 let redacted =
618 redact_url_with_query_allowlist("tcp://host:61616?pass%77ord=shortsecret", JMS_KEYS);
619 assert!(
620 redacted.contains("pass%77ord=<redacted>"),
621 "encoded key must redact keeping original bytes: {redacted}"
622 );
623 assert!(
624 !redacted.contains("shortsecret"),
625 "secret value leaked: {redacted}"
626 );
627 }
628
629 /// Regression pin (redact2): non-ASCII bytes in a pair are preserved
630 /// byte-for-byte (valid UTF-8), never Latin-1-transcoded, and a decoded
631 /// invalid byte becomes `U+FFFD` — the decoded output feeds only ASCII
632 /// shape checks, so neither case can flip a redaction decision.
633 #[test]
634 fn minimal_decode_preserves_non_ascii_bytes() {
635 // `é` (0xC3 0xA9) must survive as itself, not as `é`.
636 assert_eq!(minimal_decode_pair("café"), "café");
637 // Escapes still decode around non-ASCII bytes.
638 assert_eq!(minimal_decode_pair("café%40x"), "café@x");
639 // A decoded invalid byte (0xFF from `%FF`) becomes U+FFFD, which
640 // cannot match an ASCII needle (exercised via the full-hex decoder).
641 assert_eq!(decode_match_key("a%FFb"), "a\u{FFFD}b");
642 }
643
644 // ── Migrated: camel-config config_tests/url_redaction_tests.rs ──────
645
646 #[test]
647 fn redact_url_keeps_userinfo_mask_shape() {
648 assert_eq!(
649 redact_url("redis://user:secret@h:6379"),
650 "redis://***@h:6379"
651 );
652 }
653
654 /// Intentional semantic change: the query was previously echoed verbatim,
655 /// leaking `?password=...` cache credentials into Debug output.
656 #[test]
657 fn redact_url_drops_query_secrets() {
658 assert_eq!(
659 redact_url("redis://h:6379/0?password=hunter2"),
660 "redis://h:6379/0?[redacted]"
661 );
662 }
663
664 #[test]
665 fn redact_url_drops_fragment() {
666 assert_eq!(
667 redact_url("redis://h:6379/0#tok=x"),
668 "redis://h:6379/0#[redacted]"
669 );
670 }
671
672 /// Multiple `@` in the window: mask through the LAST one — over-masking is
673 /// safe, under-masking is not.
674 #[test]
675 fn redact_url_masks_through_last_at() {
676 assert_eq!(redact_url("redis://user:p@ss@h:6379"), "redis://***@h:6379");
677 }
678
679 /// A slash run after `//` must not hide userinfo behind it; extra leading
680 /// slashes are kept byte-for-byte.
681 #[test]
682 fn redact_url_slash_run_evader_masked() {
683 assert_eq!(
684 redact_url("redis:////user:pass@h:6379/0"),
685 "redis:////***@h:6379/0"
686 );
687 }
688
689 /// An `@` outside any `//` window (path data here) is not userinfo.
690 #[test]
691 fn redact_url_at_outside_window_visible() {
692 assert_eq!(
693 redact_url("redis://h:6379/0/user@x"),
694 "redis://h:6379/0/user@x"
695 );
696 }
697
698 /// A `//` window after the first is scanned too: credentials cannot hide
699 /// behind a benign first window.
700 #[test]
701 fn redact_url_later_window_masked() {
702 assert_eq!(redact_url("redis://h//user:pass@x/"), "redis://h//***@x/");
703 }
704
705 /// Compose-both rule: one sentinel per distinct introducer found in the
706 /// raw URL, in first-occurrence order.
707 #[test]
708 fn redact_url_sentinels_compose_both() {
709 assert_eq!(
710 redact_url("redis://h:6379/0?password=x#tok=y"),
711 "redis://h:6379/0?[redacted]#[redacted]"
712 );
713 }
714
715 #[test]
716 fn redact_url_sentinels_compose_fragment_first() {
717 assert_eq!(
718 redact_url("redis://h:6379/0#tok=y?password=x"),
719 "redis://h:6379/0#[redacted]?[redacted]"
720 );
721 }
722
723 /// The 256-byte cap must land on a UTF-8 char boundary: a 3-byte char
724 /// straddling byte 256 forces the cut to walk back instead of panicking.
725 #[test]
726 fn redact_url_truncates_256_utf8_safe() {
727 let mut url = format!("redis://{}{}", "x".repeat(246), '日');
728 url.push_str(&"tail".repeat(20));
729 assert!(url.len() > 300);
730 let redacted = redact_url(&url);
731 assert!(redacted.len() <= 256, "len={}", redacted.len());
732 assert!(redacted.starts_with("redis://"));
733 }
734
735 /// e_gpt stage-4: the 256-byte cap must not split an appended sentinel.
736 /// The base is truncated at `256 - sentinel_len` BEFORE the sentinel is
737 /// appended, so the sentinel always renders intact and the total stays
738 /// ≤ 256.
739 #[test]
740 fn redact_url_keeps_sentinel_intact_under_256_cap() {
741 // Base (masked, cut at the `?`) is 248 bytes, so byte 256 lands inside
742 // the appended `?[redacted]` (starts at 248) pre-fix.
743 let url = format!("http://{}?x=1", "a".repeat(240));
744 let redacted = redact_url(&url);
745 assert!(redacted.len() <= 256, "len={}", redacted.len());
746 assert!(
747 redacted.ends_with("?[redacted]"),
748 "sentinel must render intact: {redacted}"
749 );
750 }
751
752 // ── Migrated: camel-jms config.rs broker allowlist tests ────────────
753
754 /// Audit 2026-08-31, F5-3: JMS broker URLs must not leak credentials
755 /// through Debug output.
756 #[test]
757 fn redact_broker_url_masks_userinfo_and_sensitive_query() {
758 // userinfo form
759 let redacted = redact_url_with_query_allowlist(
760 "tcp://admin:secretpass@broker.example.com:61616",
761 JMS_KEYS,
762 );
763 assert!(
764 !redacted.contains("secretpass"),
765 "password masked: {redacted}"
766 );
767 assert!(
768 redacted.contains("broker.example.com"),
769 "host visible: {redacted}"
770 );
771
772 // failover + query-param form (ActiveMQ style)
773 let redacted = redact_url_with_query_allowlist(
774 "failover:(tcp://host:61616)?jms.userName=admin&jms.password=secret&keepAlive=true",
775 JMS_KEYS,
776 );
777 assert!(
778 !redacted.contains("secret"),
779 "password param masked: {redacted}"
780 );
781 assert!(
782 !redacted.contains("=admin"),
783 "username param masked: {redacted}"
784 );
785 assert!(
786 redacted.contains("keepAlive=true"),
787 "benign param kept: {redacted}"
788 );
789
790 // clean URL untouched
791 assert_eq!(
792 redact_url_with_query_allowlist("tcp://host:61616", JMS_KEYS),
793 "tcp://host:61616"
794 );
795 }
796
797 /// Exact-output pin: userinfo is fully masked by `***`, never partially
798 /// truncated, in scheme://...@ authority position.
799 #[test]
800 fn redact_exact_userinfo_mask() {
801 assert_eq!(
802 redact_url_with_query_allowlist(
803 "tcp://admin:secretpass@broker.example.com:61616",
804 JMS_KEYS
805 ),
806 "tcp://***@broker.example.com:61616"
807 );
808 }
809
810 /// Exact-output pin: sensitive query params redact to `<redacted>`,
811 /// benign params survive byte-for-byte, `&` separators preserved.
812 #[test]
813 fn redact_exact_query_join() {
814 assert_eq!(
815 redact_url_with_query_allowlist(
816 "tcp://host:61616?password=p&user=u&keepAlive=true",
817 JMS_KEYS
818 ),
819 "tcp://host:61616?password=<redacted>&user=<redacted>&keepAlive=true"
820 );
821 }
822
823 /// Exact-output pin: a bare `user@host` (no scheme) is NOT an authority
824 /// position — passthrough untouched.
825 #[test]
826 fn redact_exact_bare_at_passthrough() {
827 assert_eq!(
828 redact_url_with_query_allowlist("admin@host", JMS_KEYS),
829 "admin@host"
830 );
831 }
832
833 /// Exact-output pin: delimiter-exact query redaction on the ActiveMQ
834 /// failover form — the whole query part after '?' must match verbatim,
835 /// no dropped params, no mangled separators.
836 #[test]
837 fn redact_exact_failover_param_boundaries() {
838 let redacted = redact_url_with_query_allowlist(
839 "failover:(tcp://host:61616)?jms.userName=admin&jms.password=secret&keepAlive=true",
840 JMS_KEYS,
841 );
842 let (_, query) = redacted.split_once('?').expect("query segment after '?'");
843 assert_eq!(
844 query,
845 "jms.userName=<redacted>&jms.password=<redacted>&keepAlive=true"
846 );
847 }
848
849 /// bd rc-eh49 exact pin: an `@` riding the query is NOT userinfo — the
850 /// URL must pass through byte-for-byte. The old whole-string
851 /// `split_once('@')` mangled this to `failover:(tcp://***@b`.
852 #[test]
853 fn redact_broker_url_query_at_no_misfire() {
854 assert_eq!(
855 redact_url_with_query_allowlist("failover:(tcp://h:61616)?x=a@b", JMS_KEYS),
856 "failover:(tcp://h:61616)?x=a@b"
857 );
858 }
859
860 /// bd rc-eh49 exact pin: a slash run after `//` is preserved
861 /// byte-for-byte and the windowed mask composes with the per-key query
862 /// allowlist. The old whole-string scan rewrote from the scheme's own
863 /// `://` and swallowed the extra slashes.
864 #[test]
865 fn redact_exact_slash_run_window_composition() {
866 assert_eq!(
867 redact_url_with_query_allowlist("tcp:////user:pass@h:61616?keepAlive=true", JMS_KEYS),
868 "tcp:////***@h:61616?keepAlive=true"
869 );
870 }
871
872 /// bd rc-eh49 exact pin: the window mask consumes through the LAST `@`
873 /// of the window, so an `@` embedded in the userinfo cannot keep a
874 /// spoofable prefix alive (the old first-`@` scan left `a@` visible).
875 #[test]
876 fn redact_exact_last_at_in_window() {
877 assert_eq!(
878 redact_url_with_query_allowlist("tcp://u:p@a@h:61616", JMS_KEYS),
879 "tcp://***@h:61616"
880 );
881 }
882
883 /// bd rc-eh49: the 256-byte cap cuts on a char boundary — a multibyte
884 /// character straddling byte 256 is dropped whole, never split
885 /// mid-encode.
886 #[test]
887 fn redact_broker_url_truncate_multibyte_boundary() {
888 let mut url = String::from("tcp://broker:61616/");
889 url.push_str(&"x".repeat(236)); // 255 ASCII bytes before the multibyte char
890 url.push('日'); // 3 bytes straddling the 256-byte cap
891 url.push_str(&"y".repeat(50)); // push the total past 300 bytes
892 assert!(url.len() > 300);
893 let redacted = redact_url_with_query_allowlist(&url, JMS_KEYS);
894 assert!(redacted.len() <= 256, "len={}", redacted.len());
895 assert!(std::str::from_utf8(redacted.as_bytes()).is_ok());
896 assert!(
897 !redacted.contains('日'),
898 "straddling char dropped whole: {redacted}"
899 );
900 }
901
902 /// bd rc-eh49: a `//` window after the first is scanned too; the
903 /// benign query stays visible per the broker allowlist exception.
904 #[test]
905 fn redact_broker_url_later_window_masked() {
906 assert_eq!(
907 redact_url_with_query_allowlist("tcp://h//user:pass@x/?keepAlive=true", JMS_KEYS),
908 "tcp://h//***@x/?keepAlive=true"
909 );
910 }
911
912 /// bd rc-eh49: fragments are never echoed — everything from the first
913 /// `#` is dropped and the `#[redacted]` sentinel appended; processed
914 /// query params stay visible.
915 #[test]
916 fn redact_broker_url_drops_fragment() {
917 assert_eq!(
918 redact_url_with_query_allowlist("tcp://h:61616?keepAlive=true#tok=x", JMS_KEYS),
919 "tcp://h:61616?keepAlive=true#[redacted]"
920 );
921 }
922
923 /// bd rc-eh49: broker URLs are capped at 256 bytes on a UTF-8 char
924 /// boundary.
925 #[test]
926 fn redact_broker_url_truncates() {
927 let mut url = format!("tcp://broker:61616/{}", "x".repeat(300));
928 url.push('日');
929 url.push_str(&"tail".repeat(20));
930 assert!(url.len() > 300);
931 let redacted = redact_url_with_query_allowlist(&url, JMS_KEYS);
932 assert!(redacted.len() <= 256, "len={}", redacted.len());
933 assert!(redacted.starts_with("tcp://broker:61616/"));
934 }
935
936 // ── Migrated: camel-jms component.rs redact_url_* block ─────────────
937
938 #[test]
939 fn redact_url_strips_userinfo_with_password() {
940 assert_eq!(
941 redact_url("tcp://admin:s3cret@broker:61616"),
942 "tcp://***@broker:61616"
943 );
944 }
945
946 #[test]
947 fn redact_url_strips_userinfo_without_password() {
948 assert_eq!(
949 redact_url("tcp://admin@broker:61616"),
950 "tcp://***@broker:61616"
951 );
952 }
953
954 #[test]
955 fn redact_url_passes_clean_url_unchanged() {
956 assert_eq!(redact_url("tcp://localhost:61616"), "tcp://localhost:61616");
957 }
958
959 #[test]
960 fn redact_url_handles_ssl_scheme() {
961 assert_eq!(
962 redact_url("ssl://user:pass@secure-broker:61617"),
963 "ssl://***@secure-broker:61617"
964 );
965 }
966
967 /// bd rc-eh49: the earliest `?`/`#` introducer wins; both sentinels
968 /// compose in first-occurrence order when the raw URL carries both
969 /// introducers, and fragment bytes after the cut are dropped with it.
970 #[test]
971 fn redact_url_drops_query_and_fragment() {
972 assert_eq!(
973 redact_url("tcp://broker:61616?user=a#tok=x"),
974 "tcp://broker:61616?[redacted]#[redacted]"
975 );
976 }
977
978 /// bd rc-eh49 compose-both rule: a `#` before `?` flips the sentinel
979 /// order accordingly. (Name prefixed `jms_`: the redis fixture from
980 /// camel-config already owns the unprefixed name above.)
981 #[test]
982 fn jms_redact_url_sentinels_compose_fragment_first() {
983 assert_eq!(
984 redact_url("tcp://broker:61616#tok=x?user=a"),
985 "tcp://broker:61616#[redacted]?[redacted]"
986 );
987 }
988
989 /// bd rc-eh49: a `//` window after the first is scanned too —
990 /// credentials cannot hide behind a benign first window. (Name prefixed
991 /// `jms_`: the redis fixture from camel-config already owns the
992 /// unprefixed name above.)
993 #[test]
994 fn jms_redact_url_later_window_masked() {
995 assert_eq!(redact_url("tcp://h//user:pass@x/"), "tcp://h//***@x/");
996 }
997
998 /// bd rc-eh49: a slash run after `//` cannot hide userinfo from the
999 /// window scan.
1000 #[test]
1001 fn redact_url_slash_run_masked() {
1002 let redacted = redact_url("tcp:////user:pass@broker:61616");
1003 assert!(!redacted.contains("user:pass"), "leaked: {redacted}");
1004 assert!(
1005 redacted.contains("***@broker:61616"),
1006 "masked in place: {redacted}"
1007 );
1008 }
1009
1010 /// bd rc-eh49: the old first-`@`-anywhere scan masked through an `@`
1011 /// riding the query (`tcp://***@b`); only a window `@` is userinfo.
1012 #[test]
1013 fn redact_url_at_in_query_not_userinfo_mask() {
1014 assert_eq!(
1015 redact_url("tcp://broker:61616?q=a@b"),
1016 "tcp://broker:61616?[redacted]"
1017 );
1018 }
1019
1020 /// bd rc-eh49: the 256-byte cap cuts on a char boundary — a multibyte
1021 /// character straddling byte 256 is dropped whole, never split
1022 /// mid-encode.
1023 #[test]
1024 fn redact_url_truncate_multibyte_boundary() {
1025 let mut url = String::from("tcp://broker:61616/");
1026 url.push_str(&"x".repeat(236)); // 255 ASCII bytes before the multibyte char
1027 url.push('日'); // 3 bytes straddling the 256-byte cap
1028 url.push_str(&"y".repeat(50)); // push the total past 300 bytes
1029 assert!(url.len() > 300);
1030 let redacted = redact_url(&url);
1031 assert!(redacted.len() <= 256, "len={}", redacted.len());
1032 assert!(std::str::from_utf8(redacted.as_bytes()).is_ok());
1033 assert!(
1034 !redacted.contains('日'),
1035 "straddling char dropped whole: {redacted}"
1036 );
1037 }
1038
1039 /// e_gpt stage-4: the 256-byte cap must not split an appended sentinel.
1040 /// The base is truncated at `256 - sentinel_len` BEFORE the sentinel is
1041 /// appended, so the sentinel always renders intact and the total stays
1042 /// ≤ 256. Covers both redactors: `redact_url` (compose sentinels) and
1043 /// `redact_url_with_query_allowlist` (fragment sentinel over kept query
1044 /// content).
1045 #[test]
1046 fn redact_url_keeps_sentinels_intact_under_256_cap() {
1047 // `redact_url`: base (masked, cut at the `?`) is 255 bytes, so byte
1048 // 256 lands inside the appended `?[redacted]` (starts at 255) pre-fix.
1049 let url = format!("tcp://{}?x=1", "a".repeat(250));
1050 let redacted = redact_url(&url);
1051 assert!(redacted.len() <= 256, "len={}", redacted.len());
1052 assert!(
1053 redacted.ends_with("?[redacted]"),
1054 "redact_url sentinel must render intact: {redacted}"
1055 );
1056
1057 // `redact_url_with_query_allowlist`: base + kept query is 252 bytes,
1058 // so byte 256 lands inside the appended `#[redacted]` (starts at
1059 // 252) pre-fix.
1060 let broker = format!("tcp://{}?keep=1#frag", "a".repeat(240));
1061 let redacted = redact_url_with_query_allowlist(&broker, JMS_KEYS);
1062 assert!(redacted.len() <= 256, "len={}", redacted.len());
1063 assert!(
1064 redacted.ends_with("#[redacted]"),
1065 "allowlist sentinel must render intact: {redacted}"
1066 );
1067 }
1068
1069 // ── Migrated: camel-http lib.rs pure-string redact tests ────────────
1070 // These landed against the Err arm of `redact_url_for_diagnostics`
1071 // (unparseable inputs); that arm delegates to `redact_url` /
1072 // `redact_url_fail_closed`, so the fixtures pin the canonical helpers
1073 // byte-identically. The `url::Url::parse` precondition asserts of the
1074 // landed tests do not apply here: this module never parses.
1075
1076 #[test]
1077 fn redact_url_unparseable_fragment_credentials_dropped() {
1078 let raw = "ht tps://app.example/cb#access_token=SECRET";
1079 let redacted = redact_url(raw);
1080 assert!(
1081 !redacted.contains("SECRET"),
1082 "unparseable fragment token leaked: {redacted}"
1083 );
1084 assert!(
1085 !redacted.contains("access_token"),
1086 "unparseable fragment bytes leaked: {redacted}"
1087 );
1088 assert!(
1089 redacted.contains("#[redacted]"),
1090 "unparseable fragment must end in the sentinel: {redacted}"
1091 );
1092 }
1093
1094 #[test]
1095 fn redact_url_empty_host_userinfo_sentinel() {
1096 // The landed http test drives this through the parse-failure arm;
1097 // the canonical helper fails closed on the window `@` directly.
1098 let redacted = redact_url_fail_closed("scheme://user@");
1099 assert_eq!(
1100 redacted, "[redacted]",
1101 "empty-host userinfo must fail closed: {redacted}"
1102 );
1103 }
1104
1105 #[test]
1106 fn redact_url_unparseable_slash_run_evader_sentinel() {
1107 let raw = "schem e:////user:pass@evil/";
1108 let redacted = redact_url_fail_closed(raw);
1109 assert_eq!(
1110 redacted, "[redacted]",
1111 "unparseable slash-run evader must fail closed: {redacted}"
1112 );
1113 }
1114
1115 #[test]
1116 fn redact_url_unparseable_later_window_userinfo_sentinel() {
1117 // The first `//` window ("ho st") carries no `@`, but a later
1118 // `//user:pass@evil/` window does. The scan must consider every
1119 // `//` window, not just the first, or the credentials echo.
1120 let raw = "http://ho st/a//user:pass@evil/";
1121 let redacted = redact_url_fail_closed(raw);
1122 assert_eq!(
1123 redacted, "[redacted]",
1124 "userinfo in a later // window must fail closed: {redacted}"
1125 );
1126 }
1127
1128 #[test]
1129 fn redact_url_truncates_unparseable() {
1130 let long = "x".repeat(1000);
1131 let redacted = redact_url(&long);
1132 assert_eq!(redacted.len(), 256, "unparseable URL must be truncated");
1133 }
1134
1135 #[test]
1136 fn redact_url_suppresses_unparseable_authority_credentials() {
1137 let fixtures = [
1138 "http://u:secretpw@/x",
1139 "http://u:secretpw@host:99999/x",
1140 "http://u:secretpw@host:99999",
1141 "//u:secretpw@h/x",
1142 ];
1143 for fixture in fixtures {
1144 assert_eq!(
1145 redact_url_fail_closed(fixture),
1146 "[redacted]",
1147 "credential-bearing authority must be suppressed: {fixture}"
1148 );
1149 }
1150 }
1151
1152 #[test]
1153 fn redact_url_unparseable_query_redacted_short_and_long() {
1154 let short = "http://host:99999/path?token=shortsecret";
1155 let redacted = redact_url(short);
1156 assert_eq!(
1157 redacted, "http://host:99999/path?[redacted]",
1158 "short unparseable query must end with the suffix: {redacted}"
1159 );
1160
1161 let mut long = String::from("http://host:99999/");
1162 long.push_str(&"a".repeat(300));
1163 long.push_str("?token=longsecret");
1164 let redacted = redact_url(&long);
1165 assert!(
1166 !redacted.contains("longsecret"),
1167 "long unparseable query leaked a query byte: {redacted}"
1168 );
1169 assert!(
1170 redacted.len() <= 256,
1171 "long unparseable query must be capped: {} bytes",
1172 redacted.len()
1173 );
1174 }
1175
1176 #[test]
1177 fn redact_url_unparseable_sentinels_compose_both() {
1178 // Compose-both rule: one sentinel per distinct introducer found in
1179 // the raw string, in first-occurrence order.
1180 let raw = "ht tp://h.example/p?a=1#tok=x";
1181 assert_eq!(
1182 redact_url(raw),
1183 "ht tp://h.example/p?[redacted]#[redacted]",
1184 "query and fragment sentinels must compose: {raw}"
1185 );
1186 }
1187
1188 #[test]
1189 fn redact_url_unparseable_sentinels_compose_fragment_first() {
1190 let raw = "ht tp://h.example/p#tok=x?a=1";
1191 assert_eq!(
1192 redact_url(raw),
1193 "ht tp://h.example/p#[redacted]?[redacted]",
1194 "sentinels must follow the introducers' first-occurrence order: {raw}"
1195 );
1196 }
1197
1198 #[test]
1199 fn redact_url_unparseable_utf8_straddle_no_panic() {
1200 let fixture = format!("a{}", "é".repeat(200));
1201 let redacted = redact_url(&fixture);
1202 assert!(
1203 redacted.len() <= 256,
1204 "straddle fixture must be capped: {} bytes",
1205 redacted.len()
1206 );
1207 assert!(
1208 redacted.len() >= 253,
1209 "straddle fixture must not over-truncate: {} bytes",
1210 redacted.len()
1211 );
1212 assert!(
1213 fixture.is_char_boundary(redacted.len()),
1214 "cut must land on a UTF-8 char boundary: {} bytes",
1215 redacted.len()
1216 );
1217 }
1218
1219 #[test]
1220 fn redact_url_at_sign_outside_authority_window_visible() {
1221 let at_sign_in_path = "http://host:99999/x@y";
1222 assert_eq!(
1223 redact_url_fail_closed(at_sign_in_path),
1224 at_sign_in_path,
1225 "at-sign in path must not be suppressed"
1226 );
1227 // Opaque non-hierarchical strings pass through byte-identically.
1228 assert_eq!(
1229 redact_url("mailto:user@example.com"),
1230 "mailto:user@example.com",
1231 "at-sign in mailto must round-trip byte-identically"
1232 );
1233 }
1234
1235 // ── Phase 3: scheme-gated backslash windows (rc-f05q8) ──────────────
1236
1237 /// A backslash authority after a non-special scheme opens a window:
1238 /// `foo:\user:pass@evil/` carries no `//` run, yet the scheme-prefixed
1239 /// backslash run must mask the userinfo. The fail-closed variant
1240 /// suppresses the whole string; the clean sibling stays visible.
1241 #[test]
1242 fn backslash_run_non_special_scheme_masked() {
1243 assert_eq!(
1244 redact_url("foo:\\user:pass@evil/"),
1245 "foo:\\***@evil/",
1246 "non-special-scheme backslash authority must mask userinfo"
1247 );
1248 assert_eq!(
1249 redact_url_fail_closed("foo:\\user:pass@evil/"),
1250 "[redacted]",
1251 "non-special-scheme backslash authority must fail closed"
1252 );
1253 assert_eq!(
1254 redact_url("foo:\\clean/path"),
1255 "foo:\\clean/path",
1256 "clean backslash sibling stays visible"
1257 );
1258 }
1259
1260 /// A single backslash after a multi-character scheme opens a window
1261 /// even though the run is one character long.
1262 #[test]
1263 fn backslash_single_after_multi_char_scheme_masked() {
1264 let redacted = redact_url("http:\\user:pass@evil\\path");
1265 assert!(
1266 !redacted.contains("user:pass"),
1267 "single-backslash authority leaked: {redacted}"
1268 );
1269 assert!(
1270 redacted.contains("***@"),
1271 "single-backslash authority must mask userinfo: {redacted}"
1272 );
1273 }
1274
1275 /// A single backslash after a one-character scheme opens a window when
1276 /// the candidate window content is credential-shaped (`:` before the
1277 /// last `@`).
1278 #[test]
1279 fn backslash_single_after_one_char_scheme_credential_shaped_masked() {
1280 let redacted = redact_url("x:\\user:pass@evil");
1281 assert!(
1282 !redacted.contains("user:pass"),
1283 "one-char-scheme backslash authority leaked: {redacted}"
1284 );
1285 assert!(
1286 redacted.contains("***@"),
1287 "one-char-scheme backslash authority must mask userinfo: {redacted}"
1288 );
1289 }
1290
1291 /// Windows drive path: single backslash after a one-character scheme
1292 /// with no `:` in the candidate window — no qualifying window, the
1293 /// string renders unchanged.
1294 #[test]
1295 fn drive_path_stays_visible() {
1296 assert_eq!(
1297 redact_url("C:\\Users\\x@corp\\file"),
1298 "C:\\Users\\x@corp\\file"
1299 );
1300 }
1301
1302 /// UNC path: no scheme prefix before the backslash run — no qualifying
1303 /// window, the string renders unchanged.
1304 #[test]
1305 fn unc_path_stays_visible() {
1306 assert_eq!(redact_url("\\\\server\\x@y"), "\\\\server\\x@y");
1307 }
1308
1309 /// The fail-closed window scan must see scheme-prefixed backslash
1310 /// windows, while drive paths stay window-free.
1311 #[test]
1312 fn window_has_at_sign_sees_backslash_windows() {
1313 assert!(
1314 window_has_at_sign("foo:\\u:p@e/"),
1315 "scheme-prefixed backslash window must carry the at-sign"
1316 );
1317 assert!(
1318 !window_has_at_sign("C:\\Users\\x@corp\\file"),
1319 "drive path must not open a backslash window"
1320 );
1321 }
1322
1323 /// Branch pins for the scheme-gated backslash window rule: a len-2
1324 /// backslash run behind a scheme prefix opens (introducer stays
1325 /// visible), a mixed `/`+`\` run of length 2 behind a 1-char scheme
1326 /// opens, an invalid scheme char before the run gates it off, a
1327 /// scheme-less mixed run stays closed, and a single `\` behind a
1328 /// 1-char scheme with no `:` in the candidate content stays closed.
1329 #[test]
1330 fn backslash_gate_branches_pinned() {
1331 assert_eq!(redact_url("foo:\\\\user:pass@evil/"), "foo:\\\\***@evil/");
1332 assert_eq!(redact_url("a:/\\user:pass@evil/"), "a:/\\***@evil/");
1333 assert_eq!(
1334 redact_url("notscheme%\\user:pass@evil/"),
1335 "notscheme%\\user:pass@evil/"
1336 );
1337 assert_eq!(redact_url("/\\user:pass@evil/"), "/\\user:pass@evil/");
1338 assert_eq!(redact_url("a:\\user@evil"), "a:\\user@evil");
1339 assert!(window_has_at_sign("foo:\\\\u:p@e/"));
1340 assert!(!window_has_at_sign("a:\\user@evil"));
1341 }
1342}