diff --git a/SETUP.md b/SETUP.md index 0cc199fb..bc1bddce 100644 --- a/SETUP.md +++ b/SETUP.md @@ -497,6 +497,12 @@ the consumer CI pin that supplies `loopzero.hosted` or `loopzero.eligibility` eligibility workflow for the existing PR, or run the command below with its unchanged source SHA. The refreshed reader can use the approval already on GitHub. +For inherited review coverage, advance both source and candidate workflow pins to +a revision containing [23219dd3 (#1081)](https://github.com/feder-positronics/loop-zero/commit/23219dd39e641549164c346e137f4e09718115f6). +The updated reader accepts an ancestor approval only across verified clean merges +from the configured base. After deploying both pins, refresh eligibility for open +sources judged by the older reader so their statuses reflect the updated policy. + From a trusted base checkout, run: ```sh diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 2077c223..48a64159 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -420,9 +420,8 @@ def _validation_section(wt: Path, head: str, config: Config) -> str: lines = [f"Recorded for `{recorded[:12]}`" + ("" if recorded == head else " (not current head)")] if _check_report_problem(loaded, wt, config, head, require_pass=False): lines[0] += " (unverified, run `loopzero check`)" - lines += [ - f"- `{r.command}`: exit {r.exit_code}" for r in results - ] or ["- (no check commands configured)"] + lines += [f"- `{github.redact_credentials(r.command)}`: exit {r.exit_code}" + for r in results] or ["- (no check commands configured)"] return "\n".join(lines) @@ -597,7 +596,8 @@ def cmd_check(args: argparse.Namespace) -> int: report = sandbox.run_checks(config, wt, progress=lambda command: print( f"running: {command}", flush=True), status=lambda message: print(message, flush=True), - checkpoint=lambda partial: _save_report(wt, partial)) + checkpoint=lambda partial: _save_report(wt, partial), + workflow=args.config or f"origin/{config.base_branch}:workflow.toml") except sandbox.SandboxUnavailable as exc: print(f"sandbox unavailable: {exc}", file=sys.stderr) return 2 diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 508ac7a9..cc1ca931 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -193,7 +193,7 @@ def _build(data: dict[str, Any]) -> Config: ) review[family] = ReviewConfig(table.get("model"), table.get("effort"), allowed) - commands = _strings("checks.commands", checks.get("commands", [])) + commands = _commands(checks.get("commands", [])) kwargs: dict[str, Any] = {} if "runner" in checks: runner = _strings("checks.runner", checks["runner"]) @@ -272,6 +272,13 @@ def _reject_unknown(where: str, table: dict[str, Any], allowed: Any) -> None: raise ConfigError(f"unknown key(s) in {where}: {', '.join(unknown)}") +def _commands(value: list[Any]) -> tuple[str, ...]: + commands = _strings("checks.commands", value) + if any(not command.strip() for command in commands): + raise ConfigError("checks.commands entries must each be a nonblank command") + return commands + + def _strings(label: str, value: list[Any]) -> tuple[str, ...]: if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value): raise ConfigError(f"{label} must be a list of non-empty strings") diff --git a/src/loopzero/github.py b/src/loopzero/github.py index c9a77a48..45fb8ce2 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -197,6 +197,15 @@ def _api_path(args: tuple[str, ...]) -> str: return "/" + path.lstrip("/") +def redact_credentials(value: str) -> str: + value = re.sub(r"""(?i)(https?://)[^\s/?#'"<>`]+@""", r"\1[REDACTED]@", value) + value = re.sub(r"""(?i)(\bauthorization(?:\\?['"])?[ \t]*:[ \t]*)(\\?['"])(?:(?!\2)(?:\\.|[^\\\r\n]))+\2""", + r"\1\2[REDACTED]\2", value) + return re.sub(r"""(?i)((?P['"])?\bauthorization[ \t]*:[ \t]*)""" + r"""(?(quote)(?:\\.|(?!(?P=quote))[^\\\r\n])+|(?:[a-z][\w-]*[ \t]+)?(?:\\.|[^\\\s'"`])+)""", + r"\1[REDACTED]", value) + + def _redact_tokens(value: str, token: str = "") -> str: for secret in (token, os.environ.get("GH_TOKEN", ""), os.environ.get("GITHUB_TOKEN", "")): diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index f74eed7e..7409f050 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -80,7 +80,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO progress: Callable[[str], None] | None = None, status: Callable[[str], None] | None = None, checkpoint: Callable[[CheckReport], None] | None = None, - _resolved: bool = False) -> CheckReport: + workflow: str | Path = "workflow.toml", _resolved: bool = False) -> CheckReport: """Run checks, stopping at the first failure; status emits only stage metadata. progress receives each command before launch, as before. Optional status receives @@ -129,7 +129,8 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO for index, command in enumerate(commands): if progress: progress(command) - key = _input_key(config, worktree, command, base) if not dirty else None + key = _input_key(config, worktree, command, "" if dirty else base, + status=status, workflow=workflow) old = previous.get(command) if key and old and old.input_key == key: result = old @@ -253,19 +254,43 @@ def settings_fingerprint(config: Config, worktree: Path, *, base: str | None = N return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() -def _input_key(config: Config, worktree: Path, command: str, base: str) -> str | None: - if not base or (command not in config.inputs and "." not in config.inputs.get("*", ())): - return None - paths = (*config.inputs.get(command, ()), *config.inputs.get("*", ())) +def _input_blobs(config: Config, worktree: Path, paths: tuple[str, ...]) -> str | None: # Empty pathspecs must not accidentally mean the whole tree. + if not paths: + return "" empty = _git(config, worktree, "hash-object", "-t", "tree", "/dev/null").strip() try: - blobs = _git(config, worktree, "-c", "core.quotePath=true", "diff-tree", "--no-commit-id", - "--raw", "-r", "--no-abbrev", empty, "HEAD", "--", *paths) if paths else "" + return _git(config, worktree, "-c", "core.quotePath=true", "diff-tree", "--no-commit-id", + "--raw", "-r", "--no-abbrev", empty, "HEAD", "--", *paths) except OSError as exc: if exc.errno == errno.E2BIG: return None raise + + +def _input_key(config: Config, worktree: Path, command: str, base: str, *, + status: Callable[[str], None] | None = None, + workflow: str | Path = "workflow.toml") -> str | None: + if command not in config.inputs and "." not in config.inputs.get("*", ()): + return None + if not base and status is None: + return None + entries = {key: config.inputs[key] for key in (command, "*") if key in config.inputs} + try: + blobs = _input_blobs(config, worktree, tuple(path for paths in entries.values() for path in paths)) + except (SandboxUnavailable, _proc.ProcTimeout, OSError, ValueError): + if not base: + return None + raise + if blobs == "" and status: + status(f"{workflow}: checks.inputs for {command!r} matches no files in HEAD. " + f"Correct these entries: {entries!r}. Running the check fresh.") + if not blobs or not base: + return None + return _hash_inputs(config, worktree, command, base, blobs) + + +def _hash_inputs(config: Config, worktree: Path, command: str, base: str, blobs: str) -> str | None: contents = [] root = worktree.resolve() try: diff --git a/tests/test_cli.py b/tests/test_cli.py index 6933ecd3..c09d043c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -957,6 +957,50 @@ def test_pr_pushes_and_creates_draft( assert "- `echo ok`: exit 0" in body and "- `test -f README.md`: exit 0" in body +@pytest.mark.parametrize("refresh", [False, True]) +def test_pr_validation_redacts_private_check_commands(wt, gh, capsys, tmp_path, refresh): + command = ( + "git ls-remote 'https://x-access-token:ghs_FAKE0123@example.invalid/repo.git' " + "&& curl -H 'Authorization: Bearer opaque-fake-header' https://example.invalid/ " + r"&& curl -H Authorization:\ Bot\ opaque-fake-header https://example.invalid/ " + """&& curl -d '{"Authorization": "Bearer opaque-fake-header"}' https://example.invalid/ """ + r'''&& curl -d "{\"Authorization\": \"Bearer opaque-fake-header\"}" https://example.invalid/ ''' + """&& python -c "request(headers={'Authorization': 'Basic opaque-fake-header'})" """ + """&& curl -H 'Authorization: Digest username="fake-user", response="opaque-fake-header"' """ + "https://example.invalid/" + ) + private = tmp_path / "private.toml" + private.write_text(WORKFLOW.replace(json.dumps("echo ok"), json.dumps(command))) + cfg = config.load(private) + head = head_of(wt) + results = (CheckResult(command, 7, 0.1, ""), CheckResult("test -f README.md", 0, 0.1, "")) + cli._save_report(wt, CheckReport(head, False, results, cli.sandbox.settings_fingerprint(cfg, wt))) + + if refresh: + git(wt, "push", "-q", "-u", "origin", "lz/t1") + gh.respond_pr_list([pr_json(headRefOid=head)]) + gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) + cli._refresh_pr_checks(wt, cfg) + else: + gh.respond(branch_history_key(), []) + gh.respond_pr_list([]) + gh.respond_pr_create(pr_json(headRefOid=head)) + assert run(capsys, "--config", str(private), "pr")[0] == 0 + + body = json.loads(gh.calls[-1]["--input"])["body"] + assert "ghs_FAKE0123" not in body and "opaque-fake-header" not in body + assert "git ls-remote 'https://[REDACTED]@example.invalid/repo.git'" in body + assert "curl -H 'Authorization: [REDACTED]' https://example.invalid/" in body + assert "curl -H Authorization:[REDACTED] https://example.invalid/" in body + assert """curl -d '{"Authorization": "[REDACTED]"}' https://example.invalid/""" in body + assert r'''curl -d "{\"Authorization\": \"[REDACTED]\"}" https://example.invalid/''' in body + assert """python -c "request(headers={'Authorization': '[REDACTED]'})" """ in body + assert "'Authorization: [REDACTED]' https://example.invalid/`: exit 7" in body + assert f"Recorded for `{head[:12]}`" in body and "(unverified" not in body + assert "- `test -f README.md`: exit 0" in body + assert cli._load_report(wt).results == results + + @pytest.mark.parametrize("duplicate", [None, "CLOSED", "OPEN"]) def test_pr_refuses_completed_branch_before_any_publication( wt: Path, gh: FakeGh, fake_tool, tmp_path: Path, capsys, duplicate: str | None, diff --git a/tests/test_config.py b/tests/test_config.py index 509855bf..a877a3db 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -60,6 +60,9 @@ def test_load_full_config(tmp_path): limits=ResourceLimits(memory_mb=1024, file_mb=512), ) + padded = FULL.replace('"uv run pytest -q"', '" uv run pytest -q "') + assert config.load(write(tmp_path, padded)).checks[0] == " uv run pytest -q " + def test_load_applies_defaults(tmp_path): loaded = config.load(write(tmp_path, '[repo]\nname = "o/n"\n')) @@ -112,6 +115,8 @@ def test_invalid_toml(tmp_path): ('[repo]\nname = 3\n', "repo.name must be a str"), ('[repo]\nname = "o/n"\n[checks]\ncommands = "pytest"\n', "checks.commands must be a list"), ('[repo]\nname = "o/n"\n[checks]\ncommands = ["ok", 1]\n', "non-empty strings"), + ('[repo]\nname = "o/n"\n[checks]\ncommands = ["true", " "]\n', + r"workflow\.toml: checks\.commands.*nonblank command"), ('[repo]\nname = "o/n"\n[checks]\nnetwork = "yes"\n', "checks.network must be a bool"), ('[repo]\nname = "o/n"\n[delivery]\nmerge = "ff"\n', "delivery.merge must be one of"), ('[repo]\nname = "o/n"\n[delivery]\nreviewers = ["gpt"]\n', "delivery.reviewers entries"), diff --git a/tests/test_hosted.py b/tests/test_hosted.py index f9295795..b2d5ddba 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -2,6 +2,8 @@ import json import subprocess import sys +from contextlib import nullcontext +from functools import partial from pathlib import Path from types import SimpleNamespace @@ -10,6 +12,7 @@ from loopzero import github, hosted from loopzero.candidate import CandidateError, CandidateRaceError from tests import test_github as fixtures +from tests.conftest import git from tests.test_candidate import event as candidate_event from tests.test_candidate import payloads as candidate_payloads from tests.test_candidate import status as candidate_status @@ -97,6 +100,58 @@ def test_source_publication_is_bound_to_live_review(publisher, case, blocker, st assert status != "pending" or statuses[-1]["description"] == "Awaiting trusted review of current source head" +@pytest.mark.parametrize("candidate", [False, True]) +@pytest.mark.parametrize("change", ["exact", "ordinary", "clean merge"]) +def test_hosted_review_coverage_after_source_head_changes( + publisher, git_repo, monkeypatch, candidate, change, +): + git(git_repo, "switch", "-qc", "source") + git(git_repo, "commit", "-qm", "reviewed source", "--allow-empty") + reviewed = git(git_repo, "rev-parse", "HEAD").strip() + git(git_repo, "switch", "-q", "main") + git(git_repo, "commit", "-qm", "base advance", "--allow-empty") + base = git(git_repo, "rev-parse", "HEAD").strip() + git(git_repo, "switch", "-q", "source") + if change == "ordinary": + git(git_repo, "commit", "-qm", "unreviewed source", "--allow-empty") + elif change == "clean merge": + git(git_repo, "merge", "-q", "--no-edit", "main") + head = git(git_repo, "rev-parse", "HEAD").strip() + source = fixtures.rest_pr_json(pr_json(headRefOid=head)) + source["base"]["sha"] = base + publisher.respond(f"api repos/{REPO}/pulls/7", source) + publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", [{ + "state": "COMMENTED", "commit_id": reviewed, "user": {"login": "trusted-publisher"}, + "body": f"\n" + "loopzero primary review by claude: **approve** (0 critical, 0 important, 0 suggestion)", + }]) + publisher.respond(f"api repos/{REPO}/compare/{reviewed}...{head}", {"status": "ahead"}) + monkeypatch.setattr(hosted.candidate_mod, "fetched_git", + lambda *_: nullcontext(partial(git, git_repo))) + + target = head + if candidate: + target = HEAD + Path("event.json").write_text(json.dumps({ + "action": "opened", "pull_request": {"number": 9, "head": {"sha": target}}, + })) + publisher.respond(f"api repos/{REPO}/pulls/9", fixtures.rest_pr_json( + pr_json(number=9, headRefOid=target), branch="mergify/merge-queue/main", + )) + monkeypatch.setattr(hosted.candidate_mod, "attest_candidate", + lambda _event, *, source_policy, **_: source_policy(7, source)) + publisher.respond(f"api repos/{REPO}/statuses/{target}", {}) + + if change == "ordinary" and candidate: + with pytest.raises(hosted.LoopZeroError, match="no review recorded"): + hosted.main() + else: + assert hosted.main() == 0 + states = [json.loads(call["--input"])["state"] for call in publisher.calls if "--input" in call] + assert states == ["pending", ("failure" if candidate else "pending") + if change == "ordinary" else "success"] + + def test_merged_source_refresh_publishes_nothing(publisher): body = json.dumps({"head": {"sha": HEAD, "ref": "lz/task"}, "user": {"login": "author"}, "merged": True, "title": "before\u2028after"}, ensure_ascii=False) diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 5e805278..e660ee74 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -771,6 +771,43 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch assert report.head == git(git_repo, 'rev-parse', 'HEAD').strip() +@pytest.mark.parametrize("case", ["typo", "empty", "dirty", "no_base"]) +def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case): + (git_repo / ".git/info/exclude").write_text(".loopzero/\n") + command = 'test "$(cat README.md)" = hello' + paths = () if case == "empty" else ("ipnut.txt",) + config = make_config(checks=(command,), inputs={command: paths}) + first = sandbox.run_checks(config, git_repo) + assert first.ok + _save_report(git_repo, first) + (git_repo / "README.md").write_text("fail\n") + if case != "dirty": + git(git_repo, "commit", "-qam", "change actual input") + if case == "no_base": + git(git_repo, "update-ref", "-d", "refs/remotes/origin/main") + + result = sandbox.run_checks(config, git_repo, status=(messages := []).append) + assert result.results[0].exit_code == 1 + assert any("workflow.toml: checks.inputs" in message and repr(paths) in message + for message in messages) + + +@pytest.mark.parametrize("path", [":(bogus)README.md", "README\0.md", "README.md"]) +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) + (git_repo / "README.md").write_text("dirty\n") + command = 'test "$(cat README.md)" = dirty' + config = make_config(checks=(command,), inputs={command: (path,)}) + report = sandbox.run_checks(config, git_repo, status=lambda _: None) + assert report.ok and report.dirty and report.results[0].command == command + + def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base): (git_repo / ".git/info/exclude").write_text(".loopzero/\n") path = git_repo / "README.md"