From 1b2dc5b0779c11f52388d992cf2e4fc35b34f2d9 Mon Sep 17 00:00:00 2001 From: R&D12 Date: Thu, 3 Dec 2026 07:59:59 +0000 Subject: [PATCH] TD-5447: Scrubber: a private key's body never shows, however it is written or cut A private key cut short (no END line) lost only the part before its first escaped newline, so a key in a JSON or .env value, a repr, or JSON inside JSON showed its body in chat, tool output and on the wire. Its body now runs across any line break, real or escaped, with the decoration, line prefixes and string joins that tools and source code put around lines, and escaped key characters. Base64url bodies, lower-case BEGIN lines, PGP private key blocks and SSH2 private keys are covered. The first line must read as key text, not as code or words, and a key cut short inside a string stops at the string's end, so prose and code after a BEGIN line keep their words. The END search stops at the next BEGIN line (2,000 BEGIN lines in 1 MiB: ~2 minutes before, ~0.2 s now); header lines and long runs are read once. Secret names match in any case (aws_secret_access_key = ...), with code left alone: the name must end in a credential word, == is a comparison, and the value must not read as code (numbers, versions, dates, type names, snake_case and dotted names, arithmetic such as pos+1 or offset+limit). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SPdoY5jgXgTw6gUHBMBngR --- core/tests/test_pem_redaction.py | 516 +++++++++++++++++++++++++++++++ core/tstd/logging.py | 282 ++++++++++++++++- docs/tst-desk-backlog.md | 10 + 3 files changed, 804 insertions(+), 4 deletions(-) create mode 100644 core/tests/test_pem_redaction.py diff --git a/core/tests/test_pem_redaction.py b/core/tests/test_pem_redaction.py new file mode 100644 index 00000000..cdf7e7c8 --- /dev/null +++ b/core/tests/test_pem_redaction.py @@ -0,0 +1,516 @@ +"""A private key's body never shows, whatever shape it is in or wherever it is cut (TD-5447). + +The scrubber knew a PEM block with its END line, and one cut short only while its +newlines were real. Written with "\\n" escapes (a JSON or .env value, a Python +repr) and cut short (no END line), the body after the first escape showed: in chat +text, in tool output and on the wire. Prose that mentions a BEGIN line kept losing +the words after it. A text with many BEGIN lines and no END line took minutes. + +Every key here is made up; the BEGIN lines are built so no file holds one whole. +""" + +from __future__ import annotations + +import json +import re +import time +from collections.abc import Callable, Iterator + +import pytest + +from tstd.logging import REDACTED, redact_secrets, secret_spans +from tstd.protocol import AssistantDelta, ShellOutput, ToolResult, scrub_wire_json +from tstd.session import _redact_event + +DASHES = "-" * 5 +BODY = [ + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7secretLINEone", + "Zm9vYmFyYmF6cXV4c2VjcmV0TElORXR3b3NlY3JldExJTkV0d29zZWNyZXQ=", + "c2VjcmV0TElORXRocmVlc2VjcmV0TElORXRocmVl", +] +# A base64url body ("-" and "_"), as some tools write it. +URL_BODY = [ + "MIIEvQIBADANBgkqhkiG9w0BAQEF-_ASCBKcwggSjAgEAAoIBAQC7urlLINEone", + "Zm9vYmFy_YmF6-cXV4c2VjcmV0TElORXR3b3NlY3JldExJTkV0d29zZWNyZXQ", +] +# A body full of "/" and "+", for shapes that escape them. +SLASH_BODY = [ + "MIIEvQ+BADAN/gkqhk+G9w0/AQEF+ASCBK/wggSj+gEAAoIB/QC7slash+LINE/n", + "Zm9v/mFy+mF6/XV4+2Vj/mV0+ElO/XR3/2Vj+mV0/ExJ+kV0/29z+WNy/XQ=", +] +# Any 8 characters in a row from a body would be part of the key showing. +GRAMS = {line[i : i + 8] for line in BODY + URL_BODY + SLASH_BODY for i in range(len(line) - 7)} + + +def begin(kind: str = "RSA ") -> str: + return f"{DASHES}BEGIN {kind}PRIVATE KEY{DASHES}" + + +def pem( + kind: str, + newline: str, + *, + end: bool = True, + info: bool = False, + body: list[str] = BODY, + prefix: str = "", +) -> str: + """A key: BEGIN line, body lines split by *newline*, each after *prefix*, END line.""" + lines = [begin(kind)] + if info: # an old-style encrypted key's header lines + lines += ["Proc-Type: 4,ENCRYPTED", "DEK-Info: AES-128-CBC,0123456789ABCDEF", ""] + lines += body + if end: + lines.append(f"{DASHES}END {kind}PRIVATE KEY{DASHES}") + text = newline.join(prefix + line if n else line for n, line in enumerate(lines)) + return text if end else text + newline + + +def armored(begin_line: str, end_line: str, headers: list[str], *, end: bool = True) -> str: + """A PGP or SSH2 block: its header lines, a blank line, the body.""" + lines = [begin_line, *headers, "", *BODY, "=Zm9v"] + return "\n".join(lines + ([end_line] if end else [])) + ("" if end else "\n") + + +def _escaped_body(slash: str, plus: str) -> list[str]: + return [line.replace("/", slash).replace("+", plus) for line in SLASH_BODY] + + +def _lower_begin(text: str) -> str: + begin_line, rest = text.split("\n", 1) + return begin_line.lower() + "\n" + rest + + +def _numbered(text: str, gutter: Callable[[int], str]) -> str: + return "\n".join(gutter(n) + line for n, line in enumerate(text.splitlines(), 1)) + + +# The 11 shapes checked first (TD-5445's report), then the ones found since. +SHAPES: dict[str, str] = { + "plain, real newlines, END": pem("", "\n"), + "RSA, real newlines, END": pem("RSA ", "\n"), + "EC, real newlines, END": pem("EC ", "\n"), + "OPENSSH, real newlines, END": pem("OPENSSH ", "\n"), + "ENCRYPTED, real newlines, END": pem("ENCRYPTED ", "\n"), + "real newlines, no END": pem("RSA ", "\n", end=False), + "CRLF, END": pem("RSA ", "\r\n"), + "escaped \\n, END": pem("RSA ", "\\n"), + "escaped \\n, no END": pem("RSA ", "\\n", end=False), + "service-account JSON": json.dumps( + {"type": "service_account", "private_key": pem("", "\n") + "\n"}, indent=2 + ), + "in chat text": "here is the key:\n" + pem("RSA ", "\n") + "\nthanks", + "escaped twice (JSON in JSON), no END": pem("RSA ", "\\\\n", end=False), + "escaped \\r\\n, no END": pem("RSA ", "\\r\\n", end=False), + "Python repr, no END": repr(pem("RSA ", "\n", end=False)), + "old-style encrypted, no END": pem("RSA ", "\n", end=False, info=True), + "old-style encrypted, escaped, no END": pem("RSA ", "\\n", end=False, info=True), + "numbered lines (cat -n), no END": _numbered( + pem("RSA ", "\n", end=False), lambda n: f"{n:6}\t" + ), + "numbered lines (N→), no END": _numbered(pem("RSA ", "\n", end=False), lambda n: f"{n:>5}→"), + "one line, spaces for newlines, no END": pem("RSA ", " ", end=False), + "one line, no newlines, no END": pem("RSA ", "", end=False), + # Found by the review: line breaks Word and Unicode use, and line prefixes. + "vertical tab breaks, no END": pem("RSA ", "\x0b", end=False), + "form feed breaks, no END": pem("RSA ", "\x0c", end=False), + "NEL breaks, no END": pem("RSA ", "\x85", end=False), + "line separator breaks, no END": pem("RSA ", "\u2028", end=False), + "no-break space before breaks, no END": pem("RSA ", "\xa0\n", end=False), + "// comments, no END": pem("RSA ", "\n", end=False, prefix="// "), + "# comments, no END": pem("RSA ", "\n", end=False, prefix="# "), + "> quoted, no END": pem("RSA ", "\n", end=False, prefix="> "), + "diff, added lines, no END": pem("RSA ", "\n", end=False, prefix="+"), + "diff, removed lines, no END": pem("RSA ", "\n", end=False, prefix="-"), + "N | numbered, no END": _numbered(pem("RSA ", "\n", end=False), lambda n: f"{n:4} | "), + "source string per line, no END": pem("RSA ", '\\n"\n "', end=False), + "source string concat, no END": pem("RSA ", '\\n" +\n "', end=False), + "escaped tab after escaped newline, no END": pem("RSA ", "\\n\\t", end=False), + "\\u000a escapes, no END": pem("RSA ", "\\u000a", end=False), + "%0A escapes, no END": pem("RSA ", "%0A", end=False), + "
breaks, no END": pem("RSA ", "
", end=False), + " breaks, no END": pem("RSA ", " ", end=False), + "ANSI coloured lines, no END": pem("RSA ", "\x1b[0m\n\x1b[32m", end=False), + "base64url body, no END": pem("RSA ", "\n", end=False, body=URL_BODY), + # Found by the second review. + "escaped / (PHP JSON), no END": pem("RSA ", "\\n", end=False, body=_escaped_body("\\/", "+")), + "URL-encoded / and +, no END": pem("RSA ", "%0A", end=False, body=_escaped_body("%2F", "%2B")), + "HTML entities for / and +, no END": pem( + "RSA ", " ", end=False, body=_escaped_body("/", "+") + ), + "grep -n, no END": _numbered(pem("RSA ", "\n", end=False), lambda n: f"{n}:"), + "grep -n with a file name, no END": _numbered( + pem("RSA ", "\n", end=False), lambda n: f"keys/k.pem:{n}:" + ), + "grep context lines, no END": _numbered(pem("RSA ", "\n", end=False), lambda n: f"{n}-"), + "-- comments, no END": pem("RSA ", "\n", end=False, prefix="-- "), + "% comments, no END": pem("RSA ", "\n", end=False, prefix="% "), + "shell line continuation, no END": pem("RSA ", "\\\n", end=False), + "markdown table rows, no END": "| " + pem("RSA ", " |\n| ", end=False), + "JSON array of lines on one line, no END": '["' + pem("RSA ", '", "', end=False), + " breaks, no END": pem("RSA ", " ", end=False), + " breaks, no END": pem("RSA ", " ", end=False), + "octal \\012 escapes, no END": pem("RSA ", "\\012", end=False), + "lower-case BEGIN line, no END": _lower_begin(pem("RSA ", "\n", end=False)), + "zero-width space after breaks, no END": pem("RSA ", "\n\u200b", end=False), + "byte order mark after breaks, no END": pem("RSA ", "\n\ufeff", end=False), + # Found by the third review. + "grep -A with a file name, no END": _numbered( + pem("RSA ", "\n", end=False), lambda n: f"./certs/dev.pem{':' if n == 1 else '-'}{n}-" + ), + "bat gutter, no END": _numbered(pem("RSA ", "\n", end=False), lambda n: f"{n:4} │ "), + # Found by the fourth review. + "journalctl lines, no END": pem( + "RSA ", "\n", end=False, prefix="Dec 03 07:59:59 host app[1234]: " + ), + "container log lines, no END": pem( + "RSA ", "\n", end=False, prefix="2026-12-03T07:59:59.123Z stdout F " + ), + "log level lines, no END": pem("RSA ", "\n", end=False, prefix="INFO "), + "less -N, no END": _numbered(pem("RSA ", "\n", end=False), lambda n: f"{n:6} "), + "normal diff, no END": pem("RSA ", "\n", end=False, prefix="< "), + "nested quotes, no END": pem("RSA ", "\n", end=False, prefix="> > "), + "Python prompt, no END": pem("RSA ", "\n", end=False, prefix="... "), + "cat -A, no END": pem("RSA ", "$\n", end=False), + "
per line, no END": "
" + pem("RSA ", "
", end=False), + "SQL chr(10), no END": "'" + pem("RSA ", "' || chr(10) || '", end=False), + "ordered list, no END": _numbered(pem("RSA ", "\n", end=False), lambda n: f"{n}. "), + "&#10; breaks, no END": pem("RSA ", "&#10;", end=False), + "\\N{LINE FEED} escapes, no END": pem("RSA ", "\\N{LINE FEED}", end=False), + "comment between source strings, no END": pem("RSA ", '\\n" # nosec\n "', end=False), + "URL-encoded, with END": pem("RSA ", "%0A").replace(" ", "%20"), + "form-encoded, with END": pem("RSA ", "%0A").replace(" ", "+"), + "\\u002b and \\u002f escapes, no END": pem( + "RSA ", "\\n", end=False, body=_escaped_body("\\u002f", "\\u002b") + ), + "PGP private key block, END": armored( + f"{DASHES}BEGIN PGP PRIVATE KEY BLOCK{DASHES}", + f"{DASHES}END PGP PRIVATE KEY BLOCK{DASHES}", + ["Version: 1"], + ), + "PGP private key block, no END": armored( + f"{DASHES}BEGIN PGP PRIVATE KEY BLOCK{DASHES}", "", ["Version: 1"], end=False + ), + "SSH2 private key, END": armored( + "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----", + "---- END SSH2 ENCRYPTED PRIVATE KEY ----", + ['Comment: "rsa-key-1"'], + ), + "SSH2 private key, no END": armored( + "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----", "", ['Comment: "rsa-key-1"'], end=False + ), +} +# How output limits end a text they cut: nothing, a closing quote, an ellipsis, a note. +ENDINGS = ["", '"', "…", "\n[output truncated]", " (truncated)"] + + +def _wire(text: str) -> str: + return json.loads(scrub_wire_json(json.dumps({"type": "x", "text": text})))["text"] + + +def _wire_escaped(text: str) -> str: + """The text as a JSON string inside a frame's string: its newlines become "\\n".""" + return json.loads(scrub_wire_json(json.dumps({"type": "x", "text": json.dumps(text)})))["text"] + + +def _cut_short(text: str) -> Iterator[str]: + """*text* cut at every point after its BEGIN line, each way a cut can end.""" + start = re.search(r"(?i)KEY(?: BLOCK)?-----|KEY ----", text).end() # type: ignore[union-attr] + for at in range(start, len(text) + 1): + for ending in ENDINGS: + yield text[:at] + ending + + +@pytest.mark.parametrize("shape", list(SHAPES)) +@pytest.mark.parametrize( + "where", [redact_secrets, _wire, _wire_escaped], ids=["text", "wire", "wire-escaped"] +) +def test_no_part_of_a_key_shows_however_it_is_cut(shape: str, where: Callable[[str], str]) -> None: + shown = [out for out in map(where, _cut_short(SHAPES[shape])) if any(g in out for g in GRAMS)] + assert not shown, shown[:3] + + +@pytest.mark.parametrize("shape", list(SHAPES)) +def test_chat_text_and_tool_output_lose_the_key(shape: str) -> None: + for text in _cut_short(SHAPES[shape]): + if len(text) % 7: # every seventh cut: the events add nothing the texts above don't + continue + events = [ + AssistantDelta(seq=1, session_id="s1", delta=text), + ToolResult(seq=1, session_id="s1", tool_call_id="t1", status="success", output=text), + ShellOutput(seq=1, session_id="s1", tool_call_id="t1", stream="stdout", chunk=text), + ] + for event in events: + scrubbed = _redact_event(event) + for shown in ( + json.dumps(scrubbed.model_dump()), + scrub_wire_json(event.model_dump_json()), + ): + assert not any(g in shown for g in GRAMS), (type(event).__name__, text[-40:]) + + +@pytest.mark.parametrize( + ("text", "kept"), + [ + ( + f"{begin('')} marks where a key starts; keep that file out of git.", + f"{REDACTED} marks where a key starts; keep that file out of git.", + ), + ( + f"A PEM file begins with {begin()}\nand the lines after it are base64.", + f"A PEM file begins with {REDACTED}\nand the lines after it are base64.", + ), + (f"{begin('')}\nPaste your key here\n", f"{REDACTED}\nPaste your key here\n"), + (f"{begin('')}\\nPaste your key here\\n", f"{REDACTED}\\nPaste your key here\\n"), + ( + f"{begin('OPENSSH ')}\nExample only, not a real key.", + f"{REDACTED}\nExample only, not a real key.", + ), + ( + "Look for a line like BEGIN PRIVATE KEY in the file; if it is there, rotate it.", + "Look for a line like BEGIN PRIVATE KEY in the file; if it is there, rotate it.", + ), + ( + f"The header {begin('EC ')} is followed by the key, then the END line.", + f"The header {REDACTED} is followed by the key, then the END line.", + ), + ], +) +def test_prose_about_a_begin_line_keeps_its_words(text: str, kept: str) -> None: + assert redact_secrets(text) == kept + assert _wire(text) == kept + assert _wire_escaped(text) == json.dumps(kept) + + +@pytest.mark.parametrize( + "code", + [ + 'HEADER = "{begin}"\nkey_bytes = base64.b64decode(body)', + 'b"{begin}\\n"\nprivate_key = load(data)', + '{{\n "pem": "{begin}",\n "user_id": 42\n}}', + "{begin}\nsha256_digest = hashlib.sha256(x)", + "{begin}\nb64key = read(path)", + "{begin}\nkey2.load()", + # Found by the third review. + "{begin}\nb64encode(der)", + "{begin}\nsha256sum key.pem", + "{begin}\n base64encoded body here", + # Found by the fourth review. + 'pem := "{begin}\\n" + base64Body + "\\n"', + 'pem = "{begin}\\n" +\n b64_payload +\n "\\n"', + "{begin}\nMIN_KEY_LEN = 2048", + ], +) +def test_code_after_a_begin_line_keeps_its_words(code: str) -> None: + # A mask written back into a file would break it (found by the second review). + text = code.format(begin=begin("")) + assert redact_secrets(text) == code.format(begin=REDACTED) + + +@pytest.mark.parametrize( + ("code", "kept"), + [ + # A key cut short inside a string: the string's end and what follows stay. + ( + 'FAKE = "{begin}\\nMIIEvQIBADAN1234\\n"\nother = 1', + 'FAKE = "{masked}\\n"\nother = 1', + ), + ( + 'KEY = """{begin}\nMIIEvQIBADAN1234\n"""\n\ndef test_load():', + 'KEY = """{masked}\n"""\n\ndef test_load():', + ), + ( + '{{\n "pem_escaped": "{begin}\\nMIIEpemBODYmarkerA0b1C2d3E4\\nf5G6h7",\n' + ' "pem": "x",\n "api_key": "y",\n}}', + '{{\n "pem_escaped": "{masked}",\n "pem": "x",\n "api_key": "y",\n}}', + ), + ( + "KEY = {begin}\nMIIEvQIBADAN1234\nother = 1", + "KEY = {masked}\nother = 1", + ), + # Found by the fourth review: a closing quote after "\n" never opens a string. + ('KEY = "{begin}\\nMIIEvQIBADAN1234\\n"\nreturn KEY', 'KEY = "{masked}\\n"\nreturn KEY'), + ( + 'k = "{begin}\\nMIIEvQIBADAN1234\\n";\nexport default k;', + 'k = "{masked}\\n";\nexport default k;', + ), + ( + 'k = "{begin}\\nMIIEvQIBADAN1234\\n"\n// ignore this', + 'k = "{masked}\\n"\n// ignore this', + ), + ('["{begin}\\nMIIEvQIBADAN1234", "hello", "world"]', '["{masked}", "hello", "world"]'), + ("{begin}\nMIIEvQIBADAN1234\nThen I ran the tests.", "{masked}\nThen I ran the tests."), + ], +) +def test_code_after_a_cut_short_key_keeps_its_words(code: str, kept: str) -> None: + text = code.format(begin=begin(""), masked="{masked}") + assert redact_secrets(text) == kept.format(masked=REDACTED) + + +@pytest.mark.parametrize( + "text", + [ + begin() + "\nProc-Type: " + "\\" * 64000, + begin() + "\nMIIEvQIBADAN" + "\\" * 64000, + begin() + "\nMIIEvQIBADAN" + "
None: + # A header line of backslashes took 32 s at 64,000 (found by the second review). + started = time.perf_counter() + redact_secrets(text) + secret_spans(text) + assert time.perf_counter() - started < 10 + + +def test_many_begin_lines_without_an_end_line_are_read_once() -> None: + # 2,000 BEGIN lines in 1 MiB took about two minutes when each one searched the + # rest of the text for an END line. + text = ((begin() + " then some words that go on for a while\n") * 15000)[: 1 << 20] + started = time.perf_counter() + out = redact_secrets(text) + assert time.perf_counter() - started < 10 + assert "then some words that go on for a while" in out + + +def test_a_key_with_its_end_line_still_goes_whole() -> None: + out = redact_secrets(f"key:\n{pem('RSA ', chr(92) + 'n')}\nafter") + assert out == f"key:\n{REDACTED}\nafter" + assert redact_secrets(f"{pem('', chr(10))} {pem('EC ', chr(10))}") == f"{REDACTED} {REDACTED}" + + +# ── Key names in any case (TD-5447) ───────────────────────────────────────── + + +@pytest.mark.parametrize( + ("text", "kept"), + [ + ( + "aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", + "aws_secret_access_key = ", + ), + ("aws_secret_access_key=wJalrXUtnFEMI/K7MDENG", "aws_secret_access_key="), + ("Aws_Secret_Access_Key: abcd1234efgh", "Aws_Secret_Access_Key: "), + ("db_password=s3cr3tPass", "db_password="), + ("github_token='ghq1234567890'", "github_token='"), + ("lastToken: 'ab12cd34ef56'", "lastToken: '"), + ("aws_secret_access_key = AKIAAAAAAAAAAAAAAAAAabc+/=", "aws_secret_access_key = "), + ("Set `api_token=abc123/xyz` in config.", "Set `api_token="), + ], +) +def test_a_secret_named_in_lower_or_mixed_case_goes(text: str, kept: str) -> None: + out = redact_secrets(text) + assert out.startswith(kept + REDACTED) + assert text[len(kept) :].strip("'") not in out + ((start, _end),) = secret_spans(text) + assert start == len(kept) + + +@pytest.mark.parametrize( + "text", + [ + "token = get_token()", + "secret_token = os.environ['X']", + "self.api_token = cfg.token", + "apiToken: string;", + "access_token: str = field(default='')", + "my_secret = load_secret(path)", + "api_token = token_v2.value", + "db_password = None", + "user_password_hash = h(x)", + # Counts and names a model's settings use (found by the review). + "max_tokens=4096", + "prompt_tokens: 1200,", + "input_tokens=1234", + "completion_tokens=3456)", + "x_tokenizer=gpt2", + "api_token = token_v2", + "my_secret = secret1", + # Found by the second review: arithmetic, comparisons, types, settings. + "next_token = pos+1", + "let lastToken = idx+1;", + "ctx.prev_token=tok+1", + "x_token_id = vocab_size-1", + "my_token = 0.5*x", + "if user_token==expected_token:", + "a.access_token===b.access_token", + "my_token != x2", + "apiToken: Uint8Array;", + "authToken: Base64String", + "ssl_secret_path = /etc/ssl/private/key2.pem", + "db_password_file: /run/secrets/db1", + 'oauth_token_url="https://oauth2.googleapis.com/token"', + "auth_token_ttl=3600s", + "refresh_token_ttl: 720h", + "x_secret_version: v1.2.3", + "embed_token_model: text-embedding-3-small", + "my_token=1.2.3", + "my_token=1e10", + "ui_password_min=8chars", + "refresh_token_expires_at=2026-12-03T08:00:00Z", + "request_token_id=1b4e28ba-2fa1-11d2-883f-0016d3cca427", + "data_token: 0x1f2e3d", + "user_password_hash=5e884898da28047151d0e56f8dc6292773603d0d", + # Found by the third review: code with no spaces. + "const sameToken=prevToken===nextToken;", + "var hasToken=t!==null", + "nextToken=offset+limit", + "expiresToken=now+3600*1000", + "num_token=2**16", + 'o.accessToken=e.data.token+"x"', + # Found by the fourth review: numbers with units, other bases, comparisons. + "refresh_token = 1_000", + "refresh_token = 3600s", + "refresh_token = 0o755", + "refresh_token = 0b1010", + "refresh_token = 0.5f", + "refresh_token = 100L", + "refresh_token = 512MB", + "has_token=count>=1", + "apiToken: x<=10", + ], +) +def test_code_that_names_a_secret_is_left_alone(text: str) -> None: + assert redact_secrets(text) == text + assert secret_spans(text) == [] + + +@pytest.mark.parametrize( + ("text", "kept"), + [ + ("x_" + "token" * 64000, None), + ("q_token=" * 64000 + "(", None), + ("my_token = " * 64000 + "x(y)", None), + ("x_token=" + "a_" * 64000 + "/", f"x_token={REDACTED}"), + ], + ids=["one long name", "names in one value", "names in a chain", "a long snake_case value"], +) +def test_many_secret_words_in_a_row_are_read_once(text: str, kept: str | None) -> None: + # Each word was read to the end of the run: 24 s for 80 KB; a snake_case + # check backtracked once per "_" (found by the reviews). + started = time.perf_counter() + assert redact_secrets(text) == (text if kept is None else kept) + secret_spans(text) + assert time.perf_counter() - started < 10 + + +def test_many_lower_case_assignments_are_masked_in_one_pass() -> None: + text = "my token is here and x_token=abc12345 then " * 20000 + started = time.perf_counter() + out = redact_secrets(text) + assert time.perf_counter() - started < 10 + assert out.count(REDACTED) == 20000 and "abc12345" not in out + + +def test_a_closing_backtick_stays() -> None: + # Found by the third review: the mask ate the backtick that closes the code. + assert redact_secrets("Set `api_token=abc123/xyz` in config.") == ( + f"Set `api_token={REDACTED}` in config." + ) + + +def test_a_first_key_line_cut_before_a_word_still_goes() -> None: + # Found by the fourth review: 8 to 39 characters of a DER key's first line showed. + text = f"{begin('')}\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC575 truncated" + assert not any(gram in redact_secrets(text) for gram in GRAMS) diff --git a/core/tstd/logging.py b/core/tstd/logging.py index 9fcd271c..5b20671a 100644 --- a/core/tstd/logging.py +++ b/core/tstd/logging.py @@ -37,6 +37,131 @@ _SK_WORD = r"(?:[A-Z]?[a-z]{1,24}[0-9]{0,4}|[A-Z]{1,4}[0-9]{0,4}|[0-9]{1,8})" _SK_WORDS = rf"{_SK_WORD}(?:[-_]+{_SK_WORD})*[-_]*(?![a-zA-Z0-9_-])" +# TD-5447: a private key's body when the block has no END line (a key cut +# short by an output limit, or pasted without it). Its lines are split by any +# line break, real or written as an escape at any depth: "\n" in a JSON or +# .env value or a Python repr, "\\n" in JSON inside JSON, "\u000a", "\012", +# "%0A", " ", "
", or one JSON string per line ("…", "…"). Around a +# break there may be spaces, quotes, commas, "+", a shell's "\", ANSI colours +# or zero-width characters, and in front of a line a comment or quote mark, a +# diff's "-"/"+", or a tool's line number ("12 | ", "2:", "key.pem:2:"). A +# key character may itself be escaped ("\/", "%2F", "/"). +# The first line must read as key text: a DER or OpenSSH key's start, or a +# digit, "+" or "/" in it, and no "=", ":", "(" or ".name" after it. So prose +# after a BEGIN line ("Paste your key here") and code after one +# (HEADER = "…"\nkey_bytes = b64decode(body)) stay. Once a key line is seen, +# every key-character line after it goes too. A key on one line with spaces +# for its newlines goes run by run the same way. +# A literal start, so the search skips ahead to "-----" (an any-case group +# here would make every "-" a place to try). The spaces in the line may be +# URL- or JSON-encoded ("BEGIN%20PRIVATE%20KEY", "BEGIN+PRIVATE+KEY"). +_PEM_SP = r"(?: |%20|\+|\\+u0020)" +_PEM_BEGIN = ( + rf"-----(?:BEGIN{_PEM_SP}(?:[A-Z0-9]+{_PEM_SP})*?PRIVATE{_PEM_SP}KEY(?:{_PEM_SP}BLOCK)?" + rf"|begin{_PEM_SP}(?:[a-z0-9]+{_PEM_SP})*?private{_PEM_SP}key(?:{_PEM_SP}block)?)-----" +) +_PEM_END = ( + rf"-----(?:END{_PEM_SP}(?:[A-Z0-9]+{_PEM_SP})*?PRIVATE{_PEM_SP}KEY(?:{_PEM_SP}BLOCK)?" + rf"|end{_PEM_SP}(?:[a-z0-9]+{_PEM_SP})*?private{_PEM_SP}key(?:{_PEM_SP}block)?)-----" +) +_SSH2_BEGIN = r"---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----" +_SSH2_END = r"---- END SSH2 ENCRYPTED PRIVATE KEY ----" +_PEM_NEXT_BEGIN = rf"(?:-----(?:BEGIN|begin){_PEM_SP}|---- BEGIN )" +_PEM_BREAKS = r"\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029" +_PEM_VBREAK = rf"[{_PEM_BREAKS}]" +_PEM_HSPACE = rf"[^\S{_PEM_BREAKS}]" +# What follows the backslashes of an escaped line break. +_PEM_ESCAPED_BREAK = ( + r"(?:[nrfv]|u(?:000[a-dA-D]|001[c-eC-E]|0085|202[89])|x(?:0[a-dA-D]|85)|0?1[25])" +) +_PEM_BREAK_ENTITY = r"(?:(?:amp;)*+#(?:0*1[03]|[xX]0*[aAdD]);|NewLine;)" +_PEM_QUOTE = r"\\*[\"'`]" +# An HTML line:
, or a block or cell tag (

,

, ). +_PEM_TAG = r"<(?:br\s*/?|/?(?:p|div|li|tr|td|pre|code|span)(?![A-Za-z0-9])[^<>]{0,64})>" +_PEM_NEWLINE = ( + rf"(?:\r\n|{_PEM_VBREAK}|\\+r\\+n|\\+{_PEM_ESCAPED_BREAK}|%0[dD]%0[aA]|%0[aAdD]|&{_PEM_BREAK_ENTITY}" + rf"|{_PEM_TAG}|\\+N\{{(?:LINE FEED|LF|NEW LINE|CARRIAGE RETURN|CR)\}}" + # SQL: '…' || chr(10) || '…' + rf"|{_PEM_QUOTE}{_PEM_HSPACE}*+\|\|{_PEM_HSPACE}*+(?i:chr|char)\(1[03]\)" + rf"{_PEM_HSPACE}*+\|\|{_PEM_HSPACE}*+{_PEM_QUOTE})" +) +_PEM_ANSI = r"(?:\x1b|\\+u001[bB]|\\+x1[bB]|\\+e)\[[0-9;]*m" +_PEM_DECOR = ( + rf"(?:{_PEM_HSPACE}|\\+t|\\+u00(?:[aA]0|09)|{_PEM_ANSI}|[,+|$]" + r"|[\u200b-\u200d\u2060\ufeff]|\\+u(?:200[b-dB-D]|2060|[fF][eE][fF][fF])|\\++(?=\r?\n))" +) +# A line's prefix: a log line's time and source (syslog, journalctl, an ISO +# time, "[INFO]"), a line number (cat -n, less -N, grep, bat), a comment, quote +# or diff mark, or the Python prompt. Several may stack ("> > "). +_PEM_PREFIX = ( + r"(?:[A-Z][a-z]{2}[ \t]++\d{1,2}[ \t]++\d\d:\d\d:\d\d[ \t]++[^\s:]++[ \t]++[^\s:]++:" + r"|\d{4}-\d\d-\d\d[T ][\d:.,]++(?:Z|[-+]\d\d:?\d\d)?" + r"(?:[ \t]++(?:stdout|stderr)[ \t]++[FP])?" # a container log line + rf"|\[[^\]{_PEM_BREAKS}]{{1,64}}\]" + r"|(?:[\w./-]+?[:-])?\d{1,7}" + r"(?:\t|\\+t|→|\\+u2192|[ \t]*+(?:│|\\+u2502|\||-(?!-))|:|\.(?=[ \t])|[ \t]++)" + r"|(?:TRACE|DEBUG|INFO|WARN(?:ING)?|ERROR|FATAL|CRITICAL)(?![A-Za-z0-9]):?" + r"|[^\s\"'`]{1,32}\t" # a column before a tab + r"|//+|#+|>+|<+(?=[ \t])|;+|%++(?!0[aAdD])|\*+|\|+|--?(?!-)|\.\.\.)" +) +# The rest of a line, to its line break, real or escaped; read once. +_PEM_REST_OF_LINE = ( + rf"(?:[^\\%&<{_PEM_BREAKS}]++|\\++(?!{_PEM_ESCAPED_BREAK})|%(?!0[aAdD])" + rf"|&(?!{_PEM_BREAK_ENTITY})|(?!{_PEM_TAG})<)*+" +) +# A string ends and the next one starts: one per line in source code +# ('"…\n" +' then '"…'), or one after another on one line ('"…", "…"'). A +# quote is crossed only so: a closing quote alone ends the key, and so does a +# run of quotes ('"""'). +_PEM_NEXT_STRING = ( + rf"{_PEM_QUOTE}{_PEM_DECOR}*+(?:(?:#|//){_PEM_REST_OF_LINE})?" # a comment after it + rf"(?:{_PEM_NEWLINE}{_PEM_DECOR}*+(?:{_PEM_PREFIX}{_PEM_DECOR}*+)*+)*+{_PEM_QUOTE}(?![\"'`])" +) +_PEM_SEP = ( + rf"(?:(?:{_PEM_NEXT_STRING}|{_PEM_DECOR}*+{_PEM_NEWLINE})" + rf"(?:{_PEM_DECOR}*+{_PEM_PREFIX})*+{_PEM_DECOR}*+" + rf"(?:{_PEM_NEXT_STRING}(?:{_PEM_DECOR}*+{_PEM_PREFIX})*+{_PEM_DECOR}*+)?)++" +) +_PEM_CHARS = r"A-Za-z0-9+/=_-" +# One key character, plain or escaped ("\\/", "\\u002b", "%2F", "/", "/"). +_PEM_ONE_CHAR = ( + rf"(?:[{_PEM_CHARS}]|\\+/|\\+u00(?:2[bBfF]|3[dD])|%2[bBfF]|%3[dD]" + r"|&#(?:[xX]0*2[bBfF]|[xX]0*3[dD]|0*4[37]|0*61);|&(?:sol|plus|equals);)" +) +_PEM_CHAR = rf"(?:[{_PEM_CHARS}]++|{_PEM_ONE_CHAR})" +_PEM_RUN = rf"(?!--){_PEM_CHAR}++" +_PEM_LONG = rf"(?=[{_PEM_CHARS}]{{40}}){_PEM_RUN}" +# Key text: a DER key's start, OpenSSH's, or a digit, "+" or "/" in the run. +_PEM_KEYISH = ( + rf"(?=M[IHC]|b3Blbn|[A-Za-z_-]*+(?:[0-9+/]|\\+/|\\+u00|%2|&))" + rf"(?={_PEM_ONE_CHAR}{{8}}){_PEM_RUN}" +) +# What makes a run code, not a key line: an assignment, a dict key, a call, +# an attribute. +_PEM_CODE_NEXT = rf"(?:\.(?=[A-Za-z_])|\(|{_PEM_HSPACE}*+{_PEM_QUOTE}?{_PEM_HSPACE}*+[=:])" +# A first key line is not followed by words on the same line +# ("sha256sum key.pem", "base64encoded body here"), only by more key text, +# a line break, a cut or a string's end. +_PEM_LINE_ENDS = rf"(?!{_PEM_HSPACE}++(?!{_PEM_KEYISH})[A-Za-z_])" +# A DER or OpenSSH key's start ("MIIEvQ…", not "MIN_KEY_LEN") is a key line +# whatever follows; any other first line must not read as code or run on into +# words. +_PEM_FIRST = ( + rf"(?:(?=M[IHC][A-Z0-9+/]*+[a-z0-9]|b3Blbn)(?={_PEM_ONE_CHAR}{{8}}){_PEM_RUN}" + rf"(?!{_PEM_CODE_NEXT})|{_PEM_KEYISH}(?!{_PEM_CODE_NEXT}){_PEM_LINE_ENDS})" +) +# A later line that is one plain word ("hello", "Then", "return") is not key +# text: a key line's random letters never read as one. +_PEM_NOT_A_WORD = rf"(?!(?:[A-Z]?[a-z]++|[A-Z]{{1,7}})(?!{_PEM_ONE_CHAR}))" +# An old-style key's or an armored block's header line, read to its line break. +_PEM_INFO = rf"(?:Proc-Type|DEK-Info|Version|Comment|Charset|Hash|Subject):{_PEM_REST_OF_LINE}" +_PEM_CUT = r"(?=\Z|[\"'…\]}]|\\+u2026)" +_PEM_BODY_CUT_SHORT = ( + rf"(?:(?:{_PEM_SEP}(?:{_PEM_INFO}|{_PEM_FIRST})|{_PEM_HSPACE}*+{_PEM_FIRST})" + rf"(?:{_PEM_SEP}(?:{_PEM_INFO}|{_PEM_NOT_A_WORD}{_PEM_RUN}(?!{_PEM_CODE_NEXT}))" + rf"|{_PEM_HSPACE}++(?:{_PEM_LONG}|{_PEM_KEYISH}|{_PEM_RUN}{_PEM_CUT}))*+)?" +) + # Patterns that must be redacted in log output (from tst-cua policy.py). SECRET_PATTERNS: list[re.Pattern[str]] = [ # OpenAI / OpenRouter / Anthropic key. Dashed forms (sk-or-v1-…, @@ -57,11 +182,18 @@ re.compile(r"(gho_[A-Za-z0-9_]{20,})"), # GitHub OAuth token re.compile(r"(ghs_[A-Za-z0-9_]{20,})"), # GitHub server token re.compile(r"(AKIA[0-9A-Z]{16})"), # AWS access key - # SECUX-02: the whole PEM block, body and END line too; a block cut - # short still loses everything after its BEGIN line. + # SECUX-02: the whole PEM block, body and END line too. A block cut + # short (no END line) loses its body: every line after the BEGIN line + # that reads as key text (TD-5447, see _PEM_BODY_CUT_SHORT). The search + # for the END line stops at the next BEGIN line, so a text with many + # BEGIN lines and no END line is read once, not once per BEGIN line. + re.compile( + rf"{_PEM_BEGIN}" + rf"(?:(?:(?!{_PEM_NEXT_BEGIN})[\s\S])*?{_PEM_END}|{_PEM_BODY_CUT_SHORT})" + ), re.compile( - r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----" - r"(?:[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----|[A-Za-z0-9+/=\s]*)" + rf"{_SSH2_BEGIN}" + rf"(?:(?:(?!{_PEM_NEXT_BEGIN})[\s\S])*?{_SSH2_END}|{_PEM_BODY_CUT_SHORT})" ), re.compile(r"(-----BEGIN\s+(RSA |EC |DSA |OPENSSH )?PRIVATE KEY)"), # a header alone re.compile(r"\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}"), # Stripe secret / restricted @@ -85,6 +217,87 @@ r"\b([A-Z][A-Z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|APIKEY|ACCESS_KEY|PRIVATE_KEY)" r"[A-Z0-9_]*\s*[=:]\s*[\"']?)(?![$({\[<])([^\s\"'(){}\[\],;&]{4,})" ) +# TD-5447: the same names in any case, as in ~/.aws/credentials +# (``aws_secret_access_key = …``) or a lower-case .env. Code the agent reads +# names values the same way (``next_token = pos+1``, ``apiToken: Uint8Array``, +# ``max_tokens=4096``, ``auth_token_ttl=3600s``), and a mask written back into +# a file breaks it. So here the name must end in a credential word, with a +# name character before it ("db_password", "apiToken", not "token_ttl" or +# "tokenizer"); "=" or ":" must not start a comparison ("=="); and the value +# must hold a digit, "/", "+" or "=", may not run into "(" or "[", and may not +# read as code (_looks_like_code): a comparison, a number, version or hex +# literal, a word with up to 3 digits after it ("secret1"), a snake_case, +# dotted or type name ("Uint8Array"), or arithmetic on names and numbers. +_ASSIGNED = r"[^\s\"'`(){}\[\],;&]" +_SECRET_NAME_ENDS = ( + "password", + "passwd", + "secret", + "token", + "api_key", + "apikey", + "access_key", + "accesskey", + "private_key", + "privatekey", + "secret_key", + "secretkey", +) +_SECRET_NAME_END_ANY_CASE = re.compile( + "|".join( + "".join(f"[{c.upper()}{c.lower()}]" if c.isalpha() else c for c in word) + for word in _SECRET_NAME_ENDS + ) +) +# A value may hold a mask a pattern above already made ("AKIA…abc+/=" +# becomes "[REDACTED]abc+/="): the value still goes whole, as secret_spans says. +_ANY_CASE_VALUE = re.compile( + r"[ \t]*+[=:](?!=)[ \t]*+[\"']?(?!\$|[({<]|\[(?!REDACTED\]))" + rf"((?:\[REDACTED\]|{_ASSIGNED})(?:\[REDACTED\]|{_ASSIGNED})*+)" +) +_LOOKS_LIKE_CODE = re.compile( + r"v?[0-9]++(?:\.[0-9]++)*+(?:[eE][-+]?[0-9]++)?" # a number or version: 4096, 1e10, v1.2.3 + r"|v?[0-9]++(?:\.[0-9]++)++[-+][0-9A-Za-z.-]++" # a version's build: 1.0.0+build.5 + r"|[0-9]++(?:_[0-9]++)++|0[oO][0-7]++|0[bB][01]++" # 1_000, 0o755, 0b1010 + r"|[0-9]++(?:[_.][0-9]++)*+[A-Za-z]{1,5}" # a number and its unit: 3600s, 0.5f, 10_000ns + r"|[0-9]++(?::[0-9]++)++" # a time: 12:30, 10:30:00 + r"|[0-9]{4}-[0-9]{2}-[0-9]{2}(?:T[0-9:.]++(?:Z|[-+][0-9:]++)?)?" # a date: 2024-01-01T00:00:00Z + r"|[a-z]++(?:/[a-z]++)++" # words joined by "/": image/png, a/b/c + r"|0[xX][0-9a-fA-F]++" # a hex literal + r"|[A-Za-z]++[0-9]{0,3}" # a word, up to 3 digits after it: secret1, gpt2 + r"|[A-Za-z_][A-Za-z0-9_]*+(?:\.[A-Za-z_][A-Za-z0-9_]*+)++" # a dotted name: cfg.token + r"|(?:[A-Z][a-z]++[0-9]*+)++" # a type name: Uint8Array, Base64String +) +_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*+") +# A name as code writes it: lower or snake case, camelCase or PascalCase +# words (a key's random letters are none of these), dotted or not. +_WORD = r"(?:[a-z_$][a-z0-9_$]*+(?:[A-Z][a-z][a-z0-9_]*+)*+|(?:[A-Z][a-z][a-z0-9_]*+)++)[A-Z]?" +_OPERATORS = "-+*/%?|^<>!" +_EXPRESSION = re.compile( + rf"(?:{_WORD}(?:\.{_WORD})*+|[0-9]++(?:\.[0-9]++)?)?" + rf"(?:[-+*/%?|^<>!]{{1,3}}(?:{_WORD}(?:\.{_WORD})*+|[0-9]++(?:\.[0-9]++)?))*+" + r"[-+*/%?|^<>!]{0,3}" +) +_NUMBER_OPERAND = re.compile(r"(?:^|[-+*/%?|^<>!])[0-9]") + + +def _looks_like_code(value: str) -> bool: + if not any(c.isdigit() or c in "/+=" for c in value): + return True + if any(op in value for op in ("==", "!=", ">=", "<=")): # a===b, t!==null, n>=1 + return True + if _LOOKS_LIKE_CODE.fullmatch(value): + return True + if "_" in value and _IDENTIFIER.fullmatch(value): # a snake_case name: token_v2 + return True + # Arithmetic on names and numbers: pos+1, offset+limit, 2**16, a??n+1. Division + # alone counts only with a number in it, as a key's "/" joins random runs. + # e.data.token+ (the rest is a quoted string) counts too. + return _EXPRESSION.fullmatch(value) is not None and ( + any(c in _OPERATORS and c != "/" for c in value) + or _NUMBER_OPERAND.search(value) is not None + ) + # The user info of a URL (``https://user:pass@host`` or ``https://token@host``) # is a credential on every output path (LIVE2-01). @@ -161,6 +374,65 @@ def log_directory(data_dir: Path) -> Path: MIN_KNOWN_SECRET_CHARS = 8 +def _any_case_assignments(text: str) -> list[tuple[int, int]]: + """Where the values of the any-case secret assignments in *text* are, in order. + + The credential words are found by plain search on a lower-cased copy: a + regex tried at every position of long prose costs several times more. A + value is read once: a credential word inside a value already read is skipped. + """ + lowered = text.lower() + if len(lowered) == len(text): + ends = sorted( + {at + len(word) for word in _SECRET_NAME_ENDS for at in _find_all(lowered, word)} + ) + else: # a few characters change length when lower-cased; positions would drift + ends = sorted({m.end() for m in _SECRET_NAME_END_ANY_CASE.finditer(text)}) + found: list[tuple[int, int]] = [] + read_to = 0 + for end in ends: + if end < read_to or (end < len(text) and _is_name_char(text[end])): + continue + start = end - next(len(w) for w in _SECRET_NAME_ENDS if lowered.endswith(w, 0, end)) + # A name character before the word, or a mask a pattern made of the + # name's first part ("AKIA…token" is "[REDACTED]token" by now). + if start == 0 or not (_is_name_char(text[start - 1]) or text.endswith(REDACTED, 0, start)): + continue + match = _ANY_CASE_VALUE.match(text, end) + if match is None: + continue + read_to = match.end() + if len(match.group(1)) < 4 or (read_to < len(text) and text[read_to] in "(["): + continue + if not _looks_like_code(match.group(1)): + found.append(match.span(1)) + return found + + +def _is_name_char(char: str) -> bool: + return char.isascii() and (char.isalnum() or char == "_") + + +def _masked(text: str, spans: list[tuple[int, int]]) -> str: + """*text* with each of the (in order, not overlapping) *spans* replaced by REDACTED.""" + if not spans: + return text + parts, last = [], 0 + for start, end in spans: + parts += [text[last:start], REDACTED] + last = end + parts.append(text[last:]) + return "".join(parts) + + +def _find_all(text: str, word: str) -> list[int]: + found, at = [], text.find(word) + while at != -1: + found.append(at) + at = text.find(word, at + 1) + return found + + def register_secret_value(value: str) -> None: """Scrub *value* from every output path for the life of the process. @@ -197,6 +469,7 @@ def redact_secrets(text: str) -> str: for pattern in SECRET_PATTERNS: text = pattern.sub(REDACTED, text) text = _SECRET_ASSIGNMENT.sub(lambda m: m.group(1) + REDACTED, text) + text = _masked(text, _any_case_assignments(text)) return _URL_USERINFO.sub(_masked_userinfo, text) @@ -215,6 +488,7 @@ def secret_spans(text: str) -> list[tuple[int, int]]: for pattern in SECRET_PATTERNS: found += [m.span() for m in pattern.finditer(text)] found += [m.span(2) for m in _SECRET_ASSIGNMENT.finditer(text)] + found += _any_case_assignments(text) for m in _URL_USERINFO.finditer(text): if m.group(3) is None: found.append(m.span(2)) diff --git a/docs/tst-desk-backlog.md b/docs/tst-desk-backlog.md index 9b55be9a..fcf7a341 100644 --- a/docs/tst-desk-backlog.md +++ b/docs/tst-desk-backlog.md @@ -16171,3 +16171,13 @@ Cost: redacting at read time makes a read about ten times slower (a 352 KB feed - [x] The watcher keeps the current feed's scrubbed frames, one for a window (with the folder's path) and one for a phone or another computer (without it), and empties them when its fingerprint says the folder changed, or when a secret is registered at run time (`register_secret_value`): a frame scrubbed before that would still hold it, and the push sends frames as they are. A frame scrubbed while a secret was being registered isn't kept. The push and `get_code_feed` share the frames; each reply still goes through the reply funnel's scrub. **Size:** 1 · **Status:** Done + +### TD-5447 — Scrubber: a private key's body never shows, however it is written or cut + +- [x] A private key without its END line (cut short by an output limit, or pasted without it) loses its whole body. Its lines may be split by any line break, real (including Word's and Unicode's) or written as an escape at any depth (`\n` in a JSON or .env value or a Python repr, `\\n` in JSON inside JSON, `\u000a`, `\012`, `%0A`, ` `, `&#10;`, `
`, `

`/`

`, SQL's `|| chr(10) ||`), or be one string after another, as source code and JSON arrays write them. Around a break there may be spaces, commas, `+`, a shell's `\`, ANSI colours or zero-width characters, and in front of a line a comment or quote mark, a diff's mark, a log line's time, source or level (syslog, journalctl, container logs, `INFO`), or a tool's line number (`12 | `, bat's `│`, `less -N`, grep's `2:`, `k.pem:2:` and `k.pem-2-`). Key characters may be escaped (`\/`, `\u002b`, `%2F`, `/`, `/`). Base64url bodies, old-style `Proc-Type`/`DEK-Info` lines, lower-case and URL-encoded BEGIN lines, PGP private key blocks and SSH2 private keys are covered. Before, the body after the first escape showed in chat text, tool output and on the wire: N_MAIN of the 64 tested shapes showed part of a key, now none. +- [x] Prose and code after a BEGIN line keep their words (`…PRIVATE KEY----- marks where a key starts`, `HEADER = "…"` then `key_bytes = b64decode(body)`): the first line must read as key text, not as an assignment, attribute, call or words, and a later line that is one plain word ends the key. Only the BEGIN line itself is masked. A key cut short inside a string stops at the string's end, so the next line, dict key or list item stays. +- [x] The search for a block's END line stops at the next BEGIN line: a 1 MiB text with 2,000 BEGIN lines and no END line took about two minutes and now takes a quarter of a second. Header lines and long runs after a BEGIN line are read once. +- [x] Secret names in any case (`aws_secret_access_key = …`, `db_password=…`, `apiToken: '…'`). Code that names a secret the same way is left alone: in lower or mixed case the name must end in a credential word (`auth_token_ttl`, `oauth_token_url`, `max_tokens`, `x_tokenizer` stay), `==` is a comparison, and the value must hold a digit, `/`, `+` or `=` and not read as code (a comparison; a number with or without a unit, a version, time, date, or hex, octal or binary literal; a word with up to 3 digits after it; a snake_case, dotted or type name; words joined by `/`; arithmetic such as `pos+1` or `offset+limit`; a call or an index). Each value is read once. +- [x] Tested in 80 shapes, each cut at every point and ended five ways, as text, on the wire and JSON-escaped on the wire, and in chat, tool-result and shell-output events; 83 code, prose and settings texts that must stay as they are. + +**Size:** 1 · **Status:** Done