Skip to content

Commit f48d97e

Browse files
review(session-tools-2): redact a private key cut off at the front and flattened onto one line [plan 5, F]
The END-armour walk-back required a line break before the armour, so a block whose BEGIN line was lost and whose newlines became spaces ("<b64> <b64> -----END RSA PRIVATE KEY-----") redacted only the END armour and every body run survived in the text (lane L, found-not-fixed #4). _flattened_tail_start mirrors the flattened BEGIN rule backwards: from the armour, take whitespace-separated runs of body length (the same 20-character floor as _INLINE_BODY_RUN, so "see page 12 of the notes" before an END stays prose) until a shorter word, a line break, another armour or an earlier pass's NUL mask. The run nearest the armour may also be glued onto it (a paste that dropped its newlines) or a PGP CRC line "=XXXX". Each step moves strictly left and stops at the previous armour's dashes, so 20 000 END armours on one line walk their own runs once (139 ms for 3.2 MB; 1 MB body then END 29-32 ms). The line-break form is untouched (disjoint on the character before END), and the reference-algorithm corpus is byte-identical. The run alphabet is built from string.ascii_letters/digits: written out, the 65 base64 characters read as a high-entropy secret to detect-secrets.
1 parent 987fe26 commit f48d97e

2 files changed

Lines changed: 178 additions & 0 deletions

File tree

‎packages/agent-session-tools/src/agent_session_tools/scrubber.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import logging
1212
import re
13+
import string
1314
from dataclasses import dataclass, field
1415
from pathlib import Path
1516
from typing import Any
@@ -161,6 +162,13 @@
161162
rf"(?:(?=\r?\n|\\[rn]){_PEM_BODY}|{_PEM_INLINE_BODY})?"
162163
)
163164
_PEM_FOOT = re.compile(rf"-----END{_PEM_LABEL}-----")
165+
# One run of a flattened body: the characters _INLINE_BODY_RUN admits, as a
166+
# set, for the backwards walk from an END armour (no "-", so the walk stops
167+
# at the previous armour; no NUL, so it stops at an earlier pass's mask).
168+
# Built from the stdlib constants: the alphabet written out is 65 base64
169+
# characters, which the commit-time entropy scanner reads as a secret.
170+
_INLINE_RUN_CHARS = frozenset(string.ascii_letters + string.digits + "+/=")
171+
_INLINE_RUN_LENGTH = 20 # the body-length lookahead in _INLINE_BODY_RUN
164172

165173

166174
def _mask(text: str, spans: list[tuple[int, int]]) -> str:
@@ -178,6 +186,40 @@ def _mask(text: str, spans: list[tuple[int, int]]) -> str:
178186
return "".join(pieces)
179187

180188

