diff --git a/docs/architecture/browser-file-and-origin-storage.md b/docs/architecture/browser-file-and-origin-storage.md index b3dfbb11..d4ff71c7 100644 --- a/docs/architecture/browser-file-and-origin-storage.md +++ b/docs/architecture/browser-file-and-origin-storage.md @@ -976,6 +976,14 @@ preflight와 정확히 2 MiB(2,097,152 bytes) cap의 stream reader로 완전히 strict UTF-8와 runtime schema를 검증하며, cap을 넘으면 reader를 cancel하고 `CORRUPT_DATA`로 fail-closed한다. +active pointer의 rollback 목록 길이는 읽을 때 현재 +`retainedPreviousReleaseCount`와 비교하지 않는다. 더 큰 값으로 쓴 pointer도 +정상으로 읽고, 다음 activation이 목록을 현재 값으로 자른다. 읽을 수 없는 +pointer(`CORRUPT_DATA`: 손상, 또는 지금 정책으로 허용되지 않는 ID)는 조회와 +cleanup을 계속 막지만, 다음 `activateRelease`가 전체 재검증을 통과한 후보로 +rollback 목록 없이 덮어쓴다. pointer 읽기의 일시 오류는 activation을 멈춘다 +(0929/02-01). + 현재 `cleanupOwned()`와 `inspect()`는 위 ownership/integrity 경계를 지키지만 cache count에 대한 cursor, per-invocation max count와 deadline은 제공하지 않는다. 따라서 cache 수에 비례한 unbounded maintenance를 production boot path에 diff --git a/src/adapters/cache-storage/public-cache-codec.ts b/src/adapters/cache-storage/public-cache-codec.ts index 000cf490..ec6681b5 100644 --- a/src/adapters/cache-storage/public-cache-codec.ts +++ b/src/adapters/cache-storage/public-cache-codec.ts @@ -15,6 +15,7 @@ import { } from "../browser-file-storage/result.ts"; import { isAllowedPublicCacheOrigin, + MAX_RETAINED_PREVIOUS_RELEASE_COUNT, type PublicCacheRuntimePolicy, } from "./public-cache-policy.ts"; @@ -452,8 +453,12 @@ export function isActivePointer( ) && "rollbackCandidateCacheNames" in value && Array.isArray(value.rollbackCandidateCacheNames) && + // 0929/02-01. The list length is not checked against the current + // `retainedPreviousReleaseCount`: a pointer written under a larger value + // is still a good pointer. The next activation trims the list (`slice`). + // The ceiling is the policy's own maximum. value.rollbackCandidateCacheNames.length <= - policy.retainedPreviousReleaseCount && + MAX_RETAINED_PREVIOUS_RELEASE_COUNT && new Set(value.rollbackCandidateCacheNames).size === value.rollbackCandidateCacheNames.length && value.rollbackCandidateCacheNames.every( diff --git a/src/adapters/cache-storage/public-cache-policy.ts b/src/adapters/cache-storage/public-cache-policy.ts index 87bc7fdd..1a95a69e 100644 --- a/src/adapters/cache-storage/public-cache-policy.ts +++ b/src/adapters/cache-storage/public-cache-policy.ts @@ -35,6 +35,8 @@ export type PublicCacheSafeObserver = ( observation: PublicCacheSafeObservation, ) => void; +/** Also the longest rollback list a stored pointer may carry (0929/02-01). */ +export const MAX_RETAINED_PREVIOUS_RELEASE_COUNT = 5; const RELEASE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u; const CACHE_PREFIX = /^[A-Za-z0-9][A-Za-z0-9._:-]{2,63}:$/u; const DEFAULT_PUBLIC_CONTENT_TYPE = @@ -123,7 +125,8 @@ export function assertPublicCachePolicy( policy.maxEntriesPerRelease > 10_000 || !Number.isSafeInteger(policy.retainedPreviousReleaseCount) || policy.retainedPreviousReleaseCount < 1 || - policy.retainedPreviousReleaseCount > 5 || + policy.retainedPreviousReleaseCount > + MAX_RETAINED_PREVIOUS_RELEASE_COUNT || !headerNameList(policy.allowedRequestHeaderNames) || !headerNameList(policy.allowedVaryHeaderNames) || !headerNameList(policy.allowedResponseHeaderNames) || diff --git a/src/adapters/cache-storage/public-response-cache-adapter.ts b/src/adapters/cache-storage/public-response-cache-adapter.ts index fb45c70f..10d153e9 100644 --- a/src/adapters/cache-storage/public-response-cache-adapter.ts +++ b/src/adapters/cache-storage/public-response-cache-adapter.ts @@ -696,18 +696,27 @@ export function createPublicResponseCacheAdapter( dependencies.cacheStorage!, policy, ); - if (!previousPointer.ok) { + // 0929/02-01. An unreadable pointer (damaged, or no longer valid + // under this policy) is replaced by this verified candidate with + // an empty rollback list, rather than blocking every later + // deployment. A transient read failure still stops activation. + if ( + !previousPointer.ok && + previousPointer.error.code !== "CORRUPT_DATA" + ) { return rebaseFailure( previousPointer.error, "CACHE_ACTIVATE", ); } + const previous = previousPointer.ok + ? previousPointer.value + : null; const rollbackCandidateCacheNames = [ - ...(previousPointer.value + ...(previous ? [ - previousPointer.value.candidateCacheName, - ...previousPointer.value - .rollbackCandidateCacheNames, + previous.candidateCacheName, + ...previous.rollbackCandidateCacheNames, ] : []), ] diff --git a/tests/unit/public-response-cache-repair.test.ts b/tests/unit/public-response-cache-repair.test.ts index bd29d254..3ae5807c 100644 --- a/tests/unit/public-response-cache-repair.test.ts +++ b/tests/unit/public-response-cache-repair.test.ts @@ -1,7 +1,15 @@ 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 { + activePointerRequest, + controlCacheName, +} from "../../src/adapters/cache-storage/public-cache-codec.ts"; +import { + createDefaultPublicCachePolicy, + resolvePublicCachePolicy, + type PublicCacheRuntimePolicy, +} from "../../src/adapters/cache-storage/public-cache-policy.ts"; import { createPublicResponseCacheAdapter } from "../../src/adapters/cache-storage/public-response-cache-adapter.ts"; import { MemoryCacheStorage, @@ -243,3 +251,150 @@ describe("public response cache repair is failure-atomic", () => { ).toMatchObject({ ok: true }); }); }); + +/** + * 0929/02-01. The active pointer was checked against the policy of the build + * reading it, so lowering `retainedPreviousReleaseCount` or a damaged pointer + * stopped lookup, activation and cleanup for good. + */ +describe("public cache pointer after a policy change or damage (0929/02-01)", () => { + const origin = "https://assets.example.test"; + const policyRetaining = (retainedPreviousReleaseCount: number) => + resolvePublicCachePolicy({ + ...createDefaultPublicCachePolicy(origin), + retainedPreviousReleaseCount, + }); + const assetUrl = (releaseRegistryId: string) => + `${origin}/${releaseRegistryId}.js`; + const body = (releaseRegistryId: string) => + new TextEncoder().encode(`release ${releaseRegistryId}`); + + function adapterFor( + cacheStorage: MemoryCacheStorage, + policy: PublicCacheRuntimePolicy, + ) { + return createPublicResponseCacheAdapter({ + cacheStorage: cacheStorage as unknown as CacheStorage, + crypto: globalThis.crypto, + mutationLock: immediateLock, + policy, + fetcher: async (request: Request) => + new Response( + Uint8Array.from( + body(new URL(request.url).pathname.slice(1, -".js".length)), + ), + { + headers: { + "cache-control": "public", + "content-type": "application/javascript", + }, + }, + ), + }); + } + + async function manifestOf( + releaseRegistryId: string, + policy: PublicCacheRuntimePolicy, + ) { + const bytes = body(releaseRegistryId); + return await manifestFor( + releaseRegistryId, + [ + { + absoluteUrl: assetUrl(releaseRegistryId), + expectedByteLength: bytes.byteLength, + expectedContentType: "application/javascript", + integrity: { algorithm: "SHA-256", digestHex: await digestHex(bytes) }, + }, + ], + policy, + ); + } + + async function deploy( + adapter: ReturnType, + releaseRegistryId: string, + policy: PublicCacheRuntimePolicy, + ) { + const manifest = await manifestOf(releaseRegistryId, policy); + expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ + ok: true, + }); + return await adapter.admin.activateRelease( + manifest.releaseRegistryId, + manifest.manifestDigestHex, + ); + } + + it("keeps working after retainedPreviousReleaseCount is lowered", async () => { + const cacheStorage = new MemoryCacheStorage(); + const before = policyRetaining(3); + const wide = adapterFor(cacheStorage, before); + for (const id of ["r1", "r2", "r3", "r4"]) { + expect(await deploy(wide, id, before)).toMatchObject({ ok: true }); + } + + const after = policyRetaining(1); + const narrow = adapterFor(cacheStorage, after); + + expect( + await narrow.responses.matchActiveExact({ absoluteUrl: assetUrl("r4") }), + ).toMatchObject({ ok: true, value: expect.anything() }); + expect(await deploy(narrow, "r5", after)).toMatchObject({ ok: true }); + expect(await narrow.admin.cleanupOwned()).toMatchObject({ ok: true }); + expect( + await narrow.responses.matchActiveExact({ absoluteUrl: assetUrl("r5") }), + ).toMatchObject({ ok: true, value: expect.anything() }); + }); + + it("replaces a damaged pointer on the next verified activation", async () => { + const cacheStorage = new MemoryCacheStorage(); + const policy = policyRetaining(1); + const adapter = adapterFor(cacheStorage, policy); + expect(await deploy(adapter, "r1", policy)).toMatchObject({ ok: true }); + const control = await cacheStorage.open(controlCacheName(policy)); + await control.put( + activePointerRequest(policy), + new Response('{"schemaVersion":1,"releaseRegis', { + headers: { "content-type": "application/json" }, + }), + ); + + // A release that was never staged is still refused. + const unstaged = await manifestOf("r9", policy); + expect( + await adapter.admin.activateRelease( + unstaged.releaseRegistryId, + unstaged.manifestDigestHex, + ), + ).toMatchObject({ ok: false }); + + expect(await deploy(adapter, "r2", policy)).toMatchObject({ ok: true }); + expect(await adapter.admin.cleanupOwned()).toMatchObject({ ok: true }); + expect( + await adapter.responses.matchActiveExact({ absoluteUrl: assetUrl("r2") }), + ).toMatchObject({ ok: true, value: expect.anything() }); + }); + + it("still stops activation when the pointer read fails transiently", async () => { + const cacheStorage = new MemoryCacheStorage(); + const policy = policyRetaining(1); + const adapter = adapterFor(cacheStorage, policy); + expect(await deploy(adapter, "r1", policy)).toMatchObject({ ok: true }); + const control = cacheStorage.caches.get(controlCacheName(policy))!; + const realMatch = control.match.bind(control); + control.match = async () => { + throw new DOMException("Storage is busy", "InvalidStateError"); + }; + + expect(await deploy(adapter, "r2", policy)).toMatchObject({ + ok: false, + error: { code: "UNAVAILABLE", operation: "CACHE_ACTIVATE" }, + }); + control.match = realMatch; + expect( + await adapter.responses.matchActiveExact({ absoluteUrl: assetUrl("r1") }), + ).toMatchObject({ ok: true, value: expect.anything() }); + }); +});