From bcd95618f60c221ea7d46dc4c53a2871572b393f Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 14:37:22 -0500 Subject: [PATCH 1/4] Tighten release preparation and durable policy consistency --- .github/workflows/ci.yml | 5 + .github/workflows/publish.yml | 450 ++++++++++++++++++++++-- .prettierrc.json | 3 + README.md | 12 +- docs/RELEASING.md | 26 +- packages/rate-limit/README.md | 29 +- packages/rate-limit/src/durable.test.ts | 279 ++++++++++++--- packages/rate-limit/src/durable.ts | 269 +++++++++++--- packages/rate-limit/src/memory.ts | 17 +- packages/rate-limit/src/policy.ts | 10 + scripts/release-package.mjs | 252 +++++++++++-- test/release-package.test.ts | 209 +++++++++++ vitest.config.ts | 2 +- 13 files changed, 1363 insertions(+), 200 deletions(-) create mode 100644 .prettierrc.json create mode 100644 test/release-package.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ec8e755..b2f5b21 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: @@ -49,5 +51,8 @@ jobs: - name: Check types run: pnpm run check + - name: Check release metadata + run: pnpm run release:check + - name: Run tests run: pnpm test diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 183a9df..d995d93 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 one prepared tarball from an authenticated stable release tag. # Authentication is npm trusted-publisher OIDC only; no token fallback exists. name: Publish @@ -17,40 +17,67 @@ concurrency: jobs: prepare: runs-on: ubuntu-latest + outputs: + manifest-digest: ${{ steps.pack.outputs.manifest-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 tag shell: bash run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish" + 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 is not a permitted stable version" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-fA-F]{40}$ ]]; then + echo "::error::Release commit must be a full object ID" + exit 1 + fi if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then echo "::error::RELEASE_ALLOWED_SIGNERS is required" exit 1 fi + + verify_repo="$(mktemp -d "${RUNNER_TEMP}/rate-limit-tag.XXXXXX")" allowed_signers="${RUNNER_TEMP}/release-allowed-signers" umask 077 printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" - git config --local gpg.format ssh - git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git init --bare "${verify_repo}" + git -C "${verify_repo}" remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" + git -C "${verify_repo}" config gpg.format ssh + git -C "${verify_repo}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${verify_repo}" fetch --no-tags origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + test "$(git -C "${verify_repo}" cat-file -t "refs/tags/${RELEASE_TAG}")" = "tag" + git -C "${verify_repo}" verify-tag "refs/tags/${RELEASE_TAG}" + tagged_commit="$(git -C "${verify_repo}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + test "${tagged_commit}" = "${RELEASE_COMMIT,,}" + git -C "${verify_repo}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main + + - name: Check out the authenticated commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 0 - 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 @@ -63,10 +90,24 @@ jobs: run: pnpm install --frozen-lockfile - name: Run the gate - run: pnpm run format:check && pnpm run check && pnpm test + run: | + pnpm run format:check + pnpm run check + pnpm test + pnpm run release:check - - 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}" + - name: Prepare and seal the release tarball + id: pack + shell: bash + run: | + set -euo pipefail + pnpm run release:pack -- \ + --require-clean \ + --require-main-ancestor \ + --require-release-tag \ + --expected-release-commit "${RELEASE_COMMIT}" + manifest_digest="$(sha256sum .release/package-manifest.json | awk '{print $1}')" + printf 'manifest-digest=%s\n' "${manifest_digest}" >> "${GITHUB_OUTPUT}" - name: Upload the prepared release uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 @@ -74,40 +115,393 @@ jobs: name: rate-limit-release-${{ github.run_id }} path: .release/ if-no-files-found: error - include-hidden-files: true + include-hidden-files: false overwrite: true retention-days: 30 - publish: + smoke: needs: prepare runs-on: ubuntu-latest - environment: npm-publish permissions: contents: read - id-token: write env: + CI: "1" RELEASE_TAG: ${{ github.event.release.tag_name }} RELEASE_COMMIT: ${{ github.sha }} + ARTIFACT_DIR: ${{ runner.temp }}/rate-limit-release steps: - - name: Check out the exact release tag + - name: Check out the authenticated 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 npm + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Download the prepared release + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: rate-limit-release-${{ github.run_id }} + path: ${{ runner.temp }}/rate-limit-release + + - name: Import from an isolated consumer + run: node scripts/release-package.mjs smoke --manifest "${ARTIFACT_DIR}/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 }} + MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }} + ARTIFACT_DIR: ${{ runner.temp }}/rate-limit-release + + steps: + - name: Re-authenticate the release tag + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish" + 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 is not a permitted stable version" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-fA-F]{40}$ ]]; then + echo "::error::Release commit must be a full object ID" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS is required" + exit 1 + fi + + verify_repo="$(mktemp -d "${RUNNER_TEMP}/rate-limit-tag.XXXXXX")" + allowed_signers="${RUNNER_TEMP}/release-allowed-signers" + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git init --bare "${verify_repo}" + git -C "${verify_repo}" remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" + git -C "${verify_repo}" config gpg.format ssh + git -C "${verify_repo}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${verify_repo}" fetch --no-tags origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + test "$(git -C "${verify_repo}" cat-file -t "refs/tags/${RELEASE_TAG}")" = "tag" + git -C "${verify_repo}" verify-tag "refs/tags/${RELEASE_TAG}" + tagged_commit="$(git -C "${verify_repo}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + test "${tagged_commit}" = "${RELEASE_COMMIT,,}" + git -C "${verify_repo}" 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 - registry-url: https://registry.npmjs.org package-manager-cache: false - name: Download the prepared release uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: rate-limit-release-${{ github.run_id }} - path: .release + path: ${{ runner.temp }}/rate-limit-release + + - name: Verify and publish the prepared tarball + shell: bash + run: | + set -euo pipefail + node <<'NODE' + const { createHash, timingSafeEqual } = require("node:crypto"); + const { + chmodSync, + lstatSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, + } = require("node:fs"); + const { tmpdir } = require("node:os"); + const { basename, join, resolve } = require("node:path"); + const { spawnSync } = require("node:child_process"); + + const PACKAGE_NAME = "@pegma/rate-limit"; + const REGISTRY = "https://registry.npmjs.org/"; + const fail = (message) => { + throw new Error(message); + }; + const same = (left, right) => { + const leftBytes = Buffer.from(left); + const rightBytes = Buffer.from(right); + return ( + leftBytes.length === rightBytes.length && + timingSafeEqual(leftBytes, rightBytes) + ); + }; + const exactKeys = (value, keys) => + typeof value === "object" && + value !== null && + !Array.isArray(value) && + JSON.stringify(Object.keys(value).sort()) === + JSON.stringify([...keys].sort()); + + const artifactDirectory = resolve(process.env.ARTIFACT_DIR); + const entries = readdirSync(artifactDirectory).sort(); + const tarballs = entries.filter((name) => + /^pegma-rate-limit-\d+\.\d+\.\d+\.tgz$/u.test(name), + ); + if ( + tarballs.length !== 1 || + JSON.stringify(entries) !== + JSON.stringify(["package-manifest.json", tarballs[0]].sort()) + ) { + fail("release artifact must contain exactly the manifest and tarball"); + } + for (const name of entries) { + const metadata = lstatSync(join(artifactDirectory, name)); + if (!metadata.isFile() || metadata.isSymbolicLink()) { + fail("release artifact entries must be regular files"); + } + } + + const manifestPath = join(artifactDirectory, "package-manifest.json"); + const manifestBytes = readFileSync(manifestPath); + const manifestDigest = createHash("sha256") + .update(manifestBytes) + .digest("hex"); + if ( + !/^[0-9a-f]{64}$/u.test(process.env.MANIFEST_DIGEST) || + !same(manifestDigest, process.env.MANIFEST_DIGEST) + ) { + fail("manifest digest does not match preparation output"); + } + const manifest = JSON.parse(manifestBytes.toString("utf8")); + if ( + !exactKeys(manifest, [ + "schemaVersion", + "gitCommit", + "releaseTag", + "package", + ]) || + !exactKeys(manifest.package, [ + "name", + "version", + "tarball", + "integrity", + "sha256", + "files", + ]) || + manifest.schemaVersion !== 2 || + manifest.package.name !== PACKAGE_NAME || + !/^\d+\.\d+\.\d+$/u.test(manifest.package.version) || + manifest.package.version === "0.0.0" || + !/^[0-9a-f]{40}$/u.test(manifest.gitCommit) || + manifest.gitCommit !== process.env.RELEASE_COMMIT || + manifest.releaseTag !== process.env.RELEASE_TAG || + manifest.releaseTag !== `v${manifest.package.version}` || + manifest.package.tarball !== tarballs[0] || + !/^[0-9a-f]{64}$/u.test(manifest.package.sha256) || + !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test( + manifest.package.integrity, + ) || + !Array.isArray(manifest.package.files) + ) { + fail("prepared release manifest is invalid"); + } + const packedPaths = []; + for (const file of manifest.package.files) { + if ( + !exactKeys(file, ["path", "size"]) || + typeof file.path !== "string" || + !Number.isSafeInteger(file.size) || + file.size < 0 || + (![ + "package.json", + "README.md", + "LICENSE", + ].includes(file.path) && + !file.path.startsWith("dist/")) + ) { + fail("prepared package file inventory is invalid"); + } + packedPaths.push(file.path); + } + if ( + new Set(packedPaths).size !== packedPaths.length || + !["package.json", "README.md", "LICENSE"].every((path) => + packedPaths.includes(path), + ) + ) { + fail("prepared package file inventory is incomplete"); + } + + const tarball = resolve(artifactDirectory, manifest.package.tarball); + if ( + basename(tarball) !== manifest.package.tarball || + !tarball.startsWith(`${artifactDirectory}/`) + ) { + fail("prepared tarball path is invalid"); + } + const tarballBytes = readFileSync(tarball); + const sha256 = createHash("sha256").update(tarballBytes).digest("hex"); + const integrity = `sha512-${createHash("sha512") + .update(tarballBytes) + .digest("base64")}`; + if ( + !same(sha256, manifest.package.sha256) || + !same(integrity, manifest.package.integrity) + ) { + fail("prepared tarball digest is invalid"); + } + + const configDirectory = mkdtempSync( + join(process.env.RUNNER_TEMP || tmpdir(), "rate-limit-npm-config-"), + ); + const publishDirectory = mkdtempSync( + join(process.env.RUNNER_TEMP || tmpdir(), "rate-limit-npm-cwd-"), + ); + const userConfig = join(configDirectory, "user.npmrc"); + const globalConfig = join(configDirectory, "global.npmrc"); + writeFileSync(userConfig, "", { mode: 0o600 }); + writeFileSync(globalConfig, "", { mode: 0o600 }); + chmodSync(userConfig, 0o600); + chmodSync(globalConfig, 0o600); + + const keep = new Set([ + "CI", + "HOME", + "PATH", + "RUNNER_TEMP", + "SYSTEMROOT", + "TEMP", + "TMP", + "TMPDIR", + ]); + const npmEnvironment = {}; + for (const [key, value] of Object.entries(process.env)) { + const upper = key.toUpperCase(); + if ( + value !== undefined && + (keep.has(upper) || + upper.startsWith("GITHUB_") || + upper.startsWith("ACTIONS_ID_TOKEN_")) + ) { + npmEnvironment[key] = value; + } + } + npmEnvironment.NPM_CONFIG_USERCONFIG = userConfig; + npmEnvironment.NPM_CONFIG_GLOBALCONFIG = globalConfig; + npmEnvironment.NPM_CONFIG_CACHE = join(configDirectory, "cache"); + npmEnvironment.NPM_CONFIG_REGISTRY = REGISTRY; + + const runNpm = (arguments_, allowFailure = false) => { + const result = spawnSync("npm", arguments_, { + cwd: publishDirectory, + encoding: "utf8", + env: npmEnvironment, + stdio: allowFailure ? "pipe" : "inherit", + }); + if (result.error) throw result.error; + if (!allowFailure && result.status !== 0) { + fail(`npm ${arguments_.join(" ")} failed`); + } + return result; + }; + const npmVersion = runNpm(["--version"], true).stdout.trim(); + const versionMatch = /^(\d+)\.(\d+)\.(\d+)/u.exec(npmVersion); + if ( + versionMatch === null || + Number(versionMatch[1]) < 11 || + (Number(versionMatch[1]) === 11 && + (Number(versionMatch[2]) < 5 || + (Number(versionMatch[2]) === 5 && + Number(versionMatch[3]) < 1))) + ) { + fail("npm 11.5.1 or newer is required for trusted publishing"); + } + + const registryIntegrity = () => { + const result = runNpm( + [ + "view", + `${PACKAGE_NAME}@${manifest.package.version}`, + "dist.integrity", + "--json", + "--registry", + REGISTRY, + ], + true, + ); + if (result.status === 0) { + const value = JSON.parse(result.stdout); + if (typeof value !== "string") { + fail("registry returned invalid integrity metadata"); + } + return value; + } + if (/\bE404\b/u.test(`${result.stdout}\n${result.stderr}`)) { + return null; + } + fail("registry lookup failed"); + }; - - name: Publish the verified prepared tarball - run: node scripts/release-package.mjs publish --expected-release-commit "${RELEASE_COMMIT}" + try { + const existing = registryIntegrity(); + if (existing !== null) { + if (!same(existing, integrity)) { + fail("registry version has different integrity"); + } + process.stdout.write("Registry integrity matches; skipping publish.\n"); + process.exitCode = 0; + } else { + runNpm([ + "publish", + tarball, + "--registry", + REGISTRY, + "--access", + "public", + "--provenance", + "--ignore-scripts", + ]); + let confirmed = false; + for (let attempt = 0; attempt < 6; attempt += 1) { + const observed = registryIntegrity(); + if (observed !== null && same(observed, integrity)) { + confirmed = true; + break; + } + if (attempt < 5) { + Atomics.wait( + new Int32Array(new SharedArrayBuffer(4)), + 0, + 0, + 2 ** attempt * 1000, + ); + } + } + if (!confirmed) { + fail("published integrity did not become visible"); + } + } + } finally { + rmSync(configDirectory, { force: true, recursive: true }); + rmSync(publishDirectory, { force: true, recursive: true }); + } + NODE diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..168d9d2 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,3 @@ +{ + "endOfLine": "auto" +} diff --git a/README.md b/README.md index 5b5e0dc..49b4b33 100644 --- a/README.md +++ b/README.md @@ -35,14 +35,20 @@ records, and malformed time all fail closed with a millisecond `retryAfter`. Its sweep uses version-conditional deletes. Policy names and limiter keys are host-owned opaque strings, but they must be -primitive and non-blank. Whitespace is preserved once that validation passes. -Ill-formed Unicode is rejected so UTF-8 hashing remains injective before the -cryptographic digest. +primitive and non-blank. Keys are limited to 512 UTF-16 code units before +either tier scans or hashes them. Whitespace is preserved once validation +passes. Ill-formed Unicode is rejected so UTF-8 hashing remains injective +before the cryptographic digest. The durable tier stores only domain-separated SHA-256 hashes of those values, not the raw inputs, keeping entity sizes bounded. These deterministic hashes are pseudonymous, not anonymous: predictable inputs can still be guessed, and the same key remains linkable within one policy. +Durable storage binds each policy name to its initial `limit` and `windowMs`. +Conflicting instances fail closed; rolling configuration changes use a +versioned policy name or a coordinated store reset. Sweeps retain ended windows +for a configurable clock-skew grace, 60 seconds by default. + Fixed windows have a documented edge: a burst crossing a boundary can briefly admit nearly twice the configured limit. This package does not claim to be DDoS or volumetric protection, and it does not provide HTTP middleware or diff --git a/docs/RELEASING.md b/docs/RELEASING.md index fb34da3..5009062 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -10,15 +10,25 @@ npm could not configure a trusted publisher until `@pegma/rate-limit` existed. The release tool verifies the exact public workspace inventory, stable package version, exact Pegma dependency pins, matching lockfile, package metadata, README and LICENSE, prepack build, test exclusion, dist-only allowlist, and -exports. Packing builds once, checks the complete file inventory and hashes, -and imports every export from a clean consumer installation. +exports. Preparation builds once and checks the complete file inventory and +hashes; the separate smoke job imports every export from a clean consumer +installation. The prepared `package-manifest.json` records the source commit, optional -release tag, tarball filename, SHA-1, SHA-512 integrity, and packed files. +release tag, tarball filename, SHA-256, SHA-512 integrity, and packed files. `release:registry:check` revalidates those local bytes before comparing their exact integrity with npm. Only npm `E404` means `absent`; an existing different artifact or another registry failure stops the ceremony. +Normal preparation authenticates the stable signed tag in a temporary bare +repository before checkout. The resulting artifact contains exactly two +regular files: the manifest and its named tarball. Consumer installation runs +in a separate job without publication authority. The environment-protected +OIDC job checks the tag again, downloads the sealed artifact outside a source +checkout, verifies the preparation manifest digest and both tarball digests, +and invokes npm from a fresh directory with empty configuration files and an +allowlisted environment. It never executes repository code. + ## One-time `0.0.0` package-name bootstrap **Complete; do not repeat.** The exact reviewed `0.0.0` artifact was published @@ -157,10 +167,12 @@ gh release create v0.1.0 --verify-tag --title "v0.1.0" ``` The unprivileged preparation job checks the signed tag, release-event commit, -main ancestry, full gate, tarball inventory, imports, and hashes. Only the -environment-scoped publish job receives OIDC authority; it installs no -dependencies and publishes the downloaded prepared artifact with provenance. -Re-running is safe only when npm reports the same integrity. +main ancestry, full gate, tarball inventory, and hashes. A second unprivileged +job imports the sealed tarball from a clean consumer installation. Only the +environment-scoped publish job receives OIDC authority; it checks the tag and +artifact again, installs no dependencies, and publishes the downloaded +prepared artifact with provenance. Re-running is safe only when npm reports +the same integrity. After publication, select the one successful `publish.yml` release run for the exact signed tag commit, confirm the run names that tag and commit, and diff --git a/packages/rate-limit/README.md b/packages/rate-limit/README.md index 9d73bd2..a5a7eff 100644 --- a/packages/rate-limit/README.md +++ b/packages/rate-limit/README.md @@ -44,13 +44,13 @@ With N host instances this can admit approximately N times `limit`. Choosing it means accepting that property. This tier holds its counters in memory, so its footprint is bounded on both -axes. It tracks at most 10,000 keys at once and accepts keys of at most 512 -UTF-16 code units — the unit the retained string actually costs, so an astral -symbol such as an emoji counts two. A longer key is rejected as invalid, the -same way other malformed keys are. When the key cap is reached and no tracked -key has expired yet, a check for a key that is not already tracked fails closed -with `retryAfter` instead of growing the map. Keys already tracked keep their -own counts and are never evicted, so a spray of unique keys can neither exhaust +axes. It tracks at most 10,000 keys at once. Both tiers accept keys of at most +512 UTF-16 code units; the bound is checked before trimming, Unicode scanning, +or durable hashing. An astral symbol such as an emoji counts two. A longer key +is rejected as invalid. When the key cap is reached and no tracked key has +expired yet, a check for a key that is not already tracked fails closed with +`retryAfter` instead of growing the map. Keys already tracked keep their own +counts and are never evicted, so a spray of unique keys can neither exhaust host memory nor reset another subject's window. Expired keys are reclaimed as soon as they expire: the reclaim scan is aimed at @@ -59,8 +59,8 @@ within 50 ms of a spray ageing out however long the window is. That 50 ms is a floor on how often the scan may run, which is what keeps its cost amortized constant while the cap is held. -Both bounds are specific to this tier: the durable tier hashes keys to -fixed-length identifiers and stores them, so it accepts keys of any length. +The tracked-key count bound is specific to this tier. The shared key-length +bound also limits work before the durable tier creates a fixed-length hash. ## Durable tier @@ -77,6 +77,7 @@ const limiter = createDurableLimiter( windowMs: 5 * 60_000, }), store, + { maxClockSkewMs: 60_000 }, ); const decision = await limiter.allow(principalOrAddress); @@ -95,12 +96,20 @@ their policy, but they are deterministic pseudonymous identifiers, not anonymization: predictable inputs can still be guessed and activity remains linkable within a policy. +Each policy partition also has an immutable descriptor binding its hashed name +to `limit` and `windowMs`, and every counter repeats those two values. A limiter +with conflicting settings fails closed without rewriting the descriptor or +counter. Change either setting under a versioned policy name during a rolling +deployment, or coordinate a store reset before reusing the name. + The durable tier uses fixed windows. A burst across a boundary can briefly admit nearly twice the limit. It also puts shared-storage latency on every allowed check; do not use it for hot, cheap endpoints. Sweeps list one policy partition and delete structurally valid expired rows -only if their versions are unchanged. Malformed rows are retained: +only if their versions are unchanged. By default a row remains for 60 seconds +after its window ends; `maxClockSkewMs` can set a different bounded, +non-negative grace for hosts with a known clock envelope. Malformed rows are retained: storage-core listings do not expose actual row keys, so pairing a malformed row's version with a key reconstructed from its payload could target another row. Checks against that malformed row still fail closed. diff --git a/packages/rate-limit/src/durable.test.ts b/packages/rate-limit/src/durable.test.ts index 437b5aa..61651b2 100644 --- a/packages/rate-limit/src/durable.test.ts +++ b/packages/rate-limit/src/durable.test.ts @@ -45,6 +45,38 @@ function stores(): Array<[string, () => Store]> { ]; } +function trackStore(inner: Store): { + readonly store: Store; + readonly writes: () => number; + readonly deletes: () => number; +} { + let writes = 0; + let deletes = 0; + return { + store: { + collection(definition: CollectionDefinition): CollectionStore { + const collection = inner.collection(definition); + return { + ...collection, + async update(key, decide, options) { + const result = await collection.update(key, decide, options); + if (result.written) { + writes += 1; + } + return result; + }, + async deleteIfUnchanged(key, version) { + deletes += 1; + return collection.deleteIfUnchanged(key, version); + }, + }; + }, + }, + writes: () => writes, + deletes: () => deletes, + }; +} + describe.each(stores())("createDurableLimiter over %s", (_name, makeStore) => { it("allows through the limit and makes later refusals read-only", async () => { let writes = 0; @@ -81,12 +113,12 @@ describe.each(stores())("createDurableLimiter over %s", (_name, makeStore) => { await expect(limiter.allow("alice", start)).resolves.toEqual({ allowed: true, }); - expect(writes).toBe(3); + expect(writes).toBe(4); await expect(limiter.allow("alice", start)).resolves.toEqual({ allowed: false, retryAfter: 60_000, }); - expect(writes).toBe(3); + expect(writes).toBe(4); }); it("keeps policies and opaque keys independent", async () => { @@ -108,7 +140,7 @@ describe.each(stores())("createDurableLimiter over %s", (_name, makeStore) => { }); }); - it("hashes long opaque policy names and keys into backend-safe identifiers", async () => { + it("hashes bounded opaque policy names and keys into backend-safe identifiers", async () => { const limiter = createDurableLimiter( { name: `long-policy-${"p".repeat(2_000)}`, @@ -119,7 +151,7 @@ describe.each(stores())("createDurableLimiter over %s", (_name, makeStore) => { ); await expect( - limiter.allow(`long-key-${"k".repeat(2_000)}`, start), + limiter.allow(`long-key-${"k".repeat(500)}`, start), ).resolves.toEqual({ allowed: true, }); @@ -138,9 +170,122 @@ describe.each(stores())("createDurableLimiter over %s", (_name, makeStore) => { limiter.allow("live", "2026-01-01T00:02:30.000Z"), ).resolves.toEqual({ allowed: true }); }); + + it("retains an exhausted window while peer clocks straddle its boundary", async () => { + const store = makeStore(); + const sharedPolicy = { + name: "clock-boundary", + limit: 1, + windowMs: 60_000, + } as const; + const slower = createDurableLimiter(sharedPolicy, store, { + clock: { now: () => "2026-01-01T00:00:59.500Z" }, + }); + const faster = createDurableLimiter(sharedPolicy, store, { + clock: { now: () => "2026-01-01T00:01:00.500Z" }, + }); + + await expect(slower.allow("shared-subject")).resolves.toEqual({ + allowed: true, + }); + await expect(faster.sweep()).resolves.toEqual({ scanned: 1, deleted: 0 }); + await expect(slower.allow("shared-subject")).resolves.toEqual({ + allowed: false, + retryAfter: 500, + }); + }); + + it("fails closed for conflicting policy semantics without refusal writes", async () => { + const tracked = trackStore(makeStore()); + const base = createDurableLimiter( + { name: "shared-policy", limit: 1, windowMs: 60_000 }, + tracked.store, + ); + await expect(base.allow("subject", start)).resolves.toEqual({ + allowed: true, + }); + const initialWrites = tracked.writes(); + + const freshMatch = createDurableLimiter( + { name: "shared-policy", limit: 1, windowMs: 60_000 }, + tracked.store, + ); + await expect(freshMatch.allow("subject", start)).resolves.toEqual({ + allowed: false, + retryAfter: 60_000, + }); + expect(tracked.writes()).toBe(initialWrites); + + const conflictingLimit = createDurableLimiter( + { name: "shared-policy", limit: 2, windowMs: 60_000 }, + tracked.store, + ); + await expect(conflictingLimit.allow("subject", start)).resolves.toEqual({ + allowed: false, + retryAfter: 60_000, + }); + + const conflictingWindow = createDurableLimiter( + { name: "shared-policy", limit: 1, windowMs: 120_000 }, + tracked.store, + ); + await expect(conflictingWindow.allow("subject", start)).resolves.toEqual({ + allowed: false, + retryAfter: 120_000, + }); + await expect( + conflictingWindow.sweep("2026-01-01T00:10:00.000Z"), + ).resolves.toEqual({ scanned: 0, deleted: 0 }); + expect(tracked.writes()).toBe(initialWrites); + expect(tracked.deletes()).toBe(0); + }); + + it("rejects oversized keys before hashing or storage operations", async () => { + let operations = 0; + const inner = makeStore(); + const tracking: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const collection = inner.collection(definition); + return { + ...collection, + async update(key, decide, options) { + operations += 1; + return collection.update(key, decide, options); + }, + async listVersioned(partition: string) { + operations += 1; + return collection.listVersioned(partition); + }, + async deleteIfUnchanged(key, version) { + operations += 1; + return collection.deleteIfUnchanged(key, version); + }, + }; + }, + }; + const digest = vi.spyOn(crypto.subtle, "digest"); + try { + await expect( + createDurableLimiter(policy, tracking).allow("k".repeat(513), start), + ).rejects.toThrow("at most 512 UTF-16 code units"); + expect(digest).not.toHaveBeenCalled(); + expect(operations).toBe(0); + } finally { + digest.mockRestore(); + } + }); }); describe("durable failure and contention behavior", () => { + it.each([-1, 1.5, Number.NaN, Number.POSITIVE_INFINITY])( + "rejects invalid maxClockSkewMs %#", + (maxClockSkewMs) => { + expect(() => + createDurableLimiter(policy, createMemoryStore(), { maxClockSkewMs }), + ).toThrow("maxClockSkewMs"); + }, + ); + it("starts hashing lazily and handles digest rejection before it can become unhandled", async () => { let digestCalls = 0; const unhandled: unknown[] = []; @@ -178,22 +323,33 @@ describe("durable failure and contention behavior", () => { it("stores only bounded domain-separated hashes, never raw policy names or keys", async () => { let stored: unknown; + const inner = createMemoryStore(); const store: Store = { - collection(): CollectionStore { + collection(definition: CollectionDefinition): CollectionStore { + const collection = inner.collection(definition); return { - async update(_key: EntityKey, decide: UpdateDecider) { - const decision = await decide(null); - if (decision.action !== "write") { - throw new Error("expected a counter write"); - } - stored = decision.value; - return { written: true, value: decision.value, attempts: 1 }; + ...collection, + async update(key, decide: UpdateDecider, options) { + return collection.update( + key, + async (current) => { + const decision = await decide(current); + if ( + decision.action === "write" && + (decision.value as Record).kind === "window" + ) { + stored = decision.value; + } + return decision; + }, + options, + ); }, - } as unknown as CollectionStore; + }; }, }; const rawPolicy = `private-policy-${"p".repeat(2_000)}`; - const rawKey = `person@example.test-${"k".repeat(2_000)}`; + const rawKey = `person@example.test-${"k".repeat(400)}`; const limiter = createDurableLimiter( { name: rawPolicy, limit: 1, windowMs: 60_000 }, store, @@ -205,13 +361,16 @@ describe("durable failure and contention behavior", () => { const serialized = JSON.stringify(stored); expect(serialized).not.toContain(rawPolicy); expect(serialized).not.toContain(rawKey); - expect(serialized.length).toBeLessThan(400); + expect(serialized.length).toBeLessThan(450); expect(stored).toMatchObject({ + kind: "window", policyHash: expect.stringMatching(/^[0-9a-f]{64}$/u), subjectHash: expect.stringMatching(/^[0-9a-f]{64}$/u), partition: expect.stringMatching(/^policy-[0-9a-f]{64}$/u), id: expect.stringMatching(/^\d{13}-[0-9a-f]{64}$/u), count: 1, + limit: 1, + windowMs: 60_000, }); expect(stored).not.toHaveProperty("policyName"); expect(stored).not.toHaveProperty("subjectKey"); @@ -219,18 +378,29 @@ describe("durable failure and contention behavior", () => { it("scopes a subject hash to its policy", async () => { const stored: Array> = []; + const inner = createMemoryStore(); const store: Store = { - collection(): CollectionStore { + collection(definition: CollectionDefinition): CollectionStore { + const collection = inner.collection(definition); return { - async update(_key: EntityKey, decide: UpdateDecider) { - const decision = await decide(null); - if (decision.action !== "write") { - throw new Error("expected a counter write"); - } - stored.push(decision.value as Record); - return { written: true, value: decision.value, attempts: 1 }; + ...collection, + async update(key, decide: UpdateDecider, options) { + return collection.update( + key, + async (current) => { + const decision = await decide(current); + if ( + decision.action === "write" && + (decision.value as Record).kind === "window" + ) { + stored.push(decision.value as Record); + } + return decision; + }, + options, + ); }, - } as unknown as CollectionStore; + }; }, }; @@ -410,7 +580,10 @@ describe("durable failure and contention behavior", () => { ...collection, async listVersioned(partition) { const listed = await collection.listVersioned(partition); - const first = listed[0]; + const first = listed.find(({ value }) => { + const record = value as Record; + return record.kind === "window"; + }); if (first !== undefined) { await collection.update( definition.key(first.value), @@ -451,6 +624,25 @@ describe("durable failure and contention behavior", () => { const store: Store = { collection(): CollectionStore { return { + async update(key: EntityKey, decide: UpdateDecider) { + const descriptor = { + partition: key.partition, + id: "policy", + kind: "policy", + policyHash: key.partition.slice("policy-".length), + subjectHash: null, + windowStartMs: null, + count: null, + limit: policy.limit, + windowMs: policy.windowMs, + } as T; + await decide(descriptor); + return { + written: false, + value: descriptor, + attempts: 1, + }; + }, async listVersioned() { return [ { @@ -482,31 +674,22 @@ describe("durable failure and contention behavior", () => { it("retains count-malformed records rather than pairing their version with a victim key", async () => { let conditionalDeleteCalled = false; + const inner = createMemoryStore(); const store: Store = { - collection(): CollectionStore { - let stored: T | undefined; + collection(definition: CollectionDefinition): CollectionStore { + const collection = inner.collection(definition); return { - async update(_key: EntityKey, decide: UpdateDecider) { - const decision = await decide(null); - if (decision.action !== "write") { - throw new Error("expected the initial counter write"); - } - stored = decision.value; - return { written: true, value: stored, attempts: 1 }; - }, - async listVersioned() { - if (stored === undefined) { - return []; - } - return [ - { - value: { - ...(stored as Record), - count: 0, - } as T, - version: "version-shared-by-another-key", - }, - ]; + ...collection, + async listVersioned(partition: string) { + return (await collection.listVersioned(partition)).map((row) => { + const value = row.value as Record; + return value.kind === "window" + ? { + ...row, + value: { ...value, count: 0 } as T, + } + : row; + }); }, async deleteIfUnchanged() { conditionalDeleteCalled = true; diff --git a/packages/rate-limit/src/durable.ts b/packages/rate-limit/src/durable.ts index c802451..2a69355 100644 --- a/packages/rate-limit/src/durable.ts +++ b/packages/rate-limit/src/durable.ts @@ -19,28 +19,36 @@ import { } from "./policy.js"; const COLLECTION_NAME = "rate-limit-windows"; +const POLICY_DESCRIPTOR_ID = "policy"; +const DEFAULT_MAX_CLOCK_SKEW_MS = 60_000; -interface StoredWindow { +interface StoredRateLimitRecord { readonly partition: StoredValue; readonly id: StoredValue; + readonly kind: StoredValue; readonly policyHash: StoredValue; readonly subjectHash: StoredValue; readonly windowStartMs: StoredValue; readonly count: StoredValue; + readonly limit: StoredValue; + readonly windowMs: StoredValue; } interface ValidWindow { readonly partition: string; readonly id: string; + readonly kind: "window"; readonly policyHash: string; readonly subjectHash: string; readonly windowStartMs: number; readonly count: number; + readonly limit: number; + readonly windowMs: number; } type WindowIdentity = Omit; -const windows = defineCollection({ +const records = defineCollection({ name: COLLECTION_NAME, key: (value) => ({ partition: String(value.partition), @@ -51,10 +59,13 @@ const windows = defineCollection({ decode: (record) => ({ partition: record.partition ?? null, id: record.id ?? null, + kind: record.kind ?? null, policyHash: record.policyHash ?? null, subjectHash: record.subjectHash ?? null, windowStartMs: record.windowStartMs ?? null, count: record.count ?? null, + limit: record.limit ?? null, + windowMs: record.windowMs ?? null, }), }, }); @@ -62,6 +73,11 @@ const windows = defineCollection({ export interface DurableLimiterOptions extends LimiterOptions { /** Total optimistic-concurrency attempts. Defaults to 3. */ readonly maxAttempts?: number; + /** + * Retention grace added after each fixed window. Defaults to 60 seconds so + * a moderately fast peer clock cannot sweep a slower peer's active window. + */ + readonly maxClockSkewMs?: number; } export interface SweepResult { @@ -117,8 +133,9 @@ function idFor(windowStartMs: number, subjectHash: string): string { const SHA_256_HEX = /^[0-9a-f]{64}$/u; -function validWindow(value: StoredWindow): ValidWindow | null { - return typeof value.partition === "string" && +function validWindow(value: StoredRateLimitRecord): ValidWindow | null { + return value.kind === "window" && + typeof value.partition === "string" && /^policy-[0-9a-f]{64}$/u.test(value.partition) && typeof value.id === "string" && value.id.length > 0 && @@ -130,37 +147,91 @@ function validWindow(value: StoredWindow): ValidWindow | null { Number.isSafeInteger(value.windowStartMs) && typeof value.count === "number" && Number.isSafeInteger(value.count) && - value.count > 0 + value.count > 0 && + typeof value.limit === "number" && + Number.isSafeInteger(value.limit) && + value.limit > 0 && + typeof value.windowMs === "number" && + Number.isSafeInteger(value.windowMs) && + value.windowMs > 0 ? (value as ValidWindow) : null; } +function windowMatches( + value: StoredRateLimitRecord, + expected: PartitionIdentity, + policy: RateLimitPolicy, + subjectHash: string, + windowStartMs: number, +): ValidWindow | null { + const valid = validWindow(value); + const id = idFor(windowStartMs, subjectHash); + return valid !== null && + valid.partition === expected.partition && + valid.id === id && + valid.policyHash === expected.policyHash && + valid.subjectHash === subjectHash && + valid.windowStartMs === windowStartMs && + valid.limit === policy.limit && + valid.windowMs === policy.windowMs + ? valid + : null; +} + +function descriptorMatches( + value: StoredRateLimitRecord, + expected: PartitionIdentity, + policy: RateLimitPolicy, +): boolean { + return ( + value.kind === "policy" && + value.partition === expected.partition && + value.id === POLICY_DESCRIPTOR_ID && + value.policyHash === expected.policyHash && + value.subjectHash === null && + value.windowStartMs === null && + value.count === null && + value.limit === policy.limit && + value.windowMs === policy.windowMs + ); +} + +function descriptorValue( + expected: PartitionIdentity, + policy: RateLimitPolicy, +): StoredRateLimitRecord { + return { + partition: expected.partition, + id: POLICY_DESCRIPTOR_ID, + kind: "policy", + policyHash: expected.policyHash, + subjectHash: null, + windowStartMs: null, + count: null, + limit: policy.limit, + windowMs: policy.windowMs, + }; +} + function sweepIdentity( - value: StoredWindow, + value: StoredRateLimitRecord, expected: PartitionIdentity, + policy: RateLimitPolicy, ): WindowIdentity | null { + const valid = validWindow(value); if ( - typeof value.partition !== "string" || - value.partition !== expected.partition || - typeof value.id !== "string" || - value.id.length === 0 || - typeof value.policyHash !== "string" || - value.policyHash !== expected.policyHash || - typeof value.subjectHash !== "string" || - !SHA_256_HEX.test(value.subjectHash) || - typeof value.windowStartMs !== "number" || - !Number.isSafeInteger(value.windowStartMs) || - value.id !== idFor(value.windowStartMs, value.subjectHash) + valid === null || + valid.partition !== expected.partition || + valid.policyHash !== expected.policyHash || + valid.id !== idFor(valid.windowStartMs, valid.subjectHash) || + valid.limit !== policy.limit || + valid.windowMs !== policy.windowMs ) { return null; } - return { - partition: value.partition, - id: value.id, - policyHash: value.policyHash, - subjectHash: value.subjectHash, - windowStartMs: value.windowStartMs, - }; + const { count: _count, ...identity } = valid; + return identity; } function assertMaxAttempts(value: number): number { @@ -170,13 +241,21 @@ function assertMaxAttempts(value: number): number { return value; } +function assertMaxClockSkewMs(value: number): number { + if (!Number.isSafeInteger(value) || value < 0) { + throw new TypeError("maxClockSkewMs must be a non-negative integer."); + } + return value; +} + /** * Creates a shared, fixed-window limiter over an injected Store. * - * This tier pays for one storage update per allowed check. A fixed window can - * admit nearly twice the limit across a boundary; it is intended for - * low-rate, expensive or abuse-critical operations, not hot cheap endpoints. - * Storage failures and exhausted contention retries deny rather than throw. + * This tier pays for one storage update per allowed check after its immutable + * policy descriptor is validated. A fixed window can admit nearly twice the + * limit across a boundary; it is intended for low-rate, expensive or + * abuse-critical operations, not hot cheap endpoints. Storage failures and + * exhausted contention retries deny rather than throw. */ export function createDurableLimiter( inputPolicy: RateLimitPolicy, @@ -186,8 +265,12 @@ export function createDurableLimiter( const policy = defineRateLimitPolicy(inputPolicy); const clock = options.clock ?? systemClock; const maxAttempts = assertMaxAttempts(options.maxAttempts ?? 3); - const collection = store.collection(windows); + const maxClockSkewMs = assertMaxClockSkewMs( + options.maxClockSkewMs ?? DEFAULT_MAX_CLOCK_SKEW_MS, + ); + const collection = store.collection(records); let partitionPromise: Promise | undefined; + let descriptorValidated = false; function getPartition(): Promise { // Start hashing only inside allow/sweep, where fail-closed handling @@ -197,6 +280,61 @@ export function createDurableLimiter( return partitionPromise; } + async function ensureDescriptor( + expected: PartitionIdentity, + create: boolean, + ): Promise { + if (descriptorValidated) { + return true; + } + let matches = false; + await collection.update( + { partition: expected.partition, id: POLICY_DESCRIPTOR_ID }, + (current) => { + if (current === null) { + matches = create; + return create + ? { action: "write", value: descriptorValue(expected, policy) } + : { action: "keep" }; + } + matches = descriptorMatches(current, expected, policy); + return { action: "keep" }; + }, + { maxAttempts }, + ); + if (matches) { + descriptorValidated = true; + } + return matches; + } + + async function preflightRefuses( + expected: PartitionIdentity, + subjectHash: string, + windowStartMs: number, + ): Promise { + let refuses = false; + const id = idFor(windowStartMs, subjectHash); + await collection.update( + { partition: expected.partition, id }, + (current) => { + if (current !== null) { + const valid = windowMatches( + current, + expected, + policy, + subjectHash, + windowStartMs, + ); + refuses = valid === null || valid.count >= policy.limit; + } + return { action: "keep" }; + }, + { maxAttempts }, + ); + return refuses; + } + return { async allow(key: string, at?: IsoTimestamp): Promise { assertRateLimitKey(key); @@ -209,37 +347,57 @@ export function createDurableLimiter( let deciderAllowed = false; try { - const { partition, policyHash } = await getPartition(); - const subjectHash = await subjectHashFor(policyHash, key); + const expected = await getPartition(); + const subjectHash = await subjectHashFor(expected.policyHash, key); const id = idFor(windowStartMs, subjectHash); + + if (!descriptorValidated) { + // A fresh limiter checks the counter first. If it is already at its + // boundary, refusal returns after a keep decision and does not write + // a missing descriptor or any other record. + if (await preflightRefuses(expected, subjectHash, windowStartMs)) { + return { + allowed: false, + retryAfter: retryAfter(windowEndsAt, now), + }; + } + if (!(await ensureDescriptor(expected, true))) { + return { + allowed: false, + retryAfter: retryAfter(windowEndsAt, now), + }; + } + } + const result = await collection.update( - { partition, id }, + { partition: expected.partition, id }, (current) => { if (current === null) { deciderAllowed = true; return { action: "write", value: { - partition, + partition: expected.partition, id, - policyHash, + kind: "window", + policyHash: expected.policyHash, subjectHash, windowStartMs, count: 1, + limit: policy.limit, + windowMs: policy.windowMs, }, }; } - const valid = validWindow(current); - if ( - valid === null || - valid.partition !== partition || - valid.id !== id || - valid.policyHash !== policyHash || - valid.subjectHash !== subjectHash || - valid.windowStartMs !== windowStartMs || - valid.count >= policy.limit - ) { + const valid = windowMatches( + current, + expected, + policy, + subjectHash, + windowStartMs, + ); + if (valid === null || valid.count >= policy.limit) { deciderAllowed = false; return { action: "keep" }; } @@ -276,14 +434,20 @@ export function createDurableLimiter( let rows; try { expected = await getPartition(); + if (!(await ensureDescriptor(expected, false))) { + return { scanned: 0, deleted: 0 }; + } rows = await collection.listVersioned(expected.partition); } catch { return { scanned: 0, deleted: 0 }; } + const candidates = rows.filter( + ({ value }) => value.id !== POLICY_DESCRIPTOR_ID, + ); let deleted = 0; - for (const row of rows) { - const identity = sweepIdentity(row.value, expected); + for (const row of candidates) { + const identity = sweepIdentity(row.value, expected, policy); if (identity === null) { // CollectionStore.listVersioned does not expose the actual row key. // Reconstructing one from malformed identity fields could pair this @@ -291,14 +455,9 @@ export function createDurableLimiter( // safe choice. continue; } - const countIsMalformed = - typeof row.value.count !== "number" || - !Number.isSafeInteger(row.value.count) || - row.value.count <= 0; - if ( - countIsMalformed || - identity.windowStartMs + policy.windowMs > now - ) { + const expiresAt = + identity.windowStartMs + policy.windowMs + maxClockSkewMs; + if (!Number.isSafeInteger(expiresAt) || expiresAt > now) { continue; } try { @@ -316,7 +475,7 @@ export function createDurableLimiter( // A sweep is hygiene; a failed delete leaves the record for later. } } - return { scanned: rows.length, deleted }; + return { scanned: candidates.length, deleted }; }, }; } diff --git a/packages/rate-limit/src/memory.ts b/packages/rate-limit/src/memory.ts index 84ac41f..f84bd0f 100644 --- a/packages/rate-limit/src/memory.ts +++ b/packages/rate-limit/src/memory.ts @@ -29,23 +29,10 @@ const MAX_TRACKED_KEYS = 10_000; const MIN_PRUNE_INTERVAL_MS = 50; /** - * Maximum key length this tier will track, measured in UTF-16 code units - * because that is what the retained string costs: an astral symbol such as an - * emoji counts two. Only the memory tier retains the raw key — the durable tier - * hashes it to a fixed-length identifier — so only this tier needs the bound. - * Keys are opaque subject identifiers such as an address, a principal, or a - * short composite of those, so the bound sits far above legitimate use. + * The shared validator bounds keys before either tier scans or hashes them. + * Memory retains the raw string, so the UTF-16 unit also reflects its cost. */ -const MAX_KEY_LENGTH = 512; - function assertMemoryLimiterKey(key: string): void { - // Checked before the shared validator's well-formedness scan, which walks - // the whole string, so an oversized key is rejected without being traversed. - if (typeof key === "string" && key.length > MAX_KEY_LENGTH) { - throw new TypeError( - `A memory-tier rate-limit key must be at most ${MAX_KEY_LENGTH} UTF-16 code units.`, - ); - } assertRateLimitKey(key); } diff --git a/packages/rate-limit/src/policy.ts b/packages/rate-limit/src/policy.ts index fc437e1..f4e0cd7 100644 --- a/packages/rate-limit/src/policy.ts +++ b/packages/rate-limit/src/policy.ts @@ -30,6 +30,9 @@ export interface LimiterOptions { readonly clock?: Clock; } +/** Maximum opaque subject-key length, measured in UTF-16 code units. */ +export const MAX_RATE_LIMIT_KEY_LENGTH = 512; + function isWellFormedUnicode(value: string): boolean { for (let index = 0; index < value.length; index += 1) { const codeUnit = value.charCodeAt(index); @@ -78,6 +81,13 @@ export function defineRateLimitPolicy( } export function assertRateLimitKey(key: string): void { + // Deliberately precedes trimming, Unicode validation, hashing, and storage + // key interpolation so oversized input is rejected in constant time. + if (typeof key === "string" && key.length > MAX_RATE_LIMIT_KEY_LENGTH) { + throw new TypeError( + `A rate-limit key must be at most ${MAX_RATE_LIMIT_KEY_LENGTH} UTF-16 code units.`, + ); + } if (typeof key !== "string" || key.trim().length === 0) { throw new TypeError("A rate-limit key must be a non-blank string."); } diff --git a/scripts/release-package.mjs b/scripts/release-package.mjs index 3c98922..ca2f59b 100644 --- a/scripts/release-package.mjs +++ b/scripts/release-package.mjs @@ -1,4 +1,11 @@ import { createHash, timingSafeEqual } from "node:crypto"; +import { + chmodSync, + existsSync, + mkdtempSync, + rmSync, + writeFileSync, +} from "node:fs"; import { mkdir, mkdtemp, @@ -19,6 +26,7 @@ const PACKAGE_MANAGER = "pnpm@10.34.5"; const REPOSITORY_URL = "git+https://github.com/pegma-dev/rate-limit.git"; const NODE_RANGE = ">=22"; const STABLE_VERSION = /^\d+\.\d+\.\d+$/u; +const NPM_REGISTRY = "https://registry.npmjs.org/"; const REQUIRED_DEPENDENCIES = { "@pegma/spine": "0.1.1", "@pegma/storage-core": "0.4.0", @@ -47,18 +55,83 @@ function run(command, arguments_, options = {}) { return result; } -function npmEnvironment(environment = process.env) { - const isolated = { ...environment }; - delete isolated.npm_execpath; +const NPM_ENVIRONMENT_KEYS = new Set([ + "CI", + "COMSPEC", + "HOME", + "HOMEDRIVE", + "HOMEPATH", + "PATH", + "PATHEXT", + "RUNNER_TEMP", + "SYSTEMDRIVE", + "SYSTEMROOT", + "TEMP", + "TMP", + "TMPDIR", + "USERPROFILE", + "WINDIR", +]); + +export function isolatedNpmEnvironment( + environment, + { cache, globalConfig, userConfig }, +) { + const isolated = {}; + for (const [key, value] of Object.entries(environment)) { + const upper = key.toUpperCase(); + if ( + value !== undefined && + (NPM_ENVIRONMENT_KEYS.has(upper) || + upper.startsWith("GITHUB_") || + upper.startsWith("ACTIONS_ID_TOKEN_")) + ) { + isolated[key] = value; + } + } + isolated.NPM_CONFIG_USERCONFIG = userConfig; + isolated.NPM_CONFIG_GLOBALCONFIG = globalConfig; + isolated.NPM_CONFIG_CACHE = cache; + isolated.NPM_CONFIG_REGISTRY = NPM_REGISTRY; return isolated; } function runNpm(arguments_, options = {}) { - return run(process.platform === "win32" ? "npm.cmd" : "npm", arguments_, { - ...options, - env: npmEnvironment(options.env ?? process.env), - shell: process.platform === "win32", - }); + const sandbox = mkdtempSync(join(tmpdir(), "pegma-rate-limit-npm-")); + const userConfig = join(sandbox, "user.npmrc"); + const globalConfig = join(sandbox, "global.npmrc"); + const cache = join(sandbox, "cache"); + writeFileSync(userConfig, "", { mode: 0o600 }); + writeFileSync(globalConfig, "", { mode: 0o600 }); + chmodSync(userConfig, 0o600); + chmodSync(globalConfig, 0o600); + try { + const npmCli = join( + dirname(process.execPath), + "node_modules", + "npm", + "bin", + "npm-cli.js", + ); + if (process.platform === "win32" && !existsSync(npmCli)) { + fail(`npm CLI was not found beside Node.js: ${npmCli}`); + } + const command = process.platform === "win32" ? process.execPath : "npm"; + const commandArguments = + process.platform === "win32" ? [npmCli, ...arguments_] : arguments_; + return run(command, commandArguments, { + ...options, + cwd: options.cwd ?? sandbox, + env: isolatedNpmEnvironment(options.env ?? process.env, { + cache, + globalConfig, + userConfig, + }), + shell: false, + }); + } finally { + rmSync(sandbox, { force: true, recursive: true }); + } } function decodeYamlScalar(value) { @@ -82,7 +155,7 @@ const DEPENDENCY_SECTIONS = new Set([ ]); function parsePnpmImporterSections(lockText, importer) { - const lines = lockText.split("\n"); + const lines = lockText.split(/\r?\n/u); let inImporters = false; let inTarget = false; let currentSection = null; @@ -364,7 +437,7 @@ async function readPnpmWorkspacePackages(root) { const text = await readFile(join(root, "pnpm-workspace.yaml"), "utf8"); const packages = []; let inPackages = false; - for (const line of text.split("\n")) { + for (const line of text.split(/\r?\n/u)) { if (line.trim() === "packages:") { inPackages = true; continue; @@ -404,6 +477,7 @@ function safeEqual(left, right) { function hashes(bytes) { return { integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, + sha256: createHash("sha256").update(bytes).digest("hex"), shasum: createHash("sha1").update(bytes).digest("hex"), }; } @@ -535,6 +609,11 @@ export async function validateRepository(options = {}) { } } if (options.requireReleaseTag) { + const prerelease = + options.releasePrerelease ?? process.env.RELEASE_PRERELEASE; + if (prerelease !== false && prerelease !== "false") { + fail("release event prerelease state must be false"); + } if (manifest.version === "0.0.0") { fail( "the 0.0.0 package-name bootstrap must not use the GitHub release workflow", @@ -546,13 +625,13 @@ export async function validateRepository(options = {}) { } function validateReleaseTag(root, releaseTag, expectedCommit) { - if (releaseTag === undefined || !/^v\d+\.\d+\.\d+$/u.test(releaseTag)) { - fail("a stable release tag is required"); - } if ( - expectedCommit === undefined || - !/^[0-9a-f]{40,64}$/u.test(expectedCommit) + 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 (expectedCommit === undefined || !/^[0-9a-f]{40}$/u.test(expectedCommit)) { fail("an exact release-event commit is required"); } const tagRef = `refs/tags/${releaseTag}`; @@ -610,6 +689,52 @@ function verifyPackedFiles(manifest, files) { } } +async function verifyRegularFileInventory(directory, expectedNames) { + const entries = await readdir(directory, { withFileTypes: true }); + const names = entries.map(({ name }) => name).sort(); + const expected = [...expectedNames].sort(); + if ( + !sameJson(names, expected) || + entries.some((entry) => !entry.isFile() || entry.isSymbolicLink()) + ) { + fail( + `release directory must contain only regular files: ${expected.join(", ")}`, + ); + } +} + +export async function verifyReleaseInventory(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const tarballs = entries + .filter(({ name }) => /^pegma-rate-limit-\d+\.\d+\.\d+\.tgz$/u.test(name)) + .map(({ name }) => name); + if (tarballs.length !== 1) { + fail("release directory must contain exactly one versioned tarball"); + } + await verifyRegularFileInventory(directory, [ + "package-manifest.json", + tarballs[0], + ]); + return { + manifest: join(directory, "package-manifest.json"), + tarball: join(directory, tarballs[0]), + }; +} + +async function removeTypeScriptBuildInfo(directory) { + for (const entry of await readdir(directory, { withFileTypes: true })) { + if (entry.isDirectory()) { + if (entry.name !== ".git" && entry.name !== "node_modules") { + await removeTypeScriptBuildInfo(join(directory, entry.name)); + } + continue; + } + if (entry.isFile() && entry.name.endsWith(".tsbuildinfo")) { + await rm(join(directory, entry.name), { force: true }); + } + } +} + async function smokeTest(tarball) { const directory = await mkdtemp(join(tmpdir(), "pegma-rate-limit-smoke-")); try { @@ -647,10 +772,20 @@ async function smokeTest(tarball) { export async function prepareRelease(options = {}) { const { manifest, root } = await validateRepository(options); const output = resolve(root, options.output ?? ".release"); - await mkdir(output, { recursive: true }); - if ((await readdir(output)).length !== 0) { - fail(`release output directory must be empty: ${output}`); + if (options.output === undefined) { + await rm(output, { force: true, recursive: true }); + } else { + await mkdir(output, { recursive: true }); + if ((await readdir(output)).length !== 0) { + fail(`release output directory must be empty: ${output}`); + } } + await rm(join(root, PACKAGE_DIRECTORY, "dist"), { + force: true, + recursive: true, + }); + await removeTypeScriptBuildInfo(root); + await mkdir(output, { recursive: true }); const packedResult = runNpm( [ "pack", @@ -659,7 +794,7 @@ export async function prepareRelease(options = {}) { "--pack-destination", output, ], - { capture: true, cwd: root }, + { capture: true }, ); const [packed] = JSON.parse(packedResult.stdout); if ( @@ -679,9 +814,8 @@ export async function prepareRelease(options = {}) { ) { fail("tarball hashes do not match npm pack metadata"); } - await smokeTest(tarball); const prepared = { - schemaVersion: 1, + schemaVersion: 2, gitCommit: run("git", ["rev-parse", "HEAD"], { capture: true, cwd: root, @@ -691,7 +825,8 @@ export async function prepareRelease(options = {}) { name: PACKAGE_NAME, version: manifest.version, tarball: basename(tarball), - ...digest, + integrity: digest.integrity, + sha256: digest.sha256, files: packed.files .map(({ path, size }) => ({ path, size })) .sort((left, right) => left.path.localeCompare(right.path)), @@ -699,6 +834,7 @@ export async function prepareRelease(options = {}) { }; const preparedPath = join(output, "package-manifest.json"); await writeFile(preparedPath, `${JSON.stringify(prepared, null, 2)}\n`); + await verifyReleaseInventory(output); return preparedPath; } @@ -757,25 +893,61 @@ function confirmRegistryIntegrity(name, version, expected) { fail(`${name}@${version} did not become visible with expected integrity`); } -async function verifyPreparedArtifact(options = {}) { +function hasExactKeys(value, keys) { + return ( + typeof value === "object" && + value !== null && + !Array.isArray(value) && + sameJson(Object.keys(value).sort(), [...keys].sort()) + ); +} + +export async function verifyPreparedArtifact(options = {}) { const path = resolve( options.manifest ?? join(".release", "package-manifest.json"), ); + if (basename(path) !== "package-manifest.json") { + fail("prepared manifest must be named package-manifest.json"); + } + await verifyReleaseInventory(dirname(path)); const prepared = await readJson(path); const sourceManifest = await readJson( join(defaultRoot(), PACKAGE_DIRECTORY, "package.json"), ); if ( - prepared.schemaVersion !== 1 || + !hasExactKeys(prepared, [ + "schemaVersion", + "gitCommit", + "releaseTag", + "package", + ]) || + !hasExactKeys(prepared.package, [ + "name", + "version", + "tarball", + "integrity", + "sha256", + "files", + ]) || + prepared.schemaVersion !== 2 || prepared.package?.name !== PACKAGE_NAME || prepared.package.version !== sourceManifest.version || !STABLE_VERSION.test(prepared.package.version) || - !/^[0-9a-f]{40,64}$/u.test(prepared.gitCommit) || + !/^[0-9a-f]{40}$/u.test(prepared.gitCommit) || !( prepared.releaseTag === null || prepared.releaseTag === `v${prepared.package.version}` ) || - !Array.isArray(prepared.package.files) + !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(prepared.package.integrity) || + !/^[0-9a-f]{64}$/u.test(prepared.package.sha256) || + !Array.isArray(prepared.package.files) || + prepared.package.files.some( + (file) => + !hasExactKeys(file, ["path", "size"]) || + typeof file.path !== "string" || + !Number.isSafeInteger(file.size) || + file.size < 0, + ) ) { fail("prepared release metadata is invalid"); } @@ -798,13 +970,18 @@ async function verifyPreparedArtifact(options = {}) { const digest = hashes(await readFile(tarball)); if ( !safeEqual(digest.integrity, prepared.package.integrity) || - !safeEqual(digest.shasum, prepared.package.shasum) + !safeEqual(digest.sha256, prepared.package.sha256) ) { fail("the prepared tarball has changed"); } return { digest, path, prepared, tarball }; } +export async function smokePreparedArtifact(options = {}) { + const { tarball } = await verifyPreparedArtifact(options); + await smokeTest(tarball); +} + export async function inspectPreparedRegistry(options = {}) { const { digest, prepared } = await verifyPreparedArtifact(options); const existing = registryIntegrity(PACKAGE_NAME, prepared.package.version); @@ -829,8 +1006,7 @@ export async function publishPrepared(options = {}) { fail("release publishing is restricted to a GitHub release workflow"); } requireTrustedPublishingNpm(); - const { digest, path, prepared, tarball } = - await verifyPreparedArtifact(options); + const { digest, prepared, tarball } = await verifyPreparedArtifact(options); const expectedCommit = options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; @@ -850,9 +1026,16 @@ export async function publishPrepared(options = {}) { process.stdout.write("Registry integrity matches; skipping publish.\n"); return; } - runNpm(["publish", tarball, "--access", "public", "--provenance"], { - cwd: dirname(path), - }); + runNpm([ + "publish", + tarball, + "--registry", + NPM_REGISTRY, + "--access", + "public", + "--provenance", + "--ignore-scripts", + ]); confirmRegistryIntegrity( PACKAGE_NAME, prepared.package.version, @@ -911,13 +1094,16 @@ async function main() { } else if (command === "pack") { const path = await prepareRelease(options); process.stdout.write(`Prepared release at ${path}.\n`); + } else if (command === "smoke") { + await smokePreparedArtifact(options); + process.stdout.write("Prepared release imports are valid.\n"); } else if (command === "publish") { await publishPrepared(options); } else if (command === "registry-check") { await inspectPreparedRegistry(options); } else { fail( - "usage: release-package.mjs [options]", + "usage: release-package.mjs [options]", ); } } diff --git a/test/release-package.test.ts b/test/release-package.test.ts new file mode 100644 index 0000000..861d149 --- /dev/null +++ b/test/release-package.test.ts @@ -0,0 +1,209 @@ +import { + mkdtemp, + mkdir, + readFile, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + isolatedNpmEnvironment, + verifyReleaseInventory, + // @ts-expect-error TypeScript does not emit declarations for repository scripts. +} from "../scripts/release-package.mjs"; + +const temporaryDirectories: string[] = []; + +async function temporaryDirectory(prefix: string): Promise { + const directory = await mkdtemp(join(tmpdir(), prefix)); + temporaryDirectories.push(directory); + return directory; +} + +afterEach(async () => { + await Promise.all( + temporaryDirectories + .splice(0) + .map((directory) => rm(directory, { force: true, recursive: true })), + ); +}); + +describe("release artifact boundaries", () => { + it("accepts exactly two regular release files", async () => { + const directory = await temporaryDirectory("rate-limit-release-"); + await writeFile(join(directory, "package-manifest.json"), "{}\n"); + await writeFile(join(directory, "pegma-rate-limit-0.2.0.tgz"), "bytes"); + + await expect(verifyReleaseInventory(directory)).resolves.toEqual({ + manifest: join(directory, "package-manifest.json"), + tarball: join(directory, "pegma-rate-limit-0.2.0.tgz"), + }); + }); + + it.each([".npmrc", ".hidden", "extra.txt"])( + "rejects an extra sibling file named %s", + async (name) => { + const directory = await temporaryDirectory("rate-limit-release-"); + await writeFile(join(directory, "package-manifest.json"), "{}\n"); + await writeFile(join(directory, "pegma-rate-limit-0.2.0.tgz"), "bytes"); + await writeFile(join(directory, name), "extra"); + + await expect(verifyReleaseInventory(directory)).rejects.toThrow( + "only regular files", + ); + }, + ); + + it("rejects a subdirectory", async () => { + const directory = await temporaryDirectory("rate-limit-release-"); + await writeFile(join(directory, "package-manifest.json"), "{}\n"); + await writeFile(join(directory, "pegma-rate-limit-0.2.0.tgz"), "bytes"); + await mkdir(join(directory, "nested")); + + await expect(verifyReleaseInventory(directory)).rejects.toThrow( + "only regular files", + ); + }); + + it("rejects a tarball-path symlink", async () => { + const directory = await temporaryDirectory("rate-limit-release-"); + const target = await temporaryDirectory("rate-limit-release-target-"); + await writeFile(join(directory, "package-manifest.json"), "{}\n"); + await symlink( + target, + join(directory, "pegma-rate-limit-0.2.0.tgz"), + "junction", + ); + + await expect(verifyReleaseInventory(directory)).rejects.toThrow( + "only regular files", + ); + }); + + it("constructs an allowlisted npm environment", () => { + const environment = isolatedNpmEnvironment( + { + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "oidc-token", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.test/oidc", + CI: "1", + GITHUB_ACTIONS: "true", + HOME: "/home/runner", + PATH: "/bin", + HTTPS_PROXY: "https://proxy.test", + NODE_AUTH_TOKEN: "registry-token", + NODE_EXTRA_CA_CERTS: "/tmp/extra.pem", + NODE_OPTIONS: "--require hook.js", + NPM_CONFIG_USERCONFIG: "/tmp/untrusted.npmrc", + NPM_TOKEN: "registry-token", + npm_config_registry: "https://example.test/", + }, + { + cache: "/tmp/npm-cache", + globalConfig: "/tmp/global.npmrc", + userConfig: "/tmp/user.npmrc", + }, + ); + + expect(environment).toMatchObject({ + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "oidc-token", + ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.test/oidc", + CI: "1", + GITHUB_ACTIONS: "true", + HOME: "/home/runner", + PATH: "/bin", + NPM_CONFIG_CACHE: "/tmp/npm-cache", + NPM_CONFIG_GLOBALCONFIG: "/tmp/global.npmrc", + NPM_CONFIG_REGISTRY: "https://registry.npmjs.org/", + NPM_CONFIG_USERCONFIG: "/tmp/user.npmrc", + }); + for (const key of [ + "HTTPS_PROXY", + "NODE_AUTH_TOKEN", + "NODE_EXTRA_CA_CERTS", + "NODE_OPTIONS", + "NPM_TOKEN", + "npm_config_registry", + ]) { + expect(environment).not.toHaveProperty(key); + } + }); +}); + +describe("publish workflow boundaries", () => { + it("authenticates in bare repositories before checkout and never checks out in publish", async () => { + const workflow = await readFile( + resolve(".github/workflows/publish.yml"), + "utf8", + ); + const prepare = workflow.slice( + workflow.indexOf(" prepare:"), + workflow.indexOf(" smoke:"), + ); + const publish = workflow.slice(workflow.indexOf(" publish:")); + + expect(prepare.indexOf("git init --bare")).toBeLessThan( + prepare.indexOf("uses: actions/checkout"), + ); + expect(workflow.match(/git init --bare/gu)).toHaveLength(2); + expect(workflow.match(/ verify-tag /gu)).toHaveLength(2); + expect(workflow.match(/merge-base --is-ancestor/gu)).toHaveLength(2); + expect(prepare).toContain("ref: ${{ github.sha }}"); + expect(prepare).toContain("persist-credentials: false"); + expect(publish).not.toContain("actions/checkout"); + expect(publish).not.toContain("scripts/release-package.mjs"); + }); + + it("seals a non-hidden artifact before unprivileged smoke and OIDC publish", async () => { + const workflow = await readFile( + resolve(".github/workflows/publish.yml"), + "utf8", + ); + + expect(workflow).toContain("include-hidden-files: false"); + expect(workflow).toContain("manifest-digest:"); + expect(workflow).toContain("needs: [prepare, smoke]"); + expect(workflow).toContain("--ignore-scripts"); + expect(workflow).toContain("NPM_CONFIG_USERCONFIG"); + expect(workflow).toContain("NPM_CONFIG_GLOBALCONFIG"); + expect(workflow).toContain("id-token: write"); + }); + + it("keeps GitHub expressions out of run scripts", async () => { + const workflow = await readFile( + resolve(".github/workflows/publish.yml"), + "utf8", + ); + const lines = workflow.split("\n"); + const runSections: string[] = []; + for (let index = 0; index < lines.length; index += 1) { + if (!/^ {8}run:/u.test(lines[index] ?? "")) { + continue; + } + const body: string[] = [lines[index] as string]; + for (index += 1; index < lines.length; index += 1) { + const line = lines[index] as string; + if (line !== "" && !/^ {10,}/u.test(line)) { + index -= 1; + break; + } + body.push(line); + } + runSections.push(body.join("\n")); + } + + expect(runSections.join("\n")).not.toContain("${{"); + }); + + it("runs the release metadata check in CI", async () => { + const workflow = await readFile( + resolve(".github/workflows/ci.yml"), + "utf8", + ); + expect(workflow).toContain("pnpm run release:check"); + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts index d9f683f..e8f32b9 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -4,7 +4,7 @@ export default defineConfig({ test: { exclude: ["**/dist/**", "**/node_modules/**"], globalSetup: ["./test/azurite.ts"], - include: ["packages/**/*.test.ts"], + include: ["packages/**/*.test.ts", "test/**/*.test.ts"], testTimeout: 30_000, }, }); From 02eedf1963dd60e10a1ddcf79ae624aa39a8a889 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 15:04:44 -0500 Subject: [PATCH 2/4] Revalidate durable policy state and align repository gates --- .gitattributes | 1 + .github/workflows/ci.yml | 5 +- .github/workflows/publish.yml | 7 +++ .prettierrc.json | 3 - packages/rate-limit/README.md | 7 ++- packages/rate-limit/src/durable.test.ts | 73 +++++++++++++++++++++++++ packages/rate-limit/src/durable.ts | 35 ++++++++---- test/release-package.test.ts | 18 ++++++ 8 files changed, 129 insertions(+), 20 deletions(-) create mode 100644 .gitattributes delete mode 100644 .prettierrc.json diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b2f5b21..5edd253 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,16 +30,13 @@ jobs: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - name: Enable Corepack - run: corepack enable - - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: node-version: ${{ matrix.node-version }} cache: pnpm - - name: Activate pnpm + - name: Enable Corepack run: corepack enable - name: Install dependencies diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index d995d93..4ffc1bd 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -385,13 +385,20 @@ jobs: const keep = new Set([ "CI", + "COMSPEC", "HOME", + "HOMEDRIVE", + "HOMEPATH", "PATH", + "PATHEXT", "RUNNER_TEMP", + "SYSTEMDRIVE", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", + "USERPROFILE", + "WINDIR", ]); const npmEnvironment = {}; for (const [key, value] of Object.entries(process.env)) { diff --git a/.prettierrc.json b/.prettierrc.json deleted file mode 100644 index 168d9d2..0000000 --- a/.prettierrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "endOfLine": "auto" -} diff --git a/packages/rate-limit/README.md b/packages/rate-limit/README.md index a5a7eff..4d96bc4 100644 --- a/packages/rate-limit/README.md +++ b/packages/rate-limit/README.md @@ -98,9 +98,10 @@ linkable within a policy. Each policy partition also has an immutable descriptor binding its hashed name to `limit` and `windowMs`, and every counter repeats those two values. A limiter -with conflicting settings fails closed without rewriting the descriptor or -counter. Change either setting under a versioned policy name during a rolling -deployment, or coordinate a store reset before reusing the name. +revalidates the descriptor before counter writes and sweeps. Missing or +conflicting settings fail closed without rewriting the descriptor or counter. +Change either setting under a versioned policy name during a rolling deployment, +or coordinate a store reset before reusing the name. The durable tier uses fixed windows. A burst across a boundary can briefly admit nearly twice the limit. It also puts shared-storage latency on every diff --git a/packages/rate-limit/src/durable.test.ts b/packages/rate-limit/src/durable.test.ts index 61651b2..024e324 100644 --- a/packages/rate-limit/src/durable.test.ts +++ b/packages/rate-limit/src/durable.test.ts @@ -77,6 +77,45 @@ function trackStore(inner: Store): { }; } +function resettableStore(inner: Store): { + readonly store: Store; + readonly removeDescriptor: () => Promise; +} { + let removeDescriptor: (() => Promise) | undefined; + return { + store: { + collection(definition: CollectionDefinition): CollectionStore { + const collection = inner.collection(definition); + return { + ...collection, + async update(key, decide, options) { + if (key.id === "policy") { + removeDescriptor = async () => { + const rows = await collection.listVersioned(key.partition); + const descriptor = rows.find( + ({ value }) => + (value as Record).id === "policy", + ); + if (descriptor === undefined) { + throw new Error("policy descriptor is missing"); + } + await collection.deleteIfUnchanged(key, descriptor.version); + }; + } + return collection.update(key, decide, options); + }, + }; + }, + }, + async removeDescriptor() { + if (removeDescriptor === undefined) { + throw new Error("policy descriptor was not initialized"); + } + await removeDescriptor(); + }, + }; +} + describe.each(stores())("createDurableLimiter over %s", (_name, makeStore) => { it("allows through the limit and makes later refusals read-only", async () => { let writes = 0; @@ -240,6 +279,40 @@ describe.each(stores())("createDurableLimiter over %s", (_name, makeStore) => { expect(tracked.deletes()).toBe(0); }); + it("revalidates an established descriptor before writing or sweeping", async () => { + const resettable = resettableStore(makeStore()); + const tracked = trackStore(resettable.store); + const limiter = createDurableLimiter( + { name: "descriptor-recheck", limit: 2, windowMs: 60_000 }, + tracked.store, + ); + await expect(limiter.allow("first", start)).resolves.toEqual({ + allowed: true, + }); + await resettable.removeDescriptor(); + const writesBeforeRefusal = tracked.writes(); + + await expect(limiter.allow("second", start)).resolves.toEqual({ + allowed: false, + retryAfter: 60_000, + }); + await expect(limiter.sweep("2026-01-01T00:10:00.000Z")).resolves.toEqual({ + scanned: 0, + deleted: 0, + }); + expect(tracked.writes()).toBe(writesBeforeRefusal); + + const fresh = createDurableLimiter( + { name: "descriptor-recheck", limit: 3, windowMs: 120_000 }, + tracked.store, + ); + await expect(fresh.allow("new-window", start)).resolves.toEqual({ + allowed: false, + retryAfter: 120_000, + }); + expect(tracked.writes()).toBe(writesBeforeRefusal); + }); + it("rejects oversized keys before hashing or storage operations", async () => { let operations = 0; const inner = makeStore(); diff --git a/packages/rate-limit/src/durable.ts b/packages/rate-limit/src/durable.ts index 2a69355..f637562 100644 --- a/packages/rate-limit/src/durable.ts +++ b/packages/rate-limit/src/durable.ts @@ -251,8 +251,8 @@ function assertMaxClockSkewMs(value: number): number { /** * Creates a shared, fixed-window limiter over an injected Store. * - * This tier pays for one storage update per allowed check after its immutable - * policy descriptor is validated. A fixed window can admit nearly twice the + * This tier revalidates its immutable policy descriptor and pays for one + * counter write per allowed check. A fixed window can admit nearly twice the * limit across a boundary; it is intended for low-rate, expensive or * abuse-critical operations, not hot cheap endpoints. Storage failures and * exhausted contention retries deny rather than throw. @@ -270,7 +270,7 @@ export function createDurableLimiter( ); const collection = store.collection(records); let partitionPromise: Promise | undefined; - let descriptorValidated = false; + let descriptorEstablished = false; function getPartition(): Promise { // Start hashing only inside allow/sweep, where fail-closed handling @@ -284,26 +284,26 @@ export function createDurableLimiter( expected: PartitionIdentity, create: boolean, ): Promise { - if (descriptorValidated) { - return true; - } let matches = false; + let observed = false; await collection.update( { partition: expected.partition, id: POLICY_DESCRIPTOR_ID }, (current) => { if (current === null) { matches = create; + observed = create; return create ? { action: "write", value: descriptorValue(expected, policy) } : { action: "keep" }; } + observed = true; matches = descriptorMatches(current, expected, policy); return { action: "keep" }; }, { maxAttempts }, ); - if (matches) { - descriptorValidated = true; + if (observed) { + descriptorEstablished = true; } return matches; } @@ -350,8 +350,9 @@ export function createDurableLimiter( const expected = await getPartition(); const subjectHash = await subjectHashFor(expected.policyHash, key); const id = idFor(windowStartMs, subjectHash); + let createDescriptor = false; - if (!descriptorValidated) { + if (!descriptorEstablished) { // A fresh limiter checks the counter first. If it is already at its // boundary, refusal returns after a keep decision and does not write // a missing descriptor or any other record. @@ -361,12 +362,26 @@ export function createDurableLimiter( retryAfter: retryAfter(windowEndsAt, now), }; } - if (!(await ensureDescriptor(expected, true))) { + const rows = await collection.listVersioned(expected.partition); + const hasDescriptor = rows.some( + ({ value }) => value.id === POLICY_DESCRIPTOR_ID, + ); + if (!hasDescriptor && rows.length > 0) { return { allowed: false, retryAfter: retryAfter(windowEndsAt, now), }; } + createDescriptor = !hasDescriptor; + } + // Revalidate the descriptor before every counter write. Once this + // instance has observed a descriptor, a later absence fails closed + // instead of silently recreating state after a coordinated reset. + if (!(await ensureDescriptor(expected, createDescriptor))) { + return { + allowed: false, + retryAfter: retryAfter(windowEndsAt, now), + }; } const result = await collection.update( diff --git a/test/release-package.test.ts b/test/release-package.test.ts index 861d149..8990379 100644 --- a/test/release-package.test.ts +++ b/test/release-package.test.ts @@ -171,6 +171,17 @@ describe("publish workflow boundaries", () => { expect(workflow).toContain("NPM_CONFIG_USERCONFIG"); expect(workflow).toContain("NPM_CONFIG_GLOBALCONFIG"); expect(workflow).toContain("id-token: write"); + for (const key of [ + "COMSPEC", + "HOMEDRIVE", + "HOMEPATH", + "PATHEXT", + "SYSTEMDRIVE", + "USERPROFILE", + "WINDIR", + ]) { + expect(workflow).toContain(`"${key}"`); + } }); it("keeps GitHub expressions out of run scripts", async () => { @@ -205,5 +216,12 @@ describe("publish workflow boundaries", () => { "utf8", ); expect(workflow).toContain("pnpm run release:check"); + expect(workflow.match(/corepack enable/gu)).toHaveLength(1); + }); + + it("uses deterministic LF line endings", async () => { + await expect(readFile(resolve(".gitattributes"), "utf8")).resolves.toBe( + "* text=auto eol=lf\n", + ); }); }); From 3b6e07ffead7feda5013805f09d04e5d6c85a575 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 15:06:04 -0500 Subject: [PATCH 3/4] Keep pnpm cache discovery explicit --- .github/workflows/ci.yml | 6 +++++- test/release-package.test.ts | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5edd253..7aba046 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,13 +30,17 @@ jobs: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + # setup-node resolves the pnpm cache before later steps can run. + - name: Enable Corepack for cache discovery + run: corepack enable + - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: node-version: ${{ matrix.node-version }} cache: pnpm - - name: Enable Corepack + - name: Enable Corepack for selected Node.js run: corepack enable - name: Install dependencies diff --git a/test/release-package.test.ts b/test/release-package.test.ts index 8990379..a70921d 100644 --- a/test/release-package.test.ts +++ b/test/release-package.test.ts @@ -216,7 +216,10 @@ describe("publish workflow boundaries", () => { "utf8", ); expect(workflow).toContain("pnpm run release:check"); - expect(workflow.match(/corepack enable/gu)).toHaveLength(1); + expect(workflow.match(/corepack enable/gu)).toHaveLength(2); + expect(workflow).toContain( + "setup-node resolves the pnpm cache before later steps can run", + ); }); it("uses deterministic LF line endings", async () => { From 80058dbbd1da92bb05ccdd3e18ea6dfd93711a4c Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 15:10:39 -0500 Subject: [PATCH 4/4] Correct publish workflow context usage --- .github/workflows/publish.yml | 13 +++++++++---- test/release-package.test.ts | 22 +++++++++++++++++++++- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 4ffc1bd..c316cd1 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,7 +18,7 @@ jobs: prepare: runs-on: ubuntu-latest outputs: - manifest-digest: ${{ steps.pack.outputs.manifest-digest }} + manifest_digest: ${{ steps.pack.outputs['manifest-digest'] }} env: CI: "1" RELEASE_TAG: ${{ github.event.release.tag_name }} @@ -128,7 +128,6 @@ jobs: CI: "1" RELEASE_TAG: ${{ github.event.release.tag_name }} RELEASE_COMMIT: ${{ github.sha }} - ARTIFACT_DIR: ${{ runner.temp }}/rate-limit-release steps: - name: Check out the authenticated commit @@ -151,6 +150,8 @@ jobs: path: ${{ runner.temp }}/rate-limit-release - name: Import from an isolated consumer + env: + ARTIFACT_DIR: ${{ runner.temp }}/rate-limit-release run: node scripts/release-package.mjs smoke --manifest "${ARTIFACT_DIR}/package-manifest.json" publish: @@ -166,8 +167,7 @@ jobs: RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} - MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest-digest }} - ARTIFACT_DIR: ${{ runner.temp }}/rate-limit-release + MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} steps: - name: Re-authenticate the release tag @@ -216,6 +216,9 @@ jobs: 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: @@ -224,6 +227,8 @@ jobs: - name: Verify and publish the prepared tarball shell: bash + env: + ARTIFACT_DIR: ${{ runner.temp }}/rate-limit-release run: | set -euo pipefail node <<'NODE' diff --git a/test/release-package.test.ts b/test/release-package.test.ts index a70921d..c9b68c9 100644 --- a/test/release-package.test.ts +++ b/test/release-package.test.ts @@ -165,12 +165,18 @@ describe("publish workflow boundaries", () => { ); expect(workflow).toContain("include-hidden-files: false"); - expect(workflow).toContain("manifest-digest:"); + expect(workflow).toContain("manifest_digest:"); + expect(workflow).toContain("steps.pack.outputs['manifest-digest']"); + expect(workflow).toContain("needs.prepare.outputs.manifest_digest"); + expect(workflow).not.toContain("outputs.manifest-digest"); expect(workflow).toContain("needs: [prepare, smoke]"); expect(workflow).toContain("--ignore-scripts"); expect(workflow).toContain("NPM_CONFIG_USERCONFIG"); expect(workflow).toContain("NPM_CONFIG_GLOBALCONFIG"); expect(workflow).toContain("id-token: write"); + expect(workflow).toContain( + "npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/", + ); for (const key of [ "COMSPEC", "HOMEDRIVE", @@ -210,6 +216,20 @@ describe("publish workflow boundaries", () => { expect(runSections.join("\n")).not.toContain("${{"); }); + it("keeps step-only contexts out of job environments", async () => { + const workflow = await readFile( + resolve(".github/workflows/publish.yml"), + "utf8", + ); + const jobEnvironments = [ + ...workflow.matchAll(/^ {4}env:\n((?: {6}.+\n)*)/gmu), + ] + .map((match) => match[1] ?? "") + .join("\n"); + + expect(jobEnvironments).not.toMatch(/\$\{\{\s*(?:runner|steps)\./u); + }); + it("runs the release metadata check in CI", async () => { const workflow = await readFile( resolve(".github/workflows/ci.yml"),