From c5694ed45a697b4fe8cf0ae430a903a117961cd0 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 12 Nov 2026 00:50:20 -0500 Subject: [PATCH 1/9] Guard source captures against visitor bot-check tokens Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 7 +- .../guard-source-capture-tokens.fixed.md | 1 + .../code_health/test_source_conflicts.py | 155 ++++++++++++++++++ .../test_source_capture_privacy_properties.py | 64 ++++++++ source_conflicts/sources/README.md | 4 + 5 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 changelog.d/guard-source-capture-tokens.fixed.md create mode 100644 policyengine_us/tests/core/test_source_capture_privacy_properties.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 44774aa7167..ae588cdc634 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -123,6 +123,10 @@ For code already on `main` that the PR doesn't change, you can skip step 1: pin The marker comes only in the follow-up PR, because the guard rejects a marker whose entry isn't in the pinned copy, or whose entry doesn't list the marker's file under `implementations`. A `proposed` row doesn't count. +When a source site serves bot-check scripts, capture it as pandoc text with a +`Source:` URL line and an extraction line, as [the capture guide](source_conflicts/sources/README.md) +describes, to avoid publishing visitor tokens or the fetching machine's address. + `policyengine_us/tests/code_health/test_source_conflicts.py` checks structure, not whether the code follows a statute. It fails when: - the vendored register (`source_conflicts/known-source-conflicts.yaml`) differs from its pin (`source_conflicts/pin.yaml`: rulespec-us commit and sha256); @@ -130,7 +134,8 @@ The marker comes only in the follow-up PR, because the guard rejects a marker wh - a marker names an entry that isn't in the pinned copy, or whose entry doesn't list the file under `implementations`; - an implementation the register marks `cites_entry: true` is missing here or has lost its marker; - the count of comments that read like a conflict between sources ("the instructions say", "in practice", "discrepancy", "Source conflict:", ...) changes in a file without a marker. A new file or a higher count means reword a comment that describes no conflict. If it describes a real conflict, keep it, record the conflict as a candidate (step 1) and add or raise the file's `KNOWN_UNMARKED` line in the same PR; the marker in step 3 then exempts the file, and its line comes out. A lower count means lower `KNOWN_UNMARKED`. A file with any valid marker is exempt, so the count doesn't prove every conflict in it is marked; -- a backlog item (`source_conflicts/candidates.yaml`) is malformed, already registered, cites a code path that isn't a file git tracks here (absolute, with `..`, or under a hidden directory such as `.github`), or contains a decision-queue id, a session id, a local path or an email address anywhere in the file: in its raw text, comments and keys included, and in every parsed value and key (escapes, `!!binary`, sets). Homoglyphs, such as a Cyrillic letter in "Source", are not caught; review catches those. +- a backlog item (`source_conflicts/candidates.yaml`) is malformed, already registered, cites a code path that isn't a file git tracks here (absolute, with `..`, or under a hidden directory such as `.github`), or contains a decision-queue id, a session id, a local path or an email address anywhere in the file: in its raw text, comments and keys included, and in every parsed value and key (escapes, `!!binary`, sets). Homoglyphs, such as a Cyrillic letter in "Source", are not caught; review catches those; +- any file under `source_conflicts/sources/` contains a bot-manager marker or a base64 token that decodes to a UUID, a dollar sign and an IPv4 address. Failures name the file and match kind without printing token values or addresses. A model that departs from the statute with no official source behind it is a bug, not a source conflict. Fix it, or open an issue. diff --git a/changelog.d/guard-source-capture-tokens.fixed.md b/changelog.d/guard-source-capture-tokens.fixed.md new file mode 100644 index 00000000000..6bd9ee28171 --- /dev/null +++ b/changelog.d/guard-source-capture-tokens.fixed.md @@ -0,0 +1 @@ +Added source capture checks and capture guidance to prevent publishing visitor bot-check tokens. diff --git a/policyengine_us/tests/code_health/test_source_conflicts.py b/policyengine_us/tests/code_health/test_source_conflicts.py index 59c143f2fdc..ed1778f0b2e 100644 --- a/policyengine_us/tests/code_health/test_source_conflicts.py +++ b/policyengine_us/tests/code_health/test_source_conflicts.py @@ -43,6 +43,8 @@ .git or .github). The file is public: its raw text (comments and keys included) and every parsed value and key (escapes, binary, sets) carry no decision-queue ids, session ids, local paths or email addresses. +6. No file under ``source_conflicts/sources/`` contains a bot-manager marker + or a base64 token that decodes to UUID + "$" + IPv4. These are structural checks: they tie markers, the register and the backlog together; they do not judge whether code follows a statute. rulespec-us's own @@ -53,6 +55,8 @@ from __future__ import annotations +import base64 +import binascii import functools import hashlib import io @@ -60,6 +64,7 @@ import subprocess import tokenize from collections import Counter +from ipaddress import IPv4Address from pathlib import Path import pytest @@ -70,6 +75,7 @@ REGISTER = FOLDER / "known-source-conflicts.yaml" PIN = FOLDER / "pin.yaml" CANDIDATES = FOLDER / "candidates.yaml" +SOURCES = FOLDER / "sources" THIS_REPO = "PolicyEngine/policyengine-us" SCANNED = ( "policyengine_us/variables", @@ -963,6 +969,155 @@ def test_candidates_are_public(): assert not problems, "\n".join(problems) +BOT_MANAGER_MARKERS = ( + b"__uzdbm", + b"perfdrive", + b"radware", + b"shieldsquare", + b"stormcaster", + b"__cf_chl", + b"cf_clearance", + b"incap_ses", + b"visid_incap", + b"datadome", + b"px-captcha", +) +# A UUID, dollar and IPv4 occupy 44 to 52 bytes, or 59 to 70 base64 +# characters before padding. Match whole tokens so longer data URIs stay out. +CAPTURE_BASE64_RE = re.compile( + rb"(? list[str]: + """Report match kinds without exposing captured tokens or addresses.""" + + problems = [] + lowered = raw.lower() + if any(marker in lowered for marker in BOT_MANAGER_MARKERS): + problems.append(f"{name} contains a bot-manager marker") + for match in CAPTURE_BASE64_RE.finditer(raw): + token = match.group() + try: + decoded = base64.b64decode(token + b"=" * (-len(token) % 4), validate=True) + except binascii.Error: + continue + visitor = CAPTURE_VISITOR_RE.fullmatch(decoded) + if visitor is None: + continue + try: + IPv4Address(visitor[1].decode("ascii")) + except ValueError: + continue + problems.append(f"{name} contains a base64 UUID-dollar-IPv4 token") + break + return problems + + +def test_source_captures_are_public(): + problems = [] + for path in sorted(SOURCES.rglob("*")): + if path.is_file(): + problems.extend( + _source_capture_problems(path.read_bytes(), _relative(path)) + ) + assert not problems, "\n".join(problems) + + +@pytest.mark.parametrize("marker", BOT_MANAGER_MARKERS) +@pytest.mark.parametrize("uppercase", [False, True]) +def test_source_capture_bot_manager_markers(marker, uppercase): + raw = b"" + assert _source_capture_problems(raw, "capture.html") == [ + "capture.html contains a bot-manager marker" + ] + + +# RFC 5737 reserves this address block for documentation. +CAPTURE_EXAMPLE = b"00000000-0000-4000-8000-000000000001$203.0.113.42" + + +def test_source_capture_radware_token(): + encoded = base64.b64encode(CAPTURE_EXAMPLE) + raw = b'' + assert _source_capture_problems(raw, "capture.html") == [ + "capture.html contains a bot-manager marker", + "capture.html contains a base64 UUID-dollar-IPv4 token", + ] + + +@pytest.mark.parametrize("padded", [False, True], ids=["unpadded", "padded"]) +def test_source_capture_encoded_visitor_without_marker(padded): + encoded = base64.b64encode(CAPTURE_EXAMPLE) + if not padded: + encoded = encoded.rstrip(b"=") + assert _source_capture_problems(b'"' + encoded + b'"', "capture.txt") == [ + "capture.txt contains a base64 UUID-dollar-IPv4 token" + ] + + +@pytest.mark.parametrize( + "raw", + [ + b"", + b'', + b"IDAPA 16.03.04.100; COMAR 10.09.24.08", + b"window.monsido = {token: 'public-site-id'};", + b"data:image/svg+xml;base64," + + base64.b64encode(b''), + base64.b64encode(b"203.0.113.42"), + base64.b64encode(CAPTURE_EXAMPLE.replace(b"$", b":")), + base64.b64encode(CAPTURE_EXAMPLE.replace(b"4000", b"zzzz")), + base64.b64encode(CAPTURE_EXAMPLE.replace(b".42", b".256")), + base64.b64encode(b"prefix" + CAPTURE_EXAMPLE), + base64.b64encode(CAPTURE_EXAMPLE + b"suffix"), + base64.b64encode(b"\xff" * 45), + b"A" * 61, + ], + ids=[ + "empty", + "css-version", + "citations", + "monsido-token", + "svg-data-uri", + "encoded-address-alone", + "wrong-delimiter", + "invalid-uuid", + "invalid-octet", + "decoded-prefix", + "decoded-suffix", + "non-ascii", + "invalid-padding", + ], +) +def test_source_capture_benign_content(raw): + assert _source_capture_problems(raw, "capture.html") == [] + + +def test_source_capture_guard_reports_only_path_and_kind(tmp_path, monkeypatch): + monkeypatch.setitem(globals(), "REPO_ROOT", tmp_path) + monkeypatch.setitem(globals(), "SOURCES", tmp_path / "sources") + path = tmp_path / "sources" / "nested" / "capture.bin" + path.parent.mkdir(parents=True) + encoded = base64.b64encode(CAPTURE_EXAMPLE) + path.write_bytes(b'\xff__uzdbm="' + encoded + b'"') + with pytest.raises(AssertionError) as failure: + test_source_captures_are_public() + message = str(failure.value) + assert message == ( + "sources/nested/capture.bin contains a bot-manager marker\n" + "sources/nested/capture.bin contains a base64 UUID-dollar-IPv4 token" + ) + assert encoded.decode("ascii") not in message + assert CAPTURE_EXAMPLE.decode("ascii") not in message + assert CAPTURE_EXAMPLE.split(b"$")[1].decode("ascii") not in message + + @pytest.mark.parametrize( ("raw", "private"), [ diff --git a/policyengine_us/tests/core/test_source_capture_privacy_properties.py b/policyengine_us/tests/core/test_source_capture_privacy_properties.py new file mode 100644 index 00000000000..064aee08078 --- /dev/null +++ b/policyengine_us/tests/core/test_source_capture_privacy_properties.py @@ -0,0 +1,64 @@ +"""Check generated capture tokens without constructing a tax-benefit system.""" + +import base64 +import importlib.util +from pathlib import Path + +from hypothesis import given, settings, strategies as st + + +spec = importlib.util.spec_from_file_location( + "_source_capture_guard", + Path(__file__).resolve().parents[1] / "code_health" / "test_source_conflicts.py", +) +guard = importlib.util.module_from_spec(spec) +spec.loader.exec_module(guard) + +CAPTURE_NAME = "source_conflicts/sources/example/capture.html" +TOKEN_PROBLEM = f"{CAPTURE_NAME} contains a base64 UUID-dollar-IPv4 token" + + +@settings(max_examples=32, deadline=None, database=None, derandomize=True) +@given( + identifier=st.uuids(), + last_octet=st.integers(min_value=0, max_value=255), + padded=st.booleans(), + uppercase=st.booleans(), + html=st.booleans(), +) +def test_encoded_visitor_tokens_fail_without_disclosing_values( + identifier, last_octet, padded, uppercase, html +): + uuid_text = str(identifier) + if uppercase: + uuid_text = uuid_text.upper() + address = f"203.0.113.{last_octet}" + decoded = f"{uuid_text}${address}".encode("ascii") + token = base64.b64encode(decoded) + if not padded: + token = token.rstrip(b"=") + raw = ( + b'' + if html + else b'"' + token + b'"' + ) + + problems = guard._source_capture_problems(raw, CAPTURE_NAME) + + assert problems == [TOKEN_PROBLEM] + diagnostic = "\n".join(problems) + assert token.decode("ascii") not in diagnostic + assert decoded.decode("ascii") not in diagnostic + assert address not in diagnostic + + +@settings(max_examples=32, deadline=None, database=None, derandomize=True) +@given(last_octet=st.integers(min_value=0, max_value=255)) +def test_svg_data_and_stylesheet_versions_pass(last_octet): + address = f"203.0.113.{last_octet}".encode("ascii") + svg = b'' + address + b"" + image = b'' + stylesheet = b'' + + assert guard._source_capture_problems(image, CAPTURE_NAME) == [] + assert guard._source_capture_problems(stylesheet, CAPTURE_NAME) == [] diff --git a/source_conflicts/sources/README.md b/source_conflicts/sources/README.md index 624c4abf07d..d5ebc56d1b3 100644 --- a/source_conflicts/sources/README.md +++ b/source_conflicts/sources/README.md @@ -7,5 +7,9 @@ repository, a commit and the file's sha256; rulespec-us's `verify` checks that e excerpt appears verbatim in the capture. Each `.txt` file starts with the source URL and how the text was extracted. `.html` files are the official page as fetched. +When a site serves bot-check scripts, capture the page as pandoc text and include +a `Source:` URL line and an extraction line. This removes scripts that can expose +the fetching machine's address or visitor tokens. + Do not edit a capture after an entry pins it: add a new file instead, and move the entry's snapshot to it. From 924529fc206fbc0158b614eaab6956e23be60359 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 12 Nov 2026 00:53:49 -0500 Subject: [PATCH 2/9] Keep capture failures limited to safe diagnostics Co-Authored-By: Claude Opus 5.5 --- policyengine_us/tests/code_health/test_source_conflicts.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/policyengine_us/tests/code_health/test_source_conflicts.py b/policyengine_us/tests/code_health/test_source_conflicts.py index ed1778f0b2e..1dd9f509965 100644 --- a/policyengine_us/tests/code_health/test_source_conflicts.py +++ b/policyengine_us/tests/code_health/test_source_conflicts.py @@ -1026,7 +1026,8 @@ def test_source_captures_are_public(): problems.extend( _source_capture_problems(path.read_bytes(), _relative(path)) ) - assert not problems, "\n".join(problems) + if problems: + pytest.fail("\n".join(problems), pytrace=False) @pytest.mark.parametrize("marker", BOT_MANAGER_MARKERS) @@ -1106,7 +1107,7 @@ def test_source_capture_guard_reports_only_path_and_kind(tmp_path, monkeypatch): path.parent.mkdir(parents=True) encoded = base64.b64encode(CAPTURE_EXAMPLE) path.write_bytes(b'\xff__uzdbm="' + encoded + b'"') - with pytest.raises(AssertionError) as failure: + with pytest.raises(pytest.fail.Exception) as failure: test_source_captures_are_public() message = str(failure.value) assert message == ( From 1e466718576541e4f5ab4723fde0a67e73cb0c38 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:43:36 -0500 Subject: [PATCH 3/9] Pin source capture token length boundaries Co-Authored-By: Claude Opus 5.5 --- .../code_health/test_source_conflicts.py | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/policyengine_us/tests/code_health/test_source_conflicts.py b/policyengine_us/tests/code_health/test_source_conflicts.py index 1dd9f509965..d6c8fb6d28e 100644 --- a/policyengine_us/tests/code_health/test_source_conflicts.py +++ b/policyengine_us/tests/code_health/test_source_conflicts.py @@ -1052,11 +1052,28 @@ def test_source_capture_radware_token(): ] +@pytest.mark.parametrize( + ("address", "unpadded_length", "padded_length"), + [ + # IANA reserves the boundary addresses for special purposes: + # https://www.iana.org/assignments/iana-ipv4-special-registry/ + # 36 + 1 + 7 = 44 bytes; 4 * ceil(44 / 3) = 60, minus one "=" = 59. + pytest.param(b"0.0.0.0", 59, 60, id="shortest"), + # 36 + 1 + 12 = 49 bytes; 4 * ceil(49 / 3) = 68, minus two "=" = 66. + pytest.param(b"203.0.113.42", 66, 68, id="documentation"), + # 36 + 1 + 15 = 52 bytes; 4 * ceil(52 / 3) = 72, minus two "=" = 70. + pytest.param(b"255.255.255.255", 70, 72, id="longest"), + ], +) @pytest.mark.parametrize("padded", [False, True], ids=["unpadded", "padded"]) -def test_source_capture_encoded_visitor_without_marker(padded): - encoded = base64.b64encode(CAPTURE_EXAMPLE) +def test_source_capture_encoded_visitor_without_marker( + address, unpadded_length, padded_length, padded +): + decoded = CAPTURE_EXAMPLE.rsplit(b"$", 1)[0] + b"$" + address + encoded = base64.b64encode(decoded) if not padded: encoded = encoded.rstrip(b"=") + assert len(encoded) == (padded_length if padded else unpadded_length) assert _source_capture_problems(b'"' + encoded + b'"', "capture.txt") == [ "capture.txt contains a base64 UUID-dollar-IPv4 token" ] From b0d3d8f34bc6b0427030add79d02c6abb20a21ef Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:56:12 -0500 Subject: [PATCH 4/9] Cover Cloudflare challenge options and clarify capture scope Co-Authored-By: Claude Opus 5.5 --- ....fixed.md => guard-source-capture-tokens.added.md} | 0 .../tests/code_health/test_source_conflicts.py | 11 +++++++++++ source_conflicts/sources/README.md | 5 +++++ 3 files changed, 16 insertions(+) rename changelog.d/{guard-source-capture-tokens.fixed.md => guard-source-capture-tokens.added.md} (100%) diff --git a/changelog.d/guard-source-capture-tokens.fixed.md b/changelog.d/guard-source-capture-tokens.added.md similarity index 100% rename from changelog.d/guard-source-capture-tokens.fixed.md rename to changelog.d/guard-source-capture-tokens.added.md diff --git a/policyengine_us/tests/code_health/test_source_conflicts.py b/policyengine_us/tests/code_health/test_source_conflicts.py index d6c8fb6d28e..5398218a989 100644 --- a/policyengine_us/tests/code_health/test_source_conflicts.py +++ b/policyengine_us/tests/code_health/test_source_conflicts.py @@ -976,6 +976,7 @@ def test_candidates_are_public(): b"shieldsquare", b"stormcaster", b"__cf_chl", + b"_cf_chl_opt", b"cf_clearance", b"incap_ses", b"visid_incap", @@ -1039,6 +1040,16 @@ def test_source_capture_bot_manager_markers(marker, uppercase): ] +@pytest.mark.parametrize("uppercase", [False, True]) +def test_source_capture_cloudflare_challenge_options(uppercase): + raw = b"window._cf_chl_opt = {};" + if uppercase: + raw = raw.upper() + assert _source_capture_problems(raw, "capture.html") == [ + "capture.html contains a bot-manager marker" + ] + + # RFC 5737 reserves this address block for documentation. CAPTURE_EXAMPLE = b"00000000-0000-4000-8000-000000000001$203.0.113.42" diff --git a/source_conflicts/sources/README.md b/source_conflicts/sources/README.md index d5ebc56d1b3..e0c58e187c7 100644 --- a/source_conflicts/sources/README.md +++ b/source_conflicts/sources/README.md @@ -11,5 +11,10 @@ When a site serves bot-check scripts, capture the page as pandoc text and includ a `Source:` URL line and an extraction line. This removes scripts that can expose the fetching machine's address or visitor tokens. +The privacy check rejects bot-manager markers and base64 tokens whose entire +decoded value matches `UUID$IPv4`. The decoded-token check covers IPv4 only; +it does not detect IPv6 addresses or payloads with extra decoded bytes. Inspect +extracted text for visitor data before committing it. + Do not edit a capture after an entry pins it: add a new file instead, and move the entry's snapshot to it. From 1d9358f9339dac480d3726e5a2fe949244a1c4f6 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 22:46:47 -0500 Subject: [PATCH 5/9] Treat "+" and "/" as capture token boundaries Hex digits, "-", "$" and "." encode only to base64 letters and digits, so a UUID-dollar-IPv4 token never contains "+" or "/". The capture guard counted both as token characters and missed a token beside them: in a URL path, after a JSON-escaped slash, or after a plus sign. The token class now holds letters and digits only. The encoded-token test wraps each boundary token in ten page contexts, and two near misses, each one character short of a token, pass in every context. The privacy property samples the same contexts. Co-Authored-By: Claude Opus 5.5 --- .../code_health/test_source_conflicts.py | 57 ++++++++++++++++--- .../test_source_capture_privacy_properties.py | 10 +--- 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/policyengine_us/tests/code_health/test_source_conflicts.py b/policyengine_us/tests/code_health/test_source_conflicts.py index 5398218a989..c82beebe0ba 100644 --- a/policyengine_us/tests/code_health/test_source_conflicts.py +++ b/policyengine_us/tests/code_health/test_source_conflicts.py @@ -984,9 +984,11 @@ def test_candidates_are_public(): b"px-captcha", ) # A UUID, dollar and IPv4 occupy 44 to 52 bytes, or 59 to 70 base64 -# characters before padding. Match whole tokens so longer data URIs stay out. +# characters before padding. Hex digits, "-", "$" and "." encode only to +# letters and digits, so "+" and "/" end a token like any other byte. Match +# whole tokens so longer data URIs stay out. CAPTURE_BASE64_RE = re.compile( - rb"(?const value = "' + token + b'";', + "url-path": lambda token: b"/a/" + token + b"/b", + "url-path-end": lambda token: b"/a/" + token, + "after-plus": lambda token: b"+" + token, + "before-plus": lambda token: token + b"+", + "escaped-slash": lambda token: b'"\\/' + token + b'"', + "json-escaped-url": lambda token: ( + b'"https:\\/\\/example.gov\\/a\\/' + token + b'\\/b"' + ), + "line-start": lambda token: b"first line\n" + token + b" rest\nlast line", + "line-end": lambda token: b"first line\nstart " + token + b"\nlast line", +} + + +def _capture_token(address: bytes, padded: bool) -> bytes: + encoded = base64.b64encode(CAPTURE_EXAMPLE.rsplit(b"$", 1)[0] + b"$" + address) + return encoded if padded else encoded.rstrip(b"=") def test_source_capture_radware_token(): @@ -1077,19 +1100,37 @@ def test_source_capture_radware_token(): ], ) @pytest.mark.parametrize("padded", [False, True], ids=["unpadded", "padded"]) +@pytest.mark.parametrize("context", CAPTURE_CONTEXTS) def test_source_capture_encoded_visitor_without_marker( - address, unpadded_length, padded_length, padded + address, unpadded_length, padded_length, padded, context ): - decoded = CAPTURE_EXAMPLE.rsplit(b"$", 1)[0] + b"$" + address - encoded = base64.b64encode(decoded) - if not padded: - encoded = encoded.rstrip(b"=") + encoded = _capture_token(address, padded) assert len(encoded) == (padded_length if padded else unpadded_length) - assert _source_capture_problems(b'"' + encoded + b'"', "capture.txt") == [ + raw = CAPTURE_CONTEXTS[context](encoded) + assert _source_capture_problems(raw, "capture.txt") == [ "capture.txt contains a base64 UUID-dollar-IPv4 token" ] +@pytest.mark.parametrize( + ("address", "start", "stop", "length"), + [ + # The shortest token loses its last character: 59 - 1 = 58, below + # the window. + pytest.param(b"0.0.0.0", 0, -1, 58, id="shortest-minus-last"), + # The longest token loses its first character: 70 - 1 = 69, and + # 69 mod 4 = 1 leaves no valid base64 length. + pytest.param(b"255.255.255.255", 1, None, 69, id="longest-minus-first"), + ], +) +@pytest.mark.parametrize("context", CAPTURE_CONTEXTS) +def test_source_capture_near_miss_passes(address, start, stop, length, context): + near_miss = _capture_token(address, padded=False)[start:stop] + assert len(near_miss) == length + raw = CAPTURE_CONTEXTS[context](near_miss) + assert _source_capture_problems(raw, "capture.txt") == [] + + @pytest.mark.parametrize( "raw", [ diff --git a/policyengine_us/tests/core/test_source_capture_privacy_properties.py b/policyengine_us/tests/core/test_source_capture_privacy_properties.py index 064aee08078..01f31cabd8c 100644 --- a/policyengine_us/tests/core/test_source_capture_privacy_properties.py +++ b/policyengine_us/tests/core/test_source_capture_privacy_properties.py @@ -24,10 +24,10 @@ last_octet=st.integers(min_value=0, max_value=255), padded=st.booleans(), uppercase=st.booleans(), - html=st.booleans(), + context=st.sampled_from(list(guard.CAPTURE_CONTEXTS)), ) def test_encoded_visitor_tokens_fail_without_disclosing_values( - identifier, last_octet, padded, uppercase, html + identifier, last_octet, padded, uppercase, context ): uuid_text = str(identifier) if uppercase: @@ -37,11 +37,7 @@ def test_encoded_visitor_tokens_fail_without_disclosing_values( token = base64.b64encode(decoded) if not padded: token = token.rstrip(b"=") - raw = ( - b'' - if html - else b'"' + token + b'"' - ) + raw = guard.CAPTURE_CONTEXTS[context](token) problems = guard._source_capture_problems(raw, CAPTURE_NAME) From d97ee269ad753381c2a109f1d21a9b7f71d3d32e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 22:47:59 -0500 Subject: [PATCH 6/9] Find capture tokens inside percent-encoded URLs A percent-encoded URL puts "%2F" or "%3D" beside a token. The escape's hex digits join the token's letters and digits, so the guard missed the token. The guard now also scans each capture after one round of percent-decoding and reports a token found in either form once. The encoded-token and near-miss tests gain a percent-encoded URL path and query. Co-Authored-By: Claude Opus 5.5 --- .../code_health/test_source_conflicts.py | 40 ++++++++++++++----- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/policyengine_us/tests/code_health/test_source_conflicts.py b/policyengine_us/tests/code_health/test_source_conflicts.py index c82beebe0ba..d241baf2c3d 100644 --- a/policyengine_us/tests/code_health/test_source_conflicts.py +++ b/policyengine_us/tests/code_health/test_source_conflicts.py @@ -44,7 +44,8 @@ included) and every parsed value and key (escapes, binary, sets) carry no decision-queue ids, session ids, local paths or email addresses. 6. No file under ``source_conflicts/sources/`` contains a bot-manager marker - or a base64 token that decodes to UUID + "$" + IPv4. + or a base64 token that decodes to UUID + "$" + IPv4, in its raw bytes or + after one round of percent-decoding. These are structural checks: they tie markers, the register and the backlog together; they do not judge whether code follows a statute. rulespec-us's own @@ -66,6 +67,7 @@ from collections import Counter from ipaddress import IPv4Address from pathlib import Path +from urllib.parse import quote, unquote_to_bytes import pytest import yaml @@ -997,14 +999,8 @@ def test_candidates_are_public(): ) -def _source_capture_problems(raw: bytes, name: str) -> list[str]: - """Report match kinds without exposing captured tokens or addresses.""" - - problems = [] - lowered = raw.lower() - if any(marker in lowered for marker in BOT_MANAGER_MARKERS): - problems.append(f"{name} contains a bot-manager marker") - for match in CAPTURE_BASE64_RE.finditer(raw): +def _contains_visitor_token(text: bytes) -> bool: + for match in CAPTURE_BASE64_RE.finditer(text): token = match.group() try: decoded = base64.b64decode(token + b"=" * (-len(token) % 4), validate=True) @@ -1017,8 +1013,22 @@ def _source_capture_problems(raw: bytes, name: str) -> list[str]: IPv4Address(visitor[1].decode("ascii")) except ValueError: continue + return True + return False + + +def _source_capture_problems(raw: bytes, name: str) -> list[str]: + """Report match kinds without exposing captured tokens or addresses.""" + + problems = [] + lowered = raw.lower() + if any(marker in lowered for marker in BOT_MANAGER_MARKERS): + problems.append(f"{name} contains a bot-manager marker") + # Decode percent escapes once, so an escaped "/" or "=" beside a token + # ends it as the plain character would. + texts = (raw, unquote_to_bytes(raw)) if b"%" in raw else (raw,) + if any(_contains_visitor_token(text) for text in texts): problems.append(f"{name} contains a base64 UUID-dollar-IPv4 token") - break return problems @@ -1055,7 +1065,7 @@ def test_source_capture_cloudflare_challenge_options(uppercase): # RFC 5737 reserves this address block for documentation. CAPTURE_EXAMPLE = b"00000000-0000-4000-8000-000000000001$203.0.113.42" # Page text that can surround a token, from quotes and scripts to URL paths, -# JSON-escaped URLs and either end of a line. +# JSON-escaped and percent-encoded URLs and either end of a line. CAPTURE_CONTEXTS = { "quoted": lambda token: b'"' + token + b'"', "script": lambda token: b'', @@ -1067,6 +1077,14 @@ def test_source_capture_cloudflare_challenge_options(uppercase): "json-escaped-url": lambda token: ( b'"https:\\/\\/example.gov\\/a\\/' + token + b'\\/b"' ), + # quote() escapes "/", ":", "?", "=" and "&", so "%2F" or "%3D" sits + # beside the token and any padding becomes "%3D". + "percent-encoded-url": lambda token: quote( + b"https://example.gov/a/" + token + b"/b", safe="" + ).encode("ascii"), + "percent-encoded-query": lambda token: quote( + b"https://example.gov/p?t=" + token + b"&x=1", safe="" + ).encode("ascii"), "line-start": lambda token: b"first line\n" + token + b" rest\nlast line", "line-end": lambda token: b"first line\nstart " + token + b"\nlast line", } From 15bc471b2bb07a83ad9b2a0b265554d7917a96a4 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 22:49:47 -0500 Subject: [PATCH 7/9] Document capture token boundaries State in the capture README which runs the guard decodes, where it finds tokens, and what it misses: IPv6, payloads with extra decoded bytes, and tokens joined to other letters or digits. Add a raw query string to the encoded-token contexts, since the README names it. Join a hard-wrapped CONTRIBUTING paragraph into one line to match its neighbours. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 6 ++---- .../tests/code_health/test_source_conflicts.py | 6 ++++-- source_conflicts/sources/README.md | 11 ++++++++--- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ae588cdc634..c7c45de5b02 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -123,9 +123,7 @@ For code already on `main` that the PR doesn't change, you can skip step 1: pin The marker comes only in the follow-up PR, because the guard rejects a marker whose entry isn't in the pinned copy, or whose entry doesn't list the marker's file under `implementations`. A `proposed` row doesn't count. -When a source site serves bot-check scripts, capture it as pandoc text with a -`Source:` URL line and an extraction line, as [the capture guide](source_conflicts/sources/README.md) -describes, to avoid publishing visitor tokens or the fetching machine's address. +When a source site serves bot-check scripts, capture it as pandoc text with a `Source:` URL line and an extraction line, as [the capture guide](source_conflicts/sources/README.md) describes, to avoid publishing visitor tokens or the fetching machine's address. `policyengine_us/tests/code_health/test_source_conflicts.py` checks structure, not whether the code follows a statute. It fails when: @@ -135,7 +133,7 @@ describes, to avoid publishing visitor tokens or the fetching machine's address. - an implementation the register marks `cites_entry: true` is missing here or has lost its marker; - the count of comments that read like a conflict between sources ("the instructions say", "in practice", "discrepancy", "Source conflict:", ...) changes in a file without a marker. A new file or a higher count means reword a comment that describes no conflict. If it describes a real conflict, keep it, record the conflict as a candidate (step 1) and add or raise the file's `KNOWN_UNMARKED` line in the same PR; the marker in step 3 then exempts the file, and its line comes out. A lower count means lower `KNOWN_UNMARKED`. A file with any valid marker is exempt, so the count doesn't prove every conflict in it is marked; - a backlog item (`source_conflicts/candidates.yaml`) is malformed, already registered, cites a code path that isn't a file git tracks here (absolute, with `..`, or under a hidden directory such as `.github`), or contains a decision-queue id, a session id, a local path or an email address anywhere in the file: in its raw text, comments and keys included, and in every parsed value and key (escapes, `!!binary`, sets). Homoglyphs, such as a Cyrillic letter in "Source", are not caught; review catches those; -- any file under `source_conflicts/sources/` contains a bot-manager marker or a base64 token that decodes to a UUID, a dollar sign and an IPv4 address. Failures name the file and match kind without printing token values or addresses. +- any file under `source_conflicts/sources/` contains a bot-manager marker or a base64 token that decodes to a UUID, a dollar sign and an IPv4 address, in its raw bytes or after one round of percent-decoding. Failures name the file and match kind without printing token values or addresses. A model that departs from the statute with no official source behind it is a bug, not a source conflict. Fix it, or open an issue. diff --git a/policyengine_us/tests/code_health/test_source_conflicts.py b/policyengine_us/tests/code_health/test_source_conflicts.py index d241baf2c3d..57b322c5d06 100644 --- a/policyengine_us/tests/code_health/test_source_conflicts.py +++ b/policyengine_us/tests/code_health/test_source_conflicts.py @@ -1064,13 +1064,15 @@ def test_source_capture_cloudflare_challenge_options(uppercase): # RFC 5737 reserves this address block for documentation. CAPTURE_EXAMPLE = b"00000000-0000-4000-8000-000000000001$203.0.113.42" -# Page text that can surround a token, from quotes and scripts to URL paths, -# JSON-escaped and percent-encoded URLs and either end of a line. +# Page text that can surround a token, from quotes and scripts to query +# strings, URL paths, JSON-escaped and percent-encoded URLs and either end of +# a line. CAPTURE_CONTEXTS = { "quoted": lambda token: b'"' + token + b'"', "script": lambda token: b'', "url-path": lambda token: b"/a/" + token + b"/b", "url-path-end": lambda token: b"/a/" + token, + "query-string": lambda token: b"/p?t=" + token + b"&x=1", "after-plus": lambda token: b"+" + token, "before-plus": lambda token: token + b"+", "escaped-slash": lambda token: b'"\\/' + token + b'"', diff --git a/source_conflicts/sources/README.md b/source_conflicts/sources/README.md index e0c58e187c7..88121f7da52 100644 --- a/source_conflicts/sources/README.md +++ b/source_conflicts/sources/README.md @@ -12,9 +12,14 @@ a `Source:` URL line and an extraction line. This removes scripts that can expos the fetching machine's address or visitor tokens. The privacy check rejects bot-manager markers and base64 tokens whose entire -decoded value matches `UUID$IPv4`. The decoded-token check covers IPv4 only; -it does not detect IPv6 addresses or payloads with extra decoded bytes. Inspect -extracted text for visitor data before committing it. +decoded value matches `UUID$IPv4`. It decodes each run of 59 to 70 letters and +digits, with up to two `=` of padding, that has no letter or digit on either side +and no further `=` after it. It scans the raw bytes and the bytes after one round +of percent-decoding, so it finds tokens in quotes, query strings, URL paths, +JSON-escaped and percent-encoded URLs, and at either end of a line. It misses +IPv6 addresses, payloads with extra decoded bytes, and tokens joined to other +letters or digits, as after a `/` escape or in a URL percent-encoded twice. +Inspect extracted text for visitor data before committing it. Do not edit a capture after an entry pins it: add a new file instead, and move the entry's snapshot to it. From de294a03413c0ff3aaf24b34a01185f27f850f65 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 22:54:40 -0500 Subject: [PATCH 8/9] Fix the escape example in the capture README The README's example of a token joined to letters or digits named a bare slash, which the guard treats as a boundary. It now names the JSON Unicode escape for a slash, whose last hex digit joins the token. Co-Authored-By: Claude Opus 5.5 --- source_conflicts/sources/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source_conflicts/sources/README.md b/source_conflicts/sources/README.md index 88121f7da52..4bdf66e9052 100644 --- a/source_conflicts/sources/README.md +++ b/source_conflicts/sources/README.md @@ -18,7 +18,7 @@ and no further `=` after it. It scans the raw bytes and the bytes after one roun of percent-decoding, so it finds tokens in quotes, query strings, URL paths, JSON-escaped and percent-encoded URLs, and at either end of a line. It misses IPv6 addresses, payloads with extra decoded bytes, and tokens joined to other -letters or digits, as after a `/` escape or in a URL percent-encoded twice. +letters or digits, as after a `\u002F` escape or in a URL percent-encoded twice. Inspect extracted text for visitor data before committing it. Do not edit a capture after an entry pins it: add a new file instead, and move the From 8043062a4fb34fe4127b18d96a7db2e8019a64ab Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 23:17:52 -0500 Subject: [PATCH 9/9] Scope percent-decoding to tokens in the capture guard docs The guard matches bot-manager markers in a capture's raw bytes only, and base64 visitor tokens in the raw bytes and after one round of percent-decoding. Move the percent-decoding clause in CONTRIBUTING.md and the guard's docstring so it covers tokens alone. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 2 +- policyengine_us/tests/code_health/test_source_conflicts.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c7c45de5b02..1ff91d5095a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -133,7 +133,7 @@ When a source site serves bot-check scripts, capture it as pandoc text with a `S - an implementation the register marks `cites_entry: true` is missing here or has lost its marker; - the count of comments that read like a conflict between sources ("the instructions say", "in practice", "discrepancy", "Source conflict:", ...) changes in a file without a marker. A new file or a higher count means reword a comment that describes no conflict. If it describes a real conflict, keep it, record the conflict as a candidate (step 1) and add or raise the file's `KNOWN_UNMARKED` line in the same PR; the marker in step 3 then exempts the file, and its line comes out. A lower count means lower `KNOWN_UNMARKED`. A file with any valid marker is exempt, so the count doesn't prove every conflict in it is marked; - a backlog item (`source_conflicts/candidates.yaml`) is malformed, already registered, cites a code path that isn't a file git tracks here (absolute, with `..`, or under a hidden directory such as `.github`), or contains a decision-queue id, a session id, a local path or an email address anywhere in the file: in its raw text, comments and keys included, and in every parsed value and key (escapes, `!!binary`, sets). Homoglyphs, such as a Cyrillic letter in "Source", are not caught; review catches those; -- any file under `source_conflicts/sources/` contains a bot-manager marker or a base64 token that decodes to a UUID, a dollar sign and an IPv4 address, in its raw bytes or after one round of percent-decoding. Failures name the file and match kind without printing token values or addresses. +- any file under `source_conflicts/sources/` contains a bot-manager marker in its raw bytes, or a base64 token that decodes to a UUID, a dollar sign and an IPv4 address in its raw bytes or after one round of percent-decoding. Failures name the file and match kind without printing token values or addresses. A model that departs from the statute with no official source behind it is a bug, not a source conflict. Fix it, or open an issue. diff --git a/policyengine_us/tests/code_health/test_source_conflicts.py b/policyengine_us/tests/code_health/test_source_conflicts.py index 23036eeab52..da3c1dfbef5 100644 --- a/policyengine_us/tests/code_health/test_source_conflicts.py +++ b/policyengine_us/tests/code_health/test_source_conflicts.py @@ -44,8 +44,8 @@ included) and every parsed value and key (escapes, binary, sets) carry no decision-queue ids, session ids, local paths or email addresses. 6. No file under ``source_conflicts/sources/`` contains a bot-manager marker - or a base64 token that decodes to UUID + "$" + IPv4, in its raw bytes or - after one round of percent-decoding. + in its raw bytes, or a base64 token that decodes to UUID + "$" + IPv4 in + its raw bytes or after one round of percent-decoding. These are structural checks: they tie markers, the register and the backlog together; they do not judge whether code follows a statute. rulespec-us's own