From e5a44d63ff89c09d39f4d52de2d1a732fc92b55a Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 14:39:02 -0500 Subject: [PATCH 1/6] Harden release preparation and blob validation --- .github/workflows/ci.yml | 2 + .github/workflows/publish.yml | 433 ++++++++++++++++-- docs/RELEASING.md | 33 +- packages/storage-azure-blob/src/index.test.ts | 16 + packages/storage-azure-blob/src/index.ts | 102 ++++- packages/storage-blobs/src/conformance.ts | 88 +++- packages/storage-blobs/src/index.ts | 77 ++-- packages/storage-cloudflare-r2/src/index.ts | 76 +-- packages/storage-s3/src/index.ts | 76 +-- scripts/release-packages.d.mts | 5 + scripts/release-packages.mjs | 254 ++++++++-- test/localstack.ts | 4 +- tests/release-packages.test.ts | 59 ++- 13 files changed, 1016 insertions(+), 209 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d57d217..acce751 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,8 @@ jobs: validate: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest + env: + CI: "1" strategy: fail-fast: false matrix: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index a5cbdea..77e2bba 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,4 +1,4 @@ -# Publishes the exact tarball prepared from a stable GitHub release tag. +# Publishes the exact tarballs prepared from a stable GitHub release tag. # Authentication is npm trusted-publisher OIDC only; no token fallback exists. name: Publish @@ -19,40 +19,75 @@ jobs: runs-on: ubuntu-latest outputs: manifest-digest: ${{ steps.manifest.outputs.digest }} + artifact-digest: ${{ steps.upload.outputs.artifact-digest }} env: + CI: "1" RELEASE_TAG: ${{ github.event.release.tag_name }} RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} steps: - - name: Check out the release tag - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: refs/tags/${{ github.event.release.tag_name }} - fetch-depth: 0 - - - name: Fetch the protected release branch - run: git fetch --no-tags origin main:refs/remotes/origin/main - - - name: Configure approved release signers + - name: Authenticate the release source shell: bash run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish packages" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]]; then + echo "::error::Release tag format is invalid" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::Release commit must be a 40-character hexadecimal object ID" + exit 1 + fi if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then echo "::error::RELEASE_ALLOWED_SIGNERS must contain the 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}" + chmod 0600 "${allowed_signers}" + + verify_dir="$(mktemp -d "${RUNNER_TEMP}/release-git.XXXXXX")" + trap 'rm -rf "${verify_dir}"' EXIT + git init --bare "${verify_dir}" + git -C "${verify_dir}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + git -C "${verify_dir}" config gpg.format ssh + git -C "${verify_dir}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${verify_dir}" fetch --no-tags origin refs/heads/main:refs/remotes/origin/main + git -C "${verify_dir}" fetch --no-tags origin "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + test "$(git -C "${verify_dir}" cat-file -t "refs/tags/${RELEASE_TAG}")" = "tag" + git -C "${verify_dir}" verify-tag "refs/tags/${RELEASE_TAG}" + peeled="$(git -C "${verify_dir}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + test "${peeled}" = "${RELEASE_COMMIT}" + git -C "${verify_dir}" merge-base --is-ancestor "${RELEASE_COMMIT}" refs/remotes/origin/main + + - name: Check out the exact release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 0 + + - name: Fetch the verified release refs + shell: bash + run: | + set -euo pipefail + git fetch --no-tags origin refs/heads/main:refs/remotes/origin/main + git fetch --no-tags origin "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" git config --local gpg.format ssh - git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + git config --local gpg.ssh.allowedSignersFile "${RUNNER_TEMP}/release-allowed-signers" - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false - name: Enable Corepack @@ -73,65 +108,399 @@ jobs: - name: Run tests run: pnpm test - - 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 + - name: Seal the release packages + run: pnpm run release:pack -- --skip-smoke --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release - # Crosses the job boundary through run metadata rather than the artifact, - # so the publish job cannot be fooled by a self-consistent replacement of - # the manifest and the tarballs it describes. - name: Record the prepared manifest digest id: manifest shell: bash run: | + set -euo pipefail digest="$(sha256sum .release/package-manifest.json | cut -d ' ' -f 1)" printf 'digest=%s\n' "${digest}" >> "${GITHUB_OUTPUT}" printf 'Prepared manifest SHA-256 %s\n' "${digest}" >> "${GITHUB_STEP_SUMMARY}" - - name: Upload the prepared release + - name: Upload the sealed release id: upload uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: name: storage-blobs-release-${{ github.run_id }} path: .release/ if-no-files-found: error - include-hidden-files: true + include-hidden-files: false overwrite: true retention-days: 30 - name: Record the prepared artifact digest - run: echo "Prepared artifact SHA-256 ${{ steps.upload.outputs.artifact-digest }}" >> "${GITHUB_STEP_SUMMARY}" + env: + ARTIFACT_DIGEST: ${{ steps.upload.outputs.artifact-digest }} + run: printf 'Prepared artifact SHA-256 %s\n' "${ARTIFACT_DIGEST}" >> "${GITHUB_STEP_SUMMARY}" - publish: + smoke: needs: prepare runs-on: ubuntu-latest - environment: npm-publish permissions: contents: read - id-token: write env: - RELEASE_TAG: ${{ github.event.release.tag_name }} + CI: "1" RELEASE_COMMIT: ${{ github.sha }} RELEASE_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }} steps: - - name: Check out the exact release tag + - name: Check out the exact release commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: refs/tags/${{ github.event.release.tag_name }} + ref: ${{ github.sha }} + persist-credentials: false fetch-depth: 1 - - name: Set up Node.js and the npm registry + - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # 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 + run: npm install --global npm@11.18.0 + + - name: Download the sealed release copy uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: storage-blobs-release-${{ github.run_id }} path: .release - - name: Publish the verified prepared tarball - run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --expected-manifest-digest "${RELEASE_MANIFEST_DIGEST}" --manifest .release/package-manifest.json + - name: Verify the prepared manifest digest + shell: bash + run: | + set -euo pipefail + actual="$(sha256sum .release/package-manifest.json | cut -d ' ' -f 1)" + test "${actual}" = "${RELEASE_MANIFEST_DIGEST}" + + - name: Run consumer smoke imports + run: node scripts/release-packages.mjs smoke --expected-manifest-digest "${RELEASE_MANIFEST_DIGEST}" --manifest .release/package-manifest.json + + publish: + needs: [prepare, smoke] + runs-on: ubuntu-latest + environment: npm-publish + permissions: + contents: read + id-token: write + env: + CI: "1" + RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} + RELEASE_COMMIT: ${{ github.sha }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} + RELEASE_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }} + + steps: + - name: Re-authenticate the release source + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish packages" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]]; then + echo "::error::Release tag format is invalid" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::Release commit must be a 40-character hexadecimal object ID" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain the 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}" + chmod 0600 "${allowed_signers}" + + verify_dir="$(mktemp -d "${RUNNER_TEMP}/release-git.XXXXXX")" + trap 'rm -rf "${verify_dir}"' EXIT + git init --bare "${verify_dir}" + git -C "${verify_dir}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + git -C "${verify_dir}" config gpg.format ssh + git -C "${verify_dir}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${verify_dir}" fetch --no-tags origin refs/heads/main:refs/remotes/origin/main + git -C "${verify_dir}" fetch --no-tags origin "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + test "$(git -C "${verify_dir}" cat-file -t "refs/tags/${RELEASE_TAG}")" = "tag" + git -C "${verify_dir}" verify-tag "refs/tags/${RELEASE_TAG}" + peeled="$(git -C "${verify_dir}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + test "${peeled}" = "${RELEASE_COMMIT}" + git -C "${verify_dir}" merge-base --is-ancestor "${RELEASE_COMMIT}" refs/remotes/origin/main + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Download the sealed release + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: storage-blobs-release-${{ github.run_id }} + path: ${{ runner.temp }}/release-artifact + + - name: Verify and publish the sealed packages + shell: bash + run: | + set -euo pipefail + artifact_dir="${RUNNER_TEMP}/release-artifact" + actual="$(sha256sum "${artifact_dir}/package-manifest.json" | cut -d ' ' -f 1)" + test "${actual}" = "${RELEASE_MANIFEST_DIGEST}" + + script_path="${RUNNER_TEMP}/publish-release.mjs" + umask 077 + cat > "${script_path}" <<'NODE' + import { spawnSync } from "node:child_process"; + import { createHash, timingSafeEqual } from "node:crypto"; + import { + chmodSync, + lstatSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, + } from "node:fs"; + import { dirname, join, resolve } from "node:path"; + + const registry = "https://registry.npmjs.org/"; + const packages = [ + "@pegma/storage-blobs", + "@pegma/storage-azure-blob", + "@pegma/storage-cloudflare-r2", + "@pegma/storage-s3", + ]; + const artifactDirectory = resolve(process.env.RUNNER_TEMP, "release-artifact"); + const manifestPath = join(artifactDirectory, "package-manifest.json"); + + function fail(message) { + throw new Error(message); + } + + function equal(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) { + return createHash(algorithm).update(bytes).digest(encoding); + } + + function expectedTarball(name, version) { + return `${name.slice(1).replace("/", "-")}-${version}.tgz`; + } + + const manifestBytes = readFileSync(manifestPath); + const manifestDigest = hash(manifestBytes, "sha256", "hex"); + if (!equal(manifestDigest, process.env.RELEASE_MANIFEST_DIGEST ?? "")) { + fail("prepared manifest digest does not match the preparation output"); + } + const manifest = JSON.parse(manifestBytes.toString("utf8")); + if ( + Object.keys(manifest).sort().join(",") !== + "gitCommit,packages,releaseTag,schemaVersion" || + manifest.schemaVersion !== 3 || + manifest.gitCommit !== process.env.RELEASE_COMMIT || + manifest.releaseTag !== process.env.RELEASE_TAG || + !Array.isArray(manifest.packages) || + manifest.packages.length !== packages.length + ) { + fail("prepared package manifest is invalid"); + } + + const expectedInventory = ["package-manifest.json"]; + const records = []; + for (let index = 0; index < packages.length; index += 1) { + const name = packages[index]; + const record = manifest.packages[index]; + if ( + Object.keys(record ?? {}).sort().join(",") !== + "exports,files,integrity,name,sha256,tarball,version" || + record.name !== name || + !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(record.version) || + manifest.releaseTag !== `v${record.version}` || + record.tarball !== expectedTarball(name, record.version) || + !/^[0-9a-f]{64}$/.test(record.sha256) || + !/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(record.integrity) || + !Array.isArray(record.exports) || + record.exports.length === 0 || + record.exports.some((entry) => typeof entry !== "string" || !entry.startsWith(".")) || + !Array.isArray(record.files) || + record.files.some( + (file) => + typeof file !== "object" || + file === null || + Object.keys(file).sort().join(",") !== "path,size" || + typeof file.path !== "string" || + !Number.isSafeInteger(file.size) || + file.size < 0, + ) + ) { + fail(`prepared package record is invalid for ${name}`); + } + const tarball = resolve(artifactDirectory, record.tarball); + if (dirname(tarball) !== artifactDirectory) { + fail("prepared tarball must be beside the package manifest"); + } + const details = lstatSync(tarball); + if (!details.isFile() || details.isSymbolicLink()) { + fail(`prepared tarball must be a regular file for ${name}`); + } + const bytes = readFileSync(tarball); + const sha256 = hash(bytes, "sha256", "hex"); + const integrity = `sha512-${hash(bytes, "sha512", "base64")}`; + if (!equal(sha256, record.sha256) || !equal(integrity, record.integrity)) { + fail(`prepared tarball has changed for ${name}`); + } + expectedInventory.push(record.tarball); + records.push({ ...record, tarball }); + } + + const entries = readdirSync(artifactDirectory, { withFileTypes: true }); + const actualInventory = entries.map(({ name }) => name).sort(); + expectedInventory.sort(); + if (JSON.stringify(actualInventory) !== JSON.stringify(expectedInventory)) { + fail("release artifact inventory does not match the package manifest"); + } + for (const entry of entries) { + const details = lstatSync(join(artifactDirectory, entry.name)); + if (!entry.isFile() || entry.isSymbolicLink() || !details.isFile()) { + fail(`release artifact entry must be a regular file: ${entry.name}`); + } + } + + const allowedNames = new Set([ + "PATH", + "HOME", + "USERPROFILE", + "SystemRoot", + "SYSTEMROOT", + "TEMP", + "TMP", + "TMPDIR", + "CI", + ]); + const npmRoot = mkdtempSync(join(process.env.RUNNER_TEMP, "release-npm-")); + const userConfig = join(npmRoot, "user.npmrc"); + const globalConfig = join(npmRoot, "global.npmrc"); + writeFileSync(userConfig, "", { mode: 0o600 }); + writeFileSync(globalConfig, "", { mode: 0o600 }); + chmodSync(userConfig, 0o600); + chmodSync(globalConfig, 0o600); + const npmEnv = {}; + for (const [name, value] of Object.entries(process.env)) { + if ( + value !== undefined && + (allowedNames.has(name) || + name.startsWith("GITHUB_") || + name.startsWith("ACTIONS_ID_TOKEN_") || + name.startsWith("RUNNER_")) + ) { + npmEnv[name] = value; + } + } + npmEnv.NPM_CONFIG_USERCONFIG = userConfig; + npmEnv.NPM_CONFIG_GLOBALCONFIG = globalConfig; + + function runNpm(arguments_, allowFailure = false) { + const cwd = mkdtempSync(join(npmRoot, "cwd-")); + const result = spawnSync("npm", arguments_, { + cwd, + env: npmEnv, + encoding: "utf8", + stdio: "pipe", + }); + if (result.error) throw result.error; + if (result.status !== 0 && !allowFailure) { + fail(`npm ${arguments_.join(" ")} failed: ${(result.stderr || result.stdout).trim()}`); + } + return result; + } + + function registryIntegrity(record) { + const result = runNpm( + [ + "view", + `${record.name}@${record.version}`, + "dist.integrity", + "--json", + "--registry", + registry, + ], + true, + ); + if (result.status === 0) { + const integrity = JSON.parse(result.stdout); + if (typeof integrity !== "string" || integrity.length === 0) { + fail(`${record.name}@${record.version} exists without dist.integrity`); + } + return integrity; + } + const output = `${result.stdout}\n${result.stderr}`; + if (/\bE404\b/.test(output)) return null; + fail(`npm registry lookup failed for ${record.name}@${record.version}`); + } + + function wait(milliseconds) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); + } + + try { + const npmVersion = runNpm(["--version"]).stdout.trim(); + const version = /^(\d+)\.(\d+)\.(\d+)/.exec(npmVersion); + if ( + version === null || + Number(version[1]) < 11 || + (Number(version[1]) === 11 && Number(version[2]) < 5) || + (Number(version[1]) === 11 && Number(version[2]) === 5 && Number(version[3]) < 1) + ) { + fail("trusted publishing requires npm 11.5.1 or newer"); + } + + for (const record of records) { + const existing = registryIntegrity(record); + if (existing !== null) { + if (!equal(existing, record.integrity)) { + fail(`${record.name}@${record.version} exists with different integrity`); + } + process.stdout.write(`Verified existing ${record.name}@${record.version}; skipping.\n`); + continue; + } + runNpm([ + "publish", + record.tarball, + "--access", + "public", + "--provenance", + "--ignore-scripts", + "--registry", + registry, + ]); + let confirmed = false; + for (let attempt = 0; attempt < 6; attempt += 1) { + const integrity = registryIntegrity(record); + if (integrity !== null && equal(integrity, record.integrity)) { + confirmed = true; + break; + } + if (attempt < 5) wait(2 ** attempt * 1_000); + } + if (!confirmed) { + fail(`${record.name}@${record.version} did not expose the prepared integrity`); + } + } + } finally { + rmSync(npmRoot, { recursive: true, force: true }); + } + NODE + chmod 0600 "${script_path}" + node "${script_path}" diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 0fc6bcf..c920628 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -40,24 +40,33 @@ After that pull request is merged, create a signed annotated tag at the exact create the GitHub release with `--verify-tag`. Do not let GitHub create the tag and never move or recreate a release tag. -The release workflow verifies that the tag: +Before checking out release source or running repository code, the workflow +authenticates the tag in a fresh bare repository and verifies that it: - is a stable annotated `vX.Y.Z` tag signed by an allowed signer; - matches a public package version in the release inventory; - points to the checkout and the GitHub release-event commit; and - is contained in `origin/main`. -Its preparation job has no OIDC permission. It enables Corepack for the -reviewed pnpm version, installs the reviewed `npm@11.18.0` used to pack and -talk to the registry, runs the full gate against `pnpm-lock.yaml` without -dependency caching, builds and packs once, smoke-tests the tarball from a -clean consumer, records its SHA-1 and SHA-512 integrity, and uploads the -exact prepared artifact. - -Only the `npm-publish` job receives `id-token: write`. It installs no -dependencies and does not download pnpm. It verifies the prepared manifest -and tarball hashes against the release commit, and publishes that tarball -with npm provenance. +Only after those checks does preparation check out the exact release-event +commit. Its preparation job has no OIDC permission. It enables Corepack for +the reviewed pnpm version, installs the reviewed `npm@11.18.0`, runs the full +gate against `pnpm-lock.yaml` without dependency caching, removes prior build +outputs, builds and packs once, records SHA-256 and SHA-512 values, enforces an +exact regular-file inventory, and uploads the sealed artifact immediately. + +A separate unprivileged smoke job downloads a copy, verifies the manifest +digest recorded by preparation, installs the tarballs in a clean consumer with +package scripts disabled, and imports every exported entry point. Registry +dependencies resolved by that consumer cannot change the artifact used for +publication. + +Only the `npm-publish` job receives `id-token: write`. It checks out no source, +installs no dependencies, and does not download pnpm. Workflow-owned logic +re-authenticates the tag in a temporary bare repository, verifies the sealed +manifest and exact artifact inventory, and publishes dependency-ordered +tarballs from fresh temporary working directories with npm provenance and +package scripts disabled. ## Safe retry diff --git a/packages/storage-azure-blob/src/index.test.ts b/packages/storage-azure-blob/src/index.test.ts index 03262ff..4992821 100644 --- a/packages/storage-azure-blob/src/index.test.ts +++ b/packages/storage-azure-blob/src/index.test.ts @@ -121,4 +121,20 @@ describe("createAzureBlobStore", () => { await expect(store.head("some-key")).resolves.toBeNull(); expect(createAttempts).toBe(2); }); + + it("rejects a block client outside the configured container", async () => { + const service = serviceClient(); + const container = service.getContainerClient(nextContainerName()); + const other = service.getContainerClient(nextContainerName()); + container.getBlockBlobClient = (key) => other.getBlockBlobClient(key); + + const store = createAzureBlobStore({ + containerClient: container, + createContainerIfMissing: false, + }); + + await expect(store.head("some-key")).rejects.toThrow( + "outside the configured container", + ); + }); }); diff --git a/packages/storage-azure-blob/src/index.ts b/packages/storage-azure-blob/src/index.ts index 53bb380..6ef3094 100644 --- a/packages/storage-azure-blob/src/index.ts +++ b/packages/storage-azure-blob/src/index.ts @@ -28,6 +28,7 @@ import { } from "@pegma/storage-blobs"; const AZURE_LIST_CURSOR_PREFIX = "pegma-azure-blob-list-v1:"; +const MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS = 10_000; export interface AzureBlobStoreOptions { /** @@ -99,6 +100,9 @@ function assertEtag(etag: string, label: string): void { if (typeof etag !== "string" || etag.length === 0) { throw new BlobValidationError(`${label} must be a non-empty string.`); } + if (etag.trim() === "*") { + throw new BlobValidationError(`${label} must not be a wildcard.`); + } } function copyBytes(source: Uint8Array): Uint8Array { @@ -119,8 +123,9 @@ async function readBody( } const reader = body.getReader(); - const chunks: Uint8Array[] = []; let total = 0; + let emptyChunksWithoutProgress = 0; + let bytes = new Uint8Array(0); try { while (true) { const { done, value } = await reader.read(); @@ -132,14 +137,42 @@ async function readBody( "Body stream chunks must be Uint8Array values.", ); } - total += value.byteLength; - if (total > limitBytes) { + if (value.byteLength === 0) { + emptyChunksWithoutProgress += 1; + if ( + emptyChunksWithoutProgress > MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS + ) { + void reader.cancel().catch(() => { + /* validation error wins */ + }); + throw new BlobValidationError( + "Body stream produced too many empty chunks without progress.", + ); + } + continue; + } + emptyChunksWithoutProgress = 0; + const nextTotal = total + value.byteLength; + if (nextTotal > limitBytes) { void reader.cancel().catch(() => { /* size error wins */ }); throw new BlobSizeLimitError(limitBytes); } - chunks.push(copyBytes(value)); + if (bytes.byteLength < nextTotal) { + const nextCapacity = Math.min( + limitBytes, + Math.max( + nextTotal, + bytes.byteLength === 0 ? 16 * 1_024 : bytes.byteLength * 2, + ), + ); + const grown = new Uint8Array(nextCapacity); + grown.set(bytes.subarray(0, total)); + bytes = grown; + } + bytes.set(value, total); + total = nextTotal; } } catch (error) { if ( @@ -153,19 +186,13 @@ async function readBody( }); } - if (chunks.length === 0) { + if (total === 0) { return new Uint8Array(0); } - if (chunks.length === 1) { - return chunks[0]!; + if (bytes.byteLength === total) { + return bytes; } - const bytes = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - return bytes; + return copyBytes(bytes.subarray(0, total)); } function nodeStreamToWeb( @@ -273,15 +300,18 @@ export function createAzureBlobStore( const createIfMissing = options.createContainerIfMissing !== false; const containerName = container.containerName; // Credential-free identity so SAS query strings never enter list cursors. - let endpoint = container.url; + let containerUrl: URL; try { - const parsed = new URL(container.url); - parsed.search = ""; - parsed.hash = ""; - endpoint = parsed.toString(); - } catch { - // Fall back to the raw URL if it is not absolute. + containerUrl = new URL(container.url); + } catch (error) { + throw new BlobValidationError("containerClient.url must be absolute.", { + cause: error, + }); } + containerUrl.search = ""; + containerUrl.hash = ""; + const endpoint = containerUrl.toString(); + const containerPathPrefix = `${containerUrl.pathname.replace(/\/$/u, "")}/`; const backendId = `${container.accountName ?? "account"}|${endpoint}|${containerName}`; let ensureContainer: Promise | undefined; @@ -303,6 +333,28 @@ export function createAzureBlobStore( await ensureContainer; } + function containedBlockBlobClient(key: string) { + const blob = container.getBlockBlobClient(key); + let blobUrl: URL; + try { + blobUrl = new URL(blob.url); + } catch (error) { + throw new BlobStoreError( + `Azure produced an invalid URL for ${JSON.stringify(key)}.`, + { cause: error }, + ); + } + if ( + blobUrl.origin !== containerUrl.origin || + !blobUrl.pathname.startsWith(containerPathPrefix) + ) { + throw new BlobStoreError( + `Azure produced a URL outside the configured container for ${JSON.stringify(key)}.`, + ); + } + return blob; + } + return { async put(key, body, putOptions) { assertValidBlobKey(key); @@ -332,7 +384,7 @@ export function createAzureBlobStore( const bytes = await readBody(body, limitBytes); await ready(); - const blob = container.getBlockBlobClient(key); + const blob = containedBlockBlobClient(key); const conditions = ifNoneMatch === "*" @@ -409,7 +461,7 @@ export function createAzureBlobStore( async get(key) { assertValidBlobKey(key); await ready(); - const blob = container.getBlockBlobClient(key); + const blob = containedBlockBlobClient(key); let download: BlobDownloadResponseParsed; try { download = await blob.download(0); @@ -452,7 +504,7 @@ export function createAzureBlobStore( async head(key) { assertValidBlobKey(key); await ready(); - const blob = container.getBlockBlobClient(key); + const blob = containedBlockBlobClient(key); try { const props = await blob.getProperties(); return toObjectInfo(key, { @@ -480,7 +532,7 @@ export function createAzureBlobStore( assertEtag(ifMatch, "ifMatch"); } await ready(); - const blob = container.getBlockBlobClient(key); + const blob = containedBlockBlobClient(key); try { await blob.delete( ifMatch === undefined ? undefined : { conditions: { ifMatch } }, diff --git a/packages/storage-blobs/src/conformance.ts b/packages/storage-blobs/src/conformance.ts index f9a166d..a32c28d 100644 --- a/packages/storage-blobs/src/conformance.ts +++ b/packages/storage-blobs/src/conformance.ts @@ -439,18 +439,34 @@ export const conformanceCases: readonly ConformanceCase[] = [ ); }), - testCase("rejects the exact keys . and ..", async (store) => { - for (const key of [".", ".."]) { - await assert.rejects( - () => store.put(key, textBytes("x")), - (error: unknown) => error instanceof BlobValidationError, - ); - await assert.rejects( - () => store.get(key), - (error: unknown) => error instanceof BlobValidationError, - ); - } - }), + testCase( + "rejects keys and prefixes with dot path segments", + async (store) => { + const keys = [".", "..", "./a", "../a", "a/./b", "a/../b", "a/.", "a/.."]; + for (const key of keys) { + await assert.rejects( + () => store.put(key, textBytes("x")), + (error: unknown) => error instanceof BlobValidationError, + ); + await assert.rejects( + () => store.get(key), + (error: unknown) => error instanceof BlobValidationError, + ); + await assert.rejects( + () => store.head(key), + (error: unknown) => error instanceof BlobValidationError, + ); + await assert.rejects( + () => store.delete(key), + (error: unknown) => error instanceof BlobValidationError, + ); + await assert.rejects( + () => store.list({ prefix: key, limit: 1 }), + (error: unknown) => error instanceof BlobValidationError, + ); + } + }, + ), testCase("rejects a key containing a control character", async (store) => { const key = `bad${String.fromCharCode(0)}key`; @@ -647,6 +663,41 @@ export const conformanceCases: readonly ConformanceCase[] = [ }, ), + testCase("put ignores empty stream chunks around data", async (store) => { + const chunks = [ + new Uint8Array(0), + textBytes("left"), + new Uint8Array(0), + new Uint8Array(0), + textBytes("-right"), + new Uint8Array(0), + ]; + const put = await store.put( + "streams/empty-chunks", + multiChunkStream(chunks), + ); + assert.equal(put.ok, true); + const got = await store.get("streams/empty-chunks"); + assert.ok(got); + assertBytesEqual(await readAll(got.body), textBytes("left-right")); + }), + + testCase("put rejects excessive empty stream chunks", async (store) => { + let reads = 0; + const stream = new ReadableStream({ + pull(controller) { + reads += 1; + controller.enqueue(new Uint8Array(0)); + }, + }); + await assert.rejects( + () => store.put("streams/no-progress", stream), + (error: unknown) => error instanceof BlobValidationError, + ); + assert.equal(reads > 10_000, true); + assert.equal(await store.head("streams/no-progress"), null); + }), + testCase( "put from a large multi-chunk stream preserves exact bytes", async (store) => { @@ -724,6 +775,19 @@ export const conformanceCases: readonly ConformanceCase[] = [ ); }), + testCase("rejects wildcard ifMatch values", async (store) => { + for (const ifMatch of ["*", " * "]) { + await assert.rejects( + () => store.put("cond/wildcard", textBytes("x"), { ifMatch }), + (error: unknown) => error instanceof BlobValidationError, + ); + await assert.rejects( + () => store.delete("cond/wildcard", { ifMatch }), + (error: unknown) => error instanceof BlobValidationError, + ); + } + }), + testCase("accepts a key at the maximum UTF-8 byte length", async (store) => { const key = "k".repeat(MAX_BLOB_KEY_BYTES); const put = await store.put(key, textBytes("edge")); diff --git a/packages/storage-blobs/src/index.ts b/packages/storage-blobs/src/index.ts index 7f9e05d..4a8f6a2 100644 --- a/packages/storage-blobs/src/index.ts +++ b/packages/storage-blobs/src/index.ts @@ -278,6 +278,7 @@ interface MemoryListCursor { } const textEncoder = new TextEncoder(); +const MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS = 10_000; function assertWellFormedUnicode(value: string, label: string): void { for (let index = 0; index < value.length; index += 1) { @@ -315,8 +316,7 @@ function hasDisallowedControl(value: string): boolean { } /** - * Shared character/length rules for keys and list prefixes (no exact-key - * exclusions such as `.` / `..`). + * Shared character/length rules for keys and list prefixes. */ function assertBlobPathString(value: string, label: string): void { if (typeof value !== "string" || value.length === 0) { @@ -334,12 +334,17 @@ function assertBlobPathString(value: string, label: string): void { ); } // Azure Blob rejects names with more than 254 path segments. - const segments = value.split("/").length; - if (segments > MAX_BLOB_KEY_SEGMENTS) { + const segments = value.split("/"); + if (segments.length > MAX_BLOB_KEY_SEGMENTS) { throw new BlobValidationError( `${label} may have at most ${MAX_BLOB_KEY_SEGMENTS} path segments.`, ); } + if (segments.some((segment) => segment === "." || segment === "..")) { + throw new BlobValidationError( + `${label} must not contain dot path segments.`, + ); + } } /** True when every code unit is a printable ASCII character (0x20–0x7E). */ @@ -381,23 +386,17 @@ function copyBytes(source: Uint8Array): Uint8Array { * can honour. * * Keys are non-empty, at most {@link MAX_BLOB_KEY_BYTES} UTF-8 bytes, free of - * C0 controls and DEL, well-formed Unicode, and must not be `.` or `..`. + * C0 controls and DEL, well-formed Unicode, and free of dot path segments. */ export function assertValidBlobKey(key: string): void { assertBlobPathString(key, "Blob key"); - if (key === "." || key === "..") { - throw new BlobValidationError( - `Blob key ${JSON.stringify(key)} is not allowed.`, - ); - } } /** * Validates a list prefix. Empty string means “no prefix” and is rejected here * so callers use `undefined` instead of `""`. * - * Unlike object keys, the exact strings `.` and `..` are allowed as prefixes - * so keys such as `.hidden` remain listable. + * A trailing slash is allowed, but `.` and `..` path segments are not. */ export function assertValidBlobPrefix(prefix: string): void { assertBlobPathString(prefix, "List prefix"); @@ -546,6 +545,9 @@ function assertEtag(etag: string, label: string): void { `${label} must not contain control characters.`, ); } + if (etag.trim() === "*") { + throw new BlobValidationError(`${label} must not be a wildcard.`); + } } function encodeMemoryListCursor(storeId: string, afterKey: string): string { @@ -602,8 +604,9 @@ async function readBody( } const reader = body.getReader(); - const chunks: Uint8Array[] = []; let total = 0; + let emptyChunksWithoutProgress = 0; + let bytes = new Uint8Array(0); try { while (true) { const { done, value } = await reader.read(); @@ -615,16 +618,44 @@ async function readBody( "Body stream chunks must be Uint8Array values.", ); } - total += value.byteLength; - if (total > limitBytes) { + if (value.byteLength === 0) { + emptyChunksWithoutProgress += 1; + if ( + emptyChunksWithoutProgress > MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS + ) { + void reader.cancel().catch(() => { + // Ignore cancel failures; validation is what the caller needs. + }); + throw new BlobValidationError( + "Body stream produced too many empty chunks without progress.", + ); + } + continue; + } + emptyChunksWithoutProgress = 0; + const nextTotal = total + value.byteLength; + if (nextTotal > limitBytes) { // Do not await cancel: a hung cancel hook must not block the size error. void reader.cancel().catch(() => { // Ignore cancel failures; the size error is what the caller needs. }); throw new BlobSizeLimitError(limitBytes); } + if (bytes.byteLength < nextTotal) { + const nextCapacity = Math.min( + limitBytes, + Math.max( + nextTotal, + bytes.byteLength === 0 ? 16 * 1_024 : bytes.byteLength * 2, + ), + ); + const grown = new Uint8Array(nextCapacity); + grown.set(bytes.subarray(0, total)); + bytes = grown; + } // Copy immediately: streams may reuse one scratch buffer for every chunk. - chunks.push(copyBytes(value)); + bytes.set(value, total); + total = nextTotal; } } catch (error) { if ( @@ -638,19 +669,13 @@ async function readBody( }); } - if (chunks.length === 0) { + if (total === 0) { return new Uint8Array(0); } - if (chunks.length === 1) { - return copyBytes(chunks[0]!); - } - const bytes = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; + if (bytes.byteLength === total) { + return bytes; } - return bytes; + return copyBytes(bytes.subarray(0, total)); } function bytesToStream(bytes: Uint8Array): ReadableStream { diff --git a/packages/storage-cloudflare-r2/src/index.ts b/packages/storage-cloudflare-r2/src/index.ts index df349ec..d40d76f 100644 --- a/packages/storage-cloudflare-r2/src/index.ts +++ b/packages/storage-cloudflare-r2/src/index.ts @@ -30,6 +30,7 @@ import { } from "@pegma/storage-blobs"; const R2_LIST_CURSOR_PREFIX = "pegma-cloudflare-r2-list-v1:"; +const MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS = 10_000; export interface CloudflareR2BlobStoreOptions { /** @@ -161,6 +162,9 @@ function assertEtag(etag: string, label: string): void { if (typeof etag !== "string" || etag.length === 0) { throw new BlobValidationError(`${label} must be a non-empty string.`); } + if (etag.trim() === "*") { + throw new BlobValidationError(`${label} must not be a wildcard.`); + } } function assertBucketName(bucket: string): void { @@ -187,8 +191,9 @@ async function readBody( } const reader = body.getReader(); - const chunks: Uint8Array[] = []; let total = 0; + let emptyChunksWithoutProgress = 0; + let bytes = new Uint8Array(0); try { while (true) { const { done, value } = await reader.read(); @@ -200,14 +205,42 @@ async function readBody( "Body stream chunks must be Uint8Array values.", ); } - total += value.byteLength; - if (total > limitBytes) { + if (value.byteLength === 0) { + emptyChunksWithoutProgress += 1; + if ( + emptyChunksWithoutProgress > MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS + ) { + void reader.cancel().catch(() => { + /* validation error wins */ + }); + throw new BlobValidationError( + "Body stream produced too many empty chunks without progress.", + ); + } + continue; + } + emptyChunksWithoutProgress = 0; + const nextTotal = total + value.byteLength; + if (nextTotal > limitBytes) { void reader.cancel().catch(() => { /* size error wins */ }); throw new BlobSizeLimitError(limitBytes); } - chunks.push(copyBytes(value)); + if (bytes.byteLength < nextTotal) { + const nextCapacity = Math.min( + limitBytes, + Math.max( + nextTotal, + bytes.byteLength === 0 ? 16 * 1_024 : bytes.byteLength * 2, + ), + ); + const grown = new Uint8Array(nextCapacity); + grown.set(bytes.subarray(0, total)); + bytes = grown; + } + bytes.set(value, total); + total = nextTotal; } } catch (error) { if ( @@ -221,19 +254,13 @@ async function readBody( }); } - if (chunks.length === 0) { + if (total === 0) { return new Uint8Array(0); } - if (chunks.length === 1) { - return chunks[0]!; + if (bytes.byteLength === total) { + return bytes; } - const bytes = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - return bytes; + return copyBytes(bytes.subarray(0, total)); } function encodeListCursor(backendId: string, continuation: string): string { @@ -474,22 +501,15 @@ export function createCloudflareR2BlobStore( input.IfMatch = ifMatch; } - const finishPut = async (response: { + const finishPut = (response: { ETag?: string | undefined; - }): Promise => { + }): PutResult => { bucketVerified = true; - const etag = response.ETag; - if (etag === undefined || etag.length === 0) { - // Some S3-compatible servers omit ETag on put; re-read via HEAD. - const head = await headRaw(key); - if (head === null) { - throw new BlobStoreError( - `R2 put returned no etag and object is missing for ${JSON.stringify(key)}.`, - ); - } - return { ok: true, etag: head.etag, size: bytes.byteLength }; - } - return { ok: true, etag, size: bytes.byteLength }; + return { + ok: true, + etag: requireEtag(response.ETag, key), + size: bytes.byteLength, + }; }; try { diff --git a/packages/storage-s3/src/index.ts b/packages/storage-s3/src/index.ts index a6648ec..d35cbbf 100644 --- a/packages/storage-s3/src/index.ts +++ b/packages/storage-s3/src/index.ts @@ -30,6 +30,7 @@ import { } from "@pegma/storage-blobs"; const S3_LIST_CURSOR_PREFIX = "pegma-s3-list-v1:"; +const MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS = 10_000; export interface S3BlobStoreOptions { /** @@ -162,6 +163,9 @@ function assertEtag(etag: string, label: string): void { if (typeof etag !== "string" || etag.length === 0) { throw new BlobValidationError(`${label} must be a non-empty string.`); } + if (etag.trim() === "*") { + throw new BlobValidationError(`${label} must not be a wildcard.`); + } } function assertBucketName(bucket: string): void { @@ -188,8 +192,9 @@ async function readBody( } const reader = body.getReader(); - const chunks: Uint8Array[] = []; let total = 0; + let emptyChunksWithoutProgress = 0; + let bytes = new Uint8Array(0); try { while (true) { const { done, value } = await reader.read(); @@ -201,14 +206,42 @@ async function readBody( "Body stream chunks must be Uint8Array values.", ); } - total += value.byteLength; - if (total > limitBytes) { + if (value.byteLength === 0) { + emptyChunksWithoutProgress += 1; + if ( + emptyChunksWithoutProgress > MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS + ) { + void reader.cancel().catch(() => { + /* validation error wins */ + }); + throw new BlobValidationError( + "Body stream produced too many empty chunks without progress.", + ); + } + continue; + } + emptyChunksWithoutProgress = 0; + const nextTotal = total + value.byteLength; + if (nextTotal > limitBytes) { void reader.cancel().catch(() => { /* size error wins */ }); throw new BlobSizeLimitError(limitBytes); } - chunks.push(copyBytes(value)); + if (bytes.byteLength < nextTotal) { + const nextCapacity = Math.min( + limitBytes, + Math.max( + nextTotal, + bytes.byteLength === 0 ? 16 * 1_024 : bytes.byteLength * 2, + ), + ); + const grown = new Uint8Array(nextCapacity); + grown.set(bytes.subarray(0, total)); + bytes = grown; + } + bytes.set(value, total); + total = nextTotal; } } catch (error) { if ( @@ -222,19 +255,13 @@ async function readBody( }); } - if (chunks.length === 0) { + if (total === 0) { return new Uint8Array(0); } - if (chunks.length === 1) { - return chunks[0]!; + if (bytes.byteLength === total) { + return bytes; } - const bytes = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - return bytes; + return copyBytes(bytes.subarray(0, total)); } function encodeListCursor(backendId: string, continuation: string): string { @@ -473,22 +500,15 @@ export function createS3BlobStore(options: S3BlobStoreOptions): BlobStore { input.IfMatch = ifMatch; } - const finishPut = async (response: { + const finishPut = (response: { ETag?: string | undefined; - }): Promise => { + }): PutResult => { bucketVerified = true; - const etag = response.ETag; - if (etag === undefined || etag.length === 0) { - // Some S3-compatible servers omit ETag on put; re-read via HEAD. - const head = await headRaw(key); - if (head === null) { - throw new BlobStoreError( - `S3 put returned no etag and object is missing for ${JSON.stringify(key)}.`, - ); - } - return { ok: true, etag: head.etag, size: bytes.byteLength }; - } - return { ok: true, etag, size: bytes.byteLength }; + return { + ok: true, + etag: requireEtag(response.ETag, key), + size: bytes.byteLength, + }; }; try { diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index c88352d..6091167 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -17,6 +17,7 @@ export interface ReleaseCommandOptions extends ValidationOptions { readonly manifest?: string; readonly output?: string; readonly expectedManifestDigest?: string; + readonly skipSmoke?: boolean; } export interface PublicPackageManifest { @@ -97,6 +98,10 @@ export function prepareRelease(options?: ReleaseCommandOptions): Promise<{ manifestDigest: string; }>; +export function smokePreparedRelease( + options?: ReleaseCommandOptions, +): Promise; + export function publishPreparedRelease( options?: ReleaseCommandOptions, ): Promise; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 2314509..150f7c8 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -1,7 +1,15 @@ import { spawnSync } from "node:child_process"; import { createHash, timingSafeEqual } from "node:crypto"; -import { existsSync } from "node:fs"; import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { + lstat, mkdtemp, mkdir, readFile, @@ -15,6 +23,7 @@ import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const REPOSITORY_URL = "git+https://github.com/pegma-dev/storage-blobs.git"; +const NPM_REGISTRY = "https://registry.npmjs.org/"; const REVIEWED_PNPM_VERSION = "10.34.5"; const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; @@ -121,8 +130,58 @@ export function resolveNpmCli() { ); } +function isolatedNpmEnvironment(directory) { + const allowed = new Set([ + "PATH", + "HOME", + "USERPROFILE", + "SystemRoot", + "SYSTEMROOT", + "TEMP", + "TMP", + "TMPDIR", + "CI", + "ComSpec", + "COMSPEC", + "PATHEXT", + "WINDIR", + ]); + const env = {}; + for (const [name, value] of Object.entries(process.env)) { + if ( + value !== undefined && + (allowed.has(name) || + name.startsWith("GITHUB_") || + name.startsWith("ACTIONS_ID_TOKEN_") || + name.startsWith("RUNNER_")) + ) { + env[name] = value; + } + } + const userConfig = join(directory, "user.npmrc"); + const globalConfig = join(directory, "global.npmrc"); + writeFileSync(userConfig, "", { mode: 0o600 }); + writeFileSync(globalConfig, "", { mode: 0o600 }); + chmodSync(userConfig, 0o600); + chmodSync(globalConfig, 0o600); + env.NPM_CONFIG_USERCONFIG = userConfig; + env.NPM_CONFIG_GLOBALCONFIG = globalConfig; + return env; +} + function runNpm(arguments_, options = {}) { - return run(process.execPath, [resolveNpmCli(), ...arguments_], options); + const directory = mkdtempSync(join(tmpdir(), "storage-blobs-npm-")); + try { + const cwd = options.freshCwd ? join(directory, "cwd") : options.cwd; + if (options.freshCwd) mkdirSync(cwd); + return run(process.execPath, [resolveNpmCli(), ...arguments_], { + ...options, + cwd, + env: isolatedNpmEnvironment(directory), + }); + } finally { + rmSync(directory, { recursive: true, force: true }); + } } function runPnpm(arguments_, options = {}) { @@ -138,11 +197,28 @@ function gitCommand() { function hashTarball(bytes) { return { + sha256: createHash("sha256").update(bytes).digest("hex"), shasum: createHash("sha1").update(bytes).digest("hex"), integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, }; } +function parsePackResult(output) { + for ( + let start = output.indexOf("["); + start !== -1; + start = output.indexOf("[", start + 1) + ) { + try { + const parsed = JSON.parse(output.slice(start)); + if (Array.isArray(parsed)) return parsed; + } catch { + // Lifecycle output may precede npm's JSON result. + } + } + fail("npm pack did not return a JSON result"); +} + export function digestManifest(bytes) { return createHash("sha256").update(bytes).digest("hex"); } @@ -182,12 +258,15 @@ export function validateReleaseTag(options = {}) { 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)) { + if ( + releaseTag === undefined || + !/^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$/u.test(releaseTag) + ) { fail("a stable release tag is required"); } if ( expectedReleaseCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedReleaseCommit) + !/^[0-9a-f]{40}$/u.test(expectedReleaseCommit) ) { fail("an exact release event commit is required"); } @@ -594,6 +673,50 @@ function verifyPackedFiles(manifest, files) { } } +function tarballName(name, version) { + return `${name.slice(1).replace("/", "-")}-${version}.tgz`; +} + +async function removeBuildState(directory) { + for (const entry of await readdir(directory, { withFileTypes: true })) { + const path = join(directory, entry.name); + if (entry.isDirectory()) { + if (entry.name !== "node_modules") await removeBuildState(path); + continue; + } + if (entry.isFile() && entry.name.endsWith(".tsbuildinfo")) { + await rm(path, { force: true }); + } + } +} + +async function cleanWorkspaceBuildOutputs(root) { + for (const { directory } of RELEASE_PACKAGES) { + const packageDirectory = join(root, "packages", directory); + await rm(join(packageDirectory, "dist"), { recursive: true, force: true }); + await removeBuildState(packageDirectory); + } +} + +async function assertReleaseInventory(directory, records) { + const expected = [ + "package-manifest.json", + ...records.map((record) => record.tarball), + ].sort(); + const entries = await readdir(directory, { withFileTypes: true }); + const actual = entries.map(({ name }) => name).sort(); + if (JSON.stringify(actual) !== JSON.stringify(expected)) { + fail("release output inventory does not match the prepared package list"); + } + for (const entry of entries) { + const path = join(directory, entry.name); + const details = await lstat(path); + if (!entry.isFile() || entry.isSymbolicLink() || !details.isFile()) { + fail(`release output entry must be a regular file: ${entry.name}`); + } + } +} + async function smokeTestTarball(tarball, manifest, siblingTarballs = []) { const directory = await mkdtemp( join(tmpdir(), "storage-blobs-release-smoke-"), @@ -617,7 +740,7 @@ async function smokeTestTarball(tarball, manifest, siblingTarballs = []) { ], { cwd: directory, capture: true }, ); - for (const key of Object.keys(manifest.exports)) { + for (const key of manifest.exports) { const specifier = key === "." ? manifest.name : `${manifest.name}${key.slice(1)}`; run( @@ -643,21 +766,31 @@ export async function prepareRelease(options = {}) { }).stdout.trim(); const output = resolve(root, options.output ?? ".release"); await mkdir(output, { recursive: true }); + const outputDetails = await lstat(output); + if (!outputDetails.isDirectory() || outputDetails.isSymbolicLink()) { + fail(`release output must be a regular directory: ${output}`); + } if ((await readdir(output)).length !== 0) { fail(`release output directory must be empty: ${output}`); } + await cleanWorkspaceBuildOutputs(root); runPnpm(["run", "build"], { cwd: root }); - // Pack every package before smoke tests so adapters can install sibling - // tarballs instead of fetching unpublished versions from the registry. const packedEntries = []; for (const entry of packages) { const result = runNpm( - ["pack", entry.packageDirectory, "--json", "--pack-destination", output], + [ + "pack", + entry.packageDirectory, + "--json", + "--silent", + "--pack-destination", + output, + ], { cwd: root, capture: true }, ); - const [packed] = JSON.parse(result.stdout); + const [packed] = parsePackResult(result.stdout); if ( packed?.name !== entry.manifest.name || packed?.version !== entry.manifest.version || @@ -682,16 +815,13 @@ export async function prepareRelease(options = {}) { const preparedPackages = []; for (const { entry, packed, tarballPath, hashes } of packedEntries) { - const siblings = packedEntries - .filter((candidate) => candidate.tarballPath !== tarballPath) - .map((candidate) => candidate.tarballPath); - await smokeTestTarball(tarballPath, entry.manifest, siblings); preparedPackages.push({ name: entry.manifest.name, version: entry.manifest.version, tarball: basename(tarballPath), + sha256: hashes.sha256, integrity: hashes.integrity, - shasum: hashes.shasum, + exports: Object.keys(entry.manifest.exports).sort(), files: packed.files .map(({ path, size }) => ({ path, size })) .sort((left, right) => left.path.localeCompare(right.path)), @@ -699,7 +829,7 @@ export async function prepareRelease(options = {}) { } const prepared = { - schemaVersion: 2, + schemaVersion: 3, gitCommit, releaseTag: releaseTag ?? null, packages: preparedPackages, @@ -710,6 +840,17 @@ export async function prepareRelease(options = {}) { "utf8", ); await writeFile(manifestPath, manifestBytes); + await assertReleaseInventory(output, preparedPackages); + + if (!options.skipSmoke) { + for (const record of preparedPackages) { + const tarballPath = join(output, record.tarball); + const siblings = preparedPackages + .filter((candidate) => candidate.tarball !== record.tarball) + .map((candidate) => join(output, candidate.tarball)); + await smokeTestTarball(tarballPath, record, siblings); + } + } return { manifestPath, manifest: prepared, @@ -717,12 +858,31 @@ export async function prepareRelease(options = {}) { }; } +export async function smokePreparedRelease(options = {}) { + const path = resolve(options.manifest ?? ".release/package-manifest.json"); + const prepared = await verifyPreparedManifest( + path, + options.expectedManifestDigest ?? process.env.RELEASE_MANIFEST_DIGEST, + ); + for (const record of prepared.packages) { + const tarballPath = join(dirname(path), record.tarball); + const siblings = prepared.packages + .filter((candidate) => candidate.tarball !== record.tarball) + .map((candidate) => join(dirname(path), candidate.tarball)); + await smokeTestTarball(tarballPath, record, siblings); + } +} + function queryRegistryIntegrity(name, version) { const spec = `${name}@${version}`; - const result = runNpm(["view", spec, "dist.integrity", "--json"], { - capture: true, - allowFailure: true, - }); + const result = runNpm( + ["view", spec, "dist.integrity", "--json", "--registry", NPM_REGISTRY], + { + capture: true, + allowFailure: true, + freshCwd: true, + }, + ); if (result.status === 0) { const integrity = JSON.parse(result.stdout); if (typeof integrity !== "string" || integrity.length === 0) { @@ -776,8 +936,13 @@ async function verifyPreparedManifest(path, expectedManifestDigest) { const prepared = JSON.parse(manifestBytes.toString("utf8")); const records = prepared.packages; if ( - prepared.schemaVersion !== 2 || - !/^[0-9a-f]{40,64}$/u.test(prepared.gitCommit) || + Object.keys(prepared).sort().join(",") !== + "gitCommit,packages,releaseTag,schemaVersion" || + prepared.schemaVersion !== 3 || + !/^[0-9a-f]{40}$/u.test(prepared.gitCommit) || + !/^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$/u.test( + prepared.releaseTag, + ) || !Array.isArray(records) || records.length !== RELEASE_PACKAGES.length ) { @@ -790,23 +955,31 @@ async function verifyPreparedManifest(path, expectedManifestDigest) { if (!safeEqual(currentCommit, prepared.gitCommit)) { fail("prepared package manifest commit does not match the checkout"); } + await assertReleaseInventory(dirname(path), records); for (let index = 0; index < RELEASE_PACKAGES.length; index += 1) { const definition = RELEASE_PACKAGES[index]; const record = records[index]; if ( + Object.keys(record ?? {}) + .sort() + .join(",") !== "exports,files,integrity,name,sha256,tarball,version" || prepared.releaseTag !== `v${record?.version}` || record?.name !== definition.name || !STABLE_SEMVER.test(record.version) || + !/^[0-9a-f]{64}$/u.test(record.sha256) || typeof record.integrity !== "string" || - typeof record.shasum !== "string" || + !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(record.integrity) || + !Array.isArray(record.exports) || + record.exports.length === 0 || + record.exports.some( + (entry) => typeof entry !== "string" || !entry.startsWith("."), + ) || !Array.isArray(record.files) ) { fail(`prepared package record is invalid for ${definition.name}`); } - const expectedTarball = `${definition.name - .slice(1) - .replace("/", "-")}-${record.version}.tgz`; + const expectedTarball = tarballName(definition.name, record.version); if (record.tarball !== expectedTarball) { fail(`prepared tarball name is invalid for ${definition.name}`); } @@ -816,8 +989,17 @@ async function verifyPreparedManifest(path, expectedManifestDigest) { } const hashes = hashTarball(await readFile(tarball)); if ( + !safeEqual(hashes.sha256, record.sha256) || !safeEqual(hashes.integrity, record.integrity) || - !safeEqual(hashes.shasum, record.shasum) + record.files.some( + (file) => + typeof file !== "object" || + file === null || + Object.keys(file).sort().join(",") !== "path,size" || + typeof file.path !== "string" || + !Number.isSafeInteger(file.size) || + file.size < 0, + ) ) { fail(`prepared tarball has changed for ${definition.name}`); } @@ -846,7 +1028,7 @@ export async function publishPreparedRelease(options = {}) { } if ( expectedCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedCommit) || + !/^[0-9a-f]{40}$/u.test(expectedCommit) || !safeEqual(expectedCommit, prepared.gitCommit) ) { fail("prepared package manifest must match the release event commit"); @@ -870,8 +1052,11 @@ export async function publishPreparedRelease(options = {}) { "--access", "public", "--provenance", + "--ignore-scripts", + "--registry", + NPM_REGISTRY, ], - { cwd: dirname(path) }, + { freshCwd: true }, ); confirmRegistryIntegrity(record); } @@ -894,6 +1079,10 @@ export function parseArguments(arguments_) { options.requireReleaseTag = true; continue; } + if (argument === "--skip-smoke") { + options.skipSmoke = true; + continue; + } const key = argument === "--root" ? "root" @@ -933,11 +1122,18 @@ async function main() { process.stdout.write(`Prepared manifest SHA-256 ${manifestDigest}.\n`); return; } + if (command === "smoke") { + await smokePreparedRelease(options); + process.stdout.write( + "Prepared release packages passed consumer smoke tests.\n", + ); + return; + } if (command === "publish") { await publishPreparedRelease(options); return; } - fail("usage: release-packages.mjs [options]"); + fail("usage: release-packages.mjs [options]"); } const isMain = diff --git a/test/localstack.ts b/test/localstack.ts index a25cbc3..e6c6e5f 100644 --- a/test/localstack.ts +++ b/test/localstack.ts @@ -20,7 +20,7 @@ export const LOCALSTACK_SECRET_KEY = "test"; export const LOCALSTACK_ENDPOINT = `http://127.0.0.1:${LOCALSTACK_PORT}`; const CONTAINER_NAME = `pegma-storage-blobs-localstack-${process.pid}`; -const IMAGE = "localstack/localstack:4.3"; +const IMAGE = "localstack/localstack:4.3.0"; let startedContainer = false; @@ -118,7 +118,7 @@ export async function setup(): Promise { "--name", CONTAINER_NAME, "-p", - `${LOCALSTACK_PORT}:4566`, + `127.0.0.1:${LOCALSTACK_PORT}:4566`, "-e", "SERVICES=s3", "-e", diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index a1898bc..5124906 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -43,6 +43,10 @@ describe("release package metadata", () => { }); }); + it("parses preparation without consumer smoke imports", () => { + expect(parseArguments(["--skip-smoke"])).toEqual({ skipSmoke: true }); + }); + it("parses the expected prepared manifest digest", () => { expect( parseArguments(["--expected-manifest-digest", "a".repeat(64)]), @@ -214,6 +218,15 @@ importers: }); describe("release source authentication", () => { + it("rejects release tags outside the stable package series", () => { + expect(() => + validateReleaseTag({ + releaseTag: "v0.0.1", + expectedReleaseCommit: "a".repeat(40), + }), + ).toThrow("stable release tag"); + }); + it("accepts only an approved signed annotated tag at the event commit", () => { const root = mkdtempSync(join(tmpdir(), "storage-blobs-release-tag-")); try { @@ -248,20 +261,20 @@ describe("release source authentication", () => { run(git, ["config", "user.signingkey", signingKey], root); run(git, ["config", "gpg.ssh.allowedSignersFile", allowedSigners], root); - run(git, ["tag", "--sign", "v0.0.0", "--message", "signed"], root); + run(git, ["tag", "--sign", "v0.1.0", "--message", "signed"], root); expect( validateReleaseTag({ root, - releaseTag: "v0.0.0", + releaseTag: "v0.1.0", expectedReleaseCommit: releaseCommit, }), - ).toEqual({ headCommit: releaseCommit, releaseTag: "v0.0.0" }); + ).toEqual({ headCommit: releaseCommit, releaseTag: "v0.1.0" }); - run(git, ["tag", "v0.0.1"], root); + run(git, ["tag", "v0.1.1"], root); expect(() => validateReleaseTag({ root, - releaseTag: "v0.0.1", + releaseTag: "v0.1.1", expectedReleaseCommit: releaseCommit, }), ).toThrow("annotated tag object"); @@ -273,7 +286,7 @@ describe("release source authentication", () => { "commit.gpgsign=false", "tag", "--annotate", - "v0.0.2", + "v0.1.2", "--message", "unsigned", ], @@ -282,7 +295,7 @@ describe("release source authentication", () => { expect(() => validateReleaseTag({ root, - releaseTag: "v0.0.2", + releaseTag: "v0.1.2", expectedReleaseCommit: releaseCommit, }), ).toThrow("not valid for an approved signer"); @@ -291,7 +304,7 @@ describe("release source authentication", () => { } }); - it("keeps preparation outside the OIDC-enabled publisher job", () => { + it("keeps preparation and consumer smoke outside the publisher job", () => { const workflow = readFileSync( join(process.cwd(), ".github", "workflows", "publish.yml"), "utf8", @@ -302,27 +315,38 @@ describe("release source authentication", () => { const header = workflow.slice(0, jobsIndex); const jobs = workflow.slice(jobsIndex + jobsMarker.length); const prepareStart = jobs.indexOf(" prepare:"); + const smokeStart = jobs.indexOf("\n smoke:"); const publishStart = jobs.indexOf("\n publish:"); expect(header).not.toContain("id-token: write"); expect(prepareStart).toBeGreaterThanOrEqual(0); - expect(publishStart).toBeGreaterThan(prepareStart); - const prepare = jobs.slice(prepareStart, publishStart); + expect(smokeStart).toBeGreaterThan(prepareStart); + expect(publishStart).toBeGreaterThan(smokeStart); + const prepare = jobs.slice(prepareStart, smokeStart); + const smoke = jobs.slice(smokeStart, publishStart); const publish = jobs.slice(publishStart); expect(prepare).not.toContain("id-token: write"); + expect(smoke).not.toContain("id-token: write"); expect(publish).toContain("id-token: write"); expect(publish).not.toContain("pnpm install"); expect(publish).not.toContain("npm ci"); expect(publish).not.toContain("npm install"); expect(publish).not.toContain("pnpm"); expect(publish).not.toContain("corepack"); - expect(publish).toContain("node scripts/release-packages.mjs publish"); + expect(publish).not.toContain("actions/checkout"); + expect(publish).not.toContain("scripts/release-packages.mjs"); + expect(publish).toContain( + 'script_path="${RUNNER_TEMP}/publish-release.mjs"', + ); + expect(prepare).toContain("--skip-smoke"); + expect(prepare).toContain("include-hidden-files: false"); + expect(smoke).toContain("release-packages.mjs smoke"); expect(workflow).not.toContain("workflow_dispatch"); expect(workflow).toContain("retention-days: 30"); }); }); describe("prepared manifest anchoring", () => { - const manifestBytes = '{"schemaVersion":2}\n'; + const manifestBytes = '{"schemaVersion":3}\n'; const digest = digestManifest(manifestBytes); it("accepts the digest recorded by the preparation job", () => { @@ -335,7 +359,7 @@ describe("prepared manifest anchoring", () => { it("rejects a manifest replaced alongside its tarballs", () => { expect(() => - verifyManifestDigest('{"schemaVersion":2} \n', digest), + verifyManifestDigest('{"schemaVersion":3} \n', digest), ).toThrow("does not match the digest recorded by the preparation job"); }); @@ -364,10 +388,12 @@ describe("prepared manifest anchoring", () => { expect(jobsIndex).toBeGreaterThanOrEqual(0); const jobs = workflow.slice(jobsIndex + jobsMarker.length); const prepareStart = jobs.indexOf(" prepare:"); + const smokeStart = jobs.indexOf("\n smoke:"); const publishStart = jobs.indexOf("\n publish:"); expect(prepareStart).toBeGreaterThanOrEqual(0); + expect(smokeStart).toBeGreaterThan(prepareStart); expect(publishStart).toBeGreaterThan(prepareStart); - const prepare = jobs.slice(prepareStart, publishStart); + const prepare = jobs.slice(prepareStart, smokeStart); const publish = jobs.slice(publishStart); expect(prepare).toContain( "manifest-digest: ${{ steps.manifest.outputs.digest }}", @@ -375,7 +401,10 @@ describe("prepared manifest anchoring", () => { expect(publish).toContain( "RELEASE_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }}", ); - expect(publish).toContain("--expected-manifest-digest"); + expect(publish).toContain("RELEASE_MANIFEST_DIGEST"); + expect(prepare).toContain( + "artifact-digest: ${{ steps.upload.outputs.artifact-digest }}", + ); }); }); From df7641a63344e05c9e4d619db6716fd157d93c27 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 14:39:58 -0500 Subject: [PATCH 2/6] Refresh repository checks From a50ee41f614dbd0781a645fdb652035395c57684 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 14:52:34 -0500 Subject: [PATCH 3/6] Align release checks and adapter coverage --- .github/workflows/publish.yml | 14 +++--- docs/RELEASING.md | 12 ++--- packages/storage-azure-blob/src/index.ts | 2 +- packages/storage-blobs/README.md | 6 +++ packages/storage-blobs/src/conformance.ts | 3 +- packages/storage-blobs/src/index.ts | 4 +- .../storage-cloudflare-r2/src/index.test.ts | 33 ++++++++++++- packages/storage-cloudflare-r2/src/index.ts | 2 +- packages/storage-s3/src/index.test.ts | 33 ++++++++++++- packages/storage-s3/src/index.ts | 2 +- scripts/release-packages.d.mts | 6 +++ scripts/release-packages.mjs | 22 ++++----- tests/release-packages.test.ts | 49 +++++++++++++++++-- 13 files changed, 152 insertions(+), 36 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 77e2bba..f195031 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -388,6 +388,10 @@ jobs: "TMP", "TMPDIR", "CI", + "ComSpec", + "COMSPEC", + "PATHEXT", + "WINDIR", ]); const npmRoot = mkdtempSync(join(process.env.RUNNER_TEMP, "release-npm-")); const userConfig = join(npmRoot, "user.npmrc"); @@ -456,14 +460,8 @@ jobs: try { const npmVersion = runNpm(["--version"]).stdout.trim(); - const version = /^(\d+)\.(\d+)\.(\d+)/.exec(npmVersion); - if ( - version === null || - Number(version[1]) < 11 || - (Number(version[1]) === 11 && Number(version[2]) < 5) || - (Number(version[1]) === 11 && Number(version[2]) === 5 && Number(version[3]) < 1) - ) { - fail("trusted publishing requires npm 11.5.1 or newer"); + if (npmVersion !== "11.18.0") { + fail("publication requires npm 11.18.0"); } for (const record of records) { diff --git a/docs/RELEASING.md b/docs/RELEASING.md index c920628..429e779 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -44,16 +44,16 @@ Before checking out release source or running repository code, the workflow authenticates the tag in a fresh bare repository and verifies that it: - is a stable annotated `vX.Y.Z` tag signed by an allowed signer; -- matches a public package version in the release inventory; - points to the checkout and the GitHub release-event commit; and - is contained in `origin/main`. Only after those checks does preparation check out the exact release-event -commit. Its preparation job has no OIDC permission. It enables Corepack for -the reviewed pnpm version, installs the reviewed `npm@11.18.0`, runs the full -gate against `pnpm-lock.yaml` without dependency caching, removes prior build -outputs, builds and packs once, records SHA-256 and SHA-512 values, enforces an -exact regular-file inventory, and uploads the sealed artifact immediately. +commit and confirm that the tag matches the shared public package version. Its +preparation job has no OIDC permission. It enables Corepack for the reviewed +pnpm version, installs the reviewed `npm@11.18.0`, runs the full gate against +`pnpm-lock.yaml` without dependency caching, removes prior build outputs, +builds and packs once, records SHA-256 and SHA-512 values, enforces an exact +regular-file inventory, and uploads the sealed artifact immediately. A separate unprivileged smoke job downloads a copy, verifies the manifest digest recorded by preparation, installs the tarballs in a clean consumer with diff --git a/packages/storage-azure-blob/src/index.ts b/packages/storage-azure-blob/src/index.ts index 6ef3094..987be44 100644 --- a/packages/storage-azure-blob/src/index.ts +++ b/packages/storage-azure-blob/src/index.ts @@ -10,6 +10,7 @@ import { BlobValidationError, DEFAULT_CONTENT_TYPE, DEFAULT_MAX_OBJECT_BYTES, + MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS, assertValidBlobKey, assertValidBlobPrefix, assertValidCacheControl, @@ -28,7 +29,6 @@ import { } from "@pegma/storage-blobs"; const AZURE_LIST_CURSOR_PREFIX = "pegma-azure-blob-list-v1:"; -const MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS = 10_000; export interface AzureBlobStoreOptions { /** diff --git a/packages/storage-blobs/README.md b/packages/storage-blobs/README.md index f854d35..122c622 100644 --- a/packages/storage-blobs/README.md +++ b/packages/storage-blobs/README.md @@ -64,6 +64,12 @@ Expected races return a result, not an exception: Infrastructure failures still throw (`BlobStoreError` and subclasses). +### Keys and prefixes + +Keys and list prefixes use `/`-delimited segments. A segment equal to `.` or +`..` is rejected; dot-prefixed names such as `.hidden` and `.well-known` remain +valid. A trailing slash is valid for prefixes such as `support-desk/`. + ### Listing for GC ```ts diff --git a/packages/storage-blobs/src/conformance.ts b/packages/storage-blobs/src/conformance.ts index a32c28d..4a91711 100644 --- a/packages/storage-blobs/src/conformance.ts +++ b/packages/storage-blobs/src/conformance.ts @@ -7,6 +7,7 @@ import { MAX_BLOB_KEY_BYTES, MAX_BLOB_KEY_SEGMENTS, MAX_CACHE_CONTROL_BYTES, + MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS, MAX_LIST_PAGE_SIZE, MAX_USER_METADATA_TOTAL_BYTES, type BlobStore, @@ -694,7 +695,7 @@ export const conformanceCases: readonly ConformanceCase[] = [ () => store.put("streams/no-progress", stream), (error: unknown) => error instanceof BlobValidationError, ); - assert.equal(reads > 10_000, true); + assert.equal(reads > MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS, true); assert.equal(await store.head("streams/no-progress"), null); }), diff --git a/packages/storage-blobs/src/index.ts b/packages/storage-blobs/src/index.ts index 4a8f6a2..59f1606 100644 --- a/packages/storage-blobs/src/index.ts +++ b/packages/storage-blobs/src/index.ts @@ -18,6 +18,9 @@ export const MAX_LIST_PAGE_SIZE = 1_000; */ export const DEFAULT_MAX_OBJECT_BYTES = 64 * 1_024 * 1_024; +/** Maximum consecutive empty stream chunks accepted without byte progress. */ +export const MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS = 10_000; + /** Maximum number of user-metadata entries on one object. */ export const MAX_USER_METADATA_ENTRIES = 16; @@ -278,7 +281,6 @@ interface MemoryListCursor { } const textEncoder = new TextEncoder(); -const MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS = 10_000; function assertWellFormedUnicode(value: string, label: string): void { for (let index = 0; index < value.length; index += 1) { diff --git a/packages/storage-cloudflare-r2/src/index.test.ts b/packages/storage-cloudflare-r2/src/index.test.ts index f44aab9..5215aa2 100644 --- a/packages/storage-cloudflare-r2/src/index.test.ts +++ b/packages/storage-cloudflare-r2/src/index.test.ts @@ -11,7 +11,7 @@ import { dualStoreConformanceCases, sizeLimitConformanceCases, } from "@pegma/storage-blobs/conformance"; -import { afterAll, describe, it } from "vitest"; +import { afterAll, describe, expect, it } from "vitest"; import { LOCALSTACK_ACCESS_KEY, @@ -181,6 +181,37 @@ describe("createCloudflareR2BlobStore", () => { }); } + it("rejects a write response without an etag", async () => { + const name = nextBucketName(); + await ensureEmptyBucket(name); + const client = serviceClient(); + client.middlewareStack.add( + (next, context) => async (arguments_) => { + const result = await next(arguments_); + if (context.commandName === "PutObjectCommand") { + delete (result.output as { ETag?: string }).ETag; + } + return result; + }, + { name: "omitPutEtag", step: "deserialize" }, + ); + const store = createCloudflareR2BlobStore({ + client, + bucket: name, + endpoint: HARNESS_ENDPOINT, + }); + try { + await expect( + store.put("response/without-etag", new Uint8Array([1])), + ).rejects.toThrow("R2 put failed"); + await expect(store.head("response/without-etag")).resolves.toMatchObject({ + size: 1, + }); + } finally { + client.destroy(); + } + }); + for (const testCase of dualStoreConformanceCases) { it(testCase.name, async () => { const a = await freshSharedBackend(); diff --git a/packages/storage-cloudflare-r2/src/index.ts b/packages/storage-cloudflare-r2/src/index.ts index d40d76f..ead6cd5 100644 --- a/packages/storage-cloudflare-r2/src/index.ts +++ b/packages/storage-cloudflare-r2/src/index.ts @@ -13,6 +13,7 @@ import { BlobValidationError, DEFAULT_CONTENT_TYPE, DEFAULT_MAX_OBJECT_BYTES, + MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS, assertValidBlobKey, assertValidBlobPrefix, assertValidCacheControl, @@ -30,7 +31,6 @@ import { } from "@pegma/storage-blobs"; const R2_LIST_CURSOR_PREFIX = "pegma-cloudflare-r2-list-v1:"; -const MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS = 10_000; export interface CloudflareR2BlobStoreOptions { /** diff --git a/packages/storage-s3/src/index.test.ts b/packages/storage-s3/src/index.test.ts index 9e689ab..b2c86ed 100644 --- a/packages/storage-s3/src/index.test.ts +++ b/packages/storage-s3/src/index.test.ts @@ -11,7 +11,7 @@ import { dualStoreConformanceCases, sizeLimitConformanceCases, } from "@pegma/storage-blobs/conformance"; -import { afterAll, describe, it } from "vitest"; +import { afterAll, describe, expect, it } from "vitest"; import { LOCALSTACK_ACCESS_KEY, @@ -181,6 +181,37 @@ describe("createS3BlobStore", () => { }); } + it("rejects a write response without an etag", async () => { + const name = nextBucketName(); + await ensureEmptyBucket(name); + const client = serviceClient(); + client.middlewareStack.add( + (next, context) => async (arguments_) => { + const result = await next(arguments_); + if (context.commandName === "PutObjectCommand") { + delete (result.output as { ETag?: string }).ETag; + } + return result; + }, + { name: "omitPutEtag", step: "deserialize" }, + ); + const store = createS3BlobStore({ + client, + bucket: name, + endpoint: HARNESS_ENDPOINT, + }); + try { + await expect( + store.put("response/without-etag", new Uint8Array([1])), + ).rejects.toThrow("S3 put failed"); + await expect(store.head("response/without-etag")).resolves.toMatchObject({ + size: 1, + }); + } finally { + client.destroy(); + } + }); + for (const testCase of dualStoreConformanceCases) { it(testCase.name, async () => { const a = await freshSharedBackend(); diff --git a/packages/storage-s3/src/index.ts b/packages/storage-s3/src/index.ts index d35cbbf..5777b0e 100644 --- a/packages/storage-s3/src/index.ts +++ b/packages/storage-s3/src/index.ts @@ -13,6 +13,7 @@ import { BlobValidationError, DEFAULT_CONTENT_TYPE, DEFAULT_MAX_OBJECT_BYTES, + MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS, assertValidBlobKey, assertValidBlobPrefix, assertValidCacheControl, @@ -30,7 +31,6 @@ import { } from "@pegma/storage-blobs"; const S3_LIST_CURSOR_PREFIX = "pegma-s3-list-v1:"; -const MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS = 10_000; export interface S3BlobStoreOptions { /** diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index 6091167..3fd9f2a 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -35,10 +35,16 @@ export interface ValidationResult { export const RELEASE_PACKAGES: readonly ReleasePackageDefinition[]; +export const RELEASE_MANIFEST_SCHEMA_VERSION: number; + export const REVIEWED_PNPM: { readonly version: string; }; +export const REVIEWED_NPM: { + readonly version: string; +}; + export function resolveNpmCli(): string; export function lockfileImporterBlock( diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 150f7c8..811d17d 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -24,6 +24,7 @@ import { fileURLToPath } from "node:url"; const REPOSITORY_URL = "git+https://github.com/pegma-dev/storage-blobs.git"; const NPM_REGISTRY = "https://registry.npmjs.org/"; +const REVIEWED_NPM_VERSION = "11.18.0"; const REVIEWED_PNPM_VERSION = "10.34.5"; const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; @@ -32,6 +33,10 @@ export const REVIEWED_PNPM = { version: REVIEWED_PNPM_VERSION, }; +export const REVIEWED_NPM = { + version: REVIEWED_NPM_VERSION, +}; + export const RELEASE_PACKAGES = [ { directory: "storage-blobs", @@ -51,6 +56,8 @@ export const RELEASE_PACKAGES = [ }, ]; +export const RELEASE_MANIFEST_SCHEMA_VERSION = 3; + function fail(message) { throw new Error(message); } @@ -829,7 +836,7 @@ export async function prepareRelease(options = {}) { } const prepared = { - schemaVersion: 3, + schemaVersion: RELEASE_MANIFEST_SCHEMA_VERSION, gitCommit, releaseTag: releaseTag ?? null, packages: preparedPackages, @@ -903,15 +910,8 @@ export function decidePublication(localIntegrity, registryIntegrity) { 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"); + if (version !== REVIEWED_NPM_VERSION) { + fail(`publication requires npm ${REVIEWED_NPM_VERSION}`); } } @@ -938,7 +938,7 @@ async function verifyPreparedManifest(path, expectedManifestDigest) { if ( Object.keys(prepared).sort().join(",") !== "gitCommit,packages,releaseTag,schemaVersion" || - prepared.schemaVersion !== 3 || + prepared.schemaVersion !== RELEASE_MANIFEST_SCHEMA_VERSION || !/^[0-9a-f]{40}$/u.test(prepared.gitCommit) || !/^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$/u.test( prepared.releaseTag, diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 5124906..9df9117 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -5,6 +5,8 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { RELEASE_PACKAGES, + RELEASE_MANIFEST_SCHEMA_VERSION, + REVIEWED_NPM, REVIEWED_PNPM, assertPnpmLockfileSynchronized, decidePublication, @@ -65,6 +67,40 @@ describe("release package metadata", () => { ]); }); + it("keeps workflow-owned publication constants aligned", () => { + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", + ); + const packageBlock = /const packages = \[([\s\S]*?)\];/u.exec( + workflow, + )?.[1]; + expect(packageBlock).toBeDefined(); + const workflowPackages = [ + ...(packageBlock ?? "").matchAll(/"(@pegma\/[^"]+)"/gu), + ].map((match) => match[1]); + expect(workflowPackages).toEqual(RELEASE_PACKAGES.map(({ name }) => name)); + + const schemaVersion = /manifest\.schemaVersion !== (\d+)/u.exec( + workflow, + )?.[1]; + expect(schemaVersion).toBe(String(RELEASE_MANIFEST_SCHEMA_VERSION)); + expect(workflow).toContain(`npmVersion !== "${REVIEWED_NPM.version}"`); + for (const name of ["ComSpec", "COMSPEC", "PATHEXT", "WINDIR"]) { + expect(workflow).toContain(`"${name}"`); + } + + const tagPatterns = [ + ...workflow.matchAll( + /if \[\[ ! "\$\{RELEASE_TAG\}" =~ ([^ ]+) \]\]; then/gu, + ), + ].map((match) => match[1]); + expect(tagPatterns).toHaveLength(2); + expect(new Set(tagPatterns).size).toBe(1); + expect(workflow.match(/verify-tag/gu)).toHaveLength(2); + expect(workflow.match(/merge-base --is-ancestor/gu)).toHaveLength(2); + }); + it("validates package manifests and the lockfile together", async () => { await expect(validateRepository()).resolves.toBeDefined(); const rootManifest = JSON.parse( @@ -346,7 +382,9 @@ describe("release source authentication", () => { }); describe("prepared manifest anchoring", () => { - const manifestBytes = '{"schemaVersion":3}\n'; + const manifestBytes = `${JSON.stringify({ + schemaVersion: RELEASE_MANIFEST_SCHEMA_VERSION, + })}\n`; const digest = digestManifest(manifestBytes); it("accepts the digest recorded by the preparation job", () => { @@ -358,9 +396,12 @@ describe("prepared manifest anchoring", () => { }); it("rejects a manifest replaced alongside its tarballs", () => { - expect(() => - verifyManifestDigest('{"schemaVersion":3} \n', digest), - ).toThrow("does not match the digest recorded by the preparation job"); + const replacement = `${JSON.stringify({ + schemaVersion: RELEASE_MANIFEST_SCHEMA_VERSION, + })} \n`; + expect(() => verifyManifestDigest(replacement, digest)).toThrow( + "does not match the digest recorded by the preparation job", + ); }); it("refuses to publish without a usable expected digest", () => { From cac25fd08292f1cfa51a2f35e4121a4658e7787a Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 14:54:04 -0500 Subject: [PATCH 4/6] Clarify adapter and release rules --- docs/ADAPTER_AUTHORING.md | 8 +++++--- docs/RELEASING.md | 4 +++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/ADAPTER_AUTHORING.md b/docs/ADAPTER_AUTHORING.md index e5627e9..f84f281 100644 --- a/docs/ADAPTER_AUTHORING.md +++ b/docs/ADAPTER_AUTHORING.md @@ -139,9 +139,11 @@ describe("my adapter", () => { 2. **Conditionals.** Prefer native `If-Match` / `If-None-Match` (or SDK equivalents). Map precondition failures to `{ ok: false, reason }` — do not throw for expected races. -3. **Etags.** Opaque strings; pass them through. Never invent etag semantics - components can parse (for example, requiring a quoted form unless every - backend uses it — they do not). +3. **Etags.** Opaque provider-issued strings pass through unchanged. Reject + `"*"` (including surrounding whitespace) for `ifMatch`; the wildcard is + reserved for create-only `ifNoneMatch: "*"`. Never invent other etag + semantics components can parse (for example, requiring a quoted form unless + every backend uses it — they do not). 4. **Streaming.** Accept `ReadableStream` and `Uint8Array`. When the provider needs multipart under the hood, hide that inside `put`. 5. **Oversize.** Enforce the configured ceiling. Cancelling a remaining body diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 429e779..5a08184 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -43,7 +43,9 @@ and never move or recreate a release tag. Before checking out release source or running repository code, the workflow authenticates the tag in a fresh bare repository and verifies that it: -- is a stable annotated `vX.Y.Z` tag signed by an allowed signer; +- is a signed annotated tag in the stable package series (`v0.MINOR.PATCH` + with `MINOR >= 1`, or `vMAJOR.MINOR.PATCH` with `MAJOR >= 1`; `v0.0.x` is + not a release tag); - points to the checkout and the GitHub release-event commit; and - is contained in `origin/main`. From 822f803a2764f0ca0b6b63a93275f023c82058bd Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 15:16:19 -0500 Subject: [PATCH 5/6] Align shared validation and release upload --- .github/workflows/publish.yml | 12 ++- packages/storage-azure-blob/src/index.ts | 109 +------------------- packages/storage-blobs/README.md | 4 +- packages/storage-blobs/src/conformance.ts | 12 +++ packages/storage-blobs/src/index.ts | 12 ++- packages/storage-cloudflare-r2/src/index.ts | 103 +----------------- packages/storage-s3/src/index.ts | 103 +----------------- scripts/release-packages.mjs | 4 +- tests/release-packages.test.ts | 2 + 9 files changed, 51 insertions(+), 310 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index f195031..43f8474 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -118,6 +118,11 @@ jobs: set -euo pipefail digest="$(sha256sum .release/package-manifest.json | cut -d ' ' -f 1)" printf 'digest=%s\n' "${digest}" >> "${GITHUB_OUTPUT}" + { + printf 'files<> "${GITHUB_OUTPUT}" printf 'Prepared manifest SHA-256 %s\n' "${digest}" >> "${GITHUB_STEP_SUMMARY}" - name: Upload the sealed release @@ -125,7 +130,7 @@ jobs: uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: name: storage-blobs-release-${{ github.run_id }} - path: .release/ + path: ${{ steps.manifest.outputs.files }} if-no-files-found: error include-hidden-files: false overwrite: true @@ -143,7 +148,6 @@ jobs: contents: read env: CI: "1" - RELEASE_COMMIT: ${{ github.sha }} RELEASE_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }} steps: @@ -369,7 +373,9 @@ jobs: const actualInventory = entries.map(({ name }) => name).sort(); expectedInventory.sort(); if (JSON.stringify(actualInventory) !== JSON.stringify(expectedInventory)) { - fail("release artifact inventory does not match the package manifest"); + fail( + `release artifact inventory mismatch: expected ${JSON.stringify(expectedInventory)}; received ${JSON.stringify(actualInventory)}`, + ); } for (const entry of entries) { const details = lstatSync(join(artifactDirectory, entry.name)); diff --git a/packages/storage-azure-blob/src/index.ts b/packages/storage-azure-blob/src/index.ts index 987be44..7303c26 100644 --- a/packages/storage-azure-blob/src/index.ts +++ b/packages/storage-azure-blob/src/index.ts @@ -5,17 +5,17 @@ import type { ContainerClient, } from "@azure/storage-blob"; import { - BlobSizeLimitError, BlobStoreError, BlobValidationError, DEFAULT_CONTENT_TYPE, DEFAULT_MAX_OBJECT_BYTES, - MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS, + assertValidEtag, assertValidBlobKey, assertValidBlobPrefix, assertValidCacheControl, assertValidContentType, normalizeUserMetadata, + readBlobBody, type BlobGetResult, type BlobListPage, type BlobObjectInfo, @@ -96,105 +96,6 @@ function assertMaxBytes( return maxBytes; } -function assertEtag(etag: string, label: string): void { - if (typeof etag !== "string" || etag.length === 0) { - throw new BlobValidationError(`${label} must be a non-empty string.`); - } - if (etag.trim() === "*") { - throw new BlobValidationError(`${label} must not be a wildcard.`); - } -} - -function copyBytes(source: Uint8Array): Uint8Array { - const copy = new Uint8Array(source.byteLength); - copy.set(source); - return copy; -} - -async function readBody( - body: ReadableStream | Uint8Array, - limitBytes: number, -): Promise { - if (body instanceof Uint8Array) { - if (body.byteLength > limitBytes) { - throw new BlobSizeLimitError(limitBytes); - } - return copyBytes(body); - } - - const reader = body.getReader(); - let total = 0; - let emptyChunksWithoutProgress = 0; - let bytes = new Uint8Array(0); - try { - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - if (!(value instanceof Uint8Array)) { - throw new BlobValidationError( - "Body stream chunks must be Uint8Array values.", - ); - } - if (value.byteLength === 0) { - emptyChunksWithoutProgress += 1; - if ( - emptyChunksWithoutProgress > MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS - ) { - void reader.cancel().catch(() => { - /* validation error wins */ - }); - throw new BlobValidationError( - "Body stream produced too many empty chunks without progress.", - ); - } - continue; - } - emptyChunksWithoutProgress = 0; - const nextTotal = total + value.byteLength; - if (nextTotal > limitBytes) { - void reader.cancel().catch(() => { - /* size error wins */ - }); - throw new BlobSizeLimitError(limitBytes); - } - if (bytes.byteLength < nextTotal) { - const nextCapacity = Math.min( - limitBytes, - Math.max( - nextTotal, - bytes.byteLength === 0 ? 16 * 1_024 : bytes.byteLength * 2, - ), - ); - const grown = new Uint8Array(nextCapacity); - grown.set(bytes.subarray(0, total)); - bytes = grown; - } - bytes.set(value, total); - total = nextTotal; - } - } catch (error) { - if ( - error instanceof BlobSizeLimitError || - error instanceof BlobValidationError - ) { - throw error; - } - throw new BlobStoreError("Failed to read object body stream.", { - cause: error, - }); - } - - if (total === 0) { - return new Uint8Array(0); - } - if (bytes.byteLength === total) { - return bytes; - } - return copyBytes(bytes.subarray(0, total)); -} - function nodeStreamToWeb( nodeStream: NodeJS.ReadableStream, ): ReadableStream { @@ -369,7 +270,7 @@ export function createAzureBlobStore( throw new BlobValidationError('ifNoneMatch must be the literal "*".'); } if (ifMatch !== undefined) { - assertEtag(ifMatch, "ifMatch"); + assertValidEtag(ifMatch, "ifMatch"); } const contentType = assertValidContentType( @@ -381,7 +282,7 @@ export function createAzureBlobStore( : assertValidCacheControl(putOptions.cacheControl); const userMetadata = normalizeUserMetadata(putOptions?.userMetadata); const limitBytes = assertMaxBytes(putOptions?.maxBytes, maxObjectBytes); - const bytes = await readBody(body, limitBytes); + const bytes = await readBlobBody(body, limitBytes); await ready(); const blob = containedBlockBlobClient(key); @@ -529,7 +430,7 @@ export function createAzureBlobStore( assertValidBlobKey(key); const ifMatch = deleteOptions?.ifMatch; if (ifMatch !== undefined) { - assertEtag(ifMatch, "ifMatch"); + assertValidEtag(ifMatch, "ifMatch"); } await ready(); const blob = containedBlockBlobClient(key); diff --git a/packages/storage-blobs/README.md b/packages/storage-blobs/README.md index 122c622..5d229ca 100644 --- a/packages/storage-blobs/README.md +++ b/packages/storage-blobs/README.md @@ -68,7 +68,9 @@ Infrastructure failures still throw (`BlobStoreError` and subclasses). Keys and list prefixes use `/`-delimited segments. A segment equal to `.` or `..` is rejected; dot-prefixed names such as `.hidden` and `.well-known` remain -valid. A trailing slash is valid for prefixes such as `support-desk/`. +valid. A trailing slash is valid for prefixes such as `support-desk/`. To +enumerate every dot-prefixed key, list without a prefix and filter the returned +pages. ### Listing for GC diff --git a/packages/storage-blobs/src/conformance.ts b/packages/storage-blobs/src/conformance.ts index 4a91711..8e2d199 100644 --- a/packages/storage-blobs/src/conformance.ts +++ b/packages/storage-blobs/src/conformance.ts @@ -789,6 +789,18 @@ export const conformanceCases: readonly ConformanceCase[] = [ } }), + testCase("rejects control characters in ifMatch values", async (store) => { + const ifMatch = `etag${String.fromCharCode(0)}suffix`; + await assert.rejects( + () => store.put("cond/control", textBytes("x"), { ifMatch }), + (error: unknown) => error instanceof BlobValidationError, + ); + await assert.rejects( + () => store.delete("cond/control", { ifMatch }), + (error: unknown) => error instanceof BlobValidationError, + ); + }), + testCase("accepts a key at the maximum UTF-8 byte length", async (store) => { const key = "k".repeat(MAX_BLOB_KEY_BYTES); const put = await store.put(key, textBytes("edge")); diff --git a/packages/storage-blobs/src/index.ts b/packages/storage-blobs/src/index.ts index 59f1606..b7fa9c2 100644 --- a/packages/storage-blobs/src/index.ts +++ b/packages/storage-blobs/src/index.ts @@ -538,7 +538,8 @@ function assertMaxBytes( return maxBytes; } -function assertEtag(etag: string, label: string): void { +/** Validate a provider ETag used by a conditional operation. */ +export function assertValidEtag(etag: string, label: string): void { if (typeof etag !== "string" || etag.length === 0) { throw new BlobValidationError(`${label} must be a non-empty string.`); } @@ -592,7 +593,8 @@ function decodeMemoryListCursor(storeId: string, cursor: string): string { } } -async function readBody( +/** Buffer an upload body while enforcing the configured byte limit. */ +export async function readBlobBody( body: ReadableStream | Uint8Array, limitBytes: number, ): Promise { @@ -751,7 +753,7 @@ export function createMemoryBlobStore( throw new BlobValidationError('ifNoneMatch must be the literal "*".'); } if (ifMatch !== undefined) { - assertEtag(ifMatch, "ifMatch"); + assertValidEtag(ifMatch, "ifMatch"); } const contentType = assertValidContentType( @@ -779,7 +781,7 @@ export function createMemoryBlobStore( } } - const bytes = await readBody(body, limitBytes); + const bytes = await readBlobBody(body, limitBytes); // Re-check conditions after the body is fully read so a concurrent // create-only put still refuses the loser. @@ -832,7 +834,7 @@ export function createMemoryBlobStore( assertValidBlobKey(key); const ifMatch = deleteOptions?.ifMatch; if (ifMatch !== undefined) { - assertEtag(ifMatch, "ifMatch"); + assertValidEtag(ifMatch, "ifMatch"); } const stored = objects.get(key); diff --git a/packages/storage-cloudflare-r2/src/index.ts b/packages/storage-cloudflare-r2/src/index.ts index ead6cd5..6dbac37 100644 --- a/packages/storage-cloudflare-r2/src/index.ts +++ b/packages/storage-cloudflare-r2/src/index.ts @@ -8,17 +8,17 @@ import { type S3Client, } from "@aws-sdk/client-s3"; import { - BlobSizeLimitError, BlobStoreError, BlobValidationError, DEFAULT_CONTENT_TYPE, DEFAULT_MAX_OBJECT_BYTES, - MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS, + assertValidEtag, assertValidBlobKey, assertValidBlobPrefix, assertValidCacheControl, assertValidContentType, normalizeUserMetadata, + readBlobBody, type BlobListPage, type BlobObjectInfo, type BlobStore, @@ -158,15 +158,6 @@ function assertMaxBytes( return maxBytes; } -function assertEtag(etag: string, label: string): void { - if (typeof etag !== "string" || etag.length === 0) { - throw new BlobValidationError(`${label} must be a non-empty string.`); - } - if (etag.trim() === "*") { - throw new BlobValidationError(`${label} must not be a wildcard.`); - } -} - function assertBucketName(bucket: string): void { if (typeof bucket !== "string" || bucket.length === 0) { throw new BlobValidationError("bucket must be a non-empty string."); @@ -179,90 +170,6 @@ function copyBytes(source: Uint8Array): Uint8Array { return copy; } -async function readBody( - body: ReadableStream | Uint8Array, - limitBytes: number, -): Promise { - if (body instanceof Uint8Array) { - if (body.byteLength > limitBytes) { - throw new BlobSizeLimitError(limitBytes); - } - return copyBytes(body); - } - - const reader = body.getReader(); - let total = 0; - let emptyChunksWithoutProgress = 0; - let bytes = new Uint8Array(0); - try { - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - if (!(value instanceof Uint8Array)) { - throw new BlobValidationError( - "Body stream chunks must be Uint8Array values.", - ); - } - if (value.byteLength === 0) { - emptyChunksWithoutProgress += 1; - if ( - emptyChunksWithoutProgress > MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS - ) { - void reader.cancel().catch(() => { - /* validation error wins */ - }); - throw new BlobValidationError( - "Body stream produced too many empty chunks without progress.", - ); - } - continue; - } - emptyChunksWithoutProgress = 0; - const nextTotal = total + value.byteLength; - if (nextTotal > limitBytes) { - void reader.cancel().catch(() => { - /* size error wins */ - }); - throw new BlobSizeLimitError(limitBytes); - } - if (bytes.byteLength < nextTotal) { - const nextCapacity = Math.min( - limitBytes, - Math.max( - nextTotal, - bytes.byteLength === 0 ? 16 * 1_024 : bytes.byteLength * 2, - ), - ); - const grown = new Uint8Array(nextCapacity); - grown.set(bytes.subarray(0, total)); - bytes = grown; - } - bytes.set(value, total); - total = nextTotal; - } - } catch (error) { - if ( - error instanceof BlobSizeLimitError || - error instanceof BlobValidationError - ) { - throw error; - } - throw new BlobStoreError("Failed to read object body stream.", { - cause: error, - }); - } - - if (total === 0) { - return new Uint8Array(0); - } - if (bytes.byteLength === total) { - return bytes; - } - return copyBytes(bytes.subarray(0, total)); -} - function encodeListCursor(backendId: string, continuation: string): string { return `${R2_LIST_CURSOR_PREFIX}${encodeURIComponent( JSON.stringify({ backendId, continuation } satisfies R2ListCursor), @@ -460,7 +367,7 @@ export function createCloudflareR2BlobStore( throw new BlobValidationError('ifNoneMatch must be the literal "*".'); } if (ifMatch !== undefined) { - assertEtag(ifMatch, "ifMatch"); + assertValidEtag(ifMatch, "ifMatch"); } const contentType = assertValidContentType( @@ -472,7 +379,7 @@ export function createCloudflareR2BlobStore( : assertValidCacheControl(putOptions.cacheControl); const userMetadata = normalizeUserMetadata(putOptions?.userMetadata); const limitBytes = assertMaxBytes(putOptions?.maxBytes, maxObjectBytes); - const bytes = await readBody(body, limitBytes); + const bytes = await readBlobBody(body, limitBytes); const input: { Bucket: string; @@ -668,7 +575,7 @@ export function createCloudflareR2BlobStore( assertValidBlobKey(key); const ifMatch = deleteOptions?.ifMatch; if (ifMatch !== undefined) { - assertEtag(ifMatch, "ifMatch"); + assertValidEtag(ifMatch, "ifMatch"); } // S3 DeleteObject is idempotent (missing key still returns success) and diff --git a/packages/storage-s3/src/index.ts b/packages/storage-s3/src/index.ts index 5777b0e..8603d7e 100644 --- a/packages/storage-s3/src/index.ts +++ b/packages/storage-s3/src/index.ts @@ -8,17 +8,17 @@ import { type S3Client, } from "@aws-sdk/client-s3"; import { - BlobSizeLimitError, BlobStoreError, BlobValidationError, DEFAULT_CONTENT_TYPE, DEFAULT_MAX_OBJECT_BYTES, - MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS, + assertValidEtag, assertValidBlobKey, assertValidBlobPrefix, assertValidCacheControl, assertValidContentType, normalizeUserMetadata, + readBlobBody, type BlobListPage, type BlobObjectInfo, type BlobStore, @@ -159,15 +159,6 @@ function assertMaxBytes( return maxBytes; } -function assertEtag(etag: string, label: string): void { - if (typeof etag !== "string" || etag.length === 0) { - throw new BlobValidationError(`${label} must be a non-empty string.`); - } - if (etag.trim() === "*") { - throw new BlobValidationError(`${label} must not be a wildcard.`); - } -} - function assertBucketName(bucket: string): void { if (typeof bucket !== "string" || bucket.length === 0) { throw new BlobValidationError("bucket must be a non-empty string."); @@ -180,90 +171,6 @@ function copyBytes(source: Uint8Array): Uint8Array { return copy; } -async function readBody( - body: ReadableStream | Uint8Array, - limitBytes: number, -): Promise { - if (body instanceof Uint8Array) { - if (body.byteLength > limitBytes) { - throw new BlobSizeLimitError(limitBytes); - } - return copyBytes(body); - } - - const reader = body.getReader(); - let total = 0; - let emptyChunksWithoutProgress = 0; - let bytes = new Uint8Array(0); - try { - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - if (!(value instanceof Uint8Array)) { - throw new BlobValidationError( - "Body stream chunks must be Uint8Array values.", - ); - } - if (value.byteLength === 0) { - emptyChunksWithoutProgress += 1; - if ( - emptyChunksWithoutProgress > MAX_EMPTY_BODY_CHUNKS_WITHOUT_PROGRESS - ) { - void reader.cancel().catch(() => { - /* validation error wins */ - }); - throw new BlobValidationError( - "Body stream produced too many empty chunks without progress.", - ); - } - continue; - } - emptyChunksWithoutProgress = 0; - const nextTotal = total + value.byteLength; - if (nextTotal > limitBytes) { - void reader.cancel().catch(() => { - /* size error wins */ - }); - throw new BlobSizeLimitError(limitBytes); - } - if (bytes.byteLength < nextTotal) { - const nextCapacity = Math.min( - limitBytes, - Math.max( - nextTotal, - bytes.byteLength === 0 ? 16 * 1_024 : bytes.byteLength * 2, - ), - ); - const grown = new Uint8Array(nextCapacity); - grown.set(bytes.subarray(0, total)); - bytes = grown; - } - bytes.set(value, total); - total = nextTotal; - } - } catch (error) { - if ( - error instanceof BlobSizeLimitError || - error instanceof BlobValidationError - ) { - throw error; - } - throw new BlobStoreError("Failed to read object body stream.", { - cause: error, - }); - } - - if (total === 0) { - return new Uint8Array(0); - } - if (bytes.byteLength === total) { - return bytes; - } - return copyBytes(bytes.subarray(0, total)); -} - function encodeListCursor(backendId: string, continuation: string): string { return `${S3_LIST_CURSOR_PREFIX}${encodeURIComponent( JSON.stringify({ backendId, continuation } satisfies S3ListCursor), @@ -459,7 +366,7 @@ export function createS3BlobStore(options: S3BlobStoreOptions): BlobStore { throw new BlobValidationError('ifNoneMatch must be the literal "*".'); } if (ifMatch !== undefined) { - assertEtag(ifMatch, "ifMatch"); + assertValidEtag(ifMatch, "ifMatch"); } const contentType = assertValidContentType( @@ -471,7 +378,7 @@ export function createS3BlobStore(options: S3BlobStoreOptions): BlobStore { : assertValidCacheControl(putOptions.cacheControl); const userMetadata = normalizeUserMetadata(putOptions?.userMetadata); const limitBytes = assertMaxBytes(putOptions?.maxBytes, maxObjectBytes); - const bytes = await readBody(body, limitBytes); + const bytes = await readBlobBody(body, limitBytes); const input: { Bucket: string; @@ -668,7 +575,7 @@ export function createS3BlobStore(options: S3BlobStoreOptions): BlobStore { assertValidBlobKey(key); const ifMatch = deleteOptions?.ifMatch; if (ifMatch !== undefined) { - assertEtag(ifMatch, "ifMatch"); + assertValidEtag(ifMatch, "ifMatch"); } // S3 DeleteObject is idempotent (missing key still returns success) and diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 811d17d..4fa8c4d 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -713,7 +713,9 @@ async function assertReleaseInventory(directory, records) { const entries = await readdir(directory, { withFileTypes: true }); const actual = entries.map(({ name }) => name).sort(); if (JSON.stringify(actual) !== JSON.stringify(expected)) { - fail("release output inventory does not match the prepared package list"); + fail( + `release output inventory mismatch: expected ${JSON.stringify(expected)}; received ${JSON.stringify(actual)}`, + ); } for (const entry of entries) { const path = join(directory, entry.name); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 9df9117..c166efb 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -375,6 +375,8 @@ describe("release source authentication", () => { ); expect(prepare).toContain("--skip-smoke"); expect(prepare).toContain("include-hidden-files: false"); + expect(prepare).toContain("path: ${{ steps.manifest.outputs.files }}"); + expect(prepare).not.toContain("path: .release/"); expect(smoke).toContain("release-packages.mjs smoke"); expect(workflow).not.toContain("workflow_dispatch"); expect(workflow).toContain("retention-days: 30"); From f844a4cffd8523d6fda74df9d462abdbb363a939 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 15:20:30 -0500 Subject: [PATCH 6/6] Tighten shared release and URL checks --- packages/storage-azure-blob/src/index.test.ts | 23 +++++++++++++++++++ packages/storage-azure-blob/src/index.ts | 22 +++++++++++++++++- scripts/release-packages.d.mts | 2 ++ scripts/release-packages.mjs | 16 ++++++------- test/localstack.ts | 9 +++++++- tests/release-packages.test.ts | 20 ++++++++++++++++ 6 files changed, 82 insertions(+), 10 deletions(-) diff --git a/packages/storage-azure-blob/src/index.test.ts b/packages/storage-azure-blob/src/index.test.ts index 4992821..c196085 100644 --- a/packages/storage-azure-blob/src/index.test.ts +++ b/packages/storage-azure-blob/src/index.test.ts @@ -137,4 +137,27 @@ describe("createAzureBlobStore", () => { "outside the configured container", ); }); + + it("rejects encoded dot segments in a block client URL", async () => { + const container = serviceClient().getContainerClient(nextContainerName()); + const realClient = container.getBlockBlobClient("some-key"); + container.getBlockBlobClient = () => + new Proxy(realClient, { + get(target, property, receiver) { + if (property === "url") { + return `${container.url}/%2e%2e/other`; + } + return Reflect.get(target, property, receiver); + }, + }); + + const store = createAzureBlobStore({ + containerClient: container, + createContainerIfMissing: false, + }); + + await expect(store.head("some-key")).rejects.toThrow( + "outside the configured container", + ); + }); }); diff --git a/packages/storage-azure-blob/src/index.ts b/packages/storage-azure-blob/src/index.ts index 7303c26..7ce54d8 100644 --- a/packages/storage-azure-blob/src/index.ts +++ b/packages/storage-azure-blob/src/index.ts @@ -213,6 +213,9 @@ export function createAzureBlobStore( containerUrl.hash = ""; const endpoint = containerUrl.toString(); const containerPathPrefix = `${containerUrl.pathname.replace(/\/$/u, "")}/`; + const decodedContainerPathPrefix = `${decodeURIComponent( + containerUrl.pathname, + ).replace(/\/$/u, "")}/`; const backendId = `${container.accountName ?? "account"}|${endpoint}|${containerName}`; let ensureContainer: Promise | undefined; @@ -245,9 +248,26 @@ export function createAzureBlobStore( { cause: error }, ); } + let decodedBlobPath: string; + try { + decodedBlobPath = decodeURIComponent(blobUrl.pathname); + } catch (error) { + throw new BlobStoreError( + `Azure produced an invalid URL for ${JSON.stringify(key)}.`, + { cause: error }, + ); + } + const relativePath = decodedBlobPath.slice( + decodedContainerPathPrefix.length, + ); if ( blobUrl.origin !== containerUrl.origin || - !blobUrl.pathname.startsWith(containerPathPrefix) + !blobUrl.pathname.startsWith(containerPathPrefix) || + !decodedBlobPath.startsWith(decodedContainerPathPrefix) || + relativePath.length === 0 || + relativePath + .split("/") + .some((segment) => segment === "." || segment === "..") ) { throw new BlobStoreError( `Azure produced a URL outside the configured container for ${JSON.stringify(key)}.`, diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index 3fd9f2a..cdd42ad 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -37,6 +37,8 @@ export const RELEASE_PACKAGES: readonly ReleasePackageDefinition[]; export const RELEASE_MANIFEST_SCHEMA_VERSION: number; +export const STABLE_RELEASE_TAG: RegExp; + export const REVIEWED_PNPM: { readonly version: string; }; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 4fa8c4d..662140f 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -28,6 +28,9 @@ const REVIEWED_NPM_VERSION = "11.18.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 STABLE_RELEASE_TAG = + /^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$/u; + /** Workspace package manager pinned in package.json via Corepack. */ export const REVIEWED_PNPM = { version: REVIEWED_PNPM_VERSION, @@ -265,10 +268,7 @@ export function validateReleaseTag(options = {}) { const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; const expectedReleaseCommit = options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; - if ( - releaseTag === undefined || - !/^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$/u.test(releaseTag) - ) { + if (releaseTag === undefined || !STABLE_RELEASE_TAG.test(releaseTag)) { fail("a stable release tag is required"); } if ( @@ -942,9 +942,8 @@ async function verifyPreparedManifest(path, expectedManifestDigest) { "gitCommit,packages,releaseTag,schemaVersion" || prepared.schemaVersion !== RELEASE_MANIFEST_SCHEMA_VERSION || !/^[0-9a-f]{40}$/u.test(prepared.gitCommit) || - !/^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$/u.test( - prepared.releaseTag, - ) || + (prepared.releaseTag !== null && + !STABLE_RELEASE_TAG.test(prepared.releaseTag)) || !Array.isArray(records) || records.length !== RELEASE_PACKAGES.length ) { @@ -966,7 +965,8 @@ async function verifyPreparedManifest(path, expectedManifestDigest) { Object.keys(record ?? {}) .sort() .join(",") !== "exports,files,integrity,name,sha256,tarball,version" || - prepared.releaseTag !== `v${record?.version}` || + (prepared.releaseTag !== null && + prepared.releaseTag !== `v${record?.version}`) || record?.name !== definition.name || !STABLE_SEMVER.test(record.version) || !/^[0-9a-f]{64}$/u.test(record.sha256) || diff --git a/test/localstack.ts b/test/localstack.ts index e6c6e5f..33574d5 100644 --- a/test/localstack.ts +++ b/test/localstack.ts @@ -103,7 +103,14 @@ function runDocker(args: string[]): Promise<{ export async function setup(): Promise { if (await portAccepting(LOCALSTACK_PORT)) { - await waitForS3Ready(30_000); + try { + await waitForS3Ready(30_000); + } catch (error) { + throw new Error( + `Port ${LOCALSTACK_PORT} is already in use by a service that is not a ready LocalStack S3 instance.`, + { cause: error }, + ); + } return; } diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index c166efb..678612f 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -8,6 +8,7 @@ import { RELEASE_MANIFEST_SCHEMA_VERSION, REVIEWED_NPM, REVIEWED_PNPM, + STABLE_RELEASE_TAG, assertPnpmLockfileSynchronized, decidePublication, digestManifest, @@ -97,6 +98,25 @@ describe("release package metadata", () => { ].map((match) => match[1]); expect(tagPatterns).toHaveLength(2); expect(new Set(tagPatterns).size).toBe(1); + expect(tagPatterns[0]).toBe(STABLE_RELEASE_TAG.source); + const installedNpmVersions = [ + ...workflow.matchAll(/npm install --global npm@([0-9.]+)/gu), + ].map((match) => match[1]); + expect(installedNpmVersions).toEqual([ + REVIEWED_NPM.version, + REVIEWED_NPM.version, + ]); + for (const marker of [ + 'hash(manifestBytes, "sha256", "hex")', + 'hash(bytes, "sha512", "base64")', + '"--provenance"', + '"--ignore-scripts"', + '"--registry"', + "/\\bE404\\b/.test(output)", + "expectedInventory.sort()", + ]) { + expect(workflow).toContain(marker); + } expect(workflow.match(/verify-tag/gu)).toHaveLength(2); expect(workflow.match(/merge-base --is-ancestor/gu)).toHaveLength(2); });