Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
487 changes: 454 additions & 33 deletions .github/workflows/publish.yml

Large diffs are not rendered by default.

29 changes: 18 additions & 11 deletions docs/RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
37 changes: 37 additions & 0 deletions packages/cache-conformance/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
71 changes: 70 additions & 1 deletion packages/cache-core/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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<string>();
Expand Down Expand Up @@ -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<string>(),
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 });
Expand Down Expand Up @@ -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<string>();
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,
);
});
});
59 changes: 51 additions & 8 deletions packages/cache-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 Tag validation allows control and brace characters (risk)

validateCacheTags only calls assertWellFormedCacheString (surrogate check). Unlike requireToken for namespace/key/hashTag, it never checks CONTROL ([\u0000-\u001F\u007F]) or {}:.

A tag like "a\u0000b", "t{evil}", or "x:y" passes validateCacheTags and becomes tagKey = "${prefix}t:${tag}" (control/{/} in Redis key) or later tagMember handling. While Redis accepts binary keys, control characters break logging/metrics and "{"/"}" violate the invariant that keyPrefix must not contain braces so hashTag remains the first brace pair. The conformance suite now tests only surrogate rejection.

Inspected packages/cache-core/src/index.ts:118 (validateCacheTags) vs requireToken:96 and Redis tagKey:145. cache-conformance ill-formed test at index.ts:133 only asserts surrogates.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declined: tag compatibility intentionally changes only ill-formed UTF-16 as scoped. Braces and colons in a tag do not participate in CacheKey hash-tag formatting; sidecar operations remain single-key, and tags are never logged. Existing valid tag strings therefore remain accepted.

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`);
Expand All @@ -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;
}

Expand Down Expand Up @@ -257,6 +290,10 @@ export async function runGetOrCompute<T>(
options: RunGetOrComputeOptions<T>,
): Promise<CacheResult<T>> {
Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
const formatted = formatCacheKey(options.key);
const validatedOptions: RunGetOrComputeOptions<T> =
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`;
Expand Down Expand Up @@ -294,7 +331,7 @@ export async function runGetOrCompute<T>(
})
) {
const recomputed = await options.singleFlight.do(computeFlight, () =>
computeAndStore(options, clockMs(options.clock)),
computeAndStore(validatedOptions, clockMs(options.clock)),
);
if (recomputed.status === "hit") {
return recomputed;
Expand All @@ -316,7 +353,7 @@ export async function runGetOrCompute<T>(
}

return options.singleFlight.do(computeFlight, () =>
computeAndStore(options, clockMs(options.clock)),
computeAndStore(validatedOptions, clockMs(options.clock)),
);
}

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<T>(
Expand Down Expand Up @@ -593,7 +635,8 @@ export function createUnavailableCacheStore(
: { earlyExpiration: computeOptions.earlyExpiration }),
});
},
async invalidateTags() {
async invalidateTags(tags) {
validateCacheTags(tags);
return { status: "error", error: down };
},
async ping() {
Expand Down
Loading
Loading