public-response-cache-adapter.ts (1986 lines) and download-delivery-adapter.ts (1491 lines) mixed the facade with codecs and validators. Moved verbatim: - cache-storage/public-cache-codec.ts: manifest normalization and canonical digest input, marker/active-pointer validation, bounded control JSON, owned cache names, CacheValidationFailure -> Result mapping. - cache-storage/public-cache-response-validation.ts: response admission (status, directives, Content-Type, Vary, bounded body, digest). - browser-files/download-input-validation.ts: request snapshot, input/limit checks, presigned and browser-managed capability validation, handoff target. The adapters drop to 1164 and 1157 lines. Two non-verbatim edits: validateDownloadInput takes a structural DownloadInputValidationOptions instead of DownloadDeliveryAdapterOptions (no import cycle), and readBodyBounded races reads on the kernel createAbortableOperation instead of its own abort listener. Moving it out of a primitive-importing file would otherwise have raised the hand-rolled abort ratchet to 20/19; the abort outcome (ABORTED, reader cancelled) is unchanged. Verified: characterization tests added first and passing before the move (cache manifest/response/control-JSON failure codes, lookup abort during a pending body read; download input validation codes); a line diff confirms the moved code is verbatim apart from the two edits above. Inventory 139/139, lane gates, check:browser-file-storage-boundaries pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
327 lines
10 KiB
TypeScript
327 lines
10 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
|
|
import type { PublicCacheAsset } from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts";
|
|
import { createDefaultPublicCachePolicy } from "../../src/adapters/cache-storage/public-cache-policy.ts";
|
|
import { createPublicResponseCacheAdapter } from "../../src/adapters/cache-storage/public-response-cache-adapter.ts";
|
|
import {
|
|
MemoryCacheStorage,
|
|
digestHex,
|
|
immediateLock,
|
|
manifestFor,
|
|
} from "./public-response-cache-fixture.ts";
|
|
|
|
/**
|
|
* Q-6.2-11. Characterization of the manifest codec and response validation
|
|
* before they moved out of the adapter: every rejection keeps its code.
|
|
*/
|
|
const ORIGIN = "https://assets.example.test";
|
|
const policy = createDefaultPublicCachePolicy(ORIGIN);
|
|
const BYTES = new Uint8Array([1, 2, 3, 4]);
|
|
|
|
async function asset(
|
|
overrides: Partial<PublicCacheAsset> = {},
|
|
): Promise<PublicCacheAsset> {
|
|
return {
|
|
absoluteUrl: `${ORIGIN}/app.js`,
|
|
expectedByteLength: BYTES.byteLength,
|
|
expectedContentType: "application/javascript",
|
|
integrity: { algorithm: "SHA-256", digestHex: await digestHex(BYTES) },
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function adapterWith(
|
|
respond: () => Response = () =>
|
|
new Response(Uint8Array.from(BYTES), {
|
|
headers: {
|
|
"cache-control": "public",
|
|
"content-type": "application/javascript",
|
|
},
|
|
}),
|
|
cacheStorage = new MemoryCacheStorage(),
|
|
) {
|
|
return createPublicResponseCacheAdapter({
|
|
cacheStorage: cacheStorage as unknown as CacheStorage,
|
|
crypto: globalThis.crypto,
|
|
mutationLock: immediateLock,
|
|
policy,
|
|
fetcher: async () => respond(),
|
|
});
|
|
}
|
|
|
|
async function stageCode(
|
|
assets: readonly PublicCacheAsset[],
|
|
respond?: () => Response,
|
|
): Promise<string> {
|
|
const manifest = {
|
|
releaseRegistryId: "codec-release",
|
|
assets,
|
|
manifestDigestHex: "0".repeat(64),
|
|
};
|
|
try {
|
|
Object.assign(manifest, await manifestFor("codec-release", assets, policy));
|
|
} catch {
|
|
// An invalid manifest has no digest; staging must still reject it.
|
|
}
|
|
const result = await adapterWith(respond).admin.stageRelease(manifest);
|
|
return result.ok ? "OK" : result.error.code;
|
|
}
|
|
|
|
describe("public cache codec and response validation (characterization)", () => {
|
|
it("keeps manifest normalization failure codes", async () => {
|
|
const valid = await asset();
|
|
expect(await stageCode([])).toBe("LIMIT_EXCEEDED");
|
|
expect(await stageCode([valid, valid])).toBe("CONFLICT");
|
|
expect(
|
|
await stageCode([
|
|
await asset({
|
|
integrity: { algorithm: "SHA-1" as "SHA-256", digestHex: "0" },
|
|
}),
|
|
]),
|
|
).toBe("INVALID_INPUT");
|
|
expect(
|
|
await stageCode([await asset({ expectedByteLength: -1 })]),
|
|
).toBe("INVALID_INPUT");
|
|
for (const absoluteUrl of [
|
|
"https://user:secret@assets.example.test/app.js",
|
|
"https://other.example.test/app.js",
|
|
`${ORIGIN}/app.js#fragment`,
|
|
`${ORIGIN}/app.js?token=secret`,
|
|
`${ORIGIN}/.well-known/ca-public-cache-v1/candidate`,
|
|
]) {
|
|
expect(await stageCode([await asset({ absoluteUrl })])).toBe(
|
|
"POLICY_REJECTED",
|
|
);
|
|
}
|
|
expect(await stageCode([await asset({ absoluteUrl: "not a url" })])).toBe(
|
|
"INVALID_INPUT",
|
|
);
|
|
expect(
|
|
await stageCode([await asset({ expectedContentType: "text/html" })]),
|
|
).toBe("POLICY_REJECTED");
|
|
expect(
|
|
await stageCode([
|
|
await asset({ requestHeaders: [["authorization", "Bearer x"]] }),
|
|
]),
|
|
).toBe("POLICY_REJECTED");
|
|
expect(
|
|
await stageCode([
|
|
await asset({
|
|
requestHeaders: [["accept"] as unknown as readonly [string, string]],
|
|
}),
|
|
]),
|
|
).toBe("INVALID_INPUT");
|
|
|
|
const wrongDigest = await adapterWith().admin.stageRelease({
|
|
releaseRegistryId: "codec-release",
|
|
assets: [valid],
|
|
manifestDigestHex: "0".repeat(64),
|
|
});
|
|
expect(wrongDigest).toMatchObject({
|
|
ok: false,
|
|
error: { code: "INTEGRITY_FAILED" },
|
|
});
|
|
const badRelease = await adapterWith().admin.stageRelease({
|
|
...(await manifestFor("codec-release", [valid], policy)),
|
|
releaseRegistryId: "bad release id",
|
|
});
|
|
expect(badRelease).toMatchObject({
|
|
ok: false,
|
|
error: { code: "INVALID_INPUT" },
|
|
});
|
|
});
|
|
|
|
it("keeps response validation failure codes", async () => {
|
|
const valid = await asset();
|
|
const response = (
|
|
headers: Record<string, string>,
|
|
body: Uint8Array = BYTES,
|
|
init: ResponseInit = {},
|
|
) => () =>
|
|
new Response(Uint8Array.from(body), {
|
|
...init,
|
|
headers: {
|
|
"cache-control": "public",
|
|
"content-type": "application/javascript",
|
|
...headers,
|
|
},
|
|
});
|
|
|
|
expect(await stageCode([valid], response({}))).toBe("OK");
|
|
expect(
|
|
await stageCode([valid], response({}, BYTES, { status: 203 })),
|
|
).toBe("POLICY_REJECTED");
|
|
expect(
|
|
await stageCode([valid], response({ "cache-control": "no-store" })),
|
|
).toBe("POLICY_REJECTED");
|
|
expect(await stageCode([valid], response({ pragma: "no-cache" }))).toBe(
|
|
"POLICY_REJECTED",
|
|
);
|
|
expect(
|
|
await stageCode([valid], response({ "www-authenticate": "Basic" })),
|
|
).toBe("POLICY_REJECTED");
|
|
expect(
|
|
await stageCode([valid], response({ "content-type": "text/html" })),
|
|
).toBe("POLICY_REJECTED");
|
|
expect(
|
|
await stageCode([valid], response({ "content-type": "text/css" })),
|
|
).toBe("INTEGRITY_FAILED");
|
|
expect(await stageCode([valid], response({ vary: "Cookie" }))).toBe(
|
|
"POLICY_REJECTED",
|
|
);
|
|
expect(
|
|
await stageCode([valid], response({ "content-length": "99999999999" })),
|
|
).toBe("LIMIT_EXCEEDED");
|
|
expect(
|
|
await stageCode([valid], response({}, new Uint8Array([1, 2, 3, 4, 5]))),
|
|
).toBe("INTEGRITY_FAILED");
|
|
expect(
|
|
await stageCode([valid], response({}, new Uint8Array([1, 2, 3]))),
|
|
).toBe("INTEGRITY_FAILED");
|
|
expect(
|
|
await stageCode([valid], response({}, new Uint8Array([4, 3, 2, 1]))),
|
|
).toBe("INTEGRITY_FAILED");
|
|
});
|
|
|
|
it("cancels a pending cached body read when the lookup is aborted", async () => {
|
|
const valid = await asset();
|
|
const manifest = await manifestFor("codec-release", [valid], policy);
|
|
const storage = new MemoryCacheStorage();
|
|
const adapter = adapterWith(undefined, storage);
|
|
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
|
|
ok: true,
|
|
});
|
|
expect(
|
|
await adapter.admin.activateRelease(
|
|
manifest.releaseRegistryId,
|
|
manifest.manifestDigestHex,
|
|
),
|
|
).toMatchObject({ ok: true });
|
|
const name = [...storage.caches.keys()].find((key) =>
|
|
key.includes(":codec-release:"),
|
|
)!;
|
|
const cache = storage.caches.get(name)!;
|
|
const match = cache.match.bind(cache);
|
|
let cancelled = 0;
|
|
let pulled: (() => void) | undefined;
|
|
const bodyRequested = new Promise<void>((resolve) => {
|
|
pulled = resolve;
|
|
});
|
|
cache.match = async (request: RequestInfo | URL) => {
|
|
if (request instanceof Request && request.url === valid.absoluteUrl) {
|
|
return new Response(
|
|
new ReadableStream<Uint8Array>({
|
|
pull() {
|
|
pulled?.();
|
|
return new Promise<void>(() => {});
|
|
},
|
|
cancel() {
|
|
cancelled += 1;
|
|
},
|
|
}),
|
|
{
|
|
headers: {
|
|
"cache-control": "public",
|
|
"content-type": "application/javascript",
|
|
},
|
|
},
|
|
);
|
|
}
|
|
return await match(request);
|
|
};
|
|
|
|
const controller = new AbortController();
|
|
const lookup = adapter.responses.matchActiveExact({
|
|
absoluteUrl: valid.absoluteUrl,
|
|
signal: controller.signal,
|
|
});
|
|
await bodyRequested;
|
|
controller.abort();
|
|
expect(await lookup).toMatchObject({
|
|
ok: false,
|
|
error: { code: "ABORTED" },
|
|
});
|
|
expect(cancelled).toBe(1);
|
|
});
|
|
|
|
it("keeps control JSON decoding failure codes", async () => {
|
|
const valid = await asset();
|
|
const manifest = await manifestFor("codec-release", [valid], policy);
|
|
const lookupAfter = async (
|
|
tamper: (storage: MemoryCacheStorage) => Promise<void>,
|
|
): Promise<string> => {
|
|
const storage = new MemoryCacheStorage();
|
|
const adapter = adapterWith(undefined, storage);
|
|
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
|
|
ok: true,
|
|
});
|
|
expect(
|
|
await adapter.admin.activateRelease(
|
|
manifest.releaseRegistryId,
|
|
manifest.manifestDigestHex,
|
|
),
|
|
).toMatchObject({ ok: true });
|
|
await tamper(storage);
|
|
const result = await adapter.responses.matchActiveExact({
|
|
absoluteUrl: valid.absoluteUrl,
|
|
});
|
|
return result.ok ? "OK" : result.error.code;
|
|
};
|
|
const replace = async (
|
|
storage: MemoryCacheStorage,
|
|
path: "active" | "candidate",
|
|
body: BodyInit,
|
|
): Promise<void> => {
|
|
const name = [...storage.caches.keys()].find((key) =>
|
|
path === "active"
|
|
? key.endsWith(":control")
|
|
: key.includes(":codec-release:"),
|
|
)!;
|
|
await storage.caches
|
|
.get(name)!
|
|
.put(
|
|
new Request(`${ORIGIN}/.well-known/ca-public-cache-v1/${path}`),
|
|
new Response(body, {
|
|
headers: { "content-type": "application/json" },
|
|
}),
|
|
);
|
|
};
|
|
|
|
expect(await lookupAfter(async () => {})).toBe("OK");
|
|
expect(
|
|
await lookupAfter((storage) => replace(storage, "active", "{not json")),
|
|
).toBe("CORRUPT_DATA");
|
|
expect(
|
|
await lookupAfter((storage) =>
|
|
replace(storage, "active", new Uint8Array([0xff, 0xfe])),
|
|
),
|
|
).toBe("CORRUPT_DATA");
|
|
expect(
|
|
await lookupAfter((storage) =>
|
|
replace(storage, "active", JSON.stringify({ schemaVersion: 2 })),
|
|
),
|
|
).toBe("CORRUPT_DATA");
|
|
expect(
|
|
await lookupAfter(async (storage) => {
|
|
const name = [...storage.caches.keys()].find((key) =>
|
|
key.includes(":codec-release:"),
|
|
)!;
|
|
const cache = storage.caches.get(name)!;
|
|
const marker = await (await cache.match(
|
|
new Request(`${ORIGIN}/.well-known/ca-public-cache-v1/candidate`),
|
|
))!.json();
|
|
await replace(
|
|
storage,
|
|
"candidate",
|
|
JSON.stringify({ ...marker, entryCount: 2 }),
|
|
);
|
|
}),
|
|
).toBe("CORRUPT_DATA");
|
|
expect(
|
|
await lookupAfter((storage) =>
|
|
replace(storage, "candidate", JSON.stringify({ verified: false })),
|
|
),
|
|
).toBe("CORRUPT_DATA");
|
|
});
|
|
});
|