Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 22 additions & 47 deletions src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,51 +165,30 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str,
return candidate_id, sorted(source_numbers), sorted(missing)


def _repo_identity(repo: JsonObject) -> tuple[object, object]:
return repo.get("id"), repo.get("full_name")


def _candidate_snapshot(
candidate: JsonObject,
*,
event_pr: JsonObject,
repository: JsonObject,
candidate: JsonObject, number: int, event_head: JsonObject, repository: JsonObject,
expected_identity: tuple[object, object, object, object],
) -> None:
_require(
candidate.get("number") == event_pr.get("number"),
"GitHub returned the wrong candidate PR",
)
_require(candidate.get("state") != "closed", "Mergify candidate PR is superseded (closed)")
_require(candidate.get("state") == "open", "Mergify candidate PR is not open")
_require(candidate.get("number") == number, "GitHub returned the wrong candidate PR")
state = candidate.get("state")
state_error = "Mergify candidate PR is superseded (closed)" if state == "closed" else "Mergify candidate PR is not open"
_require(state == "open", state_error)
_require(candidate.get("draft") is True, "Mergify candidate PR must be a draft")
_require(
_identity(candidate.get("user")) == expected_identity,
"Candidate author is not the verified Mergify GitHub App",
)
head = candidate.get("head")
event_head = event_pr.get("head")
base = candidate.get("base")
_require(
isinstance(head, dict) and isinstance(event_head, dict) and isinstance(base, dict),
"Candidate refs are missing",
)
_require(
head.get("sha") == event_head.get("sha"),
"Candidate head changed after the workflow event",
)
_require(
head.get("ref") == event_head.get("ref")
and isinstance(head.get("ref"), str)
and head["ref"].startswith(QUEUE_BRANCH_PREFIX),
"Mergify candidate has an unexpected head ref",
)
_require(
base.get("ref") == "main",
"Mergify candidate must target the real main branch",
)
expected_repo = (repository.get("id"), repository.get("full_name"))
_require(_identity(candidate.get("user")) == expected_identity,
"Candidate author is not the verified Mergify GitHub App")
head, base = candidate.get("head"), candidate.get("base")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Head-ref prefix check now depends on an earlier check in the caller

_candidate_snapshot no longer checks that event_head is a dict or that head.ref starts with QUEUE_BRANCH_PREFIX. Today nothing changes, because the only caller, _attest_candidate_once, does both checks first: _object(...) at line 444 and the prefix check at line 446. The new check head.get("ref") == event_head.get("ref") still rejects any ref that isn't a queue branch, and the error message is unchanged. The risk is in the future: the function's safety now rests on a check that lives somewhere else. If anyone calls _candidate_snapshot from a different place, the prefix check is silently lost. A small fix is to add a one-line comment or docstring saying event_head must already be validated and prefix-checked.

_require(isinstance(head, dict) and isinstance(base, dict), "Candidate refs are missing")
_require(head.get("sha") == event_head.get("sha"), "Candidate head changed after the workflow event")
_require(head.get("ref") == event_head.get("ref"), "Mergify candidate has an unexpected head ref")
_require(base.get("ref") == "main", "Mergify candidate must target the real main branch")
expected_repo = _repo_identity(repository)
for label, repo in (("head", head.get("repo")), ("base", base.get("repo"))):
_require(
isinstance(repo, dict) and (repo.get("id"), repo.get("full_name")) == expected_repo,
f"Mergify candidate {label} repository does not match this repository",
)
_require(isinstance(repo, dict) and _repo_identity(repo) == expected_repo,
f"Mergify candidate {label} repository does not match this repository")


