diff --git a/.github/requirements/hatchling.txt b/.github/requirements/hatchling.txt new file mode 100644 index 00000000..63f02cd6 --- /dev/null +++ b/.github/requirements/hatchling.txt @@ -0,0 +1,99 @@ +# The Python build backend, hash-pinned. +# +# WHAT THIS IS FOR. `packages/aimock-pytest` declares +# `build-system.requires = ["hatchling"]`. Anything that builds it — the release +# job that publishes to PyPI, and the Python test matrix — otherwise resolves +# that name from PyPI at run time and EXECUTES it. Installed from this file with +# `pip install --require-hashes -r`, pip refuses any artifact whose sha256 is not +# listed below, so the bytes that build a release are the bytes reviewed here. +# +# The two consumers install from this file and then build with build isolation +# DISABLED, so no second, unpinned copy of the backend is fetched at build time: +# .github/workflows/publish-release.yml `publish-pytest` job +# .github/workflows/test-pytest.yml `test` job +# +# SCOPE, stated honestly. This pins the BUILD backend only. `test-pytest.yml` +# still resolves the runtime and test dependencies (`requests`, `pytest`, and +# their transitive closure) from PyPI unpinned, on purpose — that job exists to +# catch breakage against current releases, and freezing them would retire the +# signal. That job declares no secrets and holds `contents: read`. +# +# REGENERATING. Universal across every Python this repo builds on (3.10–3.13), +# which is why `tomli` carries a `python_full_version < '3.11'` marker; pip +# evaluates markers here, so the unmatched lines are simply skipped. +# +# uv pip compile --generate-hashes --universal --python-version 3.10 \ +# --no-header -o .github/requirements/hatchling.txt - +# # stdin: hatchling== +# +# Bumping a version means replacing its hashes too — a version without its +# matching hashes makes pip fail closed, not fail open. + +hatchling==1.31.0 \ + --hash=sha256:6b48ad4068a482ed7239b3a8215bc55b47aad3345d58dfc94e553c5d2d46211b \ + --hash=sha256:aac80bec8b6fe35e8480f1c335be8910fa210a0e6f735a139be205dadcacb544 +packaging==26.3 \ + --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ + --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c + # via hatchling +pathspec==1.1.1 \ + --hash=sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a \ + --hash=sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189 + # via hatchling +pluggy==1.6.0 \ + --hash=sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3 \ + --hash=sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746 + # via hatchling +tomli==2.4.1 ; python_full_version < '3.11' \ + --hash=sha256:01f520d4f53ef97964a240a035ec2a869fe1a37dde002b57ebc4417a27ccd853 \ + --hash=sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe \ + --hash=sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5 \ + --hash=sha256:1d8591993e228b0c930c4bb0db464bdad97b3289fb981255d6c9a41aedc84b2d \ + --hash=sha256:2190f2e9dd7508d2a90ded5ed369255980a1bcdd58e52f7fe24b8162bf9fedbd \ + --hash=sha256:2c1c351919aca02858f740c6d33adea0c5deea37f9ecca1cc1ef9e884a619d26 \ + --hash=sha256:36d2bd2ad5fb9eaddba5226aa02c8ec3fa4f192631e347b3ed28186d43be6b54 \ + --hash=sha256:3d48a93ee1c9b79c04bb38772ee1b64dcf18ff43085896ea460ca8dec96f35f6 \ + --hash=sha256:47149d5bd38761ac8be13a84864bf0b7b70bc051806bc3669ab1cbc56216b23c \ + --hash=sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a \ + --hash=sha256:4b605484e43cdc43f0954ddae319fb75f04cc10dd80d830540060ee7cd0243cd \ + --hash=sha256:504aa796fe0569bb43171066009ead363de03675276d2d121ac1a4572397870f \ + --hash=sha256:51529d40e3ca50046d7606fa99ce3956a617f9b36380da3b7f0dd3dd28e68cb5 \ + --hash=sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9 \ + --hash=sha256:559db847dc486944896521f68d8190be1c9e719fced785720d2216fe7022b662 \ + --hash=sha256:5a881ab208c0baf688221f8cecc5401bd291d67e38a1ac884d6736cbcd8247e9 \ + --hash=sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1 \ + --hash=sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585 \ + --hash=sha256:5ee18d9ebdb417e384b58fe414e8d6af9f4e7a0ae761519fb50f721de398dd4e \ + --hash=sha256:7008df2e7655c495dd12d2a4ad038ff878d4ca4b81fccaf82b714e07eae4402c \ + --hash=sha256:734e20b57ba95624ecf1841e72b53f6e186355e216e5412de414e3c51e5e3c41 \ + --hash=sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f \ + --hash=sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085 \ + --hash=sha256:7f94b27a62cfad8496c8d2513e1a222dd446f095fca8987fceef261225538a15 \ + --hash=sha256:88dceee75c2c63af144e456745e10101eb67361050196b0b6af5d717254dddf7 \ + --hash=sha256:8a650c2dbafa08d42e51ba0b62740dae4ecb9338eefa093aa5c78ceb546fcd5c \ + --hash=sha256:8d65a2fbf9d2f8352685bc1364177ee3923d6baf5e7f43ea4959d7d8bc326a36 \ + --hash=sha256:96481a5786729fd470164b47cdb3e0e58062a496f455ee41b4403be77cb5a076 \ + --hash=sha256:a120733b01c45e9a0c34aeef92bf0cf1d56cfe81ed9d47d562f9ed591a9828ac \ + --hash=sha256:b1d22e6e9387bf4739fbe23bfa80e93f6b0373a7f1b96c6227c32bef95a4d7a8 \ + --hash=sha256:b8c198f8c1805dc42708689ed6864951fd2494f924149d3e4bce7710f8eb5232 \ + --hash=sha256:c2541745709bad0264b7d4705ad453b76ccd191e64aa6f0fc66b69a293a45ece \ + --hash=sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a \ + --hash=sha256:c7f2c7f2b9ca6bdeef8f0fa897f8e05085923eb091721675170254cbc5b02897 \ + --hash=sha256:d312ef37c91508b0ab2cee7da26ec0b3ed2f03ce12bd87a588d771ae15dcf82d \ + --hash=sha256:d4d8fe59808a54658fcc0160ecfb1b30f9089906c50b23bcb4c69eddc19ec2b4 \ + --hash=sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917 \ + --hash=sha256:eab21f45c7f66c13f2a9e0e1535309cee140182a9cdae1e041d02e47291e8396 \ + --hash=sha256:eb0dc4e38e6a1fd579e5d50369aa2e10acfc9cace504579b2faabb478e76941a \ + --hash=sha256:ec9bfaf3ad2df51ace80688143a6a4ebc09a248f6ff781a9945e51937008fcbc \ + --hash=sha256:ede3e6487c5ef5d28634ba3f31f989030ad6af71edfb0055cbbd14189ff240ba \ + --hash=sha256:f3c6818a1a86dd6dca7ddcaaf76947d5ba31aecc28cb1b67009a5877c9a64f3f \ + --hash=sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257 \ + --hash=sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30 \ + --hash=sha256:fd0409a3653af6c147209d267a0e4243f0ae46b011aa978b1080359fddc9b6cf \ + --hash=sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9 \ + --hash=sha256:ff2983983d34813c1aeb0fa89091e76c3a22889ee83ab27c5eeb45100560c049 + # via hatchling +trove-classifiers==2026.6.1.19 \ + --hash=sha256:ab4c4ec93cc4a4e7815fa759906e05e6bb3f2fbd92ea0f897288c6a43efd15b3 \ + --hash=sha256:c5132b4b61a829d11cfbd2d72e97f20a45ed6edb95e45c5efdeb5e00836b2745 + # via hatchling diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index f8e01560..25ecb82c 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -186,7 +186,33 @@ jobs: npm view "@copilotkit/aimock@${VERSION}" version - name: Install build tools - run: pip install hatch + # HASH-PINNED, and hatchling rather than hatch. Both halves were measured + # on 2026-08-05, not reasoned about: + # + # 1. `pip install hatch` resolves a NAME from PyPI at run time. Run + # verbatim with the registry serving substituted bytes, it installed + # them (exit 0) and `hatch build` then EXECUTED them (exit 0). This + # job carries `environment: pypi` and `id-token: write` and is the + # job that publishes aimock-pytest under our own OIDC identity, so + # that is arbitrary code beside a publish token. + # + # 2. Pinning `hatch` would NOT have been sufficient — the same + # pinned-wrapper/unpinned-payload shape as the Ollama installer. + # `hatch build` builds in an ISOLATED environment and fetches this + # project's `build-system.requires` (hatchling) from PyPI at build + # time, unpinned. Against an empty index `hatch build` dies with + # "hatchling was not found in the package registry"; `python -m + # hatchling build` succeeds, because it fetches nothing. + # + # `--require-hashes` is scoped to THIS invocation on purpose. Applying it + # job-wide (PIP_REQUIRE_HASHES) would also hit the unhashed `pip install + # --dry-run` probe in the next step, whose FAILURE means "not published + # yet" — a hash-gated probe would fail for the wrong reason and turn the + # already-published gate into an unconditional publish. + # + # `python -m pip` rather than `pip` so the interpreter that installs the + # backend is the same one that imports it in the build step below. + run: python -m pip install --require-hashes -r .github/requirements/hatchling.txt - name: Check if pytest version is already published id: check @@ -201,7 +227,13 @@ jobs: - name: Build pytest package if: steps.check.outputs.published == 'false' - run: cd packages/aimock-pytest && hatch build + # The published artifacts are unchanged: `hatch build` and `python -m + # hatchling build` produced byte-identical sdist and wheel for this + # package at 0.5.2 — sha256 0a54957ba57c52957c863fdb85b535d9715269f07ff9b4d776de98d0f6d68580 + # and 29ac7b3a07d9c73955ab08f75736ebcf728134eceb5264b988e8e933f5ee2c35. + # `python -m` rather than the console script so the build does not depend + # on where the pinned install put its entry points on PATH. + run: cd packages/aimock-pytest && python -m hatchling build - name: Publish pytest package to PyPI if: steps.check.outputs.published == 'false' diff --git a/.github/workflows/test-pytest.yml b/.github/workflows/test-pytest.yml index 03d02bbe..4e4484b2 100644 --- a/.github/workflows/test-pytest.yml +++ b/.github/workflows/test-pytest.yml @@ -45,6 +45,24 @@ jobs: # Install and test Python package - name: Install aimock-pytest - run: pip install ./packages/aimock-pytest[test] + # The build backend is hash-pinned and build isolation is OFF, so pip + # does not resolve `build-system.requires` from PyPI and execute it here. + # Measured on 2026-08-05: with the registry serving substituted bytes, + # the old one-liner imported the substituted `hatchling.build` twice + # (get_requires_for_build_wheel, then prepare_metadata) before it did + # anything else. + # + # `requests` and `pytest` are STILL resolved unpinned, deliberately. This + # job exists to catch breakage against current releases across four + # Pythons; freezing them would retire that signal, and this job declares + # no secrets and holds `contents: read`. The publish job — which does hold + # a publish identity — installs from the same pinned file and builds the + # same way, so the backend that builds a release is the backend tested here. + # + # `python -m pip` rather than `pip` so the interpreter that installs the + # backend is the same one that has to import it during the build. + run: | + python -m pip install --require-hashes -r .github/requirements/hatchling.txt + python -m pip install --no-build-isolation "./packages/aimock-pytest[test]" - name: Run Python tests run: cd packages/aimock-pytest && pytest tests/ -v diff --git a/src/__tests__/publish-pin-workflow.test.ts b/src/__tests__/publish-pin-workflow.test.ts new file mode 100644 index 00000000..de527f19 --- /dev/null +++ b/src/__tests__/publish-pin-workflow.test.ts @@ -0,0 +1,459 @@ +/** + * Assertions on the Python install sites of `.github/workflows/publish-release.yml` + * and `.github/workflows/test-pytest.yml`. + * + * WHAT THIS GUARDS. `publish-release.yml`'s `publish-pytest` job carries + * `environment: pypi` and `id-token: write`, and it is the job that publishes + * `aimock-pytest` to PyPI through OIDC trusted publishing. Anything it executes + * runs beside that publish identity and can decide what bytes get published + * under our own name — a downstream-user compromise, not a key rotation. + * + * THE TWO HOLES THIS REPLACED, both measured on 2026-08-05 by running the + * committed step bodies verbatim with the registry serving substituted bytes: + * + * 1. `pip install hatch` resolved a NAME at run time. The substituted package + * installed (exit 0) and `hatch build` then EXECUTED it (exit 0). + * 2. Pinning `hatch` would NOT have closed it. `hatch build` builds in an + * ISOLATED environment and fetches `build-system.requires` — hatchling — + * from PyPI at build time, unpinned. That is the pinned-wrapper / + * unpinned-payload shape the Ollama installer had. `test-pytest.yml`'s + * `pip install ./packages/aimock-pytest[test]` had the same hole with no + * wrapper at all: the substituted `hatchling.build` was imported twice + * before pip did anything else. + * + * So the backend is hash-pinned in `.github/requirements/hatchling.txt` and both + * sites build with build isolation DISABLED, which is why the file being a real + * hash pin and the build not re-fetching are guarded together below — either one + * alone leaves unpinned bytes executing. + * + * WHY THE `--require-hashes` SCOPE IS ASSERTED. `publish-pytest` decides whether + * to publish with `pip install == --dry-run --no-deps`, where FAILURE + * means "not published yet, go publish". Hash-gating pip job-wide would make + * that probe fail for an unrelated reason and turn the gate into an + * unconditional publish, so the gate steps must stay unhashed and the two + * publishing steps must stay conditioned on it. + * + * The repo ships no YAML dependency and this suite adds none; the parser below + * is scoped to one job's `steps:` sequence, and actionlint covers structural + * validity separately in CI. + */ +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { spawnSync } from "node:child_process"; + +import { describe, expect, it } from "vitest"; + +const REPO = resolve(__dirname, "../.."); +const RELEASE_PATH = join(REPO, ".github/workflows/publish-release.yml"); +const PYTEST_PATH = join(REPO, ".github/workflows/test-pytest.yml"); +const PINS_REL = ".github/requirements/hatchling.txt"; +const PINS_PATH = join(REPO, PINS_REL); + +const release = readFileSync(RELEASE_PATH, "utf8"); +const pytestWf = readFileSync(PYTEST_PATH, "utf8"); + +const PUBLISH_JOB = "publish-pytest"; +const INSTALL_STEP = "Install build tools"; +const GATE_STEP = "Check if pytest version is already published"; +const BUILD_STEP = "Build pytest package"; +const PUBLISH_STEP = "Publish pytest package to PyPI"; + +interface Step { + name?: string; + id?: string; + uses?: string; + if?: string; + run: string; +} + +const indentOf = (l: string): number => l.length - l.trimStart().length; + +/** + * The `steps:` sequence of ONE job. + * + * Job-scoped on purpose: publish-release.yml has three jobs, and a whole-file + * scan would answer every question about `publish-pytest` with `build`'s steps — + * the first `steps:` key in the file. A locator that cannot find its job THROWS + * rather than yielding an empty or wrong slice. + */ +function stepsOfJob(job: string, src: string, label: string): Step[] { + const lines = src.split("\n"); + const jobIdx = lines.findIndex((l) => l === ` ${job}:`); + if (jobIdx === -1) throw new Error(`${label}: no job \`${job}\``); + let jobEnd = lines.length; + for (let i = jobIdx + 1; i < lines.length; i++) { + if (lines[i].trim() && indentOf(lines[i]) <= 2) { + jobEnd = i; + break; + } + } + const body = lines.slice(jobIdx, jobEnd); + + const stepsIdx = body.findIndex((l) => /^\s+steps:\s*$/.test(l)); + if (stepsIdx === -1) throw new Error(`${label}: job \`${job}\` has no \`steps:\``); + const firstItem = body.findIndex((l, i) => i > stepsIdx && /^\s+- \S/.test(l)); + if (firstItem === -1) throw new Error(`${label}: job \`${job}\` \`steps:\` is empty`); + const itemIndent = indentOf(body[firstItem]); + const keyIndent = itemIndent + 2; + + const starts: number[] = []; + let end = body.length; + for (let i = firstItem; i < body.length; i++) { + const l = body[i]; + if (!l.trim()) continue; + if (indentOf(l) < itemIndent) { + end = i; + break; + } + if (indentOf(l) === itemIndent && /^\s+- \S/.test(l)) starts.push(i); + } + + return starts.map((from, n) => { + const to = n + 1 < starts.length ? starts[n + 1] : end; + // Normalise `- key: value` to ` key: value` so every key sits at keyIndent. + const item = body.slice(from, to).map((l, i) => (i === 0 ? l.replace(/- /, " ") : l)); + + const step: Step = { run: "" }; + for (let i = 0; i < item.length; i++) { + const l = item[i]; + if (!l.trim() || indentOf(l) !== keyIndent) continue; + const m = /^\s*([A-Za-z_-]+):\s*(.*)$/.exec(l); + if (!m) continue; + const [, key, inline] = m; + + if (key === "run") { + // An INLINE `run:` is a run body too — dropping it would make a + // one-liner step invisible to every guard that reads step bodies. + if (!/^[|>]/.test(inline) && inline !== "") { + step.run = `${inline}\n`; + continue; + } + const child: string[] = []; + let blockIndent = -1; + for (let j = i + 1; j < item.length; j++) { + if (!item[j].trim()) { + child.push(""); + continue; + } + if (blockIndent === -1) blockIndent = indentOf(item[j]); + if (indentOf(item[j]) < blockIndent) break; + child.push(item[j].slice(blockIndent)); + } + while (child.length && child[child.length - 1] === "") child.pop(); + step.run = `${child.join("\n")}\n`; + continue; + } + + if (key === "name") step.name = inline.replace(/^["']|["']$/g, ""); + if (key === "id") step.id = inline.replace(/^["']|["']$/g, ""); + if (key === "uses") step.uses = inline.trim(); + if (key === "if") step.if = inline.trim(); + } + return step; + }); +} + +const releaseSteps = (): Step[] => stepsOfJob(PUBLISH_JOB, release, "publish-release.yml"); +const pytestSteps = (): Step[] => stepsOfJob("test", pytestWf, "test-pytest.yml"); + +function stepByName(name: string, steps: Step[], label: string): Step { + const hits = steps.filter((s) => s.name === name); + if (hits.length !== 1) throw new Error(`${label}: ${hits.length} steps named \`${name}\``); + return hits[0]; +} + +/** + * A step's run body with shell COMMENT lines removed. + * + * Every "does this step do X" question has to be asked of the code, not the + * prose: these steps' rationale comments name `hatch`, `hatch build` and + * `pip install hatch` as the things they replaced, so a guard that greps the + * whole body answers about the comment. + */ +const stripComments = (src: string): string => + src + .split("\n") + .filter((l) => !/^\s*#/.test(l)) + .join("\n"); + +const codeOf = (s: Step): string => stripComments(s.run); + +/** + * The whole workflow with full-line comments removed. + * + * Whole-line only, which is all this file needs and all it claims: every + * question asked of the file below is about a `key: value` line, and the + * rationale comments beside those keys deliberately NAME the settings they warn + * against — a guard that greps the raw file answers about the warning. + */ +const releaseCode = stripComments(release); + +interface Pin { + name: string; + version: string; + hashes: string[]; + marker?: string; +} + +/** Parse the pinned requirements file into one entry per requirement. */ +function parsePins(src: string): Pin[] { + const pins: Pin[] = []; + for (const raw of src.split("\n")) { + const line = raw.trim().replace(/\s*\\$/, ""); + if (!line || line.startsWith("#")) continue; + const req = /^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(==)?\s*([^\s;]*)\s*(?:;\s*(.*))?$/.exec(line); + if (req && !line.startsWith("--")) { + pins.push({ + name: req[1], + version: req[2] === "==" ? req[3] : "", + hashes: [], + marker: req[4], + }); + continue; + } + const h = /^--hash=sha256:([0-9a-fA-F]+)$/.exec(line); + if (h && pins.length) pins[pins.length - 1].hashes.push(h[1]); + } + return pins; +} + +/** A python interpreter that has pip, or `null`. */ +function findPython(): string | null { + for (const cand of ["python3", "python"]) { + const r = spawnSync(cand, ["-m", "pip", "--version"], { encoding: "utf-8" }); + if (r.status === 0) return cand; + } + return null; +} + +const PYTHON = findPython(); + +interface PipObservation { + exit: number; + /** pip's own tamper refusal, verbatim-matched. */ + refused: boolean; + stdio: string; +} + +/** + * Run REAL pip against the repo's REAL pin file, with a local directory standing + * in for the registry. + * + * `--no-index -f ` is the whole network: pip can only see the bytes in + * `dir`. That makes this the pip analogue of stubbing `curl` — the command and + * the pin file are the repo's own, only what the registry serves is substituted. + * `pip download` rather than `pip install` because hash checking happens BEFORE + * a wheel is opened, so the refusal is observable without a real, installable + * artifact; `refused` matches pip's tamper message rather than the exit code, + * since a non-zero exit alone cannot tell a hash refusal from any other error. + */ +function observePip(reqFile: string, servedBytes: string, wheelName: string): PipObservation { + const dir = mkdtempSync(join(tmpdir(), "aimock-pin-")); + try { + const links = join(dir, "links"); + mkdirSync(links); + writeFileSync(join(links, wheelName), servedBytes); + const res = spawnSync( + PYTHON as string, + [ + "-m", + "pip", + "download", + "--no-deps", + "--no-index", + "--disable-pip-version-check", + "-f", + links, + "-d", + join(dir, "out"), + "--require-hashes", + "-r", + reqFile, + ], + { encoding: "utf-8", cwd: dir }, + ); + const stdio = `${res.stdout ?? ""}${res.stderr ?? ""}`; + return { + exit: res.status ?? -1, + refused: stdio.includes("DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE"), + stdio, + }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +describe("the PyPI publish path runs no Python bytes it has not pinned", () => { + it("installs its build backend from a hash-pinned requirements file", () => { + const step = stepByName(INSTALL_STEP, releaseSteps(), "publish-release.yml"); + const code = codeOf(step); + expect(code, "the install step no longer passes --require-hashes").toContain( + "--require-hashes", + ); + expect(code, `the install step no longer reads ${PINS_REL}`).toContain(`-r ${PINS_REL}`); + // A bare `pip install ` anywhere in this job resolves a name from PyPI + // at run time, which is exactly what was replaced. + for (const s of releaseSteps()) { + const bare = /(?:^|\s)(?:python -m )?pip install\s+(?!-)(?!\.)(\S+)/m.exec(codeOf(s)); + const isGate = s.name === GATE_STEP; + if (bare && !isGate) + throw new Error( + `step \`${s.name}\` runs \`pip install ${bare[1]}\` — an unpinned name resolved from ` + + "PyPI at run time, in the job that holds `environment: pypi` and `id-token: write`", + ); + } + }); + + it("the pin file is a real hash pin: every requirement `==`-pinned and sha256-hashed", () => { + expect(existsSync(PINS_PATH), `${PINS_REL} does not exist`).toBe(true); + const pins = parsePins(readFileSync(PINS_PATH, "utf8")); + expect(pins.length, `${PINS_REL} lists no requirements at all`).toBeGreaterThan(0); + for (const pin of pins) { + expect(pin.version, `\`${pin.name}\` is not pinned to an exact version with \`==\``).toMatch( + /^[0-9]/, + ); + expect( + pin.hashes.length, + `\`${pin.name}==${pin.version}\` carries no --hash, so pip would accept any bytes ` + + "published under that name and version", + ).toBeGreaterThan(0); + for (const h of pin.hashes) + expect(h, `\`${pin.name}\` has a --hash that is not a sha256 digest`).toMatch( + /^[0-9a-f]{64}$/, + ); + } + // The backend itself is the executable that matters; a file that pinned + // only its dependencies would satisfy every assertion above. + expect( + pins.map((p) => p.name), + "hatchling — the backend that actually executes — is not in the pin file", + ).toContain("hatchling"); + }); + + it("the build re-fetches nothing: no build-isolating builder, backend invoked directly", () => { + const step = stepByName(BUILD_STEP, releaseSteps(), "publish-release.yml"); + const code = codeOf(step); + expect( + code, + "`hatch build` is back — it resolves `build-system.requires` from PyPI into an isolated " + + "env at build time, so pinning the wrapper leaves the backend unpinned", + ).not.toMatch(/(^|\s)hatch\s+build/); + expect(code, "the build no longer invokes the pinned backend directly").toContain( + "hatchling build", + ); + }); + + it("hash checking is scoped to the install, so the already-published gate still decides", () => { + // PIP_REQUIRE_HASHES anywhere job- or workflow-wide would also hit the gate's + // unhashed `--dry-run` probe. That probe's FAILURE means "not published yet", + // so breaking it does not fail the job — it publishes unconditionally. + expect( + releaseCode, + "PIP_REQUIRE_HASHES is set somewhere in this workflow; it would make the already-published " + + "probe fail for an unrelated reason, and that probe fails OPEN into publishing", + ).not.toContain("PIP_REQUIRE_HASHES"); + const gate = stepByName(GATE_STEP, releaseSteps(), "publish-release.yml"); + expect(codeOf(gate), "the already-published probe is itself hash-gated").not.toContain( + "--require-hashes", + ); + expect(gate.id, "the gate step lost its `id`, so nothing can depend on its output").toBe( + "check", + ); + expect(codeOf(gate)).toContain('echo "published='); + }); + + it("both publishing steps stay conditioned on that gate", () => { + const steps = releaseSteps(); + const gateIdx = steps.findIndex((s) => s.name === GATE_STEP); + expect(gateIdx, `no \`${GATE_STEP}\` step`).toBeGreaterThan(-1); + for (const name of [BUILD_STEP, PUBLISH_STEP]) { + const idx = steps.findIndex((s) => s.name === name); + expect(idx, `no \`${name}\` step`).toBeGreaterThan(-1); + expect( + idx, + `\`${name}\` no longer follows the gate that is supposed to guard it`, + ).toBeGreaterThan(gateIdx); + expect( + steps[idx].if, + `\`${name}\` is no longer gated on the already-published check — an unchanged version ` + + "would republish on every push to main", + ).toBe("steps.check.outputs.published == 'false'"); + } + // The publish itself is the step that spends the OIDC identity; it must stay + // the pinned action, not something the job installs. + const publish = steps[steps.findIndex((s) => s.name === PUBLISH_STEP)]; + expect(publish.uses, "the PyPI publish step is no longer a SHA-pinned action").toMatch( + /^pypa\/gh-action-pypi-publish@[0-9a-f]{40}\b/, + ); + }); + + it("the Python test matrix installs from the same pin and disables build isolation", () => { + // Same file on purpose: the backend that builds a release is then the one + // exercised across the 3.10–3.13 matrix before a release is ever cut. + const step = stepByName("Install aimock-pytest", pytestSteps(), "test-pytest.yml"); + const code = codeOf(step); + expect(code, "the test matrix no longer installs the hash-pinned backend").toContain( + `--require-hashes -r ${PINS_REL}`, + ); + expect( + code, + "build isolation is back on, so pip resolves `build-system.requires` from PyPI and " + + "executes it here regardless of what was pinned", + ).toContain("--no-build-isolation"); + }); + + describe("EXECUTED against real pip", () => { + it("finds a python with pip (a skipped guard here is a guard that proves nothing)", () => { + if (PYTHON === null && process.env.CI) + throw new Error( + "no `python3 -m pip` on this runner, so the executed pin guards below cannot run; " + + "they must not be silently skipped in CI", + ); + expect(true).toBe(true); + }); + + it.skipIf(PYTHON === null)( + "SUBSTITUTED backend bytes are REFUSED by the repo's own pin", + () => { + const pins = parsePins(readFileSync(PINS_PATH, "utf8")); + const hatchling = pins.find((p) => p.name === "hatchling"); + expect(hatchling, "no hatchling entry to test").toBeDefined(); + const wheel = `hatchling-${hatchling!.version}-py3-none-any.whl`; + const obs = observePip(PINS_PATH, "SUBSTITUTED BACKEND BYTES\n", wheel); + expect( + obs.refused, + "pip did NOT refuse bytes served under the pinned backend's own name and version — " + + `they would be imported as the PEP 517 backend in the job that publishes to PyPI. ${obs.stdio}`, + ).toBe(true); + expect(obs.exit, "the install concluded successfully on substituted bytes").not.toBe(0); + }, + ); + + it.skipIf(PYTHON === null)( + "POSITIVE CONTROL: bytes whose sha256 IS listed clear the hash gate", + () => { + // Without this, "refuse everything" — an empty or malformed pin file — + // satisfies the refusal above. Same served bytes, same command; the only + // difference is that the requirements file names THEIR digest, so + // clearing the gate isolates the hash as the reason for the refusal. + const served = "SUBSTITUTED BACKEND BYTES\n"; + const sha = createHash("sha256").update(served).digest("hex"); + const dir = mkdtempSync(join(tmpdir(), "aimock-pin-pos-")); + try { + const req = join(dir, "req.txt"); + writeFileSync(req, `hatchling==1.31.0 --hash=sha256:${sha}\n`); + const obs = observePip(req, served, "hatchling-1.31.0-py3-none-any.whl"); + expect( + obs.refused, + `pip refused bytes that match their listed digest, so the refusal above proves ` + + `nothing about hashes. ${obs.stdio}`, + ).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, + ); + }); +});