#!/usr/bin/env python3 """Tie staging and production to the exact bytes one release build made. scripts/staged-artifacts.py manifest [--instance PATH] # make release: write the provenance manifest scripts/staged-artifacts.py verify # before staging installs anything scripts/staged-artifacts.py record --instance H --runner H --tool-proxy H # after a green staging suite, with the # hashes of what staging actually ran scripts/staged-artifacts.py check # before any production deploy `manifest` runs at the end of `make release`, in the build's own tree, a clean checkout of the release commit (scripts/release-isolated.sh). It writes releases/equipo-linux-arm64-.manifest.json: the commit, the Go version and the SHA-256 of every artifact. It refuses unless every binary says it was built from that commit, unmodified (go version -m: vcs.revision, vcs.modified=false), and the runner release agrees with itself: the tool proxy the release manifest records and the runner digests in the install manifest are the bytes on disk, and the renderer pin it records is the MANIFEST of the renderer.tar.gz beside them, whose digest and size it records too. The renderer archive, its SOURCES and the install manifest are hashed with the binaries (they are not built from the commit, so they are not asked for build information). `verify` recomputes every hash and refuses unless the artifacts are the ones the provenance manifest names, at the commit it names. `record` takes the hashes of the instance staging deployed and of the runner and tool proxy it installed and ran, refuses unless `verify` passes and they equal the release's, and writes releases/staged/.json. `check` is `verify` plus a green staging record for exactly those bytes. """ import hashlib import json from pathlib import Path import subprocess import sys import tarfile import time ROOT = Path(__file__).resolve().parent.parent def artifacts(version, instance=None): runner = ROOT / 'releases' / f'equipo-runner-linux-amd64-{version}' return { 'instance': Path(instance) if instance else ROOT / 'releases' / f'equipo-linux-arm64-{version}', 'runner': runner / 'equipo-runner', 'tool_proxy': runner / 'equipo-tool-proxy', 'gitleaks': runner / 'gitleaks', 'darwin_gitleaks': runner / 'darwin-arm64' / 'gitleaks', # Both targets (Mac runners spec 3.1): the Mac worker's bytes are # part of what production receives. 'darwin_runner': runner / 'darwin-arm64' / 'equipo-runner', # Not binaries: the renderer archive and SOURCES the forge release # publishes (the runner fetches the archive there, not from the # instance), and the install manifest the instance embeds, which # names the archive. Frozen here, so neither can change after # staging while the instance keeps the original. 'renderer_archive': runner / 'renderer.tar.gz', 'renderer_sources': runner / 'SOURCES', 'install_manifest': runner / 'install-manifest.json', } # The artifacts that are files, not Go binaries: hashed, never asked for # build information. NOT_BINARIES = ('renderer_archive', 'renderer_sources', 'install_manifest') def digests(version, instance=None): out = {} for name, path in artifacts(version, instance).items(): if not path.is_file() or path.is_symlink(): raise SystemExit(f'missing {name} artifact for {version}: build it with make release') out[name] = hashlib.sha256(path.read_bytes()).hexdigest() return out def record_path(version): return ROOT / 'releases' / 'staged' / f'{version}.json' def manifest_path(version, instance=None): return Path(str(artifacts(version, instance)['instance']) + '.manifest.json') def commit_of(version, instance=None): return Path(str(artifacts(version, instance)['instance']) + '.COMMIT').read_text().strip() def built_from(path, commit): """Whether the binary at path says it was built from commit, with no change to the tree: its embedded build information, read by go.""" try: out = subprocess.run(['go', 'version', '-m', str(path)], capture_output=True, text=True, check=True).stdout except (OSError, subprocess.CalledProcessError): return False info = dict(f[1].split('=', 1) for f in (line.split('\t')[1:] for line in out.splitlines()) if len(f) == 2 and f[0] == 'build' and '=' in f[1]) return bool(commit) and info.get('vcs.revision') == commit and info.get('vcs.modified') == 'false' def scanner_from_pin(path): """Third-party scanners name their pinned module, not Equipo's commit.""" try: out = subprocess.run(['go', 'version', '-m', str(path)], capture_output=True, text=True, check=True).stdout except (OSError, subprocess.CalledProcessError): return False records = [line.strip().split() for line in out.splitlines()] return (any(row[:3] == ['mod', 'github.com/zricethezav/gitleaks/v8', 'v8.30.1'] for row in records) and not any(row and row[0] == '=>' for row in records)) def renderer_pin(path): """The SHA-256 of renderer.tar.gz's MANIFEST, the pin linked into the Linux runner (scripts/build-renderer-tree.py).""" with tarfile.open(path, 'r:gz') as tar: member = tar.getmember('MANIFEST') if not member.isfile(): raise ValueError('MANIFEST is not a file') return hashlib.sha256(tar.extractfile(member).read()).hexdigest() def self_consistent(version, sums, commit): """The runner release names its own bytes: one build, one set of digests.""" runner = ROOT / 'releases' / f'equipo-runner-linux-amd64-{version}' try: release = json.loads((runner / 'manifest.json').read_text()) install = json.loads((runner / 'install-manifest.json').read_text()) proxies = [b['sha256'] for b in release['binaries'] if b['name'] == 'equipo-tool-proxy'] targets = install['targets'] return (proxies == [sums['tool_proxy']] and install['release'] == release and install['version'] == version and install['gitleaks'] == 'v8.30.1' and install['runner_sha256'] == sums['runner'] and targets['linux/amd64'] == {'runner_sha256': sums['runner'], 'tool_proxy_sha256': sums['tool_proxy'], 'gitleaks_sha256': sums['gitleaks'], 'renderer_sha256': renderer_pin(runner / 'renderer.tar.gz'), 'renderer_archive_sha256': sums['renderer_archive'], 'renderer_archive_size': (runner / 'renderer.tar.gz').stat().st_size} and targets['darwin/arm64'] == {'runner_sha256': sums['darwin_runner'], 'gitleaks_sha256': sums['darwin_gitleaks']} and (runner / 'COMMIT').read_text().strip() == commit), release except (OSError, ValueError, KeyError, TypeError, tarfile.TarError): return False, None def verified(version): """The artifacts on disk are the ones the provenance manifest names.""" path = manifest_path(version) if not path.is_file() or path.is_symlink(): print(f'refused: no provenance manifest for {version}: build it with make release', file=sys.stderr) return False try: made = json.loads(path.read_text()) sums = digests(version) commit = commit_of(version) consistent, release = self_consistent(version, sums, commit) ok = (consistent and made['version'] == version and made['sha256'] == sums and made['release'] == release and made['commit'] == commit and commit.startswith(version)) except (OSError, ValueError, KeyError, TypeError, AttributeError): ok = False if not ok: print(f'refused: the {version} artifacts are not the ones its release build recorded', file=sys.stderr) return ok def main(): if len(sys.argv) < 3 or sys.argv[1] not in ('manifest', 'verify', 'record', 'check') or not sys.argv[2].isalnum(): print(__doc__) return 2 verb, version = sys.argv[1:3] if verb == 'manifest': args = sys.argv[3:] if args and (len(args) != 2 or args[0] != '--instance'): print(__doc__) return 2 instance = args[1] if args else None sums = digests(version, instance) commit = commit_of(version, instance) consistent, release = self_consistent(version, sums, commit) if not consistent or not commit.startswith(version): print(f'refused: the {version} runner release does not name its own bytes', file=sys.stderr) return 1 for name, path in artifacts(version, instance).items(): if name in NOT_BINARIES: continue if not (scanner_from_pin(path) if name in ('gitleaks', 'darwin_gitleaks') else built_from(path, commit)): print(f'refused: the {name} binary does not say it was built from {commit}, unmodified', file=sys.stderr) return 1 go = subprocess.run(['go', 'env', 'GOVERSION'], capture_output=True, text=True, check=True).stdout.strip() manifest_path(version, instance).write_text(json.dumps({ 'version': version, 'commit': commit, 'go': go, 'release': release, 'sha256': sums}, indent=2) + '\n') print(f'recorded {version}: {manifest_path(version, instance)}') return 0 if not verified(version): return 1 if verb == 'verify': print(f'release artifacts match their provenance manifest for {version}') return 0 commit = commit_of(version) if verb == 'record': args = sys.argv[3:] ran = dict(zip(args[0::2], args[1::2])) if len(args) != 6 or set(ran) != {'--instance', '--runner', '--tool-proxy'}: print('refused: record needs the hashes of the artifacts staging ran', file=sys.stderr) return 2 wanted = digests(version) if (ran['--instance'], ran['--runner'], ran['--tool-proxy']) != (wanted['instance'], wanted['runner'], wanted['tool_proxy']): print(f'refused: staging ran other bytes than the {version} release', file=sys.stderr) return 1 path = record_path(version) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps({'version': version, 'commit': commit, 'staging': 'PASS', 'at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'sha256': wanted}, indent=2) + '\n') print(f'staged {version}: {path}') return 0 path = record_path(version) if not path.is_file(): print(f'refused: no green staging run recorded for {version}', file=sys.stderr) return 1 staged = json.loads(path.read_text()) if staged.get('staging') != 'PASS' or staged.get('sha256') != digests(version) or staged.get('commit') != commit: print(f'refused: the {version} artifacts differ from the ones staging passed', file=sys.stderr) return 1 print(f'staged artifacts match for {version} (staging passed {staged["at"]})') return 0 if __name__ == '__main__': sys.exit(main())