diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ddb5235..593eebe 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -380,105 +380,112 @@ jobs: fail("prepared tarball digest is invalid"); } - const configDirectory = mkdtempSync( - join(process.env.RUNNER_TEMP || tmpdir(), "rate-limit-npm-config-"), - ); - const publishDirectory = mkdtempSync( - join(process.env.RUNNER_TEMP || tmpdir(), "rate-limit-npm-cwd-"), - ); - const userConfig = join(configDirectory, "user.npmrc"); - const globalConfig = join(configDirectory, "global.npmrc"); - writeFileSync(userConfig, "", { mode: 0o600 }); - writeFileSync(globalConfig, "", { mode: 0o600 }); - chmodSync(userConfig, 0o600); - chmodSync(globalConfig, 0o600); - - const keep = new Set([ - "CI", - "COMSPEC", - "HOME", - "HOMEDRIVE", - "HOMEPATH", - "PATH", - "PATHEXT", - "RUNNER_TEMP", - "SYSTEMDRIVE", - "SYSTEMROOT", - "TEMP", - "TMP", - "TMPDIR", - "USERPROFILE", - "WINDIR", - ]); - const npmEnvironment = {}; - for (const [key, value] of Object.entries(process.env)) { - const upper = key.toUpperCase(); - if ( - value !== undefined && - (keep.has(upper) || - upper.startsWith("GITHUB_") || - upper.startsWith("ACTIONS_ID_TOKEN_")) - ) { - npmEnvironment[key] = value; + let configDirectory; + let publishDirectory; + try { + configDirectory = mkdtempSync( + join(process.env.RUNNER_TEMP || tmpdir(), "rate-limit-npm-config-"), + ); + publishDirectory = mkdtempSync( + join(process.env.RUNNER_TEMP || tmpdir(), "rate-limit-npm-cwd-"), + ); + const userConfig = join(configDirectory, "user.npmrc"); + const globalConfig = join(configDirectory, "global.npmrc"); + writeFileSync(userConfig, "", { mode: 0o600 }); + writeFileSync(globalConfig, "", { mode: 0o600 }); + chmodSync(userConfig, 0o600); + chmodSync(globalConfig, 0o600); + + const keep = new Set([ + "CI", + "COMSPEC", + "HOME", + "HOMEDRIVE", + "HOMEPATH", + "PATH", + "PATHEXT", + "RUNNER_ENVIRONMENT", + "RUNNER_TEMP", + "SYSTEMDRIVE", + "SYSTEMROOT", + "TEMP", + "TMP", + "TMPDIR", + "USERPROFILE", + "WINDIR", + ]); + const npmEnvironment = {}; + for (const [key, value] of Object.entries(process.env)) { + const upper = key.toUpperCase(); + if ( + value !== undefined && + (keep.has(upper) || + upper.startsWith("GITHUB_") || + upper.startsWith("ACTIONS_ID_TOKEN_")) + ) { + npmEnvironment[key] = value; + } } - } - npmEnvironment.NPM_CONFIG_USERCONFIG = userConfig; - npmEnvironment.NPM_CONFIG_GLOBALCONFIG = globalConfig; - npmEnvironment.NPM_CONFIG_CACHE = join(configDirectory, "cache"); - npmEnvironment.NPM_CONFIG_REGISTRY = REGISTRY; - - const runNpm = (arguments_, allowFailure = false) => { - const result = spawnSync("npm", arguments_, { - cwd: publishDirectory, - encoding: "utf8", - env: npmEnvironment, - stdio: allowFailure ? "pipe" : "inherit", - }); - if (result.error) throw result.error; - if (!allowFailure && result.status !== 0) { - fail(`npm ${arguments_.join(" ")} failed`); + npmEnvironment.NPM_CONFIG_USERCONFIG = userConfig; + npmEnvironment.NPM_CONFIG_GLOBALCONFIG = globalConfig; + npmEnvironment.NPM_CONFIG_CACHE = join(configDirectory, "cache"); + npmEnvironment.NPM_CONFIG_REGISTRY = REGISTRY; + + if (npmEnvironment.RUNNER_ENVIRONMENT !== "github-hosted") { + fail("GitHub-hosted runner metadata is required for provenance"); } - return result; - }; - const npmVersion = runNpm(["--version"], true).stdout.trim(); - const versionMatch = /^(\d+)\.(\d+)\.(\d+)/u.exec(npmVersion); - if ( - versionMatch === null || - Number(versionMatch[1]) < 11 || - (Number(versionMatch[1]) === 11 && - (Number(versionMatch[2]) < 5 || - (Number(versionMatch[2]) === 5 && - Number(versionMatch[3]) < 1))) - ) { - fail("npm 11.5.1 or newer is required for trusted publishing"); - } - const registryIntegrity = () => { - const result = runNpm( - [ - "view", - `${PACKAGE_NAME}@${manifest.package.version}`, - "dist.integrity", - "--json", - "--registry", - REGISTRY, - ], - true, - ); - if (result.status === 0) { - const value = JSON.parse(result.stdout); - if (typeof value !== "string") { - fail("registry returned invalid integrity metadata"); + const runNpm = (arguments_, allowFailure = false) => { + const result = spawnSync("npm", arguments_, { + cwd: publishDirectory, + encoding: "utf8", + env: npmEnvironment, + stdio: allowFailure ? "pipe" : "inherit", + }); + if (result.error) throw result.error; + if (!allowFailure && result.status !== 0) { + fail(`npm ${arguments_.join(" ")} failed`); } - return value; - } - if (/\bE404\b/u.test(`${result.stdout}\n${result.stderr}`)) { - return null; + return result; + }; + const npmVersion = runNpm(["--version"], true).stdout.trim(); + const versionMatch = /^(\d+)\.(\d+)\.(\d+)/u.exec(npmVersion); + if ( + versionMatch === null || + Number(versionMatch[1]) < 11 || + (Number(versionMatch[1]) === 11 && + (Number(versionMatch[2]) < 5 || + (Number(versionMatch[2]) === 5 && + Number(versionMatch[3]) < 1))) + ) { + fail("npm 11.5.1 or newer is required for trusted publishing"); } - fail("registry lookup failed"); - }; - try { + const registryIntegrity = () => { + const result = runNpm( + [ + "view", + `${PACKAGE_NAME}@${manifest.package.version}`, + "dist.integrity", + "--json", + "--registry", + REGISTRY, + ], + true, + ); + if (result.status === 0) { + const value = JSON.parse(result.stdout); + if (typeof value !== "string") { + fail("registry returned invalid integrity metadata"); + } + return value; + } + if (/\bE404\b/u.test(`${result.stdout}\n${result.stderr}`)) { + return null; + } + fail("registry lookup failed"); + }; + const existing = registryIntegrity(); if (existing !== null) { if (!same(existing, integrity)) { @@ -518,7 +525,11 @@ jobs: } } } finally { - rmSync(configDirectory, { force: true, recursive: true }); - rmSync(publishDirectory, { force: true, recursive: true }); + if (configDirectory !== undefined) { + rmSync(configDirectory, { force: true, recursive: true }); + } + if (publishDirectory !== undefined) { + rmSync(publishDirectory, { force: true, recursive: true }); + } } NODE diff --git a/README.md b/README.md index 8e41d46..cd730c3 100644 --- a/README.md +++ b/README.md @@ -7,27 +7,33 @@ in-memory tier and a durable storage-backed tier for expensive operations. > [!IMPORTANT] > Rate Limit is in early `0.x` development. Its public API is not stable. -> Current source is the **`0.3.2` candidate, not published**. Registry `latest` -> remains `0.2.0`, which -> predates the merged [PR #8 hardening](https://github.com/pegma-dev/rate-limit/pull/8) -> and the new bounded maintenance helper. The first advertised `0.1.0` +> Current source is the **unpublished `0.3.3` candidate**. Registry `latest` +> is `0.3.2`: original bytes match and npm cryptographic checks passed, but strict +> postflight failed its authenticated builder-identity policy. It is not +> qualified for the planned helper adoption. The first advertised `0.1.0` > release was published from protected signed `v0.1.0` through > trusted-publisher OIDC with provenance; the historical `0.0.0` name bootstrap > remains separate under `bootstrap`. pegma.dev composes the durable tier in > its production Identity worker; this candidate is not a new host deployment. -The source behavior below describes the `0.3.2` candidate. Adoption waits for -its reviewed publication and the host's explicit configuration/storage transition. +The source behavior below describes `0.3.3`, with the limiter/helper API +unchanged from `0.3.2`. Adoption waits for the new candidate's verified release +and the host's explicit configuration/storage transition. The +[public postflight procedure](docs/RELEASING.md#public-postflight-procedure) +defines the required byte, cryptographic, provenance-policy and consumer checks. The signed `v0.3.0` tag and GitHub release are retained history: their preparation failed before packing, produced no release artifact, and did not publish npm bytes. `0.3.1` fixed that trust configuration and passed packing, but upload discovered no files beneath hidden `.release/`; no artifact was retained and smoke/publication were skipped. Neither version is on npm. -The `0.3.2` candidate uses one nonhidden preparation/digest/upload directory, -with the limiter/helper API unchanged. See the -[failed upload and new candidate record](docs/RELEASING.md#failed-031-upload-and-032-candidate). -Hosts must wait for actual verified `0.3.2` publication before pinning the new +`0.3.2` corrected artifact discovery and published the original prepared bytes; +an idempotent publisher retry reused that artifact. Its authenticated provenance +contains `https://github.com/actions/runner/undefined`, so successful workflow +completion did not satisfy strict postflight. The `0.3.3` candidate preserves +the nonsecret runner metadata and requires `github-hosted` before isolated npm +calls. See the [release record](docs/RELEASING.md#published-032-with-failed-strict-postflight). +Hosts must wait for actual verified `0.3.3` publication before pinning the new helper, including through an alias. Existing Identity/Support `0.2.0` imports remain unchanged; no legacy data transition is automatic. diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index fe4105a..5c6d44e 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -3,10 +3,11 @@ ## Status **Stage:** Phases 1, 2, and 4 are complete; Phase 3 has its first production -consumer. Registry `@pegma/rate-limit@0.2.0` is published, and pegma.dev composes -the durable tier for its Identity surface. Registry `latest` remains `0.2.0`. -Current source is the **`0.3.2` -candidate, not published**, retaining exact Storage Core `0.4.0`. Published +consumer. pegma.dev composes the durable tier for its Identity surface. +Registry `latest` is published `0.3.2`; exact-byte and npm cryptographic checks +passed, but strict postflight rejected its authenticated builder identity. +It is not qualified for the planned helper adoption. Current source is the +**unpublished `0.3.3` candidate**, retaining exact Storage Core `0.4.0`. Published `0.2.0` predates the already-merged [PR #8 hardening](https://github.com/pegma-dev/rate-limit/pull/8) for immutable policy descriptors, counter kind/configuration bindings, and clock-skew grace. The candidate includes that hardening plus bounded global @@ -19,11 +20,14 @@ temporary verification repository, not the packing checkout. No release artifact or npm `0.3.0` bytes were published. Signed `v0.3.1` corrected that trust configuration and passed its gates/pack, then upload excluded hidden `.release/`: zero artifacts were retained, smoke/publication were skipped, and -no npm `0.3.1` release exists. The `0.3.2` candidate uses one nonhidden -preparation/digest/upload directory, with the helper API unchanged. Its own -review, gates, publication and registry verification remain required. See the -[failed-upload receipt](RELEASING.md#failed-031-upload-and-032-candidate). -Hosts must await verified `0.3.2` publication before adopting the new helper, +no npm `0.3.1` release exists. `0.3.2` corrected artifact discovery and published +the original prepared bytes. Its publisher retry reused the original artifact, +but authenticated provenance names `https://github.com/actions/runner/undefined`. +The `0.3.3` candidate preserves nonsecret runner metadata and requires +`github-hosted` before isolated npm calls, with the helper API unchanged. Its +own review, gates, signed identity, publication and strict registry verification +remain pending. See the [release record](RELEASING.md#published-032-with-failed-strict-postflight). +Hosts must await verified `0.3.3` publication before adopting the new helper, including an alias; existing Identity/Support `0.2.0` imports stay unchanged. The exact reviewed `0.0.0` package-name bootstrap remains published under @@ -201,7 +205,7 @@ collection over an injected Store). The memory tier must remain importable without a Store — a host wanting only abuse-dampening should not construct storage. TypeScript, vitest, the ecosystem's standard layout. -## `0.3.2` bounded-maintenance source candidate +## `0.3.3` bounded-maintenance source candidate `sweepDurableWindowsPage` is a root/durable export over the existing `rate-limit-windows` collection. One call makes one physical global scan page, @@ -232,8 +236,11 @@ retrying from the previous cursor can repeat work. The define the interface; current-head gates, review, exact publication, and host adoption remain release work. -Host aliases for this helper must pin `0.3.2` only after its actual verified -registry publication. A signed tag or GitHub release alone is not publication. +Host aliases for this helper must await actual verified `0.3.3` registry +publication. Published `0.3.2` did not pass strict postflight; a signed tag, +GitHub release or successful publisher job alone is not adoption qualification. +The [public postflight procedure](RELEASING.md#public-postflight-procedure) +records the required independent checks and acceptance criteria. Upgrading existing durable data is deliberate: use versioned policy names or an isolated Store namespace, or coordinate a policy-store reset. Immutable diff --git a/docs/RELEASING.md b/docs/RELEASING.md index f432fe0..caf7568 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -5,10 +5,12 @@ the hardened GitHub release workflow, npm trusted publishing, and provenance. The completed one-time manual `0.0.0` ceremony below exists as an audit record: npm could not configure a trusted publisher until `@pegma/rate-limit` existed. -As of 2026-11-08, npm `latest` is `0.2.0` and historical `bootstrap` is `0.0.0`. -Current source is the **unpublished `0.3.2` candidate**. The signed `0.3.0` and -`0.3.1` GitHub releases below did not publish npm versions; neither is a host -dependency or evidence of completed artifact/consumer verification. +As of 2026-11-08, npm `latest` is `0.3.2` and historical `bootstrap` is `0.0.0`. +`0.3.2` is published with exact original bytes and successful npm cryptographic +checks, but its strict postflight **failed** the authenticated builder-identity +policy. It is not qualified for the planned helper adoption. Current source is +the **unpublished `0.3.3` candidate**. The signed `0.3.0` and `0.3.1` GitHub +releases below did not publish npm versions. ## Release invariants @@ -38,6 +40,261 @@ OIDC job checks the tag again, downloads the sealed artifact outside a source checkout, verifies the preparation manifest digest and both tarball digests, and invokes npm from a fresh directory with empty configuration files and an allowlisted environment. It never executes repository code. +The `0.3.3` candidate preserves the nonsecret `RUNNER_ENVIRONMENT` value and +requires `github-hosted` before invoking npm in that isolated environment. + +## Public postflight procedure + +Run this after publication, without publication authority. A successful +`release:registry:check` establishes prepared-byte/registry identity only; it +does **not** verify npm signatures, Sigstore provenance, authenticated claims or +the public registry consumer. Every step below must pass before host adoption. +This procedure is an acceptance requirement, not a claim that the `0.3.3` +candidate has passed it. + +### Retain the original identity and compare bytes + +Use the original prepared artifact, not a fresh local pack or a recovery +attempt's newly created artifact. Independently retain its Actions artifact ID, +archive SHA-256, preparation-output manifest SHA-256, signed tag object/source +commit, repository/owner IDs and original publishing run/attempt. Bind them to +the exact reviewed release workflow and actual successful preparation/smoke +jobs. Inspect the artifact inventory: exactly `package-manifest.json` and its +named tarball, both regular files. Compare the archive and manifest digests +with those independently retained values before trusting their contents. + +In a POSIX shell, set `ORIGINAL_ZIP` to the retained archive, `PREPARED` to its +verified extraction, `RELEASE_SOURCE` to its reviewed tooling checkout, and +`NODE` and `NPM_CLI` to absolute paths for Node 24 and the reviewed, unpacked +npm `11.18.0` CLI. Authenticate the npm +tool's archive and extracted tree before use; the reviewed npm archive SHA-256 +is `73f6155215ebabf4ed96dca1f567c2372cc713c33af2e5b9b62fde4e92373e2e`. +Set `VERSION` to the stable version in the verified manifest, not `latest`. +Use OpenSSL for the digest/certificate inspection commands below. + +```sh +set -eu +PROOF=$(mktemp -d) +openssl dgst -sha256 "$ORIGINAL_ZIP" +openssl dgst -sha256 "$PREPARED/package-manifest.json" +openssl dgst -sha256 "$PREPARED/pegma-rate-limit-$VERSION.tgz" +openssl dgst -sha512 "$PREPARED/pegma-rate-limit-$VERSION.tgz" +openssl dgst -sha1 "$PREPARED/pegma-rate-limit-$VERSION.tgz" +cd "$RELEASE_SOURCE" +pnpm run release:registry:check -- --manifest "$PREPARED/package-manifest.json" \ + > "$PROOF/registry-check.stdout" 2> "$PROOF/registry-check.stderr" +``` + +Require the tool to report `exact`, with manifest/source/tag/version and both +tarball digests matching the retained original. A missing registry version is +not postflight success. Save its output. Also obtain fresh public version +metadata and the actual tarball, then compare the latter byte for byte: + +```sh +curl --disable --noproxy '*' --fail --silent --show-error --location --proto '=https' \ + "https://registry.npmjs.org/@pegma%2Frate-limit/$VERSION" \ + --output "$PROOF/registry-version.json" +curl --disable --noproxy '*' --fail --silent --show-error --location --proto '=https' \ + "https://registry.npmjs.org/@pegma/rate-limit/-/rate-limit-$VERSION.tgz" \ + --output "$PROOF/registry.tgz" +cmp "$PREPARED/pegma-rate-limit-$VERSION.tgz" "$PROOF/registry.tgz" +``` + +Require the metadata's exact name/version, exports and dependency pins to match +the prepared package. `dist.tarball` must be that canonical public-registry +URL; `dist.integrity` and `dist.shasum` must match the original SHA-512 SRI and +SHA-1. Signature and provenance metadata must be present. Save fresh independent +GitHub repository/owner IDs and the original release/job records separately; +values copied from the provenance itself cannot establish expected identity. + +### Verify an isolated public-registry installation + +Use a new directory outside every workspace, a new cache, empty user/global npm +configurations and an allowlisted child environment. This POSIX example passes +no npm/GitHub tokens, OIDC variables, proxy configuration, `NODE_OPTIONS` or +workspace dependency paths. Do not add credentials to make verification pass. + +```sh +mkdir "$PROOF/consumer" "$PROOF/home" "$PROOF/tmp" +: > "$PROOF/user.npmrc" +: > "$PROOF/global.npmrc" +clean() { + env -i PATH="$(dirname "$NODE"):/usr/bin:/bin" \ + HOME="$PROOF/home" TMPDIR="$PROOF/tmp" CI=true \ + npm_config_userconfig="$PROOF/user.npmrc" \ + npm_config_globalconfig="$PROOF/global.npmrc" \ + npm_config_cache="$PROOF/npm-cache" \ + npm_config_registry=https://registry.npmjs.org/ \ + npm_config_ignore_scripts=true npm_config_audit=false npm_config_fund=false \ + "$@" +} +cd "$PROOF/consumer" +clean "$NODE" --version +clean "$NODE" "$NPM_CLI" --version +printf '{"name":"rate-limit-registry-proof","private":true,"type":"module","dependencies":{"@pegma/rate-limit":"%s"}}\n' \ + "$VERSION" > package.json +clean "$NODE" "$NPM_CLI" install --ignore-scripts --no-audit --no-fund \ + --registry https://registry.npmjs.org/ > "$PROOF/install.stdout" 2> "$PROOF/install.stderr" +clean "$NODE" "$NPM_CLI" audit signatures --json --include-attestations \ + --registry https://registry.npmjs.org/ > "$PROOF/signatures.json" 2> "$PROOF/signatures.stderr" +``` + +Stop on any nonzero exit; check each command rather than masking failure with a +pipeline or continuing to imports. Require Node 24 and npm exactly `11.18.0`. +Inspect `package-lock.json`: `packages["node_modules/@pegma/rate-limit"]` must +have the exact version, original integrity, canonical public tarball URL, +unchanged exact dependencies, and no workspace/file link. Retain the lockfile. + +The actual audit must have empty `invalid` and `missing` arrays and exactly one +matching target in `verified`, including location +`node_modules/@pegma/rate-limit` and registry `https://registry.npmjs.org/`. +Require exactly one target `attestationBundles` entry whose `predicateType` is +`https://slsa.dev/provenance/v1`. Do not select the first bundle: it may be the +separate npm publish attestation. Only **after** that successful cryptographic +audit may the authenticated SLSA bundle be decoded for policy inspection. + +### Inspect authenticated certificate and provenance policy + +The commands below select and save that verified target bundle, emit its +certificate and decode its statement for the subsequent manual checks. They +do not perform cryptographic verification themselves: + +```sh +clean "$NODE" --input-type=module - "$PROOF/signatures.json" "$PROOF" "$VERSION" <<'NODE' +import assert from "node:assert/strict"; +import { X509Certificate } from "node:crypto"; +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +const [auditFile, directory, version] = process.argv.slice(2); +const audit = JSON.parse(readFileSync(auditFile, "utf8")); +assert.deepEqual(audit.invalid, []); +assert.deepEqual(audit.missing, []); +const targets = audit.verified.filter((entry) => + entry.name === "@pegma/rate-limit" && entry.version === version && + entry.location === "node_modules/@pegma/rate-limit" && + entry.registry === "https://registry.npmjs.org/"); +assert.equal(targets.length, 1); +const proofs = targets[0].attestationBundles.filter((entry) => + entry.predicateType === "https://slsa.dev/provenance/v1"); +assert.equal(proofs.length, 1); +const bundle = proofs[0].bundle; +const material = bundle.verificationMaterial; +const encoded = material.certificate?.rawBytes ?? + material.x509CertificateChain?.certificates[0]?.rawBytes; +assert.ok(typeof encoded === "string" && encoded.length <= 65536); +const certificate = new X509Certificate(Buffer.from(encoded, "base64")); +assert.equal(certificate.subjectAltName, + `URI:https://github.com/pegma-dev/rate-limit/.github/workflows/publish.yml@refs/tags/v${version}`); +const envelope = bundle.dsseEnvelope; +assert.equal(envelope.payloadType, "application/vnd.in-toto+json"); +assert.ok(typeof envelope.payload === "string" && envelope.payload.length <= 1048576); +const statement = JSON.parse(Buffer.from(envelope.payload, "base64").toString("utf8")); +writeFileSync(join(directory, "selected-slsa-bundle.json"), JSON.stringify(bundle, null, 2)); +writeFileSync(join(directory, "authenticated-certificate.pem"), certificate.toString()); +writeFileSync(join(directory, "authenticated-provenance.json"), JSON.stringify(statement, null, 2)); +NODE +openssl x509 -in "$PROOF/authenticated-certificate.pem" -noout -text \ + > "$PROOF/certificate-policy-review.txt" +``` + +The selected leaf certificate is +`verificationMaterial.certificate.rawBytes`, or the first certificate's +`rawBytes` in `verificationMaterial.x509CertificateChain.certificates`; it is +base64 DER. Inspect the saved certificate output and decoded provenance against +every requirement below, retaining the complete audit alongside them. Decoding +or displaying a certificate is not signature or Sigstore verification. + +Require **every** policy check below; record each result against the original +sealed artifact and independent GitHub observations: + +| Authenticated field | Required value | +| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Certificate URI SAN | Exactly `https://github.com/pegma-dev/rate-limit/.github/workflows/publish.yml@refs/tags/v`; no extra SAN identity. | +| Certificate Fulcio OIDC issuer extension `1.3.6.1.4.1.57264.1.1` | Exactly `https://token.actions.githubusercontent.com`. This is the extension value, not the certificate issuer DN. | +| Statement `_type` and `predicateType` | `https://in-toto.io/Statement/v1` and `https://slsa.dev/provenance/v1`. | +| `subject` | Exactly one: name `pkg:npm/%40pegma/rate-limit@`, with `digest.sha512` equal to the hexadecimal SHA-512 of the **original prepared tarball**. | +| `predicate.buildDefinition.buildType` | `https://slsa-framework.github.io/github-actions-buildtypes/workflow/v1`. | +| `buildDefinition.externalParameters.workflow` | Exact object: repository `https://github.com/pegma-dev/rate-limit`, path `.github/workflows/publish.yml`, ref `refs/tags/v`. | +| `buildDefinition.internalParameters.github` | `event_name` is `release`; `repository_id` and `repository_owner_id` match the independently retained GitHub IDs. | +| `buildDefinition.resolvedDependencies` | Exactly one: URI `git+https://github.com/pegma-dev/rate-limit@refs/tags/v`, with `digest.gitCommit` equal to the original signed source commit. | +| `predicate.runDetails.builder.id` | Exactly `https://github.com/actions/runner/github-hosted`. `/undefined` is a failure. | +| `runDetails.metadata.invocationId` | Exactly `https://github.com/pegma-dev/rate-limit/actions/runs//attempts/`. | + +Here `buildDefinition` and `runDetails` are under `predicate`. An idempotent +skip-only retry can leave genuine attempt-1 provenance after attempt 2 succeeds; +compare the original physical publication, not merely the most recent attempt. +Confirm the signed tag/source, successful current-head review/CI and actual +release jobs separately. The protected `npm-publish` environment and normal +owner approval are established by the immutable workflow and actual job record; +do not invent an attested SLSA environment field. + +### Exercise the public exports and retain a result + +Only after byte, cryptographic and authenticated-policy checks pass, save this +consumer as `$PROOF/consumer/consumer.mjs` and run it in that directory. It uses +the public root/memory/durable exports and the actual Storage Core memory +adapter, following the release smoke imports and synthetic limiter checks: + +```js +import assert from "node:assert/strict"; +import * as root from "@pegma/rate-limit"; +import * as memory from "@pegma/rate-limit/memory"; +import * as durable from "@pegma/rate-limit/durable"; +import { createMemoryStore } from "@pegma/storage-core"; + +assert.equal(root.createMemoryLimiter, memory.createMemoryLimiter); +assert.equal(root.sweepDurableWindowsPage, durable.sweepDurableWindowsPage); +let time = "2026-11-08T00:00:00.000Z"; +const clock = { now: () => time }; +const policy = root.defineRateLimitPolicy({ + name: "release-proof:" + process.argv[2], + limit: 1, + windowMs: 1000, +}); +const dampener = root.createMemoryLimiter(policy, { clock }); +assert.equal((await dampener.allow("opaque")).allowed, true); +assert.equal((await dampener.allow("opaque")).allowed, false); +const store = createMemoryStore(); +const limiter = root.createDurableLimiter(policy, store, { + clock, + maxClockSkewMs: 0, +}); +assert.equal((await limiter.allow("opaque")).allowed, true); +assert.equal((await limiter.allow("opaque")).allowed, false); +time = "2026-11-08T00:00:02.000Z"; +const page = await root.sweepDurableWindowsPage(store, { + limit: 10, + clock, + maxClockSkewMs: 0, +}); +assert.deepEqual(page, { scanned: 2, deleted: 1, nextCursor: null }); +assert.equal((await limiter.allow("opaque")).allowed, true); +console.log( + JSON.stringify({ + version: process.argv[2], + publicRootsImported: 3, + memoryBoundary: true, + syntheticMemoryStore: true, + pagedSweep: page, + }), +); +``` + +```sh +clean "$NODE" consumer.mjs "$VERSION" > "$PROOF/consumer-result.json" 2> "$PROOF/consumer.stderr" +``` + +Require exit zero and those assertions, then recheck fresh registry metadata +and downloaded bytes against the original. This synthetic memory-backed +consumer is not production durability, a host deployment or client acceptance. +Retain the original ZIP/manifest/tarball and independent digests/Actions IDs, +registry metadata/bytes, Node/npm versions, install output/lockfile, actual +audit, selected bundle/certificate/decoded claims, policy checklist, consumer +output and a dated result receipt. The receipt must bind those inputs and mark +PASS only when **all** release, crypto, policy and consumer checks pass. +On any failure, retain the evidence and mark FAIL/hold; do not publish a host +alias, waive the builder policy, repack, retag or treat decoding as proof. +In particular this procedure does not qualify the existing `0.3.2` release. @@ -65,7 +322,9 @@ or treat the failed preparation as publication. The correction used reviewed added explicit trust to the packing checkout without changing limiter/helper behavior. Its later failure was a separate upload boundary, recorded next. -## Failed `0.3.1` upload and `0.3.2` candidate + + +## Failed `0.3.1` upload The signed annotated [`v0.3.1` release](https://github.com/pegma-dev/rate-limit/releases/tag/v0.3.1), @@ -89,10 +348,10 @@ Preserve the signed `v0.3.1` tag, source and failed-run record alongside the earlier `v0.3.0` history. Do not replace a tag, reuse either version for changed source, or treat a GitHub release as npm availability. -The new `0.3.2` candidate keeps the limiter/helper API and signing correction -unchanged. Its producer uses explicit `--output` at the nonhidden -`${RUNNER_TEMP}/rate-limit-prepared` directory, computes the manifest digest -there, and uploads that same directory through `${{ runner.temp }}`. Hidden-file +`0.3.2` kept the limiter/helper API and signing correction unchanged. Its +producer used explicit `--output` at the nonhidden +`${RUNNER_TEMP}/rate-limit-prepared` directory, computed the manifest digest +there, and uploaded that same directory through `${{ runner.temp }}`. Hidden-file exclusion remains enabled (`include-hidden-files: false`); recovery does not broaden artifact collection. Validate the actual YAML producer/digest/upload wiring and file discovery with @@ -104,16 +363,62 @@ Its [search implementation](https://github.com/actions/upload-artifact/blob/330a defines the glob options and directory filtering used by the [regression](../scripts/release-artifact-discovery.test.mjs). The test exercises that public glob API and filtering only; it does not execute the vendored action -bundle or upload bytes. Current-head review, full Node 22/24 -gates, the new signed release identity, retained exact artifact, isolated smoke, -publication and registry verification remain required for this candidate. - -Only after `0.3.2` actually publishes and its original prepared bytes and -registry release are verified may a host pin it, including through an npm -alias. This does not migrate legacy `0.2.0` counters or change existing host -deployment state; existing Identity/Support `0.2.0` imports remain unchanged. -No repeated bootstrap, token fallback or signature bypass is -part of this recovery. +bundle or upload bytes. The resulting `0.3.2` publication had the separate +provenance-policy failure recorded next. + +## Published `0.3.2` with failed strict postflight + +The [`v0.3.2` release](https://github.com/pegma-dev/rate-limit/releases/tag/v0.3.2) +binds signed source +[`a50469dce0c123865ef3540819060509a936ec38`](https://github.com/pegma-dev/rate-limit/commit/a50469dce0c123865ef3540819060509a936ec38). +[Run `42515823225`](https://github.com/pegma-dev/rate-limit/actions/runs/42515823225) +attempt 1 executed +[preparation `128838497494`](https://github.com/pegma-dev/rate-limit/actions/runs/42515823225/job/128838497494) +and [isolated smoke `128838619041`](https://github.com/pegma-dev/rate-limit/actions/runs/42515823225/job/128838619041). +Original artifact `13631327333` contains the sealed manifest and tarball; its +tarball SHA-256 is +`1bc74d4a7f5ca239bbee80097a815bbe3ae04f45eb60cc40bd53499139422802`. +The [first publisher](https://github.com/pegma-dev/rate-limit/actions/runs/42515823225/job/128838677268) +published but failed waiting for registry visibility. The +[attempt-2 publisher `128841340300`](https://github.com/pegma-dev/rate-limit/actions/runs/42515823225/job/128841340300) +later completed idempotently using that **same original artifact**. Preparation +and smoke were not executed again; carried-forward attempt-2 job aliases are +not fresh pack or consumer proof. + +Registry metadata and downloaded `0.3.2` tarball bytes match the original +artifact. Actual npm `11.18.0` ECDSA signature and Sigstore verification passed. +The authenticated SLSA provenance also matches the repository, source commit, +release tag and original attempt-1 invocation. Its builder URI, however, is +`https://github.com/actions/runner/undefined`, rather than the required +`https://github.com/actions/runner/github-hosted`. Strict postflight therefore +remains **FAILED**, despite publication and a successful workflow retry. +Cryptographic validity does not waive the authenticated-claims policy. +Checks downstream of that failure, including strict postflight's consumer +execution, did not complete; the earlier preparation smoke remains separate. + +The immutable +[`0.3.2` publisher environment filter](https://github.com/pegma-dev/rate-limit/blob/a50469dce0c123865ef3540819060509a936ec38/.github/workflows/publish.yml#L396) +did not preserve `RUNNER_ENVIRONMENT` for npm. The reviewed +[`npm@11.18.0` provenance generator](https://github.com/npm/cli/blob/v11.18.0/workspaces/libnpmpublish/lib/provenance.js#L58) +uses that value to construct the builder URI. These source facts explain the +observed missing runner metadata; they do not turn the failed proof into a pass. +They do not establish that the actual runner was self-hosted or untrusted. + +## `0.3.3` provenance-metadata candidate + +Current source preserves the nonsecret `RUNNER_ENVIRONMENT` value in the +isolated npm environment and refuses to invoke that publisher's npm commands +unless it is `github-hosted`. The limiter and maintenance-helper API are +unchanged. Its own review, current-head Node 22/24 gates, new protected signed +release identity, retained exact artifact, isolated smoke, publication and +strict postflight remain pending. + +Hosts must await verified `0.3.3` publication before pinning the new helper, +including through an alias. Existing Identity/Support `0.2.0` imports and +counters remain unchanged until an explicit host transition. Preserve all +`0.3.0`, `0.3.1` and `0.3.2` tags, releases, artifacts and failure receipts. +Do not weaken the builder policy, move a tag, unpublish/reuse a version, repeat +bootstrap or add a token fallback to recover. ## One-time `0.0.0` package-name bootstrap @@ -126,7 +431,8 @@ During bootstrap npm also assigned the default `latest` tag to `0.0.0`. The oper to remove it, but npm rejected the request with HTTP 400. The immutable bootstrap remains exact and the `bootstrap` tag remains correct. The later normal `0.1.0` publication moved `latest` to the first advertised version; -`latest` has since advanced to `0.2.0`. +`latest` has since advanced to published `0.3.2`, whose strict-postflight +limitation is recorded above. The steps below are retained only as the ceremony's audit and recovery record. @@ -295,5 +601,6 @@ npm dist-tag ls @pegma/rate-limit For that ceremony the registry check had to report `@pegma/rate-limit@0.1.0: exact`, with `latest` at `0.1.0` and `bootstrap` at -`0.0.0`. Current `latest` is `0.2.0`; do not retag an older release or repeat -the bootstrap to prepare the unpublished `0.3.2` candidate. +`0.0.0`. Current `latest` is published `0.3.2`, with the strict-postflight +limitation above; do not retag an older release or repeat the bootstrap to +prepare the unpublished `0.3.3` candidate. diff --git a/package.json b/package.json index 398ce68..f7789d1 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "release:pack": "node scripts/release-package.mjs pack", "release:publish": "node scripts/release-package.mjs publish", "release:registry:check": "node scripts/release-package.mjs registry-check", - "test": "pnpm run build && vitest run && node --test scripts/configure-release-signing.test.mjs scripts/release-workflow-signing.test.mjs scripts/release-artifact-discovery.test.mjs" + "test": "pnpm run build && vitest run && node --test scripts/configure-release-signing.test.mjs scripts/release-workflow-signing.test.mjs scripts/release-artifact-discovery.test.mjs scripts/release-workflow-environment.test.mjs" }, "devDependencies": { "@actions/glob": "0.5.0", diff --git a/packages/rate-limit/README.md b/packages/rate-limit/README.md index 186530e..391f87a 100644 --- a/packages/rate-limit/README.md +++ b/packages/rate-limit/README.md @@ -9,27 +9,33 @@ Two explicitly named application rate-limit tiers: abuse-critical operations. > [!IMPORTANT] -> Current source is the **`0.3.2` candidate, not published**. Registry `latest` -> remains `0.2.0`, which -> predates the merged descriptor/configuration hardening and the bounded -> global sweep described here. `0.1.0` was the first advertised release, published through -> trusted-publisher OIDC with provenance. The exact reviewed `0.0.0` +> Current source is the **unpublished `0.3.3` candidate**. Registry `latest` +> is `0.3.2`: original-byte and npm cryptographic checks passed, but strict +> postflight failed the authenticated builder-identity policy. It is not +> qualified for the planned helper adoption. `0.1.0` was the first advertised +> release, published through trusted-publisher OIDC with provenance. The exact reviewed `0.0.0` > package-name bootstrap remains isolated under the `bootstrap` dist-tag and > is never advertised as the current supported release. -The API and storage behavior below describe candidate source. Use an exact -published version only after its release verification and an explicit host -storage/configuration transition. +The API and storage behavior below describe `0.3.3` candidate source; the +limiter/helper API is unchanged from `0.3.2`. Use an exact published version +only after its release verification and an explicit host storage/configuration +transition. Follow the +[public postflight procedure](https://github.com/pegma-dev/rate-limit/blob/main/docs/RELEASING.md#public-postflight-procedure); +an exact-byte registry check alone is insufficient. The signed `v0.3.0` tag and GitHub release exist, but preparation failed before packing: no release artifact or npm `0.3.0` bytes were published. Signed `v0.3.1` fixed checkout trust and passed its gates and pack, but upload excluded hidden `.release/`, retained zero artifacts, and skipped smoke/publication. -There is no npm `0.3.1` release. The `0.3.2` candidate moves preparation, -digesting and upload to the same nonhidden directory without changing the -limiter/helper API. The immutable failure history and new candidate are recorded in +There is no npm `0.3.1` release. `0.3.2` corrected artifact discovery and published +the original prepared bytes, but its authenticated provenance names +`https://github.com/actions/runner/undefined`; strict postflight failed despite +successful npm cryptographic checks and an idempotent publisher retry. The +`0.3.3` candidate preserves nonsecret runner metadata and requires +`github-hosted` before isolated npm calls. The immutable history is recorded in [release operations](https://github.com/pegma-dev/rate-limit/blob/main/docs/RELEASING.md). -No host should pin a new helper alias until actual `0.3.2` publication and +No host should pin a new helper alias until actual `0.3.3` publication and exact-artifact verification. Existing Identity/Support `0.2.0` composition and legacy counter storage remain separate from that adoption. @@ -136,7 +142,8 @@ row. Checks against that malformed row still fail closed. ## Bounded global cleanup -The candidate adds this interface at the root and durable subpath, defined in +The global helper exposes this interface at the root and durable subpath, defined +in [the actual source](https://github.com/pegma-dev/rate-limit/blob/main/packages/rate-limit/src/durable.ts): ```ts @@ -212,9 +219,9 @@ delete arbitrary malformed rows, or mistake the global sweep for a migration of previously published `0.2.0` data. A host adopting the new helper through an npm alias must wait for actual -`0.3.2` publication and registry verification before pinning that alias. Existing -`0.2.0` consumers and counters need their own deliberate migration; the new -release does not convert them automatically. +`0.3.3` publication and strict registry verification before pinning that alias. +Existing `0.2.0` consumers and counters need their own deliberate migration; +the new release does not convert them automatically. ## License diff --git a/packages/rate-limit/package.json b/packages/rate-limit/package.json index ca5535b..1da8849 100644 --- a/packages/rate-limit/package.json +++ b/packages/rate-limit/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/rate-limit", - "version": "0.3.2", + "version": "0.3.3", "description": "Explicit per-instance sliding-window and shared durable fixed-window rate limiters.", "license": "MIT", "type": "module", diff --git a/scripts/release-package.mjs b/scripts/release-package.mjs index ca2f59b..7a8c3af 100644 --- a/scripts/release-package.mjs +++ b/scripts/release-package.mjs @@ -63,6 +63,7 @@ const NPM_ENVIRONMENT_KEYS = new Set([ "HOMEPATH", "PATH", "PATHEXT", + "RUNNER_ENVIRONMENT", "RUNNER_TEMP", "SYSTEMDRIVE", "SYSTEMROOT", @@ -82,6 +83,7 @@ export function isolatedNpmEnvironment( const upper = key.toUpperCase(); if ( value !== undefined && + (upper !== "RUNNER_ENVIRONMENT" || key === "RUNNER_ENVIRONMENT") && (NPM_ENVIRONMENT_KEYS.has(upper) || upper.startsWith("GITHUB_") || upper.startsWith("ACTIONS_ID_TOKEN_")) @@ -106,6 +108,21 @@ function runNpm(arguments_, options = {}) { chmodSync(userConfig, 0o600); chmodSync(globalConfig, 0o600); try { + const environment = isolatedNpmEnvironment(options.env ?? process.env, { + cache, + globalConfig, + userConfig, + }); + // The alternate publisher is not the normal OIDC workflow. If invoked, + // require truthful builder metadata in the actual filtered npm child too. + // Ordinary local npm reads/checks do not acquire this publishing constraint. + if ( + (options.provenancePublishing === true || + (arguments_[0] === "publish" && arguments_.includes("--provenance"))) && + environment.RUNNER_ENVIRONMENT !== "github-hosted" + ) { + fail("GitHub-hosted runner metadata is required for provenance"); + } const npmCli = join( dirname(process.execPath), "node_modules", @@ -122,11 +139,7 @@ function runNpm(arguments_, options = {}) { return run(command, commandArguments, { ...options, cwd: options.cwd ?? sandbox, - env: isolatedNpmEnvironment(options.env ?? process.env, { - cache, - globalConfig, - userConfig, - }), + env: environment, shell: false, }); } finally { @@ -860,7 +873,10 @@ function registryIntegrity(name, version) { } function requireTrustedPublishingNpm() { - const version = runNpm(["--version"], { capture: true }).stdout.trim(); + const version = runNpm(["--version"], { + capture: true, + provenancePublishing: true, + }).stdout.trim(); const match = /^(\d+)\.(\d+)\.(\d+)(?:-.+)?$/u.exec(version); if (match === null) { fail(`could not parse npm version ${version}`); diff --git a/scripts/release-workflow-environment.test.mjs b/scripts/release-workflow-environment.test.mjs new file mode 100644 index 0000000..c8106ea --- /dev/null +++ b/scripts/release-workflow-environment.test.mjs @@ -0,0 +1,359 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { test } from "node:test"; +import { Script } from "node:vm"; +import { parse } from "yaml"; + +const WORKFLOW = new URL("../.github/workflows/publish.yml", import.meta.url); +const STEP = "Verify and publish the prepared tarball"; +const START = "const keep = new Set([\n"; +const RUNNER = "const runNpm = (arguments_, allowFailure = false) => {"; +const END = 'const npmVersion = runNpm(["--version"], true).stdout.trim();'; +const OFFICIAL_REGISTRY = "https://registry.npmjs.org/"; +const RUNNER_REFUSAL = + "GitHub-hosted runner metadata is required for provenance"; + +function one(text, pattern, description) { + const matches = [...text.matchAll(pattern)]; + assert.equal(matches.length, 1, "Expected one " + description); + return matches[0]; +} + +/** Parse the actual pinned YAML; never run its shell, artifact, npm or publish stages. */ +async function boundary() { + const manifest = JSON.parse( + await readFile(new URL("../package.json", import.meta.url), "utf8"), + ); + assert.equal(manifest.devDependencies.yaml, "2.9.1"); + const document = parse(await readFile(WORKFLOW, "utf8")); + const steps = document.jobs.publish.steps.filter( + (step) => step.name === STEP, + ); + assert.equal(steps.length, 1, "Expected the actual publishing step"); + assert.equal(steps[0].shell, "bash"); + assert.equal(typeof steps[0].run, "string"); + const body = one( + steps[0].run.replace(/\r\n/gu, "\n"), + /^set -euo pipefail\nnode <<'NODE'\n([\s\S]+)\nNODE\n?$/gu, + "supported inline Node body", + )[1]; + const registry = JSON.parse( + one( + body, + /^const REGISTRY = ("[^"\n]+");$/gmu, + "actual registry constant", + )[1], + ); + assert.equal(registry, OFFICIAL_REGISTRY); + assert.equal( + body.split(START).length, + 2, + "Expected one environment start marker", + ); + assert.equal( + body.split(RUNNER).length, + 2, + "Expected one npm runner definition", + ); + assert.equal( + body.split(END).length, + 2, + "Expected one automatic npm-call marker", + ); + const start = body.indexOf(START); + const runner = body.indexOf(RUNNER); + const end = body.indexOf(END); + assert.ok( + start < runner && runner < end, + "Environment admission and runner must precede the automatic npm call", + ); + const source = body.slice(start, end); + assert.doesNotMatch( + body.slice(start, runner), + /\b(?:spawnSync|runNpm|require|import|fetch|readFileSync|writeFileSync)\b/u, + "Environment construction must contain no command or filesystem calls", + ); + assert.match( + body.slice(runner, end), + /^const runNpm = \(arguments_, allowFailure = false\) => \{[\s\S]+\n\s*\};\s*$/u, + "Capture must finish at the actual npm runner's closing boundary", + ); + return { source, registry }; +} + +/** + * Execute only the captured environment/runner slice with inert process/paths. + * The actual runner receives --version through a capturing stub, never a child + * process. No real environment, filesystem, network or credentials enter the VM. + * These tests establish a producer boundary, not OIDC/Sigstore proof. + */ +function replay(captured, environment, calls = []) { + const configDirectory = join("synthetic-release-only", "private-config"); + const publishDirectory = join("synthetic-release-only", "empty-publish-cwd"); + const userConfig = join(configDirectory, "user.npmrc"); + const globalConfig = join(configDirectory, "global.npmrc"); + const input = Object.freeze({ ...environment }); + const script = new Script( + captured.source + + '\n({ environment: npmEnvironment, probe: runNpm(["--version"], true) });', + { + filename: "captured-publish-environment-only.js", + }, + ); + const result = script.runInNewContext( + { + process: Object.freeze({ env: input }), + configDirectory, + publishDirectory, + userConfig, + globalConfig, + REGISTRY: captured.registry, + join, + spawnSync(command, arguments_, options) { + assert.equal(command, "npm", "Only the inert npm stub is supported"); + assert.deepEqual( + Array.from(arguments_), + ["--version"], + "No publish/install/registry command may enter this replay", + ); + calls.push({ + command, + arguments: Array.from(arguments_), + options: { ...options }, + environmentSnapshot: + options.env === undefined + ? undefined + : Object.fromEntries(Object.entries(options.env)), + }); + return { status: 0, stdout: "11.18.0\n", stderr: "" }; + }, + fail(message) { + throw new Error(message); + }, + }, + { + timeout: 1000, + contextCodeGeneration: { strings: false, wasm: false }, + }, + ); + return { + // Detach the cross-realm object; values are these fixture strings only. + environment: Object.fromEntries(Object.entries(result.environment)), + constructedEnvironment: result.environment, + calls, + probe: result.probe, + input, + publishDirectory, + userConfig, + globalConfig, + cache: join(configDirectory, "cache"), + }; +} + +function requireNpmEnvironment(result) { + assert.equal( + result.calls.length, + 1, + "Expected exactly one inert version probe", + ); + const call = result.calls[0]; + assert.equal( + call.options.env, + result.constructedEnvironment, + "Actual npm runner must receive exactly the constructed filtered environment", + ); + assert.deepEqual(call.environmentSnapshot, result.environment); + assert.deepEqual(call.arguments, ["--version"]); + assert.equal(call.command, "npm"); + assert.equal(call.options.cwd, result.publishDirectory); + assert.equal(call.options.encoding, "utf8"); + assert.equal(call.options.stdio, "pipe"); + assert.equal(result.probe.status, 0); + assert.equal(result.probe.stdout, "11.18.0\n"); +} + +function metadata() { + return { + CI: "1", + PATH: "synthetic-native-command-path", + HOME: "synthetic-home", + RUNNER_TEMP: "synthetic-runner-temp", + RUNNER_ENVIRONMENT: "github-hosted", + GITHUB_ACTIONS: "true", + GITHUB_EVENT_NAME: "release", + GITHUB_REPOSITORY: "pegma-dev/rate-limit", + GITHUB_REPOSITORY_ID: "1000001", + GITHUB_REPOSITORY_OWNER: "pegma-dev", + GITHUB_REPOSITORY_OWNER_ID: "1000002", + GITHUB_SERVER_URL: "https://github.com", + GITHUB_API_URL: "https://api.github.com", + GITHUB_REF: "refs/tags/v0.3.3", + GITHUB_REF_TYPE: "tag", + GITHUB_SHA: "a".repeat(40), + GITHUB_WORKFLOW_REF: + "pegma-dev/rate-limit/.github/workflows/publish.yml@refs/tags/v0.3.3", + GITHUB_WORKFLOW_SHA: "b".repeat(40), + GITHUB_RUN_ID: "12345", + GITHUB_RUN_NUMBER: "100", + GITHUB_RUN_ATTEMPT: "1", + GITHUB_WORKFLOW: "Publish", + GITHUB_JOB: "publish", + GITHUB_ACTOR: "synthetic-release-author", + GITHUB_ACTOR_ID: "1000003", + ACTIONS_ID_TOKEN_REQUEST_URL: + "https://token.actions.githubusercontent.com/synthetic-test-only", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "synthetic-oidc-request-not-a-credential", + }; +} + +test("actual YAML environment retains github-hosted and needed GitHub/OIDC metadata", async () => { + const source = metadata(); + const result = replay(await boundary(), source); + requireNpmEnvironment(result); + for (const [name, value] of Object.entries(source)) { + assert.equal( + result.environment[name], + value, + "Required metadata lost: " + name, + ); + } + assert.deepEqual(result.input, source, "Admission must not mutate its input"); +}); + +test("actual YAML rebuilds isolated npm configuration and drops ambient credential/config poison", async () => { + const poison = { + NPM_TOKEN: "synthetic-npm-token", + NODE_AUTH_TOKEN: "synthetic-node-auth-token", + GH_TOKEN: "synthetic-gh-token", + AWS_ACCESS_KEY_ID: "synthetic-aws-key", + AWS_SECRET_ACCESS_KEY: "synthetic-aws-secret", + AZURE_CLIENT_SECRET: "synthetic-azure-secret", + NPM_CONFIG_USERCONFIG: "untrusted-user-config", + NPM_CONFIG_GLOBALCONFIG: "untrusted-global-config", + NPM_CONFIG_CACHE: "untrusted-cache", + NPM_CONFIG_REGISTRY: "https://untrusted.example.invalid/", + NPM_CONFIG_PROVENANCE: "false", + NPM_CONFIG_IGNORE_SCRIPTS: "false", + npm_config_registry: "https://lowercase.example.invalid/", + npm_config_userconfig: "untrusted-lowercase-config", + npm_config_provenance: "false", + NODE_OPTIONS: "--require synthetic-untrusted-hook.js", + node_options: "--require synthetic-lowercase-hook.js", + NODE_PATH: "synthetic-untrusted-module-path", + HTTP_PROXY: "https://synthetic-proxy.example.invalid/", + HTTPS_PROXY: "https://synthetic-tls-proxy.example.invalid/", + ALL_PROXY: "socks://synthetic-all-proxy.example.invalid/", + NO_PROXY: "synthetic-bypass.example.invalid", + http_proxy: "https://synthetic-lowercase-proxy.example.invalid/", + https_proxy: "https://synthetic-lowercase-tls-proxy.example.invalid/", + all_proxy: "socks://synthetic-lowercase-all-proxy.example.invalid/", + no_proxy: "synthetic-lowercase-bypass.example.invalid", + NODE_EXTRA_CA_CERTS: "synthetic-untrusted-root-ca.pem", + node_extra_ca_certs: "synthetic-lowercase-root-ca.pem", + RELEASE_ALLOWED_SIGNERS: "synthetic-signers-not-needed-by-npm", + }; + const result = replay(await boundary(), { ...metadata(), ...poison }); + requireNpmEnvironment(result); + const replacement = { + NPM_CONFIG_USERCONFIG: result.userConfig, + NPM_CONFIG_GLOBALCONFIG: result.globalConfig, + NPM_CONFIG_CACHE: result.cache, + NPM_CONFIG_REGISTRY: OFFICIAL_REGISTRY, + }; + for (const name of Object.keys(poison)) { + if (Object.hasOwn(replacement, name)) { + assert.equal(result.environment[name], replacement[name]); + assert.notEqual(result.environment[name], poison[name]); + } else { + assert.equal( + Object.hasOwn(result.environment, name), + false, + "Ambient poison survived: " + name, + ); + } + } + assert.equal(result.environment.RUNNER_ENVIRONMENT, "github-hosted"); +}); + +for (const [name, value] of [ + ["missing", undefined], + ["empty", ""], + ["self-hosted", "self-hosted"], + ["unknown", "unknown-runner-kind"], + ["different case", "GITHUB-HOSTED"], + ["whitespace padded", "github-hosted "], +]) { + test( + "actual pre-npm boundary refuses " + name + " runner metadata", + async () => { + const captured = await boundary(); + const environment = metadata(); + if (value === undefined) delete environment.RUNNER_ENVIRONMENT; + else environment.RUNNER_ENVIRONMENT = value; + const calls = []; + assert.throws(() => replay(captured, environment, calls), { + message: RUNNER_REFUSAL, + }); + assert.deepEqual( + calls, + [], + "Invalid runner must fail before the version probe", + ); + }, + ); +} + +test("lowercase-only runner metadata cannot replace the canonical npm provenance input", async () => { + const captured = await boundary(); + const environment = metadata(); + delete environment.RUNNER_ENVIRONMENT; + environment.runner_environment = "github-hosted"; + const calls = []; + assert.throws(() => replay(captured, environment, calls), { + message: RUNNER_REFUSAL, + }); + assert.deepEqual(calls, []); +}); + +test("removing the actual keep entry reproduces the original lost-runner metadata refusal", async () => { + const captured = await boundary(); + const entry = /^\s*"RUNNER_ENVIRONMENT",\n/gmu; + one(captured.source, entry, "runner keep entry"); + const withoutRunner = { + ...captured, + source: captured.source.replace(entry, ""), + }; + const calls = []; + assert.throws(() => replay(withoutRunner, metadata(), calls), { + message: RUNNER_REFUSAL, + }); + assert.deepEqual(calls, []); +}); + +for (const [name, replacement] of [ + ["omitted child environment", ""], + ["ambient process environment", "env: process.env,\n"], +]) { + test( + "disconnecting the actual runner via " + name + " fails the child contract", + async () => { + const captured = await boundary(); + const binding = /^\s*env: npmEnvironment,\n/gmu; + one(captured.source, binding, "actual npm child environment binding"); + const disconnected = { + ...captured, + source: captured.source.replace(binding, replacement), + }; + const result = replay(disconnected, { + ...metadata(), + NODE_AUTH_TOKEN: "synthetic-ambient-poison", + HTTPS_PROXY: "https://synthetic-ambient-proxy.example.invalid/", + }); + assert.throws( + () => requireNpmEnvironment(result), + /Actual npm runner must receive exactly the constructed filtered environment/u, + ); + }, + ); +} diff --git a/test/release-package.test.ts b/test/release-package.test.ts index c9b68c9..0403ece 100644 --- a/test/release-package.test.ts +++ b/test/release-package.test.ts @@ -8,11 +8,16 @@ import { } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; +import { createHash } from "node:crypto"; +import { spawnSync } from "node:child_process"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.mock("node:child_process", () => ({ spawnSync: vi.fn() })); import { isolatedNpmEnvironment, + publishPrepared, verifyReleaseInventory, // @ts-expect-error TypeScript does not emit declarations for repository scripts. } from "../scripts/release-package.mjs"; @@ -26,6 +31,8 @@ async function temporaryDirectory(prefix: string): Promise { } afterEach(async () => { + vi.unstubAllEnvs(); + vi.mocked(spawnSync).mockReset(); await Promise.all( temporaryDirectories .splice(0) @@ -94,11 +101,17 @@ describe("release artifact boundaries", () => { GITHUB_ACTIONS: "true", HOME: "/home/runner", PATH: "/bin", + RUNNER_ENVIRONMENT: "github-hosted", + runner_environment: "self-hosted", + Runner_Environment: "self-hosted", + RUNNER_ENVIRONMENT_POISON: "github-hosted", HTTPS_PROXY: "https://proxy.test", NODE_AUTH_TOKEN: "registry-token", NODE_EXTRA_CA_CERTS: "/tmp/extra.pem", NODE_OPTIONS: "--require hook.js", + NODE_TLS_REJECT_UNAUTHORIZED: "0", NPM_CONFIG_USERCONFIG: "/tmp/untrusted.npmrc", + NPM_CONFIG_PROVENANCE: "false", NPM_TOKEN: "registry-token", npm_config_registry: "https://example.test/", }, @@ -116,6 +129,7 @@ describe("release artifact boundaries", () => { GITHUB_ACTIONS: "true", HOME: "/home/runner", PATH: "/bin", + RUNNER_ENVIRONMENT: "github-hosted", NPM_CONFIG_CACHE: "/tmp/npm-cache", NPM_CONFIG_GLOBALCONFIG: "/tmp/global.npmrc", NPM_CONFIG_REGISTRY: "https://registry.npmjs.org/", @@ -126,14 +140,167 @@ describe("release artifact boundaries", () => { "NODE_AUTH_TOKEN", "NODE_EXTRA_CA_CERTS", "NODE_OPTIONS", + "NODE_TLS_REJECT_UNAUTHORIZED", + "NPM_CONFIG_PROVENANCE", "NPM_TOKEN", "npm_config_registry", + "runner_environment", + "Runner_Environment", + "RUNNER_ENVIRONMENT_POISON", ]) { expect(environment).not.toHaveProperty(key); } }); }); +describe("alternate publisher provenance environment", () => { + const refusal = "GitHub-hosted runner metadata is required for provenance"; + + function publishingContext(value: string | undefined) { + vi.stubEnv("GITHUB_ACTIONS", "true"); + vi.stubEnv("GITHUB_EVENT_NAME", "release"); + vi.stubEnv("RUNNER_ENVIRONMENT", value); + } + + it.each([ + undefined, + "", + "undefined", + "self-hosted", + "GITHUB-HOSTED", + " github-hosted", + "github-hosted ", + ])( + "refuses actual alternate publish entry before any child command for %s", + async (value) => { + publishingContext(value); + await expect(publishPrepared()).rejects.toThrow(refusal); + expect(spawnSync).not.toHaveBeenCalled(); + }, + ); + + it("does not promote a case alias into the canonical provenance input", async () => { + publishingContext(undefined); + vi.stubEnv("runner_environment", "github-hosted"); + await expect(publishPrepared()).rejects.toThrow(refusal); + expect(spawnSync).not.toHaveBeenCalled(); + }); + + it("leaves the exported filter usable for ordinary local reads without a hosted-runner constraint", () => { + const paths = { + cache: "/tmp/cache", + userConfig: "/tmp/user.npmrc", + globalConfig: "/tmp/global.npmrc", + }; + expect(() => isolatedNpmEnvironment({ PATH: "/bin" }, paths)).not.toThrow(); + expect(isolatedNpmEnvironment({ PATH: "/bin" }, paths)).not.toHaveProperty( + "RUNNER_ENVIRONMENT", + ); + expect( + isolatedNpmEnvironment({ RUNNER_ENVIRONMENT: "self-hosted" }, paths), + ).toHaveProperty("RUNNER_ENVIRONMENT", "self-hosted"); + }); + + it("rechecks the actual filtered publish child after a valid version probe and ordinary registry query", async () => { + publishingContext("github-hosted"); + vi.stubEnv("NODE_AUTH_TOKEN", "synthetic-poison-token"); + vi.stubEnv("NPM_TOKEN", "synthetic-poison-token"); + vi.stubEnv("NODE_OPTIONS", "--require synthetic-poison-hook.js"); + const directory = await temporaryDirectory("rate-limit-alternate-control-"); + const source = JSON.parse( + await readFile(resolve("packages/rate-limit/package.json"), "utf8"), + ) as { + name: string; + version: string; + exports: Record>; + }; + // Opaque control-flow fixture, not a valid packed release or provenance + // claim. The existing verifier reads its real bytes/digests/inventory; ONLY + // child commands are mocked and no Git/npm/network command executes. + const bytes = Buffer.from("Synthetic alternate-publisher refusal fixture."); + const integrity = + "sha512-" + createHash("sha512").update(bytes).digest("base64"); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + const commit = "c".repeat(40); + const tag = "v" + source.version; + const tarball = "pegma-rate-limit-" + source.version + ".tgz"; + const files = [ + ...new Set([ + "package.json", + "README.md", + "LICENSE", + ...Object.values(source.exports).flatMap((entry) => + Object.values(entry).map((path) => path.replace(/^\.\//u, "")), + ), + ]), + ].map((path) => ({ path, size: 1 })); + const manifest = join(directory, "package-manifest.json"); + await writeFile(join(directory, tarball), bytes); + await writeFile( + manifest, + JSON.stringify({ + schemaVersion: 2, + gitCommit: commit, + releaseTag: tag, + package: { + name: source.name, + version: source.version, + tarball, + integrity, + sha256, + files, + }, + }), + ); + + const result = ( + stdout: string, + status = 0, + stderr = "", + ): ReturnType => ({ + pid: 1, + output: [null, stdout, stderr], + stdout, + stderr, + status, + signal: null, + }); + vi.mocked(spawnSync).mockImplementation((command, args, options) => { + const actual = args ?? []; + if (command === "git") { + expect(actual).toEqual(["rev-parse", "HEAD"]); + return result(commit + "\n"); + } + if (actual.includes("--version")) { + expect(options?.env?.RUNNER_ENVIRONMENT).toBe("github-hosted"); + for (const key of ["NODE_AUTH_TOKEN", "NPM_TOKEN", "NODE_OPTIONS"]) + expect(options?.env).not.toHaveProperty(key); + return result("11.18.0\n"); + } + if (actual.includes("view")) { + vi.stubEnv("RUNNER_ENVIRONMENT", "self-hosted"); + return result("", 1, "E404"); + } + throw new Error( + "An unexpected child command crossed the publishing guard.", + ); + }); + await expect( + publishPrepared({ + manifest, + releaseTag: tag, + expectedReleaseCommit: commit, + }), + ).rejects.toThrow(refusal); + expect(spawnSync).toHaveBeenCalledTimes(3); + expect( + vi + .mocked(spawnSync) + .mock.calls.some(([, args]) => args?.includes("publish")), + ).toBe(false); + }); +}); + describe("publish workflow boundaries", () => { it("authenticates in bare repositories before checkout and never checks out in publish", async () => { const workflow = await readFile(