189+
def _flattened_tail_start(text: str, armour: int) -> int:
190+
"""Start of the flattened body before the END armour at ``armour``.
191+
192+
Mirror of the flattened BEGIN rule, walked backwards: from the armour,
193+
take whitespace-separated runs of body length (``_INLINE_BODY_RUN``'s
194+
20-character floor, so ``see page 12 of the notes`` before an END armour
195+
stays prose) until a shorter word, a line break, another armour or an
196+
earlier pass's mask. Two shapes a key's last line takes are admitted as
197+
the run nearest the armour only: a run glued straight onto it (a paste
198+
that dropped its newlines; prose never glues onto an armour, the same
199+
reading the BEGIN rule makes), and a PGP CRC line ``=XXXX``. Each step
200+
moves strictly left, so a line of many END armours costs one walk per
201+
armour over its own runs, never a rescan.
202+
"""
203+
start = armour
204+
nearest = True
205+
while True:
206+
gap = start
207+
while gap > 0 and text[gap - 1] in " \t":
208+
gap -= 1
209+
run = gap
210+
while run > 0 and text[run - 1] in _INLINE_RUN_CHARS:
211+
run -= 1
212+
length = gap - run
213+
if length == 0:
214+
return start
215+
if length < _INLINE_RUN_LENGTH and not (
216+
nearest and (gap == armour or (text[run] == "=" and 2 <= length <= 5))
217+
):
218+
return start
219+
start = run
220+
nearest = False
221+
222+
181223
def _private_key_spans(text: str) -> list[tuple[int, int]]:
182224
"""Return the sorted, disjoint spans of PEM private-key material in text.
183225
@@ -211,6 +253,10 @@ def _private_key_spans(text: str) -> list[tuple[int, int]]:
211253
and not masked.endswith("-----", 0, start)
212254
):
213255
start -= 1
256+
else:
257+
# Cut off at the front AND flattened onto one line: the body runs
258+
# sit before END with spaces for line breaks (plan 5, F).
259+
start = _flattened_tail_start(masked, start)
214260
spans.append((start, match.end()))
215261
return sorted(spans)
216262

‎packages/agent-session-tools/tests/test_scrubber.py‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,138 @@ def test_prose_after_an_armour_line_and_an_inline_header_is_still_prose() -> Non
927927
)
928928

929929

930+
# ===========================================================================
931+
# A block cut off at the FRONT and flattened onto one line (plan 5, F; lane
932+
# L's found-not-fixed #4). The END-armour walk-back required a line break
933+
# before END, so "<b64> <b64> -----END ...-----" redacted only the armour and
934+
# every body run survived. Mirror of the flattened BEGIN rule: from the END
935+
# armour, walk back over whitespace-separated runs of body length.
936+
# ===========================================================================
937+
938+
939+
def test_flattened_front_cut_pem_leaves_no_body_and_keeps_the_prose_before_it() -> None:
940+
body = _pem_body("front-cut-flat")[3:]
941+
text = (
942+
"Here is the tail: "
943+
+ " ".join(body)
944+
+ " "
945+
+ _pem_marker("END", "RSA")
946+
+ " and that was it."
947+
)
948+
result = Scrubber().scrub(text)
949+
for line in body:
950+
assert line not in result.text
951+
assert result.text == "Here is the tail: [PRIVATE_KEY-001] and that was it."
952+
953+
954+
def test_flattened_front_cut_pgp_block_takes_its_checksum_too() -> None:
955+
"""The PGP CRC line ``=XXXX`` sits between the body and END; it goes with
956+
the body (lane L's shape: ``<b64> <b64> =chk -----END PGP ...-----``)."""
957+
body = _pem_body("front-cut-pgp")[2:]
958+
text = (
959+
"paste: "
960+
+ " ".join(body)
961+
+ " "
962+
+ _pgp_checksum("front-cut-pgp")
963+
+ " "
964+
+ _pgp_marker("END")
965+
+ " [end]"
966+
)
967+
result = Scrubber().scrub(text)
968+
for line in body:
969+
assert line not in result.text
970+
assert _pgp_checksum("front-cut-pgp") not in result.text
971+
assert result.text == "paste: [PRIVATE_KEY-001] [end]"
972+
973+
974+
def test_flattened_front_cut_pem_glued_to_its_end_armour_leaves_no_body() -> None:
975+
"""A paste that dropped its newlines entirely glues the last run onto END."""
976+
body = _pem_body("front-cut-glued")[4:]
977+
text = "x " + " ".join(body) + _pem_marker("END", "EC") + " y"
978+
result = Scrubber().scrub(text)
979+
for line in body:
980+
assert line not in result.text
981+
assert result.text == "x [PRIVATE_KEY-001] y"
982+
983+
984+
def test_short_words_before_an_end_armour_on_one_line_are_prose() -> None:
985+
"""Nothing before END is body unless it is a run of body length; a page
986+
reference and a date are words, not base64 lines."""
987+
text = "see page 12 of the 2026-01-01 notes " + _pem_marker("END", "RSA") + " ok"
988+
result = Scrubber().scrub(text)
989+
assert result.text == "see page 12 of the 2026-01-01 notes [PRIVATE_KEY-001] ok"
990+
991+
992+
def test_front_cut_walk_back_stops_at_the_first_word_that_is_not_body() -> None:
993+
"""Runs of body length are taken until a shorter word; prose in front of
994+
the key is left exactly as it was, including its spacing."""
995+
body = _pem_body("front-cut-stop")[:2]
996+
text = "token: abc123 " + " ".join(body) + " " + _pem_marker("END", "RSA")
997+
result = Scrubber().scrub(text)
998+
assert result.text == "token: abc123 [PRIVATE_KEY-001]"
999+
1000+
1001+
@pytest.mark.parametrize(("length", "is_body"), [(19, False), (20, True)])
1002+
def test_front_cut_body_run_length_boundary_matches_the_begin_rule(
1003+
length: int, is_body: bool
1004+
) -> None:
1005+
run = "A" * length
1006+
text = "w " + run + " " + _pem_marker("END", "RSA")
1007+
result = Scrubber().scrub(text)
1008+
assert (run not in result.text) is is_body
1009+
1010+
1011+
def test_two_front_cut_tails_on_one_line_are_two_redactions() -> None:
1012+
"""The walk-back from the second END must stop at the first END armour."""
1013+
first = _pem_body("front-cut-two-a")[5:]
1014+
second = _pem_body("front-cut-two-b")[5:]
1015+
text = (
1016+
" ".join(first)
1017+
+ " "
1018+
+ _pem_marker("END", "RSA")
1019+
+ " then "
1020+
+ " ".join(second)
1021+
+ " "
1022+
+ _pem_marker("END", "RSA")
1023+
)
1024+
result = Scrubber().scrub(text)
1025+
for line in first + second:
1026+
assert line not in result.text
1027+
assert result.text.count("[PRIVATE_KEY-") == 2
1028+
assert " then " in result.text
1029+
1030+
1031+
def test_front_cut_flattened_tail_does_not_change_the_newline_form() -> None:
1032+
"""The line-break form (lane D) keeps its exact span -- the walk-back over
1033+
body characters includes the line break before the first body line, as it
1034+
always did -- because the two rules are disjoint on the character before END."""
1035+
body = _pem_body("tail-unchanged")[3:]
1036+
text = "...\n" + "\n".join(body) + "\n" + _pem_marker("END", "RSA") + "\nnext"
1037+
result = Scrubber().scrub(text)
1038+
assert result.text == "...[PRIVATE_KEY-001]\nnext"
1039+
1040+
1041+
def _many_flattened_tails(count: int) -> str:
1042+
"""``count`` flattened front-cut tails on ONE line: two body runs, then END."""
1043+
tail = "A" * 64 + " " + "B" * 64 + " " + _pem_marker("END", "RSA")
1044+
return " ".join([tail] * count)
1045+
1046+
1047+
def test_front_cut_walk_back_cost_grows_linearly_with_end_armours() -> None:
1048+
"""Ten times the END armours on one line may cost ten times the work: each
1049+
walk-back must stop at the armour before it, never rescan the line."""
1050+
from agent_session_tools.scrubber import _private_key_spans
1051+
1052+
small, large = _many_flattened_tails(200), _many_flattened_tails(2000)
1053+
assert len(_private_key_spans(large)) == 2000
1054+
per_tail_small = _best_of(lambda: _private_key_spans(small), 7) / 200
1055+
per_tail_large = _best_of(lambda: _private_key_spans(large), 5) / 2000
1056+
assert per_tail_large <= 3 * per_tail_small, (
1057+
f"per-tail cost grew {per_tail_large / per_tail_small:.1f}x "
1058+
"from 200 to 2000 flattened tails; the walk-back is not linear"
1059+
)
1060+
1061+
9301062
# ===========================================================================
9311063
# _private_key_spans cost (plan 4, D#1). The masking loop used to rebuild the
9321064
# whole string once per matched span, so a text with many armour lines cost

0 commit comments

Comments
 (0)