lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/ci_github.py ADDED
@@ -0,0 +1,917 @@
1
+ # lean-pkg ci_github -- the `ci` block of a lower-tier receipt from a GitHub Actions run (proposal 0008)
2
+ """The additive `ci` key of `lower-receipt/1` (docs/formats.md, "The ci block"; proposal 0008): the
3
+ GitHub Actions run a receipt says it came from, every value from a variable the runner sets. A receipt with
4
+ `job_id: gha-<run_id>-<run_attempt>` and a `ci` block that passes level 1 is the job of the `github-actions`
5
+ scheduler (sites.GITHUB_ACTIONS) and can back `coverage.yaml` `compute`.
6
+
7
+ Level 1 (this module; offline, the default of `gate`, `coverage check`, `page` and `receipt check`) checks
8
+ that the block is consistent with itself, with the receipt and with the clone: every required key with its
9
+ type, the provider, the server (github.com only), `job_id == gha-<run_id>-<run_attempt>`, `head_sha ==
10
+ commit`, an allowed event (push, workflow_dispatch), a GitHub-hosted runner, `verify_log_sha256 ==
11
+ report_sha256` (gate's own report-log check binds the committed log to report_sha256), `workflow_ref` well
12
+ formed and of the same repository, and the workflow file at `workflow_sha` hashing to `workflow_file_sha256`
13
+ when that commit is in the clone (else a shown skip). Unknown keys inside the block are ignored.
14
+
15
+ A comparator receipt (`comparator-receipt/2`) written on a GitHub-hosted runner carries the same block (proposal
16
+ 0008, stage S5: comparator_receipt.github_actions_context), less `verify_log_sha256`: a comparator receipt has
17
+ no verify log, and gate binds each of its comparison logs through `configs[].log_sha256`. Its level 1 also
18
+ requires `host_policy == "GitHub Actions run <run_id> attempt <run_attempt>"` (what the runner records), and
19
+ refuses `verify_log_sha256` when present. With a block that passes, the comparator receipt backs its
20
+ `gha-<R>-<A>` job: the CI counterpart of a comparator receipt's Slurm claim, which backs only with its sacct
21
+ seal (coverage.slurm_job_of).
22
+
23
+ That is consistency only, the strength of a `slurm-<J>` receipt and as forgeable: every value is text the
24
+ author could write. Level 1 backs a compute job but never renders the GitHub Actions sentence on the page
25
+ (the scheduler's sentence_level is 2: a corroborated run).
26
+
27
+ Level 2 (`corroborate`; `receipt check --corroborate`, `page --corroborate`, `publish --dry-run --corroborate`;
28
+ stage S3) asks the public REST API of github.com: the attempt the receipt names (never the run's latest) is
29
+ completed and successful, on the receipt's commit, of the workflow file `ci.workflow_ref` names, of `ci.event`,
30
+ in the repository whose numeric id is `ci.repository_id` and the package's own; exactly one `lean-pkg-receipt`
31
+ annotation in its jobs, whose two hashes are the committed receipt and log bytes, written by a successful job
32
+ in the GitHub-hosted runner group; the workflow file at `ci.workflow_sha` hashes to `ci.workflow_file_sha256`
33
+ and calls lean-pkg's verify.yml at a 40-hex commit equal to `ci.job_workflow`, whose content SHA-256 is in the
34
+ shipped pin list (data/verify-workflow-pins.yaml). Every failed request fails closed and is named. The level is
35
+ computed at check time and never stored.
36
+
37
+ Level 3 (`attest`; `receipt check --attested`, `page --attested`; stage S4) checks the Sigstore bundle the job's
38
+ attestation step signed (actions/attest-build-provenance in verify.yml), committed beside the receipt under
39
+ `.lean-receipts/` and named by `ci.attestation`: the bundle is committed at the ref read, its in-toto statement's
40
+ subjects are exactly the committed receipt bytes and the redacted log (report_sha256), `gh attestation verify`
41
+ (an optional outside tool, as sacct is; no Sigstore dependency) verifies it with `--repo ci.repository
42
+ --signer-workflow lean-pkg/lean-pkg/.github/workflows/verify.yml --deny-self-hosted-runners` (offline with
43
+ `--custom-trusted-root FILE`), and the verified certificate names the `ci` block's repository (name and numeric
44
+ id), commit, run and attempt, the signer `ci.job_workflow` and a GitHub-hosted runner. It proves the run identity
45
+ level 2 proves, through a signature recorded in the public transparency log, so it holds after the run's records
46
+ expire. The bundle is the one committed corroboration record: it is signed. A failure fails closed and is named;
47
+ a missing gh fails under --attested (without the flag, `receipt check` shows the bundle as a skip).
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import base64
53
+ import hashlib
54
+ import json
55
+ import os
56
+ import pathlib
57
+ import re
58
+ import shutil
59
+ import subprocess
60
+ import tempfile
61
+ import urllib.error
62
+ import urllib.parse
63
+ import urllib.request
64
+
65
+ from . import core
66
+ from . import sites
67
+
68
+ KEY = "ci"
69
+ PROVIDER = "github-actions"
70
+ SERVER_URL = "https://github.com"
71
+ ALLOWED_EVENTS = ("push", "workflow_dispatch")
72
+ REQUIRED = ("provider", "server_url", "repository", "repository_id", "run_id", "run_attempt", "job", "event",
73
+ "head_sha", "workflow_ref", "workflow_sha", "workflow_file_sha256", "job_workflow", "runner",
74
+ "verify_log_sha256")
75
+ # a comparator receipt's block: the same keys less verify_log_sha256 (it has no verify log; gate binds its
76
+ # comparison logs through configs[].log_sha256)
77
+ COMPARATOR_REQUIRED = tuple(k for k in REQUIRED if k != "verify_log_sha256")
78
+ OPTIONAL = ("attestation",)
79
+ RUNNER_REQUIRED = ("environment", "os", "arch", "image", "image_version")
80
+ HOSTED = "github-hosted"
81
+ JOB_RE = sites.GITHUB_ACTIONS.job_re
82
+ HEX40 = re.compile(r"^[0-9a-f]{40}$")
83
+ HEX64 = re.compile(r"^[0-9a-f]{64}$")
84
+ REPOSITORY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$")
85
+ # OWNER/REPO/.github/workflows/FILE.yml@REF: GitHub reads workflows directly under .github/workflows/
86
+ WORKFLOW_REF_RE = re.compile(r"^(?P<repo>[^/\s]+/[^/\s]+)/(?P<path>\.github/workflows/[^/@\s]+\.ya?ml)@(?P<ref>\S+)$")
87
+ LEVEL1_NOTE = ("level 1, offline: consistent with itself, the commit and the committed log, as strong as a Slurm "
88
+ "receipt and as forgeable; it does not show that the run happened")
89
+ EVENT_WHY = ("a pull_request run is on a merge commit, not the receipt's commit; pull_request_target runs the base "
90
+ "branch's workflow with the pull request's code; other events are not accepted until a proposal says so")
91
+
92
+
93
+ def host_policy_of(run_id, attempt) -> str:
94
+ """The host_policy a comparator receipt written in a GitHub Actions run records (proposal 0008, S5)."""
95
+ return f"GitHub Actions run {run_id} attempt {attempt}"
96
+
97
+
98
+ def _pos_int(v, minimum: int = 1) -> bool:
99
+ return isinstance(v, int) and not isinstance(v, bool) and v >= minimum
100
+
101
+
102
+ def _line(v) -> bool:
103
+ return isinstance(v, str) and bool(v.strip()) and "\n" not in v
104
+
105
+
106
+ def _commit_in_clone(repo: pathlib.Path, sha: str) -> bool:
107
+ return core.git(repo, "cat-file", "-e", f"{sha}^{{commit}}").returncode == 0
108
+
109
+
110
+ def _root_file_at(repo: pathlib.Path, sha: str, path: str) -> bytes | None:
111
+ """Bytes of <sha>:<path>, the path relative to the repository root (a workflow file), or None."""
112
+ p = subprocess.run(["git", "-C", str(repo), "show", f"{sha}:{path}"], capture_output=True,
113
+ env=core.scrubbed_env())
114
+ return p.stdout if p.returncode == 0 else None
115
+
116
+
117
+ def level1(rec: dict, repo: pathlib.Path | None) -> tuple[list[str], tuple[str, str] | None]:
118
+ """(problems, workflow row) of the receipt's `ci` block at level 1. Problems are refusals, each naming its
119
+ key; the workflow row is ("pass" | "skip", detail) for the workflow-file rehash, or None when the keys it
120
+ needs are malformed (a problem says so). `repo`: the package checkout (None: the rehash is skipped)."""
121
+ ci = rec.get(KEY)
122
+ if not isinstance(ci, dict):
123
+ return [f"ci: must be a mapping (the GitHub Actions run block), got {type(ci).__name__}"], None
124
+ out: list[str] = []
125
+ comparator = rec.get("schema") in core.COMPARATOR_SCHEMAS
126
+ missing = [k for k in (COMPARATOR_REQUIRED if comparator else REQUIRED) if k not in ci]
127
+ if missing:
128
+ out.append(f"ci: missing required key(s) {', '.join(missing)}")
129
+ has = ci.__contains__
130
+ if has("provider") and ci["provider"] != PROVIDER:
131
+ out.append(f"ci.provider: must be {PROVIDER!r}, got {ci['provider']!r}")
132
+ if has("server_url") and ci["server_url"] != SERVER_URL:
133
+ out.append(f"ci.server_url: must be {SERVER_URL} (GitHub Enterprise Server is not accepted), "
134
+ f"got {ci['server_url']!r}")
135
+ repository = ci.get("repository")
136
+ repo_ok = isinstance(repository, str) and bool(REPOSITORY_RE.match(repository))
137
+ if has("repository") and not repo_ok:
138
+ out.append(f"ci.repository: must be OWNER/REPO, got {repository!r}")
139
+ if has("repository_id") and not _pos_int(ci["repository_id"]):
140
+ out.append(f"ci.repository_id: must be an integer > 0, got {ci['repository_id']!r}")
141
+ run_id, attempt = ci.get("run_id"), ci.get("run_attempt")
142
+ if has("run_id") and not _pos_int(run_id):
143
+ out.append(f"ci.run_id: must be an integer > 0, got {run_id!r}")
144
+ if has("run_attempt") and not _pos_int(attempt):
145
+ out.append(f"ci.run_attempt: must be an integer >= 1, got {attempt!r}")
146
+ if _pos_int(run_id) and _pos_int(attempt):
147
+ want = f"gha-{run_id}-{attempt}"
148
+ if rec.get("job_id") != want:
149
+ out.append(f"job_id: {rec.get('job_id')!r} is not {want} (gha-<ci.run_id>-<ci.run_attempt>)")
150
+ if comparator and rec.get("host_policy") != host_policy_of(run_id, attempt):
151
+ out.append(f"host_policy: {rec.get('host_policy')!r} is not {host_policy_of(run_id, attempt)!r} (what "
152
+ f"comparator-receipt records on a GitHub-hosted runner)")
153
+ if has("job") and not _line(ci["job"]):
154
+ out.append(f"ci.job: must be one non-empty line, got {ci['job']!r}")
155
+ if has("event") and ci["event"] not in ALLOWED_EVENTS:
156
+ out.append(f"ci.event: {ci['event']!r} is not accepted, only {' and '.join(ALLOWED_EVENTS)} ({EVENT_WHY})")
157
+ head = ci.get("head_sha")
158
+ if has("head_sha"):
159
+ if not (isinstance(head, str) and HEX40.match(head)):
160
+ out.append(f"ci.head_sha: must be 40 lowercase hex, got {head!r}")
161
+ elif head != rec.get("commit"):
162
+ out.append(f"ci.head_sha: {head[:12]} is not the receipt commit {str(rec.get('commit'))[:12]} "
163
+ f"(the run checked out another commit)")
164
+ m = WORKFLOW_REF_RE.match(ci["workflow_ref"]) if isinstance(ci.get("workflow_ref"), str) else None
165
+ if has("workflow_ref"):
166
+ if m is None:
167
+ out.append(f"ci.workflow_ref: must be OWNER/REPO/.github/workflows/FILE.yml@REF, got "
168
+ f"{ci['workflow_ref']!r}")
169
+ elif repo_ok and m["repo"] != repository:
170
+ out.append(f"ci.workflow_ref: names repository {m['repo']!r}, not ci.repository {repository!r}")
171
+ wsha, wfile = ci.get("workflow_sha"), ci.get("workflow_file_sha256")
172
+ if has("workflow_sha") and not (isinstance(wsha, str) and HEX40.match(wsha)):
173
+ out.append(f"ci.workflow_sha: must be 40 lowercase hex, got {wsha!r}")
174
+ if has("workflow_file_sha256") and not (isinstance(wfile, str) and HEX64.match(wfile)):
175
+ out.append(f"ci.workflow_file_sha256: must be 64 lowercase hex, got {wfile!r}")
176
+ jw = ci.get("job_workflow")
177
+ if jw is not None and not (isinstance(jw, str) and WORKFLOW_REF_RE.match(jw)):
178
+ out.append(f"ci.job_workflow: must be null or OWNER/REPO/.github/workflows/FILE.yml@REF, got {jw!r}")
179
+ if has("runner"):
180
+ out += _runner_problems(ci["runner"])
181
+ vlog = ci.get("verify_log_sha256")
182
+ if comparator and has("verify_log_sha256"):
183
+ out.append("ci.verify_log_sha256: a comparator receipt has no verify log (each comparison log is bound by "
184
+ "configs[].log_sha256); the key belongs to a lower-tier receipt's block")
185
+ elif has("verify_log_sha256"):
186
+ if not (isinstance(vlog, str) and HEX64.match(vlog)):
187
+ out.append(f"ci.verify_log_sha256: must be 64 lowercase hex, got {vlog!r}")
188
+ elif vlog != str(rec.get("report_sha256", "")).lower():
189
+ out.append(f"ci.verify_log_sha256: {vlog[:16]}... is not the receipt's report_sha256 "
190
+ f"{str(rec.get('report_sha256', ''))[:16]}... (the run hashed another log)")
191
+ if has("attestation"):
192
+ a = ci["attestation"]
193
+ if not (_line(a) and "/" not in a and "\\" not in a and a not in (".", "..") and len(a) <= 255):
194
+ out.append(f"ci.attestation: must be a file name (no '/'), got {a!r}")
195
+ row = None
196
+ if m is not None and isinstance(wsha, str) and HEX40.match(wsha) and isinstance(wfile, str) \
197
+ and HEX64.match(wfile):
198
+ row = _workflow_row(repo, m["path"], wsha, wfile, out)
199
+ return out, row
200
+
201
+
202
+ def _runner_problems(runner) -> list[str]:
203
+ if not isinstance(runner, dict):
204
+ return [f"ci.runner: must be a mapping with keys {', '.join(RUNNER_REQUIRED)}"]
205
+ out = []
206
+ missing = [k for k in RUNNER_REQUIRED if k not in runner]
207
+ if missing:
208
+ out.append(f"ci.runner: missing required key(s) {', '.join(missing)}")
209
+ if "environment" in runner and runner["environment"] != HOSTED:
210
+ out.append(f"ci.runner.environment: {runner['environment']!r}, not {HOSTED}: a self-hosted runner is the "
211
+ f"author's own machine, and its receipt is worth what `lean-pkg receipt local` writes; it backs "
212
+ f"no GitHub Actions job")
213
+ for k in ("os", "arch"):
214
+ if k in runner and not _line(runner[k]):
215
+ out.append(f"ci.runner.{k}: must be one non-empty line, got {runner[k]!r}")
216
+ for k in ("image", "image_version"):
217
+ if k in runner and runner[k] is not None and not _line(runner[k]):
218
+ out.append(f"ci.runner.{k}: must be one line of text or null, got {runner[k]!r}")
219
+ return out
220
+
221
+
222
+ def _workflow_row(repo, path: str, wsha: str, want: str, out: list[str]) -> tuple[str, str] | None:
223
+ if repo is None:
224
+ return "skip", f"workflow file {path} at {wsha[:12]} not rehashed: no checkout"
225
+ if not _commit_in_clone(repo, wsha):
226
+ return "skip", (f"workflow file {path} not rehashed: commit {wsha[:12]} (ci.workflow_sha) is not in this "
227
+ f"clone (fetch it to check; a shallow clone lacks it)")
228
+ raw = _root_file_at(repo, wsha, path)
229
+ if raw is None:
230
+ out.append(f"ci.workflow_file_sha256: {path} does not exist at {wsha[:12]} (ci.workflow_sha)")
231
+ return None
232
+ got = hashlib.sha256(raw).hexdigest()
233
+ if got != want:
234
+ out.append(f"ci.workflow_file_sha256: {path} at {wsha[:12]} hashes to {got[:16]}..., the block says "
235
+ f"{want[:16]}...")
236
+ return None
237
+ return "pass", f"workflow file {path} at {wsha[:12]} hashes to ci.workflow_file_sha256 {want[:12]}"
238
+
239
+
240
+ def summary(rec: dict) -> str:
241
+ """One line naming the run a valid block describes (level1 found no problem)."""
242
+ ci = rec[KEY]
243
+ logs = ("host_policy" if rec.get("schema") in core.COMPARATOR_SCHEMAS
244
+ else "verify_log_sha256 = report_sha256")
245
+ return (f"GitHub Actions run {ci['run_id']} attempt {ci['run_attempt']} of {ci['repository']} (event "
246
+ f"{ci['event']}, job {ci['job']}, {ci['runner']['environment']} runner): head_sha = commit, job_id, "
247
+ f"{logs}, server and provider consistent; {LEVEL1_NOTE}")
248
+
249
+
250
+ def check_lines(rec: dict, repo: pathlib.Path | None) -> list[str]:
251
+ """gate's check lines for the block (validate_receipt already refused an invalid one), or the note that
252
+ a gha- receipt without it backs no compute job."""
253
+ if KEY not in rec:
254
+ job = rec.get("job_id")
255
+ if isinstance(job, str) and JOB_RE.match(job):
256
+ return [f"· job_id {job} has no ci block: the receipt gates, but backs no GitHub Actions compute job"]
257
+ return []
258
+ problems, row = level1(rec, repo)
259
+ if problems:
260
+ return []
261
+ lines = [f"✓ ci: {summary(rec)}"]
262
+ if row is not None:
263
+ lines.append(("✓ ci: " if row[0] == "pass" else "· ci: ") + row[1])
264
+ return lines
265
+
266
+
267
+ # --------------------------------------------------------------------------
268
+ # the github-actions scheduler's reader (coverage.JOB_INDEX) and its near misses
269
+
270
+ def gha_job_of(rec: dict, repo: pathlib.Path | None) -> str | None:
271
+ """The receipt's GitHub Actions job `gha-<R>-<A>`, or None: a lower-tier or comparator receipt with that
272
+ job_id whose `ci` block passes level 1 (for a comparator receipt the block is what makes its claim, as an
273
+ sacct seal makes a Slurm one). A gha- job_id without the block, or with a failing one, shows no run."""
274
+ job = rec.get("job_id")
275
+ if not (isinstance(job, str) and JOB_RE.match(job) and KEY in rec):
276
+ return None
277
+ return job if not level1(rec, repo)[0] else None
278
+
279
+
280
+ def jobs_at_head(repo: pathlib.Path) -> dict[str, str]:
281
+ """{gha-<R>-<A>: receipt path} for every receipt tracked at HEAD that shows a GitHub Actions run. The verify
282
+ and comparator jobs of one verify.yml run share gha-<R>-<A>: the lower-tier receipt is named first, since
283
+ corroboration (level 2) reads its annotation; a comparator receipt is named only for a job no lower-tier
284
+ receipt shows."""
285
+ from . import coverage as cov
286
+ out: dict[str, str] = {}
287
+ comparator: dict[str, str] = {}
288
+ for rel in cov.tracked_receipts(repo):
289
+ rec, _raw = cov.receipt_at_head(repo, rel)
290
+ job = gha_job_of(rec, repo) if rec else None
291
+ if job:
292
+ (comparator if rec.get("schema") in core.COMPARATOR_SCHEMAS else out).setdefault(job, rel)
293
+ for job, rel in comparator.items():
294
+ out.setdefault(job, rel)
295
+ return out
296
+
297
+
298
+ def near_misses(repo: pathlib.Path, missing: list[str]) -> str:
299
+ """The refusal's hint for listed gha- jobs no receipt backs: a receipt at HEAD with that job_id but no
300
+ `ci` block, or one whose block fails level 1, named with the reason."""
301
+ from . import coverage as cov
302
+ hints: dict[str, str] = {}
303
+ for rel in cov.tracked_receipts(repo):
304
+ rec, _raw = cov.receipt_at_head(repo, rel)
305
+ job = rec.get("job_id") if rec else None
306
+ if job not in missing or job in hints:
307
+ continue
308
+ if KEY not in rec:
309
+ hints[job] = (f"; {rel} has job_id {job} but no ci block, so it backs no GitHub Actions job (the block "
310
+ f"names the run: docs/formats.md)")
311
+ else:
312
+ problems = level1(rec, repo)[0]
313
+ hints[job] = f"; {rel} has job_id {job} but its ci block fails: {'; '.join(problems)}"
314
+ return "".join(hints[j] for j in missing if j in hints)
315
+
316
+
317
+ # --------------------------------------------------------------------------
318
+ # level 2: corroboration against the public run API (proposal 0008, stage S3)
319
+ #
320
+ # The REST API fields read here (an assumption until a live run; the tests use recorded, scrubbed shapes):
321
+ # GET /repos/{repository}/actions/runs/{run_id}/attempts/{run_attempt}: id, run_attempt, status, conclusion,
322
+ # head_sha, path (".github/workflows/F.yml", "@ref" appended in some answers), event, repository.id
323
+ # GET /repos/{owner}/{repo}: id (only for a package repository named apart from ci.repository)
324
+ # GET /repos/{repository}/actions/runs/{run_id}/attempts/{run_attempt}/jobs?per_page=100&page=N:
325
+ # total_count, jobs[].id, name, status, conclusion, runner_group_name, labels
326
+ # GET /repos/{repository}/check-runs/{job id}/annotations?per_page=100&page=N: [].title, [].message
327
+ # (an Actions job's id is its check run's id)
328
+ # GET /repos/{owner}/{repo}/contents/{path}?ref={sha}: type, encoding ("base64"), content
329
+
330
+ API_URL = "https://api.github.com"
331
+ API_HOST = "api.github.com"
332
+ API_TIMEOUT = 30
333
+ API_MAX_BYTES = 8 << 20
334
+ API_MAX_REDIRECTS = 3
335
+ API_MAX_PAGES = 10
336
+ PER_PAGE = 100
337
+ TOKEN_ENVS = ("GH_TOKEN", "GITHUB_TOKEN")
338
+ VERIFY_REPOSITORY = "lean-pkg/lean-pkg"
339
+ VERIFY_PATH = ".github/workflows/verify.yml"
340
+ VERIFY_WORKFLOW = f"{VERIFY_REPOSITORY}/{VERIFY_PATH}"
341
+ ANNOTATION_TITLE = "lean-pkg-receipt"
342
+ ANNOTATION_RE = re.compile(r"^receipt_sha256=([0-9a-f]{64}) report_sha256=([0-9a-f]{64})$")
343
+ HOSTED_GROUP = "GitHub Actions" # the runner group of a job on a GitHub-hosted runner
344
+ PINS_FILE = "verify-workflow-pins.yaml"
345
+ PINS_SCHEMA = "lean-pkg-verify-workflow-pins/1"
346
+ LEVEL2_NOTE = ("level 2, corroborated by the public run API: a successful run of lean-pkg's pinned verify "
347
+ "workflow, in that repository (by numeric id), on that commit, on a GitHub-hosted runner, which "
348
+ "wrote exactly the committed receipt and log bytes; it says nothing once the run's records expire, "
349
+ "nor that build code in the same job did not lie")
350
+ RATE_HINT = ("set GH_TOKEN (or GITHUB_TOKEN) to a GitHub token to raise the API rate limit; it is sent only to "
351
+ "api.github.com and never printed or written")
352
+
353
+
354
+ class FetchError(Exception):
355
+ """A request that got no HTTP answer to judge: `kind` is "network" or "redirect"."""
356
+
357
+ def __init__(self, kind: str, detail: str) -> None:
358
+ super().__init__(detail)
359
+ self.kind = kind
360
+
361
+
362
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
363
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
364
+ return None # urllib raises the 3xx as an HTTPError; api_fetch decides where it may go
365
+
366
+
367
+ def _token(env) -> str | None:
368
+ for k in TOKEN_ENVS:
369
+ v = (env.get(k) or "").strip()
370
+ if v:
371
+ return v
372
+ return None
373
+
374
+
375
+ def _on_api(url: str) -> bool:
376
+ try:
377
+ u = urllib.parse.urlsplit(url)
378
+ port = u.port
379
+ except ValueError:
380
+ return False
381
+ return u.scheme == "https" and u.hostname == API_HOST and port in (None, 443) and not u.username
382
+
383
+
384
+ def _read_capped(stream) -> bytes:
385
+ buf = bytearray()
386
+ while True:
387
+ chunk = stream.read(min(1 << 16, API_MAX_BYTES + 1 - len(buf)))
388
+ if not chunk:
389
+ return bytes(buf)
390
+ buf += chunk
391
+ if len(buf) > API_MAX_BYTES:
392
+ raise FetchError("network", f"an answer larger than {API_MAX_BYTES} bytes; refused")
393
+
394
+
395
+ def api_fetch(env=None, opener=None):
396
+ """The real fetch: fetch(path) -> (HTTP status, body bytes) of GET https://api.github.com<path>. https and
397
+ api.github.com only: a redirect (a renamed repository) is followed only while it stays there; one elsewhere
398
+ raises FetchError("redirect") before anything is sent to it, so the token cannot follow. A timeout and a
399
+ body cap; anything without an HTTP answer raises FetchError("network"). The token (GH_TOKEN, else
400
+ GITHUB_TOKEN) only raises the rate limit: it is sent only in the Authorization header and never printed,
401
+ logged or written (no message here names its value). opener: for tests (urllib's OpenerDirector shape)."""
402
+ from . import __version__
403
+ token = _token(os.environ if env is None else env)
404
+ op = opener or urllib.request.build_opener(_NoRedirect)
405
+
406
+ def fetch(path: str) -> tuple[int, bytes]:
407
+ url = API_URL + path
408
+ for _hop in range(API_MAX_REDIRECTS + 1):
409
+ if not _on_api(url):
410
+ host = urllib.parse.urlsplit(url).hostname or "?"
411
+ raise FetchError("redirect", f"the API redirected to {host}, not {API_HOST}; refused before "
412
+ f"anything was sent there")
413
+ req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json",
414
+ "X-GitHub-Api-Version": "2022-11-28",
415
+ "User-Agent": f"lean-pkg/{__version__} (corroborate)"})
416
+ if token:
417
+ req.add_unredirected_header("Authorization", f"Bearer {token}")
418
+ try:
419
+ with op.open(req, timeout=API_TIMEOUT) as resp:
420
+ return int(resp.status), _read_capped(resp)
421
+ except urllib.error.HTTPError as e:
422
+ if e.code in (301, 302, 303, 307, 308):
423
+ loc = e.headers.get("Location") if e.headers is not None else None
424
+ if not loc:
425
+ raise FetchError("redirect", f"HTTP {e.code} without a Location; refused") from None
426
+ url = urllib.parse.urljoin(url, loc)
427
+ continue
428
+ try:
429
+ body = _read_capped(e)
430
+ except (OSError, FetchError):
431
+ body = b""
432
+ return int(e.code), body
433
+ except FetchError:
434
+ raise
435
+ except Exception as e: # URLError, socket timeouts, TLS and http.client errors
436
+ reason = getattr(e, "reason", None)
437
+ why = e.__class__.__name__ + (f": {reason.__class__.__name__}" if reason is not None else "")
438
+ raise FetchError("network", f"no answer from {API_HOST} ({why})") from None
439
+ raise FetchError("redirect", f"more than {API_MAX_REDIRECTS} redirects; refused")
440
+ return fetch
441
+
442
+
443
+ def pins() -> frozenset[str]:
444
+ """The content SHA-256 of every released verify.yml (data/verify-workflow-pins.yaml)."""
445
+ import yaml
446
+ path = pathlib.Path(__file__).resolve().parent / "data" / PINS_FILE
447
+ doc = yaml.safe_load(path.read_text())
448
+ if not (isinstance(doc, dict) and doc.get("schema") == PINS_SCHEMA and isinstance(doc.get("sha256"), list)):
449
+ raise core.Fail(f"{path}: not a {PINS_SCHEMA} list")
450
+ return frozenset(x for x in doc["sha256"] if isinstance(x, str) and HEX64.match(x))
451
+
452
+
453
+ class _Stop(Exception):
454
+ """A request failed and corroboration cannot go on; its failure row is already added."""
455
+
456
+
457
+ class _Rows:
458
+ def __init__(self, fetch) -> None:
459
+ self.items: list[dict] = []
460
+ self.fetch = fetch
461
+
462
+ def add(self, check: str, ok: bool, detail: str) -> bool:
463
+ self.items.append({"check": check, "verdict": "pass" if ok else "fail", "detail": detail})
464
+ return ok
465
+
466
+ def get(self, path: str, what: str):
467
+ """GET path as JSON, or add the failure row named for `what` and raise _Stop (fails closed)."""
468
+ try:
469
+ status, body = self.fetch(path)
470
+ except FetchError as e:
471
+ self.add("api", False, f"{what}: {e}: not corroborated" if e.kind == "redirect" else
472
+ f"{what}: network error, {e}: not corroborated (fails closed; nothing is assumed)")
473
+ raise _Stop() from None
474
+ if status == 404:
475
+ self.add("api", False, f"{what}: HTTP 404: deleted, expired or never there, or not public (a run's "
476
+ f"records are kept 90 days by default; level 2 is never claimed from memory)")
477
+ raise _Stop()
478
+ if status in (403, 429):
479
+ self.add("api", False, f"{what}: HTTP {status}: rate limited or forbidden; {RATE_HINT}")
480
+ raise _Stop()
481
+ if status != 200:
482
+ self.add("api", False, f"{what}: HTTP {status}: not corroborated")
483
+ raise _Stop()
484
+ try:
485
+ return json.loads(body)
486
+ except ValueError:
487
+ self.add("api", False, f"{what}: the API answer is not JSON; not corroborated")
488
+ raise _Stop() from None
489
+
490
+ def pages(self, path: str, key: str | None, what: str) -> list:
491
+ """Every item of a paged list (`key`: the list inside the answer; None: the answer is the list)."""
492
+ out: list = []
493
+ for page in range(1, API_MAX_PAGES + 1):
494
+ doc = self.get(f"{path}{'&' if '?' in path else '?'}per_page={PER_PAGE}&page={page}", what)
495
+ items = doc.get(key) if key is not None and isinstance(doc, dict) else doc
496
+ if not isinstance(items, list):
497
+ self.add("api", False, f"{what}: the API answer has no {key or 'list'}; not corroborated")
498
+ raise _Stop()
499
+ out += items
500
+ total = doc.get("total_count") if key is not None and isinstance(doc, dict) else None
501
+ if len(items) < PER_PAGE or (isinstance(total, int) and len(out) >= total):
502
+ return out
503
+ self.add("api", False, f"{what}: more than {API_MAX_PAGES} pages; not corroborated")
504
+ raise _Stop()
505
+
506
+ def content(self, repository: str, path: str, ref: str, what: str) -> bytes:
507
+ """The bytes of path at ref (contents API), or a failure row and _Stop."""
508
+ doc = self.get(f"/repos/{_q(repository)}/contents/{_q(path)}?ref={ref}", what)
509
+ if not (isinstance(doc, dict) and doc.get("type") == "file" and doc.get("encoding") == "base64"
510
+ and isinstance(doc.get("content"), str)):
511
+ self.add("api", False, f"{what}: not a file with base64 content in the API answer; not corroborated")
512
+ raise _Stop()
513
+ try:
514
+ return base64.b64decode(doc["content"])
515
+ except ValueError:
516
+ self.add("api", False, f"{what}: the content is not base64; not corroborated")
517
+ raise _Stop() from None
518
+
519
+
520
+ def _q(s: str) -> str:
521
+ return urllib.parse.quote(s, safe="/")
522
+
523
+
524
+ def verify_refs(text: bytes) -> tuple[list[str], str | None]:
525
+ """(the REF of every job-level `uses: lean-pkg/lean-pkg/.github/workflows/verify.yml@REF` of a caller
526
+ workflow, None), or ([], why the file cannot be read)."""
527
+ import yaml
528
+ try:
529
+ doc = yaml.safe_load(text.decode("utf-8"))
530
+ except (UnicodeDecodeError, yaml.YAMLError) as e:
531
+ return [], f"the workflow file is not YAML ({e.__class__.__name__})"
532
+ jobs = doc.get("jobs") if isinstance(doc, dict) else None
533
+ if not isinstance(jobs, dict):
534
+ return [], "the workflow file has no jobs mapping"
535
+ refs = []
536
+ for job in jobs.values():
537
+ uses = job.get("uses") if isinstance(job, dict) else None
538
+ if isinstance(uses, str) and uses.strip().startswith(VERIFY_WORKFLOW + "@"):
539
+ refs.append(uses.strip().split("@", 1)[1])
540
+ return refs, None
541
+
542
+
543
+ def _run_rows(rows: _Rows, run, rec: dict, wpath: str) -> int | None:
544
+ """The rows of the attempt's own fields; the run's repository id (None when absent)."""
545
+ ci = rec[KEY]
546
+ run_id, attempt, commit = ci["run_id"], ci["run_attempt"], rec["commit"]
547
+ if not isinstance(run, dict):
548
+ rows.add("run", False, "the API answer for the run is not an object")
549
+ raise _Stop()
550
+ same = run.get("id") == run_id and run.get("run_attempt") == attempt
551
+ rows.add("run", same, f"run {run_id} attempt {attempt} of {ci['repository']}" if same else
552
+ f"the API answered for run {run.get('id')!r} attempt {run.get('run_attempt')!r}, not run {run_id} "
553
+ f"attempt {attempt}")
554
+ st, cn, hs, ev = run.get("status"), run.get("conclusion"), run.get("head_sha"), run.get("event")
555
+ rows.add("run status", st == "completed", f"status {st!r}" + ("" if st == "completed" else
556
+ ", not completed: the attempt is not finished"))
557
+ rows.add("run conclusion", cn == "success",
558
+ f"conclusion {cn!r}" + ("" if cn == "success" else
559
+ " in this attempt, not success (a receipt names one attempt; another attempt "
560
+ "is another receipt)"))
561
+ rows.add("run commit", hs == commit, f"head_sha {str(hs)[:12]}" + (" = the receipt commit" if hs == commit else
562
+ f", not the receipt commit {commit[:12]}"))
563
+ rpath = str(run.get("path") or "").split("@", 1)[0]
564
+ rows.add("run workflow", rpath == wpath, f"path {rpath!r}" + (" = the file of ci.workflow_ref" if rpath == wpath
565
+ else f", not {wpath!r} (ci.workflow_ref)"))
566
+ rows.add("run event", ev == ci["event"], f"event {ev!r}" + (" = ci.event" if ev == ci["event"] else
567
+ f", not ci.event {ci['event']!r}"))
568
+ repo_obj = run.get("repository")
569
+ got = repo_obj.get("id") if isinstance(repo_obj, dict) else None
570
+ rows.add("run repository", got == ci["repository_id"],
571
+ f"repository id {got!r}" + (" = ci.repository_id" if got == ci["repository_id"] else
572
+ f", not ci.repository_id {ci['repository_id']} (another repository's "
573
+ f"run, a fork's included)"))
574
+ return got if isinstance(got, int) else None
575
+
576
+
577
+ def _package_row(rows: _Rows, ci: dict, got: int | None, expect_repo: str | None) -> None:
578
+ repository, rid = ci["repository"], ci["repository_id"]
579
+ if expect_repo is None or expect_repo.lower() == repository.lower():
580
+ how = "ci.repository" + ("" if expect_repo else ", no other named")
581
+ rows.add("package repository", got == rid, f"the package repository is {repository} ({how}), id {rid}"
582
+ + ("" if got == rid else f"; the run is in id {got!r}"))
583
+ return
584
+ doc = rows.get(f"/repos/{_q(expect_repo)}", f"repository {expect_repo}")
585
+ want = doc.get("id") if isinstance(doc, dict) else None
586
+ ok = isinstance(want, int) and got == want == rid
587
+ rows.add("package repository", ok,
588
+ f"the package repository {expect_repo} is id {want!r}" + (", the run's" if ok else
589
+ f"; the run is in id {got!r} ({repository}): "
590
+ f"a fork's or another repository's run does "
591
+ f"not back the package"))
592
+
593
+
594
+ def _annotation_rows(rows: _Rows, rec: dict, base: str, receipt_sha256: str) -> None:
595
+ ci = rec[KEY]
596
+ jobs = rows.pages(f"{base}/jobs", "jobs", f"the jobs of run {ci['run_id']} attempt {ci['run_attempt']}")
597
+ found: list[tuple[dict, dict]] = []
598
+ for job in jobs:
599
+ if not (isinstance(job, dict) and isinstance(job.get("id"), int) and not isinstance(job.get("id"), bool)):
600
+ continue
601
+ notes = rows.pages(f"/repos/{_q(ci['repository'])}/check-runs/{job['id']}/annotations", None,
602
+ f"the annotations of job {job['id']}")
603
+ found += [(job, a) for a in notes if isinstance(a, dict) and a.get("title") == ANNOTATION_TITLE]
604
+ if len(found) != 1:
605
+ rows.add("annotation", False,
606
+ f"no {ANNOTATION_TITLE} annotation in the attempt's jobs (`receipt ci` writes exactly one)"
607
+ if not found else
608
+ f"{len(found)} {ANNOTATION_TITLE} annotations (job(s) "
609
+ f"{', '.join(dict.fromkeys(str(j['id']) for j, _a in found))}); `receipt ci` writes exactly one, "
610
+ f"so another is build code imitating it")
611
+ rows.add("job", False, "no single job of the attempt carries the receipt annotation")
612
+ return
613
+ job, note = found[0]
614
+ m = ANNOTATION_RE.match(str(note.get("message") or "").strip())
615
+ if m is None:
616
+ rows.add("annotation", False, f"the {ANNOTATION_TITLE} annotation's message is not "
617
+ f"'receipt_sha256=<64 hex> report_sha256=<64 hex>'")
618
+ else:
619
+ want_log = str(rec.get("report_sha256", "")).lower()
620
+ bad = [x for x, b in ((f"the committed receipt hashes to {receipt_sha256[:12]} (its bytes changed after "
621
+ f"the run, or it is another receipt)", m[1] != receipt_sha256),
622
+ (f"the receipt's report_sha256 (the committed log) is {want_log[:12]}",
623
+ m[2] != want_log)) if b]
624
+ rows.add("annotation", not bad, f"job {job['id']} wrote receipt_sha256 {m[1][:12]} and report_sha256 "
625
+ f"{m[2][:12]}" + ("; ".join([""] + bad) if bad else
626
+ ": the committed receipt and log bytes"))
627
+ ok = job.get("status") == "completed" and job.get("conclusion") == "success"
628
+ rows.add("job", ok, f"job {job['id']} ({job.get('name')!r}): status {job.get('status')!r}, conclusion "
629
+ f"{job.get('conclusion')!r}" + ("" if ok else ", not a completed success"))
630
+ labels = job.get("labels") if isinstance(job.get("labels"), list) else []
631
+ hosted = job.get("runner_group_name") == HOSTED_GROUP and "self-hosted" not in labels
632
+ rows.add("runner", hosted, f"runner group {job.get('runner_group_name')!r}" + (
633
+ ": GitHub-hosted" if hosted else f", not {HOSTED_GROUP!r} or labelled self-hosted (a self-hosted runner "
634
+ f"is the author's own machine; its receipt is worth `receipt local`)"))
635
+
636
+
637
+ def _workflow_rows(rows: _Rows, ci: dict, wpath: str) -> None:
638
+ wsha, want = ci["workflow_sha"], ci["workflow_file_sha256"]
639
+ raw = rows.content(ci["repository"], wpath, wsha, f"{wpath} at {wsha[:12]}")
640
+ got = hashlib.sha256(raw).hexdigest()
641
+ rows.add("workflow file", got == want, f"{wpath} at {wsha[:12]} hashes to {got[:12]}" + (
642
+ " = ci.workflow_file_sha256" if got == want else f", not ci.workflow_file_sha256 {want[:12]}"))
643
+ refs, why = verify_refs(raw)
644
+ jw = ci.get("job_workflow")
645
+ jw_ref = jw.split("@", 1)[1] if isinstance(jw, str) and jw.startswith(VERIFY_WORKFLOW + "@") else None
646
+ if why or not refs:
647
+ rows.add("verify.yml call", False, why or f"{wpath} does not call {VERIFY_WORKFLOW}@<40-hex> (no job's "
648
+ f"uses: names it)")
649
+ return
650
+ if bad := [r for r in refs if not HEX40.match(r)]:
651
+ rows.add("verify.yml call", False, f"{wpath} calls {VERIFY_WORKFLOW}@{bad[0]}: a tag or branch can move; "
652
+ f"pin it to a full 40-hex commit")
653
+ return
654
+ if jw_ref is None or jw_ref not in refs:
655
+ rows.add("verify.yml call", False, f"ci.job_workflow {jw!r} is not {VERIFY_WORKFLOW}@<the commit {wpath} "
656
+ f"calls> (null: the job had no id-token: write)")
657
+ return
658
+ rows.add("verify.yml call", True, f"{wpath} calls {VERIFY_WORKFLOW}@{jw_ref[:12]} = ci.job_workflow")
659
+ vraw = rows.content(VERIFY_REPOSITORY, VERIFY_PATH, jw_ref, f"{VERIFY_WORKFLOW} at {jw_ref[:12]}")
660
+ vsha = hashlib.sha256(vraw).hexdigest()
661
+ listed = vsha in pins()
662
+ rows.add("verify.yml pin", listed, f"{VERIFY_PATH} at {jw_ref[:12]} hashes to {vsha[:12]}" + (
663
+ ", a released lean-pkg verify.yml (the shipped pin list)" if listed else
664
+ ", not in the shipped pin list (data/verify-workflow-pins.yaml): not a released lean-pkg verify.yml (a "
665
+ "fork's commit is served through the parent repository's path)"))
666
+
667
+
668
+ def corroborate(rec: dict, repo: pathlib.Path | None, *, fetch, receipt_sha256: str,
669
+ expect_repo: str | None = None) -> tuple[int, list[dict]]:
670
+ """(level, rows) of a receipt with a `ci` block: 2 when every check against the public run API holds, else 1
671
+ (a failure never lowers a receipt below level 1; 0 only when the block fails level 1 itself, which the
672
+ commands refuse before asking). rows: one {check, verdict pass|fail, detail} per level-2 check, in order. A
673
+ request that fails stops there with an `api` row naming why (404, 403/429 naming GH_TOKEN, a network error,
674
+ a redirect off api.github.com): it fails closed, never a pass.
675
+
676
+ receipt_sha256: SHA-256 of the committed receipt bytes (the annotation binds them). expect_repo: the
677
+ package's own repository OWNER/REPO (the registry's repository URL; `receipt check --github`); None takes
678
+ ci.repository. fetch(path) -> (status, body): api_fetch() or a test's recorded answers."""
679
+ rows = _Rows(fetch)
680
+ problems, _row = level1(rec, repo)
681
+ if problems:
682
+ rows.add("level 1", False, "; ".join(problems))
683
+ return 0, rows.items
684
+ ci = rec[KEY]
685
+ wpath = WORKFLOW_REF_RE.match(ci["workflow_ref"])["path"]
686
+ base = f"/repos/{_q(ci['repository'])}/actions/runs/{ci['run_id']}/attempts/{ci['run_attempt']}"
687
+ try:
688
+ run = rows.get(base, f"run {ci['run_id']} attempt {ci['run_attempt']} of {ci['repository']}")
689
+ got = _run_rows(rows, run, rec, wpath)
690
+ _package_row(rows, ci, got, expect_repo)
691
+ _annotation_rows(rows, rec, base, receipt_sha256)
692
+ _workflow_rows(rows, ci, wpath)
693
+ except _Stop:
694
+ pass
695
+ ok = bool(rows.items) and all(r["verdict"] == "pass" for r in rows.items)
696
+ return (2 if ok else 1), rows.items
697
+
698
+
699
+ def failures(rows: list[dict]) -> str:
700
+ """The failed rows, one clause each."""
701
+ return "; ".join(f"{r['check']}: {r['detail']}" for r in rows if r["verdict"] != "pass")
702
+
703
+
704
+ def run_link(ci: dict) -> str:
705
+ """A corroborated run as a Markdown link: [run R attempt A](https://github.com/OWNER/REPO/actions/runs/R/
706
+ attempts/A)."""
707
+ return (f"[run {ci['run_id']} attempt {ci['run_attempt']}]({SERVER_URL}/{ci['repository']}/actions/runs/"
708
+ f"{ci['run_id']}/attempts/{ci['run_attempt']})")
709
+
710
+
711
+ # --------------------------------------------------------------------------
712
+ # level 3: the committed Sigstore bundle, verified by `gh attestation verify` (proposal 0008, stage S4)
713
+ #
714
+ # The bundle is what actions/attest-build-provenance writes (its `bundle-path` output): a Sigstore bundle, JSON
715
+ # (one bundle, or a JSON Lines file of exactly one), whose dsseEnvelope.payload is the base64 in-toto statement
716
+ # with `subject: [{name, digest: {sha256}}]`. `gh attestation verify --format json` prints a list of results;
717
+ # the fields read here (an assumption until a live run, as for level 2) are
718
+ # verificationResult.signature.certificate.{sourceRepositoryURI, sourceRepositoryIdentifier,
719
+ # sourceRepositoryDigest, runInvocationURI, buildSignerURI, runnerEnvironment} and
720
+ # verificationResult.statement.subject.
721
+
722
+ BUNDLE_SUFFIX = ".sigstore.json"
723
+ GH_ATTEST_TIMEOUT = 300
724
+ MAX_BUNDLE_BYTES = 4 << 20
725
+ LEVEL3_NOTE = ("level 3, attested: the committed Sigstore bundle verifies (gh attestation verify) for the "
726
+ "committed receipt and log, signed in that repository (by numeric id), on that commit, in that run "
727
+ "and attempt, by lean-pkg's verify workflow on a GitHub-hosted runner, and recorded in the public "
728
+ "transparency log, so it holds after the run's records expire; it says nothing about the "
729
+ "mathematics, nor that build code in the same job did not lie")
730
+ GH_MISSING = ("gh (the GitHub CLI) is not on PATH: level 3 runs `gh attestation verify`, an optional outside tool "
731
+ "(https://cli.github.com)")
732
+
733
+
734
+ def bundle_name(commit: str, job_id: str) -> str:
735
+ """The bundle's file name beside the receipt: <commit12>-gha-<R>-<A>.sigstore.json."""
736
+ return f"{commit[:12]}-{job_id}{BUNDLE_SUFFIX}"
737
+
738
+
739
+ def bundle_subjects(raw: bytes) -> tuple[dict[str, str] | None, str | None]:
740
+ """({sha256: name} of the bundle's in-toto subjects, None), or (None, why it cannot be read). Read without
741
+ any cryptography: what the subjects are, not that they are signed (gh attestation verify decides that)."""
742
+ if len(raw) > MAX_BUNDLE_BYTES:
743
+ return None, f"larger than {MAX_BUNDLE_BYTES} bytes"
744
+ try:
745
+ text = raw.decode("utf-8")
746
+ try:
747
+ docs = [json.loads(text)]
748
+ except ValueError:
749
+ docs = [json.loads(x) for x in text.splitlines() if x.strip()]
750
+ if len(docs) != 1:
751
+ return None, f"{len(docs)} bundles in one file; exactly one is expected"
752
+ envelope = docs[0].get("dsseEnvelope") if isinstance(docs[0], dict) else None
753
+ if not (isinstance(envelope, dict) and isinstance(envelope.get("payload"), str)):
754
+ return None, "not a Sigstore bundle with a DSSE envelope (dsseEnvelope.payload)"
755
+ stmt = json.loads(base64.b64decode(envelope["payload"], validate=True))
756
+ except (UnicodeDecodeError, ValueError):
757
+ return None, "not a JSON Sigstore bundle, or its payload is not a base64 JSON statement"
758
+ subjects = stmt.get("subject") if isinstance(stmt, dict) else None
759
+ if not isinstance(subjects, list):
760
+ return None, "the statement has no subject list"
761
+ out: dict[str, str] = {}
762
+ for s in subjects:
763
+ d = s.get("digest") if isinstance(s, dict) else None
764
+ h = d.get("sha256") if isinstance(d, dict) else None
765
+ if not (isinstance(h, str) and HEX64.match(h)):
766
+ return None, "a subject without a sha256 digest"
767
+ out[h] = str(s.get("name") or "")
768
+ if len(out) != len(subjects):
769
+ return None, "two subjects with the same digest"
770
+ return out, None
771
+
772
+
773
+ def subject_problems(subjects: dict[str, str], receipt_sha256: str, report_sha256: str) -> list[str]:
774
+ """Why the subjects are not exactly the receipt and its redacted log; [] when they are."""
775
+ want = {receipt_sha256: "the receipt", report_sha256.lower(): "the redacted log"}
776
+ out = [f"no subject is {w}'s digest {h[:12]} (its bytes changed after the run, or it is another file)"
777
+ for h, w in want.items() if h not in subjects]
778
+ extra = [h for h in subjects if h not in want]
779
+ if extra:
780
+ out.append(f"{len(extra)} other subject(s) ({', '.join(h[:12] for h in extra)}): the bundle signs other "
781
+ f"bytes too")
782
+ return out
783
+
784
+
785
+ def _gh_results(stdout: str) -> list[dict] | None:
786
+ try:
787
+ doc = json.loads(stdout)
788
+ except ValueError:
789
+ return None
790
+ if isinstance(doc, dict):
791
+ doc = [doc]
792
+ return [d for d in doc if isinstance(d, dict)] if isinstance(doc, list) else None
793
+
794
+
795
+ def _dig(d, *keys):
796
+ for k in keys:
797
+ d = d.get(k) if isinstance(d, dict) else None
798
+ return d
799
+
800
+
801
+ def _certificate_rows(rows: _Rows, rec: dict, results: list[dict], receipt_sha256: str) -> None:
802
+ ci = rec[KEY]
803
+ mine = [r for r in results if receipt_sha256 in
804
+ {_dig(s, "digest", "sha256") for s in (_dig(r, "verificationResult", "statement", "subject") or [])
805
+ if isinstance(s, dict)}]
806
+ cert = _dig(mine[0], "verificationResult", "signature", "certificate") if mine else None
807
+ if not isinstance(cert, dict):
808
+ rows.add("certificate", False, "gh attestation verify printed no verified statement with a certificate "
809
+ "naming the receipt's digest; not attested")
810
+ return
811
+ repo_uri = f"{SERVER_URL}/{ci['repository']}"
812
+ got_uri, got_id = cert.get("sourceRepositoryURI"), cert.get("sourceRepositoryIdentifier")
813
+ ok = isinstance(got_uri, str) and got_uri.lower() == repo_uri.lower() and str(got_id) == str(ci["repository_id"])
814
+ rows.add("certificate repository", ok, f"source repository {got_uri!r} id {got_id!r}" + (
815
+ " = ci.repository and ci.repository_id" if ok else
816
+ f", not {repo_uri} id {ci['repository_id']} (another repository's run, a fork's included)"))
817
+ dig = cert.get("sourceRepositoryDigest")
818
+ rows.add("certificate commit", dig == rec["commit"], f"source commit {str(dig)[:12]}" + (
819
+ " = the receipt commit" if dig == rec["commit"] else f", not the receipt commit {rec['commit'][:12]}"))
820
+ run_uri = f"{repo_uri}/actions/runs/{ci['run_id']}/attempts/{ci['run_attempt']}"
821
+ got_run = cert.get("runInvocationURI")
822
+ ok = isinstance(got_run, str) and got_run.lower() == run_uri.lower()
823
+ rows.add("certificate run", ok, f"run {got_run!r}" + (" = ci.run_id and ci.run_attempt" if ok else
824
+ f", not {run_uri} (another run or attempt)"))
825
+ jw = ci.get("job_workflow")
826
+ want = f"{SERVER_URL}/{jw}" if isinstance(jw, str) and jw.startswith(VERIFY_WORKFLOW + "@") else None
827
+ signer = cert.get("buildSignerURI")
828
+ ok = want is not None and signer == want
829
+ rows.add("certificate signer", ok, f"signer {signer!r}" + (
830
+ " = ci.job_workflow, lean-pkg's verify workflow" if ok else
831
+ f", not {want}" if want else f", and ci.job_workflow {jw!r} is not {VERIFY_WORKFLOW}@<ref>"))
832
+ renv = cert.get("runnerEnvironment")
833
+ rows.add("certificate runner", renv == HOSTED, f"runner environment {renv!r}" + (
834
+ "" if renv == HOSTED else f", not {HOSTED} (a self-hosted runner is the author's own machine)"))
835
+
836
+
837
+ def attest(rec: dict, repo: pathlib.Path | None, *, receipt_bytes: bytes, bundle: bytes | None,
838
+ expect_repo: str | None = None, trusted_root: str | None = None) -> tuple[bool, list[dict]]:
839
+ """(attested, rows) of a receipt with a `ci` block: level 3. bundle: the bytes of
840
+ `.lean-receipts/<ci.attestation>` committed at the ref read (None: not committed). rows: one {check, verdict,
841
+ detail} per check, in order; attested only when every row passes. Runs `gh attestation verify` (from PATH) on
842
+ copies of the committed bytes in a private temporary directory; only the tail of a failure's message is kept.
843
+ expect_repo: the package's own repository OWNER/REPO (None: ci.repository). trusted_root: a Sigstore trusted
844
+ root file for an offline verification (gh's --custom-trusted-root)."""
845
+ rows = _Rows(None)
846
+ problems, _row = level1(rec, repo)
847
+ if problems:
848
+ rows.add("level 1", False, "; ".join(problems))
849
+ return False, rows.items
850
+ ci = rec[KEY]
851
+ name = ci.get("attestation")
852
+ if name is None:
853
+ rows.add("bundle", False, "the receipt has no ci.attestation: its run did not attest (level 3 needs the "
854
+ "Sigstore bundle lean-pkg's verify.yml signs, committed beside the receipt)")
855
+ return False, rows.items
856
+ if bundle is None:
857
+ rows.add("bundle", False, f".lean-receipts/{name} (ci.attestation) is not committed: collect it with "
858
+ f"`lean-pkg receipt ci --collect {ci['run_id']} --attempt {ci['run_attempt']}` and "
859
+ f"commit it beside the receipt")
860
+ return False, rows.items
861
+ rows.add("bundle", True, f".lean-receipts/{name} is committed ({len(bundle)} bytes, sha256 "
862
+ f"{hashlib.sha256(bundle).hexdigest()[:12]})")
863
+ receipt_sha256 = hashlib.sha256(receipt_bytes).hexdigest()
864
+ report = str(rec.get("report_sha256", ""))
865
+ subjects, why = bundle_subjects(bundle)
866
+ if subjects is None:
867
+ rows.add("bundle subjects", False, f"{name}: {why}")
868
+ return False, rows.items
869
+ bad = subject_problems(subjects, receipt_sha256, report)
870
+ rows.add("bundle subjects", not bad, "; ".join(bad) if bad else
871
+ f"the signed subjects are exactly the committed receipt ({receipt_sha256[:12]}) and log ({report[:12]})")
872
+ if expect_repo is not None and expect_repo.lower() != ci["repository"].lower():
873
+ rows.add("attestation repository", False, f"the package repository is {expect_repo}, but the run is in "
874
+ f"{ci['repository']} (ci.repository): a fork's or another repository's "
875
+ f"run does not back the package")
876
+ gh = shutil.which("gh")
877
+ if gh is None:
878
+ rows.add("verifier", False, GH_MISSING)
879
+ return False, rows.items
880
+ how = "offline, against the --trusted-root file" if trusted_root is not None else "online"
881
+ with tempfile.TemporaryDirectory(prefix="lean-pkg-attest-") as tmp:
882
+ rpath = pathlib.Path(tmp) / f"{rec['commit'][:12]}-{rec.get('job_id')}.json"
883
+ bpath = pathlib.Path(tmp) / name
884
+ rpath.write_bytes(receipt_bytes)
885
+ bpath.write_bytes(bundle)
886
+ argv = [gh, "attestation", "verify", str(rpath), "--bundle", str(bpath), "--repo", ci["repository"],
887
+ "--signer-workflow", VERIFY_WORKFLOW, "--deny-self-hosted-runners", "--format", "json"]
888
+ if trusted_root is not None:
889
+ argv += ["--custom-trusted-root", str(pathlib.Path(trusted_root).resolve())]
890
+ try:
891
+ p = subprocess.run(argv, capture_output=True, text=True, timeout=GH_ATTEST_TIMEOUT,
892
+ env=core.scrubbed_env(), cwd=tmp)
893
+ except (OSError, subprocess.TimeoutExpired) as e:
894
+ rows.add("verifier", False, f"gh attestation verify could not run ({e.__class__.__name__}); not attested")
895
+ return False, rows.items
896
+ if p.returncode != 0:
897
+ tail = " ".join((p.stderr or p.stdout or "").strip().splitlines()[-2:])[:300] or "no message"
898
+ rows.add("verifier", False, f"gh attestation verify ({how}) exited {p.returncode}: {tail}; not attested")
899
+ return False, rows.items
900
+ rows.add("verifier", True, f"gh attestation verify ({how}): the signature, the certificate chain and the "
901
+ f"transparency-log entry verify for the receipt, signer workflow {VERIFY_WORKFLOW}, "
902
+ f"no self-hosted runner")
903
+ results = _gh_results(p.stdout)
904
+ if not results:
905
+ rows.add("certificate", False, "gh attestation verify printed no JSON verification result; not attested")
906
+ else:
907
+ _certificate_rows(rows, rec, results, receipt_sha256)
908
+ return all(r["verdict"] == "pass" for r in rows.items), rows.items
909
+
910
+
911
+ def level_of(corroborated: int | None, attested: bool | None) -> int:
912
+ """The level a receipt reached under the flags given. corroborated: the level-2 answer (None: no
913
+ --corroborate); attested: the level-3 answer (None: no --attested). Level 3 needs the attestation and, under
914
+ --corroborate too, the API's answer; a failure never lowers a receipt below level 1."""
915
+ if attested and (corroborated is None or corroborated >= 2):
916
+ return 3
917
+ return 2 if corroborated is not None and corroborated >= 2 else 1