Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
8 changes: 8 additions & 0 deletions docs/changelog.d/1146-pr-queue-source-commit-provenance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Require reconstructable PR queue source commit provenance

## Fixed

- Make `scripts/build_pr_queue_governance.py::_source_commit()` fail closed on every unreconstructable Git outcome: non-timeout command failures and executable/OS/subprocess errors now raise a stable package-owned `RuntimeError` instead of degrading to a `source_commit: "unknown"` placeholder, while keeping the existing bounded `GIT_METADATA_TIMEOUT_SECONDS` deadline for hung `git rev-parse HEAD` children.
- Accept only canonical full lowercase SHA-1 (exactly 40 hexadecimal characters) or SHA-256 (exactly 64 hexadecimal characters) object identities as the governance source commit; empty, abbreviated, uppercase, non-hexadecimal, undersized, and oversized stdout are rejected with a stable package-owned error before any PR queue governance evidence can be emitted, so every published manifest cites a source that reconstructs the exact evidence build.

- Research basis: Ohm, Plate, Sykosch, and Meier (2020), *Backstabber's Knife Collection: A Review of Open Source Software Supply Chain Attacks*, https://doi.org/10.1007/978-3-030-52683-2_2. The methodological implication for this governance path matches the release-evidence path: mutable or unverifiable provenance identities must never be silently substituted into consumed evidence, so identity resolution fails closed at the boundary where the value is produced.
19 changes: 15 additions & 4 deletions scripts/build_pr_queue_governance.py
Comment thread
seonghobae marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
_GH_STDOUT_MAX_BYTES = MAX_JSON_BYTES
_GH_STDERR_MAX_BYTES = 1024 * 1024
GIT_METADATA_TIMEOUT_SECONDS = 5
_FULL_OBJECT_ID_PATTERN = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
Comment thread
seonghobae marked this conversation as resolved.
Resolved


def _parse_datetime(value: str) -> datetime:
Expand Down Expand Up @@ -128,7 +129,14 @@ def _resolve_path(value: str | Path, *, base: Path) -> Path:


def _source_commit(repo_root: Path) -> str:
"""Return the checked-out commit SHA, failing closed on a hung Git child."""
"""Return the canonical full commit SHA for the checked-out HEAD.

The value must reconstruct the exact governance-evidence source, so every
failure mode fails closed: timeouts, missing executables, non-zero exits,
empty output, and any identity that is not a full lowercase SHA-1 or
SHA-256 object name raise :class:`RuntimeError` instead of degrading to an
unreconstructable placeholder.
"""
try:
completed = subprocess.run(
["git", "rev-parse", "HEAD"],
Expand All @@ -140,9 +148,12 @@ def _source_commit(repo_root: Path) -> str:
)
except subprocess.TimeoutExpired as exc:
raise RuntimeError("source commit lookup timed out") from exc
except Exception:
return "unknown"
return completed.stdout.strip() or "unknown"
except (OSError, subprocess.SubprocessError) as exc:
raise RuntimeError("source commit lookup failed") from exc
candidate = completed.stdout.strip()
if not _FULL_OBJECT_ID_PATTERN.fullmatch(candidate):
raise RuntimeError("source commit is not a full lowercase SHA-1 or SHA-256 object id")
return candidate


