Repository navigation
Expand file tree
/
Copy pathrelease_contract.py
More file actions
339 lines (295 loc) · 15.6 KB
/
Copy pathrelease_contract.py
File metadata and controls
339 lines (295 loc) · 15.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
#!/usr/bin/env python3
"""Immutable release-ready/v1 bytes and the section 3.2 dispatch contract.
The manifest is canonical UTF-8 JSON plus LF, with neither event_id nor manifest
(both contain its hash). Delivery attempts never change these bytes or run_id.
"""
from __future__ import annotations
import base64
import hashlib
import json
import re
import release_pair as pair
from release_sources import RELEASE_TAG
HUB = "pineforge-4pass/pineforge-release"
IMAGE_OLD = "ghcr.io/pineforge-4pass/pineforge-release"
IMAGE_NEW = "ghcr.io/tunaxis/pineforge-release"
IMAGES = (IMAGE_OLD, IMAGE_NEW)
# Producers and pullers stay on the old path until rename day.
IMAGE = IMAGE_OLD
SCHEMA = "pineforge/release-ready/v1"
ASSET = "release-manifest.json"
CANDIDATE = "release-candidate.json"
ROLES = ("offline", "hosted", "application", "web", "data", "license", "compute")
DELIVERY_ONLY = ("compute",)
RECEIPT_ROLES = tuple(role for role in ROLES if role not in DELIVERY_ONLY)
EVENT_TYPES = {
"offline": "pineforge-release",
"hosted": "pineforge-release",
"application": "pineforge-release",
"web": "pineforge-release",
"data": "pineforge-release",
"license": "pineforge-release",
"compute": "release-pair",
}
SHA = r"[0-9a-f]{64}"
COMMIT = r"[0-9a-f]{40}"
MANIFEST_KEYS = {"schema", "release_version", "prerelease", "hub_commit", "versions", "image", "facts", "run_id"}
_INVENTORIES_UNSET = object()
class Invalid(ValueError):
pass
class Pending(Exception):
"""A real 404 or a legitimately unfinished prerequisite, never an API error."""
def require(condition, message):
if not condition:
raise Invalid(message)
def canonical(value):
return (json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
allow_nan=False) + "\n").encode("utf-8")
def sha256(raw):
return hashlib.sha256(raw).hexdigest()
def decode(raw):
def unique(pairs):
out = {}
for key, value in pairs:
require(key not in out, "duplicate JSON key")
out[key] = value
return out
try:
return json.loads(raw, object_pairs_hook=unique,
parse_constant=lambda _: require(False, "nonfinite JSON number"))
except (ValueError, UnicodeError, RecursionError) as error:
raise Invalid("invalid JSON") from error
def keys(obj, names):
require(type(obj) is dict and set(obj) == set(names), "unexpected object fields")
def match(pattern, value):
require(isinstance(value, str) and re.fullmatch(pattern, value) is not None, "malformed identity")
return value
def positive(value):
require(type(value) is int and 0 < value <= 2**53 - 1, "expected positive integer")
def version(value):
v = pair.parse(value)
require(str(v) == value, "version must be bare canonical semver")
return v
def parity_capable(release):
# parity_bundle uses the byte primitives above; import the cutoff lazily
# so the shared byte contract does not introduce an import cycle.
from parity_bundle import PARITY_CAPABILITY_FROM
return version(release) >= version(PARITY_CAPABILITY_FROM)
def validate_parity(engine, inventories=_INVENTORIES_UNSET):
"""Bind the exact wire identity to its source commit and canonical bytes."""
from parity_bundle import (APPROVED_FILES, DESCRIPTOR_NAME, DESCRIPTOR_SCHEMA,
SUMS_NAME, sums_bytes)
identity = engine.get("parity") if type(engine) is dict else None
require(type(identity) is dict, "parity capability missing for release")
keys(engine, ("version", "tag", "commit", "parity"))
keys(identity, ("schema", "source_manifest_sha256", "engine_commit", "payload_sha256",
"descriptor_sha256", "sums_sha256"))
require(identity["schema"] == DESCRIPTOR_SCHEMA, "parity identity differs from manifest")
match(COMMIT, engine["commit"])
match(COMMIT, identity["engine_commit"])
require(identity["engine_commit"] == engine["commit"], "parity identity differs from engine commit")
for field in ("source_manifest_sha256", "descriptor_sha256", "sums_sha256"):
match(SHA, identity[field])
payload_hashes = identity["payload_sha256"]
require(type(payload_hashes) is dict
and set(payload_hashes) == {destination for _, destination in APPROVED_FILES},
"parity inventory differs from candidate")
for value in payload_hashes.values():
match(SHA, value)
descriptor = {key: identity[key] for key in
("schema", "source_manifest_sha256", "engine_commit", "payload_sha256")}
descriptor_raw = canonical(descriptor)
require(sha256(descriptor_raw) == identity["descriptor_sha256"], "parity descriptor hash differs")
require(sha256(sums_bytes(descriptor_raw, payload_hashes)) == identity["sums_sha256"],
"parity SUMS hash differs")
if inventories is not _INVENTORIES_UNSET:
inventory = inventories.get("parity") if type(inventories) is dict else None
require(type(inventory) is dict
and set(inventory) == {DESCRIPTOR_NAME, SUMS_NAME, *payload_hashes},
"parity inventory differs from candidate")
require({name: inventory[name] for name in payload_hashes} == payload_hashes,
"parity inventory differs from candidate")
require(inventory[DESCRIPTOR_NAME] == identity["descriptor_sha256"],
"parity descriptor hash differs")
require(inventory[SUMS_NAME] == identity["sums_sha256"], "parity SUMS hash differs")
return identity
def parity_child_digests(image):
require(type(image) is dict, "parity child proof missing")
children = {arch: image.get(arch + "_digest") for arch in ("amd64", "arm64")}
require(all(value is not None for value in children.values()), "parity child proof missing")
digests = [image.get("digest"), *children.values()]
require(all(isinstance(value, str) and re.fullmatch("sha256:" + SHA, value) is not None
for value in digests) and len(set(digests)) == 3,
"parity child digest not verified")
return children
def validate(manifest):
keys(manifest, MANIFEST_KEYS)
require(manifest["schema"] == SCHEMA, "unsupported release schema")
v = version(manifest["release_version"])
require(type(manifest["prerelease"]) is bool and manifest["prerelease"] == v.prerelease,
"contradictory prerelease flag")
match(COMMIT, manifest["hub_commit"])
positive(manifest["run_id"])
versions = manifest["versions"]
keys(versions, ("engine", "codegen", "hpo"))
e, c, h = (versions[name] for name in ("engine", "codegen", "hpo"))
if parity_capable(str(v)):
require(not (type(e) is dict and set(e) == {"version", "tag", "commit"}),
"legacy manifest predates parity capability")
validate_parity(e)
else:
keys(e, ("version", "tag", "commit"))
keys(c, ("version", "pypi_version", "commit", "sdist_sha256", "npm_version", "npm_integrity"))
version(e["version"])
cv = version(c["version"])
require(e["tag"] == "v" + e["version"], "unexpected engine tag")
require(c["pypi_version"] == cv.pep440 and c["npm_version"] == str(cv), "codegen delivery versions differ")
match(SHA, c["sdist_sha256"])
match(r"sha512-[A-Za-z0-9+/]{86}==", c["npm_integrity"])
integrity = base64.b64decode(c["npm_integrity"][7:], validate=True)
require(base64.b64encode(integrity).decode("ascii") == c["npm_integrity"][7:],
"invalid npm integrity")
for item in (e, c):
match(COMMIT, item["commit"])
if pair.hpo_pairing(v):
keys(h, ("version", "package_version", "tag", "commit", "wheel_sha256", "sdist_sha256"))
hv = version(h["version"])
require(h["package_version"] == hv.pep440 and h["tag"] == "v" + hv.pep440, "unexpected HPO package spelling")
match(COMMIT, h["commit"])
for name in ("wheel_sha256", "sdist_sha256"):
match(SHA, h[name])
else:
require(h is None, "HPO must be explicitly null before cutoff")
pair.check(str(v), e["version"], c["version"], hpo=h["version"] if h else "")
image = manifest["image"]
keys(image, ("repository", "digest", "amd64_digest", "arm64_digest"))
require(isinstance(image["repository"], str) and image["repository"] in IMAGES,
"unexpected image repository")
for name in ("digest", "amd64_digest", "arm64_digest"):
match("sha256:" + SHA, image[name])
require(len({image[name] for name in ("digest", "amd64_digest", "arm64_digest")}) == 3,
"image index and architecture identities must be distinct")
facts = manifest["facts"]
keys(facts, ("commit", "path", "sha256", "release_key"))
match(COMMIT, facts["commit"])
match(SHA, facts["sha256"])
require(facts["path"] == "facts/facts.json" and facts["release_key"] == str(v), "unexpected facts identity")
return manifest
def payload(raw):
manifest = validate(decode(raw))
require(canonical(manifest) == raw, "noncanonical manifest bytes")
digest = sha256(raw)
return {**manifest, "event_id": "sha256:" + digest, "manifest": {"asset": ASSET, "sha256": digest}}
def validate_candidate(obj):
keys(obj, ("schema", "release_version", "hub_commit", "versions", "inventories", "image", "verification", "sources", "run_id"))
require(obj["schema"] == "pineforge/release-candidate/v1", "invalid candidate schema")
v = version(obj["release_version"])
match(COMMIT, obj["hub_commit"])
positive(obj["run_id"])
pins = obj["versions"]
pair.check(str(v), pins["engine"]["version"], pins["codegen"]["version"], hpo=pins["hpo"]["version"] if pins["hpo"] else "")
capable = parity_capable(str(v))
if capable:
validate_parity(pins["engine"], obj["inventories"])
children = parity_child_digests(obj["image"])
require(type(obj["verification"]) is dict and set(obj["verification"]) == {"amd64", "arm64"},
"parity child proof missing")
keys(obj["verification"], ("amd64", "arm64"))
for arch, result in obj["verification"].items():
if capable:
require(type(result) is dict, "parity child proof missing")
match(SHA, result["backtest_sha256"])
positive(result["trades"])
if pins["hpo"]:
require(type(result["hpo_trials"]) is int and result["hpo_trials"] == 9, "HPO smoke incomplete")
match(SHA, result["hpo_sha256"])
if capable:
child = result.get("parity")
require(type(child) is dict and set(child) == {"image_digest", "identity", "inventory"},
"parity child proof missing")
require(child["image_digest"] == children[arch], "parity child digest not verified")
require(child["identity"] == pins["engine"]["parity"], "parity descriptor identity differs")
require(child["inventory"] == obj["inventories"]["parity"], "parity installed file inventory differs")
keys(obj["sources"], ("release_tag", "list_asset", "list_sha256", "amd64_sha256", "arm64_sha256"))
for name in ("list_sha256", "amd64_sha256", "arm64_sha256"):
match(SHA, obj["sources"][name])
return obj
def pair_payload(manifest_raw, candidate_raw):
"""P04/P05: validate the published pair and hash its untouched asset bytes."""
manifest = payload(manifest_raw)
candidate = validate_candidate(decode(candidate_raw))
require(all(manifest[name] == candidate[name]
for name in ("release_version", "image", "hub_commit", "run_id")),
"manifest does not bind this candidate")
capable = parity_capable(manifest["release_version"])
if capable:
require(manifest["versions"]["engine"]["parity"] == candidate["versions"]["engine"]["parity"],
"parity identity differs from manifest")
for role in ("engine", "codegen", "hpo"):
actual = manifest["versions"][role]
expected = candidate["versions"][role]
if role == "engine" and capable:
# The explicit equality above owns parity; compare the remaining
# producer fields without a second, generic parity refusal.
actual = {key: value for key, value in actual.items() if key != "parity"}
expected = {key: value for key, value in expected.items() if key != "parity"}
if role == "codegen":
# npm is resolved during finalization, after the candidate is built.
actual = {key: value for key, value in actual.items() if key not in ("npm_version", "npm_integrity")}
require(actual == expected, "manifest producer identity differs from candidate")
sources = candidate["sources"]
# Only public source-bundle identities can enter the event. No arbitrary
# repository, URL, deployment name or private path is copied from a candidate.
match(RELEASE_TAG, sources["release_tag"])
match(r"set-[0-9]{2,}\.SOURCES\.list", sources["list_asset"])
base = f"https://github.com/{HUB}/releases/download/v{manifest['release_version']}/"
return {
"pair_id": manifest["release_version"],
"engine_tag": manifest["versions"]["engine"]["tag"],
"codegen_tag": "v" + manifest["versions"]["codegen"]["version"],
"hpo_tag": manifest["versions"]["hpo"]["tag"] if manifest["versions"]["hpo"] else None,
"receipt_url": base + ASSET,
"receipt_sha256": sha256(manifest_raw),
"source_sets": [sources],
"build": {
"prerelease": manifest["prerelease"], "hub_commit": manifest["hub_commit"],
"run_id": manifest["run_id"], "image": manifest["image"],
"candidate_url": base + CANDIDATE, "candidate_sha256": sha256(candidate_raw),
},
}
def validate_payload(event, raw):
keys(event, MANIFEST_KEYS | {"event_id", "manifest"})
require(event == payload(raw), "payload differs from immutable manifest")
# Python treats true == 1, so validate the original fields as well.
validate({key: event[key] for key in MANIFEST_KEYS})
return event
def bind_facts(raw, commit, release, versions):
# Import lazily so the byte contract is usable by consumers without jsonschema.
from facts_validate import validate_facts
facts = decode(raw)
validate_facts(facts)
match(COMMIT, commit)
# Prerelease measurements are not exported under releases[rc]. Bind the
# validated main snapshot bytes, without substituting them for stable proof.
if version(release).prerelease:
return {"commit": commit, "path": "facts/facts.json", "sha256": sha256(raw), "release_key": release}
entry = facts["releases"].get(release)
if entry is None:
raise Pending("measured immutable release facts unavailable")
scoreboard = entry["scoreboard"]
for role in ("engine", "codegen"):
require(scoreboard[role + "Commit"] == versions[role]["commit"], "release facts source commit differs")
require(scoreboard["graded"] > 0, "release facts have no graded evidence")
return {"commit": commit, "path": "facts/facts.json", "sha256": sha256(raw), "release_key": release}
def retain_facts(manifest, manifest_raw, installed_raw):
"""Consumers may keep newer verified canonical facts only with the same release entry."""
a, b = decode(manifest_raw), decode(installed_raw)
key = manifest["facts"]["release_key"]
require(sha256(manifest_raw) == manifest["facts"]["sha256"], "release facts digest differs")
if manifest["prerelease"] and key not in a["releases"]:
require(installed_raw == manifest_raw, "prerelease without measured entry requires pinned facts bytes")
else:
require(key in a["releases"] and a["releases"][key] == b["releases"].get(key), "release facts entry changed")
from facts_validate import validate_facts
validate_facts(b)
return sha256(installed_raw)