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/receipt_ci.py ADDED
@@ -0,0 +1,660 @@
1
+ # lean-pkg receipt ci -- a lower-tier receipt written inside a GitHub Actions job (proposal 0008, stage S2)
2
+ """`lean-pkg receipt ci --log PATH [--receipt-commit SHA] [--checker TEXT] [--repo DIR] [--redact REGEX]...
3
+ [--out PATH] [--attest] [--json]`: the CI-runner counterpart of `receipt slurm` and `receipt systemd`. Run as the last
4
+ step of a GitHub Actions job (lean-pkg's reusable `.github/workflows/verify.yml`), it turns the job's
5
+ self-sealed verify log into a lower-tier receipt through the shared pipeline (`receipt.produce`: the seal,
6
+ the log's fields, redaction, the public-safety scan), with `job_id: gha-<run_id>-<run_attempt>` and the
7
+ additive `ci` block (docs/formats.md, "The ci block") built from the variables the runner sets. It reads and
8
+ writes no registry and needs no token.
9
+
10
+ Refusals (exit 1, nothing written), before the shared pipeline's own: not in GitHub Actions
11
+ (`GITHUB_ACTIONS` is not `true`); a self-hosted runner (`RUNNER_ENVIRONMENT` other than `github-hosted`: the
12
+ author's own machine, worth what `receipt local` writes); a missing variable of REQUIRED_ENV; an event other
13
+ than push and workflow_dispatch; a server other than https://github.com; `--receipt-commit` other than
14
+ `GITHUB_SHA` (the default); a malformed run id, attempt, repository id, SHA or workflow ref; the workflow
15
+ file missing at `GITHUB_WORKFLOW_SHA` (a shallow clone without that commit is named); a `ci` block that would
16
+ fail level 1 (ci_github.level1, the check `gate` runs). Then every refusal `produce` has.
17
+
18
+ `job_workflow` is the `job_workflow_ref` claim of the job's OIDC token (proposal 0008, open question 10),
19
+ read only when the runner offers a token (`ACTIONS_ID_TOKEN_REQUEST_URL` and `_TOKEN` set: the job has
20
+ `id-token: write`), else null (level 1 accepts null; level 2 will not). The token is read to take that one
21
+ claim and is never printed, logged or written. A token request that fails refuses: a job given `id-token:
22
+ write` is lean-pkg's verify.yml, whose receipt without the claim could never be corroborated.
23
+
24
+ Built-in redactions, longest path first: the checkout (`<repo>`), `GITHUB_WORKSPACE`, `RUNNER_TEMP` and
25
+ `RUNNER_TOOL_CACHE` (as `<GITHUB_WORKSPACE>`, `<RUNNER_TEMP>`, `<RUNNER_TOOL_CACHE>`), `$HOME` and
26
+ `/home/runner` (`<HOME>`), `/run/user/N/`, then every --redact. A home path left after them (another
27
+ `/home/<x>`) is blocked by the public-safety scan.
28
+
29
+ After the receipt is written it prints exactly one workflow notice, the receipt-bytes binding that
30
+ corroboration (level 2, stage S3) reads:
31
+
32
+ ::notice title=lean-pkg-receipt::receipt_sha256=<64 hex> report_sha256=<64 hex>
33
+
34
+ (on stdout; on stderr under --json, where stdout carries the JSON document), and appends a short entry to
35
+ the job's step summary (`GITHUB_STEP_SUMMARY`).
36
+
37
+ `--attest` (stage S4; verify.yml passes it): the job attests, so the block records `ci.attestation`, the name
38
+ `<commit12>-gha-<R>-<A>.sigstore.json` of the Sigstore bundle verify.yml's next step
39
+ (actions/attest-build-provenance) signs over the receipt and its redacted log and copies beside them. Refused
40
+ when the job has no OIDC token (an attestation is signed with it).
41
+
42
+ `--collect RUN [--attempt N] [--repo DIR]` (on the author's machine): downloads the run's receipt artifact
43
+ with `gh run download` (the author's own `gh` login), checks it as `gate --check` does against the local
44
+ checkout (gate_mod.validate_receipt, which runs the `ci` block's level 1, and the redacted log against
45
+ report_sha256), and copies the receipt and its log into `.lean-receipts/`, and the bundle `ci.attestation`
46
+ names (refused when the artifact lacks it or its subjects are not exactly the receipt and the log; its
47
+ signature is checked by `receipt check --attested`). It never commits or pushes.
48
+
49
+ `--template`: prints the caller workflow a package commits (`uses: lean-pkg/lean-pkg/.github/workflows/
50
+ verify.yml@<40-hex>`, the commit of the installed lean-pkg when pip recorded one).
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import base64
56
+ import hashlib
57
+ import importlib.metadata as md
58
+ import json
59
+ import os
60
+ import pathlib
61
+ import re
62
+ import shutil
63
+ import subprocess
64
+ import sys
65
+ import tempfile
66
+ import urllib.error
67
+ import urllib.request
68
+
69
+ from . import ci_github, core, gate as gate_mod
70
+ from . import producer as pr
71
+ from . import receipt as rc
72
+
73
+ VERB = "receipt ci"
74
+ HOSTED = ci_github.HOSTED
75
+ REQUIRED_ENV = ("GITHUB_SERVER_URL", "GITHUB_REPOSITORY", "GITHUB_REPOSITORY_ID", "GITHUB_RUN_ID",
76
+ "GITHUB_RUN_ATTEMPT", "GITHUB_JOB", "GITHUB_EVENT_NAME", "GITHUB_SHA", "GITHUB_WORKFLOW_REF",
77
+ "GITHUB_WORKFLOW_SHA", "RUNNER_ENVIRONMENT", "RUNNER_OS", "RUNNER_ARCH")
78
+ # (variable, token): the runner's per-job directories a verify log prints; the checkout itself is <repo>
79
+ RUNNER_DIRS = (("GITHUB_WORKSPACE", "<GITHUB_WORKSPACE>"), ("RUNNER_TEMP", "<RUNNER_TEMP>"),
80
+ ("RUNNER_TOOL_CACHE", "<RUNNER_TOOL_CACHE>"))
81
+ RUNNER_HOME = "/home/runner"
82
+ OIDC_URL_ENV, OIDC_TOKEN_ENV = "ACTIONS_ID_TOKEN_REQUEST_URL", "ACTIONS_ID_TOKEN_REQUEST_TOKEN"
83
+ OIDC_AUDIENCE = "lean-pkg"
84
+ OIDC_TIMEOUT = 30
85
+ ANNOTATION_TITLE = "lean-pkg-receipt"
86
+ VERIFY_WORKFLOW = "lean-pkg/lean-pkg/.github/workflows/verify.yml"
87
+ ARTIFACT_PREFIX = "lean-pkg-receipt" # verify.yml uploads lean-pkg-receipt-<run_id>-<run_attempt>
88
+ GH_TIMEOUT = 300
89
+ MAX_RECEIPT_BYTES = 1 << 20
90
+ RECEIPT_NAME_RE = re.compile(r"^[0-9a-f]{12}-gha-[0-9]+-[0-9]+\.json$")
91
+ PIN_PLACEHOLDER = "<40-hex SHA of the lean-pkg release commit>"
92
+ _DIGITS = re.compile(r"^[1-9][0-9]{0,19}$")
93
+
94
+
95
+ # --------------------------------------------------------------------------
96
+ # the environment
97
+
98
+ def _env() -> dict:
99
+ return dict(os.environ)
100
+
101
+
102
+ def env_problems(env: dict) -> list[str]:
103
+ """The refusals of the job's environment, in the order the proposal lists them; [] when it is a
104
+ GitHub-hosted job of an allowed event on github.com."""
105
+ if env.get("GITHUB_ACTIONS") != "true":
106
+ return ["not in GitHub Actions (GITHUB_ACTIONS is not `true`): `receipt ci` runs as a step of a GitHub "
107
+ "Actions job; on your own machine use `lean-pkg receipt local`, or `receipt ci --collect RUN` "
108
+ "to fetch a run's receipt"]
109
+ out = []
110
+ renv = env.get("RUNNER_ENVIRONMENT")
111
+ if renv and renv != HOSTED:
112
+ out.append(f"RUNNER_ENVIRONMENT is {renv!r}, not {HOSTED}: a self-hosted runner is the author's own "
113
+ f"machine, and its receipt is worth what `lean-pkg receipt local` writes; use that instead")
114
+ missing = [k for k in REQUIRED_ENV if not (env.get(k) or "").strip()]
115
+ if missing:
116
+ out.append(f"missing runner variable(s) {', '.join(missing)}: the ci block takes every value from a "
117
+ f"variable the runner sets")
118
+ event = env.get("GITHUB_EVENT_NAME")
119
+ if event and event not in ci_github.ALLOWED_EVENTS:
120
+ out.append(f"event {event!r} is not accepted, only {' and '.join(ci_github.ALLOWED_EVENTS)} "
121
+ f"({ci_github.EVENT_WHY})")
122
+ server = env.get("GITHUB_SERVER_URL")
123
+ if server and server.rstrip("/") != ci_github.SERVER_URL:
124
+ out.append(f"GITHUB_SERVER_URL is {server!r}, not {ci_github.SERVER_URL}: GitHub Enterprise Server is not "
125
+ f"accepted")
126
+ for k in ("GITHUB_REPOSITORY_ID", "GITHUB_RUN_ID", "GITHUB_RUN_ATTEMPT"):
127
+ v = env.get(k)
128
+ if v and not _DIGITS.match(v):
129
+ out.append(f"{k} is {v!r}, not a positive integer")
130
+ for k in ("GITHUB_SHA", "GITHUB_WORKFLOW_SHA"):
131
+ v = env.get(k)
132
+ if v and not ci_github.HEX40.match(v):
133
+ out.append(f"{k} is {v!r}, not 40 lowercase hex")
134
+ repo = env.get("GITHUB_REPOSITORY")
135
+ if repo and not ci_github.REPOSITORY_RE.match(repo):
136
+ out.append(f"GITHUB_REPOSITORY is {repo!r}, not OWNER/REPO")
137
+ wref = env.get("GITHUB_WORKFLOW_REF")
138
+ if wref:
139
+ m = ci_github.WORKFLOW_REF_RE.match(wref)
140
+ if m is None:
141
+ out.append(f"GITHUB_WORKFLOW_REF is {wref!r}, not OWNER/REPO/.github/workflows/FILE.yml@REF")
142
+ elif repo and m["repo"] != repo:
143
+ out.append(f"GITHUB_WORKFLOW_REF names repository {m['repo']!r}, not GITHUB_REPOSITORY {repo!r}")
144
+ for k in ("GITHUB_JOB", "RUNNER_OS", "RUNNER_ARCH"):
145
+ v = env.get(k)
146
+ if v and "\n" in v:
147
+ out.append(f"{k} is not one line")
148
+ return out
149
+
150
+
151
+ def _opt(env: dict, key: str) -> str | None:
152
+ v = (env.get(key) or "").strip()
153
+ return v if v and "\n" not in v else None
154
+
155
+
156
+ def redactions(env: dict, repo: pathlib.Path) -> list[tuple[str, str]]:
157
+ """(regex, token) pairs, longest path first so a path inside another is replaced by its own token."""
158
+ pairs = [(os.path.abspath(repo), "<repo>"), (str(repo.resolve()), "<repo>")]
159
+ for key, token in RUNNER_DIRS:
160
+ v = _opt(env, key)
161
+ if v and v.startswith("/"):
162
+ pairs += [(os.path.abspath(v), token), (os.path.realpath(v), token)]
163
+ home = _opt(env, "HOME")
164
+ if home and home.startswith("/"):
165
+ pairs += [(os.path.abspath(home), "<HOME>"), (os.path.realpath(home), "<HOME>")]
166
+ pairs.append((RUNNER_HOME, "<HOME>"))
167
+ out, seen = [], set()
168
+ for path, token in sorted(pairs, key=lambda x: -len(x[0].rstrip("/"))):
169
+ path = path.rstrip("/")
170
+ if len(path) > 1 and path not in seen:
171
+ seen.add(path)
172
+ out.append((re.escape(path) + r"(?![A-Za-z0-9._-])", token))
173
+ out.append((r"/run/user/\d+/", "/run/user/<UID>/"))
174
+ return out
175
+
176
+
177
+ # --------------------------------------------------------------------------
178
+ # the OIDC claim (job_workflow)
179
+
180
+ def _request_token(url: str, bearer: str) -> bytes:
181
+ """GET the runner's OIDC token endpoint; the response body (JSON {"value": JWT})."""
182
+ req = urllib.request.Request(url, headers={"Authorization": f"Bearer {bearer}",
183
+ "Accept": "application/json; api-version=2.0"})
184
+ with urllib.request.urlopen(req, timeout=OIDC_TIMEOUT) as r: # noqa: S310 (https checked by the caller)
185
+ return r.read(1 << 20)
186
+
187
+
188
+ def job_workflow_claim(env: dict, fetch=None) -> tuple[str | None, str | None, str]:
189
+ """(job_workflow or None, refusal or None, check line). None with no refusal: the job has no
190
+ id-token: write. The token and the JWT never appear in what is returned."""
191
+ url, bearer = env.get(OIDC_URL_ENV), env.get(OIDC_TOKEN_ENV)
192
+ if not url or not bearer:
193
+ return None, None, ("· ci.job_workflow: null (the job has no id-token: write, so no OIDC token: level 1 "
194
+ "accepts it; corroboration needs lean-pkg's verify.yml, which has it)")
195
+ if not url.startswith("https://"):
196
+ return None, f"{OIDC_URL_ENV} is not an https URL; the OIDC token is not requested", ""
197
+ sep = "&" if "?" in url else "?"
198
+ try:
199
+ body = (fetch or _request_token)(f"{url}{sep}audience={OIDC_AUDIENCE}", bearer)
200
+ jwt = json.loads(body)["value"]
201
+ parts = jwt.split(".")
202
+ if len(parts) != 3:
203
+ raise ValueError("not a JWT")
204
+ payload = json.loads(base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4)))
205
+ claim = payload.get("job_workflow_ref")
206
+ except (OSError, urllib.error.URLError, ValueError, KeyError, TypeError, AttributeError) as e:
207
+ return None, (f"ci.job_workflow: the OIDC token request failed ({e.__class__.__name__}); the job has "
208
+ f"id-token: write, so the job_workflow_ref claim is expected (rerun the job)"), ""
209
+ if not (isinstance(claim, str) and ci_github.WORKFLOW_REF_RE.match(claim)):
210
+ return None, (f"ci.job_workflow: the OIDC token's job_workflow_ref claim is not "
211
+ f"OWNER/REPO/.github/workflows/FILE.yml@REF ({str(claim)[:120]!r})"), ""
212
+ return claim, None, f"✓ ci.job_workflow: {claim} (the OIDC token's job_workflow_ref claim; token not kept)"
213
+
214
+
215
+ # --------------------------------------------------------------------------
216
+ # the ci block
217
+
218
+ def ci_block(env: dict, workflow_sha256: str, verify_log_sha256: str, job_workflow: str | None) -> dict:
219
+ """The block in the key order of the proposal's table; every value from the runner's variables."""
220
+ return {
221
+ "provider": ci_github.PROVIDER,
222
+ "server_url": ci_github.SERVER_URL,
223
+ "repository": env["GITHUB_REPOSITORY"],
224
+ "repository_id": int(env["GITHUB_REPOSITORY_ID"]),
225
+ "run_id": int(env["GITHUB_RUN_ID"]),
226
+ "run_attempt": int(env["GITHUB_RUN_ATTEMPT"]),
227
+ "job": env["GITHUB_JOB"],
228
+ "event": env["GITHUB_EVENT_NAME"],
229
+ "head_sha": env["GITHUB_SHA"],
230
+ "workflow_ref": env["GITHUB_WORKFLOW_REF"],
231
+ "workflow_sha": env["GITHUB_WORKFLOW_SHA"],
232
+ "workflow_file_sha256": workflow_sha256,
233
+ "job_workflow": job_workflow,
234
+ "runner": {"environment": env["RUNNER_ENVIRONMENT"], "os": env["RUNNER_OS"], "arch": env["RUNNER_ARCH"],
235
+ "image": _opt(env, "ImageOS"), "image_version": _opt(env, "ImageVersion")},
236
+ "verify_log_sha256": verify_log_sha256,
237
+ }
238
+
239
+
240
+ def workflow_file(repo: pathlib.Path, env: dict) -> tuple[str | None, str | None]:
241
+ """(SHA-256 of the workflow file at GITHUB_WORKFLOW_SHA, refusal)."""
242
+ path = ci_github.WORKFLOW_REF_RE.match(env["GITHUB_WORKFLOW_REF"])["path"]
243
+ wsha = env["GITHUB_WORKFLOW_SHA"]
244
+ if not ci_github._commit_in_clone(repo, wsha):
245
+ return None, (f"the workflow file {path} cannot be read: commit {wsha[:12]} (GITHUB_WORKFLOW_SHA) is not in "
246
+ f"this clone; a shallow checkout lacks it (actions/checkout with fetch-depth: 0, or "
247
+ f"`git fetch --depth=1 origin {wsha}`)")
248
+ raw = ci_github._root_file_at(repo, wsha, path)
249
+ if raw is None:
250
+ return None, f"the workflow file {path} does not exist at {wsha[:12]} (GITHUB_WORKFLOW_SHA)"
251
+ return hashlib.sha256(raw).hexdigest(), None
252
+
253
+
254
+ def _refuse(args, refusals: list[str], checks: list[str], job_id: str | None) -> int:
255
+ if getattr(args, "json_out", False):
256
+ core.print_json({"ok": False, "receipt": None, "log": None, "report_sha256": None, "raw_log_sha256": None,
257
+ "sealed": [], "job_id": job_id, "seal": None, "log_commit_bound": None, "ci": None,
258
+ "annotation": None, "redactions": 0, "lines_redacted": 0, "checks": checks,
259
+ "readme_block": None, "readme_appended": False, "next": None, "refusals": refusals})
260
+ verdict = f"{VERB}: refused, {len(refusals)} problem(s); nothing written"
261
+ print(f"lean-pkg: {verdict}", file=sys.stderr)
262
+ for r in refusals:
263
+ print(f" ✗ {r}", file=sys.stderr)
264
+ print(f"lean-pkg: {verdict}", file=sys.stderr)
265
+ return 1
266
+
267
+
268
+ def annotation(receipt_sha: str, report_sha: str) -> str:
269
+ return f"::notice title={ANNOTATION_TITLE}::receipt_sha256={receipt_sha} report_sha256={report_sha}"
270
+
271
+
272
+ def step_summary(ci: dict, rel_receipt: str, receipt_sha: str, report_sha: str) -> str:
273
+ bundle = ci.get("attestation")
274
+ return "\n".join([
275
+ "### lean-pkg receipt",
276
+ "",
277
+ f"- Receipt: `{rel_receipt}` (job `gha-{ci['run_id']}-{ci['run_attempt']}`), SHA-256 `{receipt_sha}`",
278
+ f"- Redacted verify log SHA-256 `{report_sha}` (= `report_sha256`)",
279
+ f"- Commit `{ci['head_sha']}`, event `{ci['event']}`, {ci['runner']['environment']} runner",
280
+ *([f"- Attestation: the Sigstore bundle `{bundle}` (`ci.attestation`), signed by the next step"]
281
+ if bundle else []),
282
+ f"- Collect it: `lean-pkg receipt ci --collect {ci['run_id']} --attempt {ci['run_attempt']}`, then commit "
283
+ f"the {'three' if bundle else 'two'} files under `.lean-receipts/`",
284
+ "", ""])
285
+
286
+
287
+ def cmd_write(args) -> int:
288
+ env = _env()
289
+ repo = rc.repo_dir(args)
290
+ if args.log is None:
291
+ raise core.UsageError("receipt ci needs --log PATH (or --template, or --collect RUN)")
292
+ log = pathlib.Path(args.log).expanduser()
293
+ if not log.is_file():
294
+ raise core.UsageError(f"--log {args.log}: no such file")
295
+ paths = {"--log": log} # no --stdout: the log carries its own seal (verify.yml writes it)
296
+ extra = rc.common_usage(args)
297
+ refusals = env_problems(env)
298
+ checks: list[str] = []
299
+ if refusals:
300
+ return _refuse(args, refusals, checks, None)
301
+ sha = env["GITHUB_SHA"]
302
+ if args.commit_sha is None:
303
+ args.commit_sha = sha
304
+ elif args.commit_sha.strip().lower() != sha:
305
+ return _refuse(args, [f"--receipt-commit {args.commit_sha} is not GITHUB_SHA {sha}: the job checked out "
306
+ f"and ran on GITHUB_SHA (leave --receipt-commit out to use it)"], checks, None)
307
+ run_id, attempt = int(env["GITHUB_RUN_ID"]), int(env["GITHUB_RUN_ATTEMPT"])
308
+ job_id = f"gha-{run_id}-{attempt}"
309
+ checks.append(f"✓ runner: GitHub Actions run {run_id} attempt {attempt} of {env['GITHUB_REPOSITORY']} (event "
310
+ f"{env['GITHUB_EVENT_NAME']}, job {env['GITHUB_JOB']}, {HOSTED} {env['RUNNER_OS']} "
311
+ f"{env['RUNNER_ARCH']}); --receipt-commit = GITHUB_SHA")
312
+ wf_sha, why = workflow_file(repo, env)
313
+ if why:
314
+ refusals.append(why)
315
+ job_workflow, why, line = job_workflow_claim(env)
316
+ if why:
317
+ refusals.append(why)
318
+ elif line:
319
+ checks.append(line)
320
+ reds = redactions(env, repo)
321
+ raw_text = paths["--log"].read_bytes().decode("utf-8", errors="replace")
322
+ redacted, _n = rc.redact(raw_text, extra, reds) # the bytes produce writes: report_sha256 (same inputs)
323
+ report_sha = hashlib.sha256(redacted.encode("utf-8")).hexdigest()
324
+ ci = ci_block(env, wf_sha or "0" * 64, report_sha, job_workflow)
325
+ if getattr(args, "attest", False):
326
+ if job_workflow is None and not any(r.startswith("ci.job_workflow:") for r in refusals):
327
+ refusals.append("--attest: the job has no OIDC token (no id-token: write), so it cannot sign an "
328
+ "attestation; lean-pkg's verify.yml grants id-token: write and attestations: write")
329
+ ci["attestation"] = ci_github.bundle_name(sha, job_id)
330
+ checks.append(f"✓ ci.attestation: {ci['attestation']} (the Sigstore bundle the job's attestation step signs "
331
+ f"for this receipt and its log, to be committed beside them)")
332
+ if wf_sha is not None:
333
+ problems, row = ci_github.level1({"commit": sha, "job_id": job_id, "report_sha256": report_sha, "ci": ci},
334
+ repo)
335
+ refusals += problems
336
+ if not problems:
337
+ checks.append(f"✓ ci: level 1 holds ({ci_github.LEVEL1_NOTE})")
338
+ if row is not None:
339
+ checks.append(("✓ ci: " if row[0] == "pass" else "· ci: ") + row[1])
340
+
341
+ def lines(receipt_name: str, tar: str) -> list[str]:
342
+ r = ci["runner"]
343
+ image = f", image {r['image']} {r['image_version'] or ''}".rstrip() if r["image"] else ""
344
+ return [f"- Receipt: `{receipt_name}`. GitHub Actions run `{run_id}` attempt `{attempt}` of "
345
+ f"`{ci['repository']}` (event `{ci['event']}`, job `{ci['job']}`),",
346
+ f" {r['environment']} {r['os']} {r['arch']} runner{image}{tar}; workflow "
347
+ f"`{ci['workflow_ref']}`."]
348
+
349
+ def log_job_id(value: str) -> str | None:
350
+ if value != job_id:
351
+ return f"verify log: `job-id:` {value!r} is not this run's job id {job_id!r}"
352
+ return None
353
+
354
+ written_by = pr.receipt_producer(pr.fingerprint())
355
+ ev = rc.Evidence(verb=VERB, job_id=job_id, refusals=refusals, checks=checks, executor_lines=lines,
356
+ default_heading=f"lower-tier receipt, GitHub Actions run {run_id} attempt {attempt}",
357
+ check_log_job_id=log_job_id, json_extra={"ci": ci, "producer": written_by},
358
+ redactions=reds, redaction_note="runner paths redacted",
359
+ receipt_extra={"producer": written_by, "ci": ci})
360
+ code = rc.produce(args, ev, repo, paths, extra)
361
+ if code != 0:
362
+ return code
363
+ c12 = sha[:12]
364
+ out = (pathlib.Path(args.out).expanduser() if args.out
365
+ else repo / ".lean-receipts" / f"{c12}-{gate_mod.receipt_job_slug(job_id)}.json")
366
+ receipt_bytes = out.read_bytes()
367
+ written = json.loads(receipt_bytes)
368
+ if written.get("report_sha256") != report_sha: # an internal invariant: produce hashed other bytes
369
+ raise core.Fail(f"{VERB}: internal error: the written report_sha256 is not the one ci.verify_log_sha256 "
370
+ f"names; remove {out.name} and report this")
371
+ receipt_sha = hashlib.sha256(receipt_bytes).hexdigest()
372
+ note = annotation(receipt_sha, report_sha)
373
+ print(note, file=sys.stderr if getattr(args, "json_out", False) else sys.stdout)
374
+ summary_path = env.get("GITHUB_STEP_SUMMARY")
375
+ if summary_path:
376
+ try:
377
+ with open(summary_path, "a", encoding="utf-8") as f:
378
+ f.write(step_summary(ci, rc._shown(out, repo), receipt_sha, report_sha))
379
+ except OSError as e:
380
+ print(f"lean-pkg: WARN the step summary could not be written ({e.__class__.__name__}); the receipt "
381
+ f"is written", file=sys.stderr)
382
+ return 0
383
+
384
+
385
+ # --------------------------------------------------------------------------
386
+ # --collect
387
+
388
+ def _collect_refuse(args, refusals: list[str], checks: list[str], extra: dict) -> int:
389
+ if getattr(args, "json_out", False):
390
+ core.print_json({"ok": False, **extra, "copied": [], "checks": checks, "refusals": refusals})
391
+ verdict = f"{VERB} --collect: refused, {len(refusals)} problem(s); nothing copied"
392
+ print(f"lean-pkg: {verdict}", file=sys.stderr)
393
+ for r in refusals:
394
+ print(f" ✗ {r}", file=sys.stderr)
395
+ print(f"lean-pkg: {verdict}", file=sys.stderr)
396
+ return 1
397
+
398
+
399
+ def _download(gh: str, repo: pathlib.Path, run: int, attempt: int | None, dest: pathlib.Path) -> str | None:
400
+ """`gh run download` of the run's receipt artifact into dest; the refusal, or None."""
401
+ if attempt is not None:
402
+ argv = [gh, "run", "download", str(run), "--name", f"{ARTIFACT_PREFIX}-{run}-{attempt}", "--dir", str(dest)]
403
+ else:
404
+ argv = [gh, "run", "download", str(run), "--pattern", f"{ARTIFACT_PREFIX}-{run}-*", "--dir", str(dest)]
405
+ try:
406
+ p = subprocess.run(argv, cwd=repo, capture_output=True, text=True, timeout=GH_TIMEOUT,
407
+ env=core.scrubbed_env())
408
+ except (OSError, subprocess.TimeoutExpired) as e:
409
+ return f"gh run download failed ({e.__class__.__name__})"
410
+ if p.returncode != 0:
411
+ tail = " ".join((p.stderr or p.stdout or "").strip().splitlines()[-2:])[:300] or "no message"
412
+ what = f"{ARTIFACT_PREFIX}-{run}-{attempt}" if attempt is not None else f"{ARTIFACT_PREFIX}-{run}-*"
413
+ return (f"artifact {what} of run {run} could not be downloaded (gh exit {p.returncode}: {tail}); is the "
414
+ f"run finished and green, retained, and of this repository?")
415
+ return None
416
+
417
+
418
+ def _artifact_files(root: pathlib.Path, attempt: int | None) -> tuple[pathlib.Path | None, str | None]:
419
+ """The directory holding the artifact's files: root itself (--attempt: one artifact by name) or its one
420
+ subdirectory (a pattern download puts each artifact in its own)."""
421
+ if attempt is not None:
422
+ return root, None
423
+ subs = sorted(p for p in root.iterdir() if p.is_dir() and not p.is_symlink())
424
+ if not subs:
425
+ return None, "the run has no lean-pkg receipt artifact (lean-pkg-receipt-<run>-<attempt>)"
426
+ if len(subs) > 1:
427
+ return None, (f"the run has {len(subs)} receipt artifacts ({', '.join(p.name for p in subs)}), one per "
428
+ f"attempt; name one with --attempt N")
429
+ return subs[0], None
430
+
431
+
432
+ def cmd_collect(args) -> int:
433
+ from . import receipt_check
434
+ run = args.collect
435
+ attempt = args.attempt
436
+ repo = rc.repo_dir(args)
437
+ base = {"run_id": run, "attempt": attempt, "receipt": None, "log": None}
438
+ checks: list[str] = []
439
+ rdir = repo / ".lean-receipts"
440
+ if rdir.is_symlink():
441
+ return _collect_refuse(args, [".lean-receipts/ is a symlink; nothing copied"], checks, base)
442
+ gh = shutil.which("gh")
443
+ if gh is None:
444
+ return _collect_refuse(args, ["gh (the GitHub CLI) is not on PATH: install it and run `gh auth login`; "
445
+ "--collect downloads the artifact with your own login"], checks, base)
446
+ with tempfile.TemporaryDirectory(prefix="lean-pkg-collect-") as tmp:
447
+ root = pathlib.Path(tmp) / "dl"
448
+ root.mkdir()
449
+ why = _download(gh, repo, run, attempt, root)
450
+ if why:
451
+ return _collect_refuse(args, [why], checks, base)
452
+ adir, why = _artifact_files(root, attempt)
453
+ if why:
454
+ return _collect_refuse(args, [why], checks, base)
455
+ refusals: list[str] = []
456
+ entries = sorted(adir.iterdir())
457
+ odd = [p.name for p in entries if p.is_symlink() or not p.is_file()]
458
+ if odd:
459
+ refusals.append(f"the artifact holds entries that are not regular files: {', '.join(odd[:5])}")
460
+ receipts = [p for p in entries if p.is_file() and not p.is_symlink() and RECEIPT_NAME_RE.match(p.name)]
461
+ if len(receipts) != 1:
462
+ refusals.append(f"the artifact holds {len(receipts)} receipt(s) named <commit12>-gha-<run>-<attempt>"
463
+ f".json; exactly one is expected")
464
+ if refusals:
465
+ return _collect_refuse(args, refusals, checks, base)
466
+ rpath = receipts[0]
467
+ raw = rpath.read_bytes()
468
+ try:
469
+ if len(raw) > MAX_RECEIPT_BYTES:
470
+ raise ValueError("too large")
471
+ rec = json.loads(raw)
472
+ if not isinstance(rec, dict):
473
+ raise ValueError("not an object")
474
+ except (ValueError, UnicodeDecodeError) as e:
475
+ return _collect_refuse(args, [f"{rpath.name}: not a JSON receipt ({e.__class__.__name__})"], checks,
476
+ base)
477
+ base["receipt"] = f".lean-receipts/{rpath.name}"
478
+ ci = rec.get("ci") if isinstance(rec.get("ci"), dict) else {}
479
+ if ci.get("run_id") != run:
480
+ refusals.append(f"{rpath.name}: ci.run_id is {ci.get('run_id')!r}, not RUN {run}: the artifact is not "
481
+ f"this run's receipt")
482
+ if attempt is not None and ci.get("run_attempt") != attempt:
483
+ refusals.append(f"{rpath.name}: ci.run_attempt is {ci.get('run_attempt')!r}, not --attempt {attempt}")
484
+ if refusals:
485
+ return _collect_refuse(args, refusals, checks, base)
486
+ pkg = receipt_check.referee_pkg(repo.resolve().name, False)
487
+ try:
488
+ gate_mod.validate_receipt(pkg, repo, rec)
489
+ line, _info = gate_mod.report_log_check(repo, rec, rpath)
490
+ except core.Fail as e:
491
+ return _collect_refuse(args, [f"{rpath.name}: {e}"], checks, base)
492
+ checks.append(f"✓ receipt: {rpath.name} passes gate's validator at this checkout's HEAD (the ci block's "
493
+ f"level 1 included)")
494
+ checks.append(line)
495
+ log_name = gate_mod.report_log_name(rec)
496
+ logs = [p for p in (adir / log_name, adir / (log_name + gate_mod.REPORT_GZ_SUFFIX)) if p.is_file()]
497
+ base["log"] = f".lean-receipts/{logs[0].name}" if logs else None
498
+ copies = [(rpath, rdir / rpath.name)] + [(p, rdir / p.name) for p in logs]
499
+ bundle = ci.get("attestation")
500
+ if bundle is not None: # level 1 (validate_receipt) checked it is a plain file name
501
+ bpath = adir / bundle
502
+ if not (bpath.is_file() and not bpath.is_symlink()):
503
+ return _collect_refuse(args, [f"{rpath.name}: ci.attestation names {bundle}, which the artifact does "
504
+ f"not hold (the run's attestation step did not finish?)"], checks, base)
505
+ subjects, why = ci_github.bundle_subjects(bpath.read_bytes())
506
+ bad = [why] if subjects is None else ci_github.subject_problems(
507
+ subjects, hashlib.sha256(raw).hexdigest(), str(rec.get("report_sha256", "")))
508
+ if bad:
509
+ return _collect_refuse(args, [f"{bundle}: {'; '.join(bad)}"], checks, base)
510
+ checks.append(f"✓ attestation: {bundle} signs exactly this receipt and its log (its signature is checked "
511
+ f"by `receipt check --attested`, level 3)")
512
+ copies.append((bpath, rdir / bundle))
513
+ for src, dst in copies:
514
+ why = rc._same_or_absent(dst, src.read_bytes())
515
+ if why:
516
+ refusals.append(why)
517
+ if refusals:
518
+ return _collect_refuse(args, refusals, checks, base)
519
+ rdir.mkdir(parents=True, exist_ok=True)
520
+ copied = []
521
+ for src, dst in copies:
522
+ data = src.read_bytes()
523
+ if dst.exists():
524
+ checks.append(f"· {dst.name} already present with the same bytes")
525
+ else:
526
+ rc._write(dst, data)
527
+ copied.append({"path": f".lean-receipts/{dst.name}", "sha256": hashlib.sha256(data).hexdigest()})
528
+ files = " ".join(c["path"] for c in copied)
529
+ nxt = f"git add {files} && git commit -m 'receipt: GitHub Actions run {run}'"
530
+ if getattr(args, "json_out", False):
531
+ core.print_json({"ok": True, **base, "copied": copied, "checks": checks, "next": nxt, "refusals": []})
532
+ return 0
533
+ print(f"{VERB} --collect: ok, run {run} attempt {ci['run_attempt']}, commit {str(rec['commit'])[:12]}")
534
+ for c in checks:
535
+ print(f" {c}")
536
+ for c in copied:
537
+ print(f" copied {c['path']} (sha256 {c['sha256']})")
538
+ print("nothing committed or pushed; commit the files as an evidence-only descendant:")
539
+ print(f"next: {nxt}")
540
+ return 0
541
+
542
+
543
+ # --------------------------------------------------------------------------
544
+ # --template
545
+
546
+ def install_commit() -> str | None:
547
+ """The 40-hex commit the running lean-pkg was installed from (pip's direct_url.json vcs_info), or None
548
+ (an editable or index install records none)."""
549
+ try:
550
+ direct = json.loads(md.distribution("lean-pkg").read_text("direct_url.json") or "{}")
551
+ except (md.PackageNotFoundError, OSError, ValueError):
552
+ return None
553
+ cid = (direct.get("vcs_info") or {}).get("commit_id") if isinstance(direct, dict) else None
554
+ return cid if isinstance(cid, str) and ci_github.HEX40.match(cid) else None
555
+
556
+
557
+ def template(pin: str | None) -> str:
558
+ ref = pin or PIN_PLACEHOLDER
559
+ return f"""\
560
+ # .github/workflows/lean-pkg.yml: verify this package on a GitHub-hosted runner and write a lower-tier receipt
561
+ # (printed by `lean-pkg receipt ci --template`). lean-pkg's reusable verify.yml checks out the pushed commit,
562
+ # installs elan, the Mathlib cache and the lean-pkg release it ships with, runs the verify command with a
563
+ # self-sealed log, then `lean-pkg receipt ci`, signs the receipt and its log into a Sigstore bundle (an
564
+ # attestation, level 3), and uploads the three as the artifact lean-pkg-receipt-<run>-<attempt>. It never pushes:
565
+ # after a green run, on your machine,
566
+ #
567
+ # lean-pkg receipt ci --collect RUN_ID # download, check against your checkout, copy into .lean-receipts/
568
+ # git add .lean-receipts && git commit -m "receipt: GitHub Actions run RUN_ID"
569
+ #
570
+ # Pin `uses:` to a full 40-hex commit of a lean-pkg release, never a tag or branch: a ref that can move is not
571
+ # corroborated. Only push and workflow_dispatch runs write a receipt.
572
+ name: lean-pkg verify
573
+ on:
574
+ push:
575
+ branches: [main]
576
+ paths-ignore: [".lean-receipts/**"]
577
+ workflow_dispatch:
578
+ permissions:
579
+ contents: read
580
+ id-token: write
581
+ attestations: write
582
+ jobs:
583
+ verify:
584
+ uses: {VERIFY_WORKFLOW}@{ref}
585
+ with:
586
+ verify-command: bash verify.sh # called with the log path as its last argument
587
+ package-dir: .
588
+ """
589
+
590
+
591
+ def cmd_template(args) -> int:
592
+ pin = install_commit()
593
+ text = template(pin)
594
+ if getattr(args, "json_out", False):
595
+ core.print_json({"ok": True, "template": text, "pinned": pin})
596
+ else:
597
+ sys.stdout.write(text)
598
+ if pin is None:
599
+ print(f"lean-pkg: note: this lean-pkg was not installed from a git commit; replace {PIN_PLACEHOLDER} "
600
+ f"with the 40-hex commit of the lean-pkg release you install", file=sys.stderr)
601
+ return 0
602
+
603
+
604
+ # --------------------------------------------------------------------------
605
+
606
+ WRITER_FLAGS = (("--log", "log"), ("--receipt-commit", "commit_sha"), ("--checker", "checker"),
607
+ ("--redact", "redact"), ("--out", "out"), ("--compress-log", "compress_log"),
608
+ ("--append-readme", "append_readme"), ("--readme-heading", "readme_heading"),
609
+ ("--readme-line", "readme_line"), ("--tar-sha256", "tar_sha256"), ("--attest", "attest"))
610
+
611
+
612
+ def cmd_receipt_ci(args) -> int:
613
+ given = [flag for flag, dest in WRITER_FLAGS if getattr(args, dest, None)]
614
+ if args.template:
615
+ others = given + [f for f, v in (("--collect", args.collect is not None), ("--attempt", args.attempt is not None),
616
+ ("--repo", args.repo is not None)) if v]
617
+ if others:
618
+ raise core.UsageError(f"--template takes no other flag (got {', '.join(others)})")
619
+ return cmd_template(args)
620
+ if args.attempt is not None and args.collect is None:
621
+ raise core.UsageError("--attempt goes with --collect RUN")
622
+ if args.collect is not None:
623
+ if given:
624
+ raise core.UsageError(f"--collect downloads a written receipt; {', '.join(given)} belong to the writer "
625
+ f"(in the job)")
626
+ if args.collect < 1 or (args.attempt is not None and args.attempt < 1):
627
+ raise core.UsageError("--collect RUN and --attempt N are positive integers")
628
+ return cmd_collect(args)
629
+ return cmd_write(args)
630
+
631
+
632
+ def add_parser(rsub) -> None:
633
+ s = rsub.add_parser("ci", help="a lower-tier receipt written inside a GitHub Actions job (job_id "
634
+ "gha-<run>-<attempt>, the ci block from the runner's variables); --collect RUN: "
635
+ "fetch and check a run's receipt; --template: the caller workflow")
636
+ s.add_argument("--log", default=None, metavar="PATH",
637
+ help="the job's raw verify log, sealed in-log (one `verify-log-sha256: <hex>` line, the SHA-256 "
638
+ "of the log without it); when it has no `checker:` line, --checker TEXT is required")
639
+ s.add_argument("--receipt-commit", dest="commit_sha", default=None, metavar="SHA",
640
+ help="the verified commit (default GITHUB_SHA; any other value refuses)")
641
+ s.add_argument("--redact", action="append", default=[], metavar="REGEX",
642
+ help=f"also replace matches with {rc.REDACT_TOKEN} (repeatable); the checkout, GITHUB_WORKSPACE, "
643
+ "RUNNER_TEMP, RUNNER_TOOL_CACHE, $HOME, /home/runner and /run/user/N/ are always redacted "
644
+ "to <repo>, <GITHUB_WORKSPACE>, <RUNNER_TEMP>, <RUNNER_TOOL_CACHE>, <HOME>, "
645
+ "/run/user/<UID>/ instead")
646
+ s.add_argument("--collect", type=int, default=None, metavar="RUN",
647
+ help="on your machine: download run RUN's receipt artifact with `gh run download` (your gh "
648
+ "login), check it as gate --check does against the --repo checkout, copy the receipt and "
649
+ "its log into .lean-receipts/; never commits or pushes")
650
+ s.add_argument("--attempt", type=int, default=None, metavar="N",
651
+ help="with --collect: the run attempt (default: the run's only receipt artifact)")
652
+ s.add_argument("--attest", action="store_true",
653
+ help="the job attests (verify.yml): record ci.attestation, the name <commit12>-gha-<R>-<A>"
654
+ ".sigstore.json of the Sigstore bundle the next step signs for the receipt and its log, to "
655
+ "be committed beside them (level 3); refused without an OIDC token (id-token: write)")
656
+ s.add_argument("--template", action="store_true",
657
+ help="print the caller workflow (.github/workflows/lean-pkg.yml) that runs lean-pkg's reusable "
658
+ "verify.yml pinned to a 40-hex commit; needs no other flag")
659
+ rc.add_common_flags(s, "GitHub Actions run R attempt A", "gha-<R>-<A>")
660
+ s.set_defaults(fn=cmd_receipt_ci)