From ddd1ad4435b5b58c6f743b8e5709c6d11f85f8d1 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:12:09 +0100 Subject: [PATCH 1/2] Share sandbox reporting and candidate transport test setup Co-Authored-By: Codex --- tests/test_candidate.py | 69 +++++++++++++--------------------- tests/test_sandbox.py | 83 +++++++++++++++-------------------------- 2 files changed, 56 insertions(+), 96 deletions(-) diff --git a/tests/test_candidate.py b/tests/test_candidate.py index 91bd0bfc..d1f2b0d0 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -17,6 +17,7 @@ from itertools import cycle from os import environ from shutil import copytree +from unittest.mock import Mock import pytest @@ -158,10 +159,9 @@ def test_attests_nested_candidate_and_transitive_parent_sources() -> None: ) def test_rejects_forged_bot_or_prefix(mutation, message: str) -> None: candidate_event = event() - original_payloads = payloads(candidate_event) mutation(candidate_event) with pytest.raises(CandidateError, match=message): - run_attestation(candidate_event=candidate_event, github_payloads=original_payloads) + run_attestation(candidate_event=candidate_event, github_payloads=payloads(event())) @pytest.mark.parametrize("case,diagnostic", [ @@ -243,8 +243,21 @@ def commit(name, content): return git("rev-parse", "HEAD") popen = subprocess.Popen + observed_transport = set() def isolated_fetch(argv, **kwargs): + if environ.get("HTTPS_PROXY") == "http://proxy.invalid:8080" and "git" in argv: + env = kwargs["env"] + transport = {"HTTPS_PROXY", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"} + if "fetch" in argv: + observed_transport.add("fetch") + assert env["HTTPS_PROXY"] == environ["HTTPS_PROXY"] + assert (env["GIT_CONFIG_COUNT"], env["GIT_CONFIG_KEY_0"]) == ("1", "http.extraHeader") + header = env["GIT_CONFIG_VALUE_0"].removeprefix("Authorization: Basic ") + assert base64.b64decode(header) == b"x-access-token:secret-token" + else: + observed_transport.add("plumbing") + assert not transport & env.keys() assert not any(arg.startswith("--as") for arg in argv) # arm64 Git exceeds RLIMIT_AS if "fetch" in argv: assert "https://github.com/owner/repo.git" in argv @@ -294,47 +307,24 @@ def get(path): if base_branch != "main": run = partial(run, base_branch=base_branch) - return run_attestation(candidate_event, github_get=get, status_reads=[queue], - source_policy=policy, run=run) + sources = run_attestation(candidate_event, github_get=get, status_reads=[queue], + source_policy=policy, run=run) + if environ.get("HTTPS_PROXY") == "http://proxy.invalid:8080": + assert observed_transport == {"fetch", "plumbing"} + return sources return attest, git, commit, base, parent, source, candidate_sha @pytest.mark.parametrize("base_branch", ["main", "trunk"]) -def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate, base_branch): +def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate, base_branch, monkeypatch): + monkeypatch.setenv("HTTPS_PROXY", "http://proxy.invalid:8080") attest, _, _, _, _, source, _ = tree_candidate seen = [] assert attest(base_branch=base_branch, policy=lambda n, _: seen.append(n)) == expected_sources((102, source)) assert seen == [102] -def test_candidate_transport_configuration_is_scoped_to_fetch(tree_candidate, monkeypatch): - attest, _, _, _, _, source, _ = tree_candidate - popen = subprocess.Popen - seen = set() - proxy = "http://proxy.invalid:8080" - monkeypatch.setenv("HTTPS_PROXY", proxy) - - def check_environment(argv, **kwargs): - if "git" in argv: - env = kwargs["env"] - if "fetch" in argv: - seen.add("fetch") - assert env["HTTPS_PROXY"] == proxy - assert env["GIT_CONFIG_COUNT"] == "1" - assert env["GIT_CONFIG_KEY_0"] == "http.extraHeader" - header = env["GIT_CONFIG_VALUE_0"].removeprefix("Authorization: Basic ") - assert base64.b64decode(header) == b"x-access-token:secret-token" - else: - seen.add("non-fetch") - assert not {"HTTPS_PROXY", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"} & env.keys() - return popen(argv, **kwargs) - - monkeypatch.setattr(subprocess, "Popen", check_environment) - assert attest() == expected_sources((102, source)) - assert seen == {"fetch", "non-fetch"} - - @pytest.mark.parametrize("mutation,diagnostic", [ ("replaced", "tree mismatch"), ("withdrawn", "tree mismatch"), ("extra", "tree mismatch|objects unavailable"), ("tampered", "tree mismatch"), ("missing", "objects unavailable"), @@ -403,10 +393,7 @@ def run(event, *, github_get, mergify_status, source_policy): @pytest.fixture(params=["loopzero", "intelflo"]) def candidate_policy(request): - - if request.param == "intelflo": - return request.getfixturevalue("intelflo_policy") - return candidate, attest_candidate + return request.getfixturevalue("intelflo_policy") if request.param == "intelflo" else (candidate, attest_candidate) @pytest.mark.parametrize("case", [ @@ -566,10 +553,7 @@ def test_nonrace_failure_does_not_retry(monkeypatch, failure, reread): live["batches"].pop(0) values["/repos/owner/repo/git/ref/heads/main"] = {"object": {"sha": "b" * 40}} - def mismatch(*_): - raise CandidateError("candidate tree mismatch") - - monkeypatch.setattr(candidate, "_verify_tree", mismatch) + monkeypatch.setattr(candidate, "_verify_tree", Mock(side_effect=CandidateError("candidate tree mismatch"))) def get(path): if path == "/apps/mergify": @@ -583,10 +567,7 @@ def get(path): return deepcopy(reread) return result - def policy(*_): - if failure == "policy": - raise expected - + policy = Mock(side_effect=expected if failure == "policy" else None) monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) with pytest.raises(CandidateError) as caught: run_attestation(github_get=get, status_reads=[live], source_policy=policy) diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 06a99753..851f17ae 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -148,11 +148,15 @@ def test_check_pipeline_verdict(git_repo, bwrap_log, monkeypatch, capsys, comman assert capsys.readouterr().out.splitlines()[-1] == ("FAIL" if stage_exit else "PASS") -def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): +@pytest.mark.parametrize("limited", [False, True], ids=["default", "constrained"]) +def test_bwrap_flags(git_repo, bwrap_log, monkeypatch, limited): + options = {"limits": ResourceLimits(memory_mb=64, file_mb=3)} if limited else {} + if limited: + monkeypatch.setattr(resource, "getrlimit", lambda _: (0, 32 * 1024 * 1024)) monkeypatch.setenv("LZ_KEEP", "kept") monkeypatch.setenv("LZ_DROP", "dropped") values = 'printf "%s\\n" "$PATH" "$LZ_KEEP" "${LZ_DROP-unset}" "$UV_CACHE_DIR" "$PYTHONDONTWRITEBYTECODE"' - (result,) = sandbox.run_checks(make_config(checks=(values,)), git_repo).results + (result,) = sandbox.run_checks(make_config(checks=(values,), **options), git_repo).results argv = argv_of(bwrap_log) head, tail = argv[: argv.index("--")], argv[argv.index("--") + 1 :] for flag in ("--die-with-parent", "--new-session", "--unshare-all", "--clearenv"): @@ -183,9 +187,11 @@ def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): assert sandbox.run_checks(make_config(), git_repo).dirty is False # /tmp tmpfs comes before the worktree bind so a worktree under /tmp stays visible. assert head.index("--tmpfs") < head.index(str(git_repo)) - assert tail == ["prlimit", f"--as={sandbox._cap_limit(4096 << 20, resource.RLIMIT_AS)}", - f"--fsize={sandbox._cap_limit(2048 << 20, resource.RLIMIT_FSIZE)}", - "--", *sandbox.CHECK_SHELL, values] + limits = ["--as=33554432", "--fsize=3145728"] if limited else [ + f"--as={sandbox._cap_limit(4096 << 20, resource.RLIMIT_AS)}", + f"--fsize={sandbox._cap_limit(2048 << 20, resource.RLIMIT_FSIZE)}", + ] + assert tail == ["prlimit", *limits, "--", *sandbox.CHECK_SHELL, values] @pytest.mark.parametrize("checks", [(), ("echo hello",)], ids=["probe", "stage"]) @@ -272,17 +278,6 @@ def test_timeout_is_recorded_with_drained_output(git_repo, bwrap_log): assert len(result.tail.encode()) == 16 * 1024 -def test_configured_resource_limits_are_converted_to_bytes(git_repo, bwrap_log, monkeypatch): - limits = ResourceLimits(memory_mb=64, file_mb=3) - monkeypatch.setattr(resource, "getrlimit", lambda _: (0, 32 * 1024 * 1024)) - sandbox.run_checks(make_config(limits=limits), git_repo) - argv = argv_of(bwrap_log) - assert argv[argv.index("--") + 1:] == [ - "prlimit", "--as=33554432", "--fsize=3145728", - "--", "/bin/bash", "--posix", "-o", "pipefail", "-c", "echo hello", - ] - - def test_linked_worktree_binds_common_git_dir(git_repo, bwrap_log, tmp_path): linked = tmp_path / "linked" git(git_repo, "worktree", "add", "-q", str(linked), "-b", "feature") @@ -323,10 +318,7 @@ def test_bwrap_missing_or_probe_failure(git_repo, fake_bin, fake_tool, monkeypat def test_probe_timeout_reports_only_the_timeout(git_repo, monkeypatch): - def timed_out(*args, **kwargs): - raise sandbox._proc.ProcTimeout("private probe diagnostic") - - monkeypatch.setattr(sandbox._proc, "run", timed_out) + monkeypatch.setattr(sandbox._proc, "run", Mock(side_effect=sandbox._proc.ProcTimeout("private probe diagnostic"))) with pytest.raises(sandbox.SandboxUnavailable) as info: sandbox.probe(make_config(), git_repo, ["bwrap", "--"]) @@ -428,12 +420,8 @@ def test_real_sandbox_denies_writes(self, git_repo): report = sandbox.run_checks(make_config(checks=(command,)), git_repo) assert report.results[0].exit_code != 0, report assert not escaped.exists() - checks = ( - "echo x > \"$HOME/ok\" && cat \"$HOME/ok\" && test ! -e /tmp/repo", - "test \"$(pwd)\" = \"$PWD\" && env | grep -c '^LZ_' ; true", - ) - report = sandbox.run_checks(make_config(checks=checks), git_repo) - assert [r.exit_code for r in report.results] == [0, 0], report + allowed = 'echo x > "$HOME/ok" && cat "$HOME/ok" && test ! -e /tmp/repo' + assert sandbox.run_checks(make_config(checks=(allowed,)), git_repo).ok def test_real_sandbox_memory_limit_fails_check_and_preserves_report(self, git_repo): command = "/usr/bin/perl -e '$x = \"x\" x (64 * 1024 * 1024); print length($x)'" @@ -534,15 +522,16 @@ def wait(): return events, reporters, status, wait -@pytest.mark.parametrize("exit_code", [0, 7]) -def test_silent_stage_reports_live_metadata_then_completion( +@pytest.mark.parametrize("exit_code", [0, 7, 17], ids=["pass", "failure", "early-failure"]) +def test_stage_reports_metadata_then_completion( git_repo, bwrap_log, monkeypatch, heartbeat_log, exit_code ): import re events, _, status, wait_for_heartbeat = heartbeat_log + early = exit_code == 17 monkeypatch.setenv("LZ_KEEP", "credential-value") - command = f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}' + command = "echo secret; exit 17" if early else f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}' cfg = make_config(checks=(command, "echo next")) run_one = sandbox._run_one @@ -551,11 +540,18 @@ def run_stage(config, worktree, prefix, stage_command, timeout): wait_for_heartbeat() return run_one(config, worktree, prefix, stage_command, timeout) - monkeypatch.setattr(sandbox, "_run_one", run_stage) - report = sandbox.run_checks(cfg, git_repo, progress=events.append, status=status) + if early: + monkeypatch.setattr(sandbox, "FIRST_HEARTBEAT_DELAY", 30.0) + else: + monkeypatch.setattr(sandbox, "_run_one", run_stage) + report = sandbox.run_checks(cfg, git_repo, progress=events.append, status=events.append if early else status) assert report.results[0].exit_code == exit_code - assert report.results[0].tail == "credential-value\nprivate-stderr" + assert report.results[0].tail == ("secret" if early else "credential-value\nprivate-stderr") statuses = [event for event in events if event not in cfg.checks] + if early: + assert len(statuses) == 1 and statuses[0].startswith("stage 1/2: exit 17 (") + assert len(report.results) == 1 and not report.ok + return heartbeats = [event for event in statuses if "running" in event] assert heartbeats and all(re.fullmatch( r"stage [12]/2: running \([0-9]+\.[0-9]s elapsed\)", event @@ -574,17 +570,6 @@ def run_stage(config, worktree, prefix, stage_command, timeout): assert statuses[-1].startswith("stage 2/2: exit 0") -def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log, monkeypatch): - events = [] - report = sandbox.run_checks( - make_config(checks=("echo secret; exit 17", "echo never")), git_repo, - status=events.append, - ) - assert len(events) == 1 and events[0].startswith("stage 1/2: exit 17 (") - assert report.results[0].tail == "secret" and len(report.results) == 1 - assert not report.ok - - def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch, heartbeat_log): events, _, status, wait_for_heartbeat = heartbeat_log inject_check_timeout(monkeypatch, b"private\n", wait_for_heartbeat) @@ -803,10 +788,7 @@ def test_input_diagnostic_failure_does_not_block_dirty_check( git_repo, bwrap_log, fetched_base, monkeypatch, path, ): if path == "README.md": - def timed_out(*args): - raise sandbox._proc.ProcTimeout("input lookup timed out") - - monkeypatch.setattr(sandbox, "_input_blobs", timed_out) + monkeypatch.setattr(sandbox, "_input_blobs", Mock(side_effect=sandbox._proc.ProcTimeout("input lookup timed out"))) (git_repo / "README.md").write_text("dirty\n") command = 'test "$(cat README.md)" = dirty' config = make_config(checks=(command,), inputs={command: (path,)}) @@ -861,7 +843,6 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe command = f"echo '{marker}'" config = make_config(checks=(command,), inputs={command: ("README.md",)}) original = sandbox.run_checks(config, git_repo) - assert original.ok legacy = replace(original.results[0], tail=f"{'x' * 20_000}\n{marker}") _save_report(git_repo, replace(original, results=(legacy,))) @@ -881,8 +862,7 @@ def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkey command = "echo stage ran" config = make_config(checks=(command,), inputs={command: ("README.md",)}) original = cache_check(config, clean=True, verify_reuse=True) - assert original.results[0].input_key - assert original.head == fetched_base + assert original.results[0].input_key and original.head == fetched_base run = sandbox._proc.run @@ -969,9 +949,8 @@ def write_runner(path, exit_code): write_runner(original, 0) runner.symlink_to(original) config = make_config(check_runner=(str(runner),), inputs={"echo hello": (".",)}) - report = cache_check(config) + report = cache_check(config, verify_reuse=True) assert _current_check_report(git_repo, config, report.head) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head if change == "target": replacement = tmp_path / "runner-b" From 9bcf2c6322c996de4f88533c51615cc4ffbeef7c Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:34:36 +0100 Subject: [PATCH 2/2] Retain literal shell and stage assertions in deduped tests Co-Authored-By: Codex --- tests/test_candidate.py | 6 ++---- tests/test_sandbox.py | 10 ++++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/test_candidate.py b/tests/test_candidate.py index d1f2b0d0..b9d42e37 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -126,10 +126,8 @@ def run_attestation( run=attest_candidate, ): candidate_event = candidate_event or event() - reads, values = ( - cycle(status_reads or [status()]), - github_payloads or payloads(candidate_event), - ) + reads = cycle(status_reads or [status()]) + values = github_payloads or payloads(candidate_event) return run( candidate_event, github_get=github_get or (lambda path: deepcopy(values[path])), diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 851f17ae..3dea2ef0 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -191,7 +191,7 @@ def test_bwrap_flags(git_repo, bwrap_log, monkeypatch, limited): f"--as={sandbox._cap_limit(4096 << 20, resource.RLIMIT_AS)}", f"--fsize={sandbox._cap_limit(2048 << 20, resource.RLIMIT_FSIZE)}", ] - assert tail == ["prlimit", *limits, "--", *sandbox.CHECK_SHELL, values] + assert tail == ["prlimit", *limits, "--", "/bin/bash", "--posix", "-o", "pipefail", "-c", values] @pytest.mark.parametrize("checks", [(), ("echo hello",)], ids=["probe", "stage"]) @@ -420,8 +420,10 @@ def test_real_sandbox_denies_writes(self, git_repo): report = sandbox.run_checks(make_config(checks=(command,)), git_repo) assert report.results[0].exit_code != 0, report assert not escaped.exists() - allowed = 'echo x > "$HOME/ok" && cat "$HOME/ok" && test ! -e /tmp/repo' - assert sandbox.run_checks(make_config(checks=(allowed,)), git_repo).ok + checks = ('echo x > "$HOME/ok" && cat "$HOME/ok" && test ! -e /tmp/repo', + 'test "$(pwd)" = "$PWD" && env | grep -c "^LZ_" ; true') + report = sandbox.run_checks(make_config(checks=checks), git_repo) + assert [r.exit_code for r in report.results] == [0, 0], report def test_real_sandbox_memory_limit_fails_check_and_preserves_report(self, git_repo): command = "/usr/bin/perl -e '$x = \"x\" x (64 * 1024 * 1024); print length($x)'" @@ -852,7 +854,7 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe receipt = json.loads(receipt_path.read_text()) assert receipt["head"] == git(git_repo, "rev-parse", "HEAD").strip() [result] = receipt["results"] - assert result["reused_from"] == original.head + assert original.ok and result["reused_from"] == original.head assert marker in result["tail"].splitlines() assert len(result["tail"].encode("utf-8")) <= 16 * 1024