diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index f36114b..7ea3193 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -17,6 +17,8 @@ concurrency: jobs: prepare: runs-on: ubuntu-latest + outputs: + manifest_digest: ${{ steps.manifest.outputs.digest }} services: redis: image: redis:7.4-alpine @@ -34,40 +36,69 @@ jobs: 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 tag shell: bash run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Package publication requires a stable GitHub release" + 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 must be a stable supported version" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9A-Fa-f]{40}$ ]]; then + echo "::error::Release commit must be a full commit ID" + exit 1 + fi if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then - echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed SSH allowed-signers entries" exit 1 fi - allowed_signers="${RUNNER_TEMP}/release-allowed-signers" + auth_repo="$(mktemp -d "${RUNNER_TEMP}/release-auth.XXXXXX")" + trap 'rm -rf "${auth_repo}"' EXIT + git init --bare "${auth_repo}" + git -C "${auth_repo}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + allowed_signers="${auth_repo}/allowed-signers" umask 077 printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" - git config --local gpg.format ssh - git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git -C "${auth_repo}" config gpg.format ssh + git -C "${auth_repo}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${auth_repo}" fetch --no-tags origin \ + "refs/heads/main:refs/remotes/origin/main" \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + test "$(git -C "${auth_repo}" cat-file -t "refs/tags/${RELEASE_TAG}")" = "tag" + signed_name="$(git -C "${auth_repo}" cat-file tag "refs/tags/${RELEASE_TAG}" | sed -n 's/^tag //p' | head -n 1)" + test "${signed_name}" = "${RELEASE_TAG}" + git -C "${auth_repo}" verify-tag "refs/tags/${RELEASE_TAG}" + peeled="$(git -C "${auth_repo}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + test "${peeled,,}" = "${RELEASE_COMMIT,,}" + git -C "${auth_repo}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main + + - name: Check out the immutable release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 0 + + - name: Fetch the protected release branch + run: git fetch --no-tags origin main:refs/remotes/origin/main - 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 run: corepack enable - name: Use the reviewed npm release - run: npm install --global npm@11.18.0 + run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/ - name: Install dependencies run: pnpm install --frozen-lockfile @@ -93,25 +124,170 @@ jobs: - name: Run Upstash Redis adapter tests run: pnpm run test:upstash-redis - - name: Prepare and verify release tarballs - run: pnpm run release:pack -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release + - name: Prepare and seal release tarballs + run: pnpm run release:pack -- --require-clean --require-main-ancestor --expected-release-commit "${RELEASE_COMMIT}" --output .release + + - name: Record the package manifest digest + id: manifest + shell: bash + run: | + set -euo pipefail + digest="$(sha256sum .release/package-manifest.json | cut -d ' ' -f 1)" + echo "digest=${digest}" >> "${GITHUB_OUTPUT}" + echo "Prepared manifest SHA-256 ${digest}" >> "${GITHUB_STEP_SUMMARY}" - name: Upload the prepared release - id: upload uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: name: cache-core-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}" + smoke: + needs: prepare + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Use the reviewed npm release + run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/ + + - name: Download the prepared release + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: cache-core-release-${{ github.run_id }} + path: .release + + - name: Install and import the prepared packages + env: + MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} + RELEASE_DIRECTORY: ${{ github.workspace }}/.release + run: | + node --input-type=module <<'NODE' + import { spawnSync } from "node:child_process"; + import { createHash } from "node:crypto"; + import { + lstat, + mkdtemp, + readFile, + readdir, + rm, + writeFile, + } from "node:fs/promises"; + import { tmpdir } from "node:os"; + import { join } from "node:path"; + + const releaseDirectory = process.env.RELEASE_DIRECTORY; + const manifestBytes = await readFile(join(releaseDirectory, "package-manifest.json")); + const digest = createHash("sha256").update(manifestBytes).digest("hex"); + if (digest !== process.env.MANIFEST_DIGEST) { + throw new Error("prepared manifest digest does not match"); + } + const manifest = JSON.parse(manifestBytes.toString("utf8")); + const expectedFiles = new Set([ + "package-manifest.json", + ...manifest.packages.map(({ tarball }) => tarball), + ]); + const entries = await readdir(releaseDirectory, { withFileTypes: true }); + if ( + entries.length !== expectedFiles.size || + entries.some(({ name }) => !expectedFiles.has(name)) + ) { + throw new Error("release directory inventory does not match the prepared manifest"); + } + for (const entry of entries) { + const info = await lstat(join(releaseDirectory, entry.name)); + if ( + entry.name.startsWith(".") || + !entry.isFile() || + info.isSymbolicLink() || + !info.isFile() + ) { + throw new Error(`release entry must be a regular visible file: ${entry.name}`); + } + } + for (const record of manifest.packages) { + const tarball = await readFile(join(releaseDirectory, record.tarball)); + const sha256 = createHash("sha256").update(tarball).digest("hex"); + const shasum = createHash("sha1").update(tarball).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(tarball).digest("base64")}`; + if ( + sha256 !== record.sha256 || + shasum !== record.shasum || + integrity !== record.integrity + ) { + throw new Error(`${record.name} prepared tarball has changed`); + } + } + const consumer = await mkdtemp(join(tmpdir(), "pegma-release-smoke-")); + try { + await writeFile( + join(consumer, "package.json"), + '{"name":"pegma-release-smoke","private":true,"type":"module"}\n', + ); + const tarballs = manifest.packages.map(({ tarball }) => + join(releaseDirectory, tarball), + ); + const installed = spawnSync( + "npm", + [ + "install", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--package-lock=false", + "--registry", + "https://registry.npmjs.org/", + ...tarballs, + ], + { cwd: consumer, encoding: "utf8", stdio: "pipe" }, + ); + if (installed.status !== 0) { + throw new Error(`${installed.stdout}\n${installed.stderr}`); + } + for (const { name } of manifest.packages) { + const installedManifest = JSON.parse( + await readFile(join(consumer, "node_modules", name, "package.json"), "utf8"), + ); + if ( + installedManifest.exports === null || + typeof installedManifest.exports !== "object" || + Array.isArray(installedManifest.exports) + ) { + throw new Error(`${name} installed manifest has invalid exports`); + } + for (const exportKey of Object.keys(installedManifest.exports)) { + const specifier = exportKey === "." ? name : `${name}${exportKey.slice(1)}`; + const checked = spawnSync( + process.execPath, + [ + "--input-type=module", + "--eval", + `await import(${JSON.stringify(specifier)})`, + ], + { cwd: consumer, encoding: "utf8", stdio: "pipe" }, + ); + if (checked.status !== 0) { + throw new Error(`${checked.stdout}\n${checked.stderr}`); + } + } + } + } finally { + await rm(consumer, { recursive: true, force: true }); + } + NODE publish: - needs: prepare + needs: [prepare, smoke] runs-on: ubuntu-latest environment: npm-publish permissions: @@ -119,24 +295,61 @@ jobs: id-token: write env: 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 exact release tag - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: refs/tags/${{ github.event.release.tag_name }} - fetch-depth: 1 + - name: Re-authenticate the release tag + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Package publication requires a stable GitHub release" + 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 must be a stable supported version" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9A-Fa-f]{40}$ ]]; then + echo "::error::Release commit must be a full commit ID" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain reviewed SSH allowed-signers entries" + exit 1 + fi + auth_repo="$(mktemp -d "${RUNNER_TEMP}/release-auth.XXXXXX")" + trap 'rm -rf "${auth_repo}"' EXIT + git init --bare "${auth_repo}" + git -C "${auth_repo}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + allowed_signers="${auth_repo}/allowed-signers" + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git -C "${auth_repo}" config gpg.format ssh + git -C "${auth_repo}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${auth_repo}" fetch --no-tags origin \ + "refs/heads/main:refs/remotes/origin/main" \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + test "$(git -C "${auth_repo}" cat-file -t "refs/tags/${RELEASE_TAG}")" = "tag" + signed_name="$(git -C "${auth_repo}" cat-file tag "refs/tags/${RELEASE_TAG}" | sed -n 's/^tag //p' | head -n 1)" + test "${signed_name}" = "${RELEASE_TAG}" + git -C "${auth_repo}" verify-tag "refs/tags/${RELEASE_TAG}" + peeled="$(git -C "${auth_repo}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + test "${peeled,,}" = "${RELEASE_COMMIT,,}" + git -C "${auth_repo}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main - - 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: Use the reviewed npm release - run: npm install --global npm@11.18.0 + run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/ - name: Download the prepared release uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 @@ -144,5 +357,213 @@ jobs: name: cache-core-release-${{ github.run_id }} path: .release - - name: Publish verified prepared tarballs - run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json + - name: Verify and publish the prepared tarballs + env: + MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} + RELEASE_DIRECTORY: ${{ github.workspace }}/.release + run: | + node --input-type=module <<'NODE' + import { spawnSync } from "node:child_process"; + import { createHash, timingSafeEqual } from "node:crypto"; + import { + chmod, + lstat, + mkdtemp, + readFile, + readdir, + rm, + writeFile, + } from "node:fs/promises"; + import { join, resolve } from "node:path"; + + const expectedPackages = [ + ["cache-core", "@pegma/cache-core"], + ["cache-conformance", "@pegma/cache-conformance"], + ["cache-redis", "@pegma/cache-redis"], + ["cache-azure-redis", "@pegma/cache-azure-redis"], + ["cache-elasticache", "@pegma/cache-elasticache"], + ["cache-upstash-redis", "@pegma/cache-upstash-redis"], + ]; + const releaseDirectory = resolve(process.env.RELEASE_DIRECTORY); + const manifestPath = join(releaseDirectory, "package-manifest.json"); + const manifestBytes = await readFile(manifestPath); + const manifestDigest = createHash("sha256").update(manifestBytes).digest("hex"); + if (manifestDigest !== process.env.MANIFEST_DIGEST) { + throw new Error("prepared manifest digest does not match"); + } + const manifest = JSON.parse(manifestBytes.toString("utf8")); + const same = (left, right) => { + const a = Buffer.from(left); + const b = Buffer.from(right); + return a.length === b.length && timingSafeEqual(a, b); + }; + if ( + manifest.schemaVersion !== 1 || + !same(manifest.gitCommit.toLowerCase(), process.env.RELEASE_COMMIT.toLowerCase()) || + !same(manifest.releaseTag, process.env.RELEASE_TAG) || + !Array.isArray(manifest.packages) || + manifest.packages.length !== expectedPackages.length + ) { + throw new Error("prepared package manifest identity is invalid"); + } + const tagVersion = process.env.RELEASE_TAG.slice(1); + const expectedFiles = new Set(["package-manifest.json"]); + for (const [index, record] of manifest.packages.entries()) { + const [directory, name] = expectedPackages[index]; + const expectedTarball = `${name.slice(1).replace("/", "-")}-${record.version}.tgz`; + if ( + record.directory !== directory || + record.name !== name || + !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(record.version) || + record.tarball !== expectedTarball || + record.publish !== (record.version === tagVersion) || + !/^[0-9a-f]{64}$/.test(record.sha256) || + !/^[0-9a-f]{40}$/.test(record.shasum) || + typeof record.integrity !== "string" + ) { + throw new Error(`${name} has invalid prepared metadata`); + } + expectedFiles.add(record.tarball); + } + if (!manifest.packages.some(({ publish }) => publish)) { + throw new Error("prepared package manifest has no release candidates"); + } + const entries = await readdir(releaseDirectory, { withFileTypes: true }); + if ( + entries.length !== expectedFiles.size || + entries.some(({ name }) => !expectedFiles.has(name)) + ) { + throw new Error("release directory inventory does not match the prepared manifest"); + } + for (const entry of entries) { + const info = await lstat(join(releaseDirectory, entry.name)); + if ( + entry.name.startsWith(".") || + !entry.isFile() || + info.isSymbolicLink() || + !info.isFile() + ) { + throw new Error(`release entry must be a regular visible file: ${entry.name}`); + } + } + for (const record of manifest.packages) { + const tarball = await readFile(join(releaseDirectory, record.tarball)); + const sha256 = createHash("sha256").update(tarball).digest("hex"); + const shasum = createHash("sha1").update(tarball).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(tarball).digest("base64")}`; + if ( + !same(sha256, record.sha256) || + !same(shasum, record.shasum) || + !same(integrity, record.integrity) + ) { + throw new Error(`${record.name} prepared tarball has changed`); + } + } + + const publishDirectory = await mkdtemp(join(process.env.RUNNER_TEMP, "npm-publish-")); + const configDirectory = await mkdtemp(join(process.env.RUNNER_TEMP, "npm-config-")); + try { + const userConfig = join(configDirectory, "user.npmrc"); + const globalConfig = join(configDirectory, "global.npmrc"); + await writeFile(userConfig, "", { mode: 0o600 }); + await writeFile(globalConfig, "", { mode: 0o600 }); + await chmod(userConfig, 0o600); + await chmod(globalConfig, 0o600); + const allowedNames = new Set([ + "CI", + "PATH", + "HOME", + "RUNNER_TEMP", + "TMP", + "TEMP", + "TMPDIR", + "SYSTEMROOT", + ]); + const npmEnvironment = Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => + allowedNames.has(name) || + name.startsWith("GITHUB_") || + name.startsWith("ACTIONS_ID_TOKEN_"), + ), + ); + npmEnvironment.NPM_CONFIG_USERCONFIG = userConfig; + npmEnvironment.NPM_CONFIG_GLOBALCONFIG = globalConfig; + const runNpm = (arguments_, allowFailure = false) => { + const result = spawnSync("npm", arguments_, { + cwd: publishDirectory, + env: npmEnvironment, + encoding: "utf8", + stdio: "pipe", + }); + if (result.error) throw result.error; + if (result.status !== 0 && !allowFailure) { + throw new Error(`${result.stdout}\n${result.stderr}`); + } + return result; + }; + const registryIntegrity = (record) => { + const result = runNpm( + [ + "view", + `${record.name}@${record.version}`, + "dist.integrity", + "--json", + "--registry", + "https://registry.npmjs.org/", + "--ignore-scripts", + ], + true, + ); + if (result.status === 0) { + const value = JSON.parse(result.stdout.trim()); + if (typeof value !== "string" || value.length === 0) { + throw new Error(`${record.name}@${record.version} has no registry integrity`); + } + return value; + } + if (/\bE404\b/.test(`${result.stdout}\n${result.stderr}`)) return null; + throw new Error(`${result.stdout}\n${result.stderr}`); + }; + for (const record of manifest.packages.filter(({ publish }) => publish)) { + const existing = registryIntegrity(record); + if (existing !== null) { + if (!same(existing, record.integrity)) { + throw new Error(`${record.name}@${record.version} differs from the prepared tarball`); + } + continue; + } + runNpm([ + "publish", + join(releaseDirectory, record.tarball), + "--tag", + "latest", + "--registry", + "https://registry.npmjs.org/", + "--access", + "public", + "--provenance", + "--ignore-scripts", + ]); + let confirmed = false; + for (let attempt = 0; attempt < 6; attempt += 1) { + const visible = registryIntegrity(record); + if (visible !== null && same(visible, record.integrity)) { + confirmed = true; + break; + } + if (attempt < 5) { + await new Promise((resolveDelay) => + setTimeout(resolveDelay, 2 ** attempt * 1000), + ); + } + } + if (!confirmed) { + throw new Error(`${record.name}@${record.version} did not become visible`); + } + } + } finally { + await rm(publishDirectory, { recursive: true, force: true }); + await rm(configDirectory, { recursive: true, force: true }); + } + NODE diff --git a/docs/RELEASING.md b/docs/RELEASING.md index d9ab1e0..5624e18 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -46,24 +46,31 @@ 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 checkout, workflow-owned code verifies that the tag: - is a stable annotated `vX.Y.Z` tag signed by an allowed signer; -- matches the package version; - points to the checkout and the GitHub release-event commit; and - is contained in `origin/main`. +After checkout, preparation also verifies that the tag matches a public +package version. Before publication, workflow-owned code repeats the tag +checks and verifies the package version from the sealed manifest. + Its preparation job has no OIDC permission. It installs the reviewed npm `11.18.0` release and the pinned pnpm without dependency caching, runs the -full gate, builds and packs once with that npm CLI, smoke-tests the tarball -from a clean consumer, records its SHA-1 and SHA-512 integrity, and uploads -the exact prepared artifacts. The lockfile source of truth is `pnpm-lock.yaml`. - -Only the `npm-publish` job receives `id-token: write`. It installs no -dependencies and does not download pnpm. It runs -`node scripts/release-packages.mjs publish`, verifies the prepared manifest -and tarball hashes against the release commit, and publishes those tarballs -with npm provenance. +full gate, builds and packs once with that npm CLI, revalidates each packed +manifest, records SHA-1, SHA-256, and SHA-512 integrity, seals the exact +release-directory inventory, and uploads only those prepared artifacts. The +lockfile source of truth is `pnpm-lock.yaml`. + +A separate unprivileged job downloads the sealed artifact and installs and +imports every tarball from a clean consumer directory. Only the +`npm-publish` job receives `id-token: write`. It checks out no repository +code, installs no project dependencies, and does not download pnpm. Its +workflow-owned verifier re-authenticates the tag, verifies the prepared +manifest digest, exact inventory, and tarball hashes against the release +commit, then publishes from an empty temporary directory with isolated npm +configuration and npm provenance. ## Safe retry diff --git a/packages/cache-conformance/src/index.ts b/packages/cache-conformance/src/index.ts index ffcd0be..1faa8f3 100644 --- a/packages/cache-conformance/src/index.ts +++ b/packages/cache-conformance/src/index.ts @@ -130,6 +130,43 @@ export const conformanceCases: readonly ConformanceCase[] = [ }, ), + testCase("ill-formed Unicode tokens are rejected", async (store) => { + const malformed = "\uD800"; + await assert.rejects(store.set(key(malformed, "key"), "value", codec)); + await assert.rejects(store.set(key("ns", malformed), "value", codec)); + await assert.rejects( + store.set(key("ns", "key", malformed), "value", codec), + ); + await assert.rejects( + store.set(key("ns", "tagged"), "value", codec, { + tags: [malformed], + }), + ); + await assert.rejects(store.invalidateTags([malformed])); + }), + + testCase("well-formed Unicode tokens round-trip unchanged", async (store) => { + const address = key( + "namespace-\u{1F600}", + "key-\u{1D11E}", + "slot-\u{1F680}", + ); + const tag = "tag-\u{1F30D}"; + assert.equal( + (await store.set(address, "value", codec, { tags: [tag] })).status, + "hit", + ); + const got = await store.get(address, codec); + assert.equal(got.status, "hit"); + if (got.status === "hit") { + assert.equal(got.value, "value"); + } + assert.deepEqual(await store.invalidateTags([tag]), { + status: "hit", + value: 1, + }); + }), + testCase( "absolute TTL expires against the injected Clock", async (store, context) => { diff --git a/packages/cache-core/src/index.test.ts b/packages/cache-core/src/index.test.ts index 8b03b81..5af0777 100644 --- a/packages/cache-core/src/index.test.ts +++ b/packages/cache-core/src/index.test.ts @@ -48,6 +48,30 @@ describe("formatCacheKey", () => { formatCacheKey({ namespace: "ns", key: `bad\u0000key` }), ).toThrow(CacheKeyValidationError); }); + + it("rejects unpaired UTF-16 surrogates in key tokens", () => { + for (const malformed of ["\uD800", "\uDFFF", "\uDC00\uD800"]) { + expect(() => + formatCacheKey({ namespace: malformed, key: "key" }), + ).toThrow(CacheKeyValidationError); + expect(() => formatCacheKey({ namespace: "ns", key: malformed })).toThrow( + CacheKeyValidationError, + ); + expect(() => + formatCacheKey({ namespace: "ns", key: "key", hashTag: malformed }), + ).toThrow(CacheKeyValidationError); + } + }); + + it("preserves well-formed supplementary characters", () => { + expect( + formatCacheKey({ + namespace: "sessions-\u{1F600}", + key: "key-\u{1D11E}", + hashTag: "user-\u{1F680}", + }), + ).toBe("{user-\u{1F680}}sessions-\u{1F600}:key-\u{1D11E}"); + }); }); describe("codecs", () => { @@ -159,7 +183,7 @@ describe("createMemoryCacheStore", () => { expect(second).toMatchObject({ status: "hit", value: "v2" }); }); - it("does not let a later tag-array mutation poison the index", async () => { + it("does not let a later tag-array mutation desynchronize the index", async () => { const clock = createControllableClock(START); const store = createMemoryCacheStore({ clock }); const codec = jsonCodec(); @@ -230,6 +254,31 @@ describe("createMemoryCacheStore", () => { }); describe("runGetOrCompute fallback isolation", () => { + it("snapshots tags before compute can mutate the caller array", async () => { + const clock = createControllableClock(START); + const store = createMemoryCacheStore({ clock }); + const tags = ["group"]; + await store.getOrCompute( + { namespace: "tags", key: "compute" }, + { + codec: jsonCodec(), + tags, + compute: () => { + tags[0] = "changed"; + return "value"; + }, + }, + ); + expect(await store.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 1, + }); + expect(await store.invalidateTags(["changed"])).toEqual({ + status: "hit", + value: 0, + }); + }); + it("does not give a fail-closed caller a fail-open compute", async () => { const clock = createControllableClock(START); const store = createUnavailableCacheStore({ clock }); @@ -306,3 +355,23 @@ describe("runGetOrCompute fallback isolation", () => { expect(computes).toBe(1); }); }); + +describe("createUnavailableCacheStore validation", () => { + it("rejects ill-formed Unicode before reporting backend status", async () => { + const store = createUnavailableCacheStore({ + clock: createControllableClock(START), + }); + const codec = jsonCodec(); + await expect( + store.get({ namespace: "ns", key: "\uD800" }, codec), + ).rejects.toThrow(CacheKeyValidationError); + await expect( + store.set({ namespace: "ns", key: "key" }, "value", codec, { + tags: ["\uDFFF"], + }), + ).rejects.toThrow(CacheKeyValidationError); + await expect(store.invalidateTags(["\uD800"])).rejects.toThrow( + CacheKeyValidationError, + ); + }); +}); diff --git a/packages/cache-core/src/index.ts b/packages/cache-core/src/index.ts index feabeb7..2b3fdbc 100644 --- a/packages/cache-core/src/index.ts +++ b/packages/cache-core/src/index.ts @@ -92,6 +92,38 @@ export class CacheKeyValidationError extends Error { const CONTROL = /[\u0000-\u001F\u007F]/u; +/** Rejects strings that cannot be encoded to UTF-8 without replacement. */ +export function assertWellFormedCacheString( + value: string, + label: string, +): void { + for (let index = 0; index < value.length; index += 1) { + const unit = value.charCodeAt(index); + if (unit >= 0xd800 && unit <= 0xdbff) { + const next = value.charCodeAt(index + 1); + if (!(next >= 0xdc00 && next <= 0xdfff)) { + throw new CacheKeyValidationError( + `${label} must contain well-formed Unicode`, + ); + } + index += 1; + } else if (unit >= 0xdc00 && unit <= 0xdfff) { + throw new CacheKeyValidationError( + `${label} must contain well-formed Unicode`, + ); + } + } +} + +/** Validates and snapshots caller-owned tag arrays. */ +export function validateCacheTags(tags: readonly string[]): readonly string[] { + const validated = [...tags]; + for (const tag of validated) { + assertWellFormedCacheString(tag, "tag"); + } + return validated; +} + function requireToken(value: string, label: string): string { if (value.length === 0) { throw new CacheKeyValidationError(`${label} must not be empty`); @@ -102,6 +134,7 @@ function requireToken(value: string, label: string): string { if (value.includes("{") || value.includes("}")) { throw new CacheKeyValidationError(`${label} must not contain braces`); } + assertWellFormedCacheString(value, label); return value; } @@ -257,6 +290,10 @@ export async function runGetOrCompute( options: RunGetOrComputeOptions, ): Promise> { const formatted = formatCacheKey(options.key); + const validatedOptions: RunGetOrComputeOptions = + options.tags === undefined + ? options + : { ...options, tags: validateCacheTags(options.tags) }; const fallback = options.fallback ?? "fail-closed"; const random = options.random ?? Math.random; const getFlight = `${formatted}#get`; @@ -294,7 +331,7 @@ export async function runGetOrCompute( }) ) { const recomputed = await options.singleFlight.do(computeFlight, () => - computeAndStore(options, clockMs(options.clock)), + computeAndStore(validatedOptions, clockMs(options.clock)), ); if (recomputed.status === "hit") { return recomputed; @@ -316,7 +353,7 @@ export async function runGetOrCompute( } return options.singleFlight.do(computeFlight, () => - computeAndStore(options, clockMs(options.clock)), + computeAndStore(validatedOptions, clockMs(options.clock)), ); } @@ -459,12 +496,12 @@ export function createMemoryCacheStore(options: CacheDependencies): CacheStore { async set(key, value, codec, setOptions) { const formatted = formatCacheKey(key); const nowMs = clockMs(clock); + const tags = validateCacheTags(setOptions?.tags ?? []); const bytes = codec.encode(value).slice(); const previous = entries.get(formatted); if (previous !== undefined) { forgetTags(formatted, previous.tags); } - const tags = [...(setOptions?.tags ?? [])]; const deadlines = ttlDeadlines(nowMs, setOptions?.ttl); entries.set(formatted, { bytes, @@ -516,8 +553,9 @@ export function createMemoryCacheStore(options: CacheDependencies): CacheStore { }, async invalidateTags(tags) { + const validatedTags = validateCacheTags(tags); let removed = 0; - for (const tag of tags) { + for (const tag of validatedTags) { const keys = tagged.get(tag); if (keys === undefined) { continue; @@ -557,13 +595,17 @@ export function createUnavailableCacheStore( const down = new Error("cache backend unavailable"); const store: CacheStore = { - async get() { + async get(key) { + formatCacheKey(key); return { status: "error", error: down }; }, - async set() { + async set(key, _value, _codec, setOptions) { + formatCacheKey(key); + validateCacheTags(setOptions?.tags ?? []); return { status: "error", error: down }; }, - async delete() { + async delete(key) { + formatCacheKey(key); return { status: "error", error: down }; }, async getOrCompute( @@ -593,7 +635,8 @@ export function createUnavailableCacheStore( : { earlyExpiration: computeOptions.earlyExpiration }), }); }, - async invalidateTags() { + async invalidateTags(tags) { + validateCacheTags(tags); return { status: "error", error: down }; }, async ping() { diff --git a/packages/cache-redis/src/index.test.ts b/packages/cache-redis/src/index.test.ts index cc13c22..6012c73 100644 --- a/packages/cache-redis/src/index.test.ts +++ b/packages/cache-redis/src/index.test.ts @@ -33,6 +33,10 @@ function proxyRedis( client: Redis, hooks: { afterGetBuffer?: () => Promise; + beforeEval?: ( + script: string, + args: readonly (string | Buffer | number)[], + ) => Promise; } = {}, ): RedisCacheClient { return { @@ -47,7 +51,10 @@ function proxyRedis( srem: (key, ...members) => client.srem(key, ...members), smembers: (key) => client.smembers(key), ping: () => client.ping(), - eval: (script, numKeys, ...args) => client.eval(script, numKeys, ...args), + async eval(script, numKeys, ...args) { + await hooks.beforeEval?.(script, args); + return client.eval(script, numKeys, ...args); + }, }; } @@ -111,7 +118,7 @@ describe("Redis adapter guarantees", () => { expect(await first.get(address, codec)).toEqual({ status: "miss" }); }); - it("does not let a later tag-array mutation poison the index", async () => { + it("does not let a later tag-array mutation desynchronize the index", async () => { const clock = createControllableClock(START); const store = createRedisCacheStore({ clock, @@ -325,6 +332,188 @@ describe("Redis adapter guarantees", () => { }); }); + it("keeps a newer entry when expired cleanup loses the comparison", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "ttl", key: "cleanup-race" }; + const writer = createRedisCacheStore({ clock, redis, keyPrefix }); + await writer.set(address, "old", codec, { + ttl: { absoluteMs: 1_000 }, + tags: ["old-tag"], + }); + clock.advance(1_000); + + let replaced = false; + const reader = createRedisCacheStore({ + clock, + redis: proxyRedis(redis, { + async beforeEval(script) { + if (!replaced && script.includes("DEL")) { + replaced = true; + await writer.set(address, "new", codec, { tags: ["new-tag"] }); + } + }, + }), + keyPrefix, + }); + + expect(await reader.get(address, codec)).toEqual({ status: "miss" }); + expect(await writer.get(address, codec)).toMatchObject({ + status: "hit", + value: "new", + }); + expect(await writer.invalidateTags(["old-tag"])).toEqual({ + status: "hit", + value: 0, + }); + expect(await writer.get(address, codec)).toMatchObject({ + status: "hit", + value: "new", + }); + }); + + it("keeps a newer entry when malformed cleanup loses the comparison", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "decode", key: "malformed-race" }; + const writer = createRedisCacheStore({ clock, redis, keyPrefix }); + await redis.set(`${keyPrefix}e:decode:malformed-race`, Buffer.from("bad")); + + let replaced = false; + const reader = createRedisCacheStore({ + clock, + redis: proxyRedis(redis, { + async beforeEval(script) { + if (!replaced && script.includes("DEL")) { + replaced = true; + await writer.set(address, "new", codec, { tags: ["fresh"] }); + } + }, + }), + keyPrefix, + }); + + expect((await reader.get(address, codec)).status).toBe("error"); + expect(await writer.get(address, codec)).toMatchObject({ + status: "hit", + value: "new", + }); + }); + + it("keeps a newer entry when codec cleanup loses the comparison", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "decode", key: "codec-race" }; + const writer = createRedisCacheStore({ clock, redis, keyPrefix }); + await writer.set(address, "old", codec, { tags: ["old-tag"] }); + + let replaced = false; + const reader = createRedisCacheStore({ + clock, + redis: proxyRedis(redis, { + async beforeEval(script) { + if (!replaced && script.includes("DEL")) { + replaced = true; + await writer.set(address, "new", codec, { tags: ["new-tag"] }); + } + }, + }), + keyPrefix, + }); + const rejectingCodec = { + encode: codec.encode, + decode() { + throw new Error("cannot decode"); + }, + }; + + expect((await reader.get(address, rejectingCodec)).status).toBe("error"); + expect(await writer.get(address, codec)).toMatchObject({ + status: "hit", + value: "new", + }); + expect(await writer.invalidateTags(["old-tag"])).toEqual({ + status: "hit", + value: 0, + }); + }); + + it("keeps a newer tagged entry when invalidation loses the comparison", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "tags", key: "invalidation-race" }; + const writer = createRedisCacheStore({ clock, redis, keyPrefix }); + await writer.set(address, "old", codec, { tags: ["group"] }); + + let replaced = false; + const invalidator = createRedisCacheStore({ + clock, + redis: proxyRedis(redis, { + async beforeEval(script) { + if (!replaced && script.includes("DEL")) { + replaced = true; + await writer.set(address, "new", codec, { tags: ["group"] }); + } + }, + }), + keyPrefix, + }); + + expect(await invalidator.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 0, + }); + expect(await writer.get(address, codec)).toMatchObject({ + status: "hit", + value: "new", + }); + expect(await writer.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 1, + }); + }); + + it("bounds cleanup retries while a sliding entry keeps changing", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "tags", key: "sliding-retries" }; + const writer = createRedisCacheStore({ clock, redis, keyPrefix }); + await writer.set(address, "value", codec, { + tags: ["group"], + ttl: { slidingMs: 1_000 }, + }); + + let deleteAttempts = 0; + const invalidator = createRedisCacheStore({ + clock, + redis: proxyRedis(redis, { + async beforeEval(script) { + if (script.includes("DEL")) { + deleteAttempts += 1; + clock.advance(1); + await writer.get(address, codec); + } + }, + }), + keyPrefix, + }); + + expect(await invalidator.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 0, + }); + expect(deleteAttempts).toBe(4); + expect(await writer.get(address, codec)).toMatchObject({ + status: "hit", + value: "value", + }); + }); + it("does not delete a winning entry when a stale tag is invalidated", async () => { const clock = createControllableClock(START); const keyPrefix = nextPrefix(); @@ -387,4 +576,14 @@ describe("Redis adapter guarantees", () => { }), ).toThrow(/braces/u); }); + + it("rejects an ill-formed Unicode keyPrefix", () => { + expect(() => + createRedisCacheStore({ + clock: createControllableClock(START), + redis, + keyPrefix: "prefix-\uD800", + }), + ).toThrow(/well-formed Unicode/u); + }); }); diff --git a/packages/cache-redis/src/index.ts b/packages/cache-redis/src/index.ts index 9de354b..999456d 100644 --- a/packages/cache-redis/src/index.ts +++ b/packages/cache-redis/src/index.ts @@ -1,7 +1,11 @@ +import { randomBytes } from "node:crypto"; + import { + assertWellFormedCacheString, createSingleFlight, formatCacheKey, runGetOrCompute, + validateCacheTags, type CacheDependencies, type CacheGetOrComputeOptions, type CacheKey, @@ -61,9 +65,21 @@ end return 0 `; +/** Delete KEYS[1] only when it still equals the envelope this operation read. */ +const COMPARE_AND_DELETE = ` +if redis.call('GET', KEYS[1]) == ARGV[1] then + return redis.call('DEL', KEYS[1]) +end +return 0 +`; + +const TAG_MEMBER_SEPARATOR = "\u001F"; +const MAX_COMPARE_DELETE_ATTEMPTS = 4; + interface RedisEntry { bytes: Uint8Array; tags: readonly string[]; + generation: string | null; absoluteDeadlineMs: number | null; slidingMs: number | null; expiresAtMs: number | null; @@ -122,6 +138,7 @@ function slidingRefreshExpiry(entry: RedisEntry, nowMs: number): number | null { function requirePrefix(value: string | undefined): string { const prefix = value ?? DEFAULT_PREFIX; + assertWellFormedCacheString(prefix, "keyPrefix"); if (prefix.includes("{") || prefix.includes("}")) { throw new Error("keyPrefix must not contain braces"); } @@ -132,6 +149,7 @@ function encodeEnvelope(entry: RedisEntry): Buffer { const meta = new TextEncoder().encode( JSON.stringify({ tags: entry.tags, + generation: entry.generation, absoluteDeadlineMs: entry.absoluteDeadlineMs, slidingMs: entry.slidingMs, expiresAtMs: entry.expiresAtMs, @@ -170,13 +188,22 @@ function decodeEnvelope(raw: Uint8Array): RedisEntry { if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== "string")) { throw new Error("invalid cache envelope"); } + const validatedTags = validateCacheTags(tags as string[]); + const generation = meta["generation"]; + if ( + generation !== undefined && + (typeof generation !== "string" || !/^[0-9a-f]{32}$/u.test(generation)) + ) { + throw new Error("invalid cache envelope"); + } const lastComputeMs = meta["lastComputeMs"]; if (typeof lastComputeMs !== "number" || !Number.isFinite(lastComputeMs)) { throw new Error("invalid cache envelope"); } return { bytes: raw.subarray(5 + metaLen).slice(), - tags: [...tags], + tags: validatedTags, + generation: generation ?? null, absoluteDeadlineMs: asFiniteOrNull(meta["absoluteDeadlineMs"]), slidingMs: asFiniteOrNull(meta["slidingMs"]), expiresAtMs: asFiniteOrNull(meta["expiresAtMs"]), @@ -211,87 +238,160 @@ export function createRedisCacheStore( return `${prefix}t:${tag}`; } + function tagMember(formatted: string, generation: string): string { + return `${TAG_MEMBER_SEPARATOR}${generation}${TAG_MEMBER_SEPARATOR}${formatted}`; + } + + function parseTagMember( + member: string, + ): + | { readonly formatted: string; readonly generation: string | null } + | undefined { + if (!member.startsWith(TAG_MEMBER_SEPARATOR)) { + return { formatted: member, generation: null }; + } + const separator = member.indexOf(TAG_MEMBER_SEPARATOR, 1); + if (separator === -1) { + return undefined; + } + const generation = member.slice(1, separator); + const formatted = member.slice(separator + 1); + if (!/^[0-9a-f]{32}$/u.test(generation) || formatted.length === 0) { + return undefined; + } + return { formatted, generation }; + } + async function forgetTags( formatted: string, - tags: readonly string[], + entry: Pick, ): Promise { - for (const tag of tags) { - await redis.srem(tagKey(tag), formatted); + const member = + entry.generation === null + ? formatted + : tagMember(formatted, entry.generation); + for (const tag of entry.tags) { + await redis.srem(tagKey(tag), member); } } async function rememberTags( formatted: string, - tags: readonly string[], + entry: Pick, ): Promise { - for (const tag of tags) { - await redis.sadd(tagKey(tag), formatted); + if (entry.generation === null) { + throw new Error("new cache entries require a generation"); + } + const member = tagMember(formatted, entry.generation); + for (const tag of entry.tags) { + await redis.sadd(tagKey(tag), member); } } - async function readEntry(formatted: string): Promise { + async function readEntry( + formatted: string, + ): Promise<{ readonly entry: RedisEntry; readonly raw: Buffer } | null> { const raw = await redis.getBuffer(entryKey(formatted)); if (raw === null) { return null; } - return decodeEnvelope(raw); - } - - async function writeEntry( - formatted: string, - entry: RedisEntry, - ): Promise { - await redis.set(entryKey(formatted), encodeEnvelope(entry)); + return { entry: decodeEnvelope(raw), raw }; } async function compareAndSetEntry( formatted: string, - expected: Uint8Array, + expected: Buffer, next: RedisEntry, - ): Promise { + ): Promise { + const nextRaw = encodeEnvelope(next); const replaced = await redis.eval( COMPARE_AND_SET, 1, entryKey(formatted), - Buffer.from(expected), - encodeEnvelope(next), + expected, + nextRaw, + ); + return replaced === 1 ? nextRaw : null; + } + + async function compareAndDeleteEntry( + formatted: string, + expected: Buffer, + ): Promise { + const deleted = await redis.eval( + COMPARE_AND_DELETE, + 1, + entryKey(formatted), + expected, ); - return replaced === 1; + return deleted === 1; } - async function purge(formatted: string, entry: RedisEntry): Promise { - await redis.del(entryKey(formatted)); - await forgetTags(formatted, entry.tags); + async function purge( + formatted: string, + raw: Buffer, + entry: RedisEntry, + ): Promise { + let observedRaw = raw; + let observedEntry = entry; + for (let attempt = 0; attempt < MAX_COMPARE_DELETE_ATTEMPTS; attempt += 1) { + if (await compareAndDeleteEntry(formatted, observedRaw)) { + await forgetTags(formatted, observedEntry); + return true; + } + if (entry.generation === null) { + return false; + } + let current: { readonly entry: RedisEntry; readonly raw: Buffer } | null; + try { + current = await readEntry(formatted); + } catch { + return false; + } + if (current === null || current.entry.generation !== entry.generation) { + return false; + } + observedRaw = current.raw; + observedEntry = current.entry; + } + return false; } const store: CacheStore = { async get(key, codec) { const formatted = formatCacheKey(key); try { - const raw = await redis.getBuffer(entryKey(formatted)); - if (raw === null) { + const fetched = await redis.getBuffer(entryKey(formatted)); + if (fetched === null) { logOutcome(logger, "miss", key.namespace); return { status: "miss" }; } + let raw = fetched; let entry: RedisEntry; try { entry = decodeEnvelope(raw); } catch (error) { - await redis.del(entryKey(formatted)); + await compareAndDeleteEntry(formatted, raw); logOutcome(logger, "error", key.namespace); return { status: "error", error }; } const nowMs = clockMs(clock); if (isExpired(entry, nowMs)) { - await purge(formatted, entry); + await purge(formatted, raw, entry); logOutcome(logger, "miss", key.namespace); return { status: "miss" }; } const refreshedExpiresAtMs = slidingRefreshExpiry(entry, nowMs); if (refreshedExpiresAtMs !== null) { const refreshed = { ...entry, expiresAtMs: refreshedExpiresAtMs }; - if (await compareAndSetEntry(formatted, raw, refreshed)) { + const refreshedRaw = await compareAndSetEntry( + formatted, + raw, + refreshed, + ); + if (refreshedRaw !== null) { entry = refreshed; + raw = refreshedRaw; } } try { @@ -309,7 +409,7 @@ export function createRedisCacheStore( logOutcome(logger, "hit", key.namespace); return hit; } catch (error) { - await purge(formatted, entry); + await purge(formatted, raw, entry); logOutcome(logger, "error", key.namespace); return { status: "error", error }; } @@ -322,27 +422,31 @@ export function createRedisCacheStore( async set(key, value, codec, setOptions) { const formatted = formatCacheKey(key); const nowMs = clockMs(clock); + const tags = validateCacheTags(setOptions?.tags ?? []); const bytes = codec.encode(value).slice(); - const tags = [...(setOptions?.tags ?? [])]; const deadlines = ttlDeadlines(nowMs, setOptions?.ttl); try { - let previous: RedisEntry | null; + let previous: { + readonly entry: RedisEntry; + readonly raw: Buffer; + } | null; try { previous = await readEntry(formatted); } catch { previous = null; - await redis.del(entryKey(formatted)); - } - if (previous !== null) { - await forgetTags(formatted, previous.tags); } - await writeEntry(formatted, { + const next: RedisEntry = { bytes, tags, + generation: randomBytes(16).toString("hex"), lastComputeMs: setOptions?.lastComputeMs ?? 0, ...deadlines, - }); - await rememberTags(formatted, tags); + }; + await redis.set(entryKey(formatted), encodeEnvelope(next)); + await rememberTags(formatted, next); + if (previous !== null) { + await forgetTags(formatted, previous.entry); + } return { status: "hit", value: true }; } catch (error) { return { status: "error", error }; @@ -352,13 +456,13 @@ export function createRedisCacheStore( async delete(key) { const formatted = formatCacheKey(key); try { - const entry = await readEntry(formatted); - if (entry === null) { + const current = await readEntry(formatted); + if (current === null) { return { status: "hit", value: false }; } - const expired = isExpired(entry, clockMs(clock)); - await purge(formatted, entry); - return { status: "hit", value: !expired }; + const expired = isExpired(current.entry, clockMs(clock)); + const deleted = await purge(formatted, current.raw, current.entry); + return { status: "hit", value: deleted && !expired }; } catch (error) { return { status: "error", error }; } @@ -393,29 +497,41 @@ export function createRedisCacheStore( }, async invalidateTags(tags) { + const validatedTags = validateCacheTags(tags); try { let removed = 0; - for (const tag of tags) { + for (const tag of validatedTags) { const members = await redis.smembers(tagKey(tag)); - for (const formatted of members) { - let entry: RedisEntry | null; + for (const member of members) { + const parsed = parseTagMember(member); + if (parsed === undefined) { + await redis.srem(tagKey(tag), member); + continue; + } + const raw = await redis.getBuffer(entryKey(parsed.formatted)); + if (raw === null) { + await redis.srem(tagKey(tag), member); + continue; + } + let entry: RedisEntry; try { - entry = await readEntry(formatted); + entry = decodeEnvelope(raw); } catch { - await redis.del(entryKey(formatted)); - entry = null; - } - if (entry === null) { - await redis.srem(tagKey(tag), formatted); + if (await compareAndDeleteEntry(parsed.formatted, raw)) { + await redis.srem(tagKey(tag), member); + } continue; } - if (!entry.tags.includes(tag)) { - await redis.srem(tagKey(tag), formatted); + if ( + entry.generation !== parsed.generation || + !entry.tags.includes(tag) + ) { + await redis.srem(tagKey(tag), member); continue; } - await redis.del(entryKey(formatted)); - await forgetTags(formatted, entry.tags); - removed += 1; + if (await purge(parsed.formatted, raw, entry)) { + removed += 1; + } } } return { status: "hit", value: removed }; diff --git a/packages/cache-upstash-redis/src/index.test.ts b/packages/cache-upstash-redis/src/index.test.ts index ad15e01..a5c0d9b 100644 --- a/packages/cache-upstash-redis/src/index.test.ts +++ b/packages/cache-upstash-redis/src/index.test.ts @@ -199,6 +199,58 @@ describe("Upstash Redis adapter", () => { expect(typeof seen?.args[1]).toBe("string"); }); + it("passes compare-and-delete through the Upstash eval signature", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const codec = jsonCodec(); + const address = { namespace: "ttl", key: "expired" }; + let seen: { keys: string[]; args: unknown[] } | undefined; + const observing: UpstashRedisCacheClient = { + get: (key) => redis.get(key), + set: (key, value) => redis.set(key, value), + del: (...keys) => redis.del(...keys), + sadd: (key, ...members) => redis.sadd(key, ...members), + srem: (key, ...members) => redis.srem(key, ...members), + smembers: (key) => redis.smembers(key), + ping: () => redis.ping(), + async eval(script, keys, args) { + if (script.includes("DEL")) { + seen = { keys, args: [...args] }; + } + return redis.eval(script, keys, args); + }, + }; + const store = createUpstashRedisCacheStore({ + clock, + redis: observing, + keyPrefix, + }); + await store.set(address, "old", codec, { ttl: { absoluteMs: 1_000 } }); + clock.advance(1_000); + expect(await store.get(address, codec)).toEqual({ status: "miss" }); + expect(seen?.keys).toEqual([`${keyPrefix}e:ttl:expired`]); + expect(seen?.args).toHaveLength(1); + expect(typeof seen?.args[0]).toBe("string"); + }); + + it("uses the observed Upstash wire value for malformed cleanup", async () => { + const clock = createControllableClock(START); + const keyPrefix = nextPrefix(); + const wireKey = `${keyPrefix}e:decode:noncanonical`; + await redis.set(wireKey, "YQ"); + const store = createUpstashRedisCacheStore({ clock, redis, keyPrefix }); + + expect( + ( + await store.get( + { namespace: "decode", key: "noncanonical" }, + jsonCodec(), + ) + ).status, + ).toBe("error"); + expect(await redis.get(wireKey)).toBeNull(); + }); + it("rejects a keyPrefix that would steal the hash tag", () => { expect(() => createUpstashRedisCacheStore({ @@ -208,4 +260,14 @@ describe("Upstash Redis adapter", () => { }), ).toThrow(/braces/u); }); + + it("rejects an ill-formed Unicode keyPrefix", () => { + expect(() => + createUpstashRedisCacheStore({ + clock: createControllableClock(START), + redis, + keyPrefix: "prefix-\uD800", + }), + ).toThrow(/well-formed Unicode/u); + }); }); diff --git a/packages/cache-upstash-redis/src/index.ts b/packages/cache-upstash-redis/src/index.ts index 77901d1..ce5e17c 100644 --- a/packages/cache-upstash-redis/src/index.ts +++ b/packages/cache-upstash-redis/src/index.ts @@ -39,16 +39,6 @@ export interface UpstashRedisCacheStoreOptions extends CacheDependencies { readonly keyPrefix?: string; } -function asWireArg(value: string | Buffer | number): string { - if (typeof value === "number") { - return String(value); - } - if (typeof value === "string") { - return value; - } - return value.toString("base64"); -} - /** * REST/JSON cannot carry the binary envelope ioredis `getBuffer` / `set` * use. Encode on the wire as base64 so Lua CAS still compares the same @@ -57,6 +47,18 @@ function asWireArg(value: string | Buffer | number): string { function adaptUpstashRedisClient( redis: UpstashRedisCacheClient, ): RedisCacheClient { + const observedWireValues = new WeakMap(); + + function asWireArg(value: string | Buffer | number): string { + if (typeof value === "number") { + return String(value); + } + if (typeof value === "string") { + return value; + } + return observedWireValues.get(value) ?? value.toString("base64"); + } + return { async getBuffer(key) { const raw = await redis.get(key); @@ -66,7 +68,9 @@ function adaptUpstashRedisClient( if (typeof raw !== "string") { throw new Error("invalid upstash envelope"); } - return Buffer.from(raw, "base64"); + const decoded = Buffer.from(raw, "base64"); + observedWireValues.set(decoded, raw); + return decoded; }, set(key, value) { return redis.set(key, value.toString("base64")); diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index 5e6b945..32b3684 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -74,6 +74,16 @@ export function validateReleaseTag(options?: { export function parseNpmJson(stdout: string): unknown; +export function validatePackedManifest( + source: PublicPackageManifest, + packed: PublicPackageManifest, +): void; + +export function validateReleaseInventory( + directory: string, + tarballs: readonly string[], +): Promise; + export function decidePublication( localIntegrity: string, registryIntegrity: string | null, diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index ea08d34..210e8fb 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -1,17 +1,16 @@ import { spawnSync } from "node:child_process"; import { createHash, timingSafeEqual } from "node:crypto"; import { - mkdtemp, mkdir, + lstat, readFile, readdir, - rm, stat, writeFile, } from "node:fs/promises"; -import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { isDeepStrictEqual } from "node:util"; const REPOSITORY_URL = "git+https://github.com/pegma-dev/cache-core.git"; const NODE_RANGE = ">=22"; @@ -70,7 +69,7 @@ async function readJson(path) { } function sameJson(left, right) { - return JSON.stringify(left) === JSON.stringify(right); + return isDeepStrictEqual(left, right); } function safeEqual(left, right) { @@ -351,26 +350,18 @@ function gitCommand() { return process.platform === "win32" ? "git.exe" : "git"; } +function tarCommand() { + return process.platform === "win32" ? "tar.exe" : "tar"; +} + 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 exportSpecifiers(manifest) { - if ( - manifest.exports === null || - typeof manifest.exports !== "object" || - Array.isArray(manifest.exports) - ) { - fail(`${manifest.name} must declare object-form exports`); - } - return Object.keys(manifest.exports).map((key) => - key === "." ? manifest.name : `${manifest.name}${key.slice(1)}`, - ); -} - function exportTargets(value) { if (typeof value === "string") { return [value]; @@ -586,6 +577,23 @@ export async function validateRepository(options = {}) { fail("release preparation requires a clean checkout"); } } + if (options.expectedReleaseCommit !== undefined) { + if (!/^[0-9a-f]{40,64}$/iu.test(options.expectedReleaseCommit)) { + fail("an exact release event commit is required"); + } + const head = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: root, + capture: true, + }).stdout.trim(); + if ( + !safeEqual( + head.toLowerCase(), + options.expectedReleaseCommit.toLowerCase(), + ) + ) { + fail("release checkout must match the release event commit"); + } + } if (options.requireMainAncestor) { const head = run(gitCommand(), ["rev-parse", "HEAD"], { cwd: root, @@ -654,39 +662,118 @@ function verifyPackedFiles(manifest, files) { } } -async function smokeTestTarballs(root, packageRecords) { - const directory = await mkdtemp(join(tmpdir(), "pegma-release-smoke-")); - try { - await writeFile( - join(directory, "package.json"), - '{"name":"pegma-release-smoke","private":true,"type":"module"}\n', +export function validatePackedManifest(source, packed) { + if (packed.name !== source.name || packed.version !== source.version) { + fail(`${source.name} packed manifest identity does not match its source`); + } + for (const hook of [ + "preinstall", + "install", + "postinstall", + "prepublish", + "preprepare", + "prepare", + "postprepare", + ]) { + if (Object.hasOwn(packed.scripts ?? {}, hook)) { + fail(`${source.name} packed manifest must not define ${hook}`); + } + } + for (const section of [ + "dependencies", + "devDependencies", + "optionalDependencies", + "peerDependencies", + ]) { + const sourcePins = Object.fromEntries( + Object.entries(source[section] ?? {}).filter(([name]) => + name.startsWith("@pegma/"), + ), ); - runNpm( - [ - "install", - "--ignore-scripts", - "--no-audit", - "--no-fund", - "--package-lock=false", - ...packageRecords.map(({ tarballPath }) => tarballPath), - ], - { cwd: directory, capture: true }, + const packedPins = Object.fromEntries( + Object.entries(packed[section] ?? {}).filter(([name]) => + name.startsWith("@pegma/"), + ), ); - for (const { manifest } of packageRecords) { - for (const specifier of exportSpecifiers(manifest)) { - run( - process.execPath, - [ - "--input-type=module", - "--eval", - `await import(${JSON.stringify(specifier)})`, - ], - { cwd: directory, capture: true }, - ); + if (!sameJson(packedPins, sourcePins)) { + fail(`${source.name} packed manifest changed its ${section} pins`); + } + for (const [name, version] of Object.entries(packedPins)) { + if (typeof version !== "string" || !STABLE_SEMVER.test(version)) { + fail(`${source.name} packed manifest must exactly pin ${name}`); } } - } finally { - await rm(directory, { recursive: true, force: true }); + } + const reviewedPackedFields = Object.fromEntries( + Object.keys(source).map((field) => [field, packed[field]]), + ); + if (!sameJson(reviewedPackedFields, source)) { + fail(`${source.name} packed manifest does not match its reviewed source`); + } +} + +function readPackedManifest(tarballPath) { + const extracted = run( + tarCommand(), + ["-xOf", tarballPath, "package/package.json"], + { capture: true }, + ).stdout; + try { + return JSON.parse(extracted); + } catch { + fail(`${basename(tarballPath)} contains an invalid package manifest`); + } +} + +function validatePackedArchive(manifest, tarballPath, npmFiles) { + const archiveEntries = run(tarCommand(), ["-tf", tarballPath], { + capture: true, + }) + .stdout.split(/\r?\n/u) + .map((entry) => entry.replace(/^\.\//u, "")) + .filter((entry) => entry !== "" && !entry.endsWith("/")); + if (archiveEntries.some((entry) => !entry.startsWith("package/"))) { + fail(`${manifest.name} tarball contains an invalid archive path`); + } + const archivePaths = archiveEntries + .map((entry) => entry.slice("package/".length)) + .sort(); + const reportedPaths = npmFiles.map(({ path }) => path).sort(); + if (!sameJson(archivePaths, reportedPaths)) { + fail(`${manifest.name} tarball inventory does not match npm pack metadata`); + } + verifyPackedFiles( + manifest, + archivePaths.map((path) => ({ path })), + ); +} + +export async function validateReleaseInventory(directory, tarballs) { + const directoryInfo = await lstat(directory); + if (directoryInfo.isSymbolicLink() || !directoryInfo.isDirectory()) { + fail("release output must be a regular directory"); + } + const expected = ["package-manifest.json", ...tarballs].sort(); + if (new Set(expected).size !== expected.length) { + fail("release inventory contains duplicate names"); + } + const entries = await readdir(directory, { withFileTypes: true }); + const actual = entries.map(({ name }) => name).sort(); + if (!sameJson(actual, expected)) { + fail("release directory inventory does not match the prepared manifest"); + } + for (const entry of entries) { + const info = await lstat(join(directory, entry.name)); + if ( + entry.name.startsWith(".") || + !entry.isFile() || + info.isSymbolicLink() || + !info.isFile() + ) { + fail( + `release inventory entry must be a regular visible file: ${entry.name}`, + ); + } } } @@ -767,6 +854,8 @@ export async function prepareRelease(options = {}) { } verifyPackedFiles(manifest, packed.files); const tarballPath = join(output, basename(packed.filename)); + validatePackedArchive(manifest, tarballPath, packed.files); + validatePackedManifest(manifest, readPackedManifest(tarballPath)); const hashes = hashTarball(await readFile(tarballPath)); if ( !safeEqual(hashes.integrity, packed.integrity) || @@ -780,6 +869,7 @@ export async function prepareRelease(options = {}) { directory: definition.directory, tarball: basename(tarballPath), tarballPath, + sha256: hashes.sha256, integrity: hashes.integrity, shasum: hashes.shasum, publish: tagVersion === undefined || manifest.version === tagVersion, @@ -789,8 +879,6 @@ export async function prepareRelease(options = {}) { manifest, }); } - await smokeTestTarballs(root, records); - if (releaseTag !== undefined) { for (const record of records.filter(({ publish }) => !publish)) { const registryIntegrity = queryRegistryIntegrity( @@ -818,6 +906,10 @@ export async function prepareRelease(options = {}) { }; const manifestPath = join(output, "package-manifest.json"); await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + await validateReleaseInventory( + output, + records.map(({ tarball }) => tarball), + ); return { manifestPath, manifest }; } @@ -846,6 +938,10 @@ async function verifyPreparedManifest(manifestPath) { if (!manifest.packages.some(({ publish }) => publish)) { fail("prepared package manifest has no release candidates"); } + await validateReleaseInventory( + dirname(manifestPath), + manifest.packages.map(({ tarball }) => tarball), + ); for (const [index, record] of manifest.packages.entries()) { const definition = RELEASE_PACKAGES[index]; const expectedTarball = `${definition.name @@ -856,6 +952,7 @@ async function verifyPreparedManifest(manifestPath) { record.tarball !== expectedTarball || !STABLE_SEMVER.test(record.version) || record.publish !== (record.version === tagVersion) || + typeof record.sha256 !== "string" || typeof record.integrity !== "string" || typeof record.shasum !== "string" || !Array.isArray(record.files) @@ -868,6 +965,7 @@ async function verifyPreparedManifest(manifestPath) { } const hashes = hashTarball(await readFile(tarball)); if ( + !safeEqual(hashes.sha256, record.sha256) || !safeEqual(hashes.integrity, record.integrity) || !safeEqual(hashes.shasum, record.shasum) ) { diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 9287ba6..66d4919 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -1,4 +1,12 @@ -import { existsSync, readFileSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -11,6 +19,8 @@ import { parseNpmJson, parsePnpmLockfileImporters, resolvedVersionSatisfies, + validatePackedManifest, + validateReleaseInventory, validateRepository, } from "../scripts/release-packages.mjs"; @@ -34,6 +44,18 @@ describe("release package metadata", () => { await expect(validateRepository()).resolves.toBeDefined(); }); + it("binds preparation to the expected checkout commit", async () => { + const head = execFileSync("git", ["rev-parse", "HEAD"], { + encoding: "utf8", + }).trim(); + await expect( + validateRepository({ expectedReleaseCommit: head }), + ).resolves.toBeDefined(); + await expect( + validateRepository({ expectedReleaseCommit: "0".repeat(40) }), + ).rejects.toThrow(/release event commit/u); + }); + it("keeps the exact public package inventory in dependency order", () => { expect(RELEASE_PACKAGES.map(({ name }) => name)).toEqual([ "@pegma/cache-core", @@ -461,6 +483,87 @@ packages: "sha512-cHJlcGFyZWQtdGFyYmFsbA==", ); }); + + it("revalidates the manifest extracted from a packed archive", () => { + const source = { + name: "@pegma/cache-redis", + version: "0.1.1", + dependencies: { + "@pegma/cache-core": "0.1.1", + "@pegma/spine": "0.1.2", + ioredis: "^5.8.2", + }, + scripts: { prepack: "tsc -p tsconfig.json" }, + }; + expect(() => + validatePackedManifest(source, structuredClone(source)), + ).not.toThrow(); + expect(() => + validatePackedManifest( + source, + Object.fromEntries( + Object.entries(structuredClone(source)).reverse(), + ) as typeof source, + ), + ).not.toThrow(); + expect(() => + validatePackedManifest(source, { + ...structuredClone(source), + gitHead: "0123456789abcdef0123456789abcdef01234567", + }), + ).not.toThrow(); + expect(() => + validatePackedManifest(source, { + ...structuredClone(source), + scripts: { install: "node install.mjs" }, + }), + ).toThrow(/must not define install/u); + expect(() => + validatePackedManifest(source, { + ...structuredClone(source), + dependencies: { + ...source.dependencies, + "@pegma/cache-core": "^0.1.1", + }, + }), + ).toThrow(/dependencies pins/u); + expect(() => + validatePackedManifest(source, { + ...structuredClone(source), + dependencies: { ioredis: "^5.8.2" }, + }), + ).toThrow(/dependencies pins/u); + expect(() => + validatePackedManifest(source, { + ...structuredClone(source), + type: "commonjs", + dependencies: { + ...source.dependencies, + ioredis: "https://example.invalid/archive.tgz", + }, + }), + ).toThrow(/reviewed source/u); + }); + + it("accepts only the sealed release directory inventory", async () => { + const directory = mkdtempSync(join(tmpdir(), "pegma-release-test-")); + try { + writeFileSync(join(directory, "package-manifest.json"), "{}\n"); + writeFileSync(join(directory, "pegma-cache-core-0.1.1.tgz"), "tarball"); + await expect( + validateReleaseInventory(directory, ["pegma-cache-core-0.1.1.tgz"]), + ).resolves.toBeUndefined(); + writeFileSync( + join(directory, ".npmrc"), + "registry=https://example.invalid\n", + ); + await expect( + validateReleaseInventory(directory, ["pegma-cache-core-0.1.1.tgz"]), + ).rejects.toThrow(/inventory/u); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); }); describe("release source authentication", () => { @@ -475,28 +578,63 @@ 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(prepare).toContain("npm install --global npm@11.18.0"); + expect(prepare).toContain("Authenticate the release tag"); + expect(prepare.indexOf("Authenticate the release tag")).toBeLessThan( + prepare.indexOf("actions/checkout"), + ); + expect(prepare).toContain("ref: ${{ github.sha }}"); + expect(prepare).toContain("persist-credentials: false"); + expect(prepare).toContain( + "npm install --global npm@11.18.0 --ignore-scripts", + ); expect(prepare).toContain("pnpm run release:pack"); expect(prepare).toContain("pnpm run test:redis"); expect(prepare).toContain("pnpm run test:azure-redis"); expect(prepare).toContain("pnpm run test:elasticache"); expect(prepare).toContain("pnpm run test:upstash-redis"); expect(prepare).toContain("16379:6379"); + expect(prepare).toContain("manifest_digest:"); + expect(prepare).toContain("include-hidden-files: false"); + expect(smoke).toContain("needs: prepare"); + expect(smoke).toContain("contents: read"); + expect(smoke).not.toContain("id-token: write"); + expect(smoke).not.toContain("actions/checkout"); + expect(smoke).toContain("Install and import the prepared packages"); + expect(smoke).toContain('createHash("sha256").update(tarball)'); + expect(smoke).toContain("release directory inventory does not match"); + expect(smoke).toContain("Object.keys(installedManifest.exports)"); expect(publish).toContain("id-token: write"); + expect(publish).toContain("needs: [prepare, smoke]"); + expect(publish).toContain("Re-authenticate the release tag"); + expect(publish).not.toContain("actions/checkout"); expect(publish).not.toContain("npm ci"); - expect(publish).toContain("npm install --global npm@11.18.0"); + expect(publish).toContain( + "npm install --global npm@11.18.0 --ignore-scripts", + ); expect(publish).not.toContain("pnpm install"); expect(publish).not.toContain("corepack"); expect(publish).not.toContain("pnpm run"); expect(publish).not.toContain("pnpm/action-setup"); - expect(publish).toContain("node scripts/release-packages.mjs publish"); + expect(publish).not.toContain("scripts/release-packages.mjs"); + expect(publish).toContain( + "MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }}", + ); + expect(publish).toContain('name.startsWith("ACTIONS_ID_TOKEN_")'); + expect(publish).toContain("NPM_CONFIG_USERCONFIG"); + expect(publish).toContain("NPM_CONFIG_GLOBALCONFIG"); + expect(publish).toContain('"--tag",'); + expect(publish).toContain('"--provenance",'); + expect(publish).toContain('"--ignore-scripts",'); expect(workflow).not.toContain("workflow_dispatch"); expect(workflow).toContain("retention-days: 30"); });