diff --git a/.github/workflows/eligibility.yml b/.github/workflows/eligibility.yml index 46b4faf6..a85b85ba 100644 --- a/.github/workflows/eligibility.yml +++ b/.github/workflows/eligibility.yml @@ -1,7 +1,7 @@ name: review eligibility on: pull_request_target: - types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft] + types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft, labeled, unlabeled] workflow_run: workflows: [review event] types: [completed] @@ -20,12 +20,15 @@ jobs: # job would fail closed (no MERGIFY_API_KEY) and publish a failure, never a pass. source-eligibility: # Skip closed PRs and title/body edits before a runner is allocated. Draft churn - # waits for readiness; conversion to draft still invalidates prior eligibility. + # waits for readiness except when conversion or a hold change needs a refresh. if: >- github.event_name != 'pull_request_target' || ( github.event.action != 'closed' && - (!github.event.pull_request.draft || github.event.action == 'converted_to_draft') && + (!github.event.pull_request.draft || github.event.action == 'converted_to_draft' || + github.event.action == 'labeled' || github.event.action == 'unlabeled') && (github.event.action != 'edited' || github.event.changes.base != null) && + ((github.event.action != 'labeled' && github.event.action != 'unlabeled') || + github.event.label.name == 'hold') && github.event.pull_request.user.login != 'mergify[bot]' && !startsWith(github.event.pull_request.head.ref, 'mergify/merge-queue/')) # Skipped events stay out of the group and cannot replace a pending refresh. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 560b2481..c474e6e7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -286,6 +286,9 @@ review publication; the existing reviewer selector and delivery gates still appl [GitHub transport](../src/loopzero/github.py) owns API access and changed-only PR writes. [Hosted dispatch](../src/loopzero/hosted.py) and [eligibility](../src/loopzero/eligibility.py) evaluate trusted review evidence. +Local readiness and hosted source and candidate eligibility reject PRs with +merge-authority holds. Adding or removing a hold refreshes source eligibility +even when the head stays the same. Merge admission rechecks the live hold. [Mergify](MERGIFY.md) describes optional source-preserving queue integration; [candidate validation](../src/loopzero/candidate.py) belongs at that boundary. Candidate lineage reads wait on zero or multiple live batch matches with exponential diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index df90da9c..fc164944 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -258,9 +258,8 @@ def _readiness( wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None, *, workflow_wait: bool = False, announce_receipt: bool = False, ) -> github.Readiness: - if "hold" in pr.labels: - reason = f"PR #{pr.number} {github.MERGE_HOLD_MESSAGE}" - return github.Readiness(ready=False, reasons=(reason,)) + if hold := github.merge_hold(pr.number, pr.labels): + return github.Readiness(False, (hold,)) if reviews is None: reviews = _pr_reviews(config.repo, pr.number) publishers = config.review_publishers or (github.login(),) @@ -421,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) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 4de8fb3d..41de7f3c 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -169,6 +169,8 @@ def evaluate(repo: str, number: int, head: str, base: str, pr = github.pr_view(repo, number) if pr.head_sha != head: return github.Readiness(False, ("source head changed; refresh eligibility",)) + if hold := github.merge_hold(pr.number, pr.labels): + return github.Readiness(False, (hold,)) reviews, page = [], 1 while True: batch = github.api_get(f"repos/{repo}/pulls/{number}/reviews?per_page=100&page={page}") diff --git a/src/loopzero/github.py b/src/loopzero/github.py index dc64281d..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", "")): @@ -513,7 +522,10 @@ def _api(endpoint: str, payload: dict, method: str = "POST", path.unlink(missing_ok=True) -MERGE_HOLD_MESSAGE = "has a merge-authority hold; ask the decisions owner to release it" +def merge_hold(number: int, labels: tuple[str, ...]) -> str | None: + if "hold" in labels: + return f"PR #{number} has a merge-authority hold; ask the decisions owner to release it" + return None def _pr_labels(data: dict) -> tuple[str, ...]: @@ -1343,8 +1355,8 @@ def merged_sha( if isinstance(sha, str) and re.fullmatch(r"[0-9a-f]{40}", sha): return sha elif not view["merged"] and view.get("state") == "open": - if check_hold and "hold" in _pr_labels(view): - raise GhError(argv, f"PR #{number} {MERGE_HOLD_MESSAGE}") + if check_hold and (hold := merge_hold(number, _pr_labels(view))): + raise GhError(argv, hold) return None # An open PR's merge_commit_sha is only a test merge. if not view["merged"] and view.get("state") == "closed": raise ClosedUnmerged(argv, "PR closed without a verified merge or invalid merge evidence") diff --git a/tests/test_cli.py b/tests/test_cli.py index 9d44b146..c09d043c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -21,7 +21,7 @@ import pytest -from loopzero import cli, config, github, mergify +from loopzero import cli, config, github, hosted, mergify from loopzero._proc import Completed, build_env from loopzero.types import CheckReport, CheckResult, Finding, ReviewResult from tests.conftest import git, init_git_repo @@ -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, @@ -2588,6 +2632,34 @@ def test_hold_blocks_ready_and_merge(wt, gh, capsys, monkeypatch, command, check assert any(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == (command == "ready") +def test_hold_label_refresh_matches_local_readiness(wt, gh, head, tmp_path, monkeypatch, capsys): + trusted = tmp_path / "trusted" + trusted.mkdir() + (trusted / "workflow.toml").write_text(WORKFLOW + f'review_publishers = ["{LOGIN}"]\n') + event = trusted / "event.json" + monkeypatch.setenv("GITHUB_REPOSITORY", REPO) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) + gh.respond(f"api repos/{REPO}/statuses/{head}", {}) + + for action, labels, expected in ( + ("labeled", [{"name": "hold"}], 1), ("unlabeled", [], 0), + ): + arm_approved_ready_pr(gh, head, wt, isDraft=False, labels=labels) + gh.respond(f"api repos/{REPO}/pulls/7", rest_pr_json( + pr_json(headRefOid=head, isDraft=False, labels=labels))) + event.write_text(json.dumps({"action": action, "pull_request": {"number": 7}})) + code, out, _ = run(capsys, "ready") + assert code == expected + assert ("merge-authority hold" in out) == bool(labels) + with monkeypatch.context() as hosted_env: + hosted_env.chdir(trusted) + assert hosted.main() == expected + capsys.readouterr() + payload = json.loads(gh.calls[-1]["--input"]) + assert gh.calls[-1]["argv"][1] == f"repos/{REPO}/statuses/{head}" + assert payload["state"] == ("failure" if labels else "success") + + @pytest.mark.parametrize("wait,elapsed,conclusion,expected", [ (0, 0, None, 3), (1, 0, "failure", 1), (1, 0.25, "success", 0), (1, 6, "success", 3), ]) diff --git a/tests/test_hosted.py b/tests/test_hosted.py index 60092cc1..f9295795 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -169,6 +169,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er @pytest.mark.parametrize("case,error,message", [ ("valid", None, ""), ("policy", hosted.LoopZeroError, "no review recorded"), + ("hold", hosted.LoopZeroError, "source #101: PR #101 has a merge-authority hold"), ("merged", CandidateError, "not open"), ("race", CandidateRaceError, "metadata changed"), ("malformed", CandidateError, "invalid payload"), @@ -178,11 +179,24 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er ("stale", hosted.LoopZeroError, "head is no longer current"), ("untrusted", CandidateError, "head event was not sent"), ]) -def test_candidate_publication_and_event_controls(tmp_path, monkeypatch, case, error, message): +def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatch, case, error, message): event = candidate_event() event["action"] = "edited" if case == "metadata" else event["action"] event["sender"]["id"] = 1 if case == "untrusted" else event["sender"]["id"] values = candidate_payloads(event) + if case in {"valid", "hold"}: + gh = FakeGh(fake_bin, tmp_path) + gh.respond("api graphql", threads_json()) + for number, sha in [(101, "1" * 40), (102, "2" * 40), (900, "c" * 40)]: + path = f"/repos/owner/repo/pulls/{number}" + values[path] = fixtures.rest_pr_json(pr_json( + number=number, headRefOid=sha, isDraft=False, + labels=[{"name": "hold"}] if case == "hold" and number == 101 else [], + )) | values[path] + values[f"{path}/reviews?per_page=100&page=1"] = [{ + "state": "APPROVED", "commit_id": sha, "user": {"login": "trusted-publisher"}, + "body": f"\nreview: **approve**", + }] if case == "stale": values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40 if case == "malformed": @@ -214,14 +228,18 @@ def publish(*args): raise RuntimeError("publication details must not replace attestation error") monkeypatch.setattr(github, "commit_status", publish) evaluated = [] + real_evaluate = hosted.eligibility.evaluate def evaluate(repo, number, head, base, publishers): evaluated.append((repo, number, head, base, publishers)) + if case in {"valid", "hold"}: + return real_evaluate(repo, number, head, base, publishers) if case == "interrupt": raise KeyboardInterrupt() reasons = (github.MISSING_REVIEW_REASON,) if case == "policy" else () return github.Readiness(not reasons, reasons) - monkeypatch.setattr(github, "pr_view", lambda *_: SimpleNamespace(head_sha=("d" if case == "head" else "c") * 40)) + if case not in {"valid", "hold"}: + monkeypatch.setattr(github, "pr_view", lambda *_: SimpleNamespace(head_sha=("d" if case == "head" else "c") * 40)) monkeypatch.setattr(hosted.eligibility, "evaluate", evaluate) monkeypatch.setattr("loopzero.mergify.api_get", lambda repo, suffix: candidate_status() if (repo, suffix) == ("owner/repo", "/merge-queue/status?branch=main") else None) @@ -249,11 +267,14 @@ def evaluate(repo, number, head, base, publishers): def test_privileged_workflow_runs_only_the_trusted_default_branch_package(): workflow = (Path(__file__).parents[1] / ".github/workflows/eligibility.yml").read_text() assert "pull_request_target:" in workflow + events = next(line for line in workflow.splitlines() if line.strip().startswith("types:")) + assert "labeled" in events and "unlabeled" in events source, candidate = workflow.split("\n source-eligibility:\n", 1)[1].split( "\n candidate-eligibility:\n", 1 ) assert " environment:" not in source assert "${{ secrets.MERGIFY_API_KEY }}" not in source + assert "github.event.label.name == 'hold'" in source assert "environment:\n name: mergify-metadata\n deployment: false" in candidate assert "MERGIFY_API_KEY: ${{ secrets.MERGIFY_API_KEY }}" in candidate for job in (source, candidate):