oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Tie staging and production to the exact bytes one release build made.
3
4 scripts/staged-artifacts.py manifest <version> [--instance PATH]
5 # make release: write the provenance manifest
6 scripts/staged-artifacts.py verify <version> # before staging installs anything
7 scripts/staged-artifacts.py record <version> --instance H --runner H --tool-proxy H
8 # after a green staging suite, with the
9 # hashes of what staging actually ran
10 scripts/staged-artifacts.py check <version> # before any production deploy
11
12`manifest` runs at the end of `make release`, in the build's own tree, a
13clean checkout of the release commit (scripts/release-isolated.sh). It
14writes releases/equipo-linux-arm64-<version>.manifest.json: the commit,
15the Go version and the SHA-256 of every artifact. It refuses unless every
16binary says it was built from that commit, unmodified (go version -m:
17vcs.revision, vcs.modified=false), and the runner release agrees with
18itself: the tool proxy the release manifest records and the runner
19digests in the install manifest are the bytes on disk, and the renderer
20pin it records is the MANIFEST of the renderer.tar.gz beside them, whose
21digest and size it records too. The renderer archive, its SOURCES and the
22install manifest are hashed with the binaries (they are not built from
23the commit, so they are not asked for build information).
24
25`verify` recomputes every hash and refuses unless the artifacts are the
26ones the provenance manifest names, at the commit it names.
27
28`record` takes the hashes of the instance staging deployed and of the
29runner and tool proxy it installed and ran, refuses unless `verify`
30passes and they equal the release's, and writes
31releases/staged/<version>.json. `check` is `verify` plus a green staging
32record for exactly those bytes.
33"""
34import hashlib
35import json
36from pathlib import Path
37import subprocess
38import sys
39import tarfile
40import time
41
42ROOT = Path(__file__).resolve().parent.parent
43
44
45def artifacts(version, instance=None):
46 runner = ROOT / 'releases' / f'equipo-runner-linux-amd64-{version}'
47 return {
48 'instance': Path(instance) if instance else ROOT / 'releases' / f'equipo-linux-arm64-{version}',
49 'runner': runner / 'equipo-runner',
50 'tool_proxy': runner / 'equipo-tool-proxy',
51 'gitleaks': runner / 'gitleaks',
52 'darwin_gitleaks': runner / 'darwin-arm64' / 'gitleaks',
53 # Both targets (Mac runners spec 3.1): the Mac worker's bytes are
54 # part of what production receives.
55 'darwin_runner': runner / 'darwin-arm64' / 'equipo-runner',
56 # Not binaries: the renderer archive and SOURCES the forge release
57 # publishes (the runner fetches the archive there, not from the
58 # instance), and the install manifest the instance embeds, which
59 # names the archive. Frozen here, so neither can change after
60 # staging while the instance keeps the original.
61 'renderer_archive': runner / 'renderer.tar.gz',
62 'renderer_sources': runner / 'SOURCES',
63 'install_manifest': runner / 'install-manifest.json',
64 }
65
66
67# The artifacts that are files, not Go binaries: hashed, never asked for
68# build information.
69NOT_BINARIES = ('renderer_archive', 'renderer_sources', 'install_manifest')
70
71
72def digests(version, instance=None):
73 out = {}
74 for name, path in artifacts(version, instance).items():
75 if not path.is_file() or path.is_symlink():
76 raise SystemExit(f'missing {name} artifact for {version}: build it with make release')
77 out[name] = hashlib.sha256(path.read_bytes()).hexdigest()
78 return out
79
80
81def record_path(version):
82 return ROOT / 'releases' / 'staged' / f'{version}.json'
83
84
85def manifest_path(version, instance=None):
86 return Path(str(artifacts(version, instance)['instance']) + '.manifest.json')
87
88
89def commit_of(version, instance=None):
90 return Path(str(artifacts(version, instance)['instance']) + '.COMMIT').read_text().strip()
91
92
93def built_from(path, commit):
94 """Whether the binary at path says it was built from commit, with no
95 change to the tree: its embedded build information, read by go."""
96 try:
97 out = subprocess.run(['go', 'version', '-m', str(path)], capture_output=True, text=True, check=True).stdout
98 except (OSError, subprocess.CalledProcessError):
99 return False
100 info = dict(f[1].split('=', 1) for f in (line.split('\t')[1:] for line in out.splitlines())
101 if len(f) == 2 and f[0] == 'build' and '=' in f[1])
102 return bool(commit) and info.get('vcs.revision') == commit and info.get('vcs.modified') == 'false'
103
104
105def scanner_from_pin(path):
106 """Third-party scanners name their pinned module, not Equipo's commit."""
107 try:
108 out = subprocess.run(['go', 'version', '-m', str(path)], capture_output=True, text=True, check=True).stdout
109 except (OSError, subprocess.CalledProcessError):
110 return False
111 records = [line.strip().split() for line in out.splitlines()]
112 return (any(row[:3] == ['mod', 'github.com/zricethezav/gitleaks/v8', 'v8.30.1'] for row in records)
113 and not any(row and row[0] == '=>' for row in records))
114
115
116def renderer_pin(path):
117 """The SHA-256 of renderer.tar.gz's MANIFEST, the pin linked into the
118 Linux runner (scripts/build-renderer-tree.py)."""
119 with tarfile.open(path, 'r:gz') as tar:
120 member = tar.getmember('MANIFEST')
121 if not member.isfile():
122 raise ValueError('MANIFEST is not a file')
123 return hashlib.sha256(tar.extractfile(member).read()).hexdigest()
124
125
126def self_consistent(version, sums, commit):
127 """The runner release names its own bytes: one build, one set of digests."""
128 runner = ROOT / 'releases' / f'equipo-runner-linux-amd64-{version}'
129 try:
130 release = json.loads((runner / 'manifest.json').read_text())
131 install = json.loads((runner / 'install-manifest.json').read_text())
132 proxies = [b['sha256'] for b in release['binaries'] if b['name'] == 'equipo-tool-proxy']
133 targets = install['targets']
134 return (proxies == [sums['tool_proxy']] and install['release'] == release and install['version'] == version
135 and install['gitleaks'] == 'v8.30.1'
136 and install['runner_sha256'] == sums['runner']
137 and targets['linux/amd64'] == {'runner_sha256': sums['runner'], 'tool_proxy_sha256': sums['tool_proxy'], 'gitleaks_sha256': sums['gitleaks'],
138 'renderer_sha256': renderer_pin(runner / 'renderer.tar.gz'),
139 'renderer_archive_sha256': sums['renderer_archive'],
140 'renderer_archive_size': (runner / 'renderer.tar.gz').stat().st_size}
141 and targets['darwin/arm64'] == {'runner_sha256': sums['darwin_runner'], 'gitleaks_sha256': sums['darwin_gitleaks']}
142 and (runner / 'COMMIT').read_text().strip() == commit), release
143 except (OSError, ValueError, KeyError, TypeError, tarfile.TarError):
144 return False, None
145
146
147def verified(version):
148 """The artifacts on disk are the ones the provenance manifest names."""
149 path = manifest_path(version)
150 if not path.is_file() or path.is_symlink():
151 print(f'refused: no provenance manifest for {version}: build it with make release', file=sys.stderr)
152 return False
153 try:
154 made = json.loads(path.read_text())
155 sums = digests(version)
156 commit = commit_of(version)
157 consistent, release = self_consistent(version, sums, commit)
158 ok = (consistent and made['version'] == version and made['sha256'] == sums and made['release'] == release
159 and made['commit'] == commit and commit.startswith(version))
160 except (OSError, ValueError, KeyError, TypeError, AttributeError):
161 ok = False
162 if not ok:
163 print(f'refused: the {version} artifacts are not the ones its release build recorded', file=sys.stderr)
164 return ok
165
166
167def main():
168 if len(sys.argv) < 3 or sys.argv[1] not in ('manifest', 'verify', 'record', 'check') or not sys.argv[2].isalnum():
169 print(__doc__)
170 return 2
171 verb, version = sys.argv[1:3]
172 if verb == 'manifest':
173 args = sys.argv[3:]
174 if args and (len(args) != 2 or args[0] != '--instance'):
175 print(__doc__)
176 return 2
177 instance = args[1] if args else None
178 sums = digests(version, instance)
179 commit = commit_of(version, instance)
180 consistent, release = self_consistent(version, sums, commit)
181 if not consistent or not commit.startswith(version):
182 print(f'refused: the {version} runner release does not name its own bytes', file=sys.stderr)
183 return 1
184 for name, path in artifacts(version, instance).items():
185 if name in NOT_BINARIES:
186 continue
187 if not (scanner_from_pin(path) if name in ('gitleaks', 'darwin_gitleaks') else built_from(path, commit)):
188 print(f'refused: the {name} binary does not say it was built from {commit}, unmodified', file=sys.stderr)
189 return 1
190 go = subprocess.run(['go', 'env', 'GOVERSION'], capture_output=True, text=True, check=True).stdout.strip()
191 manifest_path(version, instance).write_text(json.dumps({
192 'version': version, 'commit': commit, 'go': go, 'release': release, 'sha256': sums}, indent=2) + '\n')
193 print(f'recorded {version}: {manifest_path(version, instance)}')
194 return 0
195 if not verified(version):
196 return 1
197 if verb == 'verify':
198 print(f'release artifacts match their provenance manifest for {version}')
199 return 0
200 commit = commit_of(version)
201 if verb == 'record':
202 args = sys.argv[3:]
203 ran = dict(zip(args[0::2], args[1::2]))
204 if len(args) != 6 or set(ran) != {'--instance', '--runner', '--tool-proxy'}:
205 print('refused: record needs the hashes of the artifacts staging ran', file=sys.stderr)
206 return 2
207 wanted = digests(version)
208 if (ran['--instance'], ran['--runner'], ran['--tool-proxy']) != (wanted['instance'], wanted['runner'], wanted['tool_proxy']):
209 print(f'refused: staging ran other bytes than the {version} release', file=sys.stderr)
210 return 1
211 path = record_path(version)
212 path.parent.mkdir(parents=True, exist_ok=True)
213 path.write_text(json.dumps({'version': version, 'commit': commit, 'staging': 'PASS',
214 'at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'sha256': wanted}, indent=2) + '\n')
215 print(f'staged {version}: {path}')
216 return 0
217 path = record_path(version)
218 if not path.is_file():
219 print(f'refused: no green staging run recorded for {version}', file=sys.stderr)
220 return 1
221 staged = json.loads(path.read_text())
222 if staged.get('staging') != 'PASS' or staged.get('sha256') != digests(version) or staged.get('commit') != commit:
223 print(f'refused: the {version} artifacts differ from the ones staging passed', file=sys.stderr)
224 return 1
225 print(f'staged artifacts match for {version} (staging passed {staged["at"]})')
226 return 0
227
228
229if __name__ == '__main__':
230 sys.exit(main())
231