Skip to content
Closed
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
134 changes: 126 additions & 8 deletions bin/guild-release
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@ from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import hmac
import json
import os
import pwd
import re
import subprocess
import shutil
import signal
import subprocess
import sys
import tempfile
from pathlib import Path
Expand Down Expand Up @@ -1236,6 +1237,118 @@ def _is_tmux_server(entry: Path, exe: str | None) -> bool:


BASELINE_GLOB = "*attribution-baseline.json"
PASS_GLOB = "*attribution-pass.json"


def _pass_key() -> bytes | None:
env = os.environ.get("GUILD_ATTRIBUTION_PASS_KEY")
path = Path(env) if env else Path.home() / ".local/share/guild/attribution-pass.key"
try:
return path.read_bytes()
except OSError:
return None


def _attribution_disposition(job_dir: Path, baseline: Path) -> str | None:
"""`pass` or `fail` when a guard pass verifies for this baseline, else None.

The pass is the file Bridgekeeper's attribution-guard writes. Its HMAC
covers the job path, the baseline bytes, and the evidence hash. A missing
key, a bad MAC, or a pass for a different baseline leaves the release held.
"""
key = _pass_key()
if key is None:
return None
try:
baseline_hash = hashlib.sha256(baseline.read_bytes()).hexdigest()
except OSError:
return None
job = str(job_dir.resolve())
for path in sorted(job_dir.glob(PASS_GLOB)):
try:
data = json.loads(path.read_text(encoding="utf-8"))
mac = data.pop("mac")
message = json.dumps(data, sort_keys=True, separators=(",", ":")).encode()
good = hmac.compare_digest(mac, hmac.new(key, message, hashlib.sha256).hexdigest())
except (OSError, ValueError, KeyError, TypeError, AttributeError):
continue
if not good or data.get("v") != 1 or data.get("result") not in ("pass", "fail"):
continue
if data.get("job") != job or data.get("baseline_sha256") != baseline_hash:
continue
if not isinstance(data.get("evidence_sha256"), str):
continue
return data["result"]
return None


def _job_is_busy(job_dir: Path) -> bool:
proc = Path("/proc")
prefix = str(job_dir.resolve())
if not (proc / "self").is_dir():
return False
for entry in proc.iterdir():
if not entry.name.isdigit():
continue
cwd = _read_proc(entry / "cwd", link=True)
if isinstance(cwd, str) and (cwd == prefix or cwd.startswith(prefix + os.sep)):
return True
return False


def _prove_settled_jobs(jobs_root: Path, releases_dir: Path) -> set[Path]:
"""Run the attribution guard for a settled job that still has no pass.

The guard rechecks while the repositories exist and writes the pass prune
reads. A running job is left alone: its process already keeps the release,
and an early pass would not cover commits it has not made yet. A guard
that exits 0 without writing a pass checked the repositories and does not
know this receipt yet, so prune does not hold those releases.
"""
cleared: set[Path] = set()
guard = os.environ.get("GUILD_ATTRIBUTION_GUARD")
if not guard:
return cleared
for job_dir in sorted(p for p in jobs_root.iterdir() if p.is_dir()):
baselines = list(job_dir.glob(BASELINE_GLOB))
if not baselines or _job_is_busy(job_dir):
continue
if all(_attribution_disposition(job_dir, path) in ("pass", "fail") for path in baselines):
continue
names: list[str] = []
for path in baselines:
try:
repos = json.loads(path.read_text(encoding="utf-8"))["repositories"]
except (OSError, ValueError, KeyError, TypeError, AttributeError):
continue
names.extend(n for n in [*repos, *(row.get("repo") for row in repos.values())] if isinstance(n, str))
if not any(_release_of(n, releases_dir) for n in names):
continue
ran = subprocess.run([guard, "check", str(job_dir)], check=False, capture_output=True, text=True, timeout=300)
if ran.returncode == 0 and all(_attribution_disposition(job_dir, path) is None for path in baselines):
cleared.add(job_dir.resolve())
return cleared


def _held_for_attribution(jobs_root: Path | None, releases_dir: Path) -> list[str]:
"""Releases a settled job's baseline names until a verified pass or failure exists."""
if jobs_root is None or not jobs_root.is_dir():
return []
cleared = _prove_settled_jobs(jobs_root, releases_dir)
held: set[str] = set()
for job_dir in sorted(jobs_root.iterdir()):
if not job_dir.is_dir() or job_dir.resolve() in cleared:
continue
for path in sorted(job_dir.glob(BASELINE_GLOB)):
if _attribution_disposition(job_dir, path) in ("pass", "fail"):
continue
try:
repos = json.loads(path.read_text(encoding="utf-8"))["repositories"]
names = [*repos, *(row.get("repo") for row in repos.values())]
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
raise ReleaseError(f"cannot read attribution baseline {path}: {exc}") from exc
held.update(rid for rid in (_release_of(n, releases_dir) for n in names if isinstance(n, str)) if rid)
return sorted(held)


