Files
clean-architecture-frontend…/tests/unit/public-response-cache-codec.test.ts
T
DongHyeonka de2670cda5 test(cache-storage): no-cache와 Set-Cookie 응답 거절을 따로 고정한다
문제: 1101/02-04의 두 변이가 이번에도 cache 단위 테스트를 모두
통과했다. N26b는 Cache-Control: no-cache 거절, N26은 Set-Cookie 응답
거절을 지운다. 둘 다 빠지면 사용자별이거나 재검증이 필요한 응답이 익명
공용 캐시에 들어간다. 기존 표는 no-store·pragma·www-authenticate만 따로
보았다.

고른 방법: 응답 검증 표("keeps response validation failure codes")에 두
행을 더한다. 각 행은 규칙 하나만 어긴다.

위험·한계: 테스트만 바꾼다.

검증: 두 변이를 하나씩 넣고 cache 단위 3파일 + tests/recipes를 돌렸다.
둘 다 이 테스트가 실패했고 되돌린 뒤 통과. eslint 통과.

Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 1101/02-04
2026-11-04 21:00:22 +09:00

334 lines
11 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",
);
// 2026-11-01 02-04 (N26b, N26). Each directive or header on its own.
expect(
await stageCode([valid], response({ "cache-control": "no-cache" })),
).toBe("POLICY_REJECTED");
expect(
await stageCode([valid], response({ "set-cookie": "session=1" })),
).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");
});
});