def _source_fingerprint(source: JsonObject) -> tuple[object, ...]:
Expand Down Expand Up @@ -263,8 +242,7 @@ def _attest_source(
_require(
base.get("ref") == "main"
and isinstance(base_repo, dict)
and (base_repo.get("id"), base_repo.get("full_name"))
== (repository.get("id"), repository.get("full_name")),
and _repo_identity(base_repo) == _repo_identity(repository),
f"source PR #{number} does not target this repository's main branch",
)
source_sha = head.get("sha")
Expand Down Expand Up @@ -503,8 +481,7 @@ def _attest_candidate_once(
candidate_path = f"/repos/{full_name}/pulls/{candidate_number}"
def recheck_candidate(message: str = "GitHub candidate lookup returned an invalid payload") -> None:
candidate = _object(github_get(candidate_path), message)
_candidate_snapshot(candidate, event_pr=event_pr, repository=repository,
expected_identity=expected_identity)
_candidate_snapshot(candidate, candidate_number, event_head, repository, expected_identity)

recheck_candidate()

Expand Down Expand Up @@ -590,6 +567,4 @@ def live_lineage() -> tuple[str, list[int], list[str]]:
f"source PR #{number} metadata changed during attestation",
CandidateRaceError,
)
return [
{"number": number, "head_sha": source_snapshots[number][0]} for number in first_lineage[1]
]
return [{"number": number, "head_sha": sha} for number, (sha, _) in source_snapshots.items()]
49 changes: 20 additions & 29 deletions src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,11 @@ def _has_replacement_refs(common_dir: Path) -> bool:
return True
return True
try:
packed = (common_dir / "packed-refs").read_bytes()
return b" refs/replace/" in (common_dir / "packed-refs").read_bytes()
except FileNotFoundError:
return False
except OSError:
return True
return b" refs/replace/" in packed


def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *,
Expand All @@ -104,11 +103,8 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *,
hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override."
ref = f"refs/remotes/origin/{branch}"
if refresh:
fetched = _proc.run(
["git", "fetch", "--quiet", "--no-tags", "--no-recurse-submodules",
"--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}"],
cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=read_timeout(60),
)
fetched = run_git(worktree, "fetch", "--quiet", "--no-tags", "--no-recurse-submodules",
"--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}", timeout=read_timeout(60))
if fetched.exit_code != 0:
raise ConfigError(f"could not refresh origin/{branch}. {hint}")
directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else []
Expand All @@ -129,13 +125,12 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *,
if shown.exit_code != 0:
raise ConfigError(f"cannot read {source}. {hint}")
try:
data = tomllib.loads(shown.stdout.encode("utf-8", errors="surrogateescape").decode("utf-8"))
text = shown.stdout.encode("utf-8", errors="surrogateescape").decode("utf-8")
return _build(tomllib.loads(text)), revision

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: _build now runs inside the TOML parse/decode try block

The result is the same today. _build raises only ConfigError, and ConfigError derives from LoopZeroError, not from UnicodeDecodeError or TOMLDecodeError, so every error still reaches the same handler as before. The new layout is still more fragile: if _build ever raises a ValueError subclass that matches an earlier except clause, it would get the wrong message. No change is needed. Just keep this in mind if _build starts calling decoding helpers.

except UnicodeDecodeError as exc:
raise ConfigError(f"{source}: {exc}") from exc
except tomllib.TOMLDecodeError as exc:
raise ConfigError(f"{source}: invalid TOML: {exc}. {hint}") from None
try:
return _build(data), revision
except ConfigError as exc:
raise ConfigError(f"{source}: {exc}. {hint}") from None

Expand All @@ -153,12 +148,12 @@ def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: boo
)
branch = ref.removeprefix(prefix)
policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, read_timeout=read_timeout)
if policy.base_branch == branch:
return replace(policy, trusted_base_revision=revision)
base, revision = _remote_workflow(worktree, policy.base_branch, previous, refresh=refresh, read_timeout=read_timeout)
if base.base_branch != policy.base_branch:
raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config")
return replace(base, trusted_base_revision=revision)
if policy.base_branch != branch:
branch = policy.base_branch
policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, read_timeout=read_timeout)
if policy.base_branch != branch:
raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config")
return replace(policy, trusted_base_revision=revision)