def _check(
Expand Down
47 changes: 37 additions & 10 deletions tests/test_pr_queue_governance.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ def _sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()


# Build-level fixtures patch ``_source_commit`` with this canonical identity so
# queue-classification tests do not depend on a real Git checkout; boundary
# behavior of the real helper is covered by test_pr_queue_governance_git_timeout.py.
_CANONICAL_TEST_COMMIT = "0123456789abcdef0123456789abcdef01234567"


def _base_pr(
number: int,
*,
Expand Down Expand Up @@ -122,8 +128,9 @@ def _write_custom_snapshot(
return path


def test_pr_queue_governance_creates_manifest_and_report(tmp_path):
def test_pr_queue_governance_creates_manifest_and_report(tmp_path, monkeypatch):
module = _load_governance()
monkeypatch.setattr(module, "_source_commit", lambda root: _CANONICAL_TEST_COMMIT)
snapshot = _write_snapshot(tmp_path / "snapshot.json")

manifest = module.build_pr_queue_governance(
Expand Down Expand Up @@ -179,8 +186,9 @@ def test_classify_pr_marks_duplicate_and_release_scope_risks():
assert classified["changed_files"] == ["src/a.py", "src/b.py"]


def test_pr_queue_governance_fails_without_snapshot_when_offline(tmp_path):
def test_pr_queue_governance_fails_without_snapshot_when_offline(tmp_path, monkeypatch):
module = _load_governance()
monkeypatch.setattr(module, "_source_commit", lambda root: _CANONICAL_TEST_COMMIT)

manifest = module.build_pr_queue_governance(
_args(tmp_path, None, tmp_path / "pr-queue-governance")
Expand All @@ -191,8 +199,11 @@ def test_pr_queue_governance_fails_without_snapshot_when_offline(tmp_path):
assert "github:snapshot" in failed


def test_duplicate_issue_claim_without_canonical_designation_fails_closed(tmp_path):
def test_duplicate_issue_claim_without_canonical_designation_fails_closed(
tmp_path, monkeypatch
):
module = _load_governance()
monkeypatch.setattr(module, "_source_commit", lambda root: _CANONICAL_TEST_COMMIT)
prs = [
_base_pr(396, body="Closes #394", files=["src/a.py", "tests/a.py"]),
_base_pr(399, body="Fixes: #394", files=["src/b.py", "tests/b.py"]),
Expand All @@ -213,8 +224,11 @@ def test_duplicate_issue_claim_without_canonical_designation_fails_closed(tmp_pa
assert "queue:duplicate_issue_claims" in failed


def test_exactly_one_canonical_designation_resolves_duplicate_claim(tmp_path):
def test_exactly_one_canonical_designation_resolves_duplicate_claim(
tmp_path, monkeypatch
):
module = _load_governance()
monkeypatch.setattr(module, "_source_commit", lambda root: _CANONICAL_TEST_COMMIT)
prs = [
_base_pr(
396,
Expand All @@ -235,8 +249,9 @@ def test_exactly_one_canonical_designation_resolves_duplicate_claim(tmp_path):
assert claim["canonical_pr"] == 396


def test_multiple_canonical_designations_remain_conflicted(tmp_path):
def test_multiple_canonical_designations_remain_conflicted(tmp_path, monkeypatch):
module = _load_governance()
monkeypatch.setattr(module, "_source_commit", lambda root: _CANONICAL_TEST_COMMIT)
prs = [
_base_pr(396, body="Closes #394\nCanonical-For: #394"),
_base_pr(399, body="Closes #394\nCanonical-For: #394"),
Expand All @@ -251,8 +266,11 @@ def test_multiple_canonical_designations_remain_conflicted(tmp_path):
assert manifest["duplicate_issue_claims"]["394"]["canonical_pr"] is None


def test_closed_claimant_leaves_active_queue_and_remains_in_history(tmp_path):
def test_closed_claimant_leaves_active_queue_and_remains_in_history(
tmp_path, monkeypatch
):
module = _load_governance()
monkeypatch.setattr(module, "_source_commit", lambda root: _CANONICAL_TEST_COMMIT)
active = _base_pr(396, body="Closes #394")
closed = _base_pr(399, body="Closes #394", state="CLOSED")
snapshot = _write_custom_snapshot(
Expand All @@ -271,8 +289,9 @@ def test_closed_claimant_leaves_active_queue_and_remains_in_history(tmp_path):
assert manifest["issue_claim_history"][1]["state"] == "CLOSED"


def test_identical_changed_file_sets_emit_nonblocking_warning(tmp_path):
def test_identical_changed_file_sets_emit_nonblocking_warning(tmp_path, monkeypatch):
module = _load_governance()
monkeypatch.setattr(module, "_source_commit", lambda root: _CANONICAL_TEST_COMMIT)
files = ["src/shared.py", "tests/test_shared.py"]
prs = [
_base_pr(1, files=files),
Expand Down Expand Up @@ -633,6 +652,7 @@ def test_build_fails_when_history_snapshot_still_errors_after_retries(
):
"""Real non-recovered transport failure still hard-fails github:snapshot."""
module = _load_governance()
monkeypatch.setattr(module, "_source_commit", lambda root: _CANONICAL_TEST_COMMIT)

def broken_snapshot(repo: str) -> dict:
return {
Expand Down Expand Up @@ -674,19 +694,25 @@ def broken_snapshot(repo: str) -> dict:

def test_source_commit_and_json_helpers_cover_success_and_failure(tmp_path, monkeypatch):
module = _load_governance()
canonical_sha1 = "0123456789abcdef0123456789abcdef01234567"
monkeypatch.setattr(
module.subprocess,
"run",
lambda *args, **kwargs: subprocess.CompletedProcess([], 0, "deadbeef\n", ""),
lambda *args, **kwargs: subprocess.CompletedProcess([], 0, f"{canonical_sha1}\n", ""),
)
assert module._source_commit(tmp_path) == "deadbeef"
assert module._source_commit(tmp_path) == canonical_sha1

monkeypatch.setattr(
module.subprocess,
"run",
lambda *args, **kwargs: (_ for _ in ()).throw(OSError("missing")),
)
assert module._source_commit(tmp_path) == "unknown"
try:
module._source_commit(tmp_path)
except RuntimeError:
pass
else:
raise AssertionError("non-timeout git failure must not degrade to 'unknown'")

object_path = tmp_path / "object.json"
object_path.write_text('{"a": 1}', encoding="utf-8")
Expand Down Expand Up @@ -868,6 +894,7 @@ def test_render_report_ignores_malformed_optional_records():

def test_main_returns_success_failure_and_exception(tmp_path, monkeypatch, capsys):
module = _load_governance()
monkeypatch.setattr(module, "_source_commit", lambda root: _CANONICAL_TEST_COMMIT)
ok_snapshot = _write_custom_snapshot(tmp_path / "ok.json", open_prs=[])
ok_code = module.main(
[
Expand Down
98 changes: 98 additions & 0 deletions tests/test_pr_queue_governance_git_timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,101 @@ def timeout_run(*args, **kwargs):
module._source_commit(tmp_path)

assert observed_timeouts == [module.GIT_METADATA_TIMEOUT_SECONDS]


def test_source_commit_rejects_nonzero_git_exit(monkeypatch, tmp_path: Path) -> None:
"""A non-zero ``git rev-parse`` exit must raise instead of returning ``unknown``."""

module = _load_governance()

def failing_run(*args, **kwargs):
raise subprocess.CalledProcessError(
returncode=128,
cmd=args[0] if args else ["git", "rev-parse", "HEAD"],
)

monkeypatch.setattr(module.subprocess, "run", failing_run)

with pytest.raises(RuntimeError, match=r"^source commit lookup failed$"):
module._source_commit(tmp_path)


def test_source_commit_rejects_missing_git_executable(monkeypatch, tmp_path: Path) -> None:
"""Executable and OS-level subprocess failures must also fail closed."""

module = _load_governance()

def missing_run(*args, **kwargs):
raise FileNotFoundError(2, "No such file or directory", "git")

monkeypatch.setattr(module.subprocess, "run", missing_run)

with pytest.raises(RuntimeError, match=r"^source commit lookup failed$"):
module._source_commit(tmp_path)


def _succeeding_run(stdout: str):
def run(*args, **kwargs):
return subprocess.CompletedProcess(
args[0] if args else ["git", "rev-parse", "HEAD"],
returncode=0,
stdout=stdout,
stderr="",
)

return run


def test_source_commit_rejects_empty_stdout(monkeypatch, tmp_path: Path) -> None:
"""Empty Git stdout carries no reconstructable identity and must fail closed."""

module = _load_governance()
monkeypatch.setattr(module.subprocess, "run", _succeeding_run("\n"))

with pytest.raises(
RuntimeError,
match=r"^source commit is not a full lowercase SHA-1 or SHA-256 object id$",
):
module._source_commit(tmp_path)


@pytest.mark.parametrize(
("stdout", "label"),
[
("a1b2c3d", "abbreviated sha"),
("A" * 40, "uppercase sha"),
("a" * 39, "undersized sha-1"),
("a" * 41, "oversized sha-1"),
("b" * 63, "undersized sha-256"),
("b" * 65, "oversized sha-256"),
("g" * 40, "non-hexadecimal identity"),
],
)
def test_source_commit_rejects_noncanonical_identity(
monkeypatch, tmp_path: Path, stdout: str, label: str
) -> None:
"""Only full lowercase hexadecimal object identities may reach evidence output."""

module = _load_governance()
monkeypatch.setattr(module.subprocess, "run", _succeeding_run(f"{stdout}\n"))

with pytest.raises(RuntimeError, match="not a full lowercase SHA-1 or SHA-256"):
module._source_commit(tmp_path)


@pytest.mark.parametrize(
"candidate",
[
"0123456789abcdef0123456789abcdef01234567",
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
],
)
def test_source_commit_accepts_canonical_full_identity(
monkeypatch, tmp_path: Path, candidate: str
) -> None:
"""Canonical lowercase SHA-1 and SHA-256 identities pass through unchanged."""

module = _load_governance()
monkeypatch.setattr(module.subprocess, "run", _succeeding_run(f"{candidate}\n"))

assert module._source_commit(tmp_path) == candidate
Loading