Repository navigation
Expand file tree
/
Copy pathrelease_artifacts.py
More file actions
406 lines (349 loc) · 18.6 KB
/
Copy pathrelease_artifacts.py
File metadata and controls
406 lines (349 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/usr/bin/env python3
"""Validate LoopX release identity and produce canonical SHA-256 manifests."""
from __future__ import annotations
import argparse
import copy
import gzip
import hashlib
import io
import json
import re
import runpy
import subprocess
import sys
import tarfile
import tempfile
from dataclasses import dataclass
from pathlib import Path
class ReleaseArtifactError(ValueError):
"""Raised when release inputs do not satisfy the public release contract."""
@dataclass(frozen=True)
class ReleaseIdentity:
name: str
version: str
@property
def tag(self) -> str:
return f"v{self.version}"
@property
def distribution_prefix(self) -> str:
return self.name.replace("-", "_")
def load_identity(project_root: Path) -> ReleaseIdentity:
try:
# The tool can inspect its own checkout: loading its package would run
# the very initializer whose version must remain inert.
reader = runpy.run_path(
str(Path(__file__).resolve().parents[1] / "loopx/control_plane/testing/release_metadata.py")
)
return ReleaseIdentity(**reader["checkout_release_metadata"](project_root))
except (OSError, SyntaxError, ValueError) as exc:
raise ReleaseArtifactError(str(exc)) from exc
def distribution_files(dist_dir: Path, identity: ReleaseIdentity) -> tuple[Path, ...]:
if not dist_dir.is_dir():
raise ReleaseArtifactError(f"distribution directory does not exist: {dist_dir}")
prefix = f"{identity.distribution_prefix}-{identity.version}"
wheel_files = sorted(dist_dir.glob(f"{prefix}-*.whl"))
sdist_files = sorted(dist_dir.glob(f"{prefix}.tar.gz"))
if len(wheel_files) != 1 or len(sdist_files) != 1:
raise ReleaseArtifactError(
"expected exactly one wheel and one sdist for "
f"{identity.name} {identity.version}; found wheels={len(wheel_files)}, "
f"sdists={len(sdist_files)}"
)
expected = tuple(sorted((*wheel_files, *sdist_files), key=lambda path: path.name))
unexpected = sorted(
path.name
for path in dist_dir.iterdir()
if path.is_file() and path not in expected
)
if unexpected:
raise ReleaseArtifactError(f"unexpected files in distribution directory: {unexpected}")
return expected
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def render_manifest(files: tuple[Path, ...]) -> str:
return "".join(f"{sha256(path)} {path.name}\n" for path in files)
def _safe_archive_name(name: str) -> bool:
path = Path(name)
return bool(name) and not path.is_absolute() and ".." not in path.parts
def normalize_sdist(dist_dir: Path, identity: ReleaseIdentity, source_date_epoch: int) -> None:
if source_date_epoch < 0:
raise ReleaseArtifactError("source date epoch must be non-negative")
files = distribution_files(dist_dir, identity)
sdist = next(path for path in files if path.name.endswith(".tar.gz"))
temporary = sdist.with_name(f".{sdist.name}.tmp")
try:
with tarfile.open(sdist, mode="r:gz") as source:
members = sorted(source.getmembers(), key=lambda member: member.name)
if any(not _safe_archive_name(member.name) for member in members):
raise ReleaseArtifactError(f"sdist contains an unsafe archive path: {sdist}")
payloads = {
member.name: source.extractfile(member).read()
for member in members
if member.isfile()
}
with temporary.open("wb") as raw_stream:
with gzip.GzipFile(
filename="",
mode="wb",
fileobj=raw_stream,
mtime=source_date_epoch,
) as gzip_stream:
with tarfile.open(
fileobj=gzip_stream,
mode="w",
format=tarfile.PAX_FORMAT,
) as target:
for member in members:
normalized = copy.copy(member)
normalized.mtime = source_date_epoch
normalized.uid = 0
normalized.gid = 0
normalized.uname = ""
normalized.gname = ""
normalized.pax_headers = {
key: value
for key, value in member.pax_headers.items()
if key not in {"atime", "ctime", "gid", "gname", "mtime", "uid", "uname"}
}
data = io.BytesIO(payloads[member.name]) if member.isfile() else None
target.addfile(normalized, data)
temporary.replace(sdist)
except (OSError, tarfile.TarError) as exc:
raise ReleaseArtifactError(f"cannot normalize sdist {sdist}: {exc}") from exc
finally:
if temporary.exists():
temporary.unlink()
print(f"normalized {sdist} with SOURCE_DATE_EPOCH={source_date_epoch}")
def write_manifest(dist_dir: Path, output: Path, identity: ReleaseIdentity) -> None:
files = distribution_files(dist_dir, identity)
output.parent.mkdir(parents=True, exist_ok=True)
temporary = output.with_name(f".{output.name}.tmp")
temporary.write_text(render_manifest(files), encoding="ascii")
temporary.replace(output)
print(f"wrote {output} for {len(files)} distributions")
def verify_manifest(dist_dir: Path, checksum_file: Path, identity: ReleaseIdentity) -> None:
files = distribution_files(dist_dir, identity)
expected = render_manifest(files)
try:
observed = checksum_file.read_text(encoding="ascii")
except (OSError, UnicodeError) as exc:
raise ReleaseArtifactError(f"cannot read checksum manifest {checksum_file}: {exc}") from exc
if observed != expected:
raise ReleaseArtifactError(
f"checksum manifest does not match release distributions: {checksum_file}"
)
print(f"verified {checksum_file} for {len(files)} distributions")
def gh(*args: str) -> bytes:
return subprocess.check_output(["gh", *args])
def verify_publication_run(repo: str, run_id: str, tag: str, commit: str) -> None:
"""Only reuse a successful tagged build from this repository's release workflow."""
if not re.fullmatch(r"[1-9][0-9]*", run_id):
raise ReleaseArtifactError("validated run id must be a positive integer")
run = json.loads(gh("api", f"repos/{repo}/actions/runs/{run_id}"))
if (
run["repository"]["full_name"] != repo
or run["event"] != "release"
or run["path"] != ".github/workflows/release-artifacts.yml"
or run["head_sha"] != commit
or run["head_branch"] != tag
):
raise ReleaseArtifactError("recovery run does not match the tagged product build")
jobs = json.loads(gh("api", f"repos/{repo}/actions/runs/{run_id}/jobs?per_page=100"))
builds = [job for job in jobs["jobs"] if job["name"] == "build"]
if len(builds) != 1 or builds[0]["conclusion"] != "success":
raise ReleaseArtifactError("recovery requires the original successful build job")
print(f"verified successful build {run_id} for {tag}@{commit}")
def publication_files(dist_dir: Path, identity: ReleaseIdentity) -> tuple[Path, ...]:
files = (*distribution_files(dist_dir / "packages", identity),
dist_dir / "SHA256SUMS", dist_dir / "RELEASE-SOURCES.json",
*sorted((dist_dir / "runtime").iterdir()))
if any(path.is_symlink() or not path.is_file() for path in files):
raise ReleaseArtifactError("publication inputs must be regular files")
if len({path.name.casefold() for path in files}) != len(files):
raise ReleaseArtifactError("publication names collide ignoring case")
verify_manifest(dist_dir / "packages", dist_dir / "SHA256SUMS", identity)
return tuple(files)
def require_stable_runtime_publication(dist_dir: Path, identity: ReleaseIdentity) -> None:
# Resolve the policy from the reviewed publication tooling. The selected tag
# supplies data and attested bytes, while package identity stays a static read.
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
try:
from loopx.cli_commands.update_artifact import (
validate_published_manifest,
verify_runtime_installation_qualification,
)
finally:
sys.path.pop(0)
runtime = dist_dir / "runtime"
try:
manifest = validate_published_manifest(
json.loads((runtime / "loopx-runtime.json").read_text(encoding="utf-8"))
)
sources = json.loads((dist_dir / "RELEASE-SOURCES.json").read_text(encoding="utf-8"))
revision = manifest["source_revision"]
if (
not isinstance(sources, dict)
or sources.get("product_tag") != identity.tag
or sources.get("product_commit") != revision
or manifest["package_version"] != identity.version
):
raise ValueError("Bundle product identity differs from the stable runtime")
qualification = json.loads((runtime / "qualification.json").read_text(encoding="utf-8"))
archive = runtime / f"loopx-runtime-{revision}.tar.gz"
verify_runtime_installation_qualification(manifest, qualification, archive, channel="stable")
except (OSError, ValueError) as exc:
raise ReleaseArtifactError(str(exc)) from exc
def require_release_commit(dist_dir: Path, identity: ReleaseIdentity, repo: str) -> str:
commit = gh("api", f"repos/{repo}/commits/{identity.tag}", "--jq", ".sha").decode().strip()
sources = json.loads((dist_dir / "RELEASE-SOURCES.json").read_text(encoding="utf-8"))
if sources["product_tag"] != identity.tag or sources["product_commit"] != commit:
raise ReleaseArtifactError("bundle product identity differs from the release tag")
return commit
def missing_release_assets(repo: str, release_id: int, files: tuple[Path, ...]) -> list[Path]:
assets = json.loads(gh("api", "--paginate", "--slurp",
f"repos/{repo}/releases/{release_id}/assets?per_page=100"))
remote = {}
for asset in (asset for page in assets for asset in page):
key = asset["name"].casefold()
if key in remote:
raise ReleaseArtifactError("remote release names collide ignoring case")
remote[key] = asset
missing = []
# Check every existing asset before the first upload; never delete or clobber.
for path in files:
asset = remote.get(path.name.casefold())
if asset is None:
missing.append(path)
continue
if asset["name"] != path.name:
raise ReleaseArtifactError(f"release name collision: {asset['name']} / {path.name}")
with tempfile.TemporaryFile() as downloaded:
subprocess.run(["gh", "api", f"repos/{repo}/releases/assets/{asset['id']}",
"-H", "Accept: application/octet-stream"],
stdout=downloaded, check=True)
downloaded.seek(0)
actual = hashlib.file_digest(downloaded, "sha256").hexdigest()
if asset["size"] != path.stat().st_size or actual != sha256(path):
raise ReleaseArtifactError(f"immutable release asset differs: {path.name}")
return missing
def upload_immutable(dist_dir: Path, identity: ReleaseIdentity, repo: str,
*, recover: bool = False, dry_run: bool = False) -> None:
files = publication_files(dist_dir, identity)
require_stable_runtime_publication(dist_dir, identity)
if recover:
commit = require_release_commit(dist_dir, identity, repo)
for path in files:
gh("attestation", "verify", str(path), "--repo", repo,
"--signer-workflow", f"{repo}/.github/workflows/release-artifacts.yml",
"--source-digest", commit, "--source-ref", f"refs/tags/{identity.tag}",
"--deny-self-hosted-runners")
release = json.loads(gh("api", f"repos/{repo}/releases/tags/{identity.tag}"))
missing = missing_release_assets(repo, release["id"], files)
if missing and not dry_run:
gh("release", "upload", identity.tag, *(str(path) for path in missing), "--repo", repo)
print(f"verified {len(files) - len(missing)} existing assets; "
f"{'would upload' if dry_run else 'uploaded'} {len(missing)} missing assets")
def create_named_release(identity: ReleaseIdentity, repo: str, notes_file: Path, title: str) -> None:
# release:published starts artifact production. Keep the old stable
# endpoint serving a complete release while the new bundle is being built.
gh("release", "create", identity.tag, "--repo", repo, "--verify-tag",
"--latest=false", "--notes-file", str(notes_file), "--title", title)
def promote_latest(dist_dir: Path, identity: ReleaseIdentity, repo: str, *, execute: bool) -> None:
files = publication_files(dist_dir, identity)
require_stable_runtime_publication(dist_dir, identity)
require_release_commit(dist_dir, identity, repo)
release = json.loads(gh("api", f"repos/{repo}/releases/tags/{identity.tag}"))
if (release.get("tag_name") != identity.tag
or release.get("draft") is not False or release.get("prerelease") is not False):
raise ReleaseArtifactError("Latest requires the exact published named release")
if missing := missing_release_assets(repo, release["id"], files):
names = ", ".join(path.name for path in missing)
raise ReleaseArtifactError(f"cannot promote Latest with missing assets: {names}")
if not execute:
print(f"verified {len(files)} published assets for {identity.tag}; ready for Latest")
return
gh("api", "--method", "PATCH", f"repos/{repo}/releases/{release['id']}", "-f", "make_latest=true")
latest = json.loads(gh("api", f"repos/{repo}/releases/latest"))
if latest.get("id") != release["id"] or latest.get("tag_name") != identity.tag:
raise ReleaseArtifactError("Latest readback differs from the verified release")
print(f"verified GitHub Latest points to {identity.tag}")
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--project-root", type=Path, default=Path.cwd())
subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("expected-tag", help="print the tag required by package metadata")
validate = subparsers.add_parser("validate-tag", help="validate a release tag")
validate.add_argument("tag")
normalize = subparsers.add_parser("normalize-sdist", help="normalize sdist metadata")
normalize.add_argument("--dist-dir", type=Path, required=True)
normalize.add_argument("--source-date-epoch", type=int, required=True)
write = subparsers.add_parser("write-checksums", help="write a canonical SHA256SUMS file")
write.add_argument("--dist-dir", type=Path, required=True)
write.add_argument("--output", type=Path, required=True)
verify = subparsers.add_parser("verify-checksums", help="verify a canonical SHA256SUMS file")
verify.add_argument("--dist-dir", type=Path, required=True)
verify.add_argument("--checksum-file", type=Path, required=True)
recovery = subparsers.add_parser("verify-publication-run", help="verify a tagged build for publication recovery")
recovery.add_argument("--repo", required=True)
recovery.add_argument("--run-id", required=True)
recovery.add_argument("--commit", required=True)
stable = subparsers.add_parser("check-stable-runtime", help="check the tagged bundle before making it the stable default")
stable.add_argument("--dist-dir", type=Path, required=True)
upload = subparsers.add_parser("upload-immutable", help="resume publication without replacing existing bytes")
upload.add_argument("--repo", required=True)
upload.add_argument("--dist-dir", type=Path, required=True)
upload.add_argument("--recover", action="store_true")
upload.add_argument("--dry-run", action="store_true")
create = subparsers.add_parser("create-named-release", help="publish the existing tag without changing Latest")
create.add_argument("--repo", required=True)
create.add_argument("--notes-file", type=Path, required=True)
create.add_argument("--title", required=True)
promote = subparsers.add_parser("promote-latest", help="verify the published bundle before moving GitHub Latest")
promote.add_argument("--repo", required=True)
promote.add_argument("--dist-dir", type=Path, required=True)
promote.add_argument("--execute", action="store_true", help="move Latest after successful asset readback")
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
try:
identity = load_identity(args.project_root.resolve())
if args.command == "expected-tag":
print(identity.tag)
elif args.command == "validate-tag":
if args.tag != identity.tag:
raise ReleaseArtifactError(
f"release tag {args.tag!r} does not match package tag {identity.tag!r}"
)
print(f"validated release tag {args.tag}")
elif args.command == "normalize-sdist":
normalize_sdist(args.dist_dir, identity, args.source_date_epoch)
elif args.command == "write-checksums":
write_manifest(args.dist_dir, args.output, identity)
elif args.command == "verify-checksums":
verify_manifest(args.dist_dir, args.checksum_file, identity)
elif args.command == "verify-publication-run":
verify_publication_run(args.repo, args.run_id, identity.tag, args.commit)
elif args.command == "check-stable-runtime":
publication_files(args.dist_dir, identity)
require_stable_runtime_publication(args.dist_dir, identity)
print(f"verified stable runtime publication policy for {identity.tag}")
elif args.command == "upload-immutable":
upload_immutable(args.dist_dir, identity, args.repo,
recover=args.recover, dry_run=args.dry_run)
elif args.command == "create-named-release":
create_named_release(identity, args.repo, args.notes_file, args.title)
elif args.command == "promote-latest":
promote_latest(args.dist_dir, identity, args.repo, execute=args.execute)
else:
parser.error(f"unsupported command: {args.command}")
except ReleaseArtifactError as exc:
print(f"release artifact error: {exc}", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())