def _baseline_releases(job_dir: Path, releases_dir: Path) -> set[str]:
Expand Down Expand Up @@ -1308,16 +1421,18 @@ def releases_in_use(root: Path) -> dict[str, list[int]]:
return {rid: sorted(pids) for rid, pids in sorted(used.items())}


def prune_releases(root: Path, *, dry_run: bool = False) -> dict[str, Any]:
def prune_releases(root: Path, *, dry_run: bool = False, jobs_root: Path | None = None) -> dict[str, Any]:
"""Remove each release that is not current, not previous, and not in use.

No new job can bind to such a release: a new job resolves `current`, and
only a process already bound to a release can start another job on it,
which keeps that release in use.
which keeps that release in use. A release named by a job baseline under
jobs_root stays until that baseline has a verified attribution pass or a
verified failure.
"""
root = root.resolve()
st = status_report(root)
keep = {st["current"], st["previous"], *st["in_use"]}
st = status_report(root, jobs_root=jobs_root)
keep = {st["current"], st["previous"], *st["in_use"], *st["held_for_attribution"]}
removed: list[str] = []
for rid in st["releases"]:
if rid in keep:
Expand All @@ -1328,7 +1443,7 @@ def prune_releases(root: Path, *, dry_run: bool = False) -> dict[str, Any]:
return {**st, "removed": removed, "dry_run": dry_run}


def status_report(root: Path) -> dict[str, Any]:
def status_report(root: Path, *, jobs_root: Path | None = None) -> dict[str, Any]:
root = root.resolve()
releases_dir = root / "releases"
releases: list[str] = []
Expand All @@ -1340,6 +1455,7 @@ def status_report(root: Path) -> dict[str, Any]:
"previous": read_pointer_id(root, "previous", tolerate_dangling=True),
"releases": releases,
"in_use": releases_in_use(root) if releases else {},
"held_for_attribution": _held_for_attribution(jobs_root, releases_dir) if releases else [],
}


Expand Down Expand Up @@ -1377,10 +1493,12 @@ def build_parser() -> argparse.ArgumentParser:

p_st = sub.add_parser("status")
p_st.add_argument("--root", type=Path, required=True)
p_st.add_argument("--jobs-root", type=Path, default=None, help="job directory parent; baselines here hold a release until a verified attribution pass")
p_st.add_argument("--json", action="store_true")

p_pr = sub.add_parser("prune")
p_pr.add_argument("--root", type=Path, required=True)
p_pr.add_argument("--jobs-root", type=Path, default=None, help="job directory parent; baselines here hold a release until a verified attribution pass")
p_pr.add_argument("--dry-run", action="store_true")
p_pr.add_argument("--json", action="store_true")

Expand Down Expand Up @@ -1435,9 +1553,9 @@ def main(argv: list[str] | None = None) -> int:
skip_check=args.skip_check,
)
elif args.cmd == "status":
res = status_report(args.root)
res = status_report(args.root, jobs_root=args.jobs_root)
elif args.cmd == "prune":
res = prune_releases(args.root, dry_run=args.dry_run)
res = prune_releases(args.root, dry_run=args.dry_run, jobs_root=args.jobs_root)
else:
raise ReleaseError(f"unknown command: {args.cmd}")
except (ReleaseError, OSError, ValueError, KeyError) as exc:
Expand Down
11 changes: 10 additions & 1 deletion bin/guild-update
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,15 @@ say "activated $id"
for unit in $restart_units; do
systemctl --user try-restart "$unit" || say "try-restart $unit failed"
done
"${release[@]}" prune --root "$root" >/dev/null || say "prune failed"
jobs_root=${GUILD_JOBS_ROOT:-$HOME/work-notes}
guard=$root/current/bin/attribution-guard
if [ -x "$guard" ]; then
export GUILD_ATTRIBUTION_GUARD=$guard
fi
if [ -d "$jobs_root" ]; then
"${release[@]}" prune --root "$root" --jobs-root "$jobs_root" >/dev/null || say "prune failed"
else
"${release[@]}" prune --root "$root" >/dev/null || say "prune failed"
fi
git -C "$src" -c advice.detachedHead=false checkout -q --detach "$sha" ||
fail "$id-src" "activated $id but cannot move $src to it"
87 changes: 83 additions & 4 deletions tests/test_release_retention.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"""
from __future__ import annotations

import hashlib
import hmac
import json
import os
import subprocess
Expand All @@ -32,6 +34,25 @@ def setUp(self) -> None:
os.symlink("releases/r3", self.root / "current")
os.symlink("releases/r2", self.root / "previous")
self.jobs = self.tmp / "jobs"
self.key = self.tmp / "pass.key"
self.key.write_bytes(b"k" * 32)
os.environ["GUILD_ATTRIBUTION_PASS_KEY"] = str(self.key)
os.environ.pop("GUILD_ATTRIBUTION_GUARD", None)

def sign(self, job_dir: Path, result: str, reason: str | None = None) -> None:
baseline = next(job_dir.glob("*attribution-baseline.json"))
body = {
"v": 1,
"job": str(job_dir.resolve()),
"baseline_sha256": hashlib.sha256(baseline.read_bytes()).hexdigest(),
"evidence_sha256": "ab" * 32,
"result": result,
}
if reason is not None:
body["reason"] = reason
message = json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
body["mac"] = hmac.new(self.key.read_bytes(), message, hashlib.sha256).hexdigest()
(job_dir / ".acme.attribution-pass.json").write_text(json.dumps(body), encoding="utf-8")

def job(self, name: str, *rids: str, text: str | None = None) -> Path:
"""A job dir whose baseline records each release's conclave checkout and one other repo."""
Expand All @@ -58,16 +79,19 @@ def settle(self, proc: subprocess.Popen[bytes]) -> None:

