diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/actions/setup-release-npm/action.yml b/.github/actions/setup-release-npm/action.yml new file mode 100644 index 0000000..8b8decf --- /dev/null +++ b/.github/actions/setup-release-npm/action.yml @@ -0,0 +1,26 @@ +name: Set up reviewed release npm +description: Verify and extract the pinned npm CLI without installing project dependencies. +runs: + using: composite + steps: + - name: Verify and extract pinned npm + shell: bash + env: + NPM_VERSION: 11.18.0 + NPM_TARBALL_SHA256: 73f6155215ebabf4ed96dca1f567c2372cc713c33af2e5b9b62fde4e92373e2e + run: | + set -euo pipefail + tarball="${RUNNER_TEMP}/npm-${NPM_VERSION}.tgz" + npm_root="${RUNNER_TEMP}/release-npm-${NPM_VERSION}" + curl --fail --silent --show-error --location --retry 3 \ + "https://registry.npmjs.org/npm/-/npm-${NPM_VERSION}.tgz" \ + --output "${tarball}" + echo "${NPM_TARBALL_SHA256} ${tarball}" | sha256sum --check --strict --quiet + mkdir "${npm_root}" + tar --extract --gzip --file "${tarball}" --directory "${npm_root}" + npm_cli="${npm_root}/package/bin/npm-cli.js" + if [[ "$(node "${npm_cli}" --version)" != "${NPM_VERSION}" ]]; then + echo "::error::The reviewed npm version is not active" + exit 1 + fi + printf 'RELEASE_NPM_CLI=%s\nRELEASE_NPM_VERSION=%s\n' "${npm_cli}" "${NPM_VERSION}" >> "${GITHUB_ENV}" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 396b5fd..5c7ea15 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,11 +1,20 @@ -# Publishes the exact tarball prepared from a stable GitHub release tag. -# Authentication is npm trusted-publisher OIDC only; no token fallback exists. - +# Publishes only the exact single-package artifact prepared from a verified tag. +# A manual dispatch prepares artifacts without entering the OIDC publish job. name: Publish on: release: types: [published] + workflow_dispatch: + inputs: + tag: + description: Protected signed annotated stable tag to prepare (vX.Y.Z) + required: true + type: string + expected_commit: + description: Exact full commit SHA targeted by the tag + required: true + type: string permissions: contents: read @@ -15,29 +24,60 @@ concurrency: cancel-in-progress: false jobs: - prepare: + identity: + name: Verify signed release identity + if: >- + github.repository == 'pegma-dev/agent-access' && + (github.event_name == 'workflow_dispatch' || + (github.event_name == 'release' && !github.event.release.draft && !github.event.release.prerelease)) runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + tag: ${{ steps.identity.outputs.tag }} + commit: ${{ steps.identity.outputs.commit }} env: - RELEASE_TAG: ${{ github.event.release.tag_name }} - RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} - RELEASE_COMMIT: ${{ github.sha }} + RELEASE_TAG: ${{ github.event.release.tag_name || inputs.tag }} + RELEASE_COMMIT: ${{ github.event_name == 'release' && github.sha || inputs.expected_commit }} RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} - steps: - - name: Check out the release tag + # Do not execute project code or install dependencies before this check. + - name: Validate release event inputs + shell: bash + run: | + set -euo pipefail + if [[ ! "${RELEASE_TAG}" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then + echo "::error::The release tag must be stable vX.Y.Z" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ ]]; then + echo "::error::The release must supply its exact full commit SHA" + exit 1 + fi + if [[ "${GITHUB_EVENT_NAME}" == "release" && "${GITHUB_REF}" != "refs/tags/${RELEASE_TAG}" ]]; then + echo "::error::The release event must identify the requested tag" + exit 1 + fi + + - name: Check out the requested tag uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: refs/tags/${{ github.event.release.tag_name }} + ref: refs/tags/${{ env.RELEASE_TAG }} fetch-depth: 0 + fetch-tags: true + persist-credentials: false - name: Fetch the protected release branch run: git fetch --no-tags origin main:refs/remotes/origin/main - - name: Configure approved release signers + - name: Verify the approved tag signer and main ancestry + id: identity shell: bash + env: + GIT_NO_REPLACE_OBJECTS: "1" run: | + set -euo pipefail if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then - echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed SSH allowed-signers entries" exit 1 fi allowed_signers="${RUNNER_TEMP}/release-allowed-signers" @@ -45,103 +85,241 @@ jobs: printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" git config --local gpg.format ssh git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + tag_ref="refs/tags/${RELEASE_TAG}" + if [[ "$(git cat-file -t "${tag_ref}")" != "tag" ]]; then + echo "::error::The release requires an annotated tag" + exit 1 + fi + if [[ "$(git rev-parse HEAD)" != "${RELEASE_COMMIT}" || "$(git rev-parse "${tag_ref}^{commit}")" != "${RELEASE_COMMIT}" ]]; then + echo "::error::The checkout, tag target, and expected release commit must match" + exit 1 + fi + git verify-tag --raw "${tag_ref}" + git merge-base --is-ancestor "${RELEASE_COMMIT}" refs/remotes/origin/main + printf 'tag=%s\ncommit=%s\n' "${RELEASE_TAG}" "${RELEASE_COMMIT}" >> "${GITHUB_OUTPUT}" + validate: + name: Release gate / Node.js ${{ matrix.node-version }} + needs: identity + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + node-version: [22, 24] + steps: + - name: Check out the verified release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.identity.outputs.commit }} + persist-credentials: false + - name: Install pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + with: + version: 10.34.5 - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version: 24.18.0 - registry-url: https://registry.npmjs.org - package-manager-cache: false + node-version: ${{ matrix.node-version }} + cache: pnpm + - name: Install dependencies + run: pnpm install --frozen-lockfile + - name: Check formatting + run: pnpm run format:check + - name: Check types + run: pnpm run check + - name: Run tests including release regressions + run: pnpm test + - name: Run synthetic composition + run: pnpm example + - name: Check package artifacts + run: pnpm run release:check - - name: Enable pnpm - run: corepack enable + prepare: + name: Prepare exact signed-tag artifact + needs: [identity, validate] + runs-on: ubuntu-latest + timeout-minutes: 30 + outputs: + artifact-id: ${{ steps.upload.outputs.artifact-id }} + manifest-sha256: ${{ steps.manifest.outputs.sha256 }} + env: + RELEASE_TAG: ${{ needs.identity.outputs.tag }} + RELEASE_COMMIT: ${{ needs.identity.outputs.commit }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} + steps: + - name: Check out the verified release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.identity.outputs.commit }} + fetch-depth: 0 + fetch-tags: true + persist-credentials: false - # Installed from a tarball checked against a committed hash, so the - # bootstrap is pinned by bytes rather than by registry metadata. Every - # other install in this job is already covered by pnpm-lock.yaml. - - name: Use the reviewed npm release + - name: Fetch the protected release branch + run: git fetch --no-tags origin main:refs/remotes/origin/main + + - name: Configure approved release signers shell: bash - env: - NPM_VERSION: 11.18.0 - NPM_TARBALL_SHA256: 73f6155215ebabf4ed96dca1f567c2372cc713c33af2e5b9b62fde4e92373e2e run: | - tarball="${RUNNER_TEMP}/npm-${NPM_VERSION}.tgz" - curl --fail --silent --show-error --location --retry 3 \ - "https://registry.npmjs.org/npm/-/npm-${NPM_VERSION}.tgz" \ - --output "${tarball}" - echo "${NPM_TARBALL_SHA256} ${tarball}" | sha256sum --check --strict --quiet - npm install --global "${tarball}" - installed="$(npm --version)" - if [[ "${installed}" != "${NPM_VERSION}" ]]; then - echo "::error::npm ${installed} is active but ${NPM_VERSION} was reviewed" + set -euo pipefail + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed SSH allowed-signers entries" exit 1 fi + allowed_signers="${RUNNER_TEMP}/release-allowed-signers" + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + git config --local gpg.format ssh + git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" - - name: Install dependencies - run: pnpm install --frozen-lockfile - - - name: Check formatting - run: pnpm run format:check + - name: Install pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + with: + version: 10.34.5 - - name: Check types - run: pnpm run check + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false - - name: Run tests - run: pnpm test + - name: Use the reviewed npm release + uses: ./.github/actions/setup-release-npm - - name: Run synthetic protocol composition - run: pnpm example + - name: Install dependencies + run: pnpm install --frozen-lockfile - - name: Check package artifacts - run: pnpm run release:check + - name: Prepare and strictly verify the signed-tag release + id: prepared + run: >- + node scripts/release-packages.mjs prepare + --tag "${RELEASE_TAG}" + --expected-commit "${RELEASE_COMMIT}" + --out "${RUNNER_TEMP}/agent-access-prepared" - - name: Prepare and verify the release tarball - run: pnpm run release:pack -- -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release + # This independent digest travels through job outputs, never through the + # artifact whose manifest it authenticates. + - name: Record the independent manifest digest + id: manifest + shell: bash + env: + PREPARED_MANIFEST_SHA256: ${{ steps.prepared.outputs.manifest-sha256 }} + run: | + set -euo pipefail + read -r manifest_sha256 _ < <(sha256sum "${RUNNER_TEMP}/agent-access-prepared/manifest.json") + if [[ ! "${manifest_sha256}" =~ ^[0-9a-f]{64}$ || "${manifest_sha256}" != "${PREPARED_MANIFEST_SHA256}" ]]; then + echo "::error::The prepared manifest digest did not match its independent hash" + exit 1 + fi + printf 'sha256=%s\n' "${manifest_sha256}" >> "${GITHUB_OUTPUT}" - - name: Upload the prepared release + - name: Upload the immutable prepared release id: upload uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: - name: agent-access-release-${{ github.run_id }} - path: .release/ + name: agent-access-release-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/agent-access-prepared/ if-no-files-found: error - include-hidden-files: true - overwrite: true + overwrite: false retention-days: 30 - - name: Record the prepared artifact digest - run: echo "Prepared artifact SHA-256 ${{ steps.upload.outputs.artifact-digest }}" >> "${GITHUB_STEP_SUMMARY}" + - name: Record prepared artifact identity + env: + ARTIFACT_ID: ${{ steps.upload.outputs.artifact-id }} + ARTIFACT_DIGEST: ${{ steps.upload.outputs.artifact-digest }} + MANIFEST_SHA256: ${{ steps.manifest.outputs.sha256 }} + run: | + printf 'Prepared artifact ID: %s\n\nArtifact SHA-256: %s\n\nManifest SHA-256: %s\n' \ + "${ARTIFACT_ID}" "${ARTIFACT_DIGEST}" "${MANIFEST_SHA256}" >> "${GITHUB_STEP_SUMMARY}" publish: - needs: prepare + name: Publish exact prepared artifact + needs: [identity, prepare] + if: github.event_name == 'release' runs-on: ubuntu-latest + timeout-minutes: 30 environment: npm-publish permissions: contents: read id-token: write env: - RELEASE_TAG: ${{ github.event.release.tag_name }} - RELEASE_COMMIT: ${{ github.sha }} + RELEASE_TAG: ${{ needs.identity.outputs.tag }} + RELEASE_COMMIT: ${{ needs.identity.outputs.commit }} + RELEASE_MANIFEST_SHA256: ${{ needs.prepare.outputs.manifest-sha256 }} + steps: + - name: Check out the exact verified release source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.identity.outputs.commit }} + persist-credentials: false + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + # Extract only the reviewed npm CLI; never install project dependencies + # or run package builds with OIDC authority. + - name: Use the reviewed npm release + uses: ./.github/actions/setup-release-npm + + - name: Download the exact immutable prepared artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.prepare.outputs.artifact-id }} + path: ${{ runner.temp }}/agent-access-prepared + + - name: Publish the exact prepared release + run: >- + node scripts/release-packages.mjs publish + --prepared-dir "${RUNNER_TEMP}/agent-access-prepared" + --manifest-sha256 "${RELEASE_MANIFEST_SHA256}" + --tag "${RELEASE_TAG}" + --expected-commit "${RELEASE_COMMIT}" + + verify: + name: Verify registry release and consumer + needs: [identity, prepare, publish] + if: github.event_name == 'release' + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + id-token: none + env: + RELEASE_TAG: ${{ needs.identity.outputs.tag }} + RELEASE_COMMIT: ${{ needs.identity.outputs.commit }} + RELEASE_MANIFEST_SHA256: ${{ needs.prepare.outputs.manifest-sha256 }} steps: - - name: Check out the exact release tag + - name: Check out the exact verified release source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: refs/tags/${{ github.event.release.tag_name }} - fetch-depth: 1 + ref: ${{ needs.identity.outputs.commit }} + persist-credentials: false - - name: Set up Node.js and the npm registry - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false - - name: Download the prepared release + - name: Use the reviewed npm release + uses: ./.github/actions/setup-release-npm + + - name: Download the exact immutable prepared artifact uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - name: agent-access-release-${{ github.run_id }} - path: .release + artifact-ids: ${{ needs.prepare.outputs.artifact-id }} + path: ${{ runner.temp }}/agent-access-prepared - - name: Publish the verified prepared tarball - run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json + # Registry availability requires this unprivileged job to pass. Consumer + # installation and provenance verification never receive OIDC authority. + - name: Verify registry bytes, provenance, and the public consumer + run: >- + node scripts/release-packages.mjs verify + --prepared-dir "${RUNNER_TEMP}/agent-access-prepared" + --manifest-sha256 "${RELEASE_MANIFEST_SHA256}" + --tag "${RELEASE_TAG}" + --expected-commit "${RELEASE_COMMIT}" diff --git a/AGENTS.md b/AGENTS.md index 91498a7..cc1845b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,6 +51,34 @@ Work on a `claude/*` branch from fetched `origin/main`. Required gates are when present. Current-head code/security review must finish clean; never bypass missing, skipped, pending, or failing gates. Use squash PR merges. +`pnpm test` includes the explicit `test:release` Node test files for release +identity, arguments, manifest integrity, fresh outputs, and registry failure and +recovery cases. Both Node lanes must execute them. The original AUTH-01 source +result is historical evidence; changed release source requires current-head +validation and review. + +Strict release preparation requires a clean checkout at an approved SSH-signed +annotated `vX.Y.Z` tag matching the package version, exact event commit, and +protected `origin/main` ancestry. Verify that identity before executing release +source. The schema-2 manifest binds the sole `@pegma/agent-access` tarball; +retain its SHA-256 independently of the uploaded immutable artifact. Publish +only that artifact ID with the independent digest, tag, and expected commit. +The protected `npm-publish` job receives OIDC only for exact-byte publication; +it installs no project dependencies, rebuilds no package, runs no consumer, and +has no token fallback. A separate unprivileged job checks registry bytes, +signatures, source-bound provenance, and a clean exact-version consumer with +scripts disabled. Manual workflow dispatch prepares only. + +See [release operations](docs/RELEASING.md) and the +[first-publication handoff](docs/BOOTSTRAP.md). The source remains unpublished +at `0.1.0`. Maintainer 2FA bootstrap creates the name under `bootstrap` without +advertising it; a later separately reviewed version must pass trusted +publication and verification before advertisement. This source change chooses +no future version. Package ownership, approved signers, immutable tag rules, +environment approval, and direct-publish trusted-publisher settings remain +external maintainer gates. Source, SDK, registry, and provenance results do not +close actual existing-login/Admin-consent or per-client two-host acceptance. + The user explicitly requests parallel in-harness subagents. Assign exact file ownership, tell workers they are not alone, and never revert others' edits. The orchestrator owns installs, builds/tests, Git, PRs, review replies, and diff --git a/README.md b/README.md index 5a7f63d..48b86a2 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ require explicit registration and fresh consent; changing the registry cannot silently widen an existing grant. The source package is `@pegma/agent-access@0.1.0`, currently unpublished. -Implementation and verification are in progress under AUTH-01 in the governing +AUTH-01 source work is tracked in the governing [Knowledge/AI plan](https://github.com/pegma-dev/support-desk/blob/main/docs/KNOWLEDGE_AI_PLAN.md). Source tests and a synthetic client example do not establish real host login, two-host client acceptance, publication, or deployment. @@ -33,6 +33,12 @@ Read the [architecture](docs/ARCHITECTURE.md), [API](docs/API.md), and [HTTP composition](docs/HTTP.md) before wiring a host. The [project plan](docs/PROJECT_PLAN.md) distinguishes source work from host gates; [release operations](docs/RELEASING.md) describes the separate first publication -and later trusted-publisher path. +and later trusted-publisher path. The [maintainer bootstrap handoff](docs/BOOTSTRAP.md) +keeps the initial 2FA-published `bootstrap` version unadvertised. The first +advertised version needs a separate reviewed change and successful registry +consumer and trusted-provenance verification. Release preparation preserves +exact tarball bytes, an independently retained manifest digest, and the +verified signed-tag identity. Merging source and manual workflow dispatch do +not publish. Built in the open by RetireGolden, LLC. MIT licensed. diff --git a/docs/BOOTSTRAP.md b/docs/BOOTSTRAP.md new file mode 100644 index 0000000..ddbfb21 --- /dev/null +++ b/docs/BOOTSTRAP.md @@ -0,0 +1,100 @@ +# First-publication handoff + +## Current state and owner + +The maintainer owns npm's first publication and external configuration. +`@pegma/agent-access` is unpublished at source version `0.1.0`. Merging this +follow-up creates no tag, GitHub release, npm publication, publisher setting, +or protection setting. Knowledge Base has its own release handoff. + +Creating the package name and advertising the first trusted release are +separate steps. Maintainer 2FA publication supplies no OIDC provenance and +cannot substitute for strict `verify` in [release operations](RELEASING.md). +The historical AUTH-01 source result does not replace this change's required +current-head code/security review and Node 22/24 gate. + +## Prepare the initial exact artifact + +1. Confirm npm ownership and publishing permission for `@pegma/agent-access`. + Record the responsible maintainer and keep credentials and one-time codes + out of repository files and logs. +2. Merge reviewed source and exact pins to protected `origin/main`. Record the + full commit, passing current-head Node 22/24 gates, and clean applicable + code/security review. Configure approved SSH signers and protected immutable + `v*` tags outside this source change. +3. The maintainer creates the approved signed annotated `v0.1.0` tag at that + merged commit. Use a clean complete checkout at the tag with approved signer + verification. Before standalone preparation, extract the reviewed npm + `11.18.0` tarball after checking the SHA-256 pinned in the + [npm setup action](../.github/actions/setup-release-npm/action.yml). + Explicitly set `RELEASE_NPM_CLI` to the extracted regular `npm-cli.js` file's + canonical absolute path and set `RELEASE_NPM_VERSION=11.18.0`; both are + required, and linked paths are rejected. Alternatively use the workflow's + prepare-only dispatch, which supplies both variables. Then run strict + preparation: + + ```sh + node scripts/release-packages.mjs prepare --tag v0.1.0 --expected-commit FULL_COMMIT_SHA + ``` + +4. Retain the prepared directory intact. Independently record the emitted + manifest SHA-256, source identity, directory, and tarball hashes. Obtain the + digest from trusted preparation output, rather than a file bundled with + downloaded artifacts. Prepare-only dispatch supplies immutable artifact IDs + and independent job outputs. +5. Run read-only preflight with that independent digest: + + ```sh + node scripts/release-packages.mjs preflight --prepared-dir PREPARED_DIRECTORY --manifest-sha256 INDEPENDENT_SHA256 --tag v0.1.0 --expected-commit FULL_COMMIT_SHA + ``` + + An existing exact version must match prepared metadata and downloaded bytes. + Only HTTP 404 establishes absence. Stop on mismatch, access failure, or an + uncertain response. + +## Maintainer 2FA bootstrap + +Using the maintainer's interactive npm login and 2FA, publish only the exact +prepared tarball. This command is an operator handoff, not a CI step or an +instruction for a source-preparation agent: + +```sh +npm publish PREPARED_DIRECTORY/pegma-agent-access-0.1.0.tgz --access public --ignore-scripts --registry https://registry.npmjs.org --tag bootstrap +``` + +Use the filename from the verified manifest. Publish no source directory and +add no token fallback. Rerun preflight before continuing an interrupted +bootstrap. Skip an existing version only after preflight confirms identical +prepared bytes; npm versions are immutable. Repeat preflight after publication +to retain the registry metadata and downloaded-byte match. + +Record manual publication receipts and bootstrap integrity with provenance +explicitly absent. Leave `0.1.0` under `bootstrap`; do not advertise it as the +released production dependency or authorize host installation from it. + +## First advertised trusted release + +Once the name exists, the maintainer configures its trusted publisher, the +protected `npm-publish` environment, approved signers, and immutable tag +protection described in [release operations](RELEASING.md). Bind the publisher +to `pegma-dev/agent-access`, exact workflow `publish.yml`, and environment +`npm-publish`; explicitly permit direct publishing. Check npm's first-use +timing before configuring it for the reviewed trusted release. + +The first advertised release needs a separately reviewed package-version and +dependent-pin change synchronized across its consumers. This source change +chooses no future version and performs no bump. A manually published version +cannot be republished through OIDC to acquire provenance. Run the full +current-head review and Node 22/24 gate for the new release commit, create its +approved signed annotated version tag on `origin/main`, then create the GitHub +release with `--verify-tag` to trigger the trusted workflow. It prepares once, +checks the independent artifact binding, preflights the exact version, and +publishes only the absent prepared tarball. + +Advertise availability only after the separate unprivileged strict `verify` +job succeeds: registry bytes/dependencies, a clean exact-version registry +consumer, registry signatures, and matching source/workflow/tag/commit +provenance. Preserve that result with the release identity and independent +manifest digest. Both hosts additionally require published Knowledge Base +and their retained actual login/Admin-consent/client/staging acceptance before +activation. Registry publication closes none of those host gates. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 28bdf2c..fa9062e 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,15 +1,29 @@ # Release operations -`@pegma/agent-access@0.1.0` is the first source version and is unpublished. -Source validation, a merged PR, and a synthetic client proof authorize no tag, -release, npm publication, trusted-publisher change, or host deployment. Those -are separate maintainer operations. +## Status and release boundary -## Source and artifact gate +The release contains only `@pegma/agent-access`, at source version `0.1.0` and +currently unpublished. AUTH-01's earlier merged source result recorded 123 +tests. That historical result and its synthetic SDK proof do not validate this +release-preparation follow-up. Changed source still needs every current-head +review and Node 22/24 gate. No source merge configures a publisher, creates a +tag or release, or publishes npm packages. Follow the +[maintainer bootstrap handoff](BOOTSTRAP.md) for first use. -Run the repository gate on Node 22 and 24: +Knowledge Base has its own release process. Production host assembly requires +exact published dependencies from both components. Source tests, local adapter +conformance, and the official SDK protocol fixture establish source behavior; +they do not establish real host login, production storage, or actual requested +client acceptance on either host. + +## Repository and development artifact gates + +Use Node 22.6.0+ or 24 with `pnpm@10.34.5`. The published package engine remains +`>=22`; the development floor supports the example's type stripping. Run the +complete gate on current Node 22 and 24: ```sh +pnpm install --frozen-lockfile pnpm run format:check pnpm run check pnpm test @@ -17,62 +31,221 @@ pnpm run release:check pnpm run example ``` -Current-head code/security review and CI must finish clean. Real Azure Tables -and D1 conformance and the synthetic SDK protocol example are source evidence; -they do not establish host login, production storage, or two-host acceptance. +Require clean current-head code/security review and all required CI. Absent, +skipped, pending, or failing gates do not authorize release. `pnpm test` +includes `pnpm run test:release`, whose explicit Node test files cover release +identity, strict arguments, independent manifest integrity, fresh build outputs, +and registry failure/recovery. Both Node lanes must execute these regressions. -The published package must have its own README and LICENSE, exact released -dependencies, a build-on-prepack hook, public exports, and no compiled tests. -Pack/import validation must check the actual artifact in a clean consumer, -including its package inventory and integrity. Test-only local artifacts may -establish source compatibility before publication. Hosts install published -exact versions for production; no Git, source-copy, workspace-path, or -unpublished-tarball substitute is permitted. +`release:check` cleans fixed generated outputs, forces a fresh build, and packs +those outputs with lifecycle scripts disabled. It validates the package's +build-on-prepack hook, then checks the actual artifact: stable version, exact +released dependency pins, ESM exports, +package-local README/MIT LICENSE, compiled-test exclusion, safe file inventory, +runtime/type entry points, SHA-1, and SHA-512 integrity. An isolated consumer +outside the workspaces installs the tarball with scripts disabled, resolves +released dependencies, and imports the public package. -The first runtime pins are `@pegma/audit@0.2.0`, +The runtime pins remain `@pegma/audit@0.2.0`, `@pegma/authorization-core@0.4.0`, `@pegma/spine@0.1.2`, and -`@pegma/storage-core@0.4.0`. `pnpm run release:check` packs and imports in a -temporary clean consumer. `pnpm run release:pack` retains the sole tarball and -hashes in `.release/package-manifest.json`; publish that reviewed tarball. - -## First publication - -A new package name needs a one-time maintainer bootstrap before trusted -publishing can be configured. After a separately authorized reviewed release: - -1. Prepare and retain the exact approved tarball and its integrity manifest - from the release commit already on `origin/main`; do not rebuild between - review and publication. -2. The maintainer signs in to npm and manually publishes that exact public - tarball using interactive 2FA. Never add an npm token to the repository or - workflow. -3. Verify the registry artifact integrity against the approved tarball. An - existing version with a different integrity is an error, never an overwrite. -4. Configure the package's GitHub Actions trusted publisher for organization - `pegma-dev`, repository `agent-access`, workflow `publish.yml`, and environment - `npm-publish`. Protect that environment with maintainer approval, configure - `RELEASE_ALLOWED_SIGNERS` with the reviewed signer entry, and protect `v*` - tags against update/deletion and unauthorized creation. -5. Verify the bootstrap and later OIDC paths separately. A manual bootstrap - does not prove a successful trusted-publisher publication. - -No bootstrap or external configuration is claimed complete in this source PR. - -## Later trusted-publisher releases - -Prepare version/pin/lockfile and release-note changes through a reviewed PR. -The maintainer creates a protected signed annotated `vX.Y.Z` tag at the exact -release commit already contained in `origin/main`, pushes that tag, and creates -the GitHub release with `gh release create vX.Y.Z --verify-tag`. - -The unprivileged preparation job verifies tag/signature/main ancestry, runs -the complete gate, and packs the exact reviewed artifacts. Only the minimal -environment-protected publication job receives OIDC authority. It publishes -those artifacts with provenance and does not install project dependencies. -There is no token fallback and merging alone never publishes. - -On partial failure, rerun against the unchanged protected tag: verify and skip -an identical already-published version, publish an absent version, and stop on -any integrity mismatch or unexplained registry failure. Never reuse a version -or retarget a release tag. Activation of either host remains a separate task -even after registry publication succeeds. +`@pegma/storage-core@0.4.0`. This follow-up changes no runtime scope or version. +`pnpm run release:pack` preserves development artifacts and a schema-1 manifest +in a new `.release/agent-access-*` directory. It requires no tag and supplies no +release identity or provenance. Publication rejects that development manifest; +use strict `prepare` for a releasable artifact. + +## Strict release preparation + +Merge reviewed release source and exact version/pin changes to protected +`origin/main` first. Configure immutable protected `v*` tags and approved SSH +release signers outside this source change. A stable `vX.Y.Z` must be a signed +annotated tag whose target matches the package version and exact expected +commit. The checkout must be clean, at that commit, in +`pegma-dev/agent-access`, with complete ancestry and the commit contained in +`origin/main`. Signature verification uses independently approved signer +configuration. Lightweight tags and unmerged commits fail the gate. + +After the full gate, prepare from that exact clean checkout. This example uses +the current source version; substitute the full approved commit SHA: + +Strict `prepare` requires both `RELEASE_NPM_CLI` and +`RELEASE_NPM_VERSION=11.18.0`. The CLI path must be canonical, absolute, and name +a regular `npm-cli.js` file; linked paths are rejected. Extract the reviewed npm +tarball after checking the SHA-256 pinned in the +[npm setup action](../.github/actions/setup-release-npm/action.yml), then set +both variables before standalone preparation. The workflow configures them +automatically. Development `check` and `pack` continue to use ambient npm. + +```sh +node scripts/release-packages.mjs prepare --tag v0.1.0 --expected-commit FULL_COMMIT_SHA +``` + +An optional `--out EMPTY_DIRECTORY` selects a new empty output directory. +Preparation repeats strict source identity checks before and after building +and packing, then retains the exact tarball and schema-2 `manifest.json`: + +- `identity`: fixed repository, tag, exact commit, and package version; +- `artifacts`: exactly one package with name, version, safe filename, byte size, + SHA-1, SHA-512 integrity, exact dependencies, and bounded file inventory. + +The producer emits `prepared-dir`, `manifest-path`, and `manifest-sha256`. +Retain that SHA-256 independently with the approved source identity and job +outputs. A digest copied only from a downloaded artifact supplies no independent +binding. Downstream commands require the digest, tag, and expected commit and +rehash the tarball. They reject extra or malformed manifest data, unsafe paths, +symlinks, missing files, wrong package/pins, and changed bytes. Preparation +establishes neither registry availability nor provenance. + +## Protected trusted-publisher workflow + +[Publish](../.github/workflows/publish.yml) prepares from a stable published +GitHub release. First create the protected signed annotated tag on +`origin/main`, then use `gh release create vX.Y.Z --verify-tag`. Its manual +`workflow_dispatch` accepts `tag` and `expected_commit` for preparation and +inspection only; it cannot enter publication or registry verification. + +The workflow verifies tag/event identity, complete main ancestry, and the +approved SSH signature before executing project source or installing project +dependencies. Node 22/24 jobs run the full gate. The unprivileged preparation +job repeats strict verification, packs once, uploads an immutable artifact, +and exposes its artifact ID and independently computed manifest SHA-256. +Only the protected `npm-publish` job has `id-token: write`. It downloads that +exact artifact ID and checks the independent digest/tag/commit before npm +writes. It installs no project dependencies, runs no package lifecycle scripts +or consumer, and does not rebuild or repack. + +A separate unprivileged `verify` job has `id-token: none`. It installs the +exact registry package in a temporary consumer with scripts disabled, checks +registry bytes and cryptographic signatures/provenance, then imports the public +package. It uses the same immutable artifact ID and independent digest. +No `setup-node` registry configuration or npm token fallback is used. + +These external settings remain pending maintainer operations: + +- npm ownership and organization publishing permission for + `@pegma/agent-access`; +- protected `origin/main`, immutable release tags, and approved SSH signer + entries in the reviewed `RELEASE_ALLOWED_SIGNERS` repository variable; +- the GitHub `npm-publish` environment with required approval and release-ref + restrictions; +- the npm trusted publisher bound to `pegma-dev/agent-access`, `publish.yml`, + and `npm-publish`, with explicit permission for direct `npm publish`; +- restrictions disallowing token-based publication. No repository npm token or + token fallback exists. + +The workflow uses Node `24.18.0` and npm `11.18.0` for release operations. It +uses the local [npm setup action](../.github/actions/setup-release-npm/action.yml) +to download npm's tarball and check the committed SHA-256 before extracting the +CLI. Review the +[official npm trusted-publisher guidance](https://docs.npmjs.com/trusted-publishers/) +when configuring direct publishing and first-use timing; source validation does +not configure or prove those external settings. + +## Preflight, publication, and interrupted-release recovery + +Read-only preflight is the first-publication inspection command: + +```sh +node scripts/release-packages.mjs preflight --prepared-dir PREPARED_DIRECTORY --manifest-sha256 INDEPENDENT_SHA256 --tag v0.1.0 --expected-commit FULL_COMMIT_SHA +``` + +It validates the schema-2 artifact and queries the exact version in the public +npm registry before any publication. Only HTTP 404 means absent. Authentication, +network/server errors, invalid metadata, wrong name/version/dependencies, or +changed registry tarball bytes stop the release. An existing version must match +the prepared SHA-1, SHA-512 integrity, and downloaded bytes. + +The protected OIDC job runs: + +```sh +node scripts/release-packages.mjs publish --prepared-dir PREPARED_DIRECTORY --manifest-sha256 INDEPENDENT_SHA256 --tag vX.Y.Z --expected-commit FULL_COMMIT_SHA +``` + +The workflow supplies `RELEASE_NPM_CLI` as an absolute path to the reviewed npm +`11.18.0` `npm-cli.js` and `RELEASE_NPM_VERSION=11.18.0`. Standalone `prepare` +and `verify` also need both variables and the canonical regular CLI path; use +the npm artifact and SHA-256 pinned in the +[npm setup action](../.github/actions/setup-release-npm/action.yml). +Read-only `preflight` needs no npm authentication. `publish` +requires the matching GitHub release OIDC environment; interactive bootstrap is +a separate maintainer procedure. npm runs with isolated configuration and the +explicit public registry. `publish` rejects ambient npm authentication and +configuration. + +`publish` repeats preflight before its npm write. It skips only an identical +existing version and publishes an absent version from the prepared tarball. +After interruption, preserve the original source identity, independent digest, +and artifact bytes; retry only after preflight accepts that same artifact. +Never overwrite a version, rebuild from another checkout, move a tag, or treat +an npm error as proof of absence. A conflict requires maintainer investigation +and a separately reviewed release decision. + +## Registry verification and availability + +After publication, the separate unprivileged job runs strict verification. The +same command is available independently: + +```sh +node scripts/release-packages.mjs verify --prepared-dir PREPARED_DIRECTORY --manifest-sha256 INDEPENDENT_SHA256 --tag vX.Y.Z --expected-commit FULL_COMMIT_SHA +``` + +The exact registry version must exist and match approved metadata and downloaded +bytes. A fresh consumer installs the exact version from the public registry +without workspace links, local tarballs, or lifecycle scripts. Before importing +it, the pinned npm CLI verifies registry signatures and provenance attestations; +the verifier requires the attested source repository, workflow, tag, and commit +to match the prepared identity. Availability requires all these results. +Preserve the artifact, independent digest, source identity, workflow run, and +verification results in the release record. + +Manual first publication cannot satisfy trusted provenance. The +[bootstrap handoff](BOOTSTRAP.md) specifies the two separate release steps; +bootstrap integrity evidence must never be reported as OIDC provenance. + +## Observed npm audit shape: 2026-11-07 + +A real isolated registry consumer used the installed npm `11.18.0` CLI and exact +`@pegma/spine@0.1.2`, with its known integrity checked and lifecycle scripts +disabled. No package runtime was imported. The command +`npm audit signatures --json --include-attestations` succeeded; the +[official npm audit documentation](https://docs.npmjs.com/cli/v11/commands/npm-audit/#audit-signatures) +documents that flag and its attestation output. + +The sanitized observed shape was: + +```text +top-level keys: invalid, missing, verified +counts: invalid=0, missing=0, verified=1 +verified entry keys: attestationBundles, attestations, location, name, registry, version +attestationBundles: 2 bundles, including one SLSA v1 provenance bundle +bundle keys: dsseEnvelope, mediaType, verificationMaterial +verificationMaterial: certificate.rawBytes, timestampVerificationData, tlogEntries +``` + +A second isolated run installed all seven exact external runtime pins used by +the two components, resolving 102 packages. Root lock versions and public +registry URLs matched; the real audit reported `invalid=0`, `missing=0`, +and `verified=21`. Lifecycle scripts and runtime imports remained disabled. +This checks the existing external dependency graph without publishing either +new component. + +The observed public source was [pegma-dev/spine](https://github.com/pegma-dev/spine) +at `refs/tags/v0.1.2`. This records the pinned CLI's working flag, output, and +certificate shape. It proves no provenance for unpublished KB or Agent Access +packages and performs no publisher operation. Their own exact repository, +workflow, tag, and source-commit post-release verification remains mandatory. +Raw bundles and certificate bytes are intentionally omitted. + +## Consumers and retained host gates + +Agent Access and Knowledge Base publication both precede real host assembly. +Git references, copied source, workspace paths, and unpublished production +tarballs do not substitute for exact verified registry releases. + +P-00 and PG-01/RG-01 still require actual existing-login/current-Admin consent, +each requested client and provider mode, host-attested staging evidence, and +credential/evidence failure cases on both hosts. Source, emulator, SDK, +registry, and provenance results cannot close those gates. Preserve staff +approval/publication, privacy, isolation, bounded work, and full human workflows +before activation, A-01, or supervised pilots. Private host configuration and +operational evidence remain in their owning private systems. diff --git a/package.json b/package.json index 26d83a9..a90805e 100644 --- a/package.json +++ b/package.json @@ -17,9 +17,14 @@ "clean": "tsc -b --clean", "format": "prettier --write .", "format:check": "prettier --check .", - "test": "pnpm run build && vitest run", + "test": "pnpm run build && vitest run && pnpm run test:release", + "test:release": "node scripts/test-release.mjs", "release:check": "node scripts/release-packages.mjs check", "release:pack": "node scripts/release-packages.mjs pack", + "release:prepare": "node scripts/release-packages.mjs prepare", + "release:preflight": "node scripts/release-packages.mjs preflight", + "release:publish": "node scripts/release-packages.mjs publish", + "release:verify": "node scripts/release-packages.mjs verify", "example": "pnpm run build && node --experimental-strip-types examples/protocol/run.ts" }, "devDependencies": { diff --git a/scripts/release-contract.mjs b/scripts/release-contract.mjs new file mode 100644 index 0000000..87067cd --- /dev/null +++ b/scripts/release-contract.mjs @@ -0,0 +1,173 @@ +import { spawnSync } from "node:child_process"; +import { realpathSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +export const RELEASE_REPOSITORY = "pegma-dev/agent-access"; +export const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; +export const RELEASE_PACKAGES = Object.freeze([ + Object.freeze({ + directory: "agent-access", + name: "@pegma/agent-access", + runtimeExport: "createAgentAccess", + runtimeExportType: "function", + }), +]); + +export function releaseDependencies(directory, version) { + if (typeof version !== "string" || !STABLE_VERSION.test(version)) { + throw new Error("release version must be stable semver"); + } + if (directory !== "agent-access") { + throw new Error("release package is not in the reviewed package set"); + } + return Object.freeze({ + "@pegma/audit": "0.2.0", + "@pegma/authorization-core": "0.4.0", + "@pegma/spine": "0.1.2", + "@pegma/storage-core": "0.4.0", + }); +} + +function fail(message) { + throw new Error(message); +} + +function git(root, arguments_, allowFailure = false) { + const env = { ...process.env }; + // Preserve the host's approved local/global signer configuration, including + // GIT_CONFIG_GLOBAL and GIT_CONFIG_NOSYSTEM. Command-scope config injection + // must not override that policy or select another repository/object database. + const excluded = new Set([ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_COMMON_DIR", + "GIT_CONFIG", + "GIT_CONFIG_COUNT", + "GIT_CONFIG_PARAMETERS", + "GIT_NO_REPLACE_OBJECTS", + ]); + for (const key of Object.keys(env)) { + // Environment names are case-insensitive on Windows. Inspect the copied + // keys as well as their canonical spelling before spawning native Git. + const normalized = key.toUpperCase(); + if ( + excluded.has(normalized) || + /^GIT_CONFIG_(?:KEY|VALUE)_/u.test(normalized) + ) { + delete env[key]; + } + } + env.GIT_NO_REPLACE_OBJECTS = "1"; + const result = spawnSync( + process.platform === "win32" ? "git.exe" : "git", + ["--no-replace-objects", ...arguments_], + { + cwd: root, + env, + shell: false, + encoding: "utf8", + stdio: "pipe", + maxBuffer: 4 * 1024 * 1024, + timeout: 30_000, + }, + ); + if (result.error || (!allowFailure && result.status !== 0)) { + fail("release identity Git verification failed"); + } + return result; +} + +export function verifyReleaseIdentity({ + root = fileURLToPath(new URL("../", import.meta.url)), + tag, + expectedCommit, + version, +} = {}) { + if ( + typeof version !== "string" || + !STABLE_VERSION.test(version) || + tag !== `v${version}` + ) { + fail("release tag must match the stable package version"); + } + if ( + typeof expectedCommit !== "string" || + !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(expectedCommit) + ) { + fail("release event must supply the exact expected commit"); + } + let checkout; + try { + checkout = realpathSync(resolve(root)); + const gitRoot = git(checkout, [ + "rev-parse", + "--show-toplevel", + ]).stdout.trim(); + if (realpathSync(gitRoot) !== checkout) { + fail("release identity requires the checkout root"); + } + } catch { + fail("release identity requires the checkout root"); + } + const origin = git(checkout, ["remote", "get-url", "origin"]).stdout.trim(); + if ( + !/^(?:https:\/\/github\.com\/pegma-dev\/agent-access(?:\.git)?|git@github\.com:pegma-dev\/agent-access(?:\.git)?|ssh:\/\/git@github\.com\/pegma-dev\/agent-access(?:\.git)?)$/u.test( + origin, + ) + ) { + fail("release origin must be the reviewed source repository"); + } + if ( + git(checkout, ["rev-parse", "--is-shallow-repository"]).stdout.trim() !== + "false" + ) { + fail("release identity requires complete Git ancestry"); + } + if ( + git(checkout, [ + "status", + "--porcelain=v1", + "--untracked-files=all", + "--ignore-submodules=none", + ]).stdout !== "" + ) { + fail("release preparation requires a clean checkout"); + } + const tagRef = `refs/tags/${tag}`; + const type = git(checkout, ["cat-file", "-t", tagRef], true); + if (type.status !== 0 || type.stdout.trim() !== "tag") { + fail("release ref must be an annotated tag object"); + } + const commit = git(checkout, ["rev-parse", "HEAD"]).stdout.trim(); + const tagCommit = git(checkout, [ + "rev-parse", + `${tagRef}^{commit}`, + ]).stdout.trim(); + if (commit !== expectedCommit || tagCommit !== expectedCommit) { + fail("release checkout, tag target, and event commit must match"); + } + // Signer approval comes from the workflow's reviewed Git verification + // configuration (for example SSH allowedSignersFile), never from this script. + if (git(checkout, ["verify-tag", "--raw", tagRef], true).status !== 0) { + fail("release tag signature is not valid for an approved signer"); + } + if ( + git( + checkout, + ["merge-base", "--is-ancestor", commit, "refs/remotes/origin/main"], + true, + ).status !== 0 + ) { + fail("release tag commit must be contained in origin/main"); + } + return Object.freeze({ + repository: RELEASE_REPOSITORY, + tag, + commit, + version, + }); +} diff --git a/scripts/release-manifest.mjs b/scripts/release-manifest.mjs new file mode 100644 index 0000000..8784bbd --- /dev/null +++ b/scripts/release-manifest.mjs @@ -0,0 +1,327 @@ +import { constants } from "node:fs"; +import { lstat, open, realpath, writeFile } from "node:fs/promises"; +import { createHash, timingSafeEqual } from "node:crypto"; +import { basename, dirname, join, resolve } from "node:path"; +import { + RELEASE_PACKAGES, + RELEASE_REPOSITORY, + STABLE_VERSION, + releaseDependencies, +} from "./release-contract.mjs"; + +export const PREPARED_MANIFEST_LIMITS = Object.freeze({ + manifestBytes: 2 * 1024 * 1024, + artifactBytes: 16 * 1024 * 1024, + totalArtifactBytes: 64 * 1024 * 1024, + filesPerArtifact: 4096, + fileBytes: 32 * 1024 * 1024, + unpackedBytesPerArtifact: 64 * 1024 * 1024, +}); + +function fail() { + throw new Error("prepared release manifest or artifact verification failed"); +} + +function exactKeys(value, expected) { + if ( + value === null || + typeof value !== "object" || + Array.isArray(value) || + ![Object.prototype, null].includes(Object.getPrototypeOf(value)) + ) { + fail(); + } + const keys = Reflect.ownKeys(value); + if ( + keys.length !== expected.length || + keys.some((key) => typeof key !== "string" || !expected.includes(key)) + ) { + fail(); + } +} + +function boundedInteger(value, maximum, minimum = 0) { + if (!Number.isSafeInteger(value) || value < minimum || value > maximum) { + fail(); + } +} + +function safeEqual(left, right) { + const a = Buffer.from(left); + const b = Buffer.from(right); + return a.length === b.length && timingSafeEqual(a, b); +} + +function hash(bytes, algorithm, encoding = "hex") { + return createHash(algorithm).update(bytes).digest(encoding); +} + +function validateIdentity(identity) { + exactKeys(identity, ["repository", "tag", "commit", "version"]); + if ( + identity.repository !== RELEASE_REPOSITORY || + typeof identity.version !== "string" || + !STABLE_VERSION.test(identity.version) || + identity.tag !== `v${identity.version}` || + typeof identity.commit !== "string" || + !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(identity.commit) + ) { + fail(); + } +} + +function validateFiles(files) { + if ( + !Array.isArray(files) || + files.length < 5 || + files.length > PREPARED_MANIFEST_LIMITS.filesPerArtifact + ) { + fail(); + } + const paths = new Set(); + let total = 0; + for (const file of files) { + exactKeys(file, ["path", "size"]); + if ( + typeof file.path !== "string" || + file.path.length > 256 || + paths.has(file.path) || + file.path + .split("/") + .some((part) => part === "" || part === "." || part === "..") || + (!["package.json", "README.md", "LICENSE"].includes(file.path) && + (!/^dist\/[A-Za-z0-9_./-]+\.(?:js|js\.map|d\.ts|d\.ts\.map)$/u.test( + file.path, + ) || + /\.(?:test|spec)\./u.test(file.path))) + ) { + fail(); + } + boundedInteger(file.size, PREPARED_MANIFEST_LIMITS.fileBytes); + total += file.size; + if (total > PREPARED_MANIFEST_LIMITS.unpackedBytesPerArtifact) fail(); + paths.add(file.path); + } + for (const required of [ + "package.json", + "README.md", + "LICENSE", + "dist/index.js", + "dist/index.d.ts", + ]) { + if (!paths.has(required)) fail(); + } +} + +function deepFreeze(value) { + for (const child of Object.values(value)) { + if (child !== null && typeof child === "object") deepFreeze(child); + } + return Object.freeze(value); +} + +export function validatePreparedManifest(manifest) { + exactKeys(manifest, ["schemaVersion", "identity", "artifacts"]); + if (manifest.schemaVersion !== 2) fail(); + validateIdentity(manifest.identity); + if ( + !Array.isArray(manifest.artifacts) || + manifest.artifacts.length !== RELEASE_PACKAGES.length + ) { + fail(); + } + let total = 0; + for (const [index, record] of manifest.artifacts.entries()) { + const specification = RELEASE_PACKAGES[index]; + exactKeys(record, [ + "name", + "version", + "filename", + "size", + "shasum", + "integrity", + "dependencies", + "files", + ]); + const filename = `${specification.name.slice(1).replace("/", "-")}-${manifest.identity.version}.tgz`; + if ( + record.name !== specification.name || + record.version !== manifest.identity.version || + record.filename !== filename || + basename(record.filename) !== record.filename || + record.filename.length > 200 || + typeof record.shasum !== "string" || + !/^[0-9a-f]{40}$/u.test(record.shasum) || + typeof record.integrity !== "string" || + !/^sha512-[A-Za-z0-9+/]{86}==$/u.test(record.integrity) + ) { + fail(); + } + boundedInteger(record.size, PREPARED_MANIFEST_LIMITS.artifactBytes, 1); + total += record.size; + if (total > PREPARED_MANIFEST_LIMITS.totalArtifactBytes) fail(); + const dependencies = releaseDependencies( + specification.directory, + record.version, + ); + exactKeys(record.dependencies, Object.keys(dependencies)); + for (const [name, version] of Object.entries(dependencies)) { + if (record.dependencies[name] !== version) fail(); + } + validateFiles(record.files); + } + return deepFreeze(manifest); +} + +async function canonicalDirectory(preparedDir) { + if (typeof preparedDir !== "string" || preparedDir.length === 0) fail(); + const directory = resolve(preparedDir); + const metadata = await lstat(directory); + if (!metadata.isDirectory() || metadata.isSymbolicLink()) fail(); + return realpath(directory); +} + +async function readBoundedFile(path, directory, maximum) { + if (dirname(resolve(path)) !== directory) fail(); + const metadata = await lstat(path); + if (!metadata.isFile() || metadata.isSymbolicLink()) fail(); + if ((await realpath(path)) !== join(directory, basename(path))) fail(); + boundedInteger(metadata.size, maximum, 1); + const handle = await open( + path, + constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0), + ); + try { + const opened = await handle.stat(); + if ( + !opened.isFile() || + opened.dev !== metadata.dev || + opened.ino !== metadata.ino || + opened.size !== metadata.size + ) { + fail(); + } + // Read no more than the validated size plus one byte, including if a file + // grows concurrently. No archive contents or package scripts are executed. + const bytes = Buffer.alloc(metadata.size + 1); + let length = 0; + while (length < bytes.length) { + const read = await handle.read( + bytes, + length, + bytes.length - length, + length, + ); + if (read.bytesRead === 0) break; + length += read.bytesRead; + } + if (length !== metadata.size) fail(); + return bytes.subarray(0, length); + } finally { + await handle.close(); + } +} + +async function verifyArtifacts(manifest, directory) { + const artifacts = []; + for (const record of manifest.artifacts) { + const path = join(directory, record.filename); + const bytes = await readBoundedFile( + path, + directory, + PREPARED_MANIFEST_LIMITS.artifactBytes, + ); + if ( + bytes.length !== record.size || + !safeEqual(hash(bytes, "sha1"), record.shasum) || + !safeEqual(`sha512-${hash(bytes, "sha512", "base64")}`, record.integrity) + ) { + fail(); + } + artifacts.push(Object.freeze({ ...record, path })); + } + return Object.freeze(artifacts); +} + +export async function writePreparedManifest({ + preparedDir, + identity, + artifacts, +} = {}) { + try { + // Copy the approved data before freezing it; never freeze the producer's + // npm metadata or mutable source package manifests as a side effect. + const manifest = validatePreparedManifest( + structuredClone({ schemaVersion: 2, identity, artifacts }), + ); + const directory = await canonicalDirectory(preparedDir); + await verifyArtifacts(manifest, directory); + const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`); + if (bytes.length > PREPARED_MANIFEST_LIMITS.manifestBytes) fail(); + const manifestPath = join(directory, "manifest.json"); + await writeFile(manifestPath, bytes, { flag: "wx", mode: 0o644 }); + return Object.freeze({ + manifestPath, + manifest, + manifestSha256: hash(bytes, "sha256"), + }); + } catch { + fail(); + } +} + +export async function verifyPreparedManifest({ + preparedDir, + manifestPath, + expectedManifestSha256, + expectedTag, + expectedCommit, + expectedVersion, +} = {}) { + try { + if ( + typeof expectedManifestSha256 !== "string" || + !/^[0-9a-f]{64}$/u.test(expectedManifestSha256) || + typeof expectedTag !== "string" || + typeof expectedCommit !== "string" || + !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(expectedCommit) + ) { + fail(); + } + const directory = await canonicalDirectory(preparedDir); + const path = + manifestPath === undefined + ? join(directory, "manifest.json") + : resolve(manifestPath); + if (basename(path) !== "manifest.json") fail(); + const bytes = await readBoundedFile( + path, + directory, + PREPARED_MANIFEST_LIMITS.manifestBytes, + ); + const manifestSha256 = hash(bytes, "sha256"); + if (!safeEqual(manifestSha256, expectedManifestSha256)) fail(); + const manifest = validatePreparedManifest( + JSON.parse(bytes.toString("utf8")), + ); + if ( + manifest.identity.tag !== expectedTag || + manifest.identity.commit !== expectedCommit || + (expectedVersion !== undefined && + manifest.identity.version !== expectedVersion) + ) { + fail(); + } + const artifacts = await verifyArtifacts(manifest, directory); + return Object.freeze({ + manifestPath: path, + manifest, + manifestSha256, + artifacts, + }); + } catch { + // Do not include parsed contents, paths, environment values, native command + // output, or registry credentials in release errors. + fail(); + } +} diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 572ab61..06804a3 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -1,73 +1,126 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { createHash, timingSafeEqual } from "node:crypto"; -import { existsSync, realpathSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { constants } from "node:fs"; import { + access, + appendFile, + copyFile, + lstat, mkdtemp, mkdir, readFile, readdir, + realpath, rm, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { basename, delimiter, dirname, join, resolve } from "node:path"; +import { + basename, + delimiter, + dirname, + isAbsolute, + join, + resolve, +} from "node:path"; import { fileURLToPath } from "node:url"; +import { + RELEASE_PACKAGES, + STABLE_VERSION, + releaseDependencies, + verifyReleaseIdentity, +} from "./release-contract.mjs"; +import { + verifyPreparedManifest, + writePreparedManifest, +} from "./release-manifest.mjs"; -const PACKAGE = { - directory: "agent-access", - name: "@pegma/agent-access", -}; -const REPOSITORY_URL = "git+https://github.com/pegma-dev/agent-access.git"; -const RUNTIME_DEPENDENCIES = { - "@pegma/audit": "0.2.0", - "@pegma/authorization-core": "0.4.0", - "@pegma/spine": "0.1.2", - "@pegma/storage-core": "0.4.0", -}; -const REVIEWED_PNPM_VERSION = "10.34.5"; -const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; - -export const RELEASE_PACKAGES = [PACKAGE]; +const root = fileURLToPath(new URL("../", import.meta.url)); +const packages = RELEASE_PACKAGES; +export { RELEASE_PACKAGES, releaseDependencies }; -function fail(message) { - throw new Error(message); +function run(command, arguments_, cwd, env = process.env) { + const result = spawnSync(command, arguments_, { + cwd, + env, + encoding: "utf8", + shell: false, + maxBuffer: 8 * 1024 * 1024, + }); + if (result.error || result.status !== 0) { + throw new Error("Release build, pack, or consumer command failed."); + } + return result.stdout.trim(); } -async function readJson(path) { - return JSON.parse(await readFile(path, "utf8")); +async function exists(path) { + try { + await access(path); + return true; + } catch { + return false; + } } -function safeEqual(left, right) { - const leftBytes = Buffer.from(left); - const rightBytes = Buffer.from(right); - return ( - leftBytes.length === rightBytes.length && - timingSafeEqual(leftBytes, rightBytes) +export async function resolveReleaseNpmCli(env = process.env) { + const candidate = env.RELEASE_NPM_CLI; + assert.ok( + typeof candidate === "string" && + isAbsolute(candidate) && + basename(candidate) === "npm-cli.js", + "The reviewed release npm CLI must be an explicit absolute npm-cli.js path.", + ); + assert.equal( + env.RELEASE_NPM_VERSION, + "11.18.0", + "Release preparation requires the reviewed npm version.", ); + const path = resolve(candidate); + const metadata = await lstat(path); + assert.ok( + metadata.isFile() && !metadata.isSymbolicLink(), + "The release npm CLI must be a regular file.", + ); + const canonical = await realpath(path); + assert.equal( + canonical, + path, + "The release npm CLI must use its canonical path.", + ); + return canonical; } -function run(command, arguments_, options = {}) { - const result = spawnSync(command, arguments_, { - cwd: options.cwd, - encoding: "utf8", - env: options.env ?? process.env, - shell: options.shell ?? false, - stdio: options.capture ? "pipe" : "inherit", - }); - if (result.error) throw result.error; - if (result.status !== 0 && !options.allowFailure) { - const detail = [result.stdout, result.stderr].filter(Boolean).join("\n"); - fail( - `${command} ${arguments_.join(" ")} failed with exit code ${String(result.status)}${detail ? `:\n${detail}` : ""}`, +async function npmCliPath(preparedRelease = false) { + if (preparedRelease) { + const candidate = await resolveReleaseNpmCli(); + const [major, minor] = process.versions.node.split(".").map(Number); + assert.ok( + major > 22 || (major === 22 && minor >= 14), + "Release preparation requires Node 22.14 or newer.", + ); + const versionEnvironment = {}; + for (const [key, value] of Object.entries(process.env)) { + if ( + /^(?:PATH|PATHEXT|SystemRoot|WINDIR|COMSPEC|TEMP|TMP|HOME|USERPROFILE|LOCALAPPDATA|APPDATA)$/iu.test( + key, + ) + ) { + versionEnvironment[key] = value; + } + } + assert.equal( + run( + process.execPath, + [candidate, "--version"], + tmpdir(), + versionEnvironment, + ), + "11.18.0", + "Release preparation npm CLI differs from the reviewed version.", ); + return candidate; } - return result; -} - -function runNpm(arguments_, options = {}) { - // Invoke npm's JavaScript entrypoint directly, including on Windows. Never - // interpret arguments through a shell or mistake pnpm's npm_execpath for npm. const directories = [ dirname(process.execPath), ...(process.env.PATH ?? "").split(delimiter).filter(Boolean), @@ -80,31 +133,39 @@ function runNpm(arguments_, options = {}) { } for (const directory of directories) { const executable = join(directory, "npm"); - if (existsSync(executable)) { - const target = realpathSync(executable); + if (await exists(executable)) { + const target = await realpath(executable); if (basename(target) === "npm-cli.js") candidates.push(target); } } - const npm = candidates.find((candidate) => existsSync(candidate)); - if (npm === undefined) - fail("Cannot locate npm-cli.js beside Node.js or on PATH."); - return run(process.execPath, [npm, ...arguments_], options); + for (const candidate of candidates) { + if (await exists(candidate)) return candidate; + } + throw new Error("Cannot locate npm-cli.js beside Node.js or on PATH."); } -function gitCommand() { - return process.platform === "win32" ? "git.exe" : "git"; +async function json(path) { + return JSON.parse(await readFile(path, "utf8")); } -function hashTarball(bytes) { - return { - shasum: createHash("sha1").update(bytes).digest("hex"), - integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, - }; +const rootDirectory = root; +const PACKAGE = RELEASE_PACKAGES[0]; +const REPOSITORY_URL = "git+https://github.com/pegma-dev/agent-access.git"; +const RUNTIME_DEPENDENCIES = releaseDependencies(PACKAGE.directory, "0.1.0"); +const REVIEWED_PNPM_VERSION = "10.34.5"; +const STABLE_SEMVER = STABLE_VERSION; + +function fail(message) { + throw new Error(message); +} + +async function readJson(path) { + return json(path); } function pnpmLockfileHasImporter(lockfile, importer) { let inImporters = false; - for (const line of lockfile.split("\n")) { + for (const line of lockfile.split(/\r?\n/u)) { if (!inImporters) { if (line === "importers:") inImporters = true; continue; @@ -130,67 +191,8 @@ function exportTargets(value) { return []; } -export function validateReleaseTag(options = {}) { - const root = resolve(options.root ?? defaultRoot()); - const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; - const expectedReleaseCommit = - options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; - if (releaseTag === undefined || !/^v\d+\.\d+\.\d+$/u.test(releaseTag)) { - fail("a stable release tag is required"); - } - if ( - expectedReleaseCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedReleaseCommit) - ) { - fail("an exact release event commit is required"); - } - - const tagRef = `refs/tags/${releaseTag}`; - const type = run(gitCommand(), ["cat-file", "-t", tagRef], { - cwd: root, - capture: true, - allowFailure: true, - }); - if (type.status !== 0 || type.stdout.trim() !== "tag") { - fail("the release ref must be an annotated tag object"); - } - const headCommit = run(gitCommand(), ["rev-parse", "HEAD"], { - cwd: root, - capture: true, - }).stdout.trim(); - const tagCommit = run(gitCommand(), ["rev-parse", `${tagRef}^{commit}`], { - cwd: root, - capture: true, - }).stdout.trim(); - if ( - !safeEqual(headCommit, tagCommit) || - !safeEqual(headCommit, expectedReleaseCommit) - ) { - fail( - "the release checkout, signed tag target, and release event commit must match", - ); - } - const signature = run(gitCommand(), ["verify-tag", "--raw", tagRef], { - cwd: root, - capture: true, - allowFailure: true, - }); - if (signature.status !== 0) { - fail("the release tag signature is not valid for an approved signer"); - } - const onMain = run( - gitCommand(), - ["merge-base", "--is-ancestor", tagCommit, "refs/remotes/origin/main"], - { cwd: root, capture: true, allowFailure: true }, - ); - if (onMain.status !== 0) { - fail("the release tag commit must be contained in origin/main"); - } - return { headCommit, releaseTag }; -} - export async function validateRepository(options = {}) { - const root = resolve(options.root ?? defaultRoot()); + const root = resolve(options.root ?? rootDirectory); const rootManifest = await readJson(join(root, "package.json")); const packageDirectory = join(root, "packages", PACKAGE.directory); const manifest = await readJson(join(packageDirectory, "package.json")); @@ -211,6 +213,7 @@ export async function validateRepository(options = {}) { manifest.license !== "MIT" || manifest.type !== "module" || manifest.publishConfig?.access !== "public" || + Object.keys(manifest.publishConfig).length !== 1 || manifest.engines?.node !== ">=22" || manifest.repository?.type !== "git" || manifest.repository?.url !== REPOSITORY_URL || @@ -223,6 +226,7 @@ export async function validateRepository(options = {}) { "peerDependencies", "optionalDependencies", "bundledDependencies", + "bundleDependencies", ]) { assert.equal( manifest[kind], @@ -234,8 +238,9 @@ export async function validateRepository(options = {}) { !Array.isArray(manifest.files) || manifest.files.length === 0 || manifest.files.some((entry) => !entry.startsWith("dist/")) || - typeof manifest.scripts?.prepack !== "string" || - !manifest.scripts.prepack.includes("build") + !["pnpm run build", "pnpm run --silent build"].includes( + manifest.scripts?.prepack, + ) ) { fail(`${PACKAGE.name} has an unsafe package allowlist or prepack`); } @@ -289,75 +294,65 @@ export async function validateRepository(options = {}) { fail("public workspace inventory does not match the reviewed release list"); } - if (options.requireClean) { - const status = run(gitCommand(), ["status", "--porcelain"], { - cwd: root, - capture: true, - }).stdout; - if (status.trim() !== "") - fail("release preparation requires a clean checkout"); - } - if (options.requireMainAncestor) { - const head = run(gitCommand(), ["rev-parse", "HEAD"], { - cwd: root, - capture: true, - }).stdout.trim(); - const onMain = run( - gitCommand(), - ["merge-base", "--is-ancestor", head, "refs/remotes/origin/main"], - { cwd: root, capture: true, allowFailure: true }, - ); - if (onMain.status !== 0) { - fail("release commit must be contained in origin/main"); - } - } + return { root, manifest, packageDirectory }; +} - const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; - if (releaseTag !== undefined && releaseTag !== `v${manifest.version}`) { - fail(`release tag must be v${manifest.version}`); - } - const prerelease = - options.releasePrerelease ?? process.env.RELEASE_PRERELEASE ?? false; - if (prerelease === true || prerelease === "true") { - fail("prereleases cannot publish packages"); - } - if (options.requireReleaseTag) { - validateReleaseTag({ - root, - releaseTag, - expectedReleaseCommit: options.expectedReleaseCommit, - }); - } - return { root, manifest, packageDirectory, releaseTag }; +async function validatePackages() { + const { manifest } = await validateRepository(); + return [manifest]; } -function verifyPackedFiles(manifest, files) { - const paths = files.map(({ path }) => path); - for (const required of ["package.json", "README.md", "LICENSE"]) { - if (!paths.includes(required)) - fail(`${manifest.name} is missing ${required}`); +function validateInventory(metadata) { + const paths = metadata.files.map(({ path }) => path); + for (const required of [ + "package.json", + "README.md", + "LICENSE", + "dist/index.js", + "dist/index.d.ts", + ]) { + assert.ok(paths.includes(required), `Tarball is missing ${required}.`); } - if ( - paths.some( - (path) => - !["package.json", "README.md", "LICENSE"].includes(path) && - (!/^dist\/[A-Za-z0-9_./-]+\.(?:js|js\.map|d\.ts|d\.ts\.map)$/u.test( + for (const path of paths) { + const parts = path.split("/"); + assert.ok(!parts.some((part) => part === "." || part === "..")); + assert.ok( + ["package.json", "README.md", "LICENSE"].includes(path) || + (/^dist\/[A-Za-z0-9_./-]+\.(?:js|js\.map|d\.ts|d\.ts\.map)$/u.test( path, - ) || - path.split("/").some((part) => part === "." || part === "..") || - /\.(?:test|spec)\./u.test(path)), - ) - ) { - fail(`${manifest.name} tarball contains an unreviewed file`); + ) && + !/\.(?:test|spec)\./u.test(path)), + `Unexpected packaged file: ${path}`, + ); } - for (const target of exportTargets(manifest.exports)) { - const path = target.replace(/^\.\//u, ""); - if (!paths.includes(path)) fail(`${manifest.name} is missing ${path}`); +} + +function sourceEnvironment(directory) { + const env = {}; + for (const [key, value] of Object.entries(process.env)) { + if ( + /^(?:PATH|PATHEXT|SystemRoot|WINDIR|COMSPEC|TEMP|TMP|HOME|USERPROFILE|LOCALAPPDATA|APPDATA)$/iu.test( + key, + ) + ) { + env[key] = value; + } } + return { + ...env, + CI: "true", + npm_config_userconfig: join(directory, "user.npmrc"), + npm_config_globalconfig: join(directory, "global.npmrc"), + npm_config_cache: join(directory, "cache"), + npm_config_registry: "https://registry.npmjs.org/", + npm_config_ignore_scripts: "true", + npm_config_audit: "false", + npm_config_fund: "false", + }; } -async function smokeTestTarball(tarball, manifest) { - const temporaryParent = realpathSync(tmpdir()); +async function smokeTestTarball(tarball, manifest, npm, env) { + const temporaryParent = await realpath(tmpdir()); const directory = await mkdtemp( join(temporaryParent, "agent-access-release-smoke-"), ); @@ -366,15 +361,10 @@ async function smokeTestTarball(tarball, manifest) { join(directory, "package.json"), '{"name":"agent-access-release-smoke","private":true,"type":"module"}\n', ); - const npmrc = join(directory, "npmrc"); - await writeFile(npmrc, "registry=https://registry.npmjs.org/\n"); - const env = { - ...process.env, - npm_config_userconfig: npmrc, - npm_config_registry: "https://registry.npmjs.org/", - }; - runNpm( + run( + process.execPath, [ + npm, "install", "--ignore-scripts", "--no-audit", @@ -382,7 +372,8 @@ async function smokeTestTarball(tarball, manifest) { "--package-lock=false", tarball, ], - { cwd: directory, capture: true, env }, + directory, + env, ); const consumerSource = join(directory, "consumer.mts"); await writeFile( @@ -408,7 +399,7 @@ void decision; run( process.execPath, [ - join(defaultRoot(), "node_modules", "typescript", "bin", "tsc"), + join(root, "node_modules", "typescript", "bin", "tsc"), "--strict", "--exactOptionalPropertyTypes", "--noUncheckedIndexedAccess", @@ -422,7 +413,8 @@ void decision; "--skipLibCheck", consumerSource, ], - { cwd: directory, capture: true, env }, + directory, + env, ); for (const key of Object.keys(manifest.exports)) { const specifier = @@ -486,291 +478,411 @@ await assert.rejects(service.authenticate({ }), (error) => error instanceof api.OAuthError && error.code === "invalid_token"); `, ], - { cwd: directory, capture: true, env }, + directory, + env, ); } } finally { - const cleanup = realpathSync(directory); + const cleanup = await realpath(directory); assert.equal(dirname(cleanup), temporaryParent); assert.ok(basename(cleanup).startsWith("agent-access-release-smoke-")); await rm(cleanup, { recursive: true, force: true }); } } -export async function prepareRelease(options = {}) { - const { root, manifest, packageDirectory, releaseTag } = - await validateRepository(options); - const gitCommit = run(gitCommand(), ["rev-parse", "HEAD"], { - cwd: root, - capture: true, - }).stdout.trim(); - const output = resolve(root, options.output ?? ".release"); - await mkdir(output, { recursive: true }); - if ((await readdir(output)).length !== 0) { - fail(`release output directory must be empty: ${output}`); - } - - runNpm(["run", "build"], { cwd: root }); - const result = runNpm( - ["pack", packageDirectory, "--json", "--pack-destination", output], - { cwd: root, capture: true }, +async function prepareArtifacts(mode, options = {}) { + const manifests = await validatePackages(); + const identity = + mode === "prepare" + ? verifyReleaseIdentity({ + root, + tag: options.tag, + expectedCommit: options.expectedCommit, + version: manifests[0].version, + }) + : undefined; + const npm = await npmCliPath(mode === "prepare"); + const temporaryParent = await realpath(tmpdir()); + const temporary = await mkdtemp( + join(temporaryParent, "pegma-agent-access-release-"), ); - const [packed] = JSON.parse(result.stdout); - if ( - packed?.name !== manifest.name || - packed?.version !== manifest.version || - typeof packed.filename !== "string" || - !Array.isArray(packed.files) - ) { - fail("npm pack returned invalid metadata"); + try { + await writeFile(join(temporary, "user.npmrc"), ""); + await writeFile(join(temporary, "global.npmrc"), ""); + const env = sourceEnvironment(temporary); + await cleanBuildOutputs(); + // Emit every output from this checkout. Packing below disables scripts so + // an incremental prepack cannot replace this fresh artifact. + run( + process.execPath, + [ + join(root, "node_modules", "typescript", "bin", "tsc"), + "-b", + "--force", + ...packages.map(({ directory }) => + join(root, "packages", directory, "tsconfig.json"), + ), + ], + root, + env, + ); + const artifacts = []; + for (const [index, specification] of packages.entries()) { + const output = run( + process.execPath, + [ + npm, + "pack", + "--json", + "--ignore-scripts", + "--registry", + "https://registry.npmjs.org/", + "--pack-destination", + temporary, + ], + join(root, "packages", specification.directory), + env, + ); + const packed = JSON.parse(output); + assert.equal(packed.length, 1); + const metadata = packed[0]; + assert.equal(metadata.name, specification.name); + assert.equal(metadata.version, manifests[index].version); + assert.equal(basename(metadata.filename), metadata.filename); + assert.equal( + metadata.filename, + `${specification.name.slice(1).replace("/", "-")}-${manifests[index].version}.tgz`, + ); + validateInventory(metadata); + const bytes = await readFile(join(temporary, metadata.filename)); + assert.equal(bytes.length, metadata.size); + assert.equal( + createHash("sha1").update(bytes).digest("hex"), + metadata.shasum, + ); + assert.equal( + `sha512-${createHash("sha512").update(bytes).digest("base64")}`, + metadata.integrity, + ); + artifacts.push(metadata); + } + await smokeTestTarball( + join(temporary, artifacts[0].filename), + manifests[0], + npm, + env, + ); + if (mode === "pack") { + const releases = join(root, ".release"); + await mkdir(releases, { recursive: true }); + const destination = await mkdtemp(join(releases, "agent-access-")); + for (const { filename } of artifacts) { + await copyFile(join(temporary, filename), join(destination, filename)); + } + await writeFile( + join(destination, "manifest.json"), + `${JSON.stringify({ schemaVersion: 1, artifacts }, null, 2)}\n`, + ); + console.log(`Prepared verified artifacts in ${destination}`); + } + if (mode === "prepare") { + // Check the reviewed source again after build and consumer execution, + // before creating any output directory that could dirty the checkout. + assert.deepEqual( + verifyReleaseIdentity({ + root, + tag: options.tag, + expectedCommit: options.expectedCommit, + version: identity.version, + }), + identity, + ); + const preparedDir = await preparedDirectory(options.output); + for (const { filename } of artifacts) { + await copyFile( + join(temporary, filename), + join(preparedDir, filename), + constants.COPYFILE_EXCL, + ); + } + const prepared = await writePreparedManifest({ + preparedDir, + identity, + artifacts: artifacts.map((artifact, index) => ({ + name: artifact.name, + version: artifact.version, + filename: artifact.filename, + size: artifact.size, + shasum: artifact.shasum, + integrity: artifact.integrity, + dependencies: manifests[index].dependencies, + files: artifact.files + .map(({ path, size }) => ({ path, size })) + .sort((left, right) => left.path.localeCompare(right.path)), + })), + }); + return { preparedDir, ...prepared }; + } + console.log( + `Verified packaging and clean-consumer imports for ${artifacts.length} packages, including public types and OAuth API behavior.`, + ); + } finally { + const cleanup = await realpath(temporary); + assert.equal(dirname(cleanup), temporaryParent); + assert.ok(basename(cleanup).startsWith("pegma-agent-access-release-")); + await rm(cleanup, { recursive: true, force: true }); } - verifyPackedFiles(manifest, packed.files); - const tarballPath = join(output, basename(packed.filename)); - const hashes = hashTarball(await readFile(tarballPath)); - if ( - !safeEqual(hashes.integrity, packed.integrity) || - !safeEqual(hashes.shasum, packed.shasum) - ) { - fail("tarball hashes do not match npm pack metadata"); - } - await smokeTestTarball(tarballPath, manifest); - - const prepared = { - schemaVersion: 1, - gitCommit, - releaseTag: releaseTag ?? null, - package: { - name: manifest.name, - version: manifest.version, - tarball: basename(tarballPath), - integrity: hashes.integrity, - shasum: hashes.shasum, - files: packed.files - .map(({ path, size }) => ({ path, size })) - .sort((left, right) => left.path.localeCompare(right.path)), - }, - }; - const manifestPath = join(output, "package-manifest.json"); - await writeFile(manifestPath, `${JSON.stringify(prepared, null, 2)}\n`); - return { manifestPath, manifest: prepared }; } -function queryRegistryIntegrity(name, version) { - const spec = `${name}@${version}`; - const result = runNpm(["view", spec, "dist.integrity", "--json"], { - capture: true, - allowFailure: true, - }); - if (result.status === 0) { - const integrity = JSON.parse(result.stdout); - if (typeof integrity !== "string" || integrity.length === 0) { - fail(`${spec} exists without dist.integrity`); - } - return integrity; +async function optionalMetadata(path) { + try { + return await lstat(path); + } catch (error) { + if (error.code === "ENOENT") return undefined; + throw error; } - const output = `${result.stdout}\n${result.stderr}`; - if (/\bE404\b/u.test(output)) return null; - fail(`npm registry lookup failed for ${spec}:\n${output.trim()}`); } -export function decidePublication(localIntegrity, registryIntegrity) { - if (registryIntegrity === null) return "publish"; - if (safeEqual(localIntegrity, registryIntegrity)) return "skip"; - fail("the registry version exists with different tarball integrity"); +async function canonicalNode(path, kind) { + const metadata = await lstat(path); + assert.ok( + !metadata.isSymbolicLink() && + (kind === "directory" ? metadata.isDirectory() : metadata.isFile()), + "Release build output paths must not contain symlinks or special files.", + ); + assert.equal( + await realpath(path), + path, + "Release build output paths must stay inside their canonical package.", + ); } -function requireTrustedPublishingNpm() { - const version = runNpm(["--version"], { capture: true }).stdout.trim(); - const match = /^(\d+)\.(\d+)\.(\d+)(?:-.+)?$/u.exec(version); - if (match === null) fail(`could not parse npm version ${version}`); - const [major, minor, patch] = match.slice(1).map(Number); - if ( - major < 11 || - (major === 11 && minor < 5) || - (major === 11 && minor === 5 && patch < 1) - ) { - fail("trusted publishing requires npm 11.5.1 or newer"); +async function validateOutputTree(path) { + await canonicalNode(path, "directory"); + for (const entry of await readdir(path, { withFileTypes: true })) { + const child = join(path, entry.name); + assert.equal(dirname(child), path); + if (entry.isDirectory()) { + await validateOutputTree(child); + } else { + await canonicalNode(child, "file"); + } } } -function wait(milliseconds) { - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); +export async function cleanBuildOutputs(checkoutRoot = root) { + const checkout = resolve(checkoutRoot); + await canonicalNode(checkout, "directory"); + const packageRoot = join(checkout, "packages"); + await canonicalNode(packageRoot, "directory"); + const outputs = []; + // Preflight every target before removing any file. Output names are fixed by + // this reviewed producer; never turn tsconfig values into deletion targets. + for (const specification of packages) { + const packageDirectory = join(packageRoot, specification.directory); + assert.equal(dirname(packageDirectory), packageRoot); + await canonicalNode(packageDirectory, "directory"); + const configurationPath = join(packageDirectory, "tsconfig.json"); + await canonicalNode(configurationPath, "file"); + const configuration = await json(configurationPath); + assert.equal(configuration.compilerOptions?.outDir, "dist"); + assert.equal(configuration.compilerOptions?.rootDir, "src"); + assert.equal( + configuration.compilerOptions?.tsBuildInfoFile, + "tsconfig.tsbuildinfo", + ); + const directory = join(packageDirectory, "dist"); + const buildInfo = join(packageDirectory, "tsconfig.tsbuildinfo"); + assert.equal(dirname(directory), packageDirectory); + assert.equal(dirname(buildInfo), packageDirectory); + if (await optionalMetadata(directory)) await validateOutputTree(directory); + if (await optionalMetadata(buildInfo)) + await canonicalNode(buildInfo, "file"); + outputs.push({ directory, buildInfo }); + } + for (const { directory, buildInfo } of outputs) { + // Recheck the exact targets immediately before deletion as well. Do not + // follow junctions/symlinks even when they point back inside the checkout. + if (await optionalMetadata(directory)) { + await validateOutputTree(directory); + await rm(directory, { recursive: true, force: true }); + } + if (await optionalMetadata(buildInfo)) { + await canonicalNode(buildInfo, "file"); + await rm(buildInfo); + } + } } -function confirmRegistryIntegrity(record) { - for (let attempt = 0; attempt < 6; attempt += 1) { - const integrity = queryRegistryIntegrity(record.name, record.version); - if (integrity !== null && safeEqual(record.integrity, integrity)) return; - if (attempt < 5) wait(2 ** attempt * 1000); - } - fail( - `${record.name}@${record.version} did not expose the prepared integrity`, +async function preparedDirectory(output) { + if (output === undefined) { + const releases = join(root, ".release"); + await mkdir(releases, { recursive: true }); + return realpath(await mkdtemp(join(releases, "agent-access-"))); + } + assert.equal(typeof output, "string", "Release output must be a directory."); + assert.ok(output.length > 0, "Release output must be a directory."); + const destination = resolve(root, output); + await mkdir(destination, { recursive: true }); + const metadata = await lstat(destination); + assert.ok( + metadata.isDirectory() && !metadata.isSymbolicLink(), + "Release output must be a regular directory.", + ); + assert.equal( + (await readdir(destination)).length, + 0, + "Release output directory must be empty.", ); + return realpath(destination); } -async function verifyPreparedManifest(path) { - const prepared = await readJson(path); - const record = prepared.package; - if ( - prepared.schemaVersion !== 1 || - !/^[0-9a-f]{40,64}$/u.test(prepared.gitCommit) || - prepared.releaseTag !== `v${record?.version}` || - record?.name !== PACKAGE.name || - !STABLE_SEMVER.test(record.version) || - typeof record.integrity !== "string" || - typeof record.shasum !== "string" || - !Array.isArray(record.files) - ) { - fail("prepared package manifest is invalid"); - } - const currentCommit = run(gitCommand(), ["rev-parse", "HEAD"], { - cwd: defaultRoot(), - capture: true, - }).stdout.trim(); - if (!safeEqual(currentCommit, prepared.gitCommit)) { - fail("prepared package manifest commit does not match the checkout"); - } - const expectedTarball = `${PACKAGE.name - .slice(1) - .replace("/", "-")}-${record.version}.tgz`; - if (record.tarball !== expectedTarball) - fail("prepared tarball name is invalid"); - const tarball = resolve(dirname(path), record.tarball); - if (dirname(tarball) !== resolve(dirname(path))) { - fail("prepared tarball must be beside the package manifest"); - } - const hashes = hashTarball(await readFile(tarball)); - if ( - !safeEqual(hashes.integrity, record.integrity) || - !safeEqual(hashes.shasum, record.shasum) - ) { - fail("prepared tarball has changed"); - } - return prepared; +export async function prepareRelease(options = {}) { + return prepareArtifacts("prepare", options); +} + +export async function preflightRelease(options = {}) { + const verified = await verifyPreparedManifest(options); + const { preflightRegistry } = await import("./release-registry.mjs"); + return preflightRegistry(verified); } export async function publishPreparedRelease(options = {}) { - if ( - process.env.GITHUB_ACTIONS !== "true" || - process.env.GITHUB_EVENT_NAME !== "release" - ) { - fail("release:publish is restricted to a GitHub release workflow"); - } - requireTrustedPublishingNpm(); - const path = resolve(options.manifest ?? ".release/package-manifest.json"); - const prepared = await verifyPreparedManifest(path); - const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; - const expectedCommit = - options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; - if (releaseTag !== prepared.releaseTag) { - fail("prepared manifest must match the release tag"); - } - if ( - expectedCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedCommit) || - !safeEqual(expectedCommit, prepared.gitCommit) - ) { - fail("prepared package manifest must match the release event commit"); - } + await verifyPreparedManifest(options); + const { publishPreparedRelease: publish } = + await import("./release-registry.mjs"); + return publish(options); +} - const record = prepared.package; - const decision = decidePublication( - record.integrity, - queryRegistryIntegrity(record.name, record.version), - ); - if (decision === "skip") { - process.stdout.write( - `Verified existing ${record.name}@${record.version}; skipping.\n`, - ); - return; - } - runNpm( - [ - "publish", - resolve(dirname(path), record.tarball), - "--access", - "public", - "--provenance", - ], - { cwd: dirname(path) }, - ); - confirmRegistryIntegrity(record); +export async function verifyRelease(options = {}) { + await verifyPreparedManifest(options); + const { verifyRegistryRelease } = await import("./release-registry.mjs"); + return verifyRegistryRelease(options); } +const usage = + "Usage: release-packages.mjs check|pack|prepare|preflight|publish|verify [options]"; + export function parseArguments(arguments_) { + const [command, ...flags] = arguments_; + assert.ok( + ["check", "pack", "prepare", "preflight", "publish", "verify"].includes( + command, + ), + usage, + ); + if (command === "check" || command === "pack") { + assert.equal(flags.length, 0, "No additional arguments are supported."); + return { command, options: {} }; + } + const keys = + command === "prepare" + ? { + "--tag": "tag", + "--expected-commit": "expectedCommit", + "--out": "output", + } + : { + "--prepared-dir": "preparedDir", + "--manifest-sha256": "expectedManifestSha256", + "--tag": "expectedTag", + "--expected-commit": "expectedCommit", + }; const options = {}; - for (let index = 0; index < arguments_.length; index += 1) { - const argument = arguments_[index]; - if (argument === "--") continue; - if (argument === "--require-main-ancestor") { - options.requireMainAncestor = true; - continue; - } - if (argument === "--require-clean") { - options.requireClean = true; - continue; - } - if (argument === "--require-release-tag") { - options.requireReleaseTag = true; - continue; - } - const key = - argument === "--root" - ? "root" - : argument === "--output" - ? "output" - : argument === "--manifest" - ? "manifest" - : argument === "--expected-release-commit" - ? "expectedReleaseCommit" - : null; - if (key === null || arguments_[index + 1] === undefined) { - fail(`unknown or incomplete argument: ${argument}`); - } - options[key] = arguments_[index + 1]; - index += 1; + for (let index = 0; index < flags.length; index += 2) { + const key = Object.hasOwn(keys, flags[index]) + ? keys[flags[index]] + : undefined; + const value = flags[index + 1]; + assert.ok( + key !== undefined && + !Object.hasOwn(options, key) && + typeof value === "string" && + value.length > 0 && + !value.startsWith("--") && + !/[\u0000-\u001f\u007f]/u.test(value), + "Unknown, repeated, or incomplete release argument.", + ); + options[key] = value; + } + const tag = command === "prepare" ? options.tag : options.expectedTag; + assert.ok( + typeof tag === "string" && + tag.startsWith("v") && + STABLE_VERSION.test(tag.slice(1)), + "An exact stable release tag is required.", + ); + assert.ok( + typeof options.expectedCommit === "string" && + /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(options.expectedCommit), + "An exact release event commit is required.", + ); + if (command !== "prepare") { + assert.equal( + typeof options.preparedDir, + "string", + "A prepared release directory is required.", + ); + assert.ok( + typeof options.expectedManifestSha256 === "string" && + /^[0-9a-f]{64}$/u.test(options.expectedManifestSha256), + "An independent prepared manifest SHA-256 is required.", + ); } - return options; + return { command, options }; } -function defaultRoot() { - return resolve(dirname(fileURLToPath(import.meta.url)), ".."); +async function reportPrepared(prepared) { + const values = { + "prepared-dir": prepared.preparedDir, + "manifest-path": prepared.manifestPath, + "manifest-sha256": prepared.manifestSha256, + }; + const output = Object.entries(values) + .map(([key, value]) => { + assert.ok( + !/[\u0000-\u001f\u007f]/u.test(value), + "Release output must be single-line.", + ); + return `${key}=${value}\n`; + }) + .join(""); + process.stdout.write(output); + if (process.env.GITHUB_ACTIONS === "true" && process.env.GITHUB_OUTPUT) { + await appendFile(process.env.GITHUB_OUTPUT, output); + } } async function main() { - const [command, ...arguments_] = process.argv.slice(2); - const options = parseArguments(arguments_); - if (command === "check") { - const temporaryParent = realpathSync(tmpdir()); - const output = await mkdtemp( - join(temporaryParent, "agent-access-release-check-"), - ); - try { - await prepareRelease({ ...options, output }); - } finally { - const cleanup = realpathSync(output); - assert.equal(dirname(cleanup), temporaryParent); - assert.ok(basename(cleanup).startsWith("agent-access-release-check-")); - await rm(cleanup, { recursive: true, force: true }); + const { command, options } = parseArguments(process.argv.slice(2)); + if (command === "check" || command === "pack") { + await prepareArtifacts(command); + } else if (command === "prepare") { + await reportPrepared(await prepareRelease(options)); + } else if (command === "preflight") { + const plan = await preflightRelease(options); + for (const record of plan) { + console.log(`${record.name}@${record.version}: ${record.action}`); } - process.stdout.write( - "Verified package metadata, tarball inventory, and clean-consumer behavior.\n", + } else if (command === "publish") { + const result = await publishPreparedRelease(options); + console.log( + `Verified publication of ${result.published.length} packages; ${result.skipped.length} already identical.`, + ); + } else { + const result = await verifyRelease(options); + console.log( + `Verified registry release and clean consumer for ${result.packages.length} packages.`, ); - return; - } - if (command === "pack") { - const { manifestPath } = await prepareRelease(options); - process.stdout.write(`Prepared release package at ${manifestPath}.\n`); - return; - } - if (command === "publish") { - await publishPreparedRelease(options); - return; } - fail("usage: release-packages.mjs [options]"); } -const isMain = +if ( process.argv[1] !== undefined && - resolve(process.argv[1]) === fileURLToPath(import.meta.url); -if (isMain) await main(); + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + main().catch((error) => { + console.error(error.message); + process.exitCode = 1; + }); +} diff --git a/scripts/release-registry.mjs b/scripts/release-registry.mjs new file mode 100644 index 0000000..1a0df12 --- /dev/null +++ b/scripts/release-registry.mjs @@ -0,0 +1,691 @@ +import { spawnSync } from "node:child_process"; +import { createHash, timingSafeEqual, X509Certificate } from "node:crypto"; +import { + copyFile, + lstat, + mkdtemp, + readFile, + realpath, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, dirname, isAbsolute, join, resolve } from "node:path"; +import { RELEASE_PACKAGES, RELEASE_REPOSITORY } from "./release-contract.mjs"; +import { + validatePreparedManifest, + verifyPreparedManifest, +} from "./release-manifest.mjs"; + +export const RELEASE_NPM_VERSION = "11.18.0"; +export const RELEASE_WORKFLOW = ".github/workflows/publish.yml"; +const registry = "https://registry.npmjs.org/"; +const provenanceType = "https://slsa.dev/provenance/v1"; +const temporaryPrefix = "agent-access-registry-"; + +function fail(message) { + // Never surface native command output, registry response bodies, or credentials. + throw new Error(message); +} + +function equal(left, right) { + if (typeof left !== "string" || typeof right !== "string") return false; + const a = Buffer.from(left); + const b = Buffer.from(right); + return a.length === b.length && timingSafeEqual(a, b); +} + +function hash(bytes, algorithm, encoding = "hex") { + return createHash(algorithm).update(bytes).digest(encoding); +} + +function sameDependencies(actual, expected) { + return ( + actual !== null && + typeof actual === "object" && + !Array.isArray(actual) && + Object.keys(actual).length === Object.keys(expected).length && + Object.entries(expected).every( + ([name, version]) => actual[name] === version, + ) + ); +} + +function tarballUrl(record) { + return `${registry}${record.name}/-/${record.name.split("/")[1]}-${record.version}.tgz`; +} + +async function responseBytes(response, maximum) { + const length = response.headers?.get("content-length"); + if ( + length !== null && + length !== undefined && + (!/^\d+$/u.test(length) || Number(length) > maximum) + ) { + await response.body?.cancel(); + fail("registry response exceeded its release verification limit"); + } + const chunks = []; + let size = 0; + if (response.body === null || response.body === undefined) + return Buffer.alloc(0); + for await (const chunk of response.body) { + size += chunk.length; + if (size > maximum) { + fail("registry response exceeded its release verification limit"); + } + chunks.push(Buffer.from(chunk)); + } + return Buffer.concat(chunks, size); +} + +async function request(url, fetch) { + try { + return await fetch(url, { + redirect: "error", + signal: AbortSignal.timeout(30_000), + headers: { accept: "application/json" }, + }); + } catch { + fail("registry lookup failed; package availability is unknown"); + } +} + +async function registryRecord(record, fetch) { + const response = await request( + `${registry}${encodeURIComponent(record.name)}/${record.version}`, + fetch, + ); + // Authentication errors, throttling, server errors, redirects, and malformed + // responses are unknown states. Only this exact response establishes absence. + if (response.status === 404) { + await response.body?.cancel(); + return null; + } + if (response.status !== 200) { + await response.body?.cancel(); + fail("registry lookup failed; package availability is unknown"); + } + let metadata; + try { + metadata = JSON.parse( + (await responseBytes(response, 2 * 1024 * 1024)).toString("utf8"), + ); + } catch { + fail("registry package metadata verification failed"); + } + if ( + metadata?.name !== record.name || + metadata.version !== record.version || + !sameDependencies(metadata.dependencies, record.dependencies) || + !equal(metadata.dist?.integrity, record.integrity) || + !equal(metadata.dist?.shasum, record.shasum) || + metadata.dist?.tarball !== tarballUrl(record) || + [ + "optionalDependencies", + "peerDependencies", + "bundledDependencies", + "bundleDependencies", + ].some((key) => metadata[key] !== undefined) + ) { + fail("registry version conflicts with the prepared release"); + } + const tarball = await request(metadata.dist.tarball, fetch); + if (tarball.status !== 200) { + await tarball.body?.cancel(); + fail("registry tarball verification failed"); + } + let bytes; + try { + bytes = await responseBytes(tarball, record.size); + } catch { + fail("registry tarball verification failed"); + } + if ( + bytes.length !== record.size || + !equal(hash(bytes, "sha1"), record.shasum) || + !equal(`sha512-${hash(bytes, "sha512", "base64")}`, record.integrity) + ) { + fail("registry tarball conflicts with the prepared release"); + } + return metadata; +} + +export async function preflightRegistry( + verified, + { fetch = globalThis.fetch } = {}, +) { + const manifest = validatePreparedManifest(verified?.manifest); + const decisions = []; + // Finish the entire set before the caller can publish even the first package. + for (const record of manifest.artifacts) { + const metadata = await registryRecord(record, fetch); + decisions.push( + Object.freeze({ + name: record.name, + version: record.version, + action: metadata === null ? "publish" : "skip", + ...(metadata === null ? {} : { metadata }), + }), + ); + } + return Object.freeze(decisions); +} + +export function assertTrustedPublishingEnvironment(env, identity) { + const workflow = `${RELEASE_REPOSITORY}/${RELEASE_WORKFLOW}@refs/tags/${identity.tag}`; + let oidcUrl; + try { + oidcUrl = new URL(env.ACTIONS_ID_TOKEN_REQUEST_URL); + } catch { + fail("publishing requires the approved GitHub Actions OIDC environment"); + } + if ( + env.GITHUB_ACTIONS !== "true" || + env.GITHUB_EVENT_NAME !== "release" || + env.GITHUB_REPOSITORY !== RELEASE_REPOSITORY || + env.GITHUB_SERVER_URL !== "https://github.com" || + env.GITHUB_REF !== `refs/tags/${identity.tag}` || + env.GITHUB_SHA !== identity.commit || + env.GITHUB_WORKFLOW_REF !== workflow || + env.GITHUB_WORKFLOW_SHA !== identity.commit || + env.RUNNER_ENVIRONMENT !== "github-hosted" || + oidcUrl.protocol !== "https:" || + oidcUrl.username !== "" || + oidcUrl.password !== "" || + !/^(?:[A-Za-z0-9-]+\.)*actions\.githubusercontent\.com$/u.test( + oidcUrl.hostname, + ) || + typeof env.ACTIONS_ID_TOKEN_REQUEST_TOKEN !== "string" || + env.ACTIONS_ID_TOKEN_REQUEST_TOKEN.length === 0 + ) { + fail("publishing requires the approved GitHub Actions OIDC environment"); + } + if ( + Object.entries(env).some( + ([key, value]) => + value !== undefined && + value !== "" && + (/^(?:NODE_AUTH_TOKEN|NPM_TOKEN|NPM_AUTH_TOKEN|NPM_AUTH|YARN_NPM_AUTH_TOKEN)$/iu.test( + key, + ) || + /^npm_config_/iu.test(key)), + ) + ) { + fail("publishing rejects npm credentials and inherited npm configuration"); + } +} + +async function nativeRun(command, arguments_, { cwd, env }) { + const result = spawnSync(command, arguments_, { + cwd, + env, + shell: false, + encoding: "utf8", + stdio: "pipe", + maxBuffer: 16 * 1024 * 1024, + timeout: 5 * 60_000, + }); + if (result.error || result.status !== 0) { + fail("release npm or consumer verification command failed"); + } + return result; +} + +async function temporary(action) { + const parent = await realpath(tmpdir()); + const directory = await mkdtemp(join(parent, temporaryPrefix)); + try { + return await action(directory); + } finally { + const target = await realpath(directory); + if ( + dirname(target) !== parent || + !basename(target).startsWith(temporaryPrefix) + ) { + fail("registry consumer cleanup refused an unexpected directory"); + } + await rm(target, { recursive: true, force: true }); + } +} + +function isolatedEnvironment(env, directory, publishing) { + const clean = {}; + // Pinned npm needs public provenance metadata and its OIDC request credential. + const publishingKeys = new Set([ + "GITHUB_ACTIONS", + "GITHUB_EVENT_NAME", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_SERVER_URL", + "GITHUB_REF", + "GITHUB_SHA", + "GITHUB_WORKFLOW_REF", + "GITHUB_WORKFLOW_SHA", + "GITHUB_RUN_ID", + "GITHUB_RUN_ATTEMPT", + "RUNNER_ENVIRONMENT", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + ]); + for (const [key, value] of Object.entries(env)) { + if ( + /^(?:PATH|PATHEXT|SystemRoot|WINDIR|COMSPEC|TEMP|TMP|HOME|USERPROFILE|LOCALAPPDATA|APPDATA)$/iu.test( + key, + ) || + (publishing && publishingKeys.has(key)) + ) { + clean[key] = value; + } + } + return { + ...clean, + CI: "true", + npm_config_userconfig: join(directory, "user.npmrc"), + npm_config_globalconfig: join(directory, "global.npmrc"), + npm_config_cache: join(directory, "cache"), + npm_config_registry: registry, + npm_config_ignore_scripts: "true", + npm_config_audit: "false", + npm_config_fund: "false", + ...(publishing ? { GITHUB_ACTIONS: "true" } : {}), + }; +} + +async function npmContext(options, seams, directory, publishing) { + const sourceEnv = seams.env ?? process.env; + const cli = options.npmCli ?? sourceEnv.RELEASE_NPM_CLI; + const version = + options.npmVersion ?? sourceEnv.RELEASE_NPM_VERSION ?? RELEASE_NPM_VERSION; + const [nodeMajor, nodeMinor] = process.versions.node.split(".").map(Number); + if (nodeMajor < 22 || (nodeMajor === 22 && nodeMinor < 14)) { + fail("trusted release verification requires Node 22.14 or newer"); + } + if ( + typeof cli !== "string" || + !isAbsolute(cli) || + basename(cli) !== "npm-cli.js" || + version !== RELEASE_NPM_VERSION + ) { + fail("release operations require the reviewed pinned npm CLI"); + } + const resolvedCli = resolve(cli); + const metadata = await lstat(resolvedCli); + if ( + !metadata.isFile() || + metadata.isSymbolicLink() || + (await realpath(resolvedCli)) !== resolvedCli + ) { + fail("release operations require the reviewed pinned npm CLI"); + } + await writeFile(join(directory, "user.npmrc"), "", { flag: "wx" }); + await writeFile(join(directory, "global.npmrc"), "", { flag: "wx" }); + await writeFile(join(directory, ".npmrc"), `registry=${registry}\n`, { + flag: "wx", + }); + const env = isolatedEnvironment(sourceEnv, directory, publishing); + const run = seams.run ?? nativeRun; + const invoke = async (arguments_) => { + let result; + try { + result = await run(process.execPath, [resolvedCli, ...arguments_], { + cwd: directory, + env, + }); + } catch { + fail("release npm or consumer verification command failed"); + } + if (result?.status !== 0 || typeof result.stdout !== "string") { + fail("release npm or consumer verification command failed"); + } + return result.stdout; + }; + if ((await invoke(["--version"])).trim() !== version) { + fail("release operations require the reviewed pinned npm CLI"); + } + return { invoke, env, run }; +} + +function derValue(bytes, start) { + const tag = bytes[start]; + const initialLength = bytes[start + 1]; + if (initialLength === undefined) fail("invalid provenance certificate"); + let offset = start + 2; + let length = initialLength; + if (initialLength > 127) { + const count = initialLength & 127; + if (count < 1 || count > 4 || offset + count > bytes.length) { + fail("invalid provenance certificate"); + } + length = 0; + for (let index = 0; index < count; index += 1) { + length = length * 256 + bytes[offset++]; + } + } + if (offset + length > bytes.length) fail("invalid provenance certificate"); + return { + tag, + value: bytes.subarray(offset, offset + length), + end: offset + length, + }; +} + +function certificateIssuer(certificate) { + // Fulcio's OIDC issuer extension (1.3.6.1.4.1.57264.1.1) distinguishes + // GitHub identities from other OIDC providers trusted by Sigstore. Parse DER + // structure, rather than searching for attacker-controlled certificate text. + const outer = derValue(certificate.raw, 0); + const tbs = derValue(outer.value, 0); + if (outer.tag !== 0x30 || tbs.tag !== 0x30) + fail("invalid provenance certificate"); + let extensions; + for (let offset = 0; offset < tbs.value.length;) { + const field = derValue(tbs.value, offset); + if (field.tag === 0xa3) extensions = derValue(field.value, 0); + offset = field.end; + } + if (extensions?.tag !== 0x30) fail("invalid provenance certificate"); + let issuer; + for (let offset = 0; offset < extensions.value.length;) { + const extension = derValue(extensions.value, offset); + const oid = derValue(extension.value, 0); + let value = derValue(extension.value, oid.end); + if (value.tag === 0x01) value = derValue(extension.value, value.end); + if (extension.tag !== 0x30 || oid.tag !== 0x06 || value.tag !== 0x04) { + fail("invalid provenance certificate"); + } + if (oid.value.toString("hex") === "2b0601040183bf300101") { + if (issuer !== undefined) fail("invalid provenance certificate"); + issuer = value.value.toString("utf8"); + } + offset = extension.end; + } + return issuer; +} + +function verifyCertificateIdentity(bundle, identity) { + try { + const material = bundle.verificationMaterial; + const encoded = + material.certificate?.rawBytes ?? + material.x509CertificateChain?.certificates?.[0]?.rawBytes; + if (typeof encoded !== "string" || encoded.length > 64 * 1024) { + fail("invalid provenance certificate"); + } + const certificate = new X509Certificate(Buffer.from(encoded, "base64")); + if ( + certificate.subjectAltName !== + `URI:https://github.com/${RELEASE_REPOSITORY}/${RELEASE_WORKFLOW}@refs/tags/${identity.tag}` || + certificateIssuer(certificate) !== + "https://token.actions.githubusercontent.com" + ) { + fail("invalid provenance certificate"); + } + } catch { + fail( + "verified provenance signer does not match the approved release workflow", + ); + } +} + +export function verifyProvenanceAudit(audit, manifest) { + validatePreparedManifest(manifest); + if ( + !Array.isArray(audit?.invalid) || + audit.invalid.length !== 0 || + !Array.isArray(audit.missing) || + audit.missing.length !== 0 || + !Array.isArray(audit.verified) + ) { + fail("registry signatures or provenance verification failed"); + } + const identity = manifest.identity; + for (const record of manifest.artifacts) { + const matches = audit.verified.filter( + (entry) => + entry.name === record.name && + entry.version === record.version && + entry.location === `node_modules/${record.name}` && + entry.registry === registry, + ); + if (matches.length !== 1 || !Array.isArray(matches[0].attestationBundles)) { + fail("release package is missing verified source provenance"); + } + const bundles = matches[0].attestationBundles.filter( + (entry) => entry.predicateType === provenanceType, + ); + if (bundles.length !== 1) + fail("release package is missing verified source provenance"); + verifyCertificateIdentity(bundles[0].bundle, identity); + let statement; + try { + const envelope = bundles[0].bundle.dsseEnvelope; + if ( + envelope.payloadType !== "application/vnd.in-toto+json" || + typeof envelope.payload !== "string" || + envelope.payload.length > 1024 * 1024 + ) { + fail("invalid provenance statement"); + } + statement = JSON.parse( + Buffer.from(envelope.payload, "base64").toString("utf8"), + ); + } catch { + fail("release source provenance verification failed"); + } + const definition = statement.predicate?.buildDefinition; + const workflow = definition?.externalParameters?.workflow; + const dependencies = definition?.resolvedDependencies; + const expectedDigest = Buffer.from( + record.integrity.slice(7), + "base64", + ).toString("hex"); + if ( + statement._type !== "https://in-toto.io/Statement/v1" || + statement.predicateType !== provenanceType || + !Array.isArray(statement.subject) || + statement.subject.length !== 1 || + statement.subject[0].name !== + `pkg:npm/${record.name.split("/").map(encodeURIComponent).join("/")}@${record.version}` || + !equal(statement.subject[0].digest?.sha512, expectedDigest) || + definition?.buildType !== + "https://slsa-framework.github.io/github-actions-buildtypes/workflow/v1" || + workflow?.repository !== `https://github.com/${RELEASE_REPOSITORY}` || + workflow.path !== RELEASE_WORKFLOW || + workflow.ref !== `refs/tags/${identity.tag}` || + definition.internalParameters?.github?.event_name !== "release" || + !Array.isArray(dependencies) || + dependencies.length !== 1 || + dependencies[0].uri !== + `git+https://github.com/${RELEASE_REPOSITORY}@refs/tags/${identity.tag}` || + !equal(dependencies[0].digest?.gitCommit, identity.commit) || + statement.predicate?.runDetails?.builder?.id !== + "https://github.com/actions/runner/github-hosted" + ) { + fail("release source provenance does not match the prepared identity"); + } + } +} + +async function registryConsumer(verified, options, seams) { + return temporary(async (directory) => { + const { invoke, env, run } = await npmContext( + options, + seams, + directory, + false, + ); + const dependencies = Object.fromEntries( + verified.manifest.artifacts.map((record) => [ + record.name, + record.version, + ]), + ); + await writeFile( + join(directory, "package.json"), + `${JSON.stringify({ + name: "agent-access-registry-proof", + private: true, + type: "module", + dependencies, + })}\n`, + { flag: "wx" }, + ); + // Exact registry specifiers only. No tarballs, workspace links, source build, + // project dependency installation, lifecycle scripts, or inherited npmrc. + await invoke([ + "install", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--registry", + registry, + ]); + const lock = JSON.parse( + await readFile(join(directory, "package-lock.json"), "utf8"), + ); + for (const record of verified.manifest.artifacts) { + const installed = lock.packages?.[`node_modules/${record.name}`]; + if ( + installed?.version !== record.version || + installed.link === true || + !equal(installed.integrity, record.integrity) || + installed.resolved !== tarballUrl(record) + ) { + fail("registry consumer did not install the prepared exact release"); + } + } + let audit; + try { + // npm performs the Sigstore/TUF cryptographic verification; the additional + // source checks below constrain the verified statement to this exact tag. + // https://docs.npmjs.com/generating-provenance-statements/#verifying-provenance-attestations + audit = JSON.parse( + await invoke([ + "audit", + "signatures", + "--json", + "--include-attestations", + "--registry", + registry, + ]), + ); + } catch { + fail("registry signatures or provenance verification failed"); + } + verifyProvenanceAudit(audit, verified.manifest); + // Authenticate all installed artifacts before executing any consumer import; + // imported package code must not be able to forge the preceding npm audit. + const source = `import assert from "node:assert/strict";\n${RELEASE_PACKAGES.map( + (entry) => + `assert.equal(typeof (await import(${JSON.stringify(entry.name)}))[${JSON.stringify(entry.runtimeExport)}], ${JSON.stringify(entry.runtimeExportType)});`, + ).join("\n")}\n`; + const consumer = join(directory, "consumer.mjs"); + await writeFile(consumer, source, { flag: "wx" }); + let imported; + try { + imported = await run(process.execPath, [consumer], { + cwd: directory, + env, + }); + } catch { + fail("registry consumer public imports failed"); + } + if (imported?.status !== 0) fail("registry consumer public imports failed"); + }); +} + +async function confirmRegistry(record, seams) { + const sleep = + seams.sleep ?? + ((milliseconds) => + new Promise((resolve_) => setTimeout(resolve_, milliseconds))); + for (let attempt = 0; attempt < 6; attempt += 1) { + if ( + (await registryRecord(record, seams.fetch ?? globalThis.fetch)) !== null + ) + return; + if (attempt < 5) await sleep(2 ** attempt * 1000); + } + fail("published registry version was not visible after bounded verification"); +} + +async function verifyPublishedBytes(verified, seams) { + const plan = await preflightRegistry(verified, seams); + if (plan.some((entry) => entry.action !== "skip")) { + fail("the complete release set is not available from the registry"); + } + return Object.freeze({ + verified: true, + packages: Object.freeze(plan.map((entry) => entry.name)), + }); +} + +export async function verifyRegistryRelease(options = {}, seams = {}) { + const verified = await verifyPreparedManifest(options); + const result = await verifyPublishedBytes(verified, seams); + await registryConsumer(verified, options, seams); + return result; +} + +export async function publishPreparedRelease(options = {}, seams = {}) { + const verified = await verifyPreparedManifest(options); + assertTrustedPublishingEnvironment( + seams.env ?? process.env, + verified.manifest.identity, + ); + const plan = await preflightRegistry(verified, seams); + const published = []; + const skipped = []; + await temporary(async (directory) => { + const { invoke } = await npmContext(options, seams, directory, true); + // Snapshot the already verified bytes outside the checkout. Npm cannot read + // project .npmrc or run source/prepack scripts in this privileged job. + for (const record of verified.artifacts) { + const destination = join(directory, record.filename); + await copyFile(record.path, destination); + const bytes = await readFile(destination); + if ( + bytes.length !== record.size || + !equal(`sha512-${hash(bytes, "sha512", "base64")}`, record.integrity) + ) { + fail("prepared publish artifact changed after verification"); + } + } + for (const [index, decision] of plan.entries()) { + const record = verified.artifacts[index]; + if (decision.action === "skip") { + skipped.push(record.name); + continue; + } + const destination = join(directory, record.filename); + // Recheck immutable versions immediately before publication to recover + // another run's successful publication without overwriting anything. + if ( + (await registryRecord(record, seams.fetch ?? globalThis.fetch)) !== null + ) { + skipped.push(record.name); + continue; + } + await invoke([ + "publish", + destination, + "--ignore-scripts", + "--access", + "public", + "--provenance", + "--registry", + registry, + ]); + published.push(record.name); + await confirmRegistry(record, seams); + } + }); + await verifyPublishedBytes(verified, seams); + return Object.freeze({ + published: Object.freeze(published), + skipped: Object.freeze(skipped), + verified: true, + }); +} diff --git a/scripts/test-release.mjs b/scripts/test-release.mjs new file mode 100644 index 0000000..509a439 --- /dev/null +++ b/scripts/test-release.mjs @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readdir } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const directory = fileURLToPath(new URL("../tests/release/", import.meta.url)); +const entries = await readdir(directory, { withFileTypes: true }); +const files = entries + .filter((entry) => entry.name.endsWith(".test.mjs")) + .map((entry) => { + assert.ok( + entry.isFile(), + "Release regression entries must be regular files.", + ); + return join(directory, entry.name); + }) + .sort(); +assert.ok(files.length > 0, "No release regression tests were found."); +const result = spawnSync(process.execPath, ["--test", ...files], { + shell: false, + stdio: "inherit", + timeout: 300_000, +}); +if (result.error) + throw new Error("Release regression tests could not complete."); +process.exitCode = result.status ?? 1; diff --git a/tests/release/arguments.test.mjs b/tests/release/arguments.test.mjs new file mode 100644 index 0000000..c928efb --- /dev/null +++ b/tests/release/arguments.test.mjs @@ -0,0 +1,242 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + mkdir, + readFile, + realpath, + symlink, + writeFile, +} from "node:fs/promises"; +import { join, sep } from "node:path"; +import { + parseArguments, + resolveReleaseNpmCli, +} from "../../scripts/release-packages.mjs"; +import { temporaryDirectory } from "./fixtures.mjs"; + +const commit = "a".repeat(40); +const manifestSha256 = "b".repeat(64); + +test("existing check and pack commands accept no publication options", () => { + for (const command of ["check", "pack"]) { + assert.deepEqual(parseArguments([command]), { command, options: {} }); + assert.throws(() => parseArguments([command, "--tag", "v0.1.0"])); + } +}); + +test("prepare requires an exact stable tag and independent commit before any work", () => { + assert.deepEqual( + parseArguments(["prepare", "--tag", "v0.1.0", "--expected-commit", commit]), + { command: "prepare", options: { tag: "v0.1.0", expectedCommit: commit } }, + ); + assert.deepEqual( + parseArguments([ + "prepare", + "--out", + "synthetic output", + "--expected-commit", + "c".repeat(64), + "--tag", + "v1.2.3", + ]), + { + command: "prepare", + options: { + output: "synthetic output", + expectedCommit: "c".repeat(64), + tag: "v1.2.3", + }, + }, + ); +}); + +test("preflight, publish, and verify require the same prepared artifact identity", () => { + for (const command of ["preflight", "publish", "verify"]) { + assert.deepEqual( + parseArguments([ + command, + "--prepared-dir", + "synthetic/prepared", + "--manifest-sha256", + manifestSha256, + "--tag", + "v0.1.0", + "--expected-commit", + commit, + ]), + { + command, + options: { + preparedDir: "synthetic/prepared", + expectedManifestSha256: manifestSha256, + expectedTag: "v0.1.0", + expectedCommit: commit, + }, + }, + ); + } +}); + +test("missing, duplicate, unknown, malformed, and credential options fail closed", () => { + const prepare = ["prepare", "--tag", "v0.1.0", "--expected-commit", commit]; + const publish = [ + "publish", + "--prepared-dir", + "synthetic", + "--manifest-sha256", + manifestSha256, + "--tag", + "v0.1.0", + "--expected-commit", + commit, + ]; + for (const arguments_ of [ + [], + ["unknown"], + ["prepare"], + ["prepare", "--tag", "v0.1.0"], + ["prepare", "--expected-commit", commit], + ["prepare", "--tag", "v0.1.0-rc.1", "--expected-commit", commit], + ["prepare", "--tag", "0.1.0", "--expected-commit", commit], + ["prepare", "--tag", "v01.1.0", "--expected-commit", commit], + ["prepare", "--tag", "v0.1.0", "--expected-commit", "HEAD"], + [...prepare, "--tag", "v0.1.0"], + [...prepare, "--out"], + [...prepare, "--out", ""], + [...prepare, "--out", "--tag"], + [...prepare, "--out", "synthetic\u0000directory"], + [...prepare, "--out", "synthetic\ndirectory"], + [...prepare, "--force", "true"], + [...prepare, "--__proto__", "value"], + [...prepare, "unexpected"], + [...publish, "--manifest-sha256", manifestSha256], + [...publish, "--npm-token", "synthetic-credential"], + [...publish, "--out", "synthetic"], + publish.filter( + (value) => value !== "--manifest-sha256" && value !== manifestSha256, + ), + [ + "verify", + "--prepared-dir", + "synthetic", + "--manifest-sha256", + "B".repeat(64), + "--tag", + "v0.1.0", + "--expected-commit", + commit, + ], + ]) { + assert.throws(() => parseArguments(arguments_)); + } +}); + +function releaseNpmEnvironment(cli) { + return { RELEASE_NPM_CLI: cli, RELEASE_NPM_VERSION: "11.18.0" }; +} + +async function npmCliFixture(t) { + const directory = await temporaryDirectory(t); + const cli = join(directory, "npm-cli.js"); + // The resolver is a filesystem boundary. Executing this file would fail the + // success case; no installed npm or version subprocess belongs in these tests. + await writeFile( + cli, + "throw new Error('synthetic npm fixture must not execute');\n", + ); + return { directory, cli }; +} + +test("strict preparation resolves a canonical reviewed CLI without executing it", async (t) => { + const { directory, cli } = await npmCliFixture(t); + await mkdir(join(directory, "nested")); + const candidate = `${directory}${sep}nested${sep}..${sep}npm-cli.js`; + const env = Object.freeze(releaseNpmEnvironment(candidate)); + assert.equal(await resolveReleaseNpmCli(env), await realpath(cli)); + assert.equal(env.RELEASE_NPM_CLI, candidate); +}); + +test("strict preparation requires an explicit absolute CLI and never uses ambient npm discovery", async (t) => { + const { directory, cli } = await npmCliFixture(t); + for (const candidate of [undefined, "", "npm-cli.js", "../npm-cli.js"]) { + await assert.rejects( + resolveReleaseNpmCli({ + ...releaseNpmEnvironment(candidate), + npm_execpath: cli, + PATH: directory, + }), + ); + } + await assert.rejects(resolveReleaseNpmCli({})); +}); + +test("strict preparation requires the exact independently configured npm version", async (t) => { + const { cli } = await npmCliFixture(t); + for (const version of [ + undefined, + "", + "11.17.0", + "^11.18.0", + "11.18.0-rc.1", + "11.18.0\n", + ]) { + await assert.rejects( + resolveReleaseNpmCli({ + ...releaseNpmEnvironment(cli), + RELEASE_NPM_VERSION: version, + }), + ); + } +}); + +test("strict preparation rejects non-CLI names, missing files, and CLI-named directories", async (t) => { + const { directory } = await npmCliFixture(t); + const nonCli = join(directory, "not-npm-cli.js"); + await writeFile(nonCli, "// synthetic non-CLI file\n"); + const cliDirectory = join(directory, "directory", "npm-cli.js"); + await mkdir(cliDirectory, { recursive: true }); + for (const candidate of [ + nonCli, + join(directory, "missing", "npm-cli.js"), + cliDirectory, + ]) { + await assert.rejects( + resolveReleaseNpmCli(releaseNpmEnvironment(candidate)), + ); + } +}); + +test("strict preparation rejects a leaf npm-cli.js symlink even to matching regular bytes", async (t) => { + const { directory, cli } = await npmCliFixture(t); + const linkedDirectory = join(directory, "leaf-link"); + await mkdir(linkedDirectory); + const linkedCli = join(linkedDirectory, "npm-cli.js"); + try { + await symlink(cli, linkedCli, "file"); + } catch (error) { + if (process.platform === "win32" && error.code === "EPERM") { + t.skip("Windows file symlinks require Developer Mode or elevation"); + return; + } + throw error; + } + await assert.rejects(resolveReleaseNpmCli(releaseNpmEnvironment(linkedCli))); +}); + +test("strict preparation rejects a CLI reached through a linked ancestor directory", async (t) => { + const { directory, cli } = await npmCliFixture(t); + const linkedDirectory = join(directory, "ancestor-link"); + const actualDirectory = join(directory, "actual-cli-directory"); + await mkdir(actualDirectory); + await writeFile(join(actualDirectory, "npm-cli.js"), await readFile(cli)); + await symlink( + actualDirectory, + linkedDirectory, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects( + resolveReleaseNpmCli( + releaseNpmEnvironment(join(linkedDirectory, "npm-cli.js")), + ), + ); +}); diff --git a/tests/release/contract.test.mjs b/tests/release/contract.test.mjs new file mode 100644 index 0000000..383be8d --- /dev/null +++ b/tests/release/contract.test.mjs @@ -0,0 +1,266 @@ +import assert from "node:assert/strict"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import test from "node:test"; +import { + RELEASE_PACKAGES, + RELEASE_REPOSITORY, + releaseDependencies, + verifyReleaseIdentity, +} from "../../scripts/release-contract.mjs"; +import { + signedGitFixture, + specifications, + withGitEnvironment, +} from "./fixtures.mjs"; + +test("the reviewed release package order and exact dependency pins are fixed", () => { + assert.equal(RELEASE_REPOSITORY, "pegma-dev/agent-access"); + assert.deepEqual( + RELEASE_PACKAGES.map(({ name, directory }) => ({ name, directory })), + specifications.map(({ name, directory }) => ({ name, directory })), + ); + for (const specification of specifications) { + assert.deepEqual( + releaseDependencies(specification.directory, "0.1.0"), + specification.dependencies, + ); + } + assert.throws(() => releaseDependencies("unknown", "0.1.0")); + for (const version of [ + "v0.1.0", + "0.1.0-rc.1", + "01.1.0", + "1.0", + "1.0.0+build", + ]) { + assert.throws(() => releaseDependencies("agent-access", version)); + } +}); + +function verify(fixture, overrides = {}) { + return verifyReleaseIdentity({ + root: fixture.root, + tag: "v0.1.0", + expectedCommit: fixture.commit, + version: "0.1.0", + ...overrides, + }); +} + +test("an approved SSH signed annotated tag at the exact clean main commit verifies", async (t) => { + const fixture = await signedGitFixture(t); + const result = verify(fixture); + assert.deepEqual(result, { + repository: "pegma-dev/agent-access", + tag: "v0.1.0", + commit: fixture.commit, + version: "0.1.0", + }); + assert.ok(Object.isFrozen(result)); +}); + +test("release identity rejects a wrong tag, version, or event commit", async (t) => { + const fixture = await signedGitFixture(t); + for (const overrides of [ + { tag: "v0.2.0" }, + { version: "0.1.0-rc.1" }, + { expectedCommit: "0".repeat(40) }, + { expectedCommit: fixture.commit.toUpperCase() }, + { expectedCommit: "HEAD" }, + ]) { + assert.throws(() => verify(fixture, overrides)); + } +}); + +test("a lightweight tag cannot satisfy the signed annotated release contract", async (t) => { + const fixture = await signedGitFixture(t); + fixture.git("tag", "-d", "v0.1.0"); + fixture.git("tag", "v0.1.0"); + assert.throws(() => verify(fixture), /annotated tag object/u); +}); + +test("an unsigned annotated tag cannot satisfy the release contract", async (t) => { + const fixture = await signedGitFixture(t); + fixture.git("tag", "-d", "v0.1.0"); + fixture.git("tag", "-a", "v0.1.0", "-m", "Unsigned fixture"); + assert.throws(() => verify(fixture), /signature/u); +}); + +test("a cryptographic signature from an unapproved signer is rejected", async (t) => { + const fixture = await signedGitFixture(t); + await writeFile(fixture.allowedSigners, ""); + assert.throws(() => verify(fixture), /signature/u); +}); + +async function signerConfig(path, allowedSigners) { + await writeFile( + path, + `[gpg "ssh"]\n\tallowedSignersFile = ${JSON.stringify(allowedSigners.replaceAll("\\", "/"))}\n`, + ); +} + +function injectedSignerEnvironments(allowedSigners, config) { + const parameter = `gpg.ssh.allowedSignersFile=${allowedSigners}`; + const environments = [ + { + name: "indexed command config", + env: { + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: "gpg.ssh.allowedSignersFile", + GIT_CONFIG_VALUE_0: allowedSigners, + }, + }, + { + name: "serialized command config", + env: { + GIT_CONFIG_PARAMETERS: `'${parameter.replaceAll("'", "'\\''")}'`, + }, + }, + { + name: "direct config path", + env: { GIT_CONFIG: config }, + }, + ]; + return environments.flatMap((entry) => + process.platform === "win32" + ? [ + entry, + { + name: `${entry.name} with Windows environment casing`, + env: Object.fromEntries( + Object.entries(entry.env).map(([key, value]) => [ + key.toLowerCase(), + value, + ]), + ), + }, + ] + : [entry], + ); +} + +test("inherited Git config cannot approve a signer rejected by local policy", async (t) => { + const fixture = await signedGitFixture(t); + const alternateSigners = join( + fixture.directory, + "environment-allowed-signers", + ); + const alternateConfig = join(fixture.directory, "environment-gitconfig"); + await writeFile( + alternateSigners, + await readFile(fixture.allowedSigners, "utf8"), + ); + await signerConfig(alternateConfig, alternateSigners); + await writeFile(fixture.allowedSigners, ""); + for (const injection of injectedSignerEnvironments( + alternateSigners, + alternateConfig, + )) { + withGitEnvironment({ ...fixture.env, ...injection.env }, () => { + assert.throws(() => verify(fixture), /signature/u, injection.name); + }); + } +}); + +test("inherited Git config cannot replace an approved local signer policy", async (t) => { + const fixture = await signedGitFixture(t); + const alternateSigners = join(fixture.directory, "environment-empty-signers"); + const alternateConfig = join(fixture.directory, "environment-gitconfig"); + await writeFile(alternateSigners, ""); + await signerConfig(alternateConfig, alternateSigners); + for (const injection of injectedSignerEnvironments( + alternateSigners, + alternateConfig, + )) { + withGitEnvironment({ ...fixture.env, ...injection.env }, () => { + assert.equal(verify(fixture).commit, fixture.commit, injection.name); + }); + } +}); + +test("trusted global signer configuration remains available to verification", async (t) => { + const fixture = await signedGitFixture(t); + const globalConfig = join(fixture.directory, "trusted-global-gitconfig"); + await signerConfig(globalConfig, fixture.allowedSigners); + fixture.git("config", "--unset", "gpg.ssh.allowedSignersFile"); + withGitEnvironment({ ...fixture.env, GIT_CONFIG_GLOBAL: globalConfig }, () => + assert.equal(verify(fixture).commit, fixture.commit), + ); +}); + +test("a tag object changed after signing fails cryptographic verification", async (t) => { + const fixture = await signedGitFixture(t); + const signed = fixture.git("cat-file", "tag", "refs/tags/v0.1.0"); + assert.ok(signed.includes("Synthetic signed release")); + const changed = join(fixture.directory, "modified-tag-object"); + await writeFile( + changed, + `${signed.replace("Synthetic signed release", "Unreviewed tag message")}\n`, + ); + const object = fixture.git("hash-object", "-t", "tag", "-w", changed); + fixture.git("update-ref", "refs/tags/v0.1.0", object); + assert.throws(() => verify(fixture), /signature/u); +}); + +test("a tag targeting an older commit is rejected even when HEAD matches the event", async (t) => { + const fixture = await signedGitFixture(t); + await writeFile( + join(fixture.root, "README.md"), + "Synthetic second commit.\n", + ); + fixture.git("add", "README.md"); + fixture.git("commit", "-m", "Advance fixture main"); + const commit = fixture.git("rev-parse", "HEAD"); + fixture.git("update-ref", "refs/remotes/origin/main", commit); + assert.throws( + () => verify(fixture, { expectedCommit: commit }), + /must match/u, + ); +}); + +test("tracked modifications and untracked files each block release preparation", async (t) => { + const fixture = await signedGitFixture(t); + await writeFile(join(fixture.root, "README.md"), "Unreviewed source edit.\n"); + assert.throws(() => verify(fixture), /clean checkout/u); + fixture.git("restore", "README.md"); + await writeFile(join(fixture.root, "untracked.txt"), "Unreviewed file.\n"); + assert.throws(() => verify(fixture), /clean checkout/u); +}); + +test("a signed clean commit outside origin/main is rejected", async (t) => { + const fixture = await signedGitFixture(t); + fixture.git("checkout", "--orphan", "unrelated"); + fixture.git("commit", "-m", "Unrelated synthetic main"); + const unrelated = fixture.git("rev-parse", "HEAD"); + fixture.git("update-ref", "refs/remotes/origin/main", unrelated); + fixture.git("checkout", "--detach", fixture.commit); + assert.throws(() => verify(fixture), /contained in origin\/main/u); +}); + +test("a shallow checkout is rejected before tag ancestry can be trusted", async (t) => { + const fixture = await signedGitFixture(t); + await writeFile(join(fixture.root, ".git", "shallow"), `${fixture.commit}\n`); + assert.throws(() => verify(fixture), /complete Git ancestry/u); +}); + +test("a different remote or a package subdirectory cannot supply release identity", async (t) => { + const fixture = await signedGitFixture(t); + fixture.git( + "remote", + "set-url", + "origin", + "https://github.com/other/agent-access.git", + ); + assert.throws(() => verify(fixture), /reviewed source repository/u); + fixture.git( + "remote", + "set-url", + "origin", + "https://github.com/pegma-dev/agent-access.git", + ); + assert.throws( + () => verify(fixture, { root: join(fixture.root, ".git") }), + /checkout root/u, + ); +}); diff --git a/tests/release/fixtures.mjs b/tests/release/fixtures.mjs new file mode 100644 index 0000000..5d0d591 --- /dev/null +++ b/tests/release/fixtures.mjs @@ -0,0 +1,265 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createHash, generateKeyPairSync, sign } from "node:crypto"; +import { + mkdir, + mkdtemp, + readFile, + realpath, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, resolve } from "node:path"; + +const temporaryPrefix = "pegma-agent-access-release-test-"; + +export const identity = Object.freeze({ + repository: "pegma-dev/agent-access", + tag: "v0.1.0", + commit: "a".repeat(40), + version: "0.1.0", +}); + +export const specifications = [ + { + directory: "agent-access", + name: "@pegma/agent-access", + dependencies: { + "@pegma/audit": "0.2.0", + "@pegma/authorization-core": "0.4.0", + "@pegma/spine": "0.1.2", + "@pegma/storage-core": "0.4.0", + }, + }, +]; + +export function digest(bytes, algorithm = "sha256", encoding = "hex") { + return createHash(algorithm).update(bytes).digest(encoding); +} + +const certificates = new Map(); + +export function syntheticCertificate({ + repository = "pegma-dev/agent-access", + tag = "v0.1.0", + workflow = ".github/workflows/publish.yml", + issuer = "https://token.actions.githubusercontent.com", +} = {}) { + const identityKey = `${repository}:${tag}:${workflow}:${issuer}`; + if (certificates.has(identityKey)) return certificates.get(identityKey); + const der = (tag, ...parts) => { + const value = Buffer.concat(parts); + let length; + if (value.length < 128) { + length = Buffer.from([value.length]); + } else { + let hexadecimal = value.length.toString(16); + if (hexadecimal.length % 2 !== 0) hexadecimal = `0${hexadecimal}`; + const bytes = Buffer.from(hexadecimal, "hex"); + length = Buffer.concat([Buffer.from([0x80 | bytes.length]), bytes]); + } + return Buffer.concat([Buffer.from([tag]), length, value]); + }; + const oid = (hexadecimal) => der(0x06, Buffer.from(hexadecimal, "hex")); + const sequence = (...parts) => der(0x30, ...parts); + const text = (value) => Buffer.from(value, "utf8"); + const algorithm = sequence(oid("2a8648ce3d040302")); + const name = sequence( + der( + 0x31, + sequence(oid("550403"), der(0x0c, text("Synthetic fixture only"))), + ), + ); + const { publicKey, privateKey } = generateKeyPairSync("ec", { + namedCurve: "prime256v1", + }); + const extensions = sequence( + sequence( + oid("551d11"), + der( + 0x04, + sequence( + der( + 0x86, + text( + `https://github.com/${repository}/${workflow}@refs/tags/${tag}`, + ), + ), + ), + ), + ), + sequence(oid("2b0601040183bf300101"), der(0x04, text(issuer))), + ); + const body = sequence( + der(0xa0, der(0x02, Buffer.from([2]))), + der(0x02, Buffer.from([1])), + algorithm, + name, + sequence( + der(0x17, text("260101000000Z")), + der(0x17, text("350101000000Z")), + ), + name, + publicKey.export({ type: "spki", format: "der" }), + der(0xa3, extensions), + ); + // A real, self-signed X.509 fixture lets the parser inspect DER and SANs. + // It establishes no Sigstore trust: npm's cryptographic audit is a run seam. + const certificate = sequence( + body, + algorithm, + der(0x03, Buffer.from([0]), sign("sha256", body, privateKey)), + ).toString("base64"); + certificates.set(identityKey, certificate); + return certificate; +} + +export async function temporaryDirectory(t) { + const parent = await realpath(tmpdir()); + const directory = await mkdtemp(join(parent, temporaryPrefix)); + t.after(async () => { + const target = resolve(directory); + assert.equal(dirname(target), resolve(parent)); + assert.ok(basename(target).startsWith(temporaryPrefix)); + assert.notEqual(target, resolve(parent)); + await rm(target, { recursive: true, force: true }); + }); + return directory; +} + +export async function preparedFixture(t) { + const directory = await temporaryDirectory(t); + const preparedDir = join(directory, "prepared"); + await mkdir(preparedDir); + const artifacts = []; + for (const specification of specifications) { + // Manifest verification treats tarballs as opaque, previously reviewed + // blobs. These fixtures exercise its byte boundary without executing npm. + const bytes = Buffer.from(`synthetic artifact: ${specification.name}\n`); + const filename = `${specification.name.slice(1).replace("/", "-")}-0.1.0.tgz`; + await writeFile(join(preparedDir, filename), bytes); + artifacts.push({ + name: specification.name, + version: "0.1.0", + filename, + size: bytes.length, + shasum: digest(bytes, "sha1"), + integrity: `sha512-${digest(bytes, "sha512", "base64")}`, + dependencies: structuredClone(specification.dependencies), + files: [ + { path: "package.json", size: 250 }, + { path: "README.md", size: 32 }, + { path: "LICENSE", size: 1_000 }, + { path: "dist/index.js", size: 64 }, + { path: "dist/index.d.ts", size: 64 }, + ], + }); + } + return { directory, preparedDir, identity: { ...identity }, artifacts }; +} + +export async function rewriteManifest(preparedDir, change) { + const manifestPath = join(preparedDir, "manifest.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + change(manifest); + const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`); + await writeFile(manifestPath, bytes); + return digest(bytes); +} + +export function run(command, arguments_, cwd, env) { + const result = spawnSync(command, arguments_, { + cwd, + env, + shell: false, + encoding: "utf8", + stdio: "pipe", + timeout: 30_000, + maxBuffer: 1024 * 1024, + }); + assert.ifError(result.error); + assert.equal(result.status, 0, `${command}: ${result.stderr}`); + return result.stdout.trim(); +} + +export function withGitEnvironment(env, operation) { + const isGit = (key) => key.toUpperCase().startsWith("GIT_"); + const original = Object.entries(process.env).filter(([key]) => isGit(key)); + const clear = () => { + for (const key of Object.keys(process.env)) { + if (isGit(key)) delete process.env[key]; + } + }; + // The release verifier is synchronous, so the environment is restored before + // any other asynchronous test work can observe these scoped fixture values. + clear(); + try { + for (const [key, value] of Object.entries(env)) { + if (isGit(key)) process.env[key] = value; + } + return operation(); + } finally { + clear(); + for (const [key, value] of original) process.env[key] = value; + } +} + +export async function signedGitFixture(t) { + const directory = await temporaryDirectory(t); + const root = join(directory, "checkout"); + const signingKey = join(directory, "signing-key"); + const allowedSigners = join(directory, "allowed-signers"); + const emptyConfig = join(directory, "empty-gitconfig"); + await mkdir(root); + await writeFile(emptyConfig, ""); + const env = { ...process.env }; + for (const key of Object.keys(env)) { + if (key.toUpperCase().startsWith("GIT_")) delete env[key]; + } + Object.assign(env, { + GIT_CONFIG_GLOBAL: emptyConfig, + GIT_CONFIG_NOSYSTEM: "1", + GIT_TERMINAL_PROMPT: "0", + }); + const git = (...arguments_) => + run( + process.platform === "win32" ? "git.exe" : "git", + ["--no-replace-objects", ...arguments_], + root, + env, + ); + run( + process.platform === "win32" ? "ssh-keygen.exe" : "ssh-keygen", + ["-q", "-t", "ed25519", "-N", "", "-f", signingKey], + directory, + env, + ); + const publicKey = (await readFile(`${signingKey}.pub`, "utf8")).trim(); + await writeFile( + allowedSigners, + `release-fixture@example.invalid ${publicKey}\n`, + ); + git("init", "--initial-branch=main"); + git("config", "user.name", "Synthetic Release Fixture"); + git("config", "user.email", "release-fixture@example.invalid"); + git("config", "commit.gpgsign", "false"); + git("config", "core.autocrlf", "false"); + git("config", "core.hooksPath", join(directory, "unused-hooks")); + git("config", "gpg.format", "ssh"); + git("config", "user.signingkey", signingKey); + git("config", "gpg.ssh.allowedSignersFile", allowedSigners); + await writeFile(join(root, "README.md"), "Synthetic release fixture.\n"); + git("add", "README.md"); + git("commit", "-m", "Create synthetic release fixture"); + const commit = git("rev-parse", "HEAD"); + git( + "remote", + "add", + "origin", + "https://github.com/pegma-dev/agent-access.git", + ); + git("update-ref", "refs/remotes/origin/main", commit); + git("tag", "-s", "v0.1.0", "-m", "Synthetic signed release"); + return { directory, root, git, env, commit, allowedSigners }; +} diff --git a/tests/release/manifest.test.mjs b/tests/release/manifest.test.mjs new file mode 100644 index 0000000..e0f1ccf --- /dev/null +++ b/tests/release/manifest.test.mjs @@ -0,0 +1,431 @@ +import assert from "node:assert/strict"; +import { + mkdir, + readFile, + rename, + symlink, + unlink, + writeFile, +} from "node:fs/promises"; +import { join } from "node:path"; +import test from "node:test"; +import { + PREPARED_MANIFEST_LIMITS, + validatePreparedManifest, + verifyPreparedManifest, + writePreparedManifest, +} from "../../scripts/release-manifest.mjs"; +import { + digest, + identity, + preparedFixture, + rewriteManifest, +} from "./fixtures.mjs"; + +const failure = /prepared release manifest or artifact verification failed/u; + +async function prepare(t) { + const fixture = await preparedFixture(t); + const written = await writePreparedManifest(fixture); + return { + ...fixture, + written, + options: { + preparedDir: fixture.preparedDir, + expectedManifestSha256: written.manifestSha256, + expectedTag: identity.tag, + expectedCommit: identity.commit, + expectedVersion: identity.version, + }, + }; +} + +test("prepared manifest is frozen, digest-bound, ordered, and independent of mutable producer metadata", async (t) => { + const fixture = await prepare(t); + const bytes = await readFile(fixture.written.manifestPath); + assert.equal(fixture.written.manifestSha256, digest(bytes)); + assert.ok(bytes.toString("utf8").endsWith("\n")); + const result = await verifyPreparedManifest(fixture.options); + assert.deepEqual(result.manifest.identity, identity); + assert.deepEqual( + result.artifacts.map(({ name }) => name), + fixture.artifacts.map(({ name }) => name), + ); + for (const artifact of result.artifacts) { + assert.equal(artifact.path, join(fixture.preparedDir, artifact.filename)); + assert.ok(Object.isFrozen(artifact)); + } + assert.ok(Object.isFrozen(result.manifest.artifacts[0].dependencies)); + assert.ok(Object.isFrozen(result.manifest.artifacts[0].files[0])); + assert.ok(Object.isFrozen(result.artifacts)); + assert.equal(Object.isFrozen(fixture.artifacts[0]), false); + fixture.identity.commit = "b".repeat(40); + fixture.artifacts[0].dependencies["@pegma/spine"] = "99.0.0"; + assert.deepEqual(result.manifest.identity, identity); + assert.equal(result.artifacts[0].dependencies["@pegma/spine"], "0.1.2"); +}); + +test("manifest digest and expected source identity come from independent trusted inputs", async (t) => { + const fixture = await prepare(t); + for (const overrides of [ + { expectedManifestSha256: undefined }, + { expectedManifestSha256: "0".repeat(64) }, + { expectedManifestSha256: fixture.written.manifestSha256.toUpperCase() }, + { expectedTag: "v0.2.0" }, + { expectedCommit: "b".repeat(40) }, + { expectedCommit: "HEAD" }, + { expectedVersion: "0.2.0" }, + ]) { + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, ...overrides }), + failure, + ); + } + await rewriteManifest(fixture.preparedDir, (manifest) => { + manifest.identity.commit = "b".repeat(40); + }); + await assert.rejects(verifyPreparedManifest(fixture.options), failure); +}); + +test("artifact byte tampering is rejected even when the blob size is unchanged", async (t) => { + const fixture = await prepare(t); + const artifact = join(fixture.preparedDir, fixture.artifacts[0].filename); + const bytes = await readFile(artifact); + bytes[0] ^= 1; + await writeFile(artifact, bytes); + await assert.rejects(verifyPreparedManifest(fixture.options), failure); +}); + +test("matching blob and manifest tampering cannot replace the independently trusted manifest digest", async (t) => { + const fixture = await prepare(t); + const artifact = join(fixture.preparedDir, fixture.artifacts[0].filename); + const bytes = await readFile(artifact); + bytes[0] ^= 1; + await writeFile(artifact, bytes); + const changedDigest = await rewriteManifest( + fixture.preparedDir, + (manifest) => { + manifest.artifacts[0].shasum = digest(bytes, "sha1"); + manifest.artifacts[0].integrity = `sha512-${digest(bytes, "sha512", "base64")}`; + }, + ); + assert.notEqual(changedDigest, fixture.options.expectedManifestSha256); + await assert.rejects(verifyPreparedManifest(fixture.options), failure); +}); + +test("artifact size and both independent hash encodings must match the exact blob", async (t) => { + for (const [name, change] of [ + [ + "size", + (record) => { + record.size += 1; + }, + ], + [ + "SHA-1", + (record) => { + record.shasum = "0".repeat(40); + }, + ], + [ + "SHA-512", + (record) => { + record.integrity = `sha512-${Buffer.alloc(64).toString("base64")}`; + }, + ], + ]) { + await t.test(name, async (t) => { + const fixture = await prepare(t); + const expectedManifestSha256 = await rewriteManifest( + fixture.preparedDir, + (manifest) => { + change(manifest.artifacts[0]); + }, + ); + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, expectedManifestSha256 }), + failure, + ); + }); + } +}); + +test("recomputed manifest hashes cannot authorize altered package sets, order, pins, or source identity", async (t) => { + const mutations = [ + [ + "missing package", + (manifest) => { + manifest.artifacts.pop(); + }, + ], + [ + "duplicate package", + (manifest) => { + manifest.artifacts.push(manifest.artifacts[0]); + }, + ], + [ + "unreviewed package", + (manifest) => { + manifest.artifacts[0].name = "@pegma/unreviewed"; + }, + ], + [ + "unexpected dependency", + (manifest) => { + manifest.artifacts[0].dependencies.extra = "1.0.0"; + }, + ], + [ + "wrong external pin", + (manifest) => { + manifest.artifacts[0].dependencies["@pegma/spine"] = "^0.1.2"; + }, + ], + [ + "missing reviewed dependency", + (manifest) => { + delete manifest.artifacts[0].dependencies["@pegma/storage-core"]; + }, + ], + [ + "wrong package version", + (manifest) => { + manifest.artifacts[0].version = "0.2.0"; + }, + ], + [ + "prerelease", + (manifest) => { + manifest.identity.version = "0.1.0-rc.1"; + }, + ], + [ + "different repository", + (manifest) => { + manifest.identity.repository = "other/agent-access"; + }, + ], + [ + "different source commit", + (manifest) => { + manifest.identity.commit = "b".repeat(40); + }, + ], + [ + "different release tag", + (manifest) => { + manifest.identity.tag = "v0.2.0"; + }, + ], + [ + "schema downgrade", + (manifest) => { + manifest.schemaVersion = 1; + }, + ], + [ + "unreviewed source field", + (manifest) => { + manifest.source = "copied-local-source"; + }, + ], + [ + "unreviewed record field", + (manifest) => { + manifest.artifacts[0].path = "../source/package.tgz"; + }, + ], + ]; + for (const [name, change] of mutations) { + await t.test(name, async (t) => { + const fixture = await prepare(t); + const expectedManifestSha256 = await rewriteManifest( + fixture.preparedDir, + change, + ); + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, expectedManifestSha256 }), + failure, + ); + }); + } +}); + +test("package inventories reject unsafe paths, tests, duplicates, missing exports, and invalid bounds", async (t) => { + const mutations = [ + [ + "parent traversal", + (record) => { + record.files.push({ path: "dist/../escape.js", size: 1 }); + }, + ], + [ + "absolute path", + (record) => { + record.files.push({ path: "/dist/escape.js", size: 1 }); + }, + ], + [ + "Windows path", + (record) => { + record.files.push({ path: "dist\\escape.js", size: 1 }); + }, + ], + [ + "compiled test", + (record) => { + record.files.push({ path: "dist/index.test.js", size: 1 }); + }, + ], + [ + "duplicate inventory", + (record) => { + record.files.push(record.files[0]); + }, + ], + [ + "missing runtime export", + (record) => { + record.files = record.files.filter( + ({ path }) => path !== "dist/index.js", + ); + }, + ], + [ + "negative size", + (record) => { + record.files[0].size = -1; + }, + ], + [ + "fractional size", + (record) => { + record.files[0].size = 1.5; + }, + ], + [ + "oversized file", + (record) => { + record.files[0].size = PREPARED_MANIFEST_LIMITS.fileBytes + 1; + }, + ], + [ + "artifact filename traversal", + (record) => { + record.filename = `../${record.filename}`; + }, + ], + [ + "artifact too large", + (record) => { + record.size = PREPARED_MANIFEST_LIMITS.artifactBytes + 1; + }, + ], + ]; + for (const [name, change] of mutations) { + await t.test(name, async (t) => { + const fixture = await preparedFixture(t); + change(fixture.artifacts[0]); + assert.throws( + () => + validatePreparedManifest({ + schemaVersion: 2, + identity, + artifacts: fixture.artifacts, + }), + failure, + ); + }); + } +}); + +test("prepared manifests are created once and invalid blobs never produce a manifest", async (t) => { + const fixture = await prepare(t); + await assert.rejects(writePreparedManifest(fixture), failure); + const invalid = await preparedFixture(t); + await writeFile( + join(invalid.preparedDir, invalid.artifacts[0].filename), + "different bytes", + ); + await assert.rejects(writePreparedManifest(invalid), failure); + await assert.rejects(readFile(join(invalid.preparedDir, "manifest.json")), { + code: "ENOENT", + }); +}); + +test("the verifier rejects missing blobs and artifact directories", async (t) => { + const fixture = await prepare(t); + const artifact = join(fixture.preparedDir, fixture.artifacts[0].filename); + await unlink(artifact); + await assert.rejects(verifyPreparedManifest(fixture.options), failure); + await mkdir(artifact); + await assert.rejects(verifyPreparedManifest(fixture.options), failure); +}); + +test("a manifest outside the prepared directory is rejected even with the exact trusted digest", async (t) => { + const fixture = await prepare(t); + const manifestPath = join(fixture.directory, "manifest.json"); + await writeFile(manifestPath, await readFile(fixture.written.manifestPath)); + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, manifestPath }), + failure, + ); +}); + +test("oversized and malformed manifests fail without disclosing paths or contents", async (t) => { + const fixture = await prepare(t); + for (const bytes of [ + Buffer.alloc(PREPARED_MANIFEST_LIMITS.manifestBytes + 1, 32), + Buffer.from('{"synthetic-secret":"do-not-echo"'), + ]) { + await writeFile(fixture.written.manifestPath, bytes); + await assert.rejects( + verifyPreparedManifest({ + ...fixture.options, + expectedManifestSha256: digest(bytes), + }), + (error) => + error.message === + "prepared release manifest or artifact verification failed", + ); + } +}); + +test("a linked prepared directory is rejected", async (t) => { + const fixture = await prepare(t); + const preparedDir = join(fixture.directory, "linked-prepared"); + await symlink( + fixture.preparedDir, + preparedDir, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects( + verifyPreparedManifest({ ...fixture.options, preparedDir }), + failure, + ); +}); + +test("artifact and manifest file symlinks are rejected even when their bytes match", async (t) => { + for (const target of ["artifact", "manifest"]) { + await t.test(target, async (t) => { + const fixture = await prepare(t); + const path = + target === "artifact" + ? join(fixture.preparedDir, fixture.artifacts[0].filename) + : fixture.written.manifestPath; + const moved = join(fixture.directory, `${target}-target`); + await rename(path, moved); + try { + await symlink(moved, path, "file"); + } catch (error) { + if (process.platform === "win32" && error.code === "EPERM") { + t.skip("Windows file symlinks require Developer Mode or elevation"); + return; + } + throw error; + } + await assert.rejects(verifyPreparedManifest(fixture.options), failure); + }); + } +}); diff --git a/tests/release/outputs.test.mjs b/tests/release/outputs.test.mjs new file mode 100644 index 0000000..0eab387 --- /dev/null +++ b/tests/release/outputs.test.mjs @@ -0,0 +1,200 @@ +import assert from "node:assert/strict"; +import { + access, + mkdir, + readFile, + rename, + symlink, + writeFile, +} from "node:fs/promises"; +import { join } from "node:path"; +import test from "node:test"; +import { cleanBuildOutputs } from "../../scripts/release-packages.mjs"; +import { specifications, temporaryDirectory } from "./fixtures.mjs"; + +async function outputFixture(t) { + const directory = await temporaryDirectory(t); + const root = join(directory, "checkout"); + for (const { directory: name } of specifications) { + const packageRoot = join(root, "packages", name); + await mkdir(join(packageRoot, "src"), { recursive: true }); + await mkdir(join(packageRoot, "dist", "nested"), { recursive: true }); + await writeFile( + join(packageRoot, "tsconfig.json"), + JSON.stringify({ + compilerOptions: { + rootDir: "src", + outDir: "dist", + tsBuildInfoFile: "tsconfig.tsbuildinfo", + }, + }), + ); + await writeFile( + join(packageRoot, "src", "index.ts"), + "export const reviewed = true;\n", + ); + await writeFile( + join(packageRoot, "dist", "index.js"), + "export const reviewed = false; // tampered ignored output\n", + ); + await writeFile( + join(packageRoot, "dist", "extra.js"), + "throw new Error('unreviewed extra');\n", + ); + await writeFile( + join(packageRoot, "dist", "nested", "stale.js"), + "// stale nested output\n", + ); + await writeFile( + join(packageRoot, "tsconfig.tsbuildinfo"), + "stale incremental cache", + ); + } + await writeFile(join(root, "tsconfig.tsbuildinfo"), "unowned root cache"); + const unrelated = join(root, "packages", "unrelated", "dist"); + await mkdir(unrelated, { recursive: true }); + await writeFile(join(unrelated, "keep.js"), "// unowned output\n"); + return { directory, root }; +} + +test("fresh packaging removes tampered ignored dist trees and incremental caches for the owned package", async (t) => { + const fixture = await outputFixture(t); + await cleanBuildOutputs(fixture.root); + for (const { directory } of specifications) { + const packageRoot = join(fixture.root, "packages", directory); + await assert.rejects(access(join(packageRoot, "dist")), { code: "ENOENT" }); + await assert.rejects(access(join(packageRoot, "tsconfig.tsbuildinfo")), { + code: "ENOENT", + }); + assert.equal( + await readFile(join(packageRoot, "src", "index.ts"), "utf8"), + "export const reviewed = true;\n", + ); + await access(join(packageRoot, "tsconfig.json")); + } + assert.equal( + await readFile(join(fixture.root, "tsconfig.tsbuildinfo"), "utf8"), + "unowned root cache", + ); + await access(join(fixture.root, "packages", "unrelated", "dist", "keep.js")); + await cleanBuildOutputs(fixture.root); +}); + +test("unsafe output configuration fails the complete preflight before any cleanup", async (t) => { + for (const [name, changed] of [ + ["outDir", { outDir: "../outside" }], + ["cache", { tsBuildInfoFile: "../../../outside-cache" }], + ["rootDir", { rootDir: "../outside-source" }], + ]) { + await t.test(name, async (t) => { + const fixture = await outputFixture(t); + const packageRoot = join(fixture.root, "packages", "agent-access"); + await writeFile( + join(fixture.directory, "outside-cache"), + "outside cleanup sentinel\n", + ); + await writeFile( + join(packageRoot, "tsconfig.json"), + JSON.stringify({ + compilerOptions: { + rootDir: "src", + outDir: "dist", + tsBuildInfoFile: "tsconfig.tsbuildinfo", + ...changed, + }, + }), + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + await access(join(packageRoot, "dist", "extra.js")); + await access(join(packageRoot, "tsconfig.tsbuildinfo")); + assert.equal( + await readFile(join(fixture.directory, "outside-cache"), "utf8"), + "outside cleanup sentinel\n", + ); + }); + } +}); + +test("a linked owned output directory is rejected without touching its target", async (t) => { + const fixture = await outputFixture(t); + const target = join(fixture.directory, "outside-output"); + await mkdir(target); + await writeFile(join(target, "keep.js"), "synthetic outside sentinel\n"); + const output = join(fixture.root, "packages", "agent-access", "dist"); + await rename(output, join(fixture.directory, "original-agent-access-dist")); + await symlink( + target, + output, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + assert.equal( + await readFile(join(target, "keep.js"), "utf8"), + "synthetic outside sentinel\n", + ); + await access( + join(fixture.directory, "original-agent-access-dist", "extra.js"), + ); +}); + +test("a link nested inside an output tree is rejected before recursive cleanup", async (t) => { + const fixture = await outputFixture(t); + const target = join(fixture.directory, "outside-nested"); + await mkdir(target); + await writeFile(join(target, "keep.js"), "synthetic nested sentinel\n"); + const output = join( + fixture.root, + "packages", + "agent-access", + "dist", + "linked", + ); + await symlink( + target, + output, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + await access(join(target, "keep.js")); + await access( + join(fixture.root, "packages", "agent-access", "dist", "extra.js"), + ); +}); + +test("a non-file incremental cache is rejected rather than recursively removed", async (t) => { + const fixture = await outputFixture(t); + const cache = join( + fixture.root, + "packages", + "agent-access", + "tsconfig.tsbuildinfo", + ); + await rename(cache, join(fixture.directory, "original-agent-access-cache")); + await mkdir(cache); + await writeFile( + join(cache, "keep.txt"), + "must not recursively delete a cache directory\n", + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + await access(join(cache, "keep.txt")); + await access( + join(fixture.root, "packages", "agent-access", "dist", "extra.js"), + ); +}); + +test("a linked package directory cannot redirect cleanup outside the checkout", async (t) => { + const fixture = await outputFixture(t); + const packageRoot = join(fixture.root, "packages", "agent-access"); + const target = join(fixture.directory, "outside-agent-access"); + await rename(packageRoot, target); + await symlink( + target, + packageRoot, + process.platform === "win32" ? "junction" : "dir", + ); + await assert.rejects(cleanBuildOutputs(fixture.root)); + await access(join(target, "dist", "extra.js")); + await access( + join(fixture.root, "packages", "agent-access", "dist", "extra.js"), + ); +}); diff --git a/tests/release/registry.test.mjs b/tests/release/registry.test.mjs new file mode 100644 index 0000000..475abea --- /dev/null +++ b/tests/release/registry.test.mjs @@ -0,0 +1,1121 @@ +import assert from "node:assert/strict"; +import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; +import { basename, dirname, join } from "node:path"; +import test from "node:test"; +import { + assertTrustedPublishingEnvironment, + preflightRegistry, + publishPreparedRelease, + RELEASE_WORKFLOW, + verifyProvenanceAudit, + verifyRegistryRelease, +} from "../../scripts/release-registry.mjs"; +import { + verifyPreparedManifest, + writePreparedManifest, +} from "../../scripts/release-manifest.mjs"; +import { + identity, + preparedFixture, + syntheticCertificate, +} from "./fixtures.mjs"; + +const registry = "https://registry.npmjs.org/"; + +function tarballUrl(record) { + return `${registry}${record.name}/-/${record.name.split("/")[1]}-${record.version}.tgz`; +} + +function metadata(record) { + return { + name: record.name, + version: record.version, + dependencies: structuredClone(record.dependencies), + dist: { + shasum: record.shasum, + integrity: record.integrity, + tarball: tarballUrl(record), + }, + }; +} + +function jsonResponse(value, status = 200) { + return new Response(JSON.stringify(value), { + status, + headers: { "content-type": "application/json" }, + }); +} + +async function fixture(t) { + const prepared = await preparedFixture(t); + const written = await writePreparedManifest(prepared); + const npmCli = join(prepared.directory, "npm-cli.js"); + await writeFile(npmCli, "// Synthetic seam: never executed.\n"); + const options = { + preparedDir: prepared.preparedDir, + expectedManifestSha256: written.manifestSha256, + expectedTag: identity.tag, + expectedCommit: identity.commit, + npmCli, + }; + const verified = await verifyPreparedManifest(options); + const blobs = new Map(); + for (const record of verified.artifacts) { + blobs.set(record.name, await readFile(record.path)); + } + return { ...prepared, options, verified, blobs }; +} + +function fakeRegistry( + fixture, + present = fixture.verified.artifacts.map(({ name }) => name), +) { + const state = { + present: new Set(present), + requests: [], + metadata: undefined, + blob: undefined, + beforeRequest: undefined, + }; + state.fetch = async (input, options) => { + const url = String(input); + assert.equal(options.redirect, "error"); + assert.ok(options.method === undefined || options.method === "GET"); + assert.ok(options.signal instanceof AbortSignal); + const record = fixture.verified.artifacts.find( + (record) => + url === + `${registry}${encodeURIComponent(record.name)}/${record.version}` || + url === tarballUrl(record), + ); + assert.ok(record, `Unexpected registry URL: ${url}`); + const kind = url === tarballUrl(record) ? "tarball" : "metadata"; + state.requests.push({ kind, name: record.name }); + await state.beforeRequest?.(kind, record); + if (kind === "metadata") { + const overridden = await state.metadata?.(record); + if (overridden !== undefined) return overridden; + return state.present.has(record.name) + ? jsonResponse(metadata(record)) + : jsonResponse({ error: "Not found" }, 404); + } + const overridden = await state.blob?.(record); + return overridden ?? new Response(fixture.blobs.get(record.name)); + }; + return state; +} + +function trustedEnvironment() { + return { + GITHUB_ACTIONS: "true", + GITHUB_EVENT_NAME: "release", + GITHUB_REPOSITORY: "pegma-dev/agent-access", + GITHUB_REPOSITORY_ID: "123456789", + GITHUB_REPOSITORY_OWNER_ID: "987654321", + GITHUB_RUN_ID: "1234567890", + GITHUB_RUN_ATTEMPT: "1", + GITHUB_SERVER_URL: "https://github.com", + GITHUB_REF: `refs/tags/${identity.tag}`, + GITHUB_SHA: identity.commit, + GITHUB_WORKFLOW_REF: `pegma-dev/agent-access/${RELEASE_WORKFLOW}@refs/tags/${identity.tag}`, + GITHUB_WORKFLOW_SHA: identity.commit, + RUNNER_ENVIRONMENT: "github-hosted", + ACTIONS_ID_TOKEN_REQUEST_URL: + "https://pipelines.actions.githubusercontent.com/synthetic", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "synthetic-oidc-request-token", + SYNTHETIC_SOURCE_SECRET: "must-not-reach-npm", + GITHUB_TOKEN: "synthetic-github-token", + GH_TOKEN: "synthetic-gh-token", + GITHUB_CUSTOM_SECRET: "synthetic-github-secret", + GITHUB_APP_PRIVATE_KEY: "synthetic-github-app-key", + RUNNER_CUSTOM_SECRET: "synthetic-runner-secret", + ACTIONS_ID_TOKEN_REQUEST_CUSTOM_SECRET: "synthetic-oidc-extra-secret", + PATH: "synthetic-os-path", + TEMP: "synthetic-os-temp", + NODE_OPTIONS: "--require=synthetic-untrusted-hook.cjs", + }; +} + +function publisher(fixture, state) { + const calls = []; + const sleeps = []; + const seams = { + env: trustedEnvironment(), + fetch: state.fetch, + sleep: async (milliseconds) => { + sleeps.push(milliseconds); + }, + run: async (command, arguments_, context) => { + calls.push({ command, arguments_, context }); + assert.equal(command, process.execPath); + assert.equal(arguments_[0], fixture.options.npmCli); + assert.equal(context.env.SYNTHETIC_SOURCE_SECRET, undefined); + assert.equal(context.env.NODE_OPTIONS, undefined); + assert.equal(context.env.npm_config_ignore_scripts, "true"); + assert.equal(context.env.npm_config_registry, registry); + assert.notEqual(context.cwd, fixture.preparedDir); + for (const key of ["npm_config_userconfig", "npm_config_globalconfig"]) { + assert.equal(dirname(context.env[key]), context.cwd); + assert.equal(await readFile(context.env[key], "utf8"), ""); + } + assert.equal(dirname(context.env.npm_config_cache), context.cwd); + assert.equal( + await readFile(join(context.cwd, ".npmrc"), "utf8"), + `registry=${registry}\n`, + ); + if (arguments_[1] === "--version") { + return { status: 0, stdout: "11.18.0\n", stderr: "" }; + } + assert.equal(arguments_[1], "publish"); + const record = fixture.verified.artifacts.find( + ({ filename }) => filename === basename(arguments_[2]), + ); + assert.ok(record); + assert.equal(dirname(arguments_[2]), context.cwd); + assert.deepEqual( + await readFile(arguments_[2]), + fixture.blobs.get(record.name), + ); + assert.deepEqual(arguments_.slice(3), [ + "--ignore-scripts", + "--access", + "public", + "--provenance", + "--registry", + registry, + ]); + const initialLookups = new Set( + state.requests + .filter(({ kind }) => kind === "metadata") + .map(({ name }) => name), + ); + assert.equal( + initialLookups.size, + 1, + "the exact version must be checked before npm publish", + ); + state.present.add(record.name); + return { status: 0, stdout: "synthetic publication\n", stderr: "" }; + }, + }; + return { seams, calls, sleeps }; +} + +test("only explicit version 404s produce a publication plan for the exact package", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const plan = await preflightRegistry(prepared.verified, { + fetch: state.fetch, + }); + assert.deepEqual( + plan, + prepared.artifacts.map(({ name, version }) => ({ + name, + version, + action: "publish", + })), + ); + assert.ok(Object.isFrozen(plan)); + assert.ok(plan.every(Object.isFrozen)); + assert.equal(state.requests.length, 1); + assert.ok(state.requests.every(({ kind }) => kind === "metadata")); +}); + +test("existing versions require exact metadata plus downloaded tarball bytes before recovery can skip them", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + const plan = await preflightRegistry(prepared.verified, { + fetch: state.fetch, + }); + assert.deepEqual( + plan.map(({ action }) => action), + ["skip"], + ); + assert.equal( + state.requests.filter(({ kind }) => kind === "tarball").length, + 1, + ); +}); + +test("unknown metadata responses and network errors never establish absence", async (t) => { + for (const status of [ + 204, + 301, + 400, + 401, + 403, + 409, + 429, + 500, + 503, + "network", + "malformed", + "failed response containing E404", + ]) { + await t.test(String(status), async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + state.metadata = (record) => { + if (record.name !== prepared.artifacts[0].name) return undefined; + if (status === "network") + throw new Error("synthetic-credential-do-not-echo"); + if (status === "malformed") + return new Response("synthetic-credential-do-not-echo", { + status: 200, + }); + if (status === "failed response containing E404") + return new Response("E404 synthetic-credential-do-not-echo", { + status: 503, + }); + return new Response(null, { status }); + }; + const publishing = publisher(prepared, state); + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + (error) => !error.message.includes("synthetic-credential-do-not-echo"), + ); + assert.equal(publishing.calls.length, 0); + }); + } +}); + +test("a conflicting exact version prevents publication before npm execution", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, [prepared.artifacts[0].name]); + state.metadata = (record) => { + if (record.name !== prepared.artifacts[0].name) return undefined; + const value = metadata(record); + value.dependencies.zod = "99.0.0"; + return jsonResponse(value); + }; + const publishing = publisher(prepared, state); + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /conflicts/u, + ); + assert.equal(publishing.calls.length, 0); +}); + +test("matching integrity alone cannot authorize wrong metadata or a foreign tarball URL", async (t) => { + const changes = [ + [ + "name", + (value) => { + value.name = "@other/agent-access"; + }, + ], + [ + "version", + (value) => { + value.version = "0.2.0"; + }, + ], + [ + "dependency", + (value) => { + value.dependencies["@pegma/spine"] = "^0.1.2"; + }, + ], + [ + "extra dependency", + (value) => { + value.dependencies.extra = "1.0.0"; + }, + ], + [ + "SHA-1", + (value) => { + value.dist.shasum = "0".repeat(40); + }, + ], + [ + "SHA-512", + (value) => { + value.dist.integrity = "sha512-unreviewed"; + }, + ], + [ + "foreign host", + (value) => { + value.dist.tarball = "https://example.invalid/package.tgz"; + }, + ], + [ + "foreign registry path", + (value) => { + value.dist.tarball = `${registry}other/-/other-0.1.0.tgz`; + }, + ], + [ + "optional dependency", + (value) => { + value.optionalDependencies = { extra: "1.0.0" }; + }, + ], + [ + "peer dependency", + (value) => { + value.peerDependencies = { extra: "1.0.0" }; + }, + ], + ]; + for (const [name, change] of changes) { + await t.test(name, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + state.metadata = (record) => { + const value = metadata(record); + change(value); + return jsonResponse(value); + }; + await assert.rejects( + preflightRegistry(prepared.verified, { fetch: state.fetch }), + /conflicts/u, + ); + assert.equal( + state.requests.some(({ kind }) => kind === "tarball"), + false, + ); + }); + } +}); + +test("registry tarball bytes, length, and response status are independently verified", async (t) => { + for (const problem of [ + "changed bytes", + "too short", + "too large", + "404", + "redirect", + "declared too large", + ]) { + await t.test(problem, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + state.blob = (record) => { + const bytes = Buffer.from(prepared.blobs.get(record.name)); + if (problem === "404") return new Response(null, { status: 404 }); + if (problem === "redirect") return new Response(null, { status: 302 }); + if (problem === "too short") return new Response(bytes.subarray(1)); + if (problem === "too large") + return new Response(Buffer.concat([bytes, Buffer.from("extra")])); + if (problem === "declared too large") + return new Response(bytes, { + headers: { "content-length": String(bytes.length + 1) }, + }); + bytes[0] ^= 1; + return new Response(bytes); + }; + await assert.rejects( + preflightRegistry(prepared.verified, { fetch: state.fetch }), + /tarball/u, + ); + }); + } +}); + +test("publishing inherits approved provenance and OIDC variables without GitHub credentials", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + await publishPreparedRelease(prepared.options, publishing.seams); + assert.ok(publishing.calls.length > 0); + for (const { context } of publishing.calls) { + for (const key of [ + "GITHUB_TOKEN", + "GH_TOKEN", + "GITHUB_CUSTOM_SECRET", + "GITHUB_APP_PRIVATE_KEY", + "RUNNER_CUSTOM_SECRET", + "ACTIONS_ID_TOKEN_REQUEST_CUSTOM_SECRET", + ]) { + assert.equal(context.env[key], undefined, key); + } + for (const key of [ + "GITHUB_ACTIONS", + "GITHUB_EVENT_NAME", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_SERVER_URL", + "GITHUB_REF", + "GITHUB_SHA", + "GITHUB_WORKFLOW_REF", + "GITHUB_WORKFLOW_SHA", + "GITHUB_RUN_ID", + "GITHUB_RUN_ATTEMPT", + "RUNNER_ENVIRONMENT", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "PATH", + "TEMP", + ]) { + assert.equal(context.env[key], publishing.seams.env[key], key); + } + } +}); + +test("a first publication checks the complete artifact then publishes only its prepared blob", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.deepEqual(result, { + published: prepared.artifacts.map(({ name }) => name), + skipped: [], + verified: true, + }); + assert.deepEqual( + publishing.calls + .filter(({ arguments_ }) => arguments_[1] === "publish") + .map(({ arguments_ }) => basename(arguments_[2])), + prepared.artifacts.map(({ filename }) => filename), + ); + assert.equal(publishing.sleeps.length, 0); + assert.ok(Object.isFrozen(result.published)); +}); + +test("an existing verified version and its rerun perform no publication or installation", async (t) => { + const prepared = await fixture(t); + const names = prepared.artifacts.map(({ name }) => name); + const state = fakeRegistry(prepared, names); + const publishing = publisher(prepared, state); + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.deepEqual(result.published, []); + assert.deepEqual(result.skipped, names); + const rerun = publisher(prepared, state); + const recovered = await publishPreparedRelease(prepared.options, rerun.seams); + assert.deepEqual(recovered.published, []); + assert.deepEqual(recovered.skipped, names); + assert.equal( + rerun.calls.some(({ arguments_ }) => arguments_[1] === "publish"), + false, + ); + assert.ok( + [...publishing.calls, ...rerun.calls].every( + ({ arguments_ }) => arguments_[1] === "--version", + ), + ); +}); + +test("a matching version published concurrently is reverified and skipped immediately before publication", async (t) => { + const prepared = await fixture(t); + const names = prepared.artifacts.map(({ name }) => name); + const state = fakeRegistry(prepared, names.slice(1)); + let lookups = 0; + state.beforeRequest = (kind, record) => { + if (kind === "metadata" && record.name === names[0] && ++lookups === 2) + state.present.add(names[0]); + }; + const publishing = publisher(prepared, state); + const result = await publishPreparedRelease( + prepared.options, + publishing.seams, + ); + assert.deepEqual(result.published, []); + assert.deepEqual(result.skipped, names); + assert.equal( + publishing.calls.some(({ arguments_ }) => arguments_[1] === "publish"), + false, + ); +}); + +test("post-publication absence has a bounded retry budget and unknown states fail immediately", async (t) => { + for (const problem of ["404", "network"]) { + await t.test(problem, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + let published = false; + const publishing = publisher(prepared, state); + const originalRun = publishing.seams.run; + publishing.seams.run = async (...arguments_) => { + const result = await originalRun(...arguments_); + if (arguments_[1][1] === "publish") published = true; + return result; + }; + state.metadata = () => { + if (!published) return undefined; + if (problem === "network") + throw new Error("synthetic unknown network state"); + return jsonResponse({ error: "Not found" }, 404); + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + ); + assert.equal( + publishing.calls.filter(({ arguments_ }) => arguments_[1] === "publish") + .length, + 1, + ); + assert.deepEqual( + publishing.sleeps, + problem === "404" ? [1000, 2000, 4000, 8000, 16000] : [], + ); + }); + } +}); + +test("privileged publication requires the exact hosted release workflow identity and rejects inherited npm authority", () => { + assert.doesNotThrow(() => + assertTrustedPublishingEnvironment(trustedEnvironment(), identity), + ); + for (const [key, value] of Object.entries({ + GITHUB_ACTIONS: "false", + GITHUB_EVENT_NAME: "workflow_dispatch", + GITHUB_REPOSITORY: "other/agent-access", + GITHUB_SERVER_URL: "https://example.invalid", + GITHUB_REF: "refs/heads/main", + GITHUB_SHA: "b".repeat(40), + GITHUB_WORKFLOW_REF: "other/workflow@refs/heads/main", + GITHUB_WORKFLOW_SHA: "b".repeat(40), + RUNNER_ENVIRONMENT: "self-hosted", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.invalid/oidc", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "", + NPM_TOKEN: "synthetic-token", + NODE_AUTH_TOKEN: "synthetic-token", + NPM_AUTH_TOKEN: "synthetic-token", + YARN_NPM_AUTH_TOKEN: "synthetic-token", + npm_config_registry: "https://example.invalid/", + NPM_CONFIG_USERCONFIG: "synthetic-npmrc", + })) { + assert.throws(() => + assertTrustedPublishingEnvironment( + { ...trustedEnvironment(), [key]: value }, + identity, + ), + ); + } +}); + +// This report is a unit seam for successful `npm audit signatures`, never a +// Sigstore trust proof. The synthetic certificate only exercises identity +// parsing; the real readonly verifier must run npm's cryptographic audit first. +function provenanceAudit(manifest) { + return { + invalid: [], + missing: [], + verified: manifest.artifacts.map((record) => { + const statement = { + _type: "https://in-toto.io/Statement/v1", + predicateType: "https://slsa.dev/provenance/v1", + subject: [ + { + name: `pkg:npm/${record.name.split("/").map(encodeURIComponent).join("/")}@${record.version}`, + digest: { + sha512: Buffer.from(record.integrity.slice(7), "base64").toString( + "hex", + ), + }, + }, + ], + predicate: { + buildDefinition: { + buildType: + "https://slsa-framework.github.io/github-actions-buildtypes/workflow/v1", + externalParameters: { + workflow: { + repository: "https://github.com/pegma-dev/agent-access", + path: RELEASE_WORKFLOW, + ref: `refs/tags/${identity.tag}`, + }, + }, + internalParameters: { github: { event_name: "release" } }, + resolvedDependencies: [ + { + uri: `git+https://github.com/pegma-dev/agent-access@refs/tags/${identity.tag}`, + digest: { gitCommit: identity.commit }, + }, + ], + }, + runDetails: { + builder: { id: "https://github.com/actions/runner/github-hosted" }, + }, + }, + }; + return { + name: record.name, + version: record.version, + location: `node_modules/${record.name}`, + registry, + attestationBundles: [ + { + predicateType: "https://slsa.dev/provenance/v1", + bundle: { + verificationMaterial: { + certificate: { rawBytes: syntheticCertificate() }, + }, + dsseEnvelope: { + payloadType: "application/vnd.in-toto+json", + payload: Buffer.from(JSON.stringify(statement)).toString( + "base64", + ), + }, + }, + }, + ], + }; + }), + }; +} + +test("cryptographically verified provenance must still bind every prepared package to the exact source workflow", async (t) => { + const prepared = await fixture(t); + assert.doesNotThrow(() => + verifyProvenanceAudit( + provenanceAudit(prepared.verified.manifest), + prepared.verified.manifest, + ), + ); + const changes = [ + [ + "missing package", + (audit) => { + audit.verified.pop(); + }, + ], + [ + "invalid signature", + (audit) => { + audit.invalid.push({ name: "synthetic" }); + }, + ], + [ + "missing attestation", + (audit) => { + audit.missing.push({ name: "synthetic" }); + }, + ], + [ + "duplicate package", + (audit) => { + audit.verified.push(audit.verified[0]); + }, + ], + [ + "foreign registry", + (audit) => { + audit.verified[0].registry = "https://example.invalid/"; + }, + ], + [ + "absent source bundle", + (audit) => { + audit.verified[0].attestationBundles = []; + }, + ], + [ + "missing certificate", + (audit) => { + delete audit.verified[0].attestationBundles[0].bundle + .verificationMaterial; + }, + ], + [ + "wrong certificate workflow", + (audit) => { + audit.verified[0].attestationBundles[0].bundle.verificationMaterial.certificate.rawBytes = + syntheticCertificate({ workflow: ".github/workflows/other.yml" }); + }, + ], + [ + "wrong certificate repository", + (audit) => { + audit.verified[0].attestationBundles[0].bundle.verificationMaterial.certificate.rawBytes = + syntheticCertificate({ repository: "other/agent-access" }); + }, + ], + [ + "wrong certificate tag", + (audit) => { + audit.verified[0].attestationBundles[0].bundle.verificationMaterial.certificate.rawBytes = + syntheticCertificate({ tag: "v0.2.0" }); + }, + ], + [ + "wrong certificate issuer", + (audit) => { + audit.verified[0].attestationBundles[0].bundle.verificationMaterial.certificate.rawBytes = + syntheticCertificate({ issuer: "https://example.invalid" }); + }, + ], + ]; + for (const [name, change] of changes) { + const audit = provenanceAudit(prepared.verified.manifest); + change(audit); + assert.throws( + () => verifyProvenanceAudit(audit, prepared.verified.manifest), + undefined, + name, + ); + } + for (const [name, change] of [ + [ + "wrong commit", + (statement) => { + statement.predicate.buildDefinition.resolvedDependencies[0].digest.gitCommit = + "b".repeat(40); + }, + ], + [ + "wrong tag", + (statement) => { + statement.predicate.buildDefinition.externalParameters.workflow.ref = + "refs/tags/v0.2.0"; + }, + ], + [ + "wrong workflow", + (statement) => { + statement.predicate.buildDefinition.externalParameters.workflow.path = + ".github/workflows/other.yml"; + }, + ], + [ + "wrong repository", + (statement) => { + statement.predicate.buildDefinition.externalParameters.workflow.repository = + "https://github.com/other/agent-access"; + }, + ], + [ + "wrong artifact digest", + (statement) => { + statement.subject[0].digest.sha512 = "0".repeat(128); + }, + ], + [ + "self hosted builder", + (statement) => { + statement.predicate.runDetails.builder.id = "synthetic-self-hosted"; + }, + ], + ]) { + const audit = provenanceAudit(prepared.verified.manifest); + const envelope = + audit.verified[0].attestationBundles[0].bundle.dsseEnvelope; + const statement = JSON.parse( + Buffer.from(envelope.payload, "base64").toString("utf8"), + ); + change(statement); + envelope.payload = Buffer.from(JSON.stringify(statement)).toString( + "base64", + ); + assert.throws( + () => verifyProvenanceAudit(audit, prepared.verified.manifest), + undefined, + name, + ); + } +}); + +test("registry verification uses exact released dependencies, script-free installation, public imports, and npm signature audit", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + const operations = []; + const result = await verifyRegistryRelease(prepared.options, { + fetch: state.fetch, + env: { + SYNTHETIC_SOURCE_SECRET: "must-not-reach-consumer", + NPM_TOKEN: "must-not-reach-consumer", + NODE_AUTH_TOKEN: "must-not-reach-consumer", + NODE_OPTIONS: "--require=synthetic-untrusted-hook.cjs", + NPM_CONFIG_USERCONFIG: "synthetic-project-npmrc", + npm_config_registry: "https://example.invalid/", + }, + run: async (command, arguments_, { cwd, env }) => { + assert.equal(command, process.execPath); + assert.equal(env.SYNTHETIC_SOURCE_SECRET, undefined); + assert.equal(env.NPM_TOKEN, undefined); + assert.equal(env.NODE_AUTH_TOKEN, undefined); + assert.equal(env.NODE_OPTIONS, undefined); + assert.equal(env.NPM_CONFIG_USERCONFIG, undefined); + assert.equal(env.npm_config_registry, registry); + assert.equal(env.npm_config_ignore_scripts, "true"); + for (const key of ["npm_config_userconfig", "npm_config_globalconfig"]) { + assert.equal(dirname(env[key]), cwd); + assert.equal(await readFile(env[key], "utf8"), ""); + } + assert.equal(dirname(env.npm_config_cache), cwd); + const operation = + arguments_[0] === prepared.options.npmCli + ? arguments_[1] + : "public-imports"; + operations.push(operation); + if (operation === "--version") return { status: 0, stdout: "11.18.0\n" }; + if (operation === "install") { + assert.deepEqual(arguments_.slice(1), [ + "install", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--registry", + registry, + ]); + const consumer = JSON.parse( + await readFile(join(cwd, "package.json"), "utf8"), + ); + assert.deepEqual( + consumer.dependencies, + Object.fromEntries( + prepared.artifacts.map(({ name, version }) => [name, version]), + ), + ); + await writeFile( + join(cwd, "package-lock.json"), + JSON.stringify({ + packages: Object.fromEntries( + prepared.artifacts.map((record) => [ + `node_modules/${record.name}`, + { + version: record.version, + integrity: record.integrity, + resolved: tarballUrl(record), + }, + ]), + ), + }), + ); + return { status: 0, stdout: "" }; + } + if (operation === "public-imports") { + const source = await readFile(arguments_[0], "utf8"); + for (const { name } of prepared.artifacts) + assert.ok(source.includes(name)); + return { status: 0, stdout: "" }; + } + assert.equal(operation, "audit"); + assert.deepEqual(arguments_.slice(1), [ + "audit", + "signatures", + "--json", + "--include-attestations", + "--registry", + registry, + ]); + return { + status: 0, + stdout: JSON.stringify(provenanceAudit(prepared.verified.manifest)), + }; + }, + }); + assert.deepEqual(operations, [ + "--version", + "install", + "audit", + "public-imports", + ]); + assert.deepEqual( + result.packages, + prepared.artifacts.map(({ name }) => name), + ); + assert.equal(result.verified, true); +}); + +test("registry verification stops before npm when any release package is absent", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry( + prepared, + prepared.artifacts.slice(0, 0).map(({ name }) => name), + ); + const publishing = publisher(prepared, state); + await assert.rejects( + verifyRegistryRelease(prepared.options, publishing.seams), + /complete release set/u, + ); + assert.equal(publishing.calls.length, 0); +}); + +test("local prepared blob tampering fails before registry access or npm execution", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + await writeFile( + prepared.verified.artifacts[0].path, + "unreviewed prepared bytes", + ); + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + ); + assert.equal(state.requests.length, 0); + assert.equal(publishing.calls.length, 0); +}); + +test("the snapshot blob is rehashed before privileged publication", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + const originalRun = publishing.seams.run; + publishing.seams.run = async (...arguments_) => { + const result = await originalRun(...arguments_); + if (arguments_[1][1] === "--version") { + const record = prepared.verified.artifacts[0]; + const bytes = Buffer.from(prepared.blobs.get(record.name)); + bytes[0] ^= 1; + await writeFile(record.path, bytes); + } + return result; + }; + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /changed after verification/u, + ); + assert.equal( + publishing.calls.some(({ arguments_ }) => arguments_[1] === "publish"), + false, + ); +}); + +test("a linked npm CLI ancestor is rejected before any npm subprocess", async (t) => { + for (const mode of ["publish", "verify"]) { + await t.test(mode, async (t) => { + const prepared = await fixture(t); + const canonicalDirectory = join(prepared.directory, "canonical-npm"); + await mkdir(canonicalDirectory); + await writeFile( + join(canonicalDirectory, "npm-cli.js"), + "// Synthetic seam: never executed.\n", + ); + const linkedDirectory = join(prepared.directory, "linked-npm"); + await symlink( + canonicalDirectory, + linkedDirectory, + process.platform === "win32" ? "junction" : "dir", + ); + const options = { + ...prepared.options, + npmCli: join(linkedDirectory, "npm-cli.js"), + }; + const state = fakeRegistry(prepared, mode === "publish" ? [] : undefined); + const calls = []; + const operation = + mode === "publish" ? publishPreparedRelease : verifyRegistryRelease; + await assert.rejects( + operation(options, { + env: trustedEnvironment(), + fetch: state.fetch, + run: async (...arguments_) => { + calls.push(arguments_); + throw new Error("Unexpected npm subprocess."); + }, + }), + /pinned npm CLI/u, + ); + assert.deepEqual(calls, []); + assert.equal( + state.present.size, + mode === "publish" ? 0 : prepared.artifacts.length, + ); + }); + } +}); + +test("an unexpected npm version cannot publish any prepared package", async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared, []); + const publishing = publisher(prepared, state); + publishing.seams.run = async () => ({ status: 0, stdout: "11.17.0\n" }); + await assert.rejects( + publishPreparedRelease(prepared.options, publishing.seams), + /pinned npm CLI/u, + ); + assert.equal(state.present.size, 0); +}); + +test("the supported certificate-chain attestation shape binds the same source identity", async (t) => { + const prepared = await fixture(t); + const audit = provenanceAudit(prepared.verified.manifest); + audit.verified[0].attestationBundles[0].bundle.verificationMaterial = { + x509CertificateChain: { + certificates: [{ rawBytes: syntheticCertificate() }], + }, + }; + assert.doesNotThrow(() => + verifyProvenanceAudit(audit, prepared.verified.manifest), + ); +}); + +test("consumer lock and provenance failures stop verification before package runtime imports", async (t) => { + for (const problem of [ + "wrong version", + "workspace link", + "wrong integrity", + "foreign tarball", + "invalid crypto audit", + "wrong provenance source", + ]) { + await t.test(problem, async (t) => { + const prepared = await fixture(t); + const state = fakeRegistry(prepared); + const operations = []; + await assert.rejects( + verifyRegistryRelease(prepared.options, { + fetch: state.fetch, + env: {}, + run: async (_command, arguments_, { cwd }) => { + const operation = + arguments_[0] === prepared.options.npmCli + ? arguments_[1] + : "public-imports"; + operations.push(operation); + if (operation === "--version") + return { status: 0, stdout: "11.18.0\n" }; + if (operation === "install") { + const packages = Object.fromEntries( + prepared.artifacts.map((record) => [ + `node_modules/${record.name}`, + { + version: record.version, + integrity: record.integrity, + resolved: tarballUrl(record), + }, + ]), + ); + const installed = + packages[`node_modules/${prepared.artifacts[0].name}`]; + if (problem === "wrong version") installed.version = "0.2.0"; + if (problem === "workspace link") installed.link = true; + if (problem === "wrong integrity") + installed.integrity = "sha512-unreviewed"; + if (problem === "foreign tarball") + installed.resolved = "https://example.invalid/foreign.tgz"; + await writeFile( + join(cwd, "package-lock.json"), + JSON.stringify({ packages }), + ); + return { status: 0, stdout: "" }; + } + assert.equal( + operation, + "audit", + "package imports cannot precede a valid exact provenance audit", + ); + if (problem === "invalid crypto audit") + return { status: 1, stdout: "synthetic failure" }; + const audit = provenanceAudit(prepared.verified.manifest); + audit.verified[0].attestationBundles[0].bundle.verificationMaterial.certificate.rawBytes = + syntheticCertificate({ workflow: ".github/workflows/other.yml" }); + return { status: 0, stdout: JSON.stringify(audit) }; + }, + }), + ); + assert.equal(operations.includes("public-imports"), false); + assert.deepEqual( + operations, + [ + "wrong version", + "workspace link", + "wrong integrity", + "foreign tarball", + ].includes(problem) + ? ["--version", "install"] + : ["--version", "install", "audit"], + ); + }); + } +});