Skip to main content

aft_base/
log_redact.rs

1//! Credential masking for durable logs and background completion previews.
2//!
3//! AFT log lines can quote URLs, error text from child processes and LSP
4//! servers, and other strings that occasionally carry a credential. Every line
5//! bound for the log file passes through [`aft_redactor`] once before it is
6//! written (see `logging::TeeWriter`).
7//!
8//! Shared token and URL patterns are also exercised by the CLI sanitizer in
9//! `packages/aft-cli/src/lib/sanitize.ts` through
10//! `tests/fixtures/log_redaction_cases.json`. The durable sink additionally masks
11//! contextual secret fields and private-key records before shortening them.
12//!
13//! What is masked:
14//! - GitHub tokens (`ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`, `github_pat_`),
15//!   `sk-` API keys, JWTs, AWS access key IDs, and `Authorization: Bearer|Basic`
16//!   header values;
17//! - URL userinfo (`https://user:pass@host` becomes `https://***@host`);
18//! - credential query parameters (`token=`, `access_token=`, `api_key=`,
19//!   `…secret=`, `password=`), and `key=` when its value looks like a secret.
20//!
21//! Ordinary `key=value` fields stay readable: AFT's structured lines use them
22//! for index keys and session identifiers. Short password names are masked in
23//! every log line; value-shape assignment masking is limited to shell commands.
24//!
25//! Shell commands quoted in a log line additionally go through
26//! [`redact_command`], which masks credentials typed inline in a command
27//! (`GITHUB_TOKEN=...`, `--password ...`). Those shapes are command-only for
28//! the reason above.
29
30use std::borrow::Cow;
31use std::sync::LazyLock;
32
33use regex::{Captures, Regex, Replacer};
34
35/// Replacement for a token-shaped secret. Matches the CLI sanitizer.
36pub const SECRET_PLACEHOLDER: &str = "<REDACTED_SECRET>";
37/// Replacement for URL userinfo. Matches the CLI sanitizer.
38pub const URL_CREDENTIAL_PLACEHOLDER: &str = "***";
39
40/// A `key=` query value shorter than this is treated as an ordinary word.
41const KEY_VALUE_MIN_SECRET_LEN: usize = 16;
42
43fn compile(pattern: &str) -> Regex {
44    Regex::new(pattern).expect("log redaction pattern must compile")
45}
46
47static AUTHORIZATION_HEADER: LazyLock<Regex> = LazyLock::new(|| {
48    compile(
49        r"(?i)\b((?:proxy-)?authorization[^\S\r\n]*:[^\S\r\n]*(?:bearer|basic|token)[^\S\r\n]+)[A-Za-z0-9._~+/-]+=*",
50    )
51});
52static API_KEY_HEADER: LazyLock<Regex> =
53    LazyLock::new(|| compile(r"(?i)\b(x-api-key[^\S\r\n]*:[^\S\r\n]*)[^\s<>]+"));
54static SECRET_JSON_FIELD: LazyLock<Regex> = LazyLock::new(|| {
55    compile(&format!(
56        r#"(?i)("(?:{JSON_SECRET_LABELS})"\s*:\s*")((?:\\.|[^"\\])+)(")"#
57    ))
58});
59/// The opening of a [`SECRET_JSON_FIELD`] value, up to and including its quote.
60static SECRET_JSON_OPENING: LazyLock<Regex> =
61    LazyLock::new(|| compile(&format!(r#"(?i)"(?:{JSON_SECRET_LABELS})"\s*:\s*""#)));
62const JSON_SECRET_LABELS: &str = "password|passwd|pwd|api[_-]?key|apikey|x-api-key|aws_secret_access_key|awsSecretAccessKey|secret_access_key";
63static AWS_SECRET_FIELD: LazyLock<Regex> = LazyLock::new(|| {
64    compile(
65        r#"(?i)\b((?:aws_secret_access_key|secret_access_key)[^\S\r\n]*[=:][^\S\r\n]*)[^\s"'<>]+"#,
66    )
67});
68static SLACK_TOKEN: LazyLock<Regex> = LazyLock::new(|| compile(r"\bxox[baprs]-[A-Za-z0-9-]+\b"));
69static PRIVATE_KEY: LazyLock<Regex> = LazyLock::new(|| {
70    compile(
71        r"(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|\z)",
72    )
73});
74
75static GITHUB_PAT: LazyLock<Regex> = LazyLock::new(|| compile(r"\bgithub_pat_[A-Za-z0-9_]+\b"));
76static GITHUB_TOKEN: LazyLock<Regex> =
77    LazyLock::new(|| compile(r"\bgh[pousr]_[A-Za-z0-9_]{16,}\b"));
78static SK_API_KEY: LazyLock<Regex> = LazyLock::new(|| {
79    compile(r"\bsk-(?:live-[A-Za-z0-9][A-Za-z0-9_-]{7,}|[A-Za-z0-9][A-Za-z0-9_-]{19,})\b")
80});
81static JWT: LazyLock<Regex> =
82    LazyLock::new(|| compile(r"\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b"));
83static AWS_ACCESS_KEY_ID: LazyLock<Regex> =
84    LazyLock::new(|| compile(r"\b(?:AKIA|ASIA|AGPA|AIDA|AROA)[A-Z0-9]{16}\b"));
85static URL_USERINFO: LazyLock<Regex> =
86    LazyLock::new(|| compile(r"(?i)\b([a-z][a-z0-9+.-]*://)[^@\s/?#]+@"));
87/// Query parameters whose name alone says the value is a credential. The value
88/// stops at the next parameter, fragment, whitespace, quote or angle bracket;
89/// excluding `<` keeps an already-masked value from matching again.
90static CREDENTIAL_QUERY: LazyLock<Regex> = LazyLock::new(|| {
91    compile(
92        r#"(?i)([?&](?:[a-z0-9_-]*token|api[_-]?key|apikey|[a-z0-9_-]*secret|password|passwd|pwd)=)[^&\s#"'<>]+"#,
93    )
94});
95/// `key=` is too generic to mask on its name alone; see [`looks_like_secret`].
96static KEY_QUERY: LazyLock<Regex> = LazyLock::new(|| compile(r#"(?i)([?&]key=)([^&\s#"'<>]+)"#));
97// Value-shape checks are restricted to explicit shell command text.
98static INLINE_ASSIGNMENT: LazyLock<Regex> = LazyLock::new(|| {
99    compile(r#"\b(([A-Za-z_][A-Za-z0-9_]*)=)("[^"\r\n]+"|'[^'\r\n]+'|[^\s,;&|<>()'"]+)"#)
100});
101// Also protects log lines from older versions that recorded raw commands.
102static SHORT_PASSWORD_ASSIGNMENT: LazyLock<Regex> = LazyLock::new(|| {
103    compile(
104        r#"(?i)\b(((?:[A-Za-z_][A-Za-z0-9_]*_)?(?:PW|PASS))=)("[^"\r\n]+"|'[^'\r\n]+'|[^\s,;&|<>()'"]+)"#,
105    )
106});
107
108/// Mask credentials in `text`. Returns the input unchanged (borrowed) when it
109/// contains nothing to mask, so the common case allocates nothing.
110pub fn aft_redactor(text: &str) -> Cow<'_, str> {
111    redact_with_range(text, None, RangeMapping::Watch)
112}
113
114const SHELL_FORMAT_TRIGGERS: &[&str] = &[
115    "PRIVATE KEY-----",
116    "xox",
117    "x-api-key",
118    "\"",
119    "secret_access_key",
120    "authorization",
121    "github_pat_",
122    "ghp_",
123    "gho_",
124    "ghu_",
125    "ghs_",
126    "ghr_",
127    "sk-",
128    "eyJ",
129    "AKIA",
130    "ASIA",
131    "AGPA",
132    "AIDA",
133    "AROA",
134    "://",
135    "?",
136    "&",
137    // Short password assignments (`PW=`, `DB_PASS=`): the name must end in
138    // PW or PASS directly before `=`.
139    "pw=",
140    "pass=",
141];
142
143/// A conservative prefilter, not a second masker. A complete capture with no
144/// trigger cannot contain any format recognized by `redact_with_range`.
145pub fn shells_may_need_format_context(text: &str) -> bool {
146    SHELL_FORMAT_TRIGGERS
147        .iter()
148        .any(|trigger| contains_ignore_ascii_case(text, trigger))
149}
150
151pub fn shells_format_scan_overlap() -> usize {
152    SHELL_FORMAT_TRIGGERS
153        .iter()
154        .map(|trigger| trigger.len())
155        .max()
156        .unwrap_or(1)
157        - 1
158}
159
160static SHELL_PRIVATE_BOUNDARY: LazyLock<Regex> =
161    LazyLock::new(|| compile(r"-----(?:BEGIN|END) [A-Z0-9 ]*PRIVATE KEY-----"));
162
163pub fn shells_private_boundary_before(text: &str, before: usize) -> bool {
164    SHELL_PRIVATE_BOUNDARY
165        .find_iter(text)
166        .any(|marker| marker.end() <= before)
167}
168
169// Shell-command credential shapes. These are applied only to command text
170// (see [`redact_command`]), not to every log line: AFT's own structured log
171// fields are lowercase `key=value` pairs and must stay readable.
172//
173// The leading `(^|[^...])` group stands in for a look-behind, which the regex
174// crate lacks; replacements re-emit it.
175
176/// One whole shell word, as the shell would read it: single-quoted runs,
177/// double-quoted runs with backslash escapes, backslash-escaped characters
178/// and plain characters, concatenated (`'a'"b"c`, `my\ pass`), up to the
179/// next unquoted whitespace or shell operator. A quote left open runs to the
180/// end of the text. `<` ends a word, so an already-masked value is never
181/// matched again.
182macro_rules! shell_word {
183    () => {
184        r#"(?:'[^']*'?|"(?:\\[\s\S]|[^"\\])*"?|\\[\s\S]?|[^\s;&|<>()'"\\])+"#
185    };
186}
187
188/// `NAME=value` where NAME is UPPER_SNAKE and contains a credential word,
189/// at its start or after other letters, followed by `=` or `_` (`TOKEN=`,
190/// `GITHUB_TOKEN=`, `export DB_PASSWORD=`, `AWS_SECRET_ACCESS_KEY_ID=`).
191/// Plain substrings do not count: `MAX_TOKENS`, `TOKENIZERS_PARALLELISM`,
192/// `GIT_AUTHOR_NAME` and `GH_SHIM_BYPASS` stay.
193static COMMAND_SECRET_ASSIGNMENT: LazyLock<Regex> = LazyLock::new(|| {
194    compile(concat!(
195        r#"(^|[^A-Za-z0-9_])((?:(?:[A-Z][A-Z0-9_]*?)?(?:TOKEN|SECRET|PASSWORD|PASSWD|PASSPHRASE|CREDENTIALS?|APIKEY|API_KEY|ACCESS_KEY|PRIVATE_KEY|AUTH_KEY|_KEY|_PAT|_AUTH)(?:_[A-Z0-9]+)*|(?:[A-Z_][A-Z0-9_]*_)?(?:PW|PASS))=)("#,
196        shell_word!(),
197        ")"
198    ))
199});
200/// Assignment names ending in one of these name where a credential lives or
201/// who owns it, not the credential (`SSH_KEY_PATH=`, `AWS_ACCESS_KEY_ID=`).
202const COMMAND_NON_SECRET_NAME_SUFFIXES: [&str; 16] = [
203    "_PATH=",
204    "_FILE=",
205    "_DIR=",
206    "_NAME=",
207    "_URL=",
208    "_ID=",
209    "_HOST=",
210    "_PORT=",
211    "_USER=",
212    "_USERNAME=",
213    "_ENV=",
214    "_COUNT=",
215    "_LEN=",
216    "_LENGTH=",
217    "_TTL=",
218    "_MODE=",
219];
220/// Long options whose value is a credential, as `--flag=value` or
221/// `--flag value`. `--secret` is deliberately absent: gcloud and others use it
222/// for a secret's name.
223static COMMAND_SECRET_FLAG: LazyLock<Regex> = LazyLock::new(|| {
224    compile(concat!(
225        r#"(^|[^A-Za-z0-9_-])(--(?:password|passwd|pass|token|api-key|apikey|client-secret|auth-token|access-token|bearer)(?:=|[ \t]+))("#,
226        shell_word!(),
227        ")"
228    ))
229});
230/// How deep [`mask_tool_passwords`] looks into quoted strings and
231/// substitutions that hold a command of their own (`bash -c "curl ..."`,
232/// `$(curl ...)`). A quoted substitution (`"$(...)"`) takes two levels.
233const QUOTED_COMMAND_DEPTH: usize = 8;
234
235/// The longest command prefix [`mask_tool_passwords`] scans. Anything past
236/// it is masked whole rather than logged unscanned, which keeps the work on
237/// a huge command bounded without letting its tail through.
238const MAX_SCANNED_COMMAND_BYTES: usize = 1 << 20;
239
240#[derive(Clone, Copy, PartialEq, Eq)]
241enum ShellTokenKind {
242    Word,
243    /// A redirection with its target (`<f`, `> f`, `2>&1`, `<<<word`). It is
244    /// neither an argument nor the value of the option before it.
245    Redirect,
246}
247
248#[derive(Clone)]
249struct ShellToken {
250    kind: ShellTokenKind,
251    range: std::ops::Range<usize>,
252}
253
254/// Bytes that separate words without ending the command: every ASCII
255/// whitespace byte except the newline (space, tab, carriage return, vertical
256/// tab, form feed; `u8::is_ascii_whitespace` leaves out the vertical tab).
257/// The command loop skips exactly these and the word scan stops at exactly
258/// these, so every byte a word stops at is one the loop around it consumes.
259fn is_shell_blank(byte: u8) -> bool {
260    matches!(byte, b' ' | b'\t' | b'\r' | b'\x0b' | b'\x0c')
261}
262
263/// Bytes that end a word: blanks, plus the bytes that start an operator or
264/// end a command. The command loop has an arm for each of them.
265fn ends_shell_word(byte: u8) -> bool {
266    is_shell_blank(byte) || matches!(byte, b'\n' | b';' | b'&' | b'|' | b'<' | b'>' | b'(' | b')')
267}
268
269/// Whether a process substitution (`<(` or `>(`) starts at `at`.
270fn starts_process_substitution(bytes: &[u8], at: usize) -> bool {
271    matches!(bytes.get(at), Some(b'<' | b'>')) && bytes.get(at + 1) == Some(&b'(')
272}
273
274/// The index of the `)` that closes a substitution whose body starts at
275/// `from`, or the end of `text` when it never closes. Quotes, backticks and
276/// escapes inside are skipped; nested parentheses are counted.
277fn substitution_end(text: &str, from: usize) -> usize {
278    let bytes = text.as_bytes();
279    let mut depth = 1;
280    let mut at = from;
281    while at < bytes.len() {
282        note_shell_scan_steps(1);
283        match bytes[at] {
284            b'\\' => at += 2,
285            b'\'' => at = skip_single_quoted(text, at),
286            b'"' => at = skip_double_quoted(bytes, at),
287            b'`' => at = backtick_end(bytes, at + 1) + 1,
288            b'(' => {
289                depth += 1;
290                at += 1;
291            }
292            b')' => {
293                depth -= 1;
294                if depth == 0 {
295                    return at;
296                }
297                at += 1;
298            }
299            _ => at += 1,
300        }
301    }
302    bytes.len()
303}
304
305/// The index just past the single-quoted run opening at `at`.
306fn skip_single_quoted(text: &str, at: usize) -> usize {
307    text[at + 1..]
308        .find('\'')
309        .map_or(text.len(), |offset| at + 1 + offset + 1)
310}
311
312/// The index just past the double-quoted run opening at `at`.
313fn skip_double_quoted(bytes: &[u8], at: usize) -> usize {
314    let mut close = at + 1;
315    while close < bytes.len() && bytes[close] != b'"' {
316        close += if bytes[close] == b'\\' { 2 } else { 1 };
317    }
318    (close + 1).min(bytes.len())
319}
320
321/// The index of the backtick that closes a substitution whose body starts
322/// at `from`, or the end of the text.
323fn backtick_end(bytes: &[u8], from: usize) -> usize {
324    let mut at = from;
325    while at < bytes.len() && bytes[at] != b'`' {
326        at += if bytes[at] == b'\\' { 2 } else { 1 };
327    }
328    at.min(bytes.len())
329}
330
331/// Split `text` into simple commands of words and redirections, reading it
332/// as the shell would: quotes and backslashes keep operators inside a word;
333/// a command substitution (`$( ... )`, backticks) or process substitution
334/// (`<( ... )`, `>( ... )`) is part of the word it appears in, so the
335/// command around it carries on after it closes; an unquoted `;`, `&`, `|`,
336/// newline, `(` or `)` ends a command (a subshell is a command of its own);
337/// a backslash-newline continues the line; redirections may be attached to
338/// a word or spaced from it. Also returns the inside of every quoted run and
339/// substitution, which [`collect_tool_password_masks`] scans as a command of
340/// its own one level down.
341fn split_shell_commands(text: &str) -> (Vec<Vec<ShellToken>>, Vec<std::ops::Range<usize>>) {
342    let bytes = text.as_bytes();
343    let mut commands = vec![Vec::new()];
344    let mut quoted = Vec::new();
345    let end_command = |commands: &mut Vec<Vec<ShellToken>>| {
346        if !commands.last().is_some_and(Vec::is_empty) {
347            commands.push(Vec::new());
348        }
349    };
350    let mut at = 0;
351    while at < bytes.len() {
352        note_shell_scan_steps(1);
353        let before = at;
354        match bytes[at] {
355            byte if is_shell_blank(byte) => at += 1,
356            b'\\' if bytes.get(at + 1) == Some(&b'\n') => at += 2,
357            b'\n' | b';' | b'(' | b')' => {
358                end_command(&mut commands);
359                at += 1;
360            }
361            b'|' => {
362                end_command(&mut commands);
363                at += 1 + usize::from(matches!(bytes.get(at + 1), Some(b'|' | b'&')));
364            }
365            b'&' if bytes.get(at + 1) != Some(&b'>') => {
366                end_command(&mut commands);
367                at += 1 + usize::from(bytes.get(at + 1) == Some(&b'&'));
368            }
369            b'&' | b'<' | b'>' if !starts_process_substitution(bytes, at) => {
370                let (token, next) = scan_redirect(text, at, &mut quoted);
371                commands.last_mut().unwrap().push(token);
372                at = next;
373            }
374            _ => {
375                let next = scan_shell_word(text, at, &mut quoted);
376                // A file-descriptor number attached to a redirection (`2>`).
377                if text[at..next].bytes().all(|byte| byte.is_ascii_digit())
378                    && matches!(bytes.get(next), Some(b'<' | b'>'))
379                {
380                    let (mut token, after) = scan_redirect(text, next, &mut quoted);
381                    token.range.start = at;
382                    commands.last_mut().unwrap().push(token);
383                    at = after;
384                } else {
385                    commands.last_mut().unwrap().push(ShellToken {
386                        kind: ShellTokenKind::Word,
387                        range: at..next,
388                    });
389                    at = next;
390                }
391            }
392        }
393        // Every arm above consumes at least one byte: the word arm is only
394        // reached on a byte that does not end a word, or on the `<(` / `>(`
395        // that opens a process substitution, which the word scan consumes
396        // whole. Should a future change
397        // break that, step over one character rather than loop forever on
398        // a spawn path.
399        if at <= before {
400            debug_assert!(false, "shell scan stalled at byte {before} of {text:?}");
401            at = before + text[before..].chars().next().map_or(1, char::len_utf8);
402        }
403    }
404    (commands, quoted)
405}
406
407/// The end of the shell word starting at `start`, recording the inside of
408/// each quoted run. An unclosed quote runs to the end of `text`.
409fn scan_shell_word(text: &str, start: usize, quoted: &mut Vec<std::ops::Range<usize>>) -> usize {
410    let bytes = text.as_bytes();
411    let mut at = start;
412    while at < bytes.len() {
413        note_shell_scan_steps(1);
414        match bytes[at] {
415            b'\'' => {
416                let close = text[at + 1..]
417                    .find('\'')
418                    .map_or(bytes.len(), |off| at + 1 + off);
419                quoted.push(at + 1..close);
420                at = (close + 1).min(bytes.len());
421            }
422            b'"' => {
423                let mut close = at + 1;
424                while close < bytes.len() && bytes[close] != b'"' {
425                    close += if bytes[close] == b'\\' { 2 } else { 1 };
426                }
427                let close = close.min(bytes.len());
428                quoted.push(at + 1..close);
429                at = (close + 1).min(bytes.len());
430            }
431            b'\\' => at = (at + 2).min(bytes.len()),
432            // A substitution belongs to the word around it; its body is
433            // scanned as a command one level down.
434            b'$' if bytes.get(at + 1) == Some(&b'(') => {
435                let close = substitution_end(text, at + 2);
436                quoted.push(at + 2..close);
437                at = (close + 1).min(bytes.len());
438            }
439            b'<' | b'>' if starts_process_substitution(bytes, at) => {
440                let close = substitution_end(text, at + 2);
441                quoted.push(at + 2..close);
442                at = (close + 1).min(bytes.len());
443            }
444            b'`' => {
445                let close = backtick_end(bytes, at + 1);
446                quoted.push(at + 1..close);
447                at = (close + 1).min(bytes.len());
448            }
449            byte if ends_shell_word(byte) => break,
450            _ => at += 1,
451        }
452    }
453    // Stay on a character boundary after a backslash before a multibyte char.
454    while !text.is_char_boundary(at) {
455        at += 1;
456    }
457    at
458}
459
460/// A redirection operator at `start` (`<`, `>>`, `<<<`, `>&`, `&>`, `>|`,
461/// `<<-`) and its target word, attached or after spaces, if one follows.
462fn scan_redirect(
463    text: &str,
464    start: usize,
465    quoted: &mut Vec<std::ops::Range<usize>>,
466) -> (ShellToken, usize) {
467    let bytes = text.as_bytes();
468    let mut at = start + usize::from(bytes[start] == b'&');
469    let mut arrows = 0;
470    while arrows < 3 && matches!(bytes.get(at), Some(b'<' | b'>')) {
471        at += 1;
472        arrows += 1;
473    }
474    if matches!(bytes.get(at), Some(b'&' | b'|' | b'-')) {
475        at += 1;
476    }
477    let mut target = at;
478    while bytes.get(target).is_some_and(|byte| is_shell_blank(*byte)) {
479        target += 1;
480    }
481    let starts_word = bytes
482        .get(target)
483        .is_some_and(|byte| !ends_shell_word(*byte));
484    if starts_word {
485        at = scan_shell_word(text, target, quoted);
486    }
487    (
488        ShellToken {
489            kind: ShellTokenKind::Redirect,
490            range: start..at,
491        },
492        at,
493    )
494}
495
496/// A shell word as the program sees it: quotes removed, escapes resolved.
497fn unquote_shell_word(word: &str) -> String {
498    let mut out = String::with_capacity(word.len());
499    let mut chars = word.chars();
500    let mut quote = None;
501    while let Some(ch) = chars.next() {
502        match (quote, ch) {
503            (None, '\'' | '"') => quote = Some(ch),
504            (Some(open), _) if ch == open => quote = None,
505            (Some('\''), _) => out.push(ch),
506            (_, '\\') => {
507                if let Some(next) = chars.next() {
508                    if next != '\n' {
509                        out.push(next);
510                    }
511                }
512            }
513            _ => out.push(ch),
514        }
515    }
516    out
517}
518
519/// Mask the passwords that curl (`-u`/`--user`), the MySQL family (`-p<pw>`)
520/// and sshpass (`-p pw`) take on the command line, wherever those programs
521/// run in `command`: after assignments or wrappers (`env`, `sudo`,
522/// `command`), inside subshells and substitutions, across continuation
523/// lines, and inside a quoted string handed to another shell.
524fn mask_tool_passwords(command: &str) -> Cow<'_, str> {
525    if !["curl", "mysql", "mariadb", "sshpass"]
526        .iter()
527        .any(|program| command.contains(program))
528    {
529        return Cow::Borrowed(command);
530    }
531    let mut masks = Vec::new();
532    let scanned = crate::compress::generic::floor_char_boundary(
533        command,
534        command.len().min(MAX_SCANNED_COMMAND_BYTES),
535    );
536    collect_tool_password_masks(&command[..scanned], 0, 0, &mut masks);
537    if scanned < command.len() {
538        masks.push((scanned..command.len(), SECRET_PLACEHOLDER.to_string()));
539    }
540    if masks.is_empty() {
541        return Cow::Borrowed(command);
542    }
543    masks.sort_by_key(|(range, _): &(std::ops::Range<usize>, String)| range.start);
544    let mut out = String::with_capacity(command.len());
545    let mut copied = 0;
546    for (range, replacement) in masks {
547        if range.start < copied {
548            // Overlaps a span already replaced: drop the rest of this span
549            // too, so no byte of either one is written out.
550            copied = copied.max(range.end);
551            continue;
552        }
553        out.push_str(&command[copied..range.start]);
554        out.push_str(&replacement);
555        copied = range.end;
556    }
557    out.push_str(&command[copied..]);
558    if out == command {
559        Cow::Borrowed(command)
560    } else {
561        Cow::Owned(out)
562    }
563}
564
565#[cfg(any(test, feature = "test-support"))]
566thread_local! {
567    /// Bytes tokenized plus tokens visited by the tool-password scan, so a
568    /// test can check the work stays linear in the command's length.
569    static SHELL_SCAN_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
570    /// A test's step budget: exceeding it panics at once, so a superlinear
571    /// scan fails quickly instead of running for hours on a large command.
572    static SHELL_SCAN_BUDGET: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
573}
574
575#[cfg(any(test, feature = "test-support"))]
576fn note_shell_scan_steps(steps: usize) {
577    let total = SHELL_SCAN_STEPS.with(|count| {
578        count.set(count.get().saturating_add(steps));
579        count.get()
580    });
581    let budget = SHELL_SCAN_BUDGET.with(std::cell::Cell::get);
582    assert!(
583        total <= budget,
584        "shell scan took {total} steps, over its budget of {budget}"
585    );
586}
587
588#[cfg(not(any(test, feature = "test-support")))]
589fn note_shell_scan_steps(_steps: usize) {}
590
591/// Where sshpass's own options stand in one command.
592#[derive(Clone, Copy, PartialEq, Eq)]
593enum SshpassOptions {
594    NotSeen,
595    Reading,
596    /// The next word is the value of `-f`, `-d` or `-P`.
597    SkipValue,
598    /// The next word is the password given to `-p`.
599    PasswordNext,
600    /// The wrapped command has started; its `-p` is not sshpass's.
601    Done,
602}
603
604/// Find the tool passwords in `text` (one level of quoting) in a single pass
605/// over each command's tokens, then in the quoted runs, at most
606/// [`QUOTED_COMMAND_DEPTH`] levels down. Quoted runs at one level do not
607/// overlap, so each byte is tokenized at most once per level.
608fn collect_tool_password_masks(
609    text: &str,
610    base: usize,
611    depth: usize,
612    masks: &mut Vec<(std::ops::Range<usize>, String)>,
613) {
614    let (commands, quoted) = split_shell_commands(text);
615    note_shell_scan_steps(1);
616    let mut local = Vec::new();
617    for tokens in &commands {
618        note_shell_scan_steps(tokens.len());
619        // A program's arguments run to the end of its command, as the
620        // shell passes them; each program seen so far keeps reading them.
621        let (mut curl, mut mysql) = (false, false);
622        let mut curl_user_next = false;
623        let mut sshpass = SshpassOptions::NotSeen;
624        for token in tokens {
625            if token.kind == ShellTokenKind::Redirect {
626                // An option followed by a redirection has no value here.
627                curl_user_next = false;
628                if sshpass == SshpassOptions::PasswordNext || sshpass == SshpassOptions::SkipValue {
629                    sshpass = SshpassOptions::Done;
630                }
631                continue;
632            }
633            let raw = &text[token.range.clone()];
634            if curl_user_next {
635                curl_user_next = false;
636                if let Some(masked) = mask_curl_password(raw) {
637                    local.push((token.range.clone(), masked));
638                }
639                continue;
640            }
641            match sshpass {
642                SshpassOptions::PasswordNext => {
643                    if !command_value_is_reference(raw) {
644                        local.push((token.range.clone(), SECRET_PLACEHOLDER.to_string()));
645                    }
646                    sshpass = SshpassOptions::Done;
647                    continue;
648                }
649                SshpassOptions::SkipValue => {
650                    sshpass = SshpassOptions::Reading;
651                    continue;
652                }
653                _ => {}
654            }
655            let plain = unquote_shell_word(raw);
656            let program = plain.rsplit('/').next().unwrap_or_default();
657            let program = program.strip_suffix(".exe").unwrap_or(program);
658            let is_curl = program == "curl";
659            let is_mysql = matches!(program, "mysql" | "mariadb" | "mysqladmin" | "mysqldump");
660            if (is_curl || is_mysql) && sshpass == SshpassOptions::Reading {
661                // The command sshpass wraps has started.
662                sshpass = SshpassOptions::Done;
663            }
664            match program {
665                _ if is_curl => {
666                    curl = true;
667                    continue;
668                }
669                _ if is_mysql => {
670                    mysql = true;
671                    continue;
672                }
673                "sshpass" => {
674                    sshpass = SshpassOptions::Reading;
675                    continue;
676                }
677                _ => {}
678            }
679            if curl {
680                if plain == "-u" || plain == "--user" {
681                    curl_user_next = true;
682                    continue;
683                }
684                if plain.starts_with("--user=") {
685                    curl_attached_mask(text, token, "--user=", &mut local);
686                } else if plain.starts_with("-u") && !plain.starts_with("--") {
687                    curl_attached_mask(text, token, "-u", &mut local);
688                }
689            }
690            if mysql && plain.starts_with("-p") {
691                mask_attached_password(text, token, "-p", &mut local);
692            }
693            if sshpass == SshpassOptions::Reading {
694                sshpass = match plain.as_str() {
695                    "-p" => SshpassOptions::PasswordNext,
696                    "-f" | "-d" | "-P" => SshpassOptions::SkipValue,
697                    _ if plain.starts_with("-p") => {
698                        mask_attached_password(text, token, "-p", &mut local);
699                        SshpassOptions::Done
700                    }
701                    _ if plain.starts_with('-') => SshpassOptions::Reading,
702                    _ => SshpassOptions::Done,
703                };
704            }
705        }
706    }
707    masks.extend(
708        local
709            .into_iter()
710            .map(|(range, replacement)| (range.start + base..range.end + base, replacement)),
711    );
712    for inner in quoted {
713        if depth < QUOTED_COMMAND_DEPTH {
714            collect_tool_password_masks(&text[inner.clone()], base + inner.start, depth + 1, masks);
715        } else if !inner.is_empty() {
716            // Too deep to scan: mask the whole body instead of logging it
717            // unscanned, so a credential nested past the limit never leaks.
718            masks.push((
719                base + inner.start..base + inner.end,
720                SECRET_PLACEHOLDER.to_string(),
721            ));
722        }
723    }
724}
725
726/// The value attached to an option word (`-uadmin:pw`, `--user=admin:pw`,
727/// `-ppw`) after `prefix`, as a range of `text`, when the word starts with
728/// the option as typed. A word whose option part is itself quoted
729/// (`"-ppw"`) yields `None` and is masked whole by the caller.
730fn attached_option_value(
731    text: &str,
732    token: &ShellToken,
733    prefix: &str,
734) -> Option<std::ops::Range<usize>> {
735    let raw = &text[token.range.clone()];
736    (raw.len() > prefix.len() && raw.starts_with(prefix))
737        .then(|| token.range.start + prefix.len()..token.range.end)
738}
739
740/// Mask the password half of an attached curl user value. When the option
741/// itself is quoted, the whole word becomes the placeholder: every byte that
742/// stays in the log is then one the command really had.
743fn curl_attached_mask(
744    text: &str,
745    token: &ShellToken,
746    prefix: &str,
747    masks: &mut Vec<(std::ops::Range<usize>, String)>,
748) {
749    match attached_option_value(text, token, prefix) {
750        Some(range) => {
751            if let Some(masked) = mask_curl_password(&text[range.clone()]) {
752                masks.push((range, masked));
753            }
754        }
755        None => {
756            let plain = unquote_shell_word(&text[token.range.clone()]);
757            let value = plain.strip_prefix(prefix).unwrap_or_default();
758            if mask_curl_password(value).is_some() {
759                masks.push((token.range.clone(), SECRET_PLACEHOLDER.to_string()));
760            }
761        }
762    }
763}
764
765/// Push a placeholder over an attached option value unless it is a
766/// reference; a quoted option word is masked whole.
767fn mask_attached_password(
768    text: &str,
769    token: &ShellToken,
770    prefix: &str,
771    masks: &mut Vec<(std::ops::Range<usize>, String)>,
772) {
773    match attached_option_value(text, token, prefix) {
774        Some(range) => {
775            if !command_value_is_reference(&text[range.clone()]) {
776                masks.push((range, SECRET_PLACEHOLDER.to_string()));
777            }
778        }
779        None => {
780            let plain = unquote_shell_word(&text[token.range.clone()]);
781            let value = plain.strip_prefix(prefix).unwrap_or_default();
782            if !command_value_is_reference(value) {
783                masks.push((token.range.clone(), SECRET_PLACEHOLDER.to_string()));
784            }
785        }
786    }
787}
788
789/// Mask what follows the first `:` of a `user:password` word, keeping the
790/// user and a quote pair that wraps the whole word (`"admin:<masked>"`).
791/// A word without a password, or whose password is a reference, is kept.
792fn mask_curl_password(word: &str) -> Option<String> {
793    let quote = word
794        .chars()
795        .next()
796        .filter(|first| matches!(first, '"' | '\'') && word.len() > 1 && word.ends_with(*first));
797    let body = match quote {
798        Some(_) => &word[1..word.len() - 1],
799        None => word,
800    };
801    let (user, password) = body.split_once(':')?;
802    if command_value_is_reference(password) {
803        return None;
804    }
805    let quote = quote.map(String::from).unwrap_or_default();
806    Some(format!("{quote}{user}:{SECRET_PLACEHOLDER}{quote}"))
807}
808
809/// A value that names another value instead of holding one: a variable or
810/// command substitution (`$GH_TOKEN`, `"$(gcloud secrets ...)"`), an empty
811/// string, a placeholder this module already wrote, or the next option.
812fn command_value_is_reference(value: &str) -> bool {
813    let unquoted = value.trim_matches(|ch| ch == '"' || ch == '\'');
814    unquoted.is_empty() || unquoted.starts_with(['$', '<', '-'])
815}
816
817/// Mask credentials typed inline in a shell command, for logs that quote the
818/// command. Applies [`aft_redactor`] plus command-only shapes: secret-named
819/// `NAME=value` assignments (including after `export` or `env`), credential
820/// long options, MySQL's `-p<value>`, `sshpass -p` and `curl -u user:pass`.
821/// Mask the whole command before shortening it for a log line: a token cut
822/// short no longer matches its pattern.
823pub fn redact_command(command: &str) -> Cow<'_, str> {
824    // Runs first, on the command as typed: the shapes below write
825    // placeholders that read as redirections to the shell-word scan.
826    let mut out = mask_tool_passwords(command);
827    let mapping = RangeMapping::Watch;
828    if command.contains('=') {
829        out = replace_in(
830            out,
831            None,
832            &COMMAND_SECRET_ASSIGNMENT,
833            |caps: &Captures<'_>| {
834                let name = &caps[2];
835                if command_value_is_reference(&caps[3])
836                    || COMMAND_NON_SECRET_NAME_SUFFIXES
837                        .iter()
838                        .any(|suffix| name.ends_with(suffix))
839                {
840                    caps[0].to_string()
841                } else {
842                    format!("{}{name}{SECRET_PLACEHOLDER}", &caps[1])
843                }
844            },
845            mapping,
846        );
847        out = replace_in(
848            out,
849            None,
850            &INLINE_ASSIGNMENT,
851            |caps: &Captures<'_>| {
852                if looks_like_assignment_secret(caps[3].trim_matches(['\'', '"'])) {
853                    masked_assignment(caps)
854                } else {
855                    caps[0].to_string()
856                }
857            },
858            mapping,
859        );
860    }
861    if command.contains("--") {
862        out = replace_in(
863            out,
864            None,
865            &COMMAND_SECRET_FLAG,
866            |caps: &Captures<'_>| {
867                if command_value_is_reference(&caps[3]) {
868                    caps[0].to_string()
869                } else {
870                    format!("{}{}{SECRET_PLACEHOLDER}", &caps[1], &caps[2])
871                }
872            },
873            mapping,
874        );
875    }
876    match aft_redactor(&out) {
877        Cow::Borrowed(_) => out,
878        Cow::Owned(masked) => Cow::Owned(masked),
879    }
880}
881
882// Separate limits bound byte scanning and expensive candidate hashes. Long
883// non-hex verdict lines need no hashes and can still retain their placeholders.
884pub const TICKET_REDACTION_BYTES: usize = 50 * 1024;
885pub const TICKET_REDACTION_WINDOWS: usize = 8 * 1024;
886
887// A 4 KiB range plus both 31-byte halos remains below the existing ticket
888// scanner's byte and candidate budgets, including an all-hex source window.
889const SHELL_TICKET_RANGE_BYTES: usize = 4 * 1024;
890
891pub fn shells_ticket_range(
892    text: &str,
893    range: std::ops::Range<usize>,
894    digest: Option<&str>,
895) -> Result<String, TicketRedactionBudgetExceeded> {
896    if digest.is_none() {
897        return Ok(text[range].to_owned());
898    }
899    let mut output = String::new();
900    let mut from = range.start;
901    while from < range.end {
902        let to = crate::compress::generic::floor_char_boundary(
903            text,
904            (from + SHELL_TICKET_RANGE_BYTES).min(range.end),
905        );
906        let start = crate::compress::generic::floor_char_boundary(
907            text,
908            from.saturating_sub(TICKET_HALO_BYTES),
909        );
910        let end = crate::compress::generic::ceil_char_boundary(
911            text,
912            (to + TICKET_HALO_BYTES).min(text.len()),
913        );
914        let source = &text[start..end];
915        let mut low = (from - start)..(from - start);
916        let mut high = (to - start)..(to - start);
917        let masked = redact_ticket_digest_range(source, &mut low, digest)?;
918        let _ = redact_ticket_digest_range(source, &mut high, digest)?;
919        output.push_str(
920            masked
921                .get(low.end..high.end)
922                .ok_or(TicketRedactionBudgetExceeded)?,
923        );
924        from = to;
925    }
926    Ok(output)
927}
928pub const TICKET_HALO_BYTES: usize = 31;
929
930#[derive(Debug)]
931pub struct TicketRedactionBudgetExceeded;
932
933/// Redact only a 32-hex candidate whose BLAKE3 digest matches this task's stored
934/// ticket digest. This keeps ordinary hashes and identifiers unchanged in previews.
935pub fn redact_ticket_digest<'a>(
936    text: &'a str,
937    digest: Option<&str>,
938) -> Result<Cow<'a, str>, TicketRedactionBudgetExceeded> {
939    redact_ticket_digest_with_range(text, None, digest)
940}
941
942#[cfg(any(test, feature = "test-support"))]
943thread_local! {
944    pub static TICKET_HASH_PROBE: std::cell::RefCell<Option<Box<dyn FnMut()>>> = const { std::cell::RefCell::new(None) };
945}
946
947/// Range-aware form used when a watch match is anchored in captured output.
948pub fn redact_ticket_digest_range<'a>(
949    text: &'a str,
950    range: &mut std::ops::Range<usize>,
951    digest: Option<&str>,
952) -> Result<Cow<'a, str>, TicketRedactionBudgetExceeded> {
953    redact_ticket_digest_with_range(text, Some(range), digest)
954}
955
956fn redact_ticket_digest_with_range<'a>(
957    text: &'a str,
958    mut range: Option<&mut std::ops::Range<usize>>,
959    digest: Option<&str>,
960) -> Result<Cow<'a, str>, TicketRedactionBudgetExceeded> {
961    let Some(digest) = digest else {
962        return Ok(Cow::Borrowed(text));
963    };
964    if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
965        return Ok(Cow::Borrowed(text));
966    }
967    // Refuse before hashing any candidate. A caller must withhold the rendered
968    // region rather than fall back to the unmasked input on budget exhaustion.
969    if text.len() > TICKET_REDACTION_BYTES || ticket_digest_windows(text) > TICKET_REDACTION_WINDOWS
970    {
971        return Err(TicketRedactionBudgetExceeded);
972    }
973    let bytes = text.as_bytes();
974    if bytes.len() < 32 {
975        return Ok(Cow::Borrowed(text));
976    }
977    let mut spans: Vec<std::ops::Range<usize>> = Vec::new();
978    let mut cursor = 0;
979    while cursor < bytes.len() {
980        if !bytes[cursor].is_ascii_hexdigit() {
981            cursor += 1;
982            continue;
983        }
984        let run_start = cursor;
985        while cursor < bytes.len() && bytes[cursor].is_ascii_hexdigit() {
986            cursor += 1;
987        }
988        let run_end = cursor;
989        if run_end - run_start < 32 {
990            continue;
991        }
992        for start in run_start..=(run_end - 32) {
993            let end = start + 32;
994            let candidate = &text[start..end];
995            #[cfg(any(test, feature = "test-support"))]
996            TICKET_HASH_PROBE.with(|probe| {
997                if let Some(probe) = probe.borrow_mut().as_mut() {
998                    probe();
999                }
1000            });
1001            if blake3::hash(candidate.as_bytes()).to_hex().as_str() != digest {
1002                continue;
1003            }
1004            if let Some(previous) = spans.last_mut() {
1005                if start < previous.end {
1006                    previous.end = previous.end.max(end);
1007                    continue;
1008                }
1009            }
1010            spans.push(start..end);
1011        }
1012    }
1013    if spans.is_empty() {
1014        return Ok(Cow::Borrowed(text));
1015    }
1016    let mut masked = String::with_capacity(text.len());
1017    let mut copied = 0;
1018    for span in spans {
1019        masked.push_str(&text[copied..span.start]);
1020        let replacement_start = masked.len();
1021        masked.push_str(SECRET_PLACEHOLDER);
1022        if let Some(range) = range.as_deref_mut() {
1023            map_redacted_range(
1024                range,
1025                replacement_start,
1026                replacement_start + span.len(),
1027                SECRET_PLACEHOLDER.len(),
1028            );
1029        }
1030        copied = span.end;
1031    }
1032    masked.push_str(&text[copied..]);
1033    Ok(Cow::Owned(masked))
1034}
1035
1036pub fn ticket_digest_windows(text: &str) -> usize {
1037    text.as_bytes()
1038        .split(|byte| !byte.is_ascii_hexdigit())
1039        .map(|run| run.len().saturating_sub(31))
1040        .sum()
1041}
1042
1043#[derive(Clone, Copy)]
1044enum RangeMapping {
1045    Watch,
1046    Stream,
1047}
1048
1049fn redact_with_range<'a>(
1050    text: &'a str,
1051    mut range: Option<&mut std::ops::Range<usize>>,
1052    mapping: RangeMapping,
1053) -> Cow<'a, str> {
1054    let mut out = Cow::Borrowed(text);
1055    if text.contains("PRIVATE KEY-----") {
1056        out = replace_in(
1057            out,
1058            range.as_deref_mut(),
1059            &PRIVATE_KEY,
1060            SECRET_PLACEHOLDER,
1061            mapping,
1062        );
1063    }
1064    if text.contains("xox") {
1065        out = replace_in(
1066            out,
1067            range.as_deref_mut(),
1068            &SLACK_TOKEN,
1069            SECRET_PLACEHOLDER,
1070            mapping,
1071        );
1072    }
1073    if contains_ignore_ascii_case(text, "x-api-key") {
1074        out = replace_in(
1075            out,
1076            range.as_deref_mut(),
1077            &API_KEY_HEADER,
1078            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}", &caps[1]),
1079            mapping,
1080        );
1081    }
1082    if text.contains('"') {
1083        out = replace_in(
1084            out,
1085            range.as_deref_mut(),
1086            &SECRET_JSON_FIELD,
1087            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}{}", &caps[1], &caps[3]),
1088            mapping,
1089        );
1090    }
1091    if contains_ignore_ascii_case(text, "secret_access_key") {
1092        out = replace_in(
1093            out,
1094            range.as_deref_mut(),
1095            &AWS_SECRET_FIELD,
1096            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}", &caps[1]),
1097            mapping,
1098        );
1099    }
1100    if contains_ignore_ascii_case(text, "authorization") {
1101        out = replace_in(
1102            out,
1103            range.as_deref_mut(),
1104            &AUTHORIZATION_HEADER,
1105            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}", &caps[1]),
1106            mapping,
1107        );
1108    }
1109    if text.contains("github_pat_") {
1110        out = replace_in(
1111            out,
1112            range.as_deref_mut(),
1113            &GITHUB_PAT,
1114            SECRET_PLACEHOLDER,
1115            mapping,
1116        );
1117    }
1118    if needs_github_token_scan(text) {
1119        out = replace_in(
1120            out,
1121            range.as_deref_mut(),
1122            &GITHUB_TOKEN,
1123            SECRET_PLACEHOLDER,
1124            mapping,
1125        );
1126    }
1127    if text.contains("sk-") {
1128        out = replace_in(
1129            out,
1130            range.as_deref_mut(),
1131            &SK_API_KEY,
1132            SECRET_PLACEHOLDER,
1133            mapping,
1134        );
1135    }
1136    if text.contains("eyJ") {
1137        out = replace_in(out, range.as_deref_mut(), &JWT, SECRET_PLACEHOLDER, mapping);
1138    }
1139    if ["AKIA", "ASIA", "AGPA", "AIDA", "AROA"]
1140        .iter()
1141        .any(|prefix| text.contains(prefix))
1142    {
1143        out = replace_in(
1144            out,
1145            range.as_deref_mut(),
1146            &AWS_ACCESS_KEY_ID,
1147            SECRET_PLACEHOLDER,
1148            mapping,
1149        );
1150    }
1151    if text.contains("://") {
1152        out = replace_in(
1153            out,
1154            range.as_deref_mut(),
1155            &URL_USERINFO,
1156            |caps: &Captures<'_>| format!("{}{URL_CREDENTIAL_PLACEHOLDER}@", &caps[1]),
1157            mapping,
1158        );
1159    }
1160    if text.contains('=') && (text.contains('?') || text.contains('&')) {
1161        out = replace_in(
1162            out,
1163            range.as_deref_mut(),
1164            &CREDENTIAL_QUERY,
1165            |caps: &Captures<'_>| format!("{}{SECRET_PLACEHOLDER}", &caps[1]),
1166            mapping,
1167        );
1168        out = replace_in(
1169            out,
1170            range.as_deref_mut(),
1171            &KEY_QUERY,
1172            |caps: &Captures<'_>| {
1173                if looks_like_secret(&caps[2]) {
1174                    format!("{}{SECRET_PLACEHOLDER}", &caps[1])
1175                } else {
1176                    caps[0].to_string()
1177                }
1178            },
1179            mapping,
1180        );
1181    }
1182    if text.contains('=') {
1183        out = replace_in(
1184            out,
1185            range.as_deref_mut(),
1186            &SHORT_PASSWORD_ASSIGNMENT,
1187            |caps: &Captures<'_>| {
1188                let raw = &caps[3];
1189                let value = raw.trim_matches(['\'', '"']);
1190                if is_short_password_name(&caps[2]) && !value.starts_with(['$', '<']) {
1191                    masked_assignment(caps)
1192                } else {
1193                    caps[0].to_string()
1194                }
1195            },
1196            mapping,
1197        );
1198    }
1199    out
1200}
1201
1202fn masked_assignment(caps: &Captures<'_>) -> String {
1203    let raw = &caps[3];
1204    let quote = if raw.starts_with(['\'', '"']) {
1205        &raw[..1]
1206    } else {
1207        ""
1208    };
1209    format!("{}{quote}{SECRET_PLACEHOLDER}{quote}", &caps[1])
1210}
1211
1212fn is_short_password_name(key: &str) -> bool {
1213    let suffix = key.rsplit('_').next().unwrap_or(key);
1214    suffix.eq_ignore_ascii_case("PW") || suffix.eq_ignore_ascii_case("PASS")
1215}
1216
1217/// A command's credential values, retained only with its live in-memory task.
1218/// Deliberately has no Debug or serialization implementation.
1219#[derive(Default)]
1220pub struct SecretValues(Vec<String>);
1221
1222/// Whether an environment variable name marks its value as a completion secret.
1223pub fn is_secret_environment_key(key: &str) -> bool {
1224    if key.eq_ignore_ascii_case(crate::gh_shim_paths::GH_SHIM_TICKET_ENV) {
1225        return true;
1226    }
1227    // The SSH agent's socket path is an address, not credential material.
1228    if key.eq_ignore_ascii_case("SSH_AUTH_SOCK") {
1229        return false;
1230    }
1231    // Git's numbered config variables carry a setting NAME in GIT_CONFIG_KEY_<n>
1232    // (AFT itself injects core.hooksPath this way). The name is not a secret,
1233    // and dropping it alone while GIT_CONFIG_COUNT and GIT_CONFIG_VALUE_<n>
1234    // stay makes every git child exit with "missing config key".
1235    if key
1236        .get(.."GIT_CONFIG_KEY_".len())
1237        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("GIT_CONFIG_KEY_"))
1238    {
1239        return false;
1240    }
1241    ["TOKEN", "SECRET", "KEY", "PASSWORD", "PASSWD", "CREDENTIAL"]
1242        .iter()
1243        .any(|part| contains_ignore_ascii_case(key, part))
1244        || is_short_password_name(key)
1245        || names_auth(key)
1246}
1247
1248/// Whether `key` contains "AUTH" other than as the word AUTHOR, which names a
1249/// person rather than a credential: GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
1250/// AFT_GIT_CO_AUTHOR, the co-author trailer AFT itself gives every governed
1251/// child. Counting those made every such child look like it carried a secret,
1252/// so its output previews were withheld after a daemon restart. AUTHOR counts
1253/// as a word only at the end of the name or before an underscore; AUTHORITY,
1254/// AUTHORIZATION, AUTH_TOKEN and NPM_AUTH still count.
1255fn names_auth(key: &str) -> bool {
1256    let key = key.as_bytes();
1257    (0..key.len()).any(|at| {
1258        let rest = &key[at..];
1259        if rest.len() < 4 || !rest[..4].eq_ignore_ascii_case(b"AUTH") {
1260            return false;
1261        }
1262        let author_word = rest.len() >= 6
1263            && rest[4..6].eq_ignore_ascii_case(b"OR")
1264            && matches!(rest.get(6), None | Some(b'_'));
1265        !author_word
1266    })
1267}
1268
1269impl SecretValues {
1270    pub fn longest_value_len(&self) -> usize {
1271        self.0.iter().map(String::len).max().unwrap_or(0)
1272    }
1273    pub fn is_empty(&self) -> bool {
1274        self.0.is_empty()
1275    }
1276    /// Whether a value contains a newline, so it can cross a cut made at one.
1277    pub fn has_multiline_value(&self) -> bool {
1278        self.0.iter().any(|value| value.contains('\n'))
1279    }
1280
1281    /// Byte ranges in `text` of every occurrence of a value that contains a
1282    /// newline. Only these occurrences can cross a cut made at a newline.
1283    pub fn cross_line_spans(&self, text: &str) -> Vec<std::ops::Range<usize>> {
1284        let mut spans = Vec::new();
1285        for value in self.0.iter().filter(|value| value.contains('\n')) {
1286            let mut start = 0;
1287            while let Some(offset) = text[start..].find(value.as_str()) {
1288                let from = start + offset;
1289                spans.push(from..from + value.len());
1290                start = from + text[from..].chars().next().unwrap().len_utf8();
1291            }
1292        }
1293        spans
1294    }
1295
1296    pub fn from_environment<'a>(
1297        env: impl IntoIterator<Item = (&'a std::ffi::OsStr, &'a std::ffi::OsStr)>,
1298    ) -> Self {
1299        let mut values = Vec::new();
1300        for (key, value) in env {
1301            let (Some(key), Some(value)) = (key.to_str(), value.to_str()) else {
1302                continue;
1303            };
1304            if value.chars().count() >= 8 && is_secret_environment_key(key) {
1305                values.push(value.to_owned());
1306            }
1307        }
1308        values.sort_unstable_by_key(|value| std::cmp::Reverse(value.len()));
1309        values.dedup();
1310        Self(values)
1311    }
1312
1313    pub fn redact<'a>(&self, text: &'a str) -> Cow<'a, str> {
1314        self.redact_range(text, None)
1315    }
1316
1317    pub fn redact_range<'a>(
1318        &self,
1319        text: &'a str,
1320        range: Option<&mut std::ops::Range<usize>>,
1321    ) -> Cow<'a, str> {
1322        self.redact_range_with_mapping(text, range, RangeMapping::Watch)
1323    }
1324
1325    pub fn redact_stream_range<'a>(
1326        &self,
1327        text: &'a str,
1328        range: &mut std::ops::Range<usize>,
1329    ) -> Cow<'a, str> {
1330        self.redact_range_with_mapping(text, Some(range), RangeMapping::Stream)
1331    }
1332
1333    fn redact_range_with_mapping<'a>(
1334        &self,
1335        text: &'a str,
1336        mut range: Option<&mut std::ops::Range<usize>>,
1337        mapping: RangeMapping,
1338    ) -> Cow<'a, str> {
1339        // Exact matches run first: a format-based replacement inside an opaque
1340        // value must not leave the rest of that value visible.
1341        let mut spans = Vec::new();
1342        for value in &self.0 {
1343            let mut start = 0;
1344            while let Some(offset) = text[start..].find(value) {
1345                let from = start + offset;
1346                spans.push((from, from + value.len()));
1347                start = from + text[from..].chars().next().unwrap().len_utf8();
1348            }
1349        }
1350        let out = if spans.is_empty() {
1351            Cow::Borrowed(text)
1352        } else {
1353            spans.sort_unstable();
1354            let mut masked = String::new();
1355            let mut copied = 0;
1356            let mut spans = spans.into_iter().peekable();
1357            while let Some((start, mut end)) = spans.next() {
1358                while spans.peek().is_some_and(|(next, _)| *next <= end) {
1359                    end = end.max(spans.next().unwrap().1);
1360                }
1361                masked.push_str(&text[copied..start]);
1362                if let Some(range) = range.as_deref_mut() {
1363                    match mapping {
1364                        RangeMapping::Watch => map_redacted_range(
1365                            range,
1366                            masked.len(),
1367                            masked.len() + end - start,
1368                            SECRET_PLACEHOLDER.len(),
1369                        ),
1370                        RangeMapping::Stream => map_stream_range(
1371                            range,
1372                            masked.len(),
1373                            masked.len() + end - start,
1374                            SECRET_PLACEHOLDER.len(),
1375                        ),
1376                    }
1377                }
1378                masked.push_str(SECRET_PLACEHOLDER);
1379                copied = end;
1380            }
1381            masked.push_str(&text[copied..]);
1382            Cow::Owned(masked)
1383        };
1384        match redact_with_range(&out, range, mapping) {
1385            Cow::Borrowed(_) => out,
1386            Cow::Owned(masked) => Cow::Owned(masked),
1387        }
1388    }
1389}
1390
1391fn needs_github_token_scan(text: &str) -> bool {
1392    ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"]
1393        .iter()
1394        .any(|prefix| text.contains(prefix))
1395}
1396
1397// How far a match can reach. A caller that masks a slice of a larger capture
1398// (a watch preview) cuts that slice at newlines. The cut is safe for a pattern
1399// only if none of its matches can contain a newline:
1400// - AUTHORIZATION_HEADER, API_KEY_HEADER and AWS_SECRET_FIELD separate their
1401//   parts with `[^\S\r\n]` (spaces and tabs only) and their values exclude `\s`;
1402// - SLACK_TOKEN, GITHUB_PAT, GITHUB_TOKEN, SK_API_KEY, JWT and
1403//   AWS_ACCESS_KEY_ID consist of letters, digits, `_`, `-` and `.` only;
1404// - URL_USERINFO, CREDENTIAL_QUERY and KEY_QUERY values exclude `\s`.
1405// Two patterns can cross a newline, and the functions below report them:
1406// - SECRET_JSON_FIELD allows `\s*` (including newlines) around its colon and a
1407//   raw newline inside the quoted value;
1408// - PRIVATE_KEY (`(?s)`) runs from its BEGIN line to the END line, or to the end
1409//   of the text when no END line follows.
1410// Exact credential values (see SecretValues) cross a newline only when the
1411// value itself contains one.
1412
1413/// Byte ranges of the masked JSON secret fields in `text`. A field can span
1414/// lines, so a slice cut at a newline may hold only part of one.
1415pub fn json_secret_field_spans(text: &str) -> Vec<std::ops::Range<usize>> {
1416    if !text.contains('"') {
1417        return Vec::new();
1418    }
1419    SECRET_JSON_FIELD
1420        .find_iter(text)
1421        .map(|found| found.range())
1422        .collect()
1423}
1424
1425/// Byte ranges of the masked private-key blocks in `text`. A block ends at its
1426/// END line or, without one, at the end of `text`.
1427pub fn private_key_spans(text: &str) -> Vec<std::ops::Range<usize>> {
1428    if !text.contains("PRIVATE KEY-----") {
1429        return Vec::new();
1430    }
1431    PRIVATE_KEY
1432        .find_iter(text)
1433        .map(|found| found.range())
1434        .collect()
1435}
1436
1437/// Whether `text` holds a private-key BEGIN or END line. Without one, `text`
1438/// alone cannot tell whether it starts inside a key block.
1439pub fn has_private_key_marker(text: &str) -> bool {
1440    text.contains("PRIVATE KEY-----")
1441}
1442
1443/// Whether `line` has the shape of a PEM private-key body line: 40 to 76
1444/// base64 characters mixing upper case, lower case and digits. Lower-case hex
1445/// digests and ordinary words do not qualify; a mixed-case hex string can.
1446pub fn looks_like_private_key_body(line: &str) -> bool {
1447    let line = line.trim_end_matches('\r');
1448    (40..=76).contains(&line.len())
1449        && line
1450            .bytes()
1451            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'='))
1452        && line.bytes().any(|byte| byte.is_ascii_uppercase())
1453        && line.bytes().any(|byte| byte.is_ascii_lowercase())
1454        && line.bytes().any(|byte| byte.is_ascii_digit())
1455}
1456
1457/// Whether a JSON secret value that opens before byte `before` is still open
1458/// at the end of `text`. Its closing quote, and so the match, may lie past the
1459/// end of `text`; masking `text` alone would then show the value.
1460pub fn json_secret_value_open_at_end(text: &str, before: usize) -> bool {
1461    if !text.contains('"') {
1462        return false;
1463    }
1464    SECRET_JSON_OPENING
1465        .find_iter(text)
1466        .take_while(|opening| opening.start() < before)
1467        .any(|opening| {
1468            // Mirror the value grammar `(?:\\.|[^"\\])+`: a backslash escapes
1469            // any character except a newline, and an unescaped quote closes it.
1470            let mut chars = text[opening.end()..].chars();
1471            loop {
1472                match chars.next() {
1473                    None => return true,
1474                    Some('"') => return false,
1475                    Some('\\') => match chars.next() {
1476                        None => return true,
1477                        Some('\n') => return false,
1478                        Some(_) => {}
1479                    },
1480                    Some(_) => {}
1481                }
1482            }
1483        })
1484}
1485
1486static SECRET_JSON_LABEL_AT_END: LazyLock<Regex> =
1487    LazyLock::new(|| compile(&format!(r#"(?i)"(?:{JSON_SECRET_LABELS})"\s*(?::\s*)?\z"#)));
1488
1489/// Whether `text` ends after a JSON secret field's label (and possibly its
1490/// colon) but before the opening quote of its value. The value, and so the
1491/// [`SECRET_JSON_FIELD`] match, would start past the end of `text`.
1492pub fn json_secret_label_open_at_end(text: &str) -> bool {
1493    text.contains('"') && SECRET_JSON_LABEL_AT_END.is_match(text)
1494}
1495
1496/// Byte-level entry point for the log sink. Invalid UTF-8 is decoded with
1497/// replacement characters before masking so malformed bytes cannot bypass it.
1498pub fn aft_redact_bytes(bytes: &[u8]) -> Cow<'_, [u8]> {
1499    let Ok(text) = std::str::from_utf8(bytes) else {
1500        return Cow::Owned(
1501            aft_redactor(&String::from_utf8_lossy(bytes))
1502                .into_owned()
1503                .into_bytes(),
1504        );
1505    };
1506    match aft_redactor(text) {
1507        Cow::Borrowed(_) => Cow::Borrowed(bytes),
1508        Cow::Owned(masked) => Cow::Owned(masked.into_bytes()),
1509    }
1510}
1511
1512/// Cut `text` to at most `max_bytes` (on a char boundary) and note how much
1513/// was dropped as `…(+N bytes)`. Used for payloads that are useful to glimpse
1514/// in a debug line but can be arbitrarily large (LSP params, parser errors).
1515pub fn truncate_for_log(text: &str, max_bytes: usize) -> Cow<'_, str> {
1516    if text.len() <= max_bytes {
1517        return Cow::Borrowed(text);
1518    }
1519    let mut cut = max_bytes;
1520    while !text.is_char_boundary(cut) {
1521        cut -= 1;
1522    }
1523    Cow::Owned(format!("{}…(+{} bytes)", &text[..cut], text.len() - cut))
1524}
1525
1526/// Describe a request line that must not itself be logged: its byte length and
1527/// a short SHA-256 prefix, enough to correlate with a copy the caller kept.
1528pub fn unlogged_input_summary(input: &str) -> String {
1529    use sha2::{Digest, Sha256};
1530    let digest = Sha256::digest(input.as_bytes());
1531    let short: String = digest[..6]
1532        .iter()
1533        .map(|byte| format!("{byte:02x}"))
1534        .collect();
1535    format!("bytes={} sha256={short}", input.len())
1536}
1537
1538/// A `key=` value is treated as a secret when it is long, uses only
1539/// token-safe characters, and mixes digits with upper- and lower-case letters
1540/// (an API key such as `AIzaSy…`). Words, paths and single-case hex hashes do
1541/// not qualify.
1542fn looks_like_secret(value: &str) -> bool {
1543    value.len() >= KEY_VALUE_MIN_SECRET_LEN
1544        && value
1545            .chars()
1546            .all(|ch| ch.is_ascii_alphanumeric() || "_-.~+/=".contains(ch))
1547        && value.chars().any(|ch| ch.is_ascii_digit())
1548        && value.chars().any(|ch| ch.is_ascii_uppercase())
1549        && value.chars().any(|ch| ch.is_ascii_lowercase())
1550}
1551
1552/// Paths and URLs in command assignments are useful diagnostics, not tokens.
1553/// Keep this rule identical to the CLI sanitizer. Query keys instead use
1554/// [`looks_like_secret`] without the path-prefix exclusions.
1555fn looks_like_assignment_secret(value: &str) -> bool {
1556    !["/", "~/", "./", "../"]
1557        .iter()
1558        .any(|prefix| value.starts_with(prefix))
1559        && !value.contains("://")
1560        && looks_like_secret(value)
1561}
1562
1563fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
1564    haystack
1565        .as_bytes()
1566        .windows(needle.len())
1567        .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
1568}
1569
1570/// Apply one pattern, keeping the borrowed input when nothing changed. A match
1571/// can re-produce its own text (an already-masked `***@`, or a `key=` value
1572/// that does not look secret), so equality is checked, not just match count.
1573fn replace_in<'a, R: Replacer>(
1574    text: Cow<'a, str>,
1575    mut range: Option<&mut std::ops::Range<usize>>,
1576    pattern: &Regex,
1577    mut replacer: R,
1578    mapping: RangeMapping,
1579) -> Cow<'a, str> {
1580    // Capture storage is allocated by replace_all even when it finds no match.
1581    // Keep the overwhelmingly common no-secret path allocation-free.
1582    if !pattern.is_match(&text) {
1583        return text;
1584    }
1585    let mut masked = String::new();
1586    let mut copied = 0;
1587    for caps in pattern.captures_iter(&text) {
1588        let found = caps.get(0).unwrap();
1589        masked.push_str(&text[copied..found.start()]);
1590        let from = masked.len();
1591        replacer.replace_append(&caps, &mut masked);
1592        if masked[from..] != *found.as_str() {
1593            if let Some(range) = range.as_deref_mut() {
1594                match mapping {
1595                    RangeMapping::Watch => {
1596                        map_redacted_range(range, from, from + found.len(), masked.len() - from)
1597                    }
1598                    RangeMapping::Stream => {
1599                        let before = found.as_str();
1600                        let after = &masked[from..];
1601                        let prefix = before
1602                            .chars()
1603                            .zip(after.chars())
1604                            .take_while(|(a, b)| a == b)
1605                            .map(|(ch, _)| ch.len_utf8())
1606                            .sum::<usize>();
1607                        let suffix = before[prefix..]
1608                            .chars()
1609                            .rev()
1610                            .zip(after[prefix..].chars().rev())
1611                            .take_while(|(a, b)| a == b)
1612                            .map(|(ch, _)| ch.len_utf8())
1613                            .sum::<usize>();
1614                        map_stream_range(
1615                            range,
1616                            from + prefix,
1617                            from + before.len() - suffix,
1618                            after.len() - prefix - suffix,
1619                        );
1620                    }
1621                }
1622            }
1623        }
1624        copied = found.end();
1625    }
1626    masked.push_str(&text[copied..]);
1627    if masked == *text {
1628        text
1629    } else {
1630        Cow::Owned(masked)
1631    }
1632}
1633
1634/// Assign a replacement to the raw range containing its first changed byte.
1635/// Unchanged prefix and suffix bytes keep their original stream positions.
1636fn map_stream_range(
1637    range: &mut std::ops::Range<usize>,
1638    from: usize,
1639    to: usize,
1640    replacement_len: usize,
1641) {
1642    let position = |at: usize| {
1643        if at <= from {
1644            at
1645        } else if at >= to {
1646            at - (to - from) + replacement_len
1647        } else {
1648            from + replacement_len
1649        }
1650    };
1651    range.start = position(range.start);
1652    range.end = position(range.end);
1653}
1654
1655/// Keep a watch's raw match anchored when a replacement changes byte lengths.
1656/// A match touching a secret expands to cover the entire visible placeholder.
1657fn map_redacted_range(
1658    range: &mut std::ops::Range<usize>,
1659    from: usize,
1660    to: usize,
1661    replacement_len: usize,
1662) {
1663    let shift = |position: usize| {
1664        position
1665            .saturating_sub(to - from)
1666            .saturating_add(replacement_len)
1667    };
1668    if range.start >= to {
1669        range.start = shift(range.start);
1670        range.end = shift(range.end);
1671    } else if range.end > from {
1672        range.start = range.start.min(from);
1673        range.end = if range.end >= to {
1674            shift(range.end)
1675        } else {
1676            from + replacement_len
1677        };
1678    }
1679}
1680
1681#[cfg(test)]
1682mod tests {
1683    use super::*;
1684
1685    #[test]
1686    fn only_json_fields_and_private_keys_match_across_a_newline() {
1687        let line_anchored: [(&str, &Regex); 14] = [
1688            ("AUTHORIZATION_HEADER", &AUTHORIZATION_HEADER),
1689            ("API_KEY_HEADER", &API_KEY_HEADER),
1690            ("AWS_SECRET_FIELD", &AWS_SECRET_FIELD),
1691            ("SLACK_TOKEN", &SLACK_TOKEN),
1692            ("GITHUB_PAT", &GITHUB_PAT),
1693            ("GITHUB_TOKEN", &GITHUB_TOKEN),
1694            ("SK_API_KEY", &SK_API_KEY),
1695            ("JWT", &JWT),
1696            ("AWS_ACCESS_KEY_ID", &AWS_ACCESS_KEY_ID),
1697            ("URL_USERINFO", &URL_USERINFO),
1698            ("CREDENTIAL_QUERY", &CREDENTIAL_QUERY),
1699            ("KEY_QUERY", &KEY_QUERY),
1700            ("INLINE_ASSIGNMENT", &INLINE_ASSIGNMENT),
1701            ("SHORT_PASSWORD_ASSIGNMENT", &SHORT_PASSWORD_ASSIGNMENT),
1702        ];
1703        let samples = [
1704            "Authorization: Bearer opaque-auth-value".to_string(),
1705            "Proxy-Authorization:\tBasic dXNlcjpwYXNz==".to_string(),
1706            "x-api-key: opaque-api-key-value".to_string(),
1707            "aws_secret_access_key = abc/def+ghi".to_string(),
1708            "xoxb-12345-slack-token".to_string(),
1709            "github_pat_11ABCDEFG0123456789_abcdef".to_string(),
1710            format!("ghp_{}", "a".repeat(36)),
1711            "sk-abcdefghijklmnopqrstuvwxyz0123456789".to_string(),
1712            "eyJhbGciOi.eyJzdWIiOi.c2lnbmF0dXJl".to_string(),
1713            "AKIAABCDEFGHIJKLMNOP".to_string(),
1714            "https://user:password@example.com/path".to_string(),
1715            "https://e.com/p?access_token=opaque&key=AbCdEfGh12345678Zz".to_string(),
1716            "PW=opaque X=\"AbCdEfGh12345678Zz\"".to_string(),
1717        ];
1718        for sample in &samples {
1719            for (cut, _) in sample.char_indices().skip(1) {
1720                let text = format!("{}\n{}", &sample[..cut], &sample[cut..]);
1721                for (name, pattern) in line_anchored {
1722                    for found in pattern.find_iter(&text) {
1723                        assert!(
1724                            !found.as_str().contains('\n'),
1725                            "{name} crossed a newline in {text:?}"
1726                        );
1727                    }
1728                }
1729            }
1730        }
1731        // The two exceptions, which watch previews widen their region for.
1732        assert!(SECRET_JSON_FIELD.is_match("{\"api_key\":\n  \"value\"}"));
1733        assert!(SECRET_JSON_FIELD.is_match("{\"api_key\":\"first\nsecond\"}"));
1734        assert!(PRIVATE_KEY.is_match("-----BEGIN PRIVATE KEY-----\nbody\n"));
1735    }
1736
1737    #[test]
1738    fn json_secret_value_open_at_end_follows_the_value_grammar() {
1739        let opening = "{\"api_key\": \"";
1740        let open = |text: &str| json_secret_value_open_at_end(text, text.len());
1741        assert!(open(&format!("{opening}abc\ndef")));
1742        assert!(open(&format!("{opening}abc\\")));
1743        assert!(!open(&format!("{opening}abc\\\"def\" more")));
1744        // A backslash before a newline ends the value without a match.
1745        assert!(!open(&format!("{opening}abc\\\ndef")));
1746        // Openings at or after `before` are outside the caller's region.
1747        assert!(!json_secret_value_open_at_end(
1748            &format!("x {opening}abc"),
1749            1
1750        ));
1751    }
1752
1753    #[test]
1754    fn ticket_digest_budget_refuses_before_hashing() {
1755        let digest = blake3::hash(b"0123456789abcdef0123456789abcdef")
1756            .to_hex()
1757            .to_string();
1758        TICKET_HASH_PROBE.with(|probe| {
1759            *probe.borrow_mut() = Some(Box::new(|| panic!("over-budget input was hashed")))
1760        });
1761        assert!(
1762            redact_ticket_digest(&"a".repeat(TICKET_REDACTION_WINDOWS + 32), Some(&digest))
1763                .is_err()
1764        );
1765        TICKET_HASH_PROBE.with(|probe| *probe.borrow_mut() = None);
1766    }
1767
1768    #[test]
1769    fn ticket_digest_hashes_only_complete_hex_windows() {
1770        let digest = blake3::hash(b"0123456789abcdef0123456789abcdef")
1771            .to_hex()
1772            .to_string();
1773        let count = std::rc::Rc::new(std::cell::Cell::new(0));
1774        let probe_count = count.clone();
1775        TICKET_HASH_PROBE.with(|probe| {
1776            *probe.borrow_mut() = Some(Box::new(move || probe_count.set(probe_count.get() + 1)))
1777        });
1778        let text = format!(
1779            "{} {} {} {}",
1780            "a".repeat(31),
1781            "g".repeat(1024),
1782            "a".repeat(32),
1783            "F".repeat(33)
1784        );
1785        assert_eq!(redact_ticket_digest(&text, Some(&digest)).unwrap(), text);
1786        TICKET_HASH_PROBE.with(|probe| *probe.borrow_mut() = None);
1787        assert_eq!(count.get(), 3);
1788    }
1789
1790    #[test]
1791    fn completion_exact_env_values_are_case_sensitive_and_overlap_safe() {
1792        let environment = [
1793            ("DEPLOY_tOkEn", "abcdefgh"),
1794            ("MY_SECRET", "fghijklm"),
1795            ("api_KEY", "key-value-long"),
1796            ("PASSWORD", "password-value"),
1797            ("PASSWD", "passwd-value"),
1798            ("CREDENTIALS", "credential-value"),
1799            ("AUTHORIZATION", "auth-value"),
1800            ("tiny_TOKEN", "short"),
1801            ("NORMAL_VALUE", "public-value"),
1802        ];
1803        let secrets = SecretValues::from_environment(
1804            environment
1805                .iter()
1806                .map(|(key, value)| (std::ffi::OsStr::new(key), std::ffi::OsStr::new(value))),
1807        );
1808        assert_eq!(
1809            secrets.redact("abcdefghijklm/abcdefgh"),
1810            format!("{SECRET_PLACEHOLDER}/{SECRET_PLACEHOLDER}")
1811        );
1812        for (_, value) in &environment[..7] {
1813            assert_eq!(
1814                secrets.redact(&format!("before{value}after")),
1815                format!("before{SECRET_PLACEHOLDER}after")
1816            );
1817        }
1818        assert!(matches!(
1819            secrets.redact("ABCDEFGH short public-value"),
1820            Cow::Borrowed(_)
1821        ));
1822    }
1823
1824    #[test]
1825    fn short_password_environment_names_do_not_include_pwd_or_bypass() {
1826        for key in ["PW", "PASS", "DB_PW", "DB_PASS", "db_pw", "db_pass"] {
1827            assert!(is_secret_environment_key(key), "missed {key}");
1828        }
1829        for key in ["PWD", "BYPASS", "COMPASS"] {
1830            assert!(!is_secret_environment_key(key), "mangled {key}");
1831        }
1832    }
1833
1834    #[test]
1835    fn completion_non_secret_corpus_stays_borrowed() {
1836        for text in [
1837            "running 42 tests\ntest task::sk-settings ... ok\ntest result: ok. 42 passed; 0 failed\n",
1838            "commit 0f78c1bcb3ab4d501d6ebc491617b097416f9138\nAuthor: Example <user@example.com>\n    add task-settings\n",
1839            "added 42 packages, and audited 128 packages in 2s\n12 packages are looking for funding\nfound 0 vulnerabilities\n",
1840            "request 550e8400-e29b-41d4-a716-446655440000 fixture SGVsbG8gd29ybGQhYWJjZGVmZ2g=\n",
1841            "sk-settings sk-something sk-words docs say sk- is a prefix; https://example.com/path\n",
1842        ] {
1843            assert!(matches!(SecretValues::default().redact(text), Cow::Borrowed(_)), "mangled: {text}");
1844        }
1845    }
1846
1847    #[test]
1848    fn completion_64k_noop_is_allocation_free() {
1849        let mut text = "running 42 tests\ntest task::sk-settings ... ok\n{\"status\":\"ok\"}\nhttps://example.com/path\n".repeat(1024);
1850        text.truncate(64 * 1024);
1851        let secrets = SecretValues::default();
1852        let _ = secrets.redact(&text); // Initialize regex automata outside the measurement.
1853        let start = std::time::Instant::now();
1854        let (out, allocations) = crate::test_allocations::count(|| secrets.redact(&text));
1855        assert!(matches!(out, Cow::Borrowed(_)));
1856        assert_eq!(allocations, 0);
1857        eprintln!(
1858            "64 KiB completion redaction: {:?}, {allocations} allocations",
1859            start.elapsed()
1860        );
1861    }
1862    #[test]
1863    fn github_prefilter_only_scans_actual_token_prefixes() {
1864        for ordinary in [
1865            "high throughput",
1866            "right path",
1867            "bright light",
1868            "github repository",
1869        ] {
1870            assert!(
1871                !super::needs_github_token_scan(ordinary),
1872                "unnecessary scan: {ordinary}"
1873            );
1874        }
1875        for prefix in ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"] {
1876            let token = format!("{prefix}1234567890abcdefghij");
1877            assert!(super::needs_github_token_scan(&token));
1878            assert_eq!(super::aft_redactor(&token), super::SECRET_PLACEHOLDER);
1879        }
1880    }
1881
1882    #[derive(serde::Deserialize)]
1883    struct Fixture {
1884        masked: Vec<MaskedCase>,
1885        untouched: Vec<String>,
1886        command_masked: Vec<MaskedCase>,
1887        command_untouched: Vec<String>,
1888    }
1889
1890    #[derive(serde::Deserialize)]
1891    struct MaskedCase {
1892        input: String,
1893        expected: String,
1894    }
1895
1896    #[derive(serde::Deserialize)]
1897    struct CommandFixture {
1898        masked: Vec<MaskedCase>,
1899        untouched: Vec<String>,
1900    }
1901
1902    /// Credentials typed inline in shell commands are masked, and none of the
1903    /// ordinary commands beside them change: the untouched list holds every
1904    /// command line from this repository's scripts, workflows and package.json
1905    /// scripts plus common cargo, git, npm, ssh and docker invocations.
1906    #[test]
1907    fn command_credentials_are_masked_without_touching_ordinary_commands() {
1908        let fixture: CommandFixture = serde_json::from_str(include_str!(
1909            "../../aft/tests/fixtures/command_redaction_cases.json"
1910        ))
1911        .expect("command redaction fixture parses");
1912        assert_eq!(fixture.masked.len(), 119);
1913        assert!(fixture.untouched.len() > 800);
1914        for case in &fixture.masked {
1915            let masked = redact_command(&case.input);
1916            assert_eq!(masked, case.expected, "input: {}", case.input);
1917            assert_eq!(redact_command(&masked), masked, "not idempotent");
1918        }
1919        // A few corpus lines hold URL userinfo (`ssh://git@host`), which the
1920        // shared log patterns already mask in every log line. The command
1921        // shapes themselves must change nothing.
1922        let mangled: Vec<_> = fixture
1923            .untouched
1924            .iter()
1925            .filter(|command| redact_command(command) != aft_redactor(command))
1926            .map(|command| format!("{command} -> {}", redact_command(command)))
1927            .collect();
1928        assert!(mangled.is_empty(), "{}", mangled.join("\n"));
1929    }
1930
1931    /// The curl, MySQL and sshpass rules as they were before commands were
1932    /// read as shell words: the span ran to the first `;`, `&`, `|` or
1933    /// newline, quoted or not.
1934    fn line_pattern_tool_passwords(command: &str) -> String {
1935        static PATTERNS: LazyLock<[Regex; 4]> = LazyLock::new(|| {
1936            [
1937                compile(r"\bcurl\b[^;&|\n]*"),
1938                compile(concat!(
1939                    r"(^|\s)(-u[ \t]*|--user(?:=|[ \t]+))(",
1940                    shell_word!(),
1941                    ")"
1942                )),
1943                compile(concat!(
1944                    r"\b((?:mysql|mariadb|mysqladmin|mysqldump)\b[^;&|\n]*?\s-p)(",
1945                    shell_word!(),
1946                    ")"
1947                )),
1948                compile(concat!(r"\b(sshpass[ \t]+-p[ \t]*)(", shell_word!(), ")")),
1949            ]
1950        });
1951        let [segment, user_option, mysql, sshpass] = &*PATTERNS;
1952        let out = segment.replace_all(command, |segment: &Captures<'_>| {
1953            user_option
1954                .replace_all(
1955                    &segment[0],
1956                    |caps: &Captures<'_>| match mask_curl_password(&caps[3]) {
1957                        Some(masked) => format!("{}{}{masked}", &caps[1], &caps[2]),
1958                        None => caps[0].to_string(),
1959                    },
1960                )
1961                .into_owned()
1962        });
1963        let mut out = out.into_owned();
1964        for pattern in [mysql, sshpass] {
1965            out = pattern
1966                .replace_all(&out, |caps: &Captures<'_>| {
1967                    if command_value_is_reference(&caps[2]) {
1968                        caps[0].to_string()
1969                    } else {
1970                        format!("{}{SECRET_PLACEHOLDER}", &caps[1])
1971                    }
1972                })
1973                .into_owned();
1974        }
1975        out
1976    }
1977
1978    /// Reading commands as shell words must not lose a password the earlier
1979    /// line patterns caught: on every fixture command, each placeholder the
1980    /// line patterns wrote is also written by the shell-word scan, at the
1981    /// same place.
1982    #[test]
1983    fn shell_word_scan_masks_everything_the_line_patterns_did() {
1984        let fixture: CommandFixture = serde_json::from_str(include_str!(
1985            "../../aft/tests/fixtures/command_redaction_cases.json"
1986        ))
1987        .expect("command redaction fixture parses");
1988        let mut compared = 0;
1989        let mut lost = Vec::new();
1990        for command in fixture
1991            .masked
1992            .iter()
1993            .map(|case| &case.input)
1994            .chain(&fixture.untouched)
1995        {
1996            let legacy = line_pattern_tool_passwords(command);
1997            if legacy == *command {
1998                continue;
1999            }
2000            compared += 1;
2001            let scanned = mask_tool_passwords(command);
2002            // Every byte the line patterns masked must be masked by the scan
2003            // too: each of their masked spans lies inside one of the scan's.
2004            let legacy_spans = masked_ranges(command, &legacy).expect("line patterns only mask");
2005            let scanned_spans = masked_ranges(command, &scanned).expect("scan only masks");
2006            for span in legacy_spans {
2007                if !scanned_spans
2008                    .iter()
2009                    .any(|scanned| scanned.start <= span.start && span.end <= scanned.end)
2010                {
2011                    lost.push(format!(
2012                        "{command:?}\n  line patterns: {legacy}\n  shell words:   {scanned}"
2013                    ));
2014                }
2015            }
2016        }
2017        assert!(lost.is_empty(), "{}", lost.join("\n"));
2018        eprintln!("{compared} fixture commands masked by the line patterns; none lost");
2019        assert!(compared > 40, "{compared}");
2020    }
2021
2022    /// Whether `output` is `input` with some spans replaced by placeholders
2023    /// and every other byte unchanged and in order.
2024    fn only_placeholders_changed(input: &str, output: &str) -> bool {
2025        masked_ranges(input, output).is_some()
2026    }
2027
2028    /// The spans of `input` that `output` replaced with placeholders, if
2029    /// `output` is `input` with only such replacements (each other piece
2030    /// matched at its earliest place).
2031    fn masked_ranges(input: &str, output: &str) -> Option<Vec<std::ops::Range<usize>>> {
2032        // Split `output` at its placeholders. Each placeholder's next
2033        // occurrence is searched for only after the previous one is passed,
2034        // so splitting a megabyte output stays linear.
2035        let placeholders = [SECRET_PLACEHOLDER, URL_CREDENTIAL_PLACEHOLDER];
2036        let find_from =
2037            |from: usize, placeholder: &str| output[from..].find(placeholder).map(|at| from + at);
2038        let mut next: Vec<Option<usize>> = placeholders
2039            .iter()
2040            .map(|placeholder| find_from(0, placeholder))
2041            .collect();
2042        let mut pieces = Vec::new();
2043        let mut copied = 0;
2044        loop {
2045            let nearest = next
2046                .iter()
2047                .enumerate()
2048                .filter_map(|(index, at)| at.map(|at| (at, index)))
2049                .min();
2050            let Some((at, index)) = nearest else {
2051                pieces.push(&output[copied..]);
2052                break;
2053            };
2054            pieces.push(&output[copied..at]);
2055            copied = at + placeholders[index].len();
2056            for (slot, placeholder) in next.iter_mut().zip(placeholders) {
2057                if slot.is_some_and(|found| found < copied) {
2058                    *slot = find_from(copied, placeholder);
2059                }
2060            }
2061        }
2062        if pieces.len() == 1 {
2063            return (input == output).then(Vec::new);
2064        }
2065        let (first, last) = (pieces[0], pieces[pieces.len() - 1]);
2066        if first.len() + last.len() > input.len()
2067            || !input.starts_with(first)
2068            || !input.ends_with(last)
2069        {
2070            return None;
2071        }
2072        let limit = input.len() - last.len();
2073        let mut cursor = first.len();
2074        let mut ranges = Vec::new();
2075        for piece in &pieces[1..pieces.len() - 1] {
2076            if cursor > limit {
2077                return None;
2078            }
2079            let at = input[cursor..limit].find(piece)?;
2080            ranges.push(cursor..cursor + at);
2081            cursor += at + piece.len();
2082        }
2083        (cursor <= limit).then(|| {
2084            ranges.push(cursor..limit);
2085            ranges
2086        })
2087    }
2088
2089    /// The command redactor runs on every spawned command, so it must never
2090    /// panic, whatever the command holds. Twenty thousand seeded random
2091    /// commands mix quotes, backslashes, substitutions, operators, every
2092    /// ASCII whitespace byte, Unicode spaces and multibyte text (combining
2093    /// marks, emoji), with unterminated quotes and trailing backslashes. Each
2094    /// command runs under a linear step budget, so a stalled scan fails.
2095    /// Each output must be `input` with only placeholder replacements.
2096    #[test]
2097    fn command_redaction_never_panics_and_changes_only_masked_bytes() {
2098        const PIECES: [&str; 54] = [
2099            "'",
2100            "\"",
2101            "\\",
2102            "$(",
2103            ")",
2104            "(",
2105            "`",
2106            "<",
2107            ">",
2108            "&",
2109            "|",
2110            ";",
2111            "\n",
2112            " ",
2113            "\t",
2114            "é",
2115            "中",
2116            "🙂",
2117            "e\u{301}",
2118            "\u{301}",
2119            "\u{200d}",
2120            "curl",
2121            "mysql",
2122            "sshpass",
2123            "-u",
2124            "-p",
2125            "--user=",
2126            "--password",
2127            "-ppw",
2128            "admin:pw",
2129            ":",
2130            "a",
2131            "1",
2132            "=",
2133            "TOKEN=",
2134            "$X",
2135            "2>&1",
2136            "<<<",
2137            "\\\n",
2138            "-f",
2139            "env",
2140            "sudo",
2141            "\"-u",
2142            "x'y",
2143            "\x0c",
2144            "\x0b",
2145            "\r",
2146            "\u{a0}",
2147            "\u{85}",
2148            "\u{2028}",
2149            "\u{2029}",
2150            "\u{3000}",
2151            "\u{feff}",
2152            "\u{1680}",
2153        ];
2154        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
2155        let mut next = move || {
2156            state ^= state << 13;
2157            state ^= state >> 7;
2158            state ^= state << 17;
2159            state
2160        };
2161        let redactors: [(&str, fn(&str) -> Cow<'_, str>); 2] = [
2162            ("mask_tool_passwords", mask_tool_passwords),
2163            ("redact_command", redact_command),
2164        ];
2165        let mut failures = Vec::new();
2166        let mut masked = 0;
2167        for case in 0..20_000 {
2168            let mut input = String::new();
2169            for _ in 0..next() % 40 {
2170                input.push_str(PIECES[(next() % PIECES.len() as u64) as usize]);
2171            }
2172            if case % 7 == 0 {
2173                input.push('\\');
2174            }
2175            for (name, redact) in redactors {
2176                // Under the same linear step budget as the 1 MB test, so a
2177                // scan that stops advancing fails here instead of hanging.
2178                SHELL_SCAN_STEPS.with(|steps| steps.set(0));
2179                SHELL_SCAN_BUDGET
2180                    .with(|budget| budget.set(3 * (QUOTED_COMMAND_DEPTH + 1) * input.len() + 16));
2181                let result = std::panic::catch_unwind(|| redact(&input).into_owned());
2182                SHELL_SCAN_BUDGET.with(|budget| budget.set(usize::MAX));
2183                match result {
2184                    Err(_) => failures.push(format!("{name} panicked on {input:?}")),
2185                    Ok(output) => {
2186                        assert!(std::str::from_utf8(output.as_bytes()).is_ok());
2187                        masked += usize::from(output != input);
2188                        if !only_placeholders_changed(&input, &output) {
2189                            failures.push(format!(
2190                                "{name} changed other bytes: {input:?} -> {output:?}"
2191                            ));
2192                        }
2193                    }
2194                }
2195            }
2196        }
2197        assert!(
2198            failures.is_empty(),
2199            "{} failures, first: {}",
2200            failures.len(),
2201            failures
2202                .iter()
2203                .take(10)
2204                .cloned()
2205                .collect::<Vec<_>>()
2206                .join("\n")
2207        );
2208        // The generator must reach the masking paths, not only ordinary text.
2209        assert!(masked > 1_000, "{masked} outputs masked");
2210    }
2211
2212    /// One command of a megabyte or more, in shapes that would make a
2213    /// rescanning or per-program-word design quadratic, is scanned in steps
2214    /// linear in its length: each nesting level tokenizes each byte once and
2215    /// visits each token once, and quoted commands nest at most
2216    /// QUOTED_COMMAND_DEPTH levels below the top.
2217    #[test]
2218    fn tool_password_scan_work_is_linear_on_a_megabyte_command() {
2219        const MEGABYTE: usize = 1 << 20;
2220        let repeat = |unit: &str| unit.repeat(MEGABYTE / unit.len() + 1);
2221        let inputs = [
2222            repeat("curl "),
2223            repeat("curl -u a:b --next -u "),
2224            repeat("mysql -ppw sshpass -p x "),
2225            format!("bash -c \"{}", repeat("sh -c 'curl \\\"x ")),
2226            format!("curl {}", repeat("\"'")),
2227            format!("curl '{}", repeat("é中🙂 \"' ")),
2228            format!("curl {}", repeat("\\")),
2229            format!("curl {}", repeat("<<<")),
2230            format!("curl \"{}\"", repeat("'\\\"`$( curl -u a:b ) ")),
2231            format!("\"'\"'\"'{}", repeat("curl -u a:b ")),
2232            // Substitutions that never close, each nested in the last.
2233            format!("curl {}", repeat("$(echo -u a:b ")),
2234            format!("curl {}", repeat("\"$(curl `mysql -ppw ")),
2235            repeat("curl $(printf x) -u a:b "),
2236        ];
2237        for input in &inputs {
2238            let bound = 3 * (QUOTED_COMMAND_DEPTH + 1) * input.len();
2239            SHELL_SCAN_STEPS.with(|steps| steps.set(0));
2240            SHELL_SCAN_BUDGET.with(|budget| budget.set(bound));
2241            let started = std::time::Instant::now();
2242            let masked = mask_tool_passwords(input);
2243            SHELL_SCAN_BUDGET.with(|budget| budget.set(usize::MAX));
2244            let steps = SHELL_SCAN_STEPS.with(std::cell::Cell::get);
2245            let elapsed = started.elapsed();
2246            assert!(
2247                steps <= bound,
2248                "{steps} steps for {} bytes (bound {bound}) starting {:?}",
2249                input.len(),
2250                input.chars().take(40).collect::<String>()
2251            );
2252            assert!(only_placeholders_changed(input, &masked));
2253            let started = std::time::Instant::now();
2254            let _ = redact_command(input);
2255            eprintln!(
2256                "{} bytes starting {:?}: {steps} scan steps, scan {elapsed:?}, full redaction {:?}",
2257                input.len(),
2258                input.chars().take(12).collect::<String>(),
2259                started.elapsed()
2260            );
2261        }
2262    }
2263
2264    /// Run `mask_tool_passwords` under a step budget linear in the
2265    /// command's length, so a scan that stops advancing panics at once.
2266    fn mask_within_budget(command: &str) -> String {
2267        let bound = 3 * (QUOTED_COMMAND_DEPTH + 1) * command.len() + 16;
2268        SHELL_SCAN_STEPS.with(|steps| steps.set(0));
2269        SHELL_SCAN_BUDGET.with(|budget| budget.set(bound));
2270        let masked = std::panic::catch_unwind(|| mask_tool_passwords(command).into_owned());
2271        SHELL_SCAN_BUDGET.with(|budget| budget.set(usize::MAX));
2272        masked.unwrap_or_else(|_| panic!("scan stalled or panicked on {command:?}"))
2273    }
2274
2275    /// A command longer than the scanned prefix has its tail masked whole: a
2276    /// credential after the cut-off, or one the cut-off splits, never
2277    /// reaches the log unscanned.
2278    #[test]
2279    fn command_tail_past_the_scan_limit_is_masked_not_logged() {
2280        let padding = "x".repeat(MAX_SCANNED_COMMAND_BYTES - 10);
2281        let after = format!("echo {padding} && curl -u admin:hunter2 h");
2282        let split = format!(
2283            "curl {} -u admin:hunter2 h",
2284            "y".repeat(MAX_SCANNED_COMMAND_BYTES - 18)
2285        );
2286        for command in [&after, &split] {
2287            assert!(command.len() > MAX_SCANNED_COMMAND_BYTES);
2288            for masked in [
2289                mask_within_budget(command),
2290                redact_command(command).into_owned(),
2291            ] {
2292                assert!(
2293                    !masked.contains("hunter2"),
2294                    "credential after the cut-off logged"
2295                );
2296                assert!(!masked.contains("hun"), "part of a split credential logged");
2297                assert!(masked.ends_with(SECRET_PLACEHOLDER));
2298                assert!(only_placeholders_changed(command, &masked));
2299            }
2300        }
2301    }
2302
2303    /// A byte that ends a word must be consumed by the loop around the word,
2304    /// or the scan stops advancing. A form feed did exactly that: words
2305    /// ended at any ASCII whitespace, while the command loop skipped only
2306    /// space, tab and carriage return. Every ASCII whitespace byte and a few
2307    /// Unicode spaces, inside a quoted argument (scanned again as a command)
2308    /// and between words, must keep the scan moving.
2309    #[test]
2310    fn every_ascii_and_unicode_space_keeps_the_scan_advancing() {
2311        let ascii = ["\x0c", "\x0b", "\r", "\t", " "];
2312        let unicode = [
2313            "\u{a0}", "\u{85}", "\u{2028}", "\u{2029}", "\u{3000}", "\u{feff}",
2314        ];
2315        for space in ascii.iter().chain(&unicode) {
2316            let quoted = format!("curl \"a{space}b\" -u admin:hunter2 h");
2317            assert_eq!(
2318                mask_within_budget(&quoted),
2319                format!("curl \"a{space}b\" -u admin:{SECRET_PLACEHOLDER} h"),
2320                "{space:?}"
2321            );
2322            for command in [
2323                format!("curl{space}-u admin:hunter2 h"),
2324                format!("curl -u admin:hunter2{space}h"),
2325                format!("mysql{space}-phunter2 db"),
2326                format!("sshpass -p hunter2{space}ssh h"),
2327                format!("{space}{space}curl{space}{space}"),
2328            ] {
2329                let masked = mask_within_budget(&command);
2330                if ascii.contains(space) {
2331                    assert!(!masked.contains("hunter2"), "{command:?} -> {masked:?}");
2332                }
2333            }
2334        }
2335    }
2336
2337    fn fixture() -> Fixture {
2338        serde_json::from_str(include_str!(
2339            "../../aft/tests/fixtures/log_redaction_cases.json"
2340        ))
2341        .expect("shared redaction fixture parses")
2342    }
2343
2344    #[test]
2345    fn shells_v1_format_context_prefilter_covers_real_redaction_corpus() {
2346        for case in fixture().masked {
2347            assert!(
2348                shells_may_need_format_context(&case.input),
2349                "{}",
2350                case.input
2351            );
2352        }
2353        assert!(!shells_may_need_format_context(&"o".repeat(70_000)));
2354        for input in [
2355            "-----BEGIN PRIVATE KEY-----\nbody",
2356            "\"password\":\"value\"",
2357            "Authorization: Bearer token",
2358        ] {
2359            assert!(shells_may_need_format_context(input));
2360        }
2361    }
2362
2363    #[test]
2364    fn shells_v1_ticket_range_streams_large_chunks_without_repeating_a_placeholder() {
2365        let ticket = "0123456789abcdef0123456789abcdef";
2366        let digest = blake3::hash(ticket.as_bytes()).to_hex().to_string();
2367        let prefix = "x".repeat(61);
2368        let suffix = format!("-{}", "o".repeat(65_536 - prefix.len() - ticket.len() - 1));
2369        let raw = format!("{prefix}{ticket}{suffix}");
2370        let first = shells_ticket_range(&raw, 0..64, Some(&digest)).unwrap();
2371        let second = shells_ticket_range(&raw, 64..raw.len(), Some(&digest)).unwrap();
2372        assert_eq!(
2373            first + &second,
2374            format!("{prefix}{SECRET_PLACEHOLDER}{suffix}")
2375        );
2376    }
2377
2378    #[test]
2379    fn shared_fixture_masked_cases_match_the_cli_sanitizer_output() {
2380        let fixture = fixture();
2381        assert!(!fixture.masked.is_empty());
2382        for case in fixture.masked {
2383            assert_eq!(
2384                aft_redactor(&case.input),
2385                case.expected,
2386                "input: {}",
2387                case.input
2388            );
2389            assert_eq!(
2390                redact_command(&case.input),
2391                case.expected,
2392                "command: {}",
2393                case.input
2394            );
2395        }
2396    }
2397
2398    #[test]
2399    fn shared_fixture_untouched_cases_are_borrowed_unchanged() {
2400        let fixture = fixture();
2401        assert!(!fixture.untouched.is_empty());
2402        for input in fixture.untouched {
2403            let out = aft_redactor(&input);
2404            assert!(matches!(out, Cow::Borrowed(_)), "mangled: {input} -> {out}");
2405        }
2406    }
2407
2408    #[test]
2409    fn shared_fixture_command_shapes_do_not_redact_structured_fields() {
2410        let fixture = fixture();
2411        assert!(!fixture.command_masked.is_empty());
2412        for case in fixture.command_masked {
2413            assert_eq!(aft_redactor(&case.input), case.input);
2414            assert_eq!(
2415                redact_command(&case.input),
2416                case.expected,
2417                "command: {}",
2418                case.input
2419            );
2420        }
2421        assert!(!fixture.command_untouched.is_empty());
2422        for command in fixture.command_untouched {
2423            assert_eq!(redact_command(&command), command);
2424        }
2425    }
2426
2427    #[test]
2428    fn masks_each_github_token_prefix() {
2429        let body = "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8";
2430        for prefix in ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"] {
2431            let line = format!("token {prefix}{body} end");
2432            assert_eq!(
2433                aft_redactor(&line),
2434                "token <REDACTED_SECRET> end",
2435                "{prefix}"
2436            );
2437        }
2438        assert_eq!(
2439            aft_redactor("x github_pat_11AB_cd34 y"),
2440            "x <REDACTED_SECRET> y"
2441        );
2442    }
2443
2444    #[test]
2445    fn masks_url_userinfo_for_any_scheme() {
2446        assert_eq!(
2447            aft_redactor("https://user:pass@host.example/path"),
2448            "https://***@host.example/path"
2449        );
2450        assert_eq!(
2451            aft_redactor("ssh://deploy@host.example:22/repo"),
2452            "ssh://***@host.example:22/repo"
2453        );
2454    }
2455
2456    #[test]
2457    fn masks_credential_query_parameters() {
2458        assert_eq!(
2459            aft_redactor("u?token=abc&access_token=def&api_key=ghi&client_secret=jkl"),
2460            "u?token=<REDACTED_SECRET>&access_token=<REDACTED_SECRET>&api_key=<REDACTED_SECRET>&client_secret=<REDACTED_SECRET>"
2461        );
2462        assert_eq!(
2463            aft_redactor("u?key=AIzaSyA1b2C3d4E5f6G7h8I9j0 done"),
2464            "u?key=<REDACTED_SECRET> done"
2465        );
2466    }
2467
2468    #[test]
2469    fn masks_header_jwt_sk_and_aws_shapes() {
2470        assert_eq!(
2471            aft_redactor("Authorization: Bearer abc.def-ghi"),
2472            "Authorization: Bearer <REDACTED_SECRET>"
2473        );
2474        assert_eq!(
2475            aft_redactor("jwt eyJhbGciOi.eyJzdWIiOi.c2lnbmF0dXJl end"),
2476            "jwt <REDACTED_SECRET> end"
2477        );
2478        assert_eq!(
2479            aft_redactor("key sk-live-abcdefgh123"),
2480            "key <REDACTED_SECRET>"
2481        );
2482        assert_eq!(
2483            aft_redactor("id AKIAABCDEFGHIJKLMNOP"),
2484            "id <REDACTED_SECRET>"
2485        );
2486    }
2487
2488    #[test]
2489    fn redaction_is_idempotent() {
2490        for case in fixture().masked {
2491            let once = aft_redactor(&case.input).into_owned();
2492            assert!(matches!(aft_redactor(&once), Cow::Borrowed(_)), "{once}");
2493        }
2494    }
2495
2496    #[test]
2497    fn ordinary_log_content_is_not_mangled() {
2498        for line in [
2499            "[aft] index_event kind=ready plane=search root=/Users/me/proj key=search:v3",
2500            "[aft] format: src/main.rs (rustfmt)",
2501            "sha256=9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
2502            "blake3 AF1349B9F5F9A1A6A0404DEA36DCC9499BCB25C9ADC112B7CC9A93CAE41F3262",
2503            "task_id=bgb_0123456789 session=ses_abcDEF0123456789",
2504            "https://example.com/search?key=ab12CD34&q=tokenizer",
2505            "url https://example.com/a?page_size=10&sort=asc",
2506            "ghost gh_pages ghp_tooShort",
2507        ] {
2508            let out = aft_redactor(line);
2509            assert!(matches!(out, Cow::Borrowed(_)), "mangled: {line} -> {out}");
2510        }
2511    }
2512
2513    #[test]
2514    fn truncate_for_log_bounds_bytes_and_reports_the_remainder() {
2515        assert_eq!(truncate_for_log("short", 10), "short");
2516        assert_eq!(truncate_for_log("abcdefghij", 4), "abcd…(+6 bytes)");
2517        // "é" is two bytes; the cut backs off to the char boundary.
2518        assert_eq!(truncate_for_log("aéb", 2), "a…(+3 bytes)");
2519    }
2520
2521    #[test]
2522    fn unlogged_input_summary_carries_length_and_hash_only() {
2523        let input = "{\"command\":\"secret\"";
2524        let summary = unlogged_input_summary(input);
2525        let prefix = format!("bytes={} sha256=", input.len());
2526        assert!(summary.starts_with(&prefix), "{summary}");
2527        assert_eq!(summary.len(), prefix.len() + 12);
2528        assert!(!summary.contains("secret"));
2529    }
2530
2531    #[test]
2532    fn contextual_secret_formats_are_masked() {
2533        for (input, secret) in [
2534            ("x-api-key: private-key-value", "private-key-value"),
2535            (
2536                "Authorization: Token private-token-value",
2537                "private-token-value",
2538            ),
2539            (
2540                r#"{"password":"private-password-value"}"#,
2541                "private-password-value",
2542            ),
2543            (
2544                "token xoxb-12345-private-slack-value",
2545                "xoxb-12345-private-slack-value",
2546            ),
2547            (
2548                "-----BEGIN RSA PRIVATE KEY-----\nprivate-pem-value\n-----END RSA PRIVATE KEY-----",
2549                "private-pem-value",
2550            ),
2551            (
2552                "AWS_SECRET_ACCESS_KEY=private-aws-secret-value",
2553                "private-aws-secret-value",
2554            ),
2555        ] {
2556            let masked = aft_redactor(input);
2557            assert!(!masked.contains(secret), "secret survived: {input}");
2558            assert!(masked.contains(SECRET_PLACEHOLDER));
2559            assert_eq!(aft_redactor(&masked), masked);
2560        }
2561        assert_eq!(
2562            aft_redactor("plain private-aws-secret-value"),
2563            "plain private-aws-secret-value"
2564        );
2565    }
2566
2567    #[test]
2568    fn invalid_utf8_does_not_bypass_masking() {
2569        let mut bytes = vec![0xff];
2570        bytes.extend_from_slice(b" ghp_1234567890abcdefghij");
2571        let masked = aft_redact_bytes(&bytes);
2572        assert!(!String::from_utf8_lossy(&masked).contains("ghp_"));
2573        assert!(std::str::from_utf8(&masked).is_ok());
2574    }
2575
2576    #[test]
2577    fn non_utf8_bytes_are_safely_decoded() {
2578        let bytes = [0xff, 0xfe, b'g', b'h'];
2579        assert_eq!(aft_redact_bytes(&bytes).as_ref(), "��gh".as_bytes());
2580    }
2581
2582    #[test]
2583    fn git_numbered_config_names_are_not_secret_names() {
2584        // Scrubbing GIT_CONFIG_KEY_0 alone leaves GIT_CONFIG_COUNT pointing at a
2585        // missing key, and git refuses to run.
2586        for key in ["GIT_CONFIG_KEY_0", "GIT_CONFIG_KEY_12", "git_config_key_1"] {
2587            assert!(!is_secret_environment_key(key), "{key}");
2588        }
2589        for key in [
2590            "GITHUB_TOKEN",
2591            "NPM_AUTH",
2592            "AWS_SECRET_ACCESS_KEY",
2593            "API_KEY",
2594        ] {
2595            assert!(is_secret_environment_key(key), "{key}");
2596        }
2597    }
2598
2599    #[test]
2600    fn author_names_are_not_secret_names() {
2601        for key in [
2602            "AFT_GIT_CO_AUTHOR",
2603            "GIT_AUTHOR_NAME",
2604            "git_author_email",
2605            "AUTHOR",
2606        ] {
2607            assert!(!is_secret_environment_key(key), "{key}");
2608        }
2609        for key in [
2610            "AUTH",
2611            "NPM_AUTH",
2612            "AUTH_HEADER",
2613            "HTTP_AUTHORIZATION",
2614            "XAUTHORITY",
2615            "AUTHORS_FILE",
2616            "GIT_AUTHOR_TOKEN",
2617            "AUTHOR_AUTH",
2618        ] {
2619            assert!(is_secret_environment_key(key), "{key}");
2620        }
2621    }
2622
2623    #[test]
2624    fn git_runs_after_the_secret_name_scrub() {
2625        let mut command = std::process::Command::new("git");
2626        command
2627            .args(["config", "--get", "core.hooksPath"])
2628            .env("GIT_CONFIG_COUNT", "1")
2629            .env("GIT_CONFIG_KEY_0", "core.hooksPath")
2630            .env("GIT_CONFIG_VALUE_0", "/dev/null");
2631        for key in ["GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"] {
2632            if is_secret_environment_key(key) {
2633                command.env_remove(key);
2634            }
2635        }
2636        let output = command.output().expect("git runs");
2637        assert!(
2638            output.status.success(),
2639            "git failed: {}",
2640            String::from_utf8_lossy(&output.stderr)
2641        );
2642        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "/dev/null");
2643    }
2644}