From a7c013a69560de336bcc6ce0af875c914602b36a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 29 Sep 2026 18:34:37 -0400 Subject: [PATCH 1/7] Put every file that decides a gate verdict on the gate surface Since the receipt shim refactor (4a23e31, #116), the trust pins live in scripts/receipt_pins.py, but the gate surface still listed only the files that held them before. receipt's append gate calls a proposal gate-changing only when it touches gate_surface, so a resolver-shaped append that also edited the pins, or bumped receipt in pyproject.toml and uv.lock, was judged as plain data: accepted, and never named. Reproduced with the base gate invoked as the trusted CI job invokes it: 3dd95a0's gate accepted the release-20 append plus a receipt_pins.py edit as "+5 appended vs base, release 20", and #299's gate accepted #297's seven rows plus a pins edit as "+7 appended vs base, release 21". The surface now covers: - scripts/**: the judge runs a script there, so scripts/ is sys.path[0], and both pull request jobs also put it on PYTHONPATH. A new module there shadows imports (the standard library's included), and a sitecustomize.py runs at startup. Both were observed. - pyproject.toml and uv.lock, which pick the receipt version the judge runs, and uv.toml, .python-version and .venv/**, which uv also reads from the project it provisions the judge from. Each was observed to change what `uv sync --locked --no-dev --project ` and `uv run` do. The same candidates are now refused as mixed, naming the decider, while both pure appends still pass and a pins-only change is reported as gate-only. The resolver's proposals change only ledger/** and releases/manifests/**, so they stay data proposals. Tests: every decider is refused as mixed beside a witnessed append and named when changed alone; a pure append beside unchanged deciders passes; an audit-hook run shows every file the gate opens or imports from its own checkout is on the surface; and the shim's surface is pinned as a deliberate superset of the originals'. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- scripts/receipt_pins.py | 22 +- tests/test_receipt_shim_transparency.py | 48 +++++ tests/test_thesis_append_shim_isolation.py | 237 +++++++++++++++++++++ 4 files changed, 309 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d65fb107..a428d531 100644 --- a/README.md +++ b/README.md @@ -571,4 +571,9 @@ environment. Verification machinery is consumed from the `receipt` package with this repository's trust pins committed in `scripts/receipt_pins.py`; see `releases/README.md` (immutable post-genesis, like everything under `releases/`) for the schema, offline -verification procedure, and security limits. +verification procedure, and security limits. The gate surface in that file +lists every base-checkout file that can decide a verdict: all of `scripts/`, +the append workflow, the anchors, and the uv inputs that build the gate's +environment (`pyproject.toml`, `uv.lock`, `uv.toml`, `.python-version`, +`.venv/`). The gate refuses a pull request that changes any of them together +with the ledger, and names them when a pull request changes only them. diff --git a/scripts/receipt_pins.py b/scripts/receipt_pins.py index 2136c758..ed1328ee 100644 --- a/scripts/receipt_pins.py +++ b/scripts/receipt_pins.py @@ -86,13 +86,27 @@ (f"releases/anchors/{LEDGER_SPEC.producer_public_key_filename}"), } ), + # Every file in the judging (base) checkout that can decide a verdict. A + # proposal that changes one of them together with the ledger is refused as + # mixed, and a proposal that changes only these is reported by name. gate_surface=frozenset( { - "scripts/check_thesis_facts_append.py", - "scripts/verify_release_chain.py", - "scripts/canonical_json.py", - "scripts/cut_release_manifest.py", + # The judge runs scripts/check_thesis_facts_append.py, so scripts/ + # is sys.path[0], and both pull request jobs also put it on + # PYTHONPATH. Any file there can decide the verdict: these pins, + # a module that shadows an import (the standard library's + # included), or a sitecustomize.py, which runs at startup. + "scripts/**", ".github/workflows/thesis-facts-append.yml", + # `uv sync --locked --no-dev --project ` builds the judge's + # environment from these, including the receipt version that + # implements the gate. uv also reads the project's uv.toml and + # .python-version, and reuses a .venv it finds there. + "pyproject.toml", + "uv.lock", + "uv.toml", + ".python-version", + ".venv/**", "releases/anchors/**", } ), diff --git a/tests/test_receipt_shim_transparency.py b/tests/test_receipt_shim_transparency.py index 99fccc19..095e5f19 100644 --- a/tests/test_receipt_shim_transparency.py +++ b/tests/test_receipt_shim_transparency.py @@ -113,6 +113,54 @@ def test_original_oracle_fixtures_are_authenticated(name: str) -> None: assert _sha256(ORIGINAL_FIXTURES / name) == ORIGINAL_HASHES[name] +def _original_surface(name: str) -> frozenset[str]: + """Read one surface literal from the authenticated original gate.""" + + import ast + + module = ast.parse( + (ORIGINAL_FIXTURES / "check_thesis_facts_append.py").read_text(encoding="utf-8") + ) + for node in module.body: + if ( + isinstance(node, ast.Assign) + and [getattr(target, "id", None) for target in node.targets] == [name] + and isinstance(node.value, ast.Call) + ): + return frozenset(ast.literal_eval(node.value.args[0])) + raise AssertionError(f"{name} not found in the original gate") + + +def test_the_shim_gate_surface_deliberately_widens_the_originals() -> None: + """The one place the pair is meant to disagree about classification. + + The originals' GATE_SURFACE predates scripts/receipt_pins.py, where the + shim's trust pins now live, and never listed the uv inputs that provision + the judge. The shim's surface covers every original entry and adds those, + so a proposal that changes one of them is refused as mixed (with rows) or + named as gate-only (alone), where the original judged it as plain data. + No case in this file changes such a file, so the byte-identity asserted + here is unaffected; tests/test_thesis_append_shim_isolation.py holds the + shim to the wider surface. + """ + + from receipt.append_gate import _matches_surface + + from scripts.receipt_pins import APPEND_GATE_SPEC + + original_gate = _original_surface("GATE_SURFACE") + shim_gate = APPEND_GATE_SPEC.gate_surface + for entry in original_gate: + if entry.endswith("/**"): + assert entry in shim_gate, entry + else: + assert _matches_surface(entry, shim_gate), entry + assert _original_surface("DATA_SURFACE") == APPEND_GATE_SPEC.data_surface + for widened in ("scripts/receipt_pins.py", "pyproject.toml", "uv.lock"): + assert not _matches_surface(widened, original_gate), widened + assert _matches_surface(widened, shim_gate), widened + + @pytest.fixture(scope="session") def original_oracle(tmp_path_factory: pytest.TempPathFactory) -> pathlib.Path: """Copy the authenticated original scripts into one executable tree.""" diff --git a/tests/test_thesis_append_shim_isolation.py b/tests/test_thesis_append_shim_isolation.py index 61e6d4c8..063d0223 100644 --- a/tests/test_thesis_append_shim_isolation.py +++ b/tests/test_thesis_append_shim_isolation.py @@ -57,6 +57,7 @@ def _subject_line(clone: pathlib.Path, candidate: str, base: str | None) -> str: line += f" base commit {base} tree {_git(clone, 'rev-parse', base + '^{tree}')}" return line + # A commit id of the right shape that no repository holds. ABSENT_OBJECT_ID = "0" * 40 @@ -942,6 +943,242 @@ def test_a_true_append_is_accepted_end_to_end(tmp_path): _assert_nothing_left_behind(clone, tmp_path / "tmp") +# Files that decide a verdict when they sit in the judging checkout, one per +# way in: the pins the shim imports, the uv inputs the workflow provisions the +# judge from, and files that are not there today but would be read if added. +# Until 2026-09-29 the first three were off the gate surface, so a resolver- +# shaped append that also edited them was judged as plain data and never named +# them (PolicyEngine/chronicle#299 review). +GATE_DECIDERS = ( + "scripts/receipt_pins.py", + "pyproject.toml", + "uv.lock", + "uv.toml", + ".python-version", + "scripts/sitecustomize.py", + ".venv/lib/python3.14/site-packages/zz_injected.pth", +) + + +def _change_gate_decider(relative: str): + """Return a mutation that changes one decider, or adds it if absent.""" + + def mutate(root: pathlib.Path) -> None: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write("# a change riding the proposal\n") + + return mutate + + +def _copy_existing_gate_deciders(root: pathlib.Path) -> None: + """Put the repository's own copy of every decider it has into the base.""" + + for relative in GATE_DECIDERS: + source = ROOT / relative + if source.is_file(): + destination = root / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + + +@pytest.mark.parametrize("relative", GATE_DECIDERS) +def test_an_append_that_also_changes_a_gate_decider_is_refused_as_mixed( + tmp_path, relative +): + """The witnessed append plus one decider change cannot pass as data. + + The refusal comes before any ledger check and names the decider, so a trust + change can no longer ride an append that the resolver merges on its own. + """ + + clone, base, candidate = _replay_latest_release( + tmp_path, + prepare=_copy_existing_gate_deciders, + mutate=_change_gate_decider(relative), + ) + + completed = _run_shim( + clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp" + ) + + assert completed.returncode == 1, completed.stdout + completed.stderr + assert completed.stdout == "" + assert f"{FAILED}mixed data/gate proposal is forbidden: " in completed.stderr + assert ( + f"; GATE_SURFACE changes={[relative]!r}; split them into separate pull requests" + ) in completed.stderr + _assert_nothing_left_behind(clone, tmp_path / "tmp") + + +@pytest.mark.parametrize("relative", GATE_DECIDERS) +def test_a_gate_decider_change_alone_is_a_named_gate_only_proposal(tmp_path, relative): + clone, base = _replay_current_state(tmp_path) + _copy_existing_gate_deciders(clone) + base = _commit(clone, "deciders in the base") + _change_gate_decider(relative)(clone) + candidate = _commit(clone, f"change {relative}") + + completed = _run_shim( + clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp" + ) + + assert completed.returncode == 0, completed.stdout + completed.stderr + assert completed.stdout.splitlines() == [ + "thesis-facts append check OK: gate-only proposal; DATA_SURFACE " + f"unchanged; GATE_SURFACE changes={[relative]!r}", + _subject_line(clone, candidate, base), + ] + _assert_nothing_left_behind(clone, tmp_path / "tmp") + + +def test_an_append_beside_unchanged_gate_deciders_still_passes(tmp_path): + """The resolver's shape: ledger and release files only, deciders untouched.""" + + clone, base, candidate = _replay_latest_release( + tmp_path, prepare=_copy_existing_gate_deciders + ) + changed = set(_git(clone, "diff", "--name-only", base, candidate).splitlines()) + assert changed and all( + path.startswith(("ledger/", "releases/manifests/")) for path in changed + ), changed + + completed = _run_shim( + clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp" + ) + + assert completed.returncode == 0, completed.stdout + completed.stderr + assert completed.stdout == ( + f"{APPEND_GATE_OK}\n{_subject_line(clone, candidate, base)}\n" + ) + _assert_nothing_left_behind(clone, tmp_path / "tmp") + + +OPENED_FILES_DRIVER = """\ +import json +import os +import pathlib +import sys + +opened = set() + + +def _record(event, arguments): + if event == "open" and isinstance(arguments[0], (str, bytes, os.PathLike)): + opened.add(os.fsdecode(arguments[0])) + + +sys.addaudithook(_record) +sys.path.insert(0, {scripts!r}) + +import check_thesis_facts_append as shim # noqa: E402 + +try: + code = shim.main() +finally: + opened.update( + getattr(module, "__file__", None) or "" for module in list(sys.modules.values()) + ) + pathlib.Path({report!r}).write_text(json.dumps(sorted(opened)), encoding="utf-8") +raise SystemExit(code) +""" + + +def test_every_file_the_gate_reads_from_its_own_checkout_is_on_the_gate_surface( + tmp_path, +): + """The invariant behind GATE_SURFACE, measured on an accepting run. + + Every file the gate process opens or imports from inside the judging + checkout is on the surface. That is the pins, the gate's scripts, the + trust anchors, and the installed receipt wheel, which lives in the + checkout's own .venv just as it does in the workflow's base-gate clone. + """ + + from receipt.append_gate import _matches_surface + + from scripts.receipt_pins import APPEND_GATE_SPEC + + clone, base, candidate = _replay_latest_release(tmp_path) + report = tmp_path / "opened.json" + driver = tmp_path / "driver" / "driver.py" + driver.parent.mkdir() + driver.write_text( + OPENED_FILES_DRIVER.format(scripts=str(SHIM_SCRIPTS), report=str(report)), + encoding="utf-8", + ) + + completed = subprocess.run( + [ + sys.executable, + str(driver), + "--root", + str(clone), + "--commit", + candidate, + "--base-ref", + base, + ], + cwd=clone, + capture_output=True, + text=True, + check=False, + ) + assert completed.returncode == 0, completed.stdout + completed.stderr + + root = ROOT.resolve() + inside = set() + for name in json.loads(report.read_text(encoding="utf-8")): + if not name: + continue + path = pathlib.Path(name) + if not path.is_absolute(): + path = clone / path + resolved = path.resolve() + if resolved.is_relative_to(root): + inside.add(resolved.relative_to(root).as_posix()) + assert "scripts/receipt_pins.py" in inside + assert any(path.startswith("releases/anchors/") for path in inside), inside + off_surface = sorted( + path + for path in inside + if not _matches_surface(path, APPEND_GATE_SPEC.gate_surface) + ) + assert off_surface == [], off_surface + + +def test_the_gate_surface_covers_the_judges_import_path_and_environment(): + """What a run cannot show: files that would decide a verdict if added. + + The judge runs a script in scripts/, so scripts/ is sys.path[0], and both + pull request jobs also put it on PYTHONPATH, where a sitecustomize.py runs + at startup. The whole directory is therefore on the surface, not just the + files imported today. The judge's environment comes from the base's own + uv project, so its inputs are on the surface too. + """ + + from scripts.receipt_pins import APPEND_GATE_SPEC + + workflow = (ROOT / ".github" / "workflows" / "thesis-facts-append.yml").read_text( + encoding="utf-8" + ) + assert 'PYTHONPATH="$base_gate/scripts"' in workflow + assert 'uv sync --locked --no-dev --project "$base_gate"' in workflow + assert SHIM.parent.relative_to(ROOT).as_posix() == "scripts" + for required in ( + "scripts/**", + ".github/workflows/thesis-facts-append.yml", + "pyproject.toml", + "uv.lock", + "uv.toml", + ".python-version", + ".venv/**", + "releases/anchors/**", + ): + assert required in APPEND_GATE_SPEC.gate_surface, required + + def test_the_scratch_directory_is_private_to_the_run(tmp_path): """The private directory is created 0700, and the shim asserts that it was. From 8438230fb0ac54e46f086a6364cbd702efcb2102 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 29 Nov 2026 07:26:42 -0500 Subject: [PATCH 2/7] Narrow the gate surface to the files the gate reads All of scripts/ on the surface would refuse a catalog-builder change shipped with the ledger/series_catalog.json it generates, as #128 did. The catalog tests require the two to land together, so that shape could not be split. The surface now lists the gate's own scripts and receipt_pins.py, plus the files that set up its interpreter and environment: scripts/sitecustomize.py, scripts/__pycache__/** (Python loads an unchecked-hash .pyc there in place of its source; observed), pyproject.toml, uv.lock, uv.toml, .python-version and .venv/**. A new module under scripts/ that shadows one of the gate's imports is now off the surface. A strict-xfail test records that limit; the fix is for the gate to stop importing from scripts/. Tests: a builder change beside an append stays a data proposal; the decider list gains the unchecked-hash .pyc; fixtures force-add the changed decider so an ignore file cannot drop it. Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +-- scripts/receipt_pins.py | 32 ++++++-- tests/test_thesis_append_shim_isolation.py | 96 ++++++++++++++++++++-- 3 files changed, 119 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 74351fb5..1c3bc81f 100644 --- a/README.md +++ b/README.md @@ -560,8 +560,11 @@ package with this repository's trust pins committed in `scripts/receipt_pins.py`; see `releases/README.md` (immutable post-genesis, like everything under `releases/`) for the schema, offline verification procedure, and security limits. The gate surface in that file -lists every base-checkout file that can decide a verdict: all of `scripts/`, -the append workflow, the anchors, and the uv inputs that build the gate's -environment (`pyproject.toml`, `uv.lock`, `uv.toml`, `.python-version`, -`.venv/`). The gate refuses a pull request that changes any of them together -with the ledger, and names them when a pull request changes only them. +lists the base-checkout files the gate reads (its scripts, the trust pins, the +anchors and the append workflow), plus the files that set up its interpreter +and environment: `scripts/sitecustomize.py`, `scripts/__pycache__/`, +`pyproject.toml`, `uv.lock`, `uv.toml`, `.python-version` and `.venv/`. The +gate refuses a pull request that changes any of them together with the +ledger, and names them when a pull request changes only them. A new module +under `scripts/` that shadows one of the gate's imports is not on the surface +yet. diff --git a/scripts/receipt_pins.py b/scripts/receipt_pins.py index ed1328ee..13dd3442 100644 --- a/scripts/receipt_pins.py +++ b/scripts/receipt_pins.py @@ -86,17 +86,31 @@ (f"releases/anchors/{LEDGER_SPEC.producer_public_key_filename}"), } ), - # Every file in the judging (base) checkout that can decide a verdict. A - # proposal that changes one of them together with the ledger is refused as - # mixed, and a proposal that changes only these is reported by name. + # The files in the judging (base) checkout that the gate reads, and the + # files that set up its interpreter and environment. A proposal that + # changes one of them together with the ledger is refused as mixed, and a + # proposal that changes only these is reported by name. + # + # Not covered: a new module under scripts/ that shadows an import (a + # scripts/tempfile.py, or a scripts/receipt/ package). The judge runs a + # script there, so scripts/ is sys.path[0], and both pull request jobs + # also put it on PYTHONPATH. Listing all of scripts/ would close that, but + # it would also refuse a catalog-builder change shipped with its + # regenerated ledger/series_catalog.json (as in #128), which the catalog + # tests require to land together. The fix is for the gate to stop + # importing from scripts/. gate_surface=frozenset( { - # The judge runs scripts/check_thesis_facts_append.py, so scripts/ - # is sys.path[0], and both pull request jobs also put it on - # PYTHONPATH. Any file there can decide the verdict: these pins, - # a module that shadows an import (the standard library's - # included), or a sitecustomize.py, which runs at startup. - "scripts/**", + "scripts/check_thesis_facts_append.py", + "scripts/verify_release_chain.py", + "scripts/canonical_json.py", + "scripts/cut_release_manifest.py", + "scripts/receipt_pins.py", + # Python runs a sitecustomize.py it finds on PYTHONPATH at + # startup, and loads an unchecked-hash .pyc from __pycache__ in + # place of its source. + "scripts/sitecustomize.py", + "scripts/__pycache__/**", ".github/workflows/thesis-facts-append.yml", # `uv sync --locked --no-dev --project ` builds the judge's # environment from these, including the receipt version that diff --git a/tests/test_thesis_append_shim_isolation.py b/tests/test_thesis_append_shim_isolation.py index 063d0223..6cb6892c 100644 --- a/tests/test_thesis_append_shim_isolation.py +++ b/tests/test_thesis_append_shim_isolation.py @@ -946,9 +946,9 @@ def test_a_true_append_is_accepted_end_to_end(tmp_path): # Files that decide a verdict when they sit in the judging checkout, one per # way in: the pins the shim imports, the uv inputs the workflow provisions the # judge from, and files that are not there today but would be read if added. -# Until 2026-09-29 the first three were off the gate surface, so a resolver- -# shaped append that also edited them was judged as plain data and never named -# them (PolicyEngine/chronicle#299 review). +# Before PolicyEngine/chronicle#308 the first three were off the gate surface, +# so a resolver-shaped append that also edited them was judged as plain data +# and never named them (PolicyEngine/chronicle#299 review). GATE_DECIDERS = ( "scripts/receipt_pins.py", "pyproject.toml", @@ -956,6 +956,7 @@ def test_a_true_append_is_accepted_end_to_end(tmp_path): "uv.toml", ".python-version", "scripts/sitecustomize.py", + "scripts/__pycache__/receipt_pins.cpython-314.pyc", ".venv/lib/python3.14/site-packages/zz_injected.pth", ) @@ -972,6 +973,20 @@ def mutate(root: pathlib.Path) -> None: return mutate +def _force_add(relative: str): + """Stage one path even where an ignore file lists it. + + ``__pycache__`` and ``.venv`` are commonly ignored, and the default global + ignore file applies even with GIT_CONFIG_GLOBAL unset, so ``git add -A`` + alone could leave the decider out of the candidate. + """ + + def stage(root: pathlib.Path) -> None: + _git(root, "add", "--force", "--", relative) + + return stage + + def _copy_existing_gate_deciders(root: pathlib.Path) -> None: """Put the repository's own copy of every decider it has into the base.""" @@ -997,6 +1012,7 @@ def test_an_append_that_also_changes_a_gate_decider_is_refused_as_mixed( tmp_path, prepare=_copy_existing_gate_deciders, mutate=_change_gate_decider(relative), + mutate_index=_force_add(relative), ) completed = _run_shim( @@ -1018,7 +1034,7 @@ def test_a_gate_decider_change_alone_is_a_named_gate_only_proposal(tmp_path, rel _copy_existing_gate_deciders(clone) base = _commit(clone, "deciders in the base") _change_gate_decider(relative)(clone) - candidate = _commit(clone, f"change {relative}") + candidate = _commit(clone, f"change {relative}", _force_add(relative)) completed = _run_shim( clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp" @@ -1055,6 +1071,38 @@ def test_an_append_beside_unchanged_gate_deciders_still_passes(tmp_path): _assert_nothing_left_behind(clone, tmp_path / "tmp") +def test_an_append_beside_a_catalog_builder_change_is_still_data(tmp_path): + """A script the gate never reads stays off the surface. + + PolicyEngine/chronicle#128 shipped scripts/build_series_catalog.py with the + ledger/series_catalog.json it generates, and the catalog tests require the + two to land together. With all of scripts/ on the surface, that shape would + be refused as mixed and could not be split. + """ + + builder = "scripts/build_series_catalog.py" + + def prepare(root: pathlib.Path) -> None: + (root / "scripts").mkdir(exist_ok=True) + shutil.copyfile(ROOT / builder, root / builder) + + clone, base, candidate = _replay_latest_release( + tmp_path, prepare=prepare, mutate=_change_gate_decider(builder) + ) + changed = set(_git(clone, "diff", "--name-only", base, candidate).splitlines()) + assert builder in changed, changed + + completed = _run_shim( + clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp" + ) + + assert completed.returncode == 0, completed.stdout + completed.stderr + assert completed.stdout == ( + f"{APPEND_GATE_OK}\n{_subject_line(clone, candidate, base)}\n" + ) + _assert_nothing_left_behind(clone, tmp_path / "tmp") + + OPENED_FILES_DRIVER = """\ import json import os @@ -1153,11 +1201,15 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): The judge runs a script in scripts/, so scripts/ is sys.path[0], and both pull request jobs also put it on PYTHONPATH, where a sitecustomize.py runs - at startup. The whole directory is therefore on the surface, not just the - files imported today. The judge's environment comes from the base's own - uv project, so its inputs are on the surface too. + at startup. Python also loads an unchecked-hash .pyc from + scripts/__pycache__ in place of its source. The judge's environment comes + from the base's own uv project, so its inputs are on the surface too. The + rest of scripts/ is not: the catalog builder ships with the catalog it + generates. """ + from receipt.append_gate import _matches_surface + from scripts.receipt_pins import APPEND_GATE_SPEC workflow = (ROOT / ".github" / "workflows" / "thesis-facts-append.yml").read_text( @@ -1167,7 +1219,13 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): assert 'uv sync --locked --no-dev --project "$base_gate"' in workflow assert SHIM.parent.relative_to(ROOT).as_posix() == "scripts" for required in ( - "scripts/**", + "scripts/check_thesis_facts_append.py", + "scripts/verify_release_chain.py", + "scripts/canonical_json.py", + "scripts/cut_release_manifest.py", + "scripts/receipt_pins.py", + "scripts/sitecustomize.py", + "scripts/__pycache__/**", ".github/workflows/thesis-facts-append.yml", "pyproject.toml", "uv.lock", @@ -1177,6 +1235,28 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): "releases/anchors/**", ): assert required in APPEND_GATE_SPEC.gate_surface, required + assert not _matches_surface( + "scripts/build_series_catalog.py", APPEND_GATE_SPEC.gate_surface + ) + + +@pytest.mark.xfail( + strict=True, + reason=( + "open limit: a new module under scripts/ that shadows one of the gate's " + "imports is not on the gate surface; the fix is for the gate to stop " + "importing from scripts/" + ), +) +@pytest.mark.parametrize( + "shadow", ["scripts/tempfile.py", "scripts/receipt/__init__.py"] +) +def test_a_module_that_shadows_a_gate_import_is_on_the_gate_surface(shadow): + from receipt.append_gate import _matches_surface + + from scripts.receipt_pins import APPEND_GATE_SPEC + + assert _matches_surface(shadow, APPEND_GATE_SPEC.gate_surface) def test_the_scratch_directory_is_private_to_the_run(tmp_path): From e0f67345d07fe1193be99835cb75e741f9d0ac33 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 11:43:40 -0500 Subject: [PATCH 3/7] Cover the bare surface directories and the judge's build inputs A "dir/**" entry matches only paths below dir, so a symlink committed at .venv or scripts/__pycache__ itself was unclassified and passed beside a ledger append. List each such directory bare as well, with a test that a symlink there is refused as mixed. Add the other files that decide the judge's environment or the anchor bytes it checks out: .python-versions, hatch.toml and hatch_build.py (uv installs this project with hatchling), a root sitecustomize.py (the editable install puts the root on sys.path), and .gitattributes and releases/.gitattributes. Record the limit that remains: a new module on the judge's import path, under scripts/ or at the root, and the project's own build inputs such as README.md. Running the judge isolated and without installing the project closes it. Pin the exact surface and the exact widening over the original gate in the tests, and let the shadowing xfail pass only on an AssertionError. Co-Authored-By: Claude Opus 5.5 --- README.md | 27 ++++-- scripts/receipt_pins.py | 56 +++++++++---- tests/test_receipt_shim_transparency.py | 37 ++++++-- tests/test_thesis_append_shim_isolation.py | 98 +++++++++++++++++++--- 4 files changed, 175 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 1c3bc81f..7d265ca4 100644 --- a/README.md +++ b/README.md @@ -559,12 +559,21 @@ environment. Verification machinery is consumed from the `receipt` package with this repository's trust pins committed in `scripts/receipt_pins.py`; see `releases/README.md` (immutable post-genesis, like everything under `releases/`) for the schema, offline -verification procedure, and security limits. The gate surface in that file -lists the base-checkout files the gate reads (its scripts, the trust pins, the -anchors and the append workflow), plus the files that set up its interpreter -and environment: `scripts/sitecustomize.py`, `scripts/__pycache__/`, -`pyproject.toml`, `uv.lock`, `uv.toml`, `.python-version` and `.venv/`. The -gate refuses a pull request that changes any of them together with the -ledger, and names them when a pull request changes only them. A new module -under `scripts/` that shadows one of the gate's imports is not on the surface -yet. +verification procedure, and security limits. The gate surface, +`APPEND_GATE_SPEC.gate_surface` in `scripts/receipt_pins.py`, lists the +files in the base checkout that decide the gate's verdict: + +- the gate's scripts, the trust pins, the anchors, and the append workflow; +- the files that build its interpreter and environment: `pyproject.toml`, + `uv.lock`, `uv.toml`, `.python-version`, `.python-versions`, `.venv`, + `hatch.toml`, `hatch_build.py`, `sitecustomize.py` (in `scripts/` and at + the root) and `scripts/__pycache__`; +- `.gitattributes` and `releases/.gitattributes`, which decide the anchor + bytes git checks out. + +The gate refuses a pull request that changes any of them together with the +ledger, and names them when a pull request changes only them. Not covered +yet: a new module on the judge's import path that shadows one of its imports, +under `scripts/` or at the root (the editable install adds the root), and the +project's own build inputs such as `README.md`. Closing that means running the +judge isolated (`python -I`) without installing this project. diff --git a/scripts/receipt_pins.py b/scripts/receipt_pins.py index 13dd3442..cedde0a6 100644 --- a/scripts/receipt_pins.py +++ b/scripts/receipt_pins.py @@ -86,19 +86,31 @@ (f"releases/anchors/{LEDGER_SPEC.producer_public_key_filename}"), } ), - # The files in the judging (base) checkout that the gate reads, and the - # files that set up its interpreter and environment. A proposal that + # The files in the judging (base) checkout that decide the gate's verdict: + # the gate's code and pins, the trust anchors, the files that build its + # interpreter and environment, and the append workflow. A proposal that # changes one of them together with the ledger is refused as mixed, and a - # proposal that changes only these is reported by name. + # proposal that changes only these is reported by name. A "dir/**" entry + # matches only paths below dir, so each one is also listed bare: otherwise + # a symlink or file committed at dir itself would be unclassified, and + # dropped on the data path. # - # Not covered: a new module under scripts/ that shadows an import (a - # scripts/tempfile.py, or a scripts/receipt/ package). The judge runs a - # script there, so scripts/ is sys.path[0], and both pull request jobs - # also put it on PYTHONPATH. Listing all of scripts/ would close that, but - # it would also refuse a catalog-builder change shipped with its - # regenerated ledger/series_catalog.json (as in #128), which the catalog - # tests require to land together. The fix is for the gate to stop - # importing from scripts/. + # Not covered: modules on the judge's import path that this list cannot + # name in advance. + # - The judge runs a script in scripts/, so scripts/ is sys.path[0], and + # both pull request jobs also put it on PYTHONPATH. A new module there + # shadows an import: a scripts/tempfile.py, a scripts/receipt/ package, + # or another spelling of sitecustomize or receipt_pins (a package, a + # sourceless .pyc, an extension module). + # - uv installs this project editable, and the .pth file that adds puts + # the repository root on sys.path. So a new module at the root, such as + # a sitecustomize/ package, can be imported at startup, and the editable + # build also reads README.md. + # Listing all of scripts/ would close the first, but it would also refuse + # a catalog-builder change shipped with its regenerated + # ledger/series_catalog.json (as in #128), which the catalog tests require + # to land together. The fix for both is in how the workflow runs the + # judge: isolated (python -I), without installing this project. gate_surface=frozenset( { "scripts/check_thesis_facts_append.py", @@ -106,21 +118,35 @@ "scripts/canonical_json.py", "scripts/cut_release_manifest.py", "scripts/receipt_pins.py", - # Python runs a sitecustomize.py it finds on PYTHONPATH at - # startup, and loads an unchecked-hash .pyc from __pycache__ in - # place of its source. + # Python runs a sitecustomize.py it finds on PYTHONPATH, or on + # the path the editable install adds, at startup, and loads an + # unchecked-hash .pyc from __pycache__ in place of its source. "scripts/sitecustomize.py", + "sitecustomize.py", + "scripts/__pycache__", "scripts/__pycache__/**", ".github/workflows/thesis-facts-append.yml", # `uv sync --locked --no-dev --project ` builds the judge's # environment from these, including the receipt version that # implements the gate. uv also reads the project's uv.toml and - # .python-version, and reuses a .venv it finds there. + # .python-version (or .python-versions), and reuses a .venv it + # finds there. It installs this project with hatchling, which + # reads hatch.toml and runs a hatch_build.py hook when one is + # configured. "pyproject.toml", "uv.lock", "uv.toml", ".python-version", + ".python-versions", + ".venv", ".venv/**", + "hatch.toml", + "hatch_build.py", + # Git applies these when it checks out the judge, so they decide + # the bytes of the anchors it pins. + ".gitattributes", + "releases/.gitattributes", + "releases/anchors", "releases/anchors/**", } ), diff --git a/tests/test_receipt_shim_transparency.py b/tests/test_receipt_shim_transparency.py index 095e5f19..55a86297 100644 --- a/tests/test_receipt_shim_transparency.py +++ b/tests/test_receipt_shim_transparency.py @@ -135,10 +135,12 @@ def test_the_shim_gate_surface_deliberately_widens_the_originals() -> None: """The one place the pair is meant to disagree about classification. The originals' GATE_SURFACE predates scripts/receipt_pins.py, where the - shim's trust pins now live, and never listed the uv inputs that provision - the judge. The shim's surface covers every original entry and adds those, - so a proposal that changes one of them is refused as mixed (with rows) or - named as gate-only (alone), where the original judged it as plain data. + shim's trust pins now live, and never listed the files that build the + judge's interpreter and environment or decide the anchor bytes it checks + out. The shim's surface covers every original entry and adds exactly + those, so a proposal that changes one of them is refused as mixed (with + rows) or named as gate-only (alone), where the original judged it as plain + data. No case in this file changes such a file, so the byte-identity asserted here is unaffected; tests/test_thesis_append_shim_isolation.py holds the shim to the wider surface. @@ -156,9 +158,30 @@ def test_the_shim_gate_surface_deliberately_widens_the_originals() -> None: else: assert _matches_surface(entry, shim_gate), entry assert _original_surface("DATA_SURFACE") == APPEND_GATE_SPEC.data_surface - for widened in ("scripts/receipt_pins.py", "pyproject.toml", "uv.lock"): - assert not _matches_surface(widened, original_gate), widened - assert _matches_surface(widened, shim_gate), widened + widened = { + "scripts/receipt_pins.py", + "scripts/sitecustomize.py", + "sitecustomize.py", + "scripts/__pycache__", + "scripts/__pycache__/**", + "pyproject.toml", + "uv.lock", + "uv.toml", + ".python-version", + ".python-versions", + ".venv", + ".venv/**", + "hatch.toml", + "hatch_build.py", + ".gitattributes", + "releases/.gitattributes", + "releases/anchors", + } + assert shim_gate - original_gate == widened + for entry in widened: + named = entry.removesuffix("/**") + assert not _matches_surface(named, original_gate), entry + assert _matches_surface(named, shim_gate), entry @pytest.fixture(scope="session") diff --git a/tests/test_thesis_append_shim_isolation.py b/tests/test_thesis_append_shim_isolation.py index 6cb6892c..13eeaeac 100644 --- a/tests/test_thesis_append_shim_isolation.py +++ b/tests/test_thesis_append_shim_isolation.py @@ -944,8 +944,9 @@ def test_a_true_append_is_accepted_end_to_end(tmp_path): # Files that decide a verdict when they sit in the judging checkout, one per -# way in: the pins the shim imports, the uv inputs the workflow provisions the -# judge from, and files that are not there today but would be read if added. +# way in: the pins the shim imports, the uv and hatchling inputs the workflow +# provisions the judge from, the attributes git checks the anchors out with, +# and files that are not there today but would be read if added. # Before PolicyEngine/chronicle#308 the first three were off the gate surface, # so a resolver-shaped append that also edited them was judged as plain data # and never named them (PolicyEngine/chronicle#299 review). @@ -955,11 +956,23 @@ def test_a_true_append_is_accepted_end_to_end(tmp_path): "uv.lock", "uv.toml", ".python-version", + ".python-versions", + "hatch.toml", + "hatch_build.py", "scripts/sitecustomize.py", + "sitecustomize.py", "scripts/__pycache__/receipt_pins.cpython-314.pyc", ".venv/lib/python3.14/site-packages/zz_injected.pth", + ".gitattributes", + "releases/.gitattributes", ) +# A "dir/**" entry matches only paths below dir, so these directories are also +# on the surface bare: a symlink committed in their place is a decider too. +# (releases/anchors is listed bare as well; the chain checks refuse a symlink +# there on their own.) +SURFACE_DIRECTORIES = (".venv", "scripts/__pycache__") + def _change_gate_decider(relative: str): """Return a mutation that changes one decider, or adds it if absent.""" @@ -1049,6 +1062,43 @@ def test_a_gate_decider_change_alone_is_a_named_gate_only_proposal(tmp_path, rel _assert_nothing_left_behind(clone, tmp_path / "tmp") +def _link_surface_directory(relative: str): + """Return a mutation that commits a symlink where a surface directory goes.""" + + def mutate(root: pathlib.Path) -> None: + path = root / relative + if path.is_symlink() or path.is_file(): + path.unlink() + elif path.exists(): + shutil.rmtree(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.symlink_to("ledger" if "/" not in relative else "../ledger") + + return mutate + + +@pytest.mark.parametrize("relative", SURFACE_DIRECTORIES) +def test_an_append_beside_a_symlinked_surface_directory_is_refused_as_mixed( + tmp_path, relative +): + clone, base, candidate = _replay_latest_release( + tmp_path, + mutate=_link_surface_directory(relative), + mutate_index=_force_add(relative), + ) + assert _git(clone, "ls-tree", candidate, "--", relative).startswith("120000 ") + + completed = _run_shim( + clone, commit=candidate, base_ref=base, temporary_root=tmp_path / "tmp" + ) + + assert completed.returncode == 1, completed.stdout + completed.stderr + assert completed.stdout == "" + assert f"{FAILED}mixed data/gate proposal is forbidden: " in completed.stderr + assert f"GATE_SURFACE changes=[{relative!r}" in completed.stderr + _assert_nothing_left_behind(clone, tmp_path / "tmp") + + def test_an_append_beside_unchanged_gate_deciders_still_passes(tmp_path): """The resolver's shape: ledger and release files only, deciders untouched.""" @@ -1203,9 +1253,10 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): pull request jobs also put it on PYTHONPATH, where a sitecustomize.py runs at startup. Python also loads an unchecked-hash .pyc from scripts/__pycache__ in place of its source. The judge's environment comes - from the base's own uv project, so its inputs are on the surface too. The - rest of scripts/ is not: the catalog builder ships with the catalog it - generates. + from the base's own uv project, built with hatchling, so its inputs are on + the surface too, and git's attributes decide the anchor bytes it checks + out. The rest of scripts/ is not: the catalog builder ships with the + catalog it generates. """ from receipt.append_gate import _matches_surface @@ -1218,23 +1269,37 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): assert 'PYTHONPATH="$base_gate/scripts"' in workflow assert 'uv sync --locked --no-dev --project "$base_gate"' in workflow assert SHIM.parent.relative_to(ROOT).as_posix() == "scripts" - for required in ( + pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8") + assert 'build-backend = "hatchling.build"' in pyproject + assert APPEND_GATE_SPEC.gate_surface == { "scripts/check_thesis_facts_append.py", "scripts/verify_release_chain.py", "scripts/canonical_json.py", "scripts/cut_release_manifest.py", "scripts/receipt_pins.py", "scripts/sitecustomize.py", + "sitecustomize.py", + "scripts/__pycache__", "scripts/__pycache__/**", ".github/workflows/thesis-facts-append.yml", "pyproject.toml", "uv.lock", "uv.toml", ".python-version", + ".python-versions", + ".venv", ".venv/**", + "hatch.toml", + "hatch_build.py", + ".gitattributes", + "releases/.gitattributes", + "releases/anchors", "releases/anchors/**", - ): - assert required in APPEND_GATE_SPEC.gate_surface, required + } + # Every "dir/**" entry is also listed bare, so dir itself is covered. + for pattern in APPEND_GATE_SPEC.gate_surface: + if pattern.endswith("/**"): + assert pattern[: -len("/**")] in APPEND_GATE_SPEC.gate_surface, pattern assert not _matches_surface( "scripts/build_series_catalog.py", APPEND_GATE_SPEC.gate_surface ) @@ -1242,14 +1307,23 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): @pytest.mark.xfail( strict=True, + raises=AssertionError, reason=( - "open limit: a new module under scripts/ that shadows one of the gate's " - "imports is not on the gate surface; the fix is for the gate to stop " - "importing from scripts/" + "open limit: a new module on the judge's import path (under scripts/, " + "or at the root through the editable install) that shadows one of its " + "imports is not on the gate surface; the fix is to run the judge " + "isolated (python -I) without installing this project" ), ) @pytest.mark.parametrize( - "shadow", ["scripts/tempfile.py", "scripts/receipt/__init__.py"] + "shadow", + [ + "scripts/tempfile.py", + "scripts/receipt/__init__.py", + "scripts/receipt_pins/__init__.py", + "scripts/sitecustomize/__init__.py", + "sitecustomize/__init__.py", + ], ) def test_a_module_that_shadows_a_gate_import_is_on_the_gate_surface(shadow): from receipt.append_gate import _matches_surface From c29e1de425431ab5e856e58f9f1be35b5f2238ed Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 13:35:02 -0500 Subject: [PATCH 4/7] List the nested .gitattributes git applies to the judge Git applies scripts/.gitattributes, .github/.gitattributes and .github/workflows/.gitattributes when it checks out the judge. receipt 0.6.2 already refuses filter, ident and working-tree-encoding on every surface path at any depth, and Python reads either line ending, so none of the three can change a verdict today. Listing them keeps that from depending on the receipt version. A structural test now checks that every .gitattributes above a surface entry is on the surface. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +++++-- scripts/receipt_pins.py | 28 +++++++++++++++------- tests/test_receipt_shim_transparency.py | 7 ++++-- tests/test_thesis_append_shim_isolation.py | 24 +++++++++++++++---- 4 files changed, 52 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 7d265ca4..13771d6d 100644 --- a/README.md +++ b/README.md @@ -568,8 +568,13 @@ files in the base checkout that decide the gate's verdict: `uv.lock`, `uv.toml`, `.python-version`, `.python-versions`, `.venv`, `hatch.toml`, `hatch_build.py`, `sitecustomize.py` (in `scripts/` and at the root) and `scripts/__pycache__`; -- `.gitattributes` and `releases/.gitattributes`, which decide the anchor - bytes git checks out. +- every `.gitattributes` git applies to these files when it checks out the + judge: at the root and in `releases/`, which decide the anchor bytes, and + in `scripts/`, `.github/` and `.github/workflows/`. Receipt already refuses + `filter`, `ident` and `working-tree-encoding` on the gate's scripts and the + workflow, and line endings do not change how Python reads a script, so + these three cannot change a verdict today; listing them keeps that from + depending on the receipt version. The gate refuses a pull request that changes any of them together with the ledger, and names them when a pull request changes only them. Not covered diff --git a/scripts/receipt_pins.py b/scripts/receipt_pins.py index cedde0a6..cd2c8df2 100644 --- a/scripts/receipt_pins.py +++ b/scripts/receipt_pins.py @@ -88,12 +88,13 @@ ), # The files in the judging (base) checkout that decide the gate's verdict: # the gate's code and pins, the trust anchors, the files that build its - # interpreter and environment, and the append workflow. A proposal that - # changes one of them together with the ledger is refused as mixed, and a - # proposal that changes only these is reported by name. A "dir/**" entry - # matches only paths below dir, so each one is also listed bare: otherwise - # a symlink or file committed at dir itself would be unclassified, and - # dropped on the data path. + # interpreter and environment, the append workflow, and the .gitattributes + # files git applies to any of them. A proposal that changes one of them + # together with the ledger is refused as mixed, and a proposal that + # changes only these is reported by name. A "dir/**" entry matches only + # paths below dir, so each one is also listed bare: otherwise a symlink or + # file committed at dir itself would be unclassified, and dropped on the + # data path. # # Not covered: modules on the judge's import path that this list cannot # name in advance. @@ -142,10 +143,21 @@ ".venv/**", "hatch.toml", "hatch_build.py", - # Git applies these when it checks out the judge, so they decide - # the bytes of the anchors it pins. + # Git applies the .gitattributes in each directory above a file + # when it checks out the judge, so every one above an entry here + # is listed. The root and releases/ files decide the bytes of the + # anchors the judge pins. The scripts/ file reaches the gate's + # Python, and the .github/ files reach no entry here but the + # workflow, which the judge does not read. Receipt refuses filter, + # ident and working-tree-encoding on every surface path, and + # Python reads either line ending, so these three cannot change a + # verdict today. They are listed so that this does not depend on + # the receipt version. ".gitattributes", "releases/.gitattributes", + "scripts/.gitattributes", + ".github/.gitattributes", + ".github/workflows/.gitattributes", "releases/anchors", "releases/anchors/**", } diff --git a/tests/test_receipt_shim_transparency.py b/tests/test_receipt_shim_transparency.py index 55a86297..20962e0d 100644 --- a/tests/test_receipt_shim_transparency.py +++ b/tests/test_receipt_shim_transparency.py @@ -136,8 +136,8 @@ def test_the_shim_gate_surface_deliberately_widens_the_originals() -> None: The originals' GATE_SURFACE predates scripts/receipt_pins.py, where the shim's trust pins now live, and never listed the files that build the - judge's interpreter and environment or decide the anchor bytes it checks - out. The shim's surface covers every original entry and adds exactly + judge's interpreter and environment or the .gitattributes git checks it + out with. The shim's surface covers every original entry and adds exactly those, so a proposal that changes one of them is refused as mixed (with rows) or named as gate-only (alone), where the original judged it as plain data. @@ -175,6 +175,9 @@ def test_the_shim_gate_surface_deliberately_widens_the_originals() -> None: "hatch_build.py", ".gitattributes", "releases/.gitattributes", + "scripts/.gitattributes", + ".github/.gitattributes", + ".github/workflows/.gitattributes", "releases/anchors", } assert shim_gate - original_gate == widened diff --git a/tests/test_thesis_append_shim_isolation.py b/tests/test_thesis_append_shim_isolation.py index 13eeaeac..b03809e7 100644 --- a/tests/test_thesis_append_shim_isolation.py +++ b/tests/test_thesis_append_shim_isolation.py @@ -945,7 +945,7 @@ def test_a_true_append_is_accepted_end_to_end(tmp_path): # Files that decide a verdict when they sit in the judging checkout, one per # way in: the pins the shim imports, the uv and hatchling inputs the workflow -# provisions the judge from, the attributes git checks the anchors out with, +# provisions the judge from, the attributes git checks the judge out with, # and files that are not there today but would be read if added. # Before PolicyEngine/chronicle#308 the first three were off the gate surface, # so a resolver-shaped append that also edited them was judged as plain data @@ -965,6 +965,9 @@ def test_a_true_append_is_accepted_end_to_end(tmp_path): ".venv/lib/python3.14/site-packages/zz_injected.pth", ".gitattributes", "releases/.gitattributes", + "scripts/.gitattributes", + ".github/.gitattributes", + ".github/workflows/.gitattributes", ) # A "dir/**" entry matches only paths below dir, so these directories are also @@ -1254,9 +1257,9 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): at startup. Python also loads an unchecked-hash .pyc from scripts/__pycache__ in place of its source. The judge's environment comes from the base's own uv project, built with hatchling, so its inputs are on - the surface too, and git's attributes decide the anchor bytes it checks - out. The rest of scripts/ is not: the catalog builder ships with the - catalog it generates. + the surface too, and so is every .gitattributes git applies to a surface + file when it checks the judge out. The rest of scripts/ is not: the + catalog builder ships with the catalog it generates. """ from receipt.append_gate import _matches_surface @@ -1293,6 +1296,9 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): "hatch_build.py", ".gitattributes", "releases/.gitattributes", + "scripts/.gitattributes", + ".github/.gitattributes", + ".github/workflows/.gitattributes", "releases/anchors", "releases/anchors/**", } @@ -1300,6 +1306,16 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): for pattern in APPEND_GATE_SPEC.gate_surface: if pattern.endswith("/**"): assert pattern[: -len("/**")] in APPEND_GATE_SPEC.gate_surface, pattern + # Every .gitattributes above a surface entry is on the surface; one inside + # a "dir/**" entry is covered by that entry. + for pattern in APPEND_GATE_SPEC.gate_surface: + parts = pattern.removesuffix("/**").split("/") + for depth in range(len(parts)): + attributes = "/".join((*parts[:depth], ".gitattributes")) + assert _matches_surface(attributes, APPEND_GATE_SPEC.gate_surface), ( + pattern, + attributes, + ) assert not _matches_surface( "scripts/build_series_catalog.py", APPEND_GATE_SPEC.gate_surface ) From 845658a6f1c4fadf0136d213f319b33fc4f80f23 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 10:35:09 -0500 Subject: [PATCH 5/7] Start the append gate isolated, without the project installed The thesis-ledger append gate could import a module that a data proposal added off the gate surface. scripts/ was sys.path[0] and on PYTHONPATH, and uv's editable install of this project put the base checkout's root on sys.path. A scripts/tempfile.py, a scripts/receipt/ or scripts/receipt_pins/ package, or a root sitecustomize/ package would then run inside the judge on every later pull request. - The gate and verify_release_chain.py compile scripts/receipt_pins.py by path; the scripts.receipt_pins fallback is gone. - Both pull request jobs build the base gate's environment with `uv sync --no-install-project` and start it with `uv run --no-sync ... python -I`, with no PYTHONPATH. A base gate that still imports its pins by name gets the project installed, as before, so the new workflow still judges with an older base gate. - The push path and ci.yml's `verify_release_chain.py --full` start the same way. - The strict xfail becomes end-to-end tests that run the workflow's own step scripts against all five shadows. A fake uv builds a real venv and models the editable install. Controls show each shadow runs when its way in is open. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 13 +- .github/workflows/thesis-facts-append.yml | 111 ++-- README.md | 13 +- scripts/check_thesis_facts_append.py | 29 +- scripts/receipt_pins.py | 55 +- scripts/verify_release_chain.py | 29 +- tests/test_legacy_targets_retired.py | 11 +- tests/test_policyengine_ledger.py | 1 + tests/test_release_chain.py | 1 + tests/test_thesis_append_adversarial.py | 19 +- tests/test_thesis_append_shim_isolation.py | 621 +++++++++++++++++++-- 11 files changed, 758 insertions(+), 145 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 712e0652..3dd931ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,11 +20,16 @@ jobs: if: >- github.event_name == 'push' && github.ref == 'refs/heads/codex/thesis-ledger-facts' - # Runs in the repo's hash-locked env: the verifier may import - # packaged dependencies (receipt) once the consumption shims land. + # Runs in the repo's hash-locked env: the verifier imports the + # packaged receipt. The env does not install this project, so the + # checkout's root is not on sys.path, and `python -I` keeps scripts/ + # off it too: no other module in either can stand in for one the + # verifier imports. It loads scripts/receipt_pins.py by path. + # `uv run --no-sync` keeps uv from installing the project again; + # the steps below install it for the tests. run: | - uv sync --locked --no-dev - uv run --locked --no-dev python scripts/verify_release_chain.py --full + uv sync --locked --no-dev --no-install-project + uv run --no-sync python -I scripts/verify_release_chain.py --full - name: Set up Python uses: actions/setup-python@v5 diff --git a/.github/workflows/thesis-facts-append.yml b/.github/workflows/thesis-facts-append.yml index a7c45cc1..68b4de12 100644 --- a/.github/workflows/thesis-facts-append.yml +++ b/.github/workflows/thesis-facts-append.yml @@ -99,7 +99,36 @@ jobs: # the base gate with it: the gate scripts may import packaged # dependencies, and installing from the base's uv.lock # keeps the PR unable to influence what code judges it. - uv sync --locked --no-dev --project "$base_gate" + # + # Every start of the base gate, the --help question included, uses + # `python -I` and sets no PYTHONPATH, and the environment does not + # install this project. -I keeps the script's own directory off + # sys.path and ignores PYTHON* variables; without the project, no + # editable .pth puts the base checkout's root on sys.path, and the + # sync builds nothing from the checkout (no README.md, hatch.toml or + # hatch_build.py). Most of scripts/ and the root are off the gate + # surface, so an earlier data proposal can add a module there (a + # scripts/tempfile.py, a scripts/receipt/ package, a root + # sitecustomize/ package); started this way, the gate never imports + # it. `uv run --no-sync` keeps uv from installing the project again. + # + # A base gate that still imports its pins as scripts.receipt_pins + # finds them only through that root, so for such a base alone the + # project is installed as before, and the base keeps that older + # gate's limits. The check reads base-owned code, which the + # candidate cannot change. Delete the first branch below once no + # base reachable from this branch imports its pins by name. A gate + # older than the pins imports its sibling scripts by name, cannot + # start this way, and stops the step. + base_gate_script="$base_gate/scripts/check_thesis_facts_append.py" + if grep -qE '^[[:space:]]*from scripts\.receipt_pins import ' \ + "$base_gate_script"; then + uv sync --locked --no-dev --project "$base_gate" + base_gate_python=(uv run --locked --no-dev --project "$base_gate" python -I) + else + uv sync --locked --no-dev --no-install-project --project "$base_gate" + base_gate_python=(uv run --no-sync --project "$base_gate" python -I) + fi # Receipt 0.6 reads and rehashes the named commit's objects; the shim # prints the commit and tree from that verdict. --root only locates @@ -118,33 +147,24 @@ jobs: # cannot run at all stops the step instead of being read as an old # one. Delete the second branch below once no base reachable from # this branch predates --commit. - base_gate_help="$( - uv run --locked --no-dev --project "$base_gate" \ - python "$base_gate/scripts/check_thesis_facts_append.py" --help - )" + base_gate_help="$("${base_gate_python[@]}" "$base_gate_script" --help)" cd "$RUNNER_TEMP" case "$base_gate_help" in *--commit*) - PYTHONPATH="$base_gate/scripts" \ - PYTHONNOUSERSITE=1 \ - uv run --locked --no-dev --project "$base_gate" \ - python "$base_gate/scripts/check_thesis_facts_append.py" \ - --root "$candidate" \ - --commit "$MERGE_SHA" \ - --base-ref "$BASE_SHA" + "${base_gate_python[@]}" "$base_gate_script" \ + --root "$candidate" \ + --commit "$MERGE_SHA" \ + --base-ref "$BASE_SHA" ;; *) echo "note: the base gate at $BASE_SHA predates --commit, so it" \ "judges the working tree at $candidate, without binding its" \ "verdict to $MERGE_SHA. This is the base's own guarantee and" \ "the only one available against that base." >&2 - PYTHONPATH="$base_gate/scripts" \ - PYTHONNOUSERSITE=1 \ - uv run --locked --no-dev --project "$base_gate" \ - python "$base_gate/scripts/check_thesis_facts_append.py" \ - --root "$candidate" \ - --base-ref "$BASE_SHA" + "${base_gate_python[@]}" "$base_gate_script" \ + --root "$candidate" \ + --base-ref "$BASE_SHA" ;; esac @@ -178,50 +198,57 @@ jobs: test "$(git -C "$base_gate" rev-parse HEAD)" = "$base_sha" # Base gate runs from the BASE commit's own hash-locked env so - # gate dependencies resolve without the PR influencing them. - uv sync --locked --no-dev --project "$base_gate" + # gate dependencies resolve without the PR influencing them. As + # in the trusted job above, the env does not install this + # project and every start uses `python -I` with no PYTHONPATH, + # so no module in the base's scripts/ or at its root can stand in + # for one the gate imports, except for a base gate that still + # imports its pins by name. Delete the first branch below once + # no base reachable from this branch does. + base_gate_script="$base_gate/scripts/check_thesis_facts_append.py" + if grep -qE '^[[:space:]]*from scripts\.receipt_pins import ' \ + "$base_gate_script"; then + uv sync --locked --no-dev --project "$base_gate" + base_gate_python=(uv run --locked --no-dev --project "$base_gate" python -I) + else + uv sync --locked --no-dev --no-install-project --project "$base_gate" + base_gate_python=(uv run --no-sync --project "$base_gate" python -I) + fi workspace_sha="$(git -C "$GITHUB_WORKSPACE" rev-parse HEAD)" [[ "$workspace_sha" =~ ^[0-9a-f]{40,64}$ ]] # As in the trusted job above: the commit is named, not inferred, # and the base gate is asked what it accepts for the same reason. - base_gate_help="$( - uv run --locked --no-dev --project "$base_gate" \ - python "$base_gate/scripts/check_thesis_facts_append.py" --help - )" + base_gate_help="$("${base_gate_python[@]}" "$base_gate_script" --help)" cd "$RUNNER_TEMP" case "$base_gate_help" in *--commit*) - PYTHONPATH="$base_gate/scripts" \ - PYTHONNOUSERSITE=1 \ - uv run --locked --no-dev --project "$base_gate" \ - python "$base_gate/scripts/check_thesis_facts_append.py" \ - --root "$GITHUB_WORKSPACE" \ - --commit "$workspace_sha" \ - --base-ref "$base_sha" + "${base_gate_python[@]}" "$base_gate_script" \ + --root "$GITHUB_WORKSPACE" \ + --commit "$workspace_sha" \ + --base-ref "$base_sha" ;; *) echo "note: the base gate at $base_sha predates --commit, so" \ "it judges the workspace, without binding its verdict to" \ "$workspace_sha." >&2 - PYTHONPATH="$base_gate/scripts" \ - PYTHONNOUSERSITE=1 \ - uv run --locked --no-dev --project "$base_gate" \ - python "$base_gate/scripts/check_thesis_facts_append.py" \ - --root "$GITHUB_WORKSPACE" \ - --base-ref "$base_sha" + "${base_gate_python[@]}" "$base_gate_script" \ + --root "$GITHUB_WORKSPACE" \ + --base-ref "$base_sha" ;; esac else # The push path names the pushed commit explicitly too. The # argument is required, so there is no spelling of this run in - # which the commit is taken from the checkout instead. - uv sync --locked --no-dev - uv run --locked --no-dev \ - python scripts/check_thesis_facts_append.py \ - --commit "$GITHUB_SHA" + # which the commit is taken from the checkout instead. It runs + # the pushed commit's own gate, which loads its pins by path, so + # it starts it isolated, as the jobs above do, with no project + # install to undo. + uv sync --locked --no-dev --no-install-project + uv run --no-sync python -I scripts/check_thesis_facts_append.py \ + --commit "$GITHUB_SHA" fi - name: Install uv diff --git a/README.md b/README.md index 13771d6d..9614d4a6 100644 --- a/README.md +++ b/README.md @@ -577,8 +577,11 @@ files in the base checkout that decide the gate's verdict: depending on the receipt version. The gate refuses a pull request that changes any of them together with the -ledger, and names them when a pull request changes only them. Not covered -yet: a new module on the judge's import path that shadows one of its imports, -under `scripts/` or at the root (the editable install adds the root), and the -project's own build inputs such as `README.md`. Closing that means running the -judge isolated (`python -I`) without installing this project. +ledger, and names them when a pull request changes only them. The rest of +`scripts/` is off the surface, and so is any new module that could shadow one +of the gate's imports, there or at the root. None can reach the gate. The +append workflow builds its environment without installing this project, so +the root is not on its import path, starts it with `python -I` and no +`PYTHONPATH`, so `scripts/` is not either, and the gate loads +`receipt_pins.py` by path. Only a base whose gate still imports its pins by +name gets the project installed, and that older gate keeps the earlier limit. diff --git a/scripts/check_thesis_facts_append.py b/scripts/check_thesis_facts_append.py index 62972832..e157aae2 100644 --- a/scripts/check_thesis_facts_append.py +++ b/scripts/check_thesis_facts_append.py @@ -44,21 +44,34 @@ import subprocess import sys import tempfile +import types from collections.abc import Iterator from typing import Any import receipt.append_gate as _receipt from receipt.release_chain import MANIFEST_RE, ReleaseChainError -try: - from receipt_pins import APPEND_GATE_SPEC -except ModuleNotFoundError as exc: - if exc.name != "receipt_pins": - raise - # The test suite copies the legacy three-script surface into temporary - # repositories. The editable consumer tree remains the sole pin owner. - from scripts.receipt_pins import APPEND_GATE_SPEC +def _load_receipt_pins() -> types.ModuleType: + """Load the trust pins from ``receipt_pins.py`` beside this file, by path. + + The append workflow starts this script with ``python -I``, which keeps its + directory off ``sys.path``. No other module in ``scripts/`` can then stand + in for one this script imports, such as a ``tempfile.py`` or a + ``receipt/`` package. The pins are compiled from their source here rather + than imported, so a ``__pycache__`` entry cannot stand in for them either. + ``scripts/verify_release_chain.py`` loads them the same way. + """ + + path = pathlib.Path(__file__).resolve().with_name("receipt_pins.py") + module = types.ModuleType("receipt_pins") + module.__file__ = str(path) + code = compile(path.read_bytes(), str(path), "exec", dont_inherit=True) + exec(code, module.__dict__) + return module + + +APPEND_GATE_SPEC = _load_receipt_pins().APPEND_GATE_SPEC CODE_ROOT = pathlib.Path(__file__).resolve().parents[1] RELEASE_MANIFEST_PREFIX = APPEND_GATE_SPEC.release_manifest_prefix diff --git a/scripts/receipt_pins.py b/scripts/receipt_pins.py index cd2c8df2..128dc550 100644 --- a/scripts/receipt_pins.py +++ b/scripts/receipt_pins.py @@ -96,22 +96,22 @@ # file committed at dir itself would be unclassified, and dropped on the # data path. # - # Not covered: modules on the judge's import path that this list cannot - # name in advance. - # - The judge runs a script in scripts/, so scripts/ is sys.path[0], and - # both pull request jobs also put it on PYTHONPATH. A new module there - # shadows an import: a scripts/tempfile.py, a scripts/receipt/ package, - # or another spelling of sitecustomize or receipt_pins (a package, a - # sourceless .pyc, an extension module). - # - uv installs this project editable, and the .pth file that adds puts - # the repository root on sys.path. So a new module at the root, such as - # a sitecustomize/ package, can be imported at startup, and the editable - # build also reads README.md. - # Listing all of scripts/ would close the first, but it would also refuse - # a catalog-builder change shipped with its regenerated - # ledger/series_catalog.json (as in #128), which the catalog tests require - # to land together. The fix for both is in how the workflow runs the - # judge: isolated (python -I), without installing this project. + # The rest of scripts/ stays off the surface. A catalog-builder change + # ships with the ledger/series_catalog.json it regenerates (as in #128), + # and the catalog tests require the two to land together. Nor can this + # list name in advance every module that could shadow one the judge + # imports: a scripts/tempfile.py, a scripts/receipt/ package, a root + # sitecustomize/ package, or another spelling of sitecustomize or + # receipt_pins (a sourceless .pyc, an extension module). None of them can + # reach the judge. The append workflow builds its environment without + # installing this project (uv sync --no-install-project), so the base + # checkout's root is not on sys.path, and starts it with python -I and no + # PYTHONPATH, so scripts/ is not either. The gate loads this file by path. + # + # The one exception is a base whose gate still imports these pins as + # scripts.receipt_pins, through the root. The workflow installs the + # project for that base alone, so a root-level module can still reach a + # gate that old. gate_surface=frozenset( { "scripts/check_thesis_facts_append.py", @@ -119,21 +119,24 @@ "scripts/canonical_json.py", "scripts/cut_release_manifest.py", "scripts/receipt_pins.py", - # Python runs a sitecustomize.py it finds on PYTHONPATH, or on - # the path the editable install adds, at startup, and loads an - # unchecked-hash .pyc from __pycache__ in place of its source. + # Older pairings still read these. A gate started with scripts/ + # on PYTHONPATH, or with the project installed (which puts the + # root on sys.path), runs a sitecustomize.py found there at + # startup, and a gate that imports the pins by name loads an + # unchecked-hash .pyc from __pycache__ in place of their source. "scripts/sitecustomize.py", "sitecustomize.py", "scripts/__pycache__", "scripts/__pycache__/**", ".github/workflows/thesis-facts-append.yml", - # `uv sync --locked --no-dev --project ` builds the judge's - # environment from these, including the receipt version that - # implements the gate. uv also reads the project's uv.toml and - # .python-version (or .python-versions), and reuses a .venv it - # finds there. It installs this project with hatchling, which - # reads hatch.toml and runs a hatch_build.py hook when one is - # configured. + # `uv sync --locked --no-dev --no-install-project --project + # ` builds the judge's environment from these, including + # the receipt version that implements the gate. uv also reads the + # project's uv.toml and .python-version (or .python-versions), + # and reuses a .venv it finds there. For a base whose gate still + # imports its pins by name, the workflow also installs this + # project, with hatchling, which reads hatch.toml and runs a + # hatch_build.py hook when one is configured. "pyproject.toml", "uv.lock", "uv.toml", diff --git a/scripts/verify_release_chain.py b/scripts/verify_release_chain.py index 0231113f..c0a0ce3f 100644 --- a/scripts/verify_release_chain.py +++ b/scripts/verify_release_chain.py @@ -15,20 +15,33 @@ import argparse import pathlib import sys +import types from datetime import datetime from typing import Any import receipt.release_chain as _receipt from receipt.snapshot import SnapshotError, TreeSnapshot -try: - from receipt_pins import LEDGER_SPEC -except ModuleNotFoundError as exc: - if exc.name != "receipt_pins": - raise - # The test suite copies the legacy three-script surface into temporary - # repositories. The editable consumer tree remains the sole pin owner. - from scripts.receipt_pins import LEDGER_SPEC + +def _load_receipt_pins() -> types.ModuleType: + """Load the trust pins from ``receipt_pins.py`` beside this file, by path. + + CI starts this script with ``python -I``, which keeps its directory off + ``sys.path``, so no other module in ``scripts/`` can stand in for one this + script imports. The pins are compiled from their source rather than + imported, so a ``__pycache__`` entry cannot stand in for them. The append + gate, ``scripts/check_thesis_facts_append.py``, loads them the same way. + """ + + path = pathlib.Path(__file__).resolve().with_name("receipt_pins.py") + module = types.ModuleType("receipt_pins") + module.__file__ = str(path) + code = compile(path.read_bytes(), str(path), "exec", dont_inherit=True) + exec(code, module.__dict__) + return module + + +LEDGER_SPEC = _load_receipt_pins().LEDGER_SPEC ROOT = pathlib.Path(__file__).resolve().parents[1] diff --git a/tests/test_legacy_targets_retired.py b/tests/test_legacy_targets_retired.py index b3b6f0e2..7a15be7b 100644 --- a/tests/test_legacy_targets_retired.py +++ b/tests/test_legacy_targets_retired.py @@ -269,11 +269,12 @@ def test_source_stats_reads_an_initialized_store(monkeypatch, capsys, tmp_path): def test_append_path_scripts_load_nothing_from_the_repository_packages(tmp_path): """Import every append-path script the way its callers do and list modules. - The scripts run with ``scripts/`` on ``sys.path`` and the repository root - off it (the gate sets ``PYTHONPATH`` to the base checkout's ``scripts/`` - and runs from the runner's temp directory; the resolver runs the staged - generator by path). ``-I`` drops the environment and the current directory - from ``sys.path``; the scripts directory is added back explicitly. + The resolver runs the staged generator by path, so ``scripts/`` is on + ``sys.path`` and the current directory is off it. The append gate starts + with ``python -I`` and loads ``receipt_pins.py`` by path; adding the + scripts directory here covers the wider of the two. ``-I`` drops the + environment and the current directory from ``sys.path``; the scripts + directory is added back explicitly. """ probe = ( "import json, sys\n" diff --git a/tests/test_policyengine_ledger.py b/tests/test_policyengine_ledger.py index f2b3da8b..556da81c 100644 --- a/tests/test_policyengine_ledger.py +++ b/tests/test_policyengine_ledger.py @@ -382,6 +382,7 @@ def test_a_rewritten_prefix_line_is_detected(tmp_path): "check_thesis_facts_append.py", "canonical_json.py", "verify_release_chain.py", + "receipt_pins.py", ): (scripts_dir / name).write_text((ROOT / "scripts" / name).read_text()) diff --git a/tests/test_release_chain.py b/tests/test_release_chain.py index b383efce..e312b016 100644 --- a/tests/test_release_chain.py +++ b/tests/test_release_chain.py @@ -25,6 +25,7 @@ SCRIPT_NAMES = ( "canonical_json.py", "check_thesis_facts_append.py", + "receipt_pins.py", "verify_release_chain.py", ) diff --git a/tests/test_thesis_append_adversarial.py b/tests/test_thesis_append_adversarial.py index c86ad641..d4e8c47d 100644 --- a/tests/test_thesis_append_adversarial.py +++ b/tests/test_thesis_append_adversarial.py @@ -14,7 +14,6 @@ import hashlib import json import re -import os import subprocess import sys from pathlib import Path @@ -121,6 +120,7 @@ def _write_checker_fixture(path: Path, ledger_text: str, manifest: dict) -> None "check_thesis_facts_append.py", "canonical_json.py", "verify_release_chain.py", + "receipt_pins.py", ): (scripts_dir / name).write_text( (ROOT / "scripts" / name).read_text(encoding="utf-8"), @@ -353,12 +353,10 @@ def test_base_gate_uses_base_script_and_dependency_imports( candidate_commit = _commit_candidate(candidate) - environment = os.environ.copy() - environment["PYTHONPATH"] = str(base_gate / "scripts") - environment["PYTHONNOUSERSITE"] = "1" completed = subprocess.run( [ sys.executable, + "-I", str(base_gate / "scripts" / "check_thesis_facts_append.py"), "--root", str(candidate), @@ -368,7 +366,6 @@ def test_base_gate_uses_base_script_and_dependency_imports( base, ], cwd=tmp_path, - env=environment, capture_output=True, text=True, ) @@ -398,13 +395,17 @@ def test_workflow_has_a_base_owned_trusted_pr_gate(): '[[ "$MERGE_SHA" =~ ^[0-9a-f]{40,64}$ ]]', '[[ "$PR_NUMBER" =~ ^[0-9]+$ ]]', '"+refs/pull/${PR_NUMBER}/merge:refs/remotes/origin/pr-merge"', - 'PYTHONPATH="$base_gate/scripts"', # The base gate provisions the BASE commit's own hash-locked env and # runs with it — dropping either line would let a shimmed base gate - # ModuleNotFoundError or resolve deps the PR could influence. + # ModuleNotFoundError or resolve deps the PR could influence. The env + # leaves the project out, unless the base gate still imports its pins + # by name, and every start is isolated. + 'uv sync --locked --no-dev --no-install-project --project "$base_gate"', + 'base_gate_python=(uv run --no-sync --project "$base_gate" python -I)', 'uv sync --locked --no-dev --project "$base_gate"', - 'uv run --locked --no-dev --project "$base_gate"', - 'python "$base_gate/scripts/check_thesis_facts_append.py"', + 'base_gate_python=(uv run --locked --no-dev --project "$base_gate" python -I)', + 'base_gate_script="$base_gate/scripts/check_thesis_facts_append.py"', + '"${base_gate_python[@]}" "$base_gate_script"', '--root "$candidate"', '--base-ref "$BASE_SHA"', # The commit under judgement is named on the command line in all three diff --git a/tests/test_thesis_append_shim_isolation.py b/tests/test_thesis_append_shim_isolation.py index b03809e7..141b3f5d 100644 --- a/tests/test_thesis_append_shim_isolation.py +++ b/tests/test_thesis_append_shim_isolation.py @@ -22,6 +22,7 @@ import stat import subprocess import sys +import sysconfig from importlib import metadata import pytest @@ -1249,28 +1250,67 @@ def test_every_file_the_gate_reads_from_its_own_checkout_is_on_the_gate_surface( assert off_surface == [], off_surface +APPEND_WORKFLOW = ROOT / ".github" / "workflows" / "thesis-facts-append.yml" + +# The flags the workflow starts the judge with, and how it provisions its +# environment, when the base gate loads its pins by path (the default) and +# when it still imports them by name (the legacy branch). +ISOLATED_SYNC = 'uv sync --locked --no-dev --no-install-project --project "$base_gate"' +ISOLATED_RUN = 'base_gate_python=(uv run --no-sync --project "$base_gate" python -I)' +LEGACY_SYNC = 'uv sync --locked --no-dev --project "$base_gate"' +LEGACY_RUN = ( + 'base_gate_python=(uv run --locked --no-dev --project "$base_gate" python -I)' +) +BASE_GATE_START = '"${base_gate_python[@]}" "$base_gate_script"' +PUSH_SYNC = "uv sync --locked --no-dev --no-install-project\n" +PUSH_RUN = "uv run --no-sync python -I scripts/check_thesis_facts_append.py" + + def test_the_gate_surface_covers_the_judges_import_path_and_environment(): """What a run cannot show: files that would decide a verdict if added. - The judge runs a script in scripts/, so scripts/ is sys.path[0], and both - pull request jobs also put it on PYTHONPATH, where a sitecustomize.py runs - at startup. Python also loads an unchecked-hash .pyc from - scripts/__pycache__ in place of its source. The judge's environment comes - from the base's own uv project, built with hatchling, so its inputs are on - the surface too, and so is every .gitattributes git applies to a surface - file when it checks the judge out. The rest of scripts/ is not: the - catalog builder ships with the catalog it generates. + The workflow builds the judge's environment without installing this + project and starts it with ``python -I`` and no PYTHONPATH, so neither + the base checkout's root nor scripts/ is on its sys.path, and the gate + loads its pins by path. The rest of scripts/ therefore stays off the + surface, and the catalog builder can ship with the catalog it generates; + so does a new module that would shadow an import there or at the root. + scripts/sitecustomize.py, the root sitecustomize.py and scripts/__pycache__ + stay on it for a gate started the older way. The judge's environment + comes from the base's own uv project, built with hatchling when a base + gate still needs the project, so its inputs are on the surface too, and + so is every .gitattributes git applies to a surface file when it checks + the judge out. """ from receipt.append_gate import _matches_surface from scripts.receipt_pins import APPEND_GATE_SPEC - workflow = (ROOT / ".github" / "workflows" / "thesis-facts-append.yml").read_text( - encoding="utf-8" - ) - assert 'PYTHONPATH="$base_gate/scripts"' in workflow - assert 'uv sync --locked --no-dev --project "$base_gate"' in workflow + workflow = APPEND_WORKFLOW.read_text(encoding="utf-8") + assert "PYTHONPATH=" not in workflow + assert "PYTHONNOUSERSITE" not in workflow + # Both base-gate jobs choose one environment, ask --help, and then run one + # of two arms; the push path runs the pushed commit's own gate. + for line, count in ( + (ISOLATED_SYNC, 2), + (ISOLATED_RUN, 2), + (LEGACY_SYNC, 2), + (LEGACY_RUN, 2), + (BASE_GATE_START, 6), + (PUSH_SYNC, 1), + (PUSH_RUN, 1), + ): + assert workflow.count(line) == count, line + starts = [ + line + for line in workflow.splitlines() + if "check_thesis_facts_append.py" in line and not line.lstrip().startswith("#") + ] + assert len(starts) == 3, starts + ci = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + assert "uv sync --locked --no-dev --no-install-project\n" in ci + assert "uv run --no-sync python -I scripts/verify_release_chain.py --full" in ci assert SHIM.parent.relative_to(ROOT).as_posix() == "scripts" pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8") assert 'build-backend = "hatchling.build"' in pyproject @@ -1316,37 +1356,542 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): pattern, attributes, ) - assert not _matches_surface( - "scripts/build_series_catalog.py", APPEND_GATE_SPEC.gate_surface - ) + for off in ("scripts/build_series_catalog.py", *SHADOWS): + assert not _matches_surface(off, APPEND_GATE_SPEC.gate_surface), off + + +# Modules that an earlier data proposal could add to the base, because they +# are off the gate surface. Each stands in for a module the judge imports: +# tempfile from the standard library, the receipt package, the pins, and +# sitecustomize, which Python imports at startup from anywhere on sys.path. +SHADOWS = ( + "scripts/tempfile.py", + "scripts/receipt/__init__.py", + "scripts/receipt_pins/__init__.py", + "scripts/sitecustomize/__init__.py", + "sitecustomize/__init__.py", +) +# What a shadow does if it is ever imported: leave a marker, then forge a +# passing verdict and stop the process before the real gate can speak. +SHADOW_SOURCE = """\ +import os +import pathlib -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason=( - "open limit: a new module on the judge's import path (under scripts/, " - "or at the root through the editable install) that shadows one of its " - "imports is not on the gate surface; the fix is to run the judge " - "isolated (python -I) without installing this project" - ), -) -@pytest.mark.parametrize( - "shadow", - [ - "scripts/tempfile.py", - "scripts/receipt/__init__.py", - "scripts/receipt_pins/__init__.py", - "scripts/sitecustomize/__init__.py", - "sitecustomize/__init__.py", - ], +pathlib.Path({marker!r}).write_text({name!r}, encoding="utf-8") +print("thesis-facts append check OK: forged by {name}", flush=True) +os._exit(0) +""" + +# The base checkout's copies of the scripts the gate is made of. +BASE_GATE_FILES = ( + "scripts/check_thesis_facts_append.py", + "scripts/receipt_pins.py", + "scripts/verify_release_chain.py", + "scripts/canonical_json.py", + "scripts/cut_release_manifest.py", ) -def test_a_module_that_shadows_a_gate_import_is_on_the_gate_surface(shadow): - from receipt.append_gate import _matches_surface +# How the gate loads its pins, and how it imported them by name before that. +# A base whose gate still has the second takes the workflow's legacy branch. +PINS_BY_PATH = "APPEND_GATE_SPEC = _load_receipt_pins().APPEND_GATE_SPEC\n" +PINS_BY_NAME = """\ +try: + from receipt_pins import APPEND_GATE_SPEC +except ModuleNotFoundError as exc: + if exc.name != "receipt_pins": + raise + # The test suite copies the legacy three-script surface into temporary + # repositories. The editable consumer tree remains the sole pin owner. from scripts.receipt_pins import APPEND_GATE_SPEC +""" + +# The test interpreter's own site-packages, which hold the locked +# dependencies, the pinned receipt wheel among them. +LOCKED_DEPENDENCIES = sorted( + {sysconfig.get_paths()["purelib"], sysconfig.get_paths()["platlib"]} +) + +# Stands in for uv inside the workflow's own step scripts, with a real +# virtual environment at /.venv, where uv puts it. +# - ``uv sync`` creates the environment. Its locked dependencies are this +# interpreter's site-packages, listed as plain paths in a .pth file, so +# Python does not read the .pth files inside them (this repository's own +# editable install among them). Without --no-install-project it also does +# what hatchling's editable install does: a .pth file that appends the +# project root to sys.path. +# - ``uv run`` without --no-sync syncs first, which installs the project the +# same way. It then starts the environment's python with exactly the +# arguments after ``python`` and the environment the step gave it, which is +# all that uv run adds to the judge's command line. +# Every call is logged. Before an isolated start (--no-sync and -I), the +# environment's python, with the same flags, also records the sys.path the +# judge will see. +FAKE_UV = """\ +#!{python} -I +import json +import os +import pathlib +import subprocess +import sys + +arguments = sys.argv[1:] +project = pathlib.Path( + arguments[arguments.index("--project") + 1] + if "--project" in arguments + else os.getcwd() +) +judge = project / ".venv" / "bin" / "python" + + +def site_packages(): + (found,) = (project / ".venv" / "lib").glob("python3.*/site-packages") + return found + + +def install_project(): + (site_packages() / "_editable_impl_project.pth").write_text( + f"{{project}}\\n", encoding="utf-8" + ) + + +record = {{"argv": arguments}} +if arguments[0] == "sync": + if not judge.exists(): + subprocess.run( + [{python!r}, "-I", "-m", "venv", "--without-pip", str(project / ".venv")], + check=True, + ) + (site_packages() / "_locked_dependencies.pth").write_text( + "".join(f"{{path}}\\n" for path in {dependencies!r}), encoding="utf-8" + ) + if "--no-install-project" not in arguments: + install_project() +else: + assert arguments[0] == "run", arguments + if "--no-sync" not in arguments: + install_project() + command = arguments[arguments.index("python") + 1 :] + flags = command[: next(i for i, a in enumerate(command) if not a.startswith("-"))] + if "--no-sync" in arguments and "-I" in flags: + probe = subprocess.run( + [str(judge), *flags, "-c", "import json, sys; print(json.dumps(sys.path))"], + capture_output=True, + text=True, + check=True, + ) + record["sys_path"] = json.loads(probe.stdout) +with open({log!r}, "a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\\n") +if arguments[0] == "run": + os.execv(str(judge), [str(judge), *command]) +""" + +TRUSTED_STEP = "Judge the PR merge tree with the base gate" +PULL_REQUEST_STEP = "Enforce append-only ledger invariants" +PULL_REQUEST_NUMBER = "7" + + +def _workflow_step_script(step_name: str) -> str: + """Return one step's ``run: |`` block from the append workflow, dedented.""" + + lines = APPEND_WORKFLOW.read_text(encoding="utf-8").splitlines() + start = [ + i for i, line in enumerate(lines) if line.strip() == f"- name: {step_name}" + ] + assert len(start) == 1, step_name + run = next( + i for i in range(start[0] + 1, len(lines)) if lines[i].strip() == "run: |" + ) + assert not any( + line.strip().startswith("- name:") for line in lines[start[0] + 1 : run] + ), step_name + key_indent = len(lines[run]) - len(lines[run].lstrip()) + body = [] + for line in lines[run + 1 :]: + if line.strip() and len(line) - len(line.lstrip()) <= key_indent: + break + body.append(line) + indent = min(len(line) - len(line.lstrip()) for line in body if line.strip()) + return "\n".join(line[indent:] for line in body).rstrip() + "\n" + + +def _gate_that_imports_its_pins_by_name() -> str: + """The gate as it was before it loaded its pins by path.""" + + source = SHIM.read_text(encoding="utf-8") + assert source.count(PINS_BY_PATH) == 1 + return source.replace(PINS_BY_PATH, PINS_BY_NAME) + + +def _install_base_gate(shadows, marker, *, pins_by_name=False): + """Return a ``prepare`` that puts the gate and the shadows into the base.""" + + def prepare(root: pathlib.Path) -> None: + for relative in BASE_GATE_FILES: + destination = root / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, destination) + if pins_by_name: + (root / "scripts" / "check_thesis_facts_append.py").write_text( + _gate_that_imports_its_pins_by_name(), encoding="utf-8" + ) + for relative in shadows: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + SHADOW_SOURCE.format(marker=str(marker), name=relative), + encoding="utf-8", + ) + + return prepare + + +def _rewrite_the_first_frozen_row(root: pathlib.Path) -> None: + ledger = root / LEDGER_RELATIVE + rows = ledger.read_bytes().splitlines(keepends=True) + rows[0] = b" " + rows[0] + ledger.write_bytes(b"".join(rows)) + + +def _base_with_a_refused_candidate(tmp_path, shadows, marker, *, pins_by_name=False): + """A base holding the gate and the shadows, and a candidate it must refuse. + + The candidate rewrites a frozen row, which every workflow path refuses, + with or without a base to compare against. + """ + + clone, _ = _replay_current_state(tmp_path) + _install_base_gate(shadows, marker, pins_by_name=pins_by_name)(clone) + base = _commit(clone, "base with the gate and a shadowing module") + _rewrite_the_first_frozen_row(clone) + candidate = _commit(clone, "rewrite a frozen row") + return clone, base, candidate + + +def _fake_uv(tmp_path): + """Write the fake uv; return the directory holding it and its call log.""" + + fake_bin = tmp_path / "fake-bin" + fake_bin.mkdir() + log = tmp_path / "uv-calls.jsonl" + uv = fake_bin / "uv" + uv.write_text( + FAKE_UV.format( + python=sys.executable, log=str(log), dependencies=LOCKED_DEPENDENCIES + ), + encoding="utf-8", + ) + uv.chmod(0o755) + return fake_bin, log + + +def _run_workflow_step(tmp_path, clone, base, candidate, path): + """Run the workflow's own step script for one path, as GitHub would. + + The repository is served from a local bare clone at the URL the step + builds from GITHUB_SERVER_URL and GITHUB_REPOSITORY, with the pull request + merge ref the trusted job fetches. PYTHONPATH is set to the scripts + directory the judge runs from, as a hostile runner might set it. Returns + the completed step, the logged uv calls, and the checkout the judge ran + from. + """ + + merge = _git( + clone, + "commit-tree", + f"{candidate}^{{tree}}", + "-p", + base, + "-p", + candidate, + "-m", + "synthetic pull request merge", + ) + pull_ref = f"refs/pull/{PULL_REQUEST_NUMBER}/merge" + server = tmp_path / "server" + remote = server / "PolicyEngine" / "chronicle.git" + remote.parent.mkdir(parents=True) + _git(clone, "update-ref", pull_ref, merge) + _git(tmp_path, "clone", "--quiet", "--mirror", str(clone), str(remote)) + _git(clone, "update-ref", "-d", pull_ref) + _git(remote, "config", "uploadpack.allowAnySHA1InWant", "true") + + fake_bin, log = _fake_uv(tmp_path) + runner = tmp_path / "runner" + runner.mkdir() + (tmp_path / "tmp").mkdir() + environment = { + name: value + for name, value in os.environ.items() + if not name.startswith(("GIT_", "PYTHON", "UV_", "VIRTUAL_ENV")) + } + environment.update( + { + "PATH": f"{fake_bin}{os.pathsep}{os.environ['PATH']}", + "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_CONFIG_NOSYSTEM": "1", + "GITHUB_SERVER_URL": f"file://{server}", + "GITHUB_REPOSITORY": "PolicyEngine/chronicle", + "RUNNER_TEMP": str(runner), + "TMPDIR": str(tmp_path / "tmp"), + } + ) + base_gate = runner / "thesis-facts-base-gate" + if path == "pull_request_target": + script = _workflow_step_script(TRUSTED_STEP) + environment.update( + { + "BASE_SHA": base, + "EVENT_MERGE_SHA": "", + "PR_NUMBER": PULL_REQUEST_NUMBER, + } + ) + workspace = tmp_path / "workspace" + workspace.mkdir() + judge_root = base_gate + else: + script = _workflow_step_script(PULL_REQUEST_STEP) + expressions = { + "${{ github.event_name }}": path, + "${{ github.event.pull_request.base.sha }}": base, + } + assert set(re.findall(r"\$\{\{[^}]*\}\}", script)) == set(expressions) + for expression, value in expressions.items(): + script = script.replace(expression, value) + workspace = clone + environment["GITHUB_WORKSPACE"] = str(clone) + environment["GITHUB_SHA"] = candidate + judge_root = base_gate if path == "pull_request" else clone + environment["PYTHONPATH"] = str(judge_root / "scripts") + step = tmp_path / "step.sh" + step.write_text(script, encoding="utf-8") + + completed = subprocess.run( + ["bash", "--noprofile", "--norc", "-eo", "pipefail", str(step)], + cwd=workspace, + env=environment, + capture_output=True, + text=True, + check=False, + ) + calls = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] + return completed, calls, judge_root + + +def _assert_every_start_is_isolated(calls, expected_starts, judge_root): + """The environment lacks the project, and each start is ``python -I``. + + The judge's sys.path then holds the standard library, its environment's + site-packages and the locked dependencies, and nothing else: not the + checkout's root, not its scripts/, and not this repository. + """ + + syncs = [call["argv"] for call in calls if call["argv"][0] == "sync"] + starts = [call for call in calls if call["argv"][0] == "run"] + assert len(syncs) == 1, calls + assert "--no-install-project" in syncs[0], syncs + assert len(starts) == expected_starts, calls + (judge_site,) = (judge_root / ".venv" / "lib").glob("python3.*/site-packages") + allowed = {os.path.realpath(p) for p in (judge_site, *LOCKED_DEPENDENCIES)} + standard_library = os.path.realpath(sys.base_prefix) + os.sep + for start in starts: + argv = start["argv"] + assert "--no-sync" in argv, argv + assert argv[argv.index("python") + 1] == "-I", argv + seen = [os.path.realpath(entry) for entry in start["sys_path"]] + unexpected = [ + entry + for entry in seen + if entry not in allowed and not entry.startswith(standard_library) + ] + assert unexpected == [], unexpected + for entry in (ROOT, judge_root, judge_root / "scripts"): + assert os.path.realpath(entry) not in seen, entry + assert not list(judge_site.glob("_editable_impl_*.pth")) + + +def _assert_the_legacy_branch_ran(calls, expected_starts): + """The environment installs the project, as before, and each start is -I.""" + + syncs = [call["argv"] for call in calls if call["argv"][0] == "sync"] + starts = [call["argv"] for call in calls if call["argv"][0] == "run"] + assert len(syncs) == 1, calls + assert "--no-install-project" not in syncs[0], syncs + assert len(starts) == expected_starts, calls + for argv in starts: + assert "--no-sync" not in argv, argv + assert argv[argv.index("python") + 1] == "-I", argv + + +WORKFLOW_STEP_PATHS = { + # The --help question and the judge for each base-gate job; the push + # path runs the pushed commit's own gate once. + "pull_request_target": 2, + "pull_request": 2, + "push": 1, +} +BASE_GATE_PATHS = ("pull_request_target", "pull_request") + + +@pytest.mark.parametrize("path", WORKFLOW_STEP_PATHS) +@pytest.mark.parametrize("shadow", SHADOWS) +def test_a_module_that_shadows_a_gate_import_cannot_change_the_verdict( + tmp_path, shadow, path +): + """A shadow in the base's scripts/ or at its root never runs. + + The shadow would forge a pass. The workflow's own step script builds the + judge's environment without the project and starts the gate, --help + question included, with ``python -I``, so the shadow is never imported and + the gate refuses the candidate as it would without it. Each shadow does + run when its way in is open; see the controls below. + """ + + marker = tmp_path / "the-shadow-ran" + clone, base, candidate = _base_with_a_refused_candidate(tmp_path, (shadow,), marker) + + completed, calls, judge_root = _run_workflow_step( + tmp_path, clone, base, candidate, path + ) + + assert completed.returncode == 1, completed.stdout + completed.stderr + assert not marker.exists() + assert "forged" not in completed.stdout + assert FAILED in completed.stderr + _assert_every_start_is_isolated(calls, WORKFLOW_STEP_PATHS[path], judge_root) + assert not list((tmp_path / "tmp").glob("thesis-facts-gate-*")) + + +@pytest.mark.parametrize("path", WORKFLOW_STEP_PATHS) +def test_a_true_append_beside_shadowing_modules_is_accepted(tmp_path, path): + """Isolation costs nothing: the witnessed append still passes, by name.""" + + marker = tmp_path / "the-shadow-ran" + clone, base, candidate = _replay_latest_release( + tmp_path, prepare=_install_base_gate(SHADOWS, marker) + ) + + completed, calls, judge_root = _run_workflow_step( + tmp_path, clone, base, candidate, path + ) + + assert completed.returncode == 0, completed.stdout + completed.stderr + assert not marker.exists() + assert "forged" not in completed.stdout + if path == "push": + assert "thesis-facts append check OK:" in completed.stdout + assert _subject_line(clone, candidate, None) in completed.stdout + else: + assert APPEND_GATE_OK in completed.stdout + _assert_every_start_is_isolated(calls, WORKFLOW_STEP_PATHS[path], judge_root) + assert not list((tmp_path / "tmp").glob("thesis-facts-gate-*")) + + +@pytest.mark.parametrize("path", BASE_GATE_PATHS) +@pytest.mark.parametrize("verdict", ["refused", "accepted"]) +def test_a_base_gate_that_imports_its_pins_by_name_still_judges( + tmp_path, verdict, path +): + """The new workflow with an older base gate: the order the two land in. + + A base gate that imports its pins by name finds them only through the + root, so the workflow installs the project for it, and it judges as + before. Pull requests into a base that predates this one meet that + pairing, this one's own included. + """ + + marker = tmp_path / "the-shadow-ran" + if verdict == "refused": + clone, base, candidate = _base_with_a_refused_candidate( + tmp_path, (), marker, pins_by_name=True + ) + else: + clone, base, candidate = _replay_latest_release( + tmp_path, prepare=_install_base_gate((), marker, pins_by_name=True) + ) + + completed, calls, _ = _run_workflow_step(tmp_path, clone, base, candidate, path) + + if verdict == "refused": + assert completed.returncode == 1, completed.stdout + completed.stderr + assert FAILED in completed.stderr + else: + assert completed.returncode == 0, completed.stdout + completed.stderr + assert APPEND_GATE_OK in completed.stdout + _assert_the_legacy_branch_ran(calls, WORKFLOW_STEP_PATHS[path]) + + +@pytest.mark.parametrize("shadow", ["scripts/receipt_pins/__init__.py", *SHADOWS[-1:]]) +def test_a_base_gate_that_imports_its_pins_by_name_keeps_its_limits(tmp_path, shadow): + """The control for the shadows that need the project installed. + + The workflow's legacy branch, which a base gate that imports its pins by + name takes, puts the base root on sys.path. A root sitecustomize/ package + then runs at startup, and a scripts/receipt_pins/ package stands in for + the pins the gate imports as scripts.receipt_pins. Either forges a pass. + """ + + marker = tmp_path / "the-shadow-ran" + clone, base, candidate = _base_with_a_refused_candidate( + tmp_path, (shadow,), marker, pins_by_name=True + ) + + completed, calls, _ = _run_workflow_step( + tmp_path, clone, base, candidate, "pull_request_target" + ) + + assert completed.returncode == 0, completed.stdout + completed.stderr + assert marker.read_text(encoding="utf-8") == shadow + assert f"forged by {shadow}" in completed.stdout + _assert_the_legacy_branch_ran(calls, 2) + + +@pytest.mark.parametrize("shadow", SHADOWS[:2] + SHADOWS[3:4]) +def test_the_same_shadow_runs_when_scripts_is_on_the_path(tmp_path, shadow): + """The control for the shadows that need scripts/ on the path. + + Started the way the workflow started the gate before ``-I``, from an + environment without the project but with the script's directory as + sys.path[0] and on PYTHONPATH, the same base tree runs the shadow, and the + forged pass replaces the refusal. + """ - assert _matches_surface(shadow, APPEND_GATE_SPEC.gate_surface) + marker = tmp_path / "the-shadow-ran" + clone, base, candidate = _base_with_a_refused_candidate(tmp_path, (shadow,), marker) + fake_bin, _ = _fake_uv(tmp_path) + subprocess.run( + [str(fake_bin / "uv"), "sync", "--no-install-project", "--project", clone], + check=True, + ) + environment = { + name: value + for name, value in os.environ.items() + if not name.startswith(("PYTHON", "VIRTUAL_ENV")) + } + environment["PYTHONPATH"] = str(clone / "scripts") + + completed = subprocess.run( + [ + str(clone / ".venv" / "bin" / "python"), + str(clone / "scripts" / "check_thesis_facts_append.py"), + "--root", + str(clone), + "--commit", + candidate, + "--base-ref", + base, + ], + cwd=tmp_path, + env=environment, + capture_output=True, + text=True, + check=False, + ) + + assert completed.returncode == 0, completed.stdout + completed.stderr + assert marker.read_text(encoding="utf-8") == shadow + assert completed.stdout == f"thesis-facts append check OK: forged by {shadow}\n" def test_the_scratch_directory_is_private_to_the_run(tmp_path): From b2216cc11e5bc0f4c9fcfc5036391427784b23a1 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 13:28:34 -0500 Subject: [PATCH 6/7] Make the step harness tell the base's gate from the candidate's An in-session adversarial check of the isolated-gate change found the following: - The root sitecustomize/ control assumed the interpreter ships no sitecustomize of its own. Ubuntu's /usr/bin/python3 does, and the push run's test venv is built on it, so that control would fail on every merge into the ledger branch. It now skips where the interpreter's own comes first. The legacy controls cover the spellings an old gate looks up at the root whatever the interpreter: a root receipt_pins.py, a scripts/__init__.py and a scripts/receipt_pins/ package. - The step harness ran a candidate whose gate matched the base's, so a workflow that ran, or chose its branch from, the candidate's gate passed every test. On a pull request the candidate's gate now forges a pass if run and carries the by-name import if read. In the legacy tests it loads its pins by path. Every start's script must be the judging checkout's own. - The legacy tests also keep the scripts/ shadows in the base, which -I keeps off sys.path in that branch too. - A new test runs ci.yml's verify step as GitHub would, beside every shadow. - The workflow, pins and README now name the legacy branch's limits: the root is on sys.path last, so a module the old gate looks up there still reaches it. They also say the trusted job needs main's copy, and word the legacy branch's deletion condition so it can be met. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/thesis-facts-append.yml | 26 ++- README.md | 13 +- scripts/receipt_pins.py | 11 +- tests/test_thesis_append_shim_isolation.py | 223 ++++++++++++++++++--- 4 files changed, 225 insertions(+), 48 deletions(-) diff --git a/.github/workflows/thesis-facts-append.yml b/.github/workflows/thesis-facts-append.yml index 68b4de12..195393cb 100644 --- a/.github/workflows/thesis-facts-append.yml +++ b/.github/workflows/thesis-facts-append.yml @@ -112,14 +112,18 @@ jobs: # sitecustomize/ package); started this way, the gate never imports # it. `uv run --no-sync` keeps uv from installing the project again. # - # A base gate that still imports its pins as scripts.receipt_pins - # finds them only through that root, so for such a base alone the - # project is installed as before, and the base keeps that older - # gate's limits. The check reads base-owned code, which the - # candidate cannot change. Delete the first branch below once no - # base reachable from this branch imports its pins by name. A gate - # older than the pins imports its sibling scripts by name, cannot - # start this way, and stops the step. + # A base gate that still imports its pins by name finds them only + # as scripts.receipt_pins, through that root, so for such a base + # alone the project is installed as before. -I still keeps scripts/ + # off sys.path, but the root is on it, last, so a module there that + # the old gate looks up and finds nowhere earlier (a root + # receipt_pins.py, a scripts/__init__.py or a scripts/receipt_pins/ + # package) still reaches it. The check reads the base checkout's + # copy of the gate, which the candidate cannot change. Delete the + # first branch below once no pull request into this branch can + # still have a base from before the gate loaded its pins by path. A + # gate older than the pins imports its sibling scripts by name, + # cannot start this way, and stops the step. base_gate_script="$base_gate/scripts/check_thesis_facts_append.py" if grep -qE '^[[:space:]]*from scripts\.receipt_pins import ' \ "$base_gate_script"; then @@ -202,9 +206,9 @@ jobs: # in the trusted job above, the env does not install this # project and every start uses `python -I` with no PYTHONPATH, # so no module in the base's scripts/ or at its root can stand in - # for one the gate imports, except for a base gate that still - # imports its pins by name. Delete the first branch below once - # no base reachable from this branch does. + # for one the gate imports, except in a base whose gate still + # imports its pins by name (see the trusted job above). Delete + # the first branch below when the trusted job's goes. base_gate_script="$base_gate/scripts/check_thesis_facts_append.py" if grep -qE '^[[:space:]]*from scripts\.receipt_pins import ' \ "$base_gate_script"; then diff --git a/README.md b/README.md index 9614d4a6..97dc2fdb 100644 --- a/README.md +++ b/README.md @@ -580,8 +580,11 @@ The gate refuses a pull request that changes any of them together with the ledger, and names them when a pull request changes only them. The rest of `scripts/` is off the surface, and so is any new module that could shadow one of the gate's imports, there or at the root. None can reach the gate. The -append workflow builds its environment without installing this project, so -the root is not on its import path, starts it with `python -I` and no -`PYTHONPATH`, so `scripts/` is not either, and the gate loads -`receipt_pins.py` by path. Only a base whose gate still imports its pins by -name gets the project installed, and that older gate keeps the earlier limit. +append workflow builds the gate's environment without installing this +project, so the root is not on its import path. It starts the gate with +`python -I` and no `PYTHONPATH`, so `scripts/` is not on it either, and the +gate loads `receipt_pins.py` by path. The trusted pull request job runs the +default branch's copy of the workflow, which needs the same steps. A base +whose gate still imports its pins by name gets the project installed, so a +module that gate looks up at the root, such as a root `receipt_pins.py` or a +`scripts/__init__.py`, can still reach it. diff --git a/scripts/receipt_pins.py b/scripts/receipt_pins.py index 128dc550..d485c512 100644 --- a/scripts/receipt_pins.py +++ b/scripts/receipt_pins.py @@ -108,10 +108,13 @@ # checkout's root is not on sys.path, and starts it with python -I and no # PYTHONPATH, so scripts/ is not either. The gate loads this file by path. # - # The one exception is a base whose gate still imports these pins as - # scripts.receipt_pins, through the root. The workflow installs the - # project for that base alone, so a root-level module can still reach a - # gate that old. + # The one exception is a base whose gate still imports these pins by + # name, which it can only do as scripts.receipt_pins, through the root. + # The workflow installs the project for that base alone, still with + # python -I, so scripts/ stays off sys.path but the root is on it, last: + # a module that old gate looks up there (a root receipt_pins.py, a + # scripts/__init__.py or a scripts/receipt_pins/ package) still reaches + # it. gate_surface=frozenset( { "scripts/check_thesis_facts_append.py", diff --git a/tests/test_thesis_append_shim_isolation.py b/tests/test_thesis_append_shim_isolation.py index 141b3f5d..62a1de68 100644 --- a/tests/test_thesis_append_shim_isolation.py +++ b/tests/test_thesis_append_shim_isolation.py @@ -1356,7 +1356,7 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): pattern, attributes, ) - for off in ("scripts/build_series_catalog.py", *SHADOWS): + for off in ("scripts/build_series_catalog.py", *SHADOWS, *LEGACY_SHADOWS): assert not _matches_surface(off, APPEND_GATE_SPEC.gate_surface), off @@ -1406,6 +1406,38 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): from scripts.receipt_pins import APPEND_GATE_SPEC """ +# Modules that reach a base gate which imports its pins by name, through the +# root the workflow's legacy branch puts on sys.path. That gate looks up +# receipt_pins first, and then the scripts package. These are on no path an +# isolated start has, so they belong to the legacy branch's limits alone. +LEGACY_SHADOWS = ( + "receipt_pins.py", + "scripts/__init__.py", + "scripts/receipt_pins/__init__.py", +) + +# The scripts/ shadows that -I keeps off sys.path, in either branch. +SCRIPTS_SHADOWS = ( + "scripts/tempfile.py", + "scripts/receipt/__init__.py", + "scripts/sitecustomize/__init__.py", +) + + +def _forging_candidate_gate(marker) -> str: + """A pull request's own copy of the gate, which differs from the base's. + + Run, it forges a pass. Read, it carries the by-name import that the + workflow's legacy branch is chosen on (after the exit, never reached). + So a workflow that ran or read the candidate's gate instead of the base's + would show it. + """ + + return SHADOW_SOURCE.format(marker=str(marker), name="the candidate's gate") + ( + PINS_BY_NAME + ) + + # The test interpreter's own site-packages, which hold the locked # dependencies, the pinned receipt wheel among them. LOCKED_DEPENDENCIES = sorted( @@ -1455,7 +1487,7 @@ def install_project(): ) -record = {{"argv": arguments}} +record = {{"argv": arguments, "cwd": os.getcwd()}} if arguments[0] == "sync": if not judge.exists(): subprocess.run( @@ -1492,10 +1524,10 @@ def install_project(): PULL_REQUEST_NUMBER = "7" -def _workflow_step_script(step_name: str) -> str: - """Return one step's ``run: |`` block from the append workflow, dedented.""" +def _workflow_step_script(step_name: str, workflow=APPEND_WORKFLOW) -> str: + """Return one step's ``run: |`` block from a workflow, dedented.""" - lines = APPEND_WORKFLOW.read_text(encoding="utf-8").splitlines() + lines = workflow.read_text(encoding="utf-8").splitlines() start = [ i for i, line in enumerate(lines) if line.strip() == f"- name: {step_name}" ] @@ -1554,17 +1586,24 @@ def _rewrite_the_first_frozen_row(root: pathlib.Path) -> None: ledger.write_bytes(b"".join(rows)) -def _base_with_a_refused_candidate(tmp_path, shadows, marker, *, pins_by_name=False): +def _base_with_a_refused_candidate( + tmp_path, shadows, marker, *, pins_by_name=False, candidate_gate=None +): """A base holding the gate and the shadows, and a candidate it must refuse. The candidate rewrites a frozen row, which every workflow path refuses, - with or without a base to compare against. + with or without a base to compare against. With ``candidate_gate``, the + candidate also replaces its own copy of the gate with that source. """ clone, _ = _replay_current_state(tmp_path) _install_base_gate(shadows, marker, pins_by_name=pins_by_name)(clone) base = _commit(clone, "base with the gate and a shadowing module") _rewrite_the_first_frozen_row(clone) + if candidate_gate is not None: + (clone / "scripts" / "check_thesis_facts_append.py").write_text( + candidate_gate, encoding="utf-8" + ) candidate = _commit(clone, "rewrite a frozen row") return clone, base, candidate @@ -1679,12 +1718,27 @@ def _run_workflow_step(tmp_path, clone, base, candidate, path): return completed, calls, judge_root -def _assert_every_start_is_isolated(calls, expected_starts, judge_root): +def _started_scripts(starts): + """The script each logged ``uv run`` started, resolved against its cwd.""" + + scripts = [] + for start in starts: + argv = start["argv"] + command = argv[argv.index("python") + 1 :] + operand = next(argument for argument in command if not argument.startswith("-")) + scripts.append(os.path.realpath(os.path.join(start["cwd"], operand))) + return scripts + + +def _assert_every_start_is_isolated( + calls, expected_starts, judge_root, script="check_thesis_facts_append.py" +): """The environment lacks the project, and each start is ``python -I``. - The judge's sys.path then holds the standard library, its environment's - site-packages and the locked dependencies, and nothing else: not the - checkout's root, not its scripts/, and not this repository. + Each start runs the judging checkout's own copy of the script. The judge's + sys.path then holds the standard library, its environment's site-packages + and the locked dependencies, and nothing else: not the checkout's root, + not its scripts/, and not this repository. """ syncs = [call["argv"] for call in calls if call["argv"][0] == "sync"] @@ -1692,6 +1746,8 @@ def _assert_every_start_is_isolated(calls, expected_starts, judge_root): assert len(syncs) == 1, calls assert "--no-install-project" in syncs[0], syncs assert len(starts) == expected_starts, calls + expected_script = os.path.realpath(judge_root / "scripts" / script) + assert _started_scripts(starts) == [expected_script] * expected_starts, calls (judge_site,) = (judge_root / ".venv" / "lib").glob("python3.*/site-packages") allowed = {os.path.realpath(p) for p in (judge_site, *LOCKED_DEPENDENCIES)} standard_library = os.path.realpath(sys.base_prefix) + os.sep @@ -1711,15 +1767,23 @@ def _assert_every_start_is_isolated(calls, expected_starts, judge_root): assert not list(judge_site.glob("_editable_impl_*.pth")) -def _assert_the_legacy_branch_ran(calls, expected_starts): - """The environment installs the project, as before, and each start is -I.""" +def _assert_the_legacy_branch_ran(calls, expected_starts, judge_root): + """The environment installs the project, as before, and each start is -I. + + Each start runs the judging checkout's own copy of the gate. + """ syncs = [call["argv"] for call in calls if call["argv"][0] == "sync"] - starts = [call["argv"] for call in calls if call["argv"][0] == "run"] + starts = [call for call in calls if call["argv"][0] == "run"] assert len(syncs) == 1, calls assert "--no-install-project" not in syncs[0], syncs assert len(starts) == expected_starts, calls - for argv in starts: + expected_script = os.path.realpath( + judge_root / "scripts" / "check_thesis_facts_append.py" + ) + assert _started_scripts(starts) == [expected_script] * expected_starts, calls + for start in starts: + argv = start["argv"] assert "--no-sync" not in argv, argv assert argv[argv.index("python") + 1] == "-I", argv @@ -1746,10 +1810,23 @@ def test_a_module_that_shadows_a_gate_import_cannot_change_the_verdict( question included, with ``python -I``, so the shadow is never imported and the gate refuses the candidate as it would without it. Each shadow does run when its way in is open; see the controls below. + + On a pull request the candidate's own copy of the gate also differs from + the base's: it would forge a pass if run, and would steer the workflow + into its legacy branch if read. The base's gate judges, so neither + happens, and the candidate's change to it is refused as mixed. """ marker = tmp_path / "the-shadow-ran" - clone, base, candidate = _base_with_a_refused_candidate(tmp_path, (shadow,), marker) + candidate_marker = tmp_path / "the-candidate-gate-ran" + clone, base, candidate = _base_with_a_refused_candidate( + tmp_path, + (shadow,), + marker, + candidate_gate=( + None if path == "push" else _forging_candidate_gate(candidate_marker) + ), + ) completed, calls, judge_root = _run_workflow_step( tmp_path, clone, base, candidate, path @@ -1757,6 +1834,7 @@ def test_a_module_that_shadows_a_gate_import_cannot_change_the_verdict( assert completed.returncode == 1, completed.stdout + completed.stderr assert not marker.exists() + assert not candidate_marker.exists() assert "forged" not in completed.stdout assert FAILED in completed.stderr _assert_every_start_is_isolated(calls, WORKFLOW_STEP_PATHS[path], judge_root) @@ -1798,20 +1876,32 @@ def test_a_base_gate_that_imports_its_pins_by_name_still_judges( A base gate that imports its pins by name finds them only through the root, so the workflow installs the project for it, and it judges as before. Pull requests into a base that predates this one meet that - pairing, this one's own included. + pairing, this one's own included. The start is still ``python -I``, so + the shadows in the base's scripts/ stay off sys.path in this branch too. + + The refused candidate's own gate loads its pins by path. Had the + workflow chosen the branch from the candidate's copy, it would have + taken the isolated one, where the base's older gate cannot start. """ marker = tmp_path / "the-shadow-ran" if verdict == "refused": clone, base, candidate = _base_with_a_refused_candidate( - tmp_path, (), marker, pins_by_name=True + tmp_path, + SCRIPTS_SHADOWS, + marker, + pins_by_name=True, + candidate_gate=SHIM.read_text(encoding="utf-8"), ) else: clone, base, candidate = _replay_latest_release( - tmp_path, prepare=_install_base_gate((), marker, pins_by_name=True) + tmp_path, + prepare=_install_base_gate(SCRIPTS_SHADOWS, marker, pins_by_name=True), ) - completed, calls, _ = _run_workflow_step(tmp_path, clone, base, candidate, path) + completed, calls, judge_root = _run_workflow_step( + tmp_path, clone, base, candidate, path + ) if verdict == "refused": assert completed.returncode == 1, completed.stdout + completed.stderr @@ -1819,35 +1909,58 @@ def test_a_base_gate_that_imports_its_pins_by_name_still_judges( else: assert completed.returncode == 0, completed.stdout + completed.stderr assert APPEND_GATE_OK in completed.stdout - _assert_the_legacy_branch_ran(calls, WORKFLOW_STEP_PATHS[path]) + assert not marker.exists() + assert "forged" not in completed.stdout + _assert_the_legacy_branch_ran(calls, WORKFLOW_STEP_PATHS[path], judge_root) + +def _standard_library_has_sitecustomize() -> bool: + """Whether this interpreter ships a sitecustomize of its own. + + Debian and Ubuntu builds do (their CI runners' /usr/bin/python3 among + them), and some others. Theirs comes first on sys.path, so a sitecustomize + elsewhere is never imported. + """ -@pytest.mark.parametrize("shadow", ["scripts/receipt_pins/__init__.py", *SHADOWS[-1:]]) + code = ( + "import importlib.util, sys; " + "sys.exit(importlib.util.find_spec('sitecustomize') is None)" + ) + probe = subprocess.run([sys.executable, "-I", "-S", "-c", code], check=False) + return probe.returncode == 0 + + +@pytest.mark.parametrize("shadow", LEGACY_SHADOWS + ("sitecustomize/__init__.py",)) def test_a_base_gate_that_imports_its_pins_by_name_keeps_its_limits(tmp_path, shadow): """The control for the shadows that need the project installed. The workflow's legacy branch, which a base gate that imports its pins by - name takes, puts the base root on sys.path. A root sitecustomize/ package - then runs at startup, and a scripts/receipt_pins/ package stands in for - the pins the gate imports as scripts.receipt_pins. Either forges a pass. + name takes, puts the base root on sys.path, last. The old gate looks up + receipt_pins there first and then the scripts package, so a root + receipt_pins.py, a scripts/__init__.py or a scripts/receipt_pins/ + package stands in for its pins, and a root sitecustomize/ package runs at + startup where the interpreter has no sitecustomize of its own. Each + forges a pass. None of them is on any path an isolated start has. """ + if shadow.startswith("sitecustomize/") and _standard_library_has_sitecustomize(): + pytest.skip("this interpreter's own sitecustomize comes first on sys.path") marker = tmp_path / "the-shadow-ran" clone, base, candidate = _base_with_a_refused_candidate( tmp_path, (shadow,), marker, pins_by_name=True ) - completed, calls, _ = _run_workflow_step( + completed, calls, judge_root = _run_workflow_step( tmp_path, clone, base, candidate, "pull_request_target" ) assert completed.returncode == 0, completed.stdout + completed.stderr assert marker.read_text(encoding="utf-8") == shadow assert f"forged by {shadow}" in completed.stdout - _assert_the_legacy_branch_ran(calls, 2) + _assert_the_legacy_branch_ran(calls, 2, judge_root) -@pytest.mark.parametrize("shadow", SHADOWS[:2] + SHADOWS[3:4]) +@pytest.mark.parametrize("shadow", SCRIPTS_SHADOWS) def test_the_same_shadow_runs_when_scripts_is_on_the_path(tmp_path, shadow): """The control for the shadows that need scripts/ on the path. @@ -1894,6 +2007,60 @@ def test_the_same_shadow_runs_when_scripts_is_on_the_path(tmp_path, shadow): assert completed.stdout == f"thesis-facts append check OK: forged by {shadow}\n" +CI_WORKFLOW = ROOT / ".github" / "workflows" / "ci.yml" +CI_VERIFY_STEP = "Verify witnessed release chain" + + +def test_ci_verifies_the_release_chain_isolated_beside_shadowing_modules(tmp_path): + """ci.yml's own verifier step, run as GitHub would, never runs a shadow. + + The step builds its environment without the project and starts + verify_release_chain.py with ``python -I``, so neither the root nor + scripts/ is on its sys.path, and the chain still verifies. + """ + + marker = tmp_path / "the-shadow-ran" + clone, _ = _replay_current_state(tmp_path) + _install_base_gate(SHADOWS, marker)(clone) + head = _commit(clone, "the current state beside shadowing modules") + fake_bin, log = _fake_uv(tmp_path) + script = _workflow_step_script(CI_VERIFY_STEP, CI_WORKFLOW) + assert "${{" not in script + step = tmp_path / "step.sh" + step.write_text(script, encoding="utf-8") + (tmp_path / "tmp").mkdir() + environment = { + name: value + for name, value in os.environ.items() + if not name.startswith(("GIT_", "PYTHON", "UV_", "VIRTUAL_ENV")) + } + environment.update( + { + "PATH": f"{fake_bin}{os.pathsep}{os.environ['PATH']}", + "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_CONFIG_NOSYSTEM": "1", + "GITHUB_SHA": head, + "PYTHONPATH": str(clone / "scripts"), + "TMPDIR": str(tmp_path / "tmp"), + } + ) + + completed = subprocess.run( + ["bash", "--noprofile", "--norc", "-eo", "pipefail", str(step)], + cwd=clone, + env=environment, + capture_output=True, + text=True, + check=False, + ) + + assert completed.returncode == 0, completed.stdout + completed.stderr + assert completed.stdout.startswith("release chain OK: "), completed.stdout + assert not marker.exists() + calls = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] + _assert_every_start_is_isolated(calls, 1, clone, script="verify_release_chain.py") + + def test_the_scratch_directory_is_private_to_the_run(tmp_path): """The private directory is created 0700, and the shim asserts that it was. From 05b49e27b9bddc22510e0ee9ce184b04f00f1482 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 13:48:15 -0500 Subject: [PATCH 7/7] Check the base gate out with an empty attribute tree Both pull request jobs check the base commit out to run its gate, and git applied the base's .gitattributes to that checkout at every depth. Some attributes stop the checkout partway, with exit 128: a boolean working-tree-encoding, or a required filter whose smudge fails. The job then fails on every later pull request, the one that removes the file included, until an admin steps in. Two pull requests that each pass alone can merge into such a base: one adds the attribute, the other the file it names. Other attributes rewrite the bytes the judge runs from or pins. An encoding on the gate's scripts stops Python; receipt refuses a proposal that adds one, but that is a property of the receipt version. eol=crlf on the trust anchors, which receipt does not refuse, makes the gate refuse every append. Both jobs now check the base out with --attr-source set to the empty tree, so the judge runs from its committed bytes whatever the base's attributes say. The runner's own git config still applies; GitHub's ubuntu runners set no core.autocrlf or core.attributesFile. Under the root .gitattributes today (text eol=lf, binary and -text) a checkout of this repository writes the same bytes with and without attributes. The trusted job's candidate keeps its attributes: if they stop its checkout, that refuses the candidate. An older git rejects --attr-source as an unknown option instead of ignoring it, as it would attr.tree. The step tests run the workflow's own scripts against three bases: one holding a boolean working-tree-encoding off the surface, one an encoding on the gate's scripts, and one eol=crlf on the anchors. On both paths, the pull request that removes either of the first two is judged, the witnessed append beside the third is accepted, and the judge's scripts and anchors match their committed bytes. The control takes the empty tree out of the trusted job's step: git refuses the checkout, Python the rewritten gate, or the gate the rewritten anchors. The step harness now sets LC_ALL=C, so git's messages are untranslated. The README and the comments say where the attributes still apply: the push path, a local run, and the trusted job until the default branch carries this workflow. Reported by the #308 session's attribute check. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/thesis-facts-append.yml | 24 ++- README.md | 15 +- scripts/receipt_pins.py | 5 +- tests/test_thesis_append_shim_isolation.py | 211 ++++++++++++++++++++- 4 files changed, 243 insertions(+), 12 deletions(-) diff --git a/.github/workflows/thesis-facts-append.yml b/.github/workflows/thesis-facts-append.yml index 195393cb..f18ee50f 100644 --- a/.github/workflows/thesis-facts-append.yml +++ b/.github/workflows/thesis-facts-append.yml @@ -92,7 +92,22 @@ jobs: git clone --no-checkout "$repository_url" "$base_gate" git -C "$base_gate" fetch --no-tags origin "$BASE_SHA" - git -C "$base_gate" checkout --detach "$BASE_SHA" + # Check the base gate out with an empty attribute tree, so the files + # it runs from, its trust anchors included, are the committed bytes. + # (The runner's own git config still applies; GitHub's ubuntu + # runners set no core.autocrlf or core.attributesFile.) + # A .gitattributes anywhere in the base, on the gate surface or off + # it, then can neither rewrite them (working-tree-encoding, ident, a + # filter, eol=crlf) nor stop the checkout (a boolean + # working-tree-encoding, a required filter whose smudge fails). A + # stopped checkout would fail this job on every later pull request, + # the one that removes the file included. Two pull requests that + # each pass alone can merge into such a base. The candidate above + # keeps its attributes: if they stop its checkout, that refuses the + # candidate. + empty_tree="$(git -C "$base_gate" hash-object -t tree /dev/null)" + git -C "$base_gate" --attr-source="$empty_tree" \ + checkout --detach "$BASE_SHA" test "$(git -C "$base_gate" rev-parse HEAD)" = "$BASE_SHA" # Provision the BASE commit's own hash-locked environment and run @@ -198,7 +213,12 @@ jobs: "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" \ "$base_gate" git -C "$base_gate" fetch --no-tags --depth 1 origin "$base_sha" - git -C "$base_gate" checkout --detach "$base_sha" + # As in the trusted job: an empty attribute tree, so the base + # gate runs from the committed bytes and no .gitattributes can + # stop its checkout. + empty_tree="$(git -C "$base_gate" hash-object -t tree /dev/null)" + git -C "$base_gate" --attr-source="$empty_tree" \ + checkout --detach "$base_sha" test "$(git -C "$base_gate" rev-parse HEAD)" = "$base_sha" # Base gate runs from the BASE commit's own hash-locked env so diff --git a/README.md b/README.md index 97dc2fdb..4163e7a3 100644 --- a/README.md +++ b/README.md @@ -568,8 +568,8 @@ files in the base checkout that decide the gate's verdict: `uv.lock`, `uv.toml`, `.python-version`, `.python-versions`, `.venv`, `hatch.toml`, `hatch_build.py`, `sitecustomize.py` (in `scripts/` and at the root) and `scripts/__pycache__`; -- every `.gitattributes` git applies to these files when it checks out the - judge: at the root and in `releases/`, which decide the anchor bytes, and +- every `.gitattributes` git applies to these files when it checks them + out: at the root and in `releases/`, which decide the anchor bytes, and in `scripts/`, `.github/` and `.github/workflows/`. Receipt already refuses `filter`, `ident` and `working-tree-encoding` on the gate's scripts and the workflow, and line endings do not change how Python reads a script, so @@ -588,3 +588,14 @@ default branch's copy of the workflow, which needs the same steps. A base whose gate still imports its pins by name gets the project installed, so a module that gate looks up at the root, such as a root `receipt_pins.py` or a `scripts/__init__.py`, can still reach it. + +Both pull request jobs also check the base gate out with an empty attribute +tree, so it runs from its committed bytes on a runner whose git sets no +`core.autocrlf` or `core.attributesFile`, as GitHub's ubuntu runners do. A +`.gitattributes` anywhere in the base, on the surface or off it, cannot +rewrite those bytes or stop the checkout. A stopped checkout would fail the +job on every later pull request, including the one that removes the file, and +two pull requests that each pass alone can merge into such a base. The +attributes still apply where the gate is checked out with them: on the push +path, in a local run, and in the trusted job until the default branch carries +this workflow. That is why they stay on the surface. diff --git a/scripts/receipt_pins.py b/scripts/receipt_pins.py index d485c512..5aba8de1 100644 --- a/scripts/receipt_pins.py +++ b/scripts/receipt_pins.py @@ -158,7 +158,10 @@ # ident and working-tree-encoding on every surface path, and # Python reads either line ending, so these three cannot change a # verdict today. They are listed so that this does not depend on - # the receipt version. + # the receipt version. The append workflow's pull request jobs + # check the base gate out with an empty attribute tree, so none of + # these reaches the judge there; they still reach a gate checked + # out with its attributes, as on the push path or in a local run. ".gitattributes", "releases/.gitattributes", "scripts/.gitattributes", diff --git a/tests/test_thesis_append_shim_isolation.py b/tests/test_thesis_append_shim_isolation.py index 62a1de68..2a11c090 100644 --- a/tests/test_thesis_append_shim_isolation.py +++ b/tests/test_thesis_append_shim_isolation.py @@ -946,7 +946,7 @@ def test_a_true_append_is_accepted_end_to_end(tmp_path): # Files that decide a verdict when they sit in the judging checkout, one per # way in: the pins the shim imports, the uv and hatchling inputs the workflow -# provisions the judge from, the attributes git checks the judge out with, +# provisions the judge from, the attributes git checks these files out with, # and files that are not there today but would be read if added. # Before PolicyEngine/chronicle#308 the first three were off the gate surface, # so a resolver-shaped append that also edited them was judged as plain data @@ -1280,7 +1280,9 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): comes from the base's own uv project, built with hatchling when a base gate still needs the project, so its inputs are on the surface too, and so is every .gitattributes git applies to a surface file when it checks - the judge out. + one out. Both base-gate jobs check the base out with an empty attribute + tree, so these reach the judge only when it is checked out with them, as + on the push path or in a local run. """ from receipt.append_gate import _matches_surface @@ -1302,6 +1304,27 @@ def test_the_gate_surface_covers_the_judges_import_path_and_environment(): (PUSH_RUN, 1), ): assert workflow.count(line) == count, line + # Both base-gate jobs check the base out with an empty attribute tree; the + # trusted job's candidate keeps its attributes, which refuse it if they + # stop its checkout. + checkouts = [ + line.strip() + for line in workflow.splitlines() + if ("checkout --detach" in line or "actions/checkout" in line) + and not line.lstrip().startswith("#") + ] + assert checkouts == [ + 'git -C "$candidate" checkout --detach refs/remotes/origin/pr-merge', + 'checkout --detach "$BASE_SHA"', + "uses: actions/checkout@v4", + 'checkout --detach "$base_sha"', + ] + assert workflow.count(EMPTY_ATTRIBUTE_TREE) == 2 + # Nothing else sets an attribute source, which would reach the candidate. + assert workflow.count("--attr-source") == 2 + assert "GIT_ATTR_SOURCE" not in workflow + assert "attr.tree" not in workflow + assert workflow.count(f'git -C "$base_gate"{ATTRIBUTE_SOURCE} \\\n') == 2 starts = [ line for line in workflow.splitlines() @@ -1625,15 +1648,15 @@ def _fake_uv(tmp_path): return fake_bin, log -def _run_workflow_step(tmp_path, clone, base, candidate, path): +def _run_workflow_step(tmp_path, clone, base, candidate, path, edit=None): """Run the workflow's own step script for one path, as GitHub would. The repository is served from a local bare clone at the URL the step builds from GITHUB_SERVER_URL and GITHUB_REPOSITORY, with the pull request merge ref the trusted job fetches. PYTHONPATH is set to the scripts - directory the judge runs from, as a hostile runner might set it. Returns - the completed step, the logged uv calls, and the checkout the judge ran - from. + directory the judge runs from, as a hostile runner might set it. A control + passes ``edit`` to change the step script before it runs. Returns the + completed step, the logged uv calls, and the checkout the judge ran from. """ merge = _git( @@ -1674,6 +1697,8 @@ def _run_workflow_step(tmp_path, clone, base, candidate, path): "GITHUB_REPOSITORY": "PolicyEngine/chronicle", "RUNNER_TEMP": str(runner), "TMPDIR": str(tmp_path / "tmp"), + # Untranslated messages from git, which the controls match. + "LC_ALL": "C", } ) base_gate = runner / "thesis-facts-base-gate" @@ -1703,6 +1728,8 @@ def _run_workflow_step(tmp_path, clone, base, candidate, path): environment["GITHUB_SHA"] = candidate judge_root = base_gate if path == "pull_request" else clone environment["PYTHONPATH"] = str(judge_root / "scripts") + if edit is not None: + script = edit(script) step = tmp_path / "step.sh" step.write_text(script, encoding="utf-8") @@ -1714,7 +1741,8 @@ def _run_workflow_step(tmp_path, clone, base, candidate, path): text=True, check=False, ) - calls = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] + lines = log.read_text(encoding="utf-8").splitlines() if log.exists() else [] + calls = [json.loads(line) for line in lines] return completed, calls, judge_root @@ -2061,6 +2089,175 @@ def test_ci_verifies_the_release_chain_isolated_beside_shadowing_modules(tmp_pat _assert_every_start_is_isolated(calls, 1, clone, script="verify_release_chain.py") +# A .gitattributes in a base, and what it does to a checkout of that base made +# with its attributes: +# - "stops": a boolean working-tree-encoding stops git's checkout partway, +# with exit 128. Two pull requests that each pass alone merge into this base: +# one adds the attribute, the other the file it names. +# - "rewrites": an encoding on the gate's scripts rewrites the code the judge +# runs, so it cannot start. Receipt refuses a proposal that adds this, so it +# needs a direct push. +# - "anchors": eol=crlf on the trust anchors rewrites the bytes the gate pins, +# so the gate refuses every append. Receipt does not refuse eol, so a +# gate-only proposal can add this. +# For the first two the candidate is the pull request that removes the file +# again: the base gate judges it on the data path, or names it as a gate-only +# proposal. For "anchors" the candidate is the witnessed append, which keeps +# the file. +BASE_ATTRIBUTES = { + "stops": ("docs/.gitattributes", "notes.txt working-tree-encoding\n"), + "rewrites": ("scripts/.gitattributes", "*.py working-tree-encoding=UTF-16LE\n"), + "anchors": ("releases/.gitattributes", "anchors/* text eol=crlf\n"), +} +BASE_ATTRIBUTES_STOP = { + "stops": "true/false are no valid working-tree-encodings", + "rewrites": "source code cannot contain null bytes", + "anchors": "anchor bytes are not code-pinned", +} +ATTRIBUTE_SOURCE = ' --attr-source="$empty_tree"' +EMPTY_ATTRIBUTE_TREE = ( + 'empty_tree="$(git -C "$base_gate" hash-object -t tree /dev/null)"' +) + + +def _commit_index_edit(root, tmp_path, parent, message, *, add=None, remove=()): + """Commit ``parent`` with index entries added or removed, by plumbing. + + ``git add`` and ``git commit`` read the attributes they would commit, and + stop on the ones under test, so the tree is written from the index and the + working tree is left as it was. + """ + + _git(root, "read-tree", parent) + for relative, text in (add or {}).items(): + source = tmp_path / "attribute-blob" + source.write_text(text, encoding="utf-8") + blob = _git(root, "hash-object", "-w", "--no-filters", str(source)) + source.unlink() + _git(root, "update-index", "--add", "--cacheinfo", f"100644,{blob},{relative}") + for relative in remove: + _git(root, "update-index", "--force-remove", relative) + tree = _git(root, "write-tree") + commit = _git(root, "commit-tree", tree, "-p", parent, "-m", message) + _git(root, "update-ref", "HEAD", commit) + return commit + + +def _base_with_attributes(tmp_path, hazard): + """A base holding the gate and one .gitattributes, and the candidate.""" + + relative, text = BASE_ATTRIBUTES[hazard] + if hazard == "anchors": + + def prepare(root: pathlib.Path) -> None: + _install_base_gate((), tmp_path / "unused-marker")(root) + (root / relative).write_text(text, encoding="utf-8") + + clone, base, candidate = _replay_latest_release(tmp_path, prepare=prepare) + return clone, base, candidate, relative + clone, _ = _replay_current_state(tmp_path) + _install_base_gate((), tmp_path / "unused-marker")(clone) + (clone / "docs").mkdir() + (clone / "docs" / "notes.txt").write_text("notes\n", encoding="utf-8") + gate = _commit(clone, "the gate and a note") + base = _commit_index_edit( + clone, tmp_path, gate, f"merge {relative}", add={relative: text} + ) + candidate = _commit_index_edit( + clone, tmp_path, base, f"remove {relative}", remove=(relative,) + ) + return clone, base, candidate, relative + + +def _committed_bytes(root: pathlib.Path, relative: str) -> bytes: + """The bytes of ``relative`` in the commit checked out at ``root``.""" + + environment = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + environment.update({"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"}) + return subprocess.run( + ["git", "cat-file", "blob", f"HEAD:{relative}"], + cwd=root, + env=environment, + capture_output=True, + check=True, + ).stdout + + +@pytest.mark.parametrize("path", BASE_GATE_PATHS) +@pytest.mark.parametrize("hazard", BASE_ATTRIBUTES) +def test_a_gitattributes_in_the_base_cannot_stop_or_rewrite_the_base_gate( + tmp_path, hazard, path +): + """The base gate is checked out as committed, whatever its attributes say. + + Both base-gate jobs check the base out with an empty attribute tree, so a + .gitattributes in it, on the gate surface or off it, neither stops the + checkout nor rewrites a file the gate runs from or pins. The pull request + that removes the file, or an append beside it, is judged as any other + would be. + """ + + clone, base, candidate, relative = _base_with_attributes(tmp_path, hazard) + + completed, calls, judge_root = _run_workflow_step( + tmp_path, clone, base, candidate, path + ) + + assert completed.returncode == 0, completed.stdout + completed.stderr + verdict = completed.stdout.splitlines()[0] + if hazard == "stops": + assert verdict.startswith("thesis-facts append check OK: "), verdict + assert ", +0 appended vs base, release " in verdict, verdict + elif hazard == "anchors": + assert APPEND_GATE_OK in completed.stdout + else: + assert verdict == ( + "thesis-facts append check OK: gate-only proposal; DATA_SURFACE " + f"unchanged; GATE_SURFACE changes={[relative]!r}" + ) + assert (judge_root / relative).read_bytes() == _committed_bytes( + judge_root, relative + ) + anchors = [ + f"releases/anchors/{anchor.name}" + for anchor in (judge_root / "releases" / "anchors").iterdir() + ] + assert anchors + for checked_out in (*BASE_GATE_FILES, *anchors): + assert (judge_root / checked_out).read_bytes() == _committed_bytes( + judge_root, checked_out + ), checked_out + _assert_every_start_is_isolated(calls, WORKFLOW_STEP_PATHS[path], judge_root) + + +@pytest.mark.parametrize("hazard", BASE_ATTRIBUTES) +def test_the_same_attributes_stop_a_base_gate_checked_out_with_them(tmp_path, hazard): + """The control: the trusted job, checking the base out with its attributes. + + The same base and candidate, with the empty attribute tree taken out of + the step, stop the job: git refuses the checkout, Python the rewritten + gate, or the gate the rewritten anchors. For the first two, every later + pull request into this base stops the same way, the one that removes the + file included; for the anchors, every later append. + """ + + clone, base, candidate, _ = _base_with_attributes(tmp_path, hazard) + + def with_attributes(script: str) -> str: + assert script.count(ATTRIBUTE_SOURCE) == 1 + return script.replace(ATTRIBUTE_SOURCE, "") + + completed, calls, _ = _run_workflow_step( + tmp_path, clone, base, candidate, "pull_request_target", with_attributes + ) + + assert completed.returncode != 0 + assert "OK" not in completed.stdout + assert BASE_ATTRIBUTES_STOP[hazard] in completed.stderr, completed.stderr + if hazard == "stops": + assert calls == [] + + def test_the_scratch_directory_is_private_to_the_run(tmp_path): """The private directory is created 0700, and the shim asserts that it was.