def prune(self, *extra: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[sys.executable, str(GUILD_RELEASE_BIN), "prune", "--root", str(self.root), "--json", *extra],
[sys.executable, str(GUILD_RELEASE_BIN), "prune", "--root", str(self.root),
"--jobs-root", str(self.jobs), "--json", *extra],
text=True, capture_output=True, timeout=60,
)

def releases(self) -> list[str]:
return sorted(p.name for p in (self.root / "releases").iterdir())

def test_running_job_baseline_keeps_only_its_release_until_the_job_ends(self) -> None:
active = self.run_job(self.job("review-active", "r1"))
self.job("review-settled", "r0") # no process: this job has ended
active_job = self.job("review-active", "r1")
active = self.run_job(active_job)
settled = self.job("review-settled", "r0") # no process: this job has ended
self.sign(settled, "pass")

dry = self.prune("--dry-run")
self.assertEqual(dry.returncode, 0, dry.stderr)
Expand All @@ -80,8 +104,9 @@ def test_running_job_baseline_keeps_only_its_release_until_the_job_ends(self) ->
self.assertEqual(json.loads(pr.stdout)["removed"], ["r0"])
self.assertEqual(self.releases(), ["r1", "r2", "r3"])

# Once the job ends, normal pruning removes r1.
# The guard writes a pass at job exit. Prune then removes r1.
self.settle(active)
self.sign(active_job, "pass")
deadline = time.monotonic() + 10
while True:
pr = self.prune()
Expand All @@ -103,6 +128,60 @@ def test_a_process_below_the_job_dir_keeps_the_release(self) -> None:
self.assertEqual(report["removed"], ["r0"])
self.assertIn(proc.pid, report["in_use"]["r1"])

def test_settled_job_without_a_pass_keeps_its_release(self) -> None:
self.job("review-settled", "r1")
pr = self.prune()
self.assertEqual(pr.returncode, 0, pr.stderr)
report = json.loads(pr.stdout)
self.assertEqual(report["removed"], ["r0"])
self.assertEqual(report["held_for_attribution"], ["r1"])
self.assertEqual(self.releases(), ["r1", "r2", "r3"])

def test_verified_failure_lets_prune_resume(self) -> None:
job = self.job("review-failed", "r1")
self.sign(job, "fail", reason="1 hits")
pr = self.prune()
self.assertEqual(pr.returncode, 0, pr.stderr)
self.assertEqual(json.loads(pr.stdout)["removed"], ["r0", "r1"])
self.assertEqual(self.releases(), ["r2", "r3"])

def test_bogus_pass_keeps_the_release(self) -> None:
job = self.job("review-bogus", "r1")
self.sign(job, "pass")
path = job / ".acme.attribution-pass.json"
data = json.loads(path.read_text())
data["mac"] = "0" * 64
path.write_text(json.dumps(data), encoding="utf-8")
pr = self.prune()
self.assertEqual(pr.returncode, 0, pr.stderr)
report = json.loads(pr.stdout)
self.assertEqual(report["held_for_attribution"], ["r1"])
self.assertNotIn("r1", report["removed"])

def test_pass_for_a_changed_baseline_keeps_the_release(self) -> None:
job = self.job("review-changed", "r1")
self.sign(job, "pass")
baseline = job / ".acme.attribution-baseline.json"
data = json.loads(baseline.read_text())
data["started"] = 2
baseline.write_text(json.dumps(data), encoding="utf-8")
pr = self.prune()
self.assertEqual(pr.returncode, 0, pr.stderr)
self.assertEqual(json.loads(pr.stdout)["held_for_attribution"], ["r1"])

def test_guard_that_passes_without_a_receipt_does_not_hold(self) -> None:
self.job("review-legacy", "r1")
guard = self.tmp / "guard"
guard.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
guard.chmod(0o755)
os.environ["GUILD_ATTRIBUTION_GUARD"] = str(guard)
self.addCleanup(os.environ.pop, "GUILD_ATTRIBUTION_GUARD", None)
pr = self.prune()
self.assertEqual(pr.returncode, 0, pr.stderr)
report = json.loads(pr.stdout)
self.assertEqual(report["held_for_attribution"], [])
self.assertIn("r1", report["removed"])

def test_unreadable_baseline_of_a_running_job_removes_nothing(self) -> None:
self.run_job(self.job("review-broken", text="{not json"))
pr = self.prune()
Expand Down
Loading