From 581c25e6a944c5f4850bc9b337dd4df0ecfa905a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:11:45 +0100 Subject: [PATCH 1/3] Redact forwarded credentials from check diagnostics Architecture-Review: unchanged; check environments and outcomes retain their existing authority while captured diagnostics redact forwarded values. Co-Authored-By: Codex --- src/loopzero/sandbox.py | 58 ++++++++++++++++++++++++++++++-------- tests/test_cli.py | 15 ++++++++-- tests/test_sandbox.py | 23 +++++++++++---- tests/test_stage_runner.py | 30 ++++++++++++-------- 4 files changed, 94 insertions(+), 32 deletions(-) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 6f725e28..c1401566 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -46,6 +46,14 @@ "PYTEST_ADDOPTS": "-p no:cacheprovider", } +_CHECK_CONTEXT_ENV = {*Config.env_allowlist, "TMP", "TEMP", "TMPDIR", "UV_PYTHON_INSTALL_DIR", + *(name for name in SANDBOX_ENV if name.endswith("_CACHE_DIR"))} +_CHECK_MODES = {"development", "production", "staging", "testing"} +_CREDENTIAL_ENV = re.compile( + r"PASSWORD|PASSWD|PASSPHRASE|(?:^|_)(?:PWD|PIN|PAT|AUTH|TOKEN|SECRET|CREDENTIALS?|COOKIE|" + r"(?:API|ACCESS|PRIVATE)_KEY)(?:_|$)", re.IGNORECASE, +) + class SandboxUnavailable(LoopZeroError): """bubblewrap is missing or cannot create a sandbox on this host.""" @@ -199,7 +207,7 @@ def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, and is_check_exit_code(code) and code == 0 and isinstance(tail, str)): source = result.get("reused_from") previous[command] = CheckResult( - command, 0, 0.0, _check_tail(tail), key, + command, 0, 0.0, _check_tail(tail, config), key, source if isinstance(source, str) else data["head"], ) return previous @@ -428,9 +436,32 @@ def _cap_limit(requested: int, resource_limit: int) -> int: return requested if hard == resource.RLIM_INFINITY else min(requested, hard) -def _check_tail(text: str) -> str: - suffix = text.rstrip("\n")[-CHECK_TAIL_BYTES:] - encoded = suffix.encode("utf-8", errors="replace")[-CHECK_TAIL_BYTES:] +def _private_check_value(name: str, value: str) -> bool: + if name in _CHECK_CONTEXT_ENV or value == SANDBOX_ENV.get(name): + return False + normalized = value.strip() + if not normalized: + return False + if _CREDENTIAL_ENV.search(name): + return True + mode = name == "ENV" or name.endswith(("_ENV", "_ENVIRONMENT", "_MODE")) + return len(normalized) >= 6 and not (mode and normalized.casefold() in _CHECK_MODES) + + +def _redact_check_output(config: Config, text: str) -> str: + stage_env = _runner_environment(config) if config.check_runner else _sandbox_environment(config) + wrapper_env = _proc.build_env(config.env_allowlist) + secrets = {value for env in (stage_env, wrapper_env) for name, value in env.items() + if _private_check_value(name, value)} + pattern = "|".join(map(re.escape, sorted(secrets, key=len, reverse=True))) + return re.sub(pattern, "[REDACTED]", text) if pattern else text + + +def _check_tail(text: str, config: Config | None = None, *, suffix: str = "") -> str: + if config is not None: + text = _redact_check_output(config, text) + bounded = (text + suffix).rstrip("\n")[-CHECK_TAIL_BYTES:] + encoded = bounded.encode("utf-8", errors="replace")[-CHECK_TAIL_BYTES:] # A byte cut can start inside a multibyte character. return _proc.tail(encoded.decode("utf-8", errors="ignore")) @@ -453,8 +484,8 @@ def _run_one( ) except _proc.ProcTimeout as exc: return CheckResult(command, TIMEOUT_EXIT, timeout, - _check_tail(exc.stdout + f"\n[loopzero] timed out after {timeout:g}s")) - return CheckResult(command, done.exit_code, done.duration_s, _check_tail(done.stdout)) + _check_tail(exc.stdout, config, suffix=f"\n[loopzero] timed out after {timeout:g}s")) + return CheckResult(command, done.exit_code, done.duration_s, _check_tail(done.stdout, config)) def probe(config: Config, worktree: Path, prefix: list[str]) -> None: @@ -478,6 +509,10 @@ def probe(config: Config, worktree: Path, prefix: list[str]) -> None: raise SandboxUnavailable(f"bwrap namespace creation failed: exit {probe.exit_code}{remedy}") +def _runner_environment(config: Config) -> dict[str, str]: + return {**SANDBOX_ENV, **dict(config.env)} + + def _sandbox_environment(config: Config) -> dict[str, str]: return { **SANDBOX_ENV, @@ -596,7 +631,7 @@ def _stage_frame(stdout: str, binding: dict) -> dict: def _dispatch_one( config: Config, worktree: Path, head: str, base: str, command: str, timeout: float, ) -> CheckResult: - env = {**SANDBOX_ENV, **dict(config.env)} + env = _runner_environment(config) binding = {"worktree": str(worktree.resolve()), "head": head, "base": base, "command": command, "network": config.network, "env_sha256": hashlib.sha256(json.dumps( env, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()} @@ -621,7 +656,7 @@ def _dispatch_one( done = _proc.run(argv, cwd=cwd, env_allowlist=config.env_allowlist, timeout=timeout, input=json.dumps({**binding, "env": env}), encoding="utf-8") if done.exit_code: - stderr = _proc.tail(done.stderr)[-2000:] + stderr = _proc.tail(_redact_check_output(config, done.stderr))[-2000:] detail = f"Stage runner failed: process exit {done.exit_code}" return CheckResult(command, done.exit_code, done.duration_s, f"{detail}\n{stderr}".rstrip()) @@ -639,10 +674,11 @@ def _dispatch_one( raise ValueError("Local fallback failed") return local.results[-1] return CheckResult(command, frame["exit_code"], frame["duration_s"], - _check_tail(frame["tail"])) + _check_tail(frame["tail"], config)) except _proc.ProcTimeout as exc: return CheckResult(command, TIMEOUT_EXIT, exc.duration_s if exc.duration_s is not None else timeout, - _check_tail(exc.stdout + f"\n[loopzero] timed out after {timeout:g}s")) + _check_tail(exc.stdout, config, suffix=f"\n[loopzero] timed out after {timeout:g}s")) except (LoopZeroError, ValueError, TypeError, OverflowError, RecursionError, OSError) as exc: - return CheckResult(command, 1, 0.0, _check_tail(f"Stage runner failed: {exc}")) + detail = _redact_check_output(config, str(exc)) + return CheckResult(command, 1, 0.0, _check_tail(f"Stage runner failed: {detail}")) diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..0a9ebc6c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -429,19 +429,24 @@ def test_check_skips_closed_pr_history(wt, gh, capsys, head, state): @pytest.mark.parametrize("pushed,refresh_timeout,stage_exit", [ (False, False, 0), (True, False, 0), (True, True, 0), (True, True, 124), ]) -def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, pushed, refresh_timeout, stage_exit): +def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, tmp_path, pushed, refresh_timeout, stage_exit): git(wt, "push", "-q", "-u", "origin", "lz/t1") arm_pr(gh, head_of(wt)) if not pushed: git(wt, "commit", "-q", "--allow-empty", "-m", "unpushed change") + options = () if stage_exit: - inject_check_timeout(monkeypatch, b"local check output") + monkeypatch.setenv("AUDIT_TOKEN", "ghs_FAKE0123") + private = tmp_path / "private.toml" + private.write_text(WORKFLOW.replace("[checks]", '[checks]\nenv_allowlist = ["PATH", "AUDIT_TOKEN"]')) + options = ("--config", str(private)) + inject_check_timeout(monkeypatch, b"local check ghs_FAKE0123 output") endpoint = f"repos/{REPO}/pulls/7" gh.respond(f"api {endpoint} --method PATCH", {}) if refresh_timeout: timeout = cli._proc.ProcTimeout(f"PATCH {endpoint} timed out") monkeypatch.setattr(github, "update_body", Mock(side_effect=timeout)) - code, out, err = run(capsys, "check") + code, out, err = run(capsys, *options, "check") assert (code, out.splitlines()[-1]) == ((1, "FAIL") if stage_exit else (0, "PASS")) assert [call["argv"][:2] for call in gh.calls] == LOOKUP_CALLS + ( [["api", endpoint]] if pushed and not refresh_timeout else []) @@ -449,6 +454,10 @@ def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, push assert report["head"] == head_of(wt) and report["dirty"] is False assert report["results"][0]["exit_code"] == stage_exit assert bool(err) == refresh_timeout + if stage_exit: + assert "local check [REDACTED] output" in err + assert "local check [REDACTED] output" in report["results"][0]["tail"] + assert "ghs_FAKE0123" not in err if refresh_timeout: assert f"note: could not refresh PR checks: PATCH {endpoint} timed out" in err if pushed and not refresh_timeout: diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 674e4d8a..6d1057ca 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -567,8 +567,13 @@ def test_silent_stage_reports_live_metadata_then_completion( events, _, status, wait_for_heartbeat = heartbeat_log monkeypatch.setenv("LZ_KEEP", "credential-value") - command = f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}' - cfg = make_config(checks=(command, "echo next")) + monkeypatch.setenv("AUDIT_TOKEN", "p1n") + monkeypatch.setenv("RUST_BACKTRACE", "1") + command = ('test -z "$LZ_KEEP" || echo "$LZ_KEEP"; echo "$AUDIT_TOKEN"; ' + 'echo "tests/test_example.py:12: $RUST_BACKTRACE $NODE_ENV $DJANGO_DEBUG" >&2; ' + f'exit {exit_code}') + cfg = make_config(checks=(command, "echo next"), env_allowlist=("PATH", "AUDIT_TOKEN", "RUST_BACKTRACE"), + env=(("NODE_ENV", "test"), ("DJANGO_DEBUG", "true"))) run_one = sandbox._run_one def run_stage(config, worktree, prefix, stage_command, timeout): @@ -579,7 +584,7 @@ def run_stage(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) assert report.results[0].exit_code == exit_code - assert report.results[0].tail == "credential-value\nprivate-stderr" + assert report.results[0].tail == "[REDACTED]\ntests/test_example.py:12: 1 test true" statuses = [event for event in events if event not in cfg.checks] heartbeats = [event for event in statuses if "running" in event] assert heartbeats and all(re.fullmatch( @@ -587,7 +592,7 @@ def run_stage(config, worktree, prefix, stage_command, timeout): ) for event in heartbeats) completion = next(event for event in statuses if f"exit {exit_code}" in event) assert re.fullmatch(rf"stage 1/2: exit {exit_code} \([0-9]+\.[0-9]s\)", completion) - assert all("private" not in event and "credential-value" not in event for event in statuses) + assert all("tests/test_example.py" not in event and "p1n" not in event for event in statuses) assert any(event.startswith("stage 1/2: running") for event in statuses) assert all(not event.startswith("stage 1/2: running") for event in events[events.index(completion) + 1:]) @@ -751,7 +756,7 @@ def cache(config, *, clean=False, verify_reuse=False): 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', 'dirty_tree', 'legacy', 'grant']) def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change): - cfg = make_config(checks=('echo one', 'echo two'), + cfg = make_config(checks=('echo one', 'echo two'), env=(("AUDIT_TOKEN", "fake-cached-token"), ("NODE_ENV", "test")), inputs={'echo one': ('*.md',), 'echo two': ('*.md',), '*': ('shared',)}) if change == 'grant': cfg = replace(cfg, env_allowlist=(*cfg.env_allowlist, "HEAVY_SLOT_GRANTED_CORES")) @@ -761,7 +766,9 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch whole = replace(cfg, inputs={'*': ('.',)}) key = sandbox._input_key(whole, git_repo, 'unlisted', fetched_base) assert key is not None - _save_report(git_repo, sandbox.run_checks(cfg, git_repo)) + first = sandbox.run_checks(cfg, git_repo) + original_tails = tuple(replace(r, tail=f"{r.tail} tests/test_example.py:12 fake-cached-token") for r in first.results) + _save_report(git_repo, replace(first, results=original_tails)) receipt = git_repo / '.loopzero/checks.json' git(git_repo, 'config', 'core.excludesFile', str(git_repo / '.git/info/exclude')) with (git_repo / '.git/info/exclude').open('a') as stream: @@ -803,6 +810,10 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch report = sandbox.run_checks(cfg, git_repo, status=(messages := []).append) assert [r.command for r in report.results] == list(cfg.checks) assert all(bool(r.reused_from) == (change == 'other') for r in report.results) + if change == 'other': + assert [r.tail for r in report.results] == [ + 'one tests/test_example.py:12 [REDACTED]', 'two tests/test_example.py:12 [REDACTED]', + ] assert any('reused ' in m for m in messages) == (change == 'other') assert report.head == git(git_repo, 'rev-parse', 'HEAD').strip() diff --git a/tests/test_stage_runner.py b/tests/test_stage_runner.py index ddc88774..765ca21a 100644 --- a/tests/test_stage_runner.py +++ b/tests/test_stage_runner.py @@ -13,9 +13,12 @@ @pytest.mark.parametrize('base_ref,body,verdict,tails', [ - *[(base_ref, 'print(json.dumps(r))', True, ['ok', 'ok']) for base_ref in ('stale', 'missing', 'recorded')], - ('stale', 'r["exit_code"]=7;print(json.dumps(r))', False, ['ok']), - ('stale', 'print("x" * 3000 + "worker socket unavailable", file=sys.stderr);sys.exit(42)', False, None), + *[(base_ref, 'r["tail"]=" ".join((env["UV_CACHE_DIR"],env["NODE_ENV"],env["AUDIT_VALUE"],os.environ["AUDIT_VALUE"]));print(json.dumps(r))', + True, ['/operator/cache production [REDACTED] [REDACTED]'] * 2) for base_ref in ('stale', 'missing', 'recorded')], + ('stale', 'r["exit_code"]=7;r["tail"]="ok "+env["AUDIT_VALUE"];print(json.dumps(r))', False, ['ok [REDACTED]']), + ('stale', 'print("x" * 3000 + "worker socket unavailable " + env["AUDIT_VALUE"], file=sys.stderr);sys.exit(42)', False, None), + ('stale', 'r["exit_code"]=7;r["tail"]=env["AUDIT_VALUE"]+"Ω"*8183+" newest";print(json.dumps(r))', False, + ['[REDACTED]' + 'Ω' * 8183 + ' newest']), ('stale', 'r["exit_code"]=7;r["tail"]="Ω"*10000+" newest";print(json.dumps(r))', False, ['Ω' * 8188 + ' newest']), ('stale', 'subprocess.run(["git","-C",repo,"-c","user.name=test","-c","user.email=t@e","commit","--allow-empty","-m","drift"],stdout=sys.stderr,check=True);print(json.dumps(r))', False, None), @@ -30,7 +33,7 @@ *[f'r["{field}"]="wrong";print(json.dumps(r))' for field in ('head', 'base', 'command', 'env_sha256', 'network', 'worktree')], ]], ]) -def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): # noqa: F811 +def test_runner(git_repo, tmp_path, bwrap_log, monkeypatch, body, verdict, tails, base_ref): # noqa: F811 git(git_repo, 'switch', '-c', 'task') git(git_repo, 'commit', '--allow-empty', '-m', 'advance') base = git(git_repo, 'rev-parse', 'HEAD').strip() @@ -42,18 +45,20 @@ def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): git(git_repo, 'update-ref', 'refs/remotes/origin/main', base) if base_ref == 'missing': git(git_repo, 'branch', '-D', 'main') + monkeypatch.setenv("AUDIT_VALUE", "opaque-fake-wrapper-password") + configured = {"UV_CACHE_DIR": "/operator/cache", "NODE_ENV": "production", "AUDIT_VALUE": "opaque-fake-db-password"} body = (f'repo=r["worktree"]\nassert r["base"] == "{base}"\n' 'assert not Path.cwd().is_relative_to(Path(repo))\n' - f'assert r.pop("env") == {dict(sandbox.SANDBOX_ENV, UV_CACHE_DIR="/operator/cache")!r}\n' + f'env=r.pop("env");assert env == {dict(sandbox.SANDBOX_ENV, **configured)!r}\n' 'assert r["network"] is True\n' 'assert r["env_sha256"] == hashlib.sha256(json.dumps(' - f'{dict(sandbox.SANDBOX_ENV, UV_CACHE_DIR="/operator/cache")!r},' + f'{dict(sandbox.SANDBOX_ENV, **configured)!r},' 'sort_keys=True,separators=(",", ":")).encode()).hexdigest()\n' + body) path = tmp_path / 'runner.py' - path.write_text('import hashlib,json,sys,subprocess\nfrom pathlib import Path\nr=json.load(sys.stdin)\nr.update(exit_code=0,duration_s=0.1,not_started=False,tail="ok")\n' + body) + path.write_text('import hashlib,json,os,sys,subprocess\nfrom pathlib import Path\nr=json.load(sys.stdin)\nr.update(exit_code=0,duration_s=0.1,not_started=False,tail="ok")\n' + body) calls = [] report = sandbox.run_checks(make_config(checks=('echo one', 'echo two'), - env=(("UV_CACHE_DIR", "/operator/cache"),), network=True, + env=tuple(configured.items()), env_allowlist=("PATH", "AUDIT_VALUE"), network=True, check_runner=(sys.executable, str(path))), git_repo, progress=calls.append) assert report.ok is verdict if 'exit_code"]=7' in body: @@ -61,7 +66,7 @@ def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): if 'sys.exit(42)' in body: result = report.results[0] assert result.exit_code == 42 and result.duration_s > 0 - assert result.tail == 'Stage runner failed: process exit 42\n' + ('x' * 3000 + 'worker socket unavailable')[-2000:] + assert result.tail == 'Stage runner failed: process exit 42\n' + ('x' * 3000 + 'worker socket unavailable [REDACTED]')[-2000:] if tails is not None: assert [r.tail for r in report.results] == tails if not verdict: @@ -152,14 +157,15 @@ def test_runner_timeout(git_repo, monkeypatch, fetched_base): # noqa: F811 original = sandbox._proc.run def run(argv, **kwargs): if argv[0] == sys.executable: - raise sandbox._proc.ProcTimeout('deadline', 'partial', duration_s=0.25) + raise sandbox._proc.ProcTimeout('deadline', 'partial opaque-fake-db-password', duration_s=0.25) return original(argv, **kwargs) monkeypatch.setattr(sandbox._proc, 'run', run) - report = sandbox.run_checks(make_config(check_runner=(sys.executable,)), git_repo, timeout=0.1) + cfg = make_config(check_runner=(sys.executable,), env=(("AUDIT_VALUE", "opaque-fake-db-password"),)) + report = sandbox.run_checks(cfg, git_repo, timeout=0.1) assert not report.ok result = report.results[0] assert result.exit_code == 124 and result.duration_s == 0.25 - assert 'partial' in result.tail and 'timed out after 0.1s' in result.tail + assert 'partial [REDACTED]' in result.tail and 'timed out after 0.1s' in result.tail @pytest.mark.parametrize('change', ['fallback', 'base']) From 20f4f8112360c2e1400c7220e21080325eb3a8af Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:10:14 +0100 Subject: [PATCH 2/3] Pass redaction configuration through the merged cache reader Co-Authored-By: Codex --- src/loopzero/sandbox.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index ec57741b..be5d8e0f 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -104,7 +104,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO "Runner requires a clean worktree"),)) base = _check_base(config, worktree) settings_sha256 = settings_fingerprint(config) - previous = _previous(worktree, settings_sha256) if config.inputs and base and settings_sha256 and not dirty else {} + previous = _previous(config, worktree, settings_sha256) if config.inputs and base and settings_sha256 and not dirty else {} common_dir = _git_dir(config, worktree, "--git-common-dir") git_dir = _git_dir(config, worktree, "--git-dir") @@ -177,7 +177,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO INCOMPLETE_CHECK_COMMAND = "" -def _previous(worktree: Path, settings_sha256: str) -> dict[str, CheckResult]: +def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]: try: data = json.loads(read_local_state(worktree, "checks.json")) if (data["dirty"] is not False or not isinstance(data["head"], str) From 73905bd925775fd640c82a46515008c50ee703a5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:25:40 +0100 Subject: [PATCH 3/3] Deduplicate configuration, process and budget tests Co-Authored-By: Codex --- tests/test_config.py | 22 ++++---------- tests/test_proc.py | 34 ++++++++++----------- tests/test_size_budget.py | 62 +++++++++++++++------------------------ 3 files changed, 44 insertions(+), 74 deletions(-) diff --git a/tests/test_config.py b/tests/test_config.py index 3aa91cea..37aaa373 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -65,7 +65,8 @@ def test_missing_file(tmp_path): config.load(tmp_path / "nope.toml") -MINIMAL = '[repo]\nname = "o/n"\n' +FORBIDDEN = ["/", "/home", "/root", "/run", "/var/run", "/run/user/1000", "/proc/1", "/dev", + "/var/run/docker.sock", "/sys/fs", "/tmp/../run"] @pytest.mark.parametrize("text,message", [ @@ -102,6 +103,7 @@ def test_missing_file(tmp_path): (MINIMAL + '[delivery.review.codex]\nallowed_efforts = "medium"\n', "allowed_efforts must be a list"), (MINIMAL + '[checks]\nro_paths = ["rel/path"]\n', "must be absolute"), + *((MINIMAL + table("checks", ro_paths=[path]), "must not expose") for path in FORBIDDEN), (MINIMAL + '[checks]\nwritable = ["/run/x"]\n', "writable must not expose"), *((MINIMAL + f'[checks]\nscratch = ["{path}"]\n', "scratch entries must be relative") for path in ("../x", "/abs")), @@ -127,24 +129,12 @@ def test_invalid_content(tmp_path, text, message): assert str(info.value).startswith(str(tmp_path / "workflow.toml")) -FORBIDDEN = ["/", "/home", "/root", "/run", "/var/run", "/run/user/1000", "/proc/1", "/dev"] -FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"] - - @pytest.mark.parametrize("runner", [("dispatch", "--stage"), ("python3", "tools/run_stage.py"), ("dispatch", "--opt=/operator/run.py")]) def test_runner_prefix(tmp_path, runner): assert config.load(write(tmp_path, MINIMAL + f"[checks]\nrunner = {list(runner)!r}")).check_runner == runner -@pytest.mark.parametrize("path,allowed", [ - *((path, False) for path in FORBIDDEN), - *((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")), -]) -def test_ro_path_boundary(tmp_path, path, allowed): - cfg = write(tmp_path, f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n') - if allowed: - assert config.load(cfg).sandbox_ro == (path,) - else: - with pytest.raises(config.ConfigError, match="must not expose"): - config.load(cfg) +@pytest.mark.parametrize("path", ["/home/me/.local/bin", "/opt/tool", "/tmp/x"]) +def test_ro_path_boundary(tmp_path, path): + assert config.load(write(tmp_path, MINIMAL + table("checks", ro_paths=[path]))).sandbox_ro == (path,) diff --git a/tests/test_proc.py b/tests/test_proc.py index 65b5a209..d0a04713 100644 --- a/tests/test_proc.py +++ b/tests/test_proc.py @@ -44,15 +44,6 @@ def run(script, *, timeout=30, env_allowlist=("PATH",), unbuffered=False, args=( return run -def test_run_strips_environment_to_allowlist(run_python, monkeypatch): - monkeypatch.delenv("LZ_ABSENT", raising=False) - monkeypatch.setenv("LZ_SECRET", "nope") - monkeypatch.setenv("LZ_KEEP", "yes") - done = run_python("import os; print(sorted(k for k in os.environ if k.startswith('LZ_')))", - env_allowlist=("PATH", "LZ_KEEP", "LZ_ABSENT"), extra_env={"LZ_EXTRA": "1"}) - assert done.stdout.strip() == "['LZ_EXTRA', 'LZ_KEEP']" - - def test_run_raises_tool_missing(tmp_path): with pytest.raises(_proc.ToolMissing, match="definitely-not-a-tool"): _proc.run(["definitely-not-a-tool"], cwd=tmp_path, env_allowlist=("PATH",), timeout=30) @@ -122,14 +113,21 @@ def communicate(self, input=None, timeout=None): @pytest.mark.parametrize("merge,stderr", [(True, ""), (False, "b\n")]) -def test_run_captures_exit_duration_cwd_and_streams(tmp_path, run_python, merge, stderr): +def test_run_captures_streams_and_allowlisted_environment(tmp_path, run_python, monkeypatch, merge, stderr): + monkeypatch.delenv("LZ_ABSENT", raising=False) + monkeypatch.setenv("LZ_SECRET", "nope") + monkeypatch.setenv("LZ_KEEP", "yes") done = run_python( - "import os,sys; print(os.getcwd()); print('b', file=sys.stderr); print(sys.argv[1]); sys.exit(3)", - unbuffered=True, merge_output=merge, env_allowlist=(), args=("argument with spaces",), + "import os,sys; print(os.getcwd()); print('b', file=sys.stderr); print(sys.argv[1]); " + "print(sorted(k for k in os.environ if k.startswith('LZ_'))); sys.exit(3)", + unbuffered=True, merge_output=merge, args=("argument with spaces",), + env_allowlist=("PATH", "LZ_KEEP", "LZ_ABSENT"), extra_env={"LZ_EXTRA": "1"}, ) assert (done.exit_code, done.stderr) == (3, stderr) assert done.duration_s >= 0 - assert done.stdout.splitlines() == [str(tmp_path.resolve()), *(["b"] if merge else []), "argument with spaces"] + assert done.stdout.splitlines() == [ + str(tmp_path.resolve()), *(["b"] if merge else []), "argument with spaces", "['LZ_EXTRA', 'LZ_KEEP']", + ] def test_tail_keeps_last_lines(): @@ -138,7 +136,7 @@ def test_tail_keeps_last_lines(): assert _proc.tail("", 3) == "" -def test_explicit_utf8_input_under_ascii_parent_locale(tmp_path): +def test_explicit_utf8_input_under_ascii_parent_locale(run_python): source = str(Path(_proc.__file__).resolve().parents[1]) script = r""" import locale, sys @@ -150,10 +148,8 @@ def test_explicit_utf8_input_under_ascii_parent_locale(tmp_path): assert _proc.run(argv, input='\u03a9', **options).stdout.strip() == '3f' print(_proc.run(argv, input='\u03a9\r\n\u2028\r', encoding='utf-8', **options).stdout.strip()) """ - done = _proc.run( - [sys.executable, "-c", script], cwd=tmp_path, env_allowlist=(), timeout=30, - extra_env={"PYTHONPATH": source, "LC_ALL": "C", "PYTHONUTF8": "0", - "PYTHONCOERCECLOCALE": "0"}, - ) + done = run_python(script, env_allowlist=(), extra_env={ + "PYTHONPATH": source, "LC_ALL": "C", "PYTHONUTF8": "0", "PYTHONCOERCECLOCALE": "0", + }) assert done.exit_code == 0, done.stderr assert done.stdout.strip() == "Ω\r\n\u2028\r".encode("utf-8").hex() diff --git a/tests/test_size_budget.py b/tests/test_size_budget.py index 0acf66dc..64ce0033 100644 --- a/tests/test_size_budget.py +++ b/tests/test_size_budget.py @@ -45,16 +45,13 @@ def test_size_budget_counts_unicode_and_propagates_read_errors(git_repo, fake_to source.parent.mkdir(parents=True) source.write_text("one\ntwo\n") source.with_name("z.py").write_text("three\n") - git(git_repo, "add", ".") - base = git(git_repo, "write-tree").strip() + base = stage_tree(git_repo) if failure == "deleted": # unstaged deletion: skipped, not an error source.unlink() elif failure == "show": fake_tool("git", 'if [ "$1" = show ]; then case "$2" in */a.py) exit 1;; esac; fi\n' f'exec {shutil.which("git")} "$@"\n') - done = subprocess.run(["bash", str(SCRIPT), base], cwd=git_repo, - env={**os.environ, "PYTHON": sys.executable}, - capture_output=True, text=True, check=False) + done = run_budget(git_repo, base) assert bool(done.returncode) is (failure == "show") if failure != "show": assert done.stdout.startswith("src=1 (base 3," if failure else "src=3 (base 3, delta 0,") @@ -82,38 +79,29 @@ def module_path(git_repo): _HOT_FUNCTION = _branchy("hot", 11) -@pytest.mark.parametrize("before,after,expected_rc", [ - pytest.param(_SIMPLE_FUNCTION, _branchy("new_hot", 10), 1, id="new_over_cap"), - pytest.param(_HOT_FUNCTION, _HOT_FUNCTION, 0, id="existing_hold"), - pytest.param(_HOT_FUNCTION, _branchy("hot", 10), 0, id="existing_shrink"), - pytest.param(_HOT_FUNCTION, _branchy("hot", 12), 1, id="existing_grow"), +_CONTEXT_MANAGERS = "".join(f" with contextlib.suppress(ValueError):\n y = {i}\n" + for i in range(11)) +_PEP758 = "import contextlib\ndef pep758(x):\n" + _CONTEXT_MANAGERS + ( + " try:\n return int(x) + y\n except KeyError, TypeError:\n return 0\n" +) + + +@pytest.mark.parametrize("before,after,over_cap,regressions", [ + pytest.param(_SIMPLE_FUNCTION, _branchy("new_hot", 10), 1, 1, id="new_over_cap"), + pytest.param(_HOT_FUNCTION, _HOT_FUNCTION, 1, 0, id="existing_hold"), + pytest.param(_HOT_FUNCTION, _branchy("hot", 10), 1, 0, id="existing_shrink"), + pytest.param(_HOT_FUNCTION, _branchy("hot", 12), 1, 1, id="existing_grow"), + pytest.param(_PEP758, _PEP758, 0, 0, id="pep758_with_blocks"), ]) -def test_complexity_ratchet(git_repo, module_path, before, after, expected_rc): +def test_complexity_ratchet(git_repo, module_path, before, after, over_cap, regressions): module_path.write_text(before) base = stage_tree(git_repo) if after != before: module_path.write_text(after) done = run_budget(git_repo, base) - assert done.returncode == expected_rc, done.stdout + done.stderr - assert ("complexity=FAIL" if expected_rc else "complexity=PASS") in done.stdout - - -def test_complexity_parses_pep758_and_ignores_with_blocks(git_repo, module_path): - with_blocks = "".join(f" with contextlib.suppress(ValueError):\n y = {i}\n" - for i in range(11)) - module_path.write_text( - "import contextlib\n" - "def pep758(x):\n" - f"{with_blocks}" - " try:\n" - " return int(x) + y\n" - " except KeyError, TypeError:\n" - " return 0\n" - ) - base = stage_tree(git_repo) - done = run_budget(git_repo, base) - assert done.returncode == 0, done.stdout + done.stderr - assert "complexity=PASS (cap 10, over_cap 0, regressions 0)" in done.stdout + assert done.returncode == int(bool(regressions)), done.stdout + done.stderr + result = "FAIL" if regressions else "PASS" + assert f"complexity={result} (cap 10, over_cap {over_cap}, regressions {regressions})" in done.stdout def test_complexity_rejects_old_python(git_repo, module_path, tmp_path): @@ -133,13 +121,9 @@ def test_complexity_rejects_old_python(git_repo, module_path, tmp_path): assert "requires Python 3.14+" in done.stderr -@pytest.mark.parametrize("path,cap,grew,expected_rc", [ - ("core/CONTRACT.md", 1500, True, 1), - ("core/CONTRACT.md", 1500, False, 0), - ("docs/DELEGATION.md", 660, True, 1), - ("docs/DELEGATION.md", 660, False, 0), -]) -def test_markdown_doc_budgets(git_repo, path, cap, grew, expected_rc): +@pytest.mark.parametrize("path,cap", [("core/CONTRACT.md", 1500), ("docs/DELEGATION.md", 660)]) +@pytest.mark.parametrize("grew", [True, False]) +def test_markdown_doc_budgets(git_repo, path, cap, grew): doc = git_repo / path doc.parent.mkdir(parents=True) doc.write_text("line\n" * (cap + 5)) @@ -147,4 +131,4 @@ def test_markdown_doc_budgets(git_repo, path, cap, grew, expected_rc): if grew: doc.write_text("line\n" * (cap + 6)) done = run_budget(git_repo, base) - assert done.returncode == expected_rc, done.stdout + done.stderr + assert done.returncode == int(grew), done.stdout + done.stderr