def _build(data: dict[str, Any]) -> Config:
Expand Down Expand Up @@ -225,21 +220,18 @@ def _build(data: dict[str, Any]) -> Config:
if "/" in runner[0] and not Path(runner[0]).is_absolute():
raise ConfigError("checks.runner executable paths must be absolute")
kwargs["check_runner"] = runner
if "inputs" in checks:
inputs = {}
for key, value in checks["inputs"].items():
label = f'checks.inputs."{key}"'
if key != "*" and key not in commands:
raise ConfigError(f"{label} must exactly match a checks.commands entry")
inputs[key] = _strings(label, value)
kwargs["inputs"] = inputs
inputs = {}
for key, value in checks.get("inputs", {}).items():
label = f'checks.inputs."{key}"'
if key != "*" and key not in commands:
raise ConfigError(f"{label} must exactly match a checks.commands entry")
inputs[key] = _strings(label, value)
for key, field, read in (("env_allowlist", "env_allowlist", _strings),
("ro_paths", "sandbox_ro", _host_paths),
("writable", "writable", _host_paths)):
if key in checks:
kwargs[field] = read(f"checks.{key}", checks[key])
if "env" in checks:
kwargs["env"] = _env_table(checks["env"])
env = _env_table(checks.get("env", {}))
if "scratch" in checks:
kwargs["scratch"] = _strings("checks.scratch", checks["scratch"])
for entry in kwargs["scratch"]:
Expand Down Expand Up @@ -268,7 +260,7 @@ def _build(data: dict[str, Any]) -> Config:
reviewer_ro_paths=reviewer_ro_paths,
review_chunk_bytes=review_chunk_bytes,
network=checks.get("network", False),
**kwargs,
inputs=inputs, env=env, **kwargs,
)


Expand Down Expand Up @@ -326,8 +318,7 @@ def _env_table(table: dict[str, Any]) -> tuple[tuple[str, str], ...]:

def _limits(table: dict[str, Any]) -> ResourceLimits:
defaults = ResourceLimits()
allowed = tuple(defaults.__dict__)
_reject_unknown("checks.limits", table, allowed)
_reject_unknown("checks.limits", table, defaults.__dict__)
values = defaults.__dict__ | table
for name, value in values.items():
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
Expand Down
16 changes: 5 additions & 11 deletions src/loopzero/hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import json
import os
import sys
from collections.abc import Callable
from contextlib import suppress
from pathlib import Path

Expand Down Expand Up @@ -71,10 +70,9 @@ def _run(cfg: Config) -> int:
head = pr["head"]["sha"]
candidate = (pr["head"]["ref"].startswith("mergify/merge-queue/")
or pr["user"]["login"] == "mergify[bot]")
if not candidate and pr.get("merged") is True:
active = _candidate_event(event, head) if candidate else pr.get("merged") is not True
if not active:
return 0 # A landed source needs no new verdict; a late refresh must not turn it red.
if candidate and not _candidate_event(event, head):
return 0
def publish(state: str, message: str) -> None:
github.commit_status(cfg.repo, head, eligibility.CONTEXT, state, message[:140])
publish("pending", "Refreshing live source review evidence")
Expand Down Expand Up @@ -110,7 +108,9 @@ def policy(source_number: int, source: dict) -> None:
print(f"Eligibility pending: evidence unavailable ({exc})", file=sys.stderr)
return 0
except Exception as exc:
_mark_refresh_failed(publish, exc)
if not isinstance(exc, github.StatusLimitReached):
with suppress(Exception):
publish("failure", "Eligibility refresh failed; inspect workflow logs")
raise
_publish_verdict(cfg.repo, head, state, message[:140])
print(message)
Expand Down Expand Up @@ -142,11 +142,5 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None
raise LoopZeroError(f"Could not confirm eligibility status publication: {exc}") from exc


def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None:
if not isinstance(exc, github.StatusLimitReached):
with suppress(Exception):
publish("failure", "Eligibility refresh failed; inspect workflow logs")


if __name__ == "__main__":
raise SystemExit(main())
Loading