Repository navigation
Expand file tree
/
Copy pathrelease_receipts.py
More file actions
1366 lines (1251 loc) · 77.7 KB
/
Copy pathrelease_receipts.py
File metadata and controls
1366 lines (1251 loc) · 77.7 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Read consumer-owned Actions evidence and publish neutral completion receipts.
A callback is only a wakeup. Neither a callback nor a successful dispatch can
claim verified. Evidence must come from a configured workflow's artifact in the
configured repository, and its full CI/E2E inventory is checked against GitHub.
"""
from __future__ import annotations
import argparse
import base64
import binascii
import datetime as dt
import io
import os
import re
import sys
import zipfile
import zlib
from pathlib import Path
from release_artifacts import Client, RequestError
from release_contract import (ASSET, COMMIT, HUB, RECEIPT_ROLES, ROLES, SHA, Invalid, Pending,
canonical, decode, keys, match, payload, positive,
require, sha256, version)
from release_pipeline import (Store, configured_roles, receipt_roles, receipts,
load_receipt_exclusions, release_superseded,
report_issue, run_link)
STATES = ("pending", "pr_open", "testing", "ready", "merged", "deploying", "verified", "failed", "superseded", "skipped_by_policy")
RANK = {state: i for i, state in enumerate(STATES[:7])}
PRODUCT_SCHEMA = "pineforge/consumer-receipt/v1"
FACTS_SCHEMA = "pineforge/facts-consumer-receipt/v1"
COMMON_FIELDS = {"schema", "consumer", "attempt", "sequence", "state", "timestamp",
"pr", "ci", "e2e", "deploy", "preview", "deployed", "previous"}
# TEMPORARY first-adopter previous. Remove together with pineforge-data's BOOTSTRAP_PACKAGE exemption
# (scripts/release_chain/publishing.py), only after data 0.3.1 is verified AND every retained
# release-receipt-data artifact carrying this previous has expired (see docs/release-chain.md).
DATA_BOOTSTRAP_PREVIOUS = {
"provenance": "pre-manifest-bootstrap",
"package": "pineforge-data",
"version": "0.3.0",
"source": "fb5cec39b6c6d70af103df0df182d47bb5812191",
"image_digest": "sha256:b271873d0e91a9eeeb4595daaded9bdfbdbcd3925d3ec1300a833395e2004c86",
"distributions": {
"pineforge_data-0.3.0-py3-none-any.whl": "609b3e9976ae55fc290c725731cf1dd0266c9b3eb6f3353122c8bcdc05e497bc",
"pineforge_data-0.3.0.tar.gz": "f29a2bd50f70ff46ebdf31f987260dec3123600ab5bf493741bbbd4e21aaacdc",
},
}
# TEMPORARY real offline 0.9.40 predecessor. Remove in the first hub release after
# offline MCP ships its first non-legacy release through the new chain (0.9.43 or later).
# See docs/release-chain.md.
OFFLINE_LEGACY_PREVIOUS = {
"legacy": True,
"npm_version": "0.9.40",
"npm_integrity": "sha512-o1hmSb6FwjkF8lIwLhENJV+YPbYqSwG1KPvHyViPj5Yan3aHoNRCpM5uINaYbjZKjGS95VDClmASOUSD6ZktVw==",
"git_head": "b988217f2aa21b6b772fb723adbc89bd4130c3f5",
# Multi-architecture index of ghcr.io/pineforge-4pass/pineforge-backtest-mcp:v0.9.40.
"image_digest": "sha256:129aa9cb5db4400523d1fc12a11671cfb820f934d893e4ee8945cd25c5bc202d",
}
def object_pages(client, route, key):
rows = []
for page in range(1, 1001):
result = client.api(route + ("&" if "?" in route else "?") + f"per_page=100&page={page}")[key]
rows.extend(result)
if len(result) < 100:
return rows
raise Invalid("consumer API pagination limit exceeded")
# --- Shard receipt plans ----------------------------------------------------
SHARD_FIELD = "shards"
SHARD_CHECK_FIELDS = {"run_id", "run_attempt", "sha", "expected", "approved_skips", "results"}
SHARD_MANIFEST, SHARD_CHANGE = "manifest", "n_change"
SHARD_COUNT, SHARD_DECLARED, SHARD_TIMEOUT = "shard_count", "declared_count", "timeout_minutes"
SHARD_DISJOINT, SHARD_UNION, SHARD_INVENTORY = "disjoint", "union_count", "inventory_count"
SHARD_EQUAL = "union_equals_inventory"
SHARD_INVENTORY_HASH, SHARD_PLAN_HASH = "inventory_sha256", "plan_sha256"
SHARD_BASE, SHARD_CANDIDATE, SHARD_PATH = "base_n", "candidate_n", "path"
SHARD_POLICY_FIELDS = {"format", "file", SHARD_PATH, "max_minutes"}
SHARD_STEADY_CHANGE = None
SHARD_PUBLIC_COUNT, SHARD_PUBLIC_INVENTORY, SHARD_PUBLIC_CHANGE = "count", "inventory", "change"
SHARD_SECONDS, SHARD_FROM, SHARD_TO = "seconds", "from", "to"
SHARD_CHECKED = "checked_shards"
SHARD_EVIDENCE_FIELDS = SHARD_CHECK_FIELDS | {SHARD_MANIFEST, SHARD_CHANGE}
SHARD_MANIFEST_FIELDS = {
SHARD_COUNT, SHARD_FIELD, SHARD_DISJOINT, SHARD_UNION, SHARD_INVENTORY,
SHARD_EQUAL, SHARD_INVENTORY_HASH, SHARD_PLAN_HASH,
}
SHARD_ENTRY_FIELDS = {SHARD_DECLARED, SHARD_TIMEOUT}
SHARD_CHANGE_FIELDS = {SHARD_BASE, SHARD_CANDIDATE, SHARD_PATH}
def shard_positive(value):
return type(value) is int and value >= 1
def transitional_absent_base_plan(shards, *, validate_only=False, candidate=None, evidence=None):
"""Keep the optional absent-file allowance and its validation together."""
field = "absent_count"
require(type(shards) is dict
and SHARD_POLICY_FIELDS <= set(shards) <= SHARD_POLICY_FIELDS | {field},
"unexpected shard policy fields")
if field in shards:
require(shard_positive(shards[field]), "invalid transitional shard count")
if validate_only:
return None
require(field in shards, "shard base file absent without transitional count")
if candidate is None:
require(type(evidence) is dict and set(evidence) == SHARD_CHECK_FIELDS,
"transitional shard evidence must use legacy fields")
return shards[field]
def shard_inventory(row):
expected, skips = row["expected"], row["approved_skips"]
require(type(expected) is list and bool(expected)
and all(type(name) is str for name in expected)
and len(expected) == len(set(expected)), "empty or duplicate required inventory")
require(type(skips) is list and all(type(name) is str for name in skips)
and set(skips) <= set(expected), "invalid skip policy")
require(set(expected) - set(skips), "entire required inventory cannot be skipped")
def shard_policy(row):
shards = row[SHARD_FIELD]
transitional_absent_base_plan(shards, validate_only=True)
template = shards["format"]
require(type(template) is str and template.count("{i}") == template.count("{n}") == 1
and not any(char in template.replace("{i}", "").replace("{n}", "") for char in "{}"),
"invalid shard format")
path = shards["file"]
require(type(path) is str and re.fullmatch(r"[A-Za-z0-9_./-]+", path) is not None
and not path.startswith("/") and all(part not in ("", ".", "..") for part in path.split("/")),
"invalid shard file path")
require(type(shards[SHARD_PATH]) is list and bool(shards[SHARD_PATH])
and all(type(key) is str and bool(key) for key in shards[SHARD_PATH]), "invalid shard count path")
require(shard_positive(shards["max_minutes"]), "invalid shard time limit")
require(type(row["expected"]) is list and row["expected"].count(template) == 1,
"shard placeholder must appear exactly once")
require(type(row["approved_skips"]) is list, "invalid skip policy")
require(template not in row["approved_skips"], "shard checks cannot be skipped")
shard_inventory(row)
def shard_file_count(client, repo, shards, ref):
try:
contents = client.api(f"repos/{repo}/contents/{shards['file']}?ref={ref}")
except Pending:
return None
require(type(contents) is dict and contents.get("type") == "file", "shard source is not a file")
content = contents.get("content")
require(contents.get("encoding") == "base64" and type(content) is str and bool(content),
"shard file has no inline base64 content")
try:
# The contents API wraps inline base64 in lines.
raw = base64.b64decode(content.replace("\n", "").replace("\r", ""), validate=True)
except (ValueError, binascii.Error):
raise Invalid("invalid shard file base64") from None
try:
value = decode(raw)
except Invalid:
raise Invalid("invalid shard file JSON") from None
for key in shards[SHARD_PATH]:
require(type(value) is dict and key in value, "shard count path missing")
value = value[key]
require(shard_positive(value), "shard count must be a positive integer")
return value
def shard_manifest(manifest, count, family, max_minutes):
require(type(manifest) is dict and set(manifest) == SHARD_MANIFEST_FIELDS,
"unexpected shard manifest fields")
require(type(manifest[SHARD_COUNT]) is int and manifest[SHARD_COUNT] == count,
"shard manifest count differs")
entries = manifest[SHARD_FIELD]
require(type(entries) is dict and len(entries) == count, "shard manifest size differs")
require(set(entries) == set(family), "shard manifest names differ")
declared = []
for entry in entries.values():
require(type(entry) is dict and set(entry) == SHARD_ENTRY_FIELDS, "unexpected shard entry fields")
require(shard_positive(entry[SHARD_DECLARED]), "shard declared count must be a positive integer")
require(shard_positive(entry[SHARD_TIMEOUT]), "shard timeouts must be positive integers")
require(entry[SHARD_TIMEOUT] <= max_minutes, "shard timeout exceeds policy limit")
declared.append(entry[SHARD_DECLARED])
require(manifest[SHARD_DISJOINT] is True, "shard manifest is not disjoint")
union = manifest[SHARD_UNION]
require(shard_positive(union), "shard manifest union must be a positive integer")
require(union == sum(declared), "shard manifest union differs from shard sum")
inventory = manifest[SHARD_INVENTORY]
require(shard_positive(inventory), "shard manifest inventory must be a positive integer")
require(union == inventory, "shard manifest union differs from inventory")
require(manifest[SHARD_EQUAL] is True, "shard manifest inventory equality is not true")
for field, message in (
(SHARD_INVENTORY_HASH, "invalid shard inventory hash"), (SHARD_PLAN_HASH, "invalid shard plan hash")):
require(type(manifest[field]) is str and re.fullmatch(SHA, manifest[field]) is not None, message)
return inventory
def shard_plan(client, repo, evidence, row, pr):
"""Resolve both commits and validate bounded evidence before reading a run."""
shard_policy(row)
shards = row[SHARD_FIELD]
base = shard_file_count(client, repo, shards, pr["base_sha"])
candidate = shard_file_count(client, repo, shards, pr["head"])
base_absent = base is None
legacy = base_absent and candidate is None
if base_absent:
base = transitional_absent_base_plan(shards, candidate=candidate, evidence=evidence)
else:
require(candidate is not None, "shard count file deletion is forbidden")
count = base if legacy or candidate == base else candidate
changed = not legacy and (base_absent or candidate != base)
require(type(evidence) is dict, "unexpected shard check fields")
fields = SHARD_CHECK_FIELDS
if not legacy:
require(SHARD_MANIFEST in evidence, "shard manifest evidence is required")
fields = SHARD_EVIDENCE_FIELDS
require(set(evidence) == fields, "unexpected shard check fields")
expected = evidence["expected"]
require(type(expected) is list, "shard evidence expected must be a list")
require(len(expected) == len(row["expected"]) - 1 + count, "shard evidence list length differs")
# Allocation is bounded by the evidence's own list, after the length check.
template = shards["format"]
family = [template.format(i=i, n=count) for i in range(1, count + 1)]
effective = {"workflow": row["workflow"], "expected": [], "approved_skips": row["approved_skips"]}
for name in row["expected"]:
effective["expected"].extend(family if name == template else [name])
shard_inventory(effective)
require(expected == effective["expected"] and evidence["approved_skips"] == effective["approved_skips"],
"required check inventory differs from owner policy")
inventory, change = None, None
if not legacy:
inventory = shard_manifest(evidence[SHARD_MANIFEST], count, family, shards["max_minutes"])
if changed:
claimed = evidence[SHARD_CHANGE]
require(claimed is not None, "shard count change record is required")
require(type(claimed) is dict and set(claimed) == SHARD_CHANGE_FIELDS,
"unexpected shard change fields")
require(type(claimed[SHARD_BASE]) is int and claimed[SHARD_BASE] == base,
"shard change base count differs")
require(type(claimed[SHARD_CANDIDATE]) is int and claimed[SHARD_CANDIDATE] == candidate,
"shard change candidate count differs")
require(type(claimed[SHARD_PATH]) is str and claimed[SHARD_PATH] == shards["file"],
"shard change file path differs")
change = {SHARD_FROM: base, SHARD_TO: count}
else:
require(evidence[SHARD_CHANGE] is SHARD_STEADY_CHANGE, "unchanged shard count cannot claim change")
summary = {SHARD_PUBLIC_COUNT: count, SHARD_PUBLIC_INVENTORY: inventory, SHARD_PUBLIC_CHANGE: change}
plain = {key: evidence[key] for key in SHARD_CHECK_FIELDS}
return effective, plain, family, summary
def shard_duration(job):
start, end = job.get("started_at"), job.get("completed_at")
require(type(start) is str and type(end) is str, "shard job timestamps missing")
try:
started = dt.datetime.fromisoformat(start.replace("Z", "+00:00"))
completed = dt.datetime.fromisoformat(end.replace("Z", "+00:00"))
except ValueError:
raise Invalid("invalid shard job timestamps") from None
require(started.utcoffset() is not None and completed.utcoffset() is not None,
"invalid shard job timestamps")
require(completed >= started, "shard job duration is negative")
return completed - started
def check_shard_run(client, repo, evidence, row, pr):
effective, plain, family, summary = shard_plan(client, repo, evidence, row, pr)
template = row[SHARD_FIELD]["format"]
pattern = re.escape(template).replace(re.escape("{i}"), "[0-9]+").replace(re.escape("{n}"), "[0-9]+")
allowed, family_names, seen = set(effective["expected"]), set(family), {}
def inspect_jobs(jobs):
for job in jobs:
name = job["name"]
require(re.fullmatch(pattern, name) is None or name in allowed, "unexpected job in shard family")
if name in family_names:
seen[name] = job
run = check_run(client, repo, plain, effective, pr["head"], inspect_jobs=inspect_jobs)
summary[SHARD_SECONDS] = []
for name in family:
duration = shard_duration(seen[name])
summary[SHARD_SECONDS].append(duration // dt.timedelta(seconds=1))
run[SHARD_CHECKED] = summary
return run
# --- End shard receipt plans ------------------------------------------------
def profile(role):
require(role in RECEIPT_ROLES, "unexpected receipt role")
profiles = decode(os.environ.get("RELEASE_RECEIPT_POLICY", "{}"))
require(role in profiles, "consumer evidence policy not configured")
policy = profiles[role]
sections = ("ci", "e2e", "deploy")
if type(policy) is dict and "post_merge" in policy:
require(role == "application", "post-merge policy is only valid for application")
sections += ("post_merge",)
reporter = ()
if type(policy) is dict and APPLICATION_REPORTER in policy:
require(role == "application", "application reporter policy is only valid for application")
reporter = (APPLICATION_REPORTER,)
keys(policy, ("workflow", "artifact", "base", *sections, *reporter))
for item in (policy, *(policy[name] for name in sections)):
match(r"[A-Za-z0-9_.-]+\.yml", item["workflow"])
match(r"[A-Za-z0-9_.-]+", policy["artifact"])
require(policy["base"] in ("main", "dev"), "unapproved consumer base")
for name in sections:
row = policy[name]
if type(row) is dict and SHARD_FIELD in row:
require(name == "ci", "shards policy is only valid for ci")
keys(row, ("workflow", "expected", "approved_skips", SHARD_FIELD))
shard_policy(row)
else:
keys(row, ("workflow", "expected", "approved_skips"))
require(type(row["expected"]) is list and len(row["expected"]) > 0
and len(row["expected"]) == len(set(row["expected"])), "empty or duplicate required inventory")
require(type(row["approved_skips"]) is list and set(row["approved_skips"]) <= set(row["expected"]), "invalid skip policy")
require(set(row["expected"]) - set(row["approved_skips"]), "entire required inventory cannot be skipped")
if name == "post_merge":
require(row["approved_skips"] == [], "post-merge checks cannot be skipped")
if reporter:
application_reporter_policy(policy)
return policy
def check_run(client, repo, evidence, policy, expected_sha, *, inspect_jobs=None):
keys(evidence, ("run_id", "run_attempt", "sha", "expected", "approved_skips", "results"))
positive(evidence["run_id"])
positive(evidence["run_attempt"])
require(evidence["sha"] == expected_sha, "checks ran against a different source")
require(evidence["expected"] == policy["expected"] and evidence["approved_skips"] == policy["approved_skips"],
"required check inventory differs from owner policy")
run = client.api(f"repos/{repo}/actions/runs/{evidence['run_id']}/attempts/{evidence['run_attempt']}")
require(run["path"] == ".github/workflows/" + policy["workflow"] and run["head_sha"] == expected_sha,
"unexpected checks workflow or head")
require(run["status"] == "completed" and run["conclusion"] == "success", "required check run not successful")
jobs = object_pages(client, f"repos/{repo}/actions/runs/{evidence['run_id']}/attempts/{evidence['run_attempt']}/jobs", "jobs")
if inspect_jobs is not None:
inspect_jobs(jobs)
checked, finished = {}, []
for name in policy["expected"]:
found = [row for row in jobs if row["name"] == name]
require(len(found) == 1 and found[0]["status"] == "completed", "required check missing or incomplete")
result = found[0]["conclusion"]
require(result == "success" or (result == "skipped" and name in policy["approved_skips"]), "required check failed/cancelled/skipped")
if result == "success":
require(isinstance(found[0].get("completed_at"), str), "required check completion time missing")
finished.append(found[0]["completed_at"])
checked[name] = result
require(evidence["results"] == checked, "reported checks differ from GitHub")
require(bool(finished), "required inventory contains no successful checks")
run["checked_finished_at"] = max(finished)
run["checked_first_finished_at"] = min(finished)
return run
def check_coordinator(client, repo, evidence, policy, pr, ci):
"""Hosted base-code E2E bound to an exact PR-head build attempt/artifact.
The caller restricts this adapter to hosted. Keep check_run's exact SHA
equality for every other workflow, including hosted CI and deployment.
"""
require(policy["workflow"] == "release-coordinator.yml", "unapproved coordinator workflow")
require(policy["expected"] == ["candidate", "release/ready"] and policy["approved_skips"] == [],
"coordinator inventory differs")
run = check_run(client, repo, evidence, policy, pr["base_sha"])
require(run["id"] == evidence["run_id"] and run["run_attempt"] == evidence["run_attempt"],
"coordinator run identity differs")
metadata = client.api(f"repos/{repo}")
require(metadata["full_name"].lower() == repo.lower()
and run["repository"]["full_name"].lower() == repo.lower()
and run["head_repository"]["full_name"].lower() == repo.lower(),
"coordinator repository differs")
require(run["event"] == "workflow_run" and pr["base"] == metadata["default_branch"] == "main"
and run["head_branch"] == metadata["default_branch"], "untrusted coordinator source")
artifacts = object_pages(client, f"repos/{repo}/actions/runs/{run['id']}/artifacts", "artifacts")
name = f"coordinator-binding-{run['id']}-{run['run_attempt']}"
found = [a for a in artifacts if a["name"] == name and not a["expired"]]
require(len(found) == 1, "missing/ambiguous coordinator binding")
positive(found[0]["id"])
# GitHub 415s application/octet-stream on the artifact zip endpoint; release assets need it, artifacts must not use it (incident #61).
archive = client.request(f"https://api.github.com/repos/{repo}/actions/artifacts/{found[0]['id']}/zip",
github=True)
require(len(archive) <= 2 * 1024 * 1024, "binding archive too large")
require(found[0].get("digest") == "sha256:" + sha256(archive), "binding archive digest missing or differs")
with zipfile.ZipFile(io.BytesIO(archive)) as zipped:
require(zipped.namelist() == ["binding.json"], "unexpected binding archive inventory")
require(zipped.getinfo("binding.json").file_size <= 2 * 1024 * 1024, "binding too large")
binding = decode(zipped.read("binding.json"))
keys(binding, ("schema", "pr", "head", "base", "source", "coordinator", "artifact"))
require(binding["schema"] == "pineforge/mcp-coordinator-binding/v1", "unknown coordinator binding")
positive(binding["pr"])
keys(binding["source"], ("run_id", "attempt"))
keys(binding["coordinator"], ("run_id", "attempt", "sha"))
for bound_run in (binding["source"], binding["coordinator"]):
positive(bound_run["run_id"])
positive(bound_run["attempt"])
require(binding["pr"] == pr["number"] and binding["head"] == pr["head"] and binding["base"] == pr["base_sha"],
"coordinator verified another PR head/base")
require(binding["source"] == {"run_id": ci["run_id"], "attempt": ci["run_attempt"]}, "coordinator verified another CI attempt")
require(binding["coordinator"] == {"run_id": run["id"], "attempt": run["run_attempt"], "sha": pr["base_sha"]},
"coordinator binding source differs")
artifact = binding["artifact"]
keys(artifact, ("id", "name", "digest", "manifest_sha256", "worker_sha256", "container_sha256"))
positive(artifact["id"])
require(artifact["name"] == f"candidate-{ci['run_id']}-{ci['run_attempt']}", "candidate attempt differs")
match("sha256:" + SHA, artifact["digest"])
for key in ("manifest_sha256", "worker_sha256", "container_sha256"):
match(SHA, artifact[key])
candidates = object_pages(client, f"repos/{repo}/actions/runs/{ci['run_id']}/artifacts", "artifacts")
matched = [a for a in candidates if a["name"] == artifact["name"] and not a["expired"]]
require(len(matched) == 1 and matched[0]["id"] == artifact["id"] and matched[0].get("digest") == artifact["digest"],
"verified candidate artifact missing or replaced")
return run
def check_postmerge(client, repo, evidence, policy, pr, actual, timestamp):
"""Hosted E2E on merged main; private evidence content stays consumer-side."""
require(policy["e2e"]["expected"] == ["authz", "build", "verified"] and policy["e2e"]["approved_skips"] == [],
"postmerge inventory differs")
run = check_run(client, repo, evidence, policy["e2e"], pr["merge"])
require(run["id"] == evidence["run_id"] and run["run_attempt"] == evidence["run_attempt"],
"postmerge run identity differs")
metadata = client.api(f"repos/{repo}")
require(metadata["full_name"].lower() == repo.lower()
and run["repository"]["full_name"].lower() == repo.lower()
and run["head_repository"]["full_name"].lower() == repo.lower(),
"postmerge repository differs")
require(run["event"] == "workflow_dispatch" and run["head_branch"] == metadata["default_branch"] == "main" == pr["base"],
"untrusted postmerge source")
require(actual["merged"] is True and actual["merge_commit_sha"] == pr["merge"], "PR is not the recorded merge")
require(run["checked_first_finished_at"] >= actual["merged_at"], "postmerge E2E completed before merge")
require(timestamp >= run["checked_finished_at"], "receipt predates postmerge verification")
# The released PR must not supply a different definition of its own gate.
workflow_route = f"repos/{repo}/contents/.github/workflows/{policy['e2e']['workflow']}"
blobs = []
for ref in (pr["base_sha"], pr["merge"]):
try:
contents = client.api(f"{workflow_route}?ref={ref}")
except Pending:
raise Invalid("postmerge workflow is not a file") from None
require(type(contents) is dict and contents.get("type") == "file", "postmerge workflow is not a file")
blobs.append(match(COMMIT, contents.get("sha")))
require(blobs[0] == blobs[1], "postmerge workflow differs from tested base")
artifacts = object_pages(client, f"repos/{repo}/actions/runs/{run['id']}/artifacts", "artifacts")
name = f"postmerge-evidence-{run['id']}-{run['run_attempt']}"
found = [a for a in artifacts if a["name"] == name and not a["expired"]]
require(len(found) == 1, "missing/ambiguous postmerge evidence")
return run
# --- Application protected-main reporter ------------------------------------
# An application `verified` receipt normally needs its reporting run at pr.merge. When
# the application policy carries `application_reporter`, the reporter is instead one
# reviewed commit on protected main. That history is separate from the development
# merge, so the reporter is never compared with pr.merge or required to descend from
# it. The bridge is two signed App records (kinds `snapshot` and `receipt-run`) read
# from GitHub deployments and verified only with the policy-pinned coordinator key.
# Their members are exactly the ones the pinned App coordinator (blob 0c96484d) and its
# signed state (blob 260912eb) write. The served source stays pr.merge. Without the
# profile nothing here runs; once it is selected there is no fallback to the legacy rule
# on missing or invalid evidence.
#
# Step 1 verifies the signed binders. It still fails closed on the missing authenticated
# dispatch inputs; see docs/application-receipt-reporter.md.
APPLICATION_REPORTER = "application_reporter"
REPORTER_FIELDS = ("commit", "workflow_id", "reusable", "actor", "coordinator_public_key",
"coordinator_spki_sha256")
EVIDENCE_ENVIRONMENT, EVIDENCE_TASK = "dev-release-evidence", "dev-release-observation"
EVIDENCE_SCHEMA = "pineforge/dev-observation/v1"
SNAPSHOT_KIND, RECEIPT_RUN_KIND = "snapshot", "receipt-run"
REPORTER_BRANCH, REPORTER_EVENT = "main", "workflow_dispatch"
# The ref of the reporter's reusable-workflow reference. The signed records carry another ref: the
# receipt tag the coordinator creates at the served source.
REPORTER_REF = "refs/heads/main"
# The receipt-run row: the members the coordinator names when it writes the row, plus the three every
# signed record carries (schema, owner, owner_sha). dry_run and receipt_only are NOT among them: they
# are inputs of the coordinator's workflow dispatch, and no signed record keeps them.
RECEIPT_RUN_FIELDS = ("schema", "kind", "owner", "owner_sha", "snapshot_id", "request", "repository",
"workflow", "dispatch_ref", "workflow_run_id", "workflow_sha", "ref", "source",
"pair", "sequence", "attempt", "owner_attempt", "created_at")
# The snapshot: the members this validator reads must be present; the rest of what the coordinator may
# write (the observation's neighbours) are allowed and otherwise ignored; nothing else is.
SNAPSHOT_REQUIRED = ("schema", "kind", "owner", "owner_sha", "ref", "source", "request", "payload",
"sequence", "observation", "pair", "owner_attempt", "created_at")
SNAPSHOT_OPTIONAL = ("before", "after", "previousGood", "deployedGood", "landed", "postMerge",
"deploy_ref", "landed_ref")
# A policy key is one Ed25519 SubjectPublicKeyInfo PEM: 44 DER bytes are exactly one 60-character line.
ED25519_PUBLIC_KEY_PEM = re.compile(r"-----BEGIN PUBLIC KEY-----\n([A-Za-z0-9+/]{59}=)\n-----END PUBLIC KEY-----\n?")
# A signature is the canonical standard base64 of 64 raw bytes (the padding bits are zero: A, Q, g or w).
SIGNATURE_TEXT = re.compile(r"[A-Za-z0-9+/]{85}[AQgw]==")
def positive_number(value):
return type(value) is int and 0 < value <= 2**53 - 1
def commit_text(value):
return type(value) is str and re.fullmatch(COMMIT, value) is not None
def plain_text(value):
return type(value) is str and value != ""
def pinned_key_der(pem):
found = ED25519_PUBLIC_KEY_PEM.fullmatch(pem) if type(pem) is str else None
require(found is not None, "application reporter coordinator public key is malformed")
try:
der = base64.b64decode(found.group(1), validate=True)
except (ValueError, binascii.Error):
raise Invalid("application reporter coordinator public key is malformed") from None
require(base64.b64encode(der).decode("ascii") == found.group(1),
"application reporter coordinator public key is malformed")
return der
def application_reporter_policy(policy):
"""Validate the pinned reporter profile and return it. The key is this pin and nothing else."""
require(type(policy) is dict and type(policy.get(APPLICATION_REPORTER)) is dict,
"application reporter policy missing")
pin = policy[APPLICATION_REPORTER]
require(set(pin) == set(REPORTER_FIELDS), "application reporter policy fields differ from the schema")
for name, valid in (
("commit", commit_text(pin["commit"])),
("workflow_id", positive_number(pin["workflow_id"])),
("reusable", type(pin["reusable"]) is str
and re.fullmatch(r"[A-Za-z0-9_.-]+\.yml", pin["reusable"]) is not None),
("actor", type(pin["actor"]) is str
and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9-]*(?:\[bot\])?", pin["actor"]) is not None)):
require(valid, f"application reporter policy member {name} is malformed")
require(pin["reusable"] != policy["workflow"],
"application reporter reusable workflow must differ from the reporting workflow")
# Never a key from the provider run, a signed record, a repository variable or a snapshot.
der = pinned_key_der(pin["coordinator_public_key"])
require(type(pin["coordinator_spki_sha256"]) is str
and re.fullmatch(SHA, pin["coordinator_spki_sha256"]) is not None,
"application reporter coordinator key pin is malformed")
require(sha256(der) == pin["coordinator_spki_sha256"],
"application reporter coordinator public key is not the pinned key")
return pin
def run_member(run, name):
require(type(run) is dict and name in run, "application reporter run lacks a required member")
return run[name]
def instant(value, message):
require(type(value) is str
and re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", value) is not None,
message)
try:
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
raise Invalid(message) from None
def reporter_run(repo, policy, pin, actual, run):
"""Checks that need only the pin and the provider run; they precede every reporter API read."""
require(run_member(run, "event") == REPORTER_EVENT, "application reporter requires workflow_dispatch")
positive(run_member(run, "id"))
require(run_member(run, "path") == ".github/workflows/" + policy["workflow"]
and type(run_member(run, "workflow_id")) is int and run["workflow_id"] == pin["workflow_id"],
"application reporter workflow differs from policy")
require(type(run_member(run, "run_attempt")) is int and run["run_attempt"] == 1,
"application reporter attempt differs")
require(run_member(run, "head_branch") == REPORTER_BRANCH, "application reporter branch differs from main")
require(run_member(run, "head_sha") == pin["commit"], "application reporter head differs from the pinned commit")
# Both actors come from the pin; an actor named inside signed evidence is never trusted.
for name in ("actor", "triggering_actor"):
who = run_member(run, name)
require(type(who) is dict and who.get("login") == pin["actor"],
"application reporter actor differs from policy")
for name in ("repository", "head_repository"):
where = run_member(run, name)
require(type(where) is dict and type(where.get("full_name")) is str
and where["full_name"].lower() == repo.lower(), "application reporter repository differs")
malformed = "application reporter timestamp is malformed"
require(instant(run_member(run, "created_at"), malformed) > instant(actual.get("merged_at"), malformed),
"application reporter was not created after the PR merge")
# Exactly one direct reference, to the reviewed reusable workflow, at the pinned commit and
# at the explicit main ref: nothing floating, foreign, extra or otherwise shaped.
tail = f"/.github/workflows/{pin['reusable']}@{pin['commit']}"
references = run_member(run, "referenced_workflows")
require(type(references) is list and len(references) == 1,
"application reporter must reference exactly one reusable workflow")
reference = references[0]
require(type(reference) is dict and set(reference) == {"path", "sha", "ref"},
"application reporter reusable reference members differ")
require(type(reference["path"]) is str and reference["path"].endswith(tail)
and reference["path"][:-len(tail)].lower() == repo.lower(),
"application reporter reusable workflow path differs from the pin")
require(reference["sha"] == pin["commit"], "application reporter reusable workflow commit differs from the pin")
require(reference["ref"] == REPORTER_REF, "application reporter reusable workflow ref is not refs/heads/main")
def reporter_source(client, repo, pin):
"""The pinned commit is on protected main; main may since have advanced."""
try:
branch = client.api(f"repos/{repo}/branches/{REPORTER_BRANCH}")
except Pending:
raise Invalid("application reporter branch is not protected main") from None
require(type(branch) is dict and branch.get("name") == REPORTER_BRANCH and branch.get("protected") is True
and type(branch.get("commit")) is dict, "application reporter branch is not protected main")
head = match(COMMIT, branch["commit"].get("sha"))
try:
comparison = client.api(f"repos/{repo}/compare/{pin['commit']}...{head}")
except Pending:
raise Invalid("application reporter commit is not on protected main") from None
require(type(comparison) is dict and comparison.get("status") in ("ahead", "identical"),
"application reporter commit is not on protected main")
def deployment_pages(client, route):
rows = []
for page in range(1, 1001):
result = client.api(f"{route}&per_page=100&page={page}")
require(type(result) is list, "unexpected application deployment listing")
rows.extend(result)
if len(result) < 100:
return rows
raise Invalid("application deployment pagination limit exceeded")
def deployment_claim(deployment):
"""The (envelope, record) a store deployment appears to carry, or None. Nothing here is trusted yet."""
if (type(deployment) is not dict or deployment.get("environment") != EVIDENCE_ENVIRONMENT
or deployment.get("task") != EVIDENCE_TASK):
return None
envelope = deployment.get("payload")
value = envelope
if type(envelope) is str:
try:
value = decode(envelope)
except Invalid:
return None
if type(value) is not dict or type(value.get("record")) is not dict:
return None
return envelope, value["record"]
def authenticate_record(envelope, kind, noun, pin):
"""The record of a store envelope once the pinned key has signed it as `kind`.
A record is evidence only through this, and every way it can fail names its own check.
"""
# Keep the new dependency off the legacy path, including the signal job.
import release_signed_record as signed
value = envelope
if type(envelope) is str:
try:
value = signed.parse_json_strict(envelope.encode("utf-8"))
except (UnicodeError, signed.SignedRecordError):
raise Invalid(f"application {noun} envelope is malformed") from None
# For a provider object payload, Client.api already rejected duplicate JSON members.
# An envelope is a record and, optionally, its signature: any other member is not the coordinator's.
require(type(value) is dict and set(value) - {"signature"} == {"record"} and type(value["record"]) is dict,
f"application {noun} envelope is malformed")
record, signature = value["record"], value.get("signature")
require(signature not in (None, ""), f"application {noun} record is not signed")
# 64 bytes are 21 whole groups plus one byte: 85 characters, then one of the four that carry two bits, then "==".
require(type(signature) is str and SIGNATURE_TEXT.fullmatch(signature) is not None,
f"application {noun} signature is malformed")
try:
trusted_key = signed.load_trusted_key(pinned_key_der(pin["coordinator_public_key"]),
expected_spki_sha256=pin["coordinator_spki_sha256"])
return signed.verify_envelope(value, trusted_key, expected_kind=kind)
except signed.SignedRecordError as error:
reasons = {
"kind_mismatch": f"record is not a {kind} binder",
"schema_mismatch": "record schema differs",
"owner_invalid": "member owner is malformed",
"signature_invalid": "signature does not verify against the pinned key",
"signature_noncanonical": "signature does not verify against the pinned key",
}
reason = reasons.get(error.code, f"signed record rejected ({error.code})")
raise Invalid(f"application {noun} {reason}") from None
def signed_instant(value):
"""Whole seconds in UTC, the form the coordinator's signedAt() writes."""
try:
instant(value, "")
except Invalid:
return False
return True
# Each member of a signed record, by name, with the form its writer gives it. `pair` is not listed: it is
# the coordinator's published pair of the PR, whose form comes from a module outside the pinned inputs, so
# it is only ever compared (row against snapshot), never read.
RECEIPT_RUN_MEMBERS = {
"owner": positive_number, "owner_sha": commit_text, "snapshot_id": positive_number,
"request": positive_number, "repository": plain_text, "workflow": plain_text,
"dispatch_ref": plain_text, "workflow_run_id": positive_number, "workflow_sha": commit_text,
"ref": plain_text, "source": commit_text, "sequence": positive_number, "attempt": positive_number,
"owner_attempt": positive_number, "created_at": signed_instant,
}
SNAPSHOT_MEMBERS = {
"owner": positive_number, "owner_sha": commit_text, "ref": plain_text, "source": commit_text,
"request": positive_number, "sequence": positive_number, "owner_attempt": positive_number,
"created_at": signed_instant,
}
def receipt_run_shape(record):
"""The signed row is exactly the members the coordinator writes, each of its form."""
require(set(record) == set(RECEIPT_RUN_FIELDS), "application receipt-run record fields differ from the schema")
require(record["schema"] == EVIDENCE_SCHEMA, "application receipt-run record schema differs")
for name, valid in RECEIPT_RUN_MEMBERS.items():
require(valid(record[name]), f"application receipt-run member {name} is malformed")
def snapshot_shape(record):
"""The members of the signed snapshot this binding reads; the rest of the observation is the App's."""
require(set(SNAPSHOT_REQUIRED) <= set(record) <= set(SNAPSHOT_REQUIRED) | set(SNAPSHOT_OPTIONAL),
"application snapshot record fields differ from the schema")
require(record["schema"] == EVIDENCE_SCHEMA, "application snapshot record schema differs")
for name, valid in SNAPSHOT_MEMBERS.items():
require(valid(record[name]), f"application snapshot member {name} is malformed")
release = record["payload"]
require(type(release) is dict and type(release.get("release_version")) is str
and type(release.get("manifest")) is dict and type(release["manifest"].get("sha256")) is str
and re.fullmatch(SHA, release["manifest"]["sha256"]) is not None,
"application snapshot member payload is malformed")
observed = record["observation"]
require(type(observed) is dict and type(observed.get("pr")) is dict
and positive_number(observed["pr"].get("number")) and commit_text(observed["pr"].get("merge")),
"application snapshot member observation is malformed")
# The receipt tag the coordinator created at the served source: its run (the owner) and its sequence.
tag = "dev-release/%d/receipt-%d-" % (record["owner"], record["sequence"])
require(re.fullmatch(tag + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
record["ref"]) is not None,
"application snapshot ref is not the receipt tag of its owner and sequence")
def owner_run(client, repo, owner, owner_sha):
"""The coordinator run the signed records name, bound to their commit and this repository."""
try:
found = client.api(f"repos/{repo}/actions/runs/{owner}")
except Pending:
raise Invalid("application coordinator owner run is missing") from None
require(type(found) is dict and type(found.get("id")) is int and found["id"] == owner
and found.get("head_sha") == owner_sha
and type(found.get("repository")) is dict and type(found["repository"].get("full_name")) is str
and found["repository"]["full_name"].lower() == repo.lower(),
"application coordinator owner run differs from the signed owner")
return found
def reporter_evidence(client, repo, policy, pin, receipt, event, pr, run):
"""Bind the provider run to this release through two signed App records from the deployment store."""
route = f"repos/{repo}/deployments?environment={EVIDENCE_ENVIRONMENT}&task={EVIDENCE_TASK}"
claims = []
for deployment in deployment_pages(client, route):
claimed = deployment_claim(deployment)
if claimed is not None:
claims.append((deployment, claimed[0], claimed[1]))
run_id = run["id"]
# The row is found by the run it names, never by a hash. Only a record the pinned key signed as a
# receipt-run counts. A record naming this run that is not one is ignored when a good row exists,
# and otherwise the first such record's own failure is the refusal.
rows, failure = [], None
for deployment, envelope, record in claims:
if type(record.get("workflow_run_id")) is int and record["workflow_run_id"] == run_id:
try:
rows.append((deployment, authenticate_record(envelope, RECEIPT_RUN_KIND, "receipt-run", pin)))
except Invalid as error:
failure = failure or error
if not rows:
raise failure or Invalid("missing signed application receipt-run binding")
# One run binds one receipt: a replay is the very same canonical record, anything else is reuse.
row = rows[0][1]
require(all(canonical(signed) == canonical(row) for _, signed in rows),
"application receipt run is bound more than once")
receipt_run_shape(row)
# The row against the provider run, field by field. Its ref (the receipt tag) and created_at (the
# coordinator's own signing clock) belong to the coordinator: they are bound to the snapshot below.
require(row["repository"].lower() == repo.lower(),
"application receipt-run repository differs from the provider run")
require(row["workflow"] == run["path"] == ".github/workflows/" + policy["workflow"],
"application receipt-run workflow differs from the provider run")
require(row["dispatch_ref"] == run["head_branch"] == REPORTER_BRANCH,
"application receipt-run dispatch ref differs from the provider run")
require(row["workflow_sha"] == run["head_sha"] == pin["commit"],
"application receipt-run workflow SHA differs from the provider run")
require(row["attempt"] == run["run_attempt"] == 1,
"application receipt-run attempt differs from the provider run")
# The snapshot is the deployment the row names, read by that ID.
snapshot_id = row["snapshot_id"]
try:
snapshot_deployment = client.api(f"repos/{repo}/deployments/{snapshot_id}")
except Pending:
raise Invalid("application snapshot deployment is missing") from None
require(type(snapshot_deployment) is dict and type(snapshot_deployment.get("id")) is int
and snapshot_deployment["id"] == snapshot_id,
"application snapshot deployment differs from the receipt-run")
claimed = deployment_claim(snapshot_deployment)
require(claimed is not None, "application snapshot deployment is not a coordinator observation")
snapshot = authenticate_record(claimed[0], SNAPSHOT_KIND, "snapshot", pin)
snapshot_shape(snapshot)
# The snapshot against this release: version, manifest, PR and the served source, which stays the
# development merge and never becomes the reporter commit.
release = snapshot["payload"]
require(release["release_version"] == receipt["release_version"],
"application snapshot release differs from the receipt")
require(release["manifest"]["sha256"] == event["manifest"]["sha256"],
"application snapshot manifest differs from the release")
observed = snapshot["observation"]["pr"]
require(observed["number"] == pr["number"], "application snapshot PR differs from the receipt")
require(observed["merge"] == pr["merge"], "application snapshot merge differs from the receipt")
require(snapshot["source"] == pr["merge"], "application snapshot source differs from the merge commit")
# The row against the snapshot: the coordinator writes both in one call, from the same values.
for name in ("owner", "owner_sha", "owner_attempt", "request", "source", "sequence", "ref"):
require(row[name] == snapshot[name], f"application receipt-run {name} differs from the signed snapshot")
require(canonical(row["pair"]) == canonical(snapshot["pair"]),
"application receipt-run pair differs from the signed snapshot")
# The receipt against the snapshot: its attempt is the coordinator's run, its sequence the snapshot's.
require(receipt["attempt"] == snapshot["owner"],
"application receipt attempt differs from the signed snapshot owner")
require(receipt["sequence"] == snapshot["sequence"],
"application receipt sequence differs from the signed snapshot")
# One snapshot is reported by one run: any other authentic row for it is reuse.
for deployment, envelope, record in claims:
if (type(record.get("snapshot_id")) is int and record["snapshot_id"] == snapshot_id
and record.get("workflow_run_id") != run_id):
try:
authenticate_record(envelope, RECEIPT_RUN_KIND, "receipt-run", pin)
except Invalid:
continue
raise Invalid("application snapshot is bound to another receipt run")
# Both signed records name one coordinator run: deployment SHA, owner SHA and the owner run's head agree.
for deployment, record in (*rows, (snapshot_deployment, snapshot)):
require(deployment.get("sha") == record["owner_sha"],
"application deployment SHA differs from the coordinator owner SHA")
owner = owner_run(client, repo, row["owner"], row["owner_sha"])
require(type(owner.get("run_attempt")) is int and owner["run_attempt"] == row["owner_attempt"],
"application coordinator owner attempt differs from the receipt-run")
def require_authenticated_dispatch_inputs(run):
"""dry_run == "false" and receipt_only == "true" need an authenticated record of this run's dispatch inputs.
None exists. They are inputs of the coordinator's workflow dispatch, which the coordinator sends and
keeps no signed record of (pinned coordinator, receipt dispatch and receipt-run row); the run API does
not return them (the retained manual-dispatch run record has no `inputs`); and the receipt contract
has no field for them. A value inferred from the workflow name, the event or a job's success would be
an invented claim, so until the producer records them for this run ID and attempt, no application
receipt can be verified under this profile. This is the last check, so every other one is exercised first.
"""
raise Invalid("application reporter dispatch inputs are not authenticated for this run")
def check_application_reporter(client, repo, policy, receipt, event, pr, actual, run):
"""Everything that replaces the reporting_run.head_sha == pr.merge rule for application."""
require(receipt["consumer"] == "application" and type(event) is dict,
"application reporter policy is only valid for application")
pin = application_reporter_policy(policy)
reporter_run(repo, policy, pin, actual, run)
reporter_source(client, repo, pin)
reporter_evidence(client, repo, policy, pin, receipt, event, pr, run)
# --- End application protected-main reporter --------------------------------
def identity(obj, *, facts_only=False, consumer=None, slot=None):
if type(obj) is dict and "legacy" in obj:
require(not facts_only and consumer == "offline" and slot == "previous",
"legacy identity is only valid for product offline.previous")
keys(obj, OFFLINE_LEGACY_PREVIOUS)
require(obj["legacy"] is True, "legacy identity flag must be true")
try:
version(obj["npm_version"])
except ValueError as error:
raise Invalid("malformed identity") from error
match(r"sha512-[A-Za-z0-9+/]{86}==", obj["npm_integrity"])
integrity = base64.b64decode(obj["npm_integrity"][7:], validate=True)
require(base64.b64encode(integrity).decode("ascii") == obj["npm_integrity"][7:],
"invalid npm integrity")
match(COMMIT, obj["git_head"])
match("sha256:" + SHA, obj["image_digest"])
require(all(obj[name] == value for name, value in OFFLINE_LEGACY_PREVIOUS.items()),
"legacy previous identity differs")
return
if type(obj) is dict and "provenance" in obj:
require(not facts_only and consumer == "data" and slot == "previous",
"bootstrap identity is only valid for product data.previous")
# Facts keys (including null values) and all other additions fail here.
keys(obj, (*DATA_BOOTSTRAP_PREVIOUS, "deployment_id_sha256"))
keys(obj["distributions"], DATA_BOOTSTRAP_PREVIOUS["distributions"])
require(all(obj[name] == value for name, value in DATA_BOOTSTRAP_PREVIOUS.items()),
"bootstrap previous identity differs")
# Match pineforge-data scripts/release_chain/receipts.py served() byte for byte.
deployment = {name: obj[name] for name in ("package", "version", "distributions")}
require(obj["deployment_id_sha256"] == sha256(canonical(deployment)),
"bootstrap deployment identity differs")
return
keys(obj, ("source", "image_digest", "facts_commit", "facts_sha256", "deployment_id_sha256"))
match(COMMIT, obj["source"])
match(COMMIT, obj["facts_commit"])
for name in ("facts_sha256", "deployment_id_sha256"):
match(SHA, obj[name])
if not facts_only or obj["image_digest"] is not None:
match("sha256:" + SHA, obj["image_digest"])
def validate_receipt(client, repo, receipt, event, policy, reporting_run):
facts_only = receipt.get("schema") == FACTS_SCHEMA
fields = {"facts"} if facts_only else {"event_id", "release_version"}
if not facts_only and "post_merge" in policy:
fields.add("post_merge")
keys(receipt, COMMON_FIELDS | fields)
require(receipt["schema"] in (PRODUCT_SCHEMA, FACTS_SCHEMA) and receipt["consumer"] in RECEIPT_ROLES, "invalid consumer receipt schema")
if APPLICATION_REPORTER in policy:
require(not facts_only and receipt["consumer"] == "application",
"application reporter policy is only valid for application")
if facts_only:
require(event is None and receipt["consumer"] in ("web", "license"), "unexpected facts-only receipt")
keys(receipt["facts"], ("commit", "sha256"))
match(COMMIT, receipt["facts"]["commit"])
match(SHA, receipt["facts"]["sha256"])
else:
require(receipt["event_id"] == event["event_id"] and receipt["release_version"] == event["release_version"], "receipt event differs")
positive(receipt["attempt"])
positive(receipt["sequence"])
require(receipt["state"] in STATES, "invalid receipt state")
match(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", receipt["timestamp"])
timestamp = dt.datetime.fromisoformat(receipt["timestamp"].replace("Z", "+00:00"))
require(timestamp <= dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=5), "receipt timestamp is in future")
require(reporting_run["path"] == ".github/workflows/" + policy["workflow"], "untrusted receipt workflow")
require(reporting_run["event"] in ("push", "workflow_dispatch", "workflow_run", "repository_dispatch"),
"receipt must come from the trusted consumer coordinator")
# A provenance-bearing or legacy identity must obey its temporary rule even
# before its evidence stage is required (including states that return early).
for name in ("preview", "deployed", "previous"):
if type(receipt[name]) is dict and ("provenance" in receipt[name] or "legacy" in receipt[name]):
identity(receipt[name], facts_only=facts_only, consumer=receipt["consumer"], slot=name)
# A public receipt never contains private URLs, names, job labels or raw deployment IDs.
public = {key: receipt[key] for key in ("schema", "consumer", "attempt", "sequence", "state", "timestamp")}
if facts_only:
public["facts"] = receipt["facts"]
else:
public.update(event_id=receipt["event_id"], release_version=receipt["release_version"])
state = receipt["state"]
postmerge = policy["e2e"]["workflow"] == "release-postmerge.yml"
if postmerge:
require(receipt["consumer"] == "hosted" and policy["ci"]["workflow"] == "release-pr.yml"
and policy["deploy"]["workflow"] == "release.yml", "unexpected postmerge consumer")
require(state != "ready", "postmerge policy does not accept ready state")
require((state == "verified") == (receipt["e2e"] is not None),
"postmerge E2E is required exactly in verified state")
public["evidence_sha256"] = sha256(canonical(receipt))
public["reporting_run_id"] = reporting_run["id"]
if state in ("pending", "failed", "superseded", "skipped_by_policy"):
require(state != "skipped_by_policy" or (not facts_only and event["prerelease"]), "consumer cannot skip by policy")
return public
pr = receipt["pr"]
keys(pr, ("number", "base", "base_sha", "head", "merge"))
positive(pr["number"])
match(COMMIT, pr["base_sha"])
match(COMMIT, pr["head"])
require(pr["base"] == policy["base"], "PR base differs from policy")
actual = client.api(f"repos/{repo}/pulls/{pr['number']}")
require(actual["base"]["ref"] == pr["base"] and actual["head"]["sha"] == pr["head"], "PR head or base moved")
require(actual["head"]["repo"]["full_name"].lower() == repo.lower(), "receipt refers to fork PR")
if not actual["merged"]:
require(actual["base"]["sha"] == pr["base_sha"], "PR base moved after candidate verification")
if state in ("pr_open", "testing", "ready") and pr["merge"] is not None:
match(COMMIT, pr["merge"])
require(actual["merged"] is True and actual["merge_commit_sha"] == pr["merge"], "PR is not the recorded merge")
public["pr"] = pr
if state in ("ready", "merged", "deploying", "verified"):
if SHARD_FIELD in policy["ci"]:
ci_run = check_shard_run(client, repo, receipt["ci"], policy["ci"], pr)
else:
ci_run = check_run(client, repo, receipt["ci"], policy["ci"], pr["head"])
if postmerge:
if state == "verified":
e2e_run = check_postmerge(client, repo, receipt["e2e"], policy, pr, actual, receipt["timestamp"])
elif policy["e2e"]["workflow"] == "release-coordinator.yml":
require(receipt["consumer"] == "hosted" and policy["ci"]["workflow"] == "release-pr.yml", "unexpected coordinator consumer")
e2e_run = check_coordinator(client, repo, receipt["e2e"], policy["e2e"], pr, receipt["ci"])
else: