chore: sync the frontend template from 5434760 to ebea300

Carries 21 template commits: the shared IndexedDB connection/transaction
kernel and the four runtimes moved onto it, the adapter barrel boundary and
the architecture rule that enforces it, the feature adapter contribution
model, `feature-http-binding`, the split of several oversized test files,
and the release identity now derived from the package name.

Product identity is unchanged. The three hard-coded `tech-log-frontend/…`
verifier ids are gone because the template derives them from the package
name and this package is `tech-log-frontend`.

Two decisions worth naming. The platform HTTP executor is the template's
verbatim — it now takes the installed contract so a feature's types flow
through the binding — and TechLog's four gateways, which address operations
by id, reach it through one adapter at the composition root instead of being
rewritten here. And the three derived CI baselines were recomputed from the
merged `config/ci/gates.json` rather than taken from either side: 94 command
definitions, 106 references, 141 artifacts, gate shape `629e5898…`. The
method was checked by first reproducing the pre-merge values from the
pre-merge file.

Verified here: types, lint, architecture, adapter inventory, CI contract,
design system, diagnostics, remediation ledger, browser security and build
all pass; 1789 unit, 152 component, 415 TechLog, 102 integration, 19
reference-feature, 17 recipe and 7 contract tests pass. Five gates stay
red and every one was reproduced at b297d65 first: `check:i18n`,
`check:registries`, `test:runtime-schema`, `verify:documentation` and
`test:sample-removal`.

Full decision record, including what was deliberately not carried and the
five open follow-ups, in `docs/operations/template-sync-2026-09-21.md`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-21 16:31:05 +09:00
co-authored by Claude Opus 5
parent b297d659f5
commit afde2b1da1
196 changed files with 21854 additions and 9992 deletions
+28 -4
View File
@@ -223,11 +223,12 @@ describe("bounded body reader", () => {
});
});
it("abandons and cancels a forbidden-body probe when its lifetime aborts", async () => {
it("abandons a pending bounded read when the operation is aborted", async () => {
const controller = new AbortController();
const reader = {
read: vi.fn(() => new Promise<never>(() => {})),
cancel: vi.fn().mockRejectedValue(new Error("abandoned cancel failed")),
cancel: vi.fn().mockRejectedValue(new Error("cancel ignored")),
releaseLock: vi.fn(),
};
const response = {
@@ -235,10 +236,33 @@ describe("bounded body reader", () => {
body: { getReader: () => reader },
} as unknown as Response;
const outcome = probeForbiddenBody(response, controller.signal);
const pending = readBoundedBytes(response, 8, controller.signal);
controller.abort();
await expect(outcome).resolves.toEqual({
await expect(pending).resolves.toEqual({
ok: false,
code: "RESPONSE_STREAM_FAILURE",
});
expect(reader.cancel).toHaveBeenCalledOnce();
expect(reader.releaseLock).toHaveBeenCalledOnce();
});
it("abandons a pending forbidden-body probe when the operation is aborted", async () => {
const controller = new AbortController();
const reader = {
read: vi.fn(() => new Promise<never>(() => {})),
cancel: vi.fn().mockRejectedValue(new Error("cancel ignored")),
releaseLock: vi.fn(),
};
const response = {
headers: new Headers(),
body: { getReader: () => reader },
} as unknown as Response;
const pending = probeForbiddenBody(response, controller.signal);
controller.abort();
await expect(pending).resolves.toEqual({
ok: false,
code: "RESPONSE_STREAM_FAILURE",
});
+22 -16
View File
@@ -73,12 +73,17 @@ function labelledFileInput(): HTMLInputElement {
describe("browser file pickers", () => {
it("treats native input cancellation as a normal dismissed outcome", async () => {
const input = labelledFileInput();
Object.defineProperty(input, "showPicker", {
Object.defineProperty(input, "click", {
configurable: true,
value: vi.fn(() => {
queueMicrotask(() => input.dispatchEvent(new Event("cancel")));
}),
});
const baselineShowPicker = vi.fn();
Object.defineProperty(input, "showPicker", {
configurable: true,
value: baselineShowPicker,
});
const harness = createHarness();
const picker = new NativeInputFilePicker({
input,
@@ -90,6 +95,7 @@ describe("browser file pickers", () => {
ok: true,
value: { kind: "DISMISSED" },
});
expect(baselineShowPicker).not.toHaveBeenCalled();
});
it("resets the native input and supports same-file reselection", async () => {
@@ -102,12 +108,12 @@ describe("browser file pickers", () => {
configurable: true,
value: [selected],
});
const showPicker = vi.fn(() => {
const click = vi.fn(() => {
queueMicrotask(() => input.dispatchEvent(new Event("change")));
});
Object.defineProperty(input, "showPicker", {
Object.defineProperty(input, "click", {
configurable: true,
value: showPicker,
value: click,
});
let sequence = 0;
const { policies, vault } = createHarness(policyDefinition, {
@@ -130,14 +136,14 @@ describe("browser file pickers", () => {
ok: true,
value: { kind: "SELECTED" },
});
expect(showPicker).toHaveBeenCalledTimes(2);
expect(click).toHaveBeenCalledTimes(2);
expect(input.value).toBe("");
expect(vault.activeReferenceCount).toBe(2);
});
it("snapshots selection policy before awaiting picker events", async () => {
const input = labelledFileInput();
Object.defineProperty(input, "showPicker", {
Object.defineProperty(input, "click", {
configurable: true,
value: vi.fn(),
});
@@ -186,7 +192,7 @@ describe("browser file pickers", () => {
it("honors AbortSignal while a native dialog is pending", async () => {
const input = labelledFileInput();
Object.defineProperty(input, "showPicker", {
Object.defineProperty(input, "click", {
configurable: true,
value: vi.fn(),
});
@@ -215,7 +221,7 @@ describe("browser file pickers", () => {
let fallback: (() => void) | undefined;
let delay: number | undefined;
const clearTimeout = vi.fn();
Object.defineProperty(input, "showPicker", {
Object.defineProperty(input, "click", {
configurable: true,
value: vi.fn(() => {
window.dispatchEvent(new Event("focus"));
@@ -261,7 +267,7 @@ describe("browser file pickers", () => {
const input = labelledFileInput();
let fallback: (() => void) | undefined;
const clearTimeout = vi.fn();
Object.defineProperty(input, "showPicker", {
Object.defineProperty(input, "click", {
configurable: true,
value: vi.fn(() => {
window.dispatchEvent(new Event("focus"));
@@ -316,14 +322,14 @@ describe("browser file pickers", () => {
setTimeout: originalSetTimeout,
clearTimeout: originalClearTimeout,
};
const originalShowPicker = vi.fn(() => {
const originalClick = vi.fn(() => {
focus?.(new Event("focus"));
});
const replacedShowPicker = vi.fn();
Object.defineProperty(input, "showPicker", {
const replacedClick = vi.fn();
Object.defineProperty(input, "click", {
configurable: true,
writable: true,
value: originalShowPicker,
value: originalClick,
});
const harness = createHarness();
const picker = new NativeInputFilePicker({
@@ -338,7 +344,7 @@ describe("browser file pickers", () => {
focusFallbackGraceMs: 0,
});
input.showPicker = replacedShowPicker;
input.click = replacedClick;
windowHost.addEventListener = vi.fn();
windowHost.removeEventListener = vi.fn();
scheduler.setTimeout = vi.fn();
@@ -348,8 +354,8 @@ describe("browser file pickers", () => {
ok: true,
value: { kind: "DISMISSED" },
});
expect(originalShowPicker).toHaveBeenCalledOnce();
expect(replacedShowPicker).not.toHaveBeenCalled();
expect(originalClick).toHaveBeenCalledOnce();
expect(replacedClick).not.toHaveBeenCalled();
expect(originalWindowAdd).toHaveBeenCalledOnce();
expect(originalWindowRemove).toHaveBeenCalledOnce();
expect(originalSetTimeout).toHaveBeenCalledOnce();
+1 -1
View File
@@ -178,7 +178,7 @@ describe("browser file runtime hard limits and disposal", () => {
it("aborts a pending native picker and prevents event resurrection", async () => {
const input = fileInput();
Object.defineProperty(input, "showPicker", {
Object.defineProperty(input, "click", {
configurable: true,
value: vi.fn(),
});
@@ -9,7 +9,7 @@ import {
type BrowserRpcStreamFrame,
type BrowserRpcTransport,
} from "../../../src/adapters/browser-rpc/index.ts";
import type { Result } from "../../../src/application/result.ts";
import type { Result } from "../../../src/contracts/result.ts";
import type { AppFailure } from "../../../src/contracts/errors.ts";
import {
MAPPERS,
File diff suppressed because it is too large Load Diff
+10 -107
View File
@@ -193,18 +193,21 @@ describe("CI gate contract", () => {
// Alignment follow-up item 2: FE-GATE-007 gained `test-tech-log`.
// Dev release manifest drift fix item 2: FE-GATE-010 gained
// `check-dev-release-manifest`.
expect(contract.commands).toHaveLength(85);
expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(97);
expect(contract.commands.filter(({ expect }) => expect === "fail")).toHaveLength(23);
// Template merge. Recounted from the merged config/ci/gates.json rather
// than taking either side's number.
// Task 11 added TECH_LOG_STUDIO_ASSETS's manual accessibility evidence.
// Alignment follow-up item 2 added the TechLog junit report.
// 주제 화면 셋(`/topics`, `/topics/:slug/:variant`, `/studio/topics/:id`)이 라우트마다
// 하나씩인 수동 접근성 증거를 셋 더했다.
// 환경 구성(SETUP)이 `/setups/:slug` 로 하나를 더 더했다.
expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(118);
expect(contract.artifacts).toHaveLength(139);
// Template sync (ebea300). Every count below is recounted from the merged
// config/ci/gates.json rather than taken from either side: this product
// pinned 85/97/23/118/139 and the template pinned 91/103/30/88/109, and
// neither set describes the merged file. The method was checked by first
// reproducing this product's numbers from the pre-merge gates.json.
expect(contract.commands).toHaveLength(94);
expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(106);
expect(contract.commands.filter(({ expect }) => expect === "fail")).toHaveLength(30);
expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(120);
expect(contract.artifacts).toHaveLength(141);
expect(contract.stages).toHaveLength(5);
expect(contract.retention.classes).toHaveLength(5);
expect(index.gates.get("FE-GATE-015")?.commandIds).toHaveLength(2);
@@ -1367,106 +1370,6 @@ describe("CI gate contract", () => {
);
});
it("caps aggregate gate output at the log schema before later commands can accumulate", async () => {
const root = await mkdtemp(path.join(tmpdir(), "ci-gate-output-budget-"));
temporaryRoots.push(root);
await mkdir(path.join(root, "config/ci"), { recursive: true });
const contract = JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))) as Record<string, any>;
const gate = contract.gates.find((entry: any) => entry.id === "FE-GATE-001");
const command = contract.commands.find((entry: any) => entry.id === gate.commandIds[0]);
command.script = "test:huge-output";
const logArtifact = contract.artifacts.find((entry: any) => entry.id === gate.logArtifactId);
const logSchema = contract.artifactSchemas.find((entry: any) => entry.id === logArtifact.schemaId);
logSchema.maxBytes = 8_192;
const packageDocument = JSON.parse(await readFile("package.json", "utf8")) as { scripts: Record<string, string> };
packageDocument.scripts["test:huge-output"] = "node -e \"process.stdout.write('x'.repeat(20000))\"";
await writeFile(path.join(root, "config/ci/gates.json"), `${JSON.stringify(contract)}\n`);
await writeFile(path.join(root, "package.json"), `${JSON.stringify(packageDocument)}\n`);
const environment = { ...process.env, CI: "false" };
const result = spawnSync(process.execPath, [path.resolve("scripts/run-ci-gate.ts"), "FE-GATE-001"], {
cwd: root,
encoding: "utf8",
env: environment,
timeout: 15_000,
});
expect(result.status).toBe(1);
const log = await readFile(path.join(root, logArtifact.path));
expect(log.byteLength).toBeLessThanOrEqual(8_192);
expect(log.toString("utf8")).toMatch(/aggregate output|INFRASTRUCTURE_FAILURE/i);
}, 20_000);
it("rejects stale command-generated evidence from a successful no-op producer", async () => {
const root = await mkdtemp(path.join(tmpdir(), "ci-gate-stale-evidence-"));
temporaryRoots.push(root);
await mkdir(path.join(root, "config/ci"), { recursive: true });
await mkdir(path.join(root, "artifacts/tests"), { recursive: true });
const contract = JSON.parse(
JSON.stringify(await loadCiGateContract(process.cwd())),
) as Record<string, any>;
const command = contract.commands.find(
(entry: Record<string, any>) => entry.id === "test-runtime-schema",
);
command.script = "test:stale-evidence-noop";
const evidence = contract.artifacts.find(
(entry: Record<string, any>) => entry.path === "artifacts/tests/runtime-schema.xml",
);
const packageDocument = JSON.parse(await readFile("package.json", "utf8")) as {
scripts: Record<string, string>;
};
packageDocument.scripts[command.script] = "true";
await writeFile(path.join(root, "config/ci/gates.json"), `${JSON.stringify(contract)}\n`);
await writeFile(path.join(root, "package.json"), `${JSON.stringify(packageDocument)}\n`);
await writeFile(
path.join(root, evidence.path),
'<testsuite name="stale" tests="0" failures="0"/>\n',
);
const result = spawnSync(
process.execPath,
[path.resolve("scripts/run-ci-gate.ts"), "FE-GATE-004"],
{ cwd: root, encoding: "utf8", env: { ...process.env, CI: "false" } },
);
expect(result.status).toBe(1);
expect(
await readFile(path.join(root, "artifacts/quality/gates/FE-GATE-004.txt"), "utf8"),
).toMatch(/not freshly produced/i);
});
it("accepts a fresh deterministic rewrite with identical evidence bytes", async () => {
const root = await mkdtemp(path.join(tmpdir(), "ci-gate-identical-rewrite-"));
temporaryRoots.push(root);
await mkdir(path.join(root, "config/ci"), { recursive: true });
await mkdir(path.join(root, "artifacts/tests"), { recursive: true });
const contract = JSON.parse(
JSON.stringify(await loadCiGateContract(process.cwd())),
) as Record<string, any>;
const command = contract.commands.find(
(entry: Record<string, any>) => entry.id === "test-runtime-schema",
);
command.script = "test:identical-evidence-rewrite";
const evidence = contract.artifacts.find(
(entry: Record<string, any>) => entry.path === "artifacts/tests/runtime-schema.xml",
);
const evidenceBytes = '<testsuite name="deterministic" tests="0" failures="0"/>\n';
const packageDocument = JSON.parse(await readFile("package.json", "utf8")) as {
scripts: Record<string, string>;
};
packageDocument.scripts[command.script] =
`node -e 'require("node:fs").writeFileSync("${evidence.path}", Buffer.from("${Buffer.from(evidenceBytes).toString("base64")}", "base64"))'`;
await writeFile(path.join(root, "config/ci/gates.json"), `${JSON.stringify(contract)}\n`);
await writeFile(path.join(root, "package.json"), `${JSON.stringify(packageDocument)}\n`);
await writeFile(path.join(root, evidence.path), evidenceBytes);
const result = spawnSync(
process.execPath,
[path.resolve("scripts/run-ci-gate.ts"), "FE-GATE-004"],
{ cwd: root, encoding: "utf8", env: { ...process.env, CI: "false" } },
);
expect(result.status).toBe(0);
expect(result.stdout).toMatch(/FE-GATE-004 runtime-schema: PASS/);
});
});
describe("CI workflow generation", () => {
+1 -1
View File
@@ -5,7 +5,7 @@ import {
isVersionCompatible,
parseNumericVersion,
verifyCompatibilityTuple,
} from "../../src/application/policies/compatibility.ts";
} from "../../src/contracts/compatibility.ts";
describe("contract compatibility", () => {
it("uses numeric version parsing rather than lexical comparison", () => {
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { createCursorPaginationRuntime } from "../../src/adapters/query-cache/cursor-pagination-runtime.ts";
import { createCursorPaginationRuntime } from "../../src/adapters/query-cache/index.ts";
const profile = {
profileId: "bounded-cursor-v1",
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import {
canRetryTransport,
isRetryableHttpStatus,
isRetryableSemantics,
jitteredDelay,
retryDelayFor,
} from "../../src/adapters/http/http-retry-lifecycle.ts";
describe("HTTP retry lifecycle policy", () => {
it("allows KEYED replay only before a physical dispatch", () => {
expect(canRetryTransport("KEYED", "PREPARING")).toBe(true);
expect(canRetryTransport("KEYED", "READY_TO_SEND")).toBe(true);
expect(canRetryTransport("KEYED", "DISPATCHED")).toBe(false);
expect(canRetryTransport("KEYED", "RESPONSE_HEADERS")).toBe(false);
});
it("keeps SAFE and IDEMPOTENT retryable while NEVER is terminal", () => {
expect(isRetryableSemantics("SAFE")).toBe(true);
expect(isRetryableSemantics("IDEMPOTENT")).toBe(true);
expect(isRetryableSemantics("KEYED")).toBe(false);
expect(isRetryableSemantics("NEVER")).toBe(false);
expect(canRetryTransport("SAFE", "DISPATCHED")).toBe(true);
expect(canRetryTransport("IDEMPOTENT", "READING_BODY")).toBe(true);
expect(canRetryTransport("NEVER", "PREPARING")).toBe(false);
});
it("owns the closed retryable status vocabulary", () => {
for (const status of [408, 425, 429, 502, 503, 504]) {
expect(isRetryableHttpStatus(status)).toBe(true);
}
for (const status of [400, 401, 403, 404, 409, 500, 501]) {
expect(isRetryableHttpStatus(status)).toBe(false);
}
});
it("uses bounded full jitter and rejects excessive Retry-After", () => {
expect(jitteredDelay(0, () => 0)).toBe(0);
expect(jitteredDelay(0, () => 0.5)).toBe(125);
expect(jitteredDelay(8, () => 0.5)).toBe(1_000);
expect(retryDelayFor(null, 0, () => 0.5)).toBe(125);
expect(retryDelayFor(400, 0, () => 0.5)).toBe(400);
expect(retryDelayFor(5_001, 0, () => 0.5)).toBeNull();
});
});
+652
View File
@@ -0,0 +1,652 @@
import { describe, expect, it, vi } from "vitest";
import type {
ImageProbeRequest,
} from "../../src/application/ports/browser-transfer/image-cdn.ts";
import { createBrowserImageProbe } from "../../src/adapters/browser-transfer/image-cdn/browser-image-probe.ts";
import {
avifBytes,
jpegBytes,
manualImageProbeScheduler,
pngBytes,
publicImageHeaders,
responseAt,
webpBytes,
} from "./image-cdn-test-fixture.ts";
describe("browser image probe", () => {
const imageUrl =
"https://images.example.test/v1/assets/a/rev?format=png";
const request = (
overrides: Partial<ImageProbeRequest> = {},
): ImageProbeRequest => ({
absoluteUrl: imageUrl,
expectedMediaType: "image/png",
expectedWidth: 640,
expectedHeight: 360,
maxEncodedBytes: 1_024,
maxDecodedPixels: 230_400,
maxDecodedBytes: 921_600,
delivery: "PUBLIC_IMMUTABLE",
minimumPublicMaxAgeSeconds: 31_536_000,
referrerPolicy: "no-referrer",
signal: new AbortController().signal,
...overrides,
});
it("parses all supported static headers before decode and closes each bitmap", async () => {
const samples = [
{
mediaType: "image/png" as const,
bytes: pngBytes(640, 360),
},
{
mediaType: "image/jpeg" as const,
bytes: jpegBytes(640, 360),
},
{
mediaType: "image/webp" as const,
bytes: webpBytes(640, 360),
},
{
mediaType: "image/avif" as const,
bytes: avifBytes(640, 360),
},
];
const close = vi.fn();
for (const sample of samples) {
const exactUrl = imageUrl.replace(
"format=png",
`format=${sample.mediaType.slice("image/".length)}`,
);
const fetcher = vi.fn(async () =>
responseAt(exactUrl, sample.bytes, {
status: 200,
headers: publicImageHeaders(
sample.mediaType,
sample.bytes.byteLength,
),
}),
);
const probe = createBrowserImageProbe({
fetcher: fetcher as typeof fetch,
createBitmap: vi.fn(async () => ({
width: 640,
height: 360,
close,
})),
});
await expect(
probe.probe(
request({
absoluteUrl: exactUrl,
expectedMediaType: sample.mediaType,
}),
),
).resolves.toMatchObject({
ok: true,
value: {
absoluteUrl: exactUrl,
mediaType: sample.mediaType,
encodedBytes: sample.bytes.byteLength,
decodedWidth: 640,
decodedHeight: 360,
},
});
expect(fetcher).toHaveBeenCalledWith(
exactUrl,
expect.objectContaining({
credentials: "omit",
redirect: "error",
mode: "cors",
cache: "no-store",
referrerPolicy: "no-referrer",
}),
);
}
expect(close).toHaveBeenCalledTimes(samples.length);
});
it("fails closed on duplicate/conflicting cache directives and oversized bodies", async () => {
const png = pngBytes(640, 360);
const createBitmap = vi.fn(async () => ({
width: 640,
height: 360,
close: vi.fn(),
}));
for (const cacheControl of [
// BT-IMG-02. Unmatched quotes must not be unwrapped into a bare number.
'public, max-age="31536000, immutable',
'public, max-age=31536000", immutable',
'public, max-age="31536000\\", immutable',
"public, public, max-age=31536000, immutable",
"public, max-age=31536000, s-maxage=60, immutable",
"public, max-age=31536000, immutable, must-revalidate",
"public=1, max-age=31536000, immutable",
"public, max-age=31536000, immutable=true",
]) {
const probe = createBrowserImageProbe({
fetcher: (async () =>
responseAt(imageUrl, png, {
status: 200,
headers: {
"cache-control": cacheControl,
"content-type": "image/png",
},
})) as typeof fetch,
createBitmap,
});
await expect(probe.probe(request())).resolves.toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
}
const probe = createBrowserImageProbe({
fetcher: (async () =>
responseAt(imageUrl, new Uint8Array(2_048), {
status: 200,
headers: {
"cache-control":
"public, max-age=31536000, immutable",
"content-type": "image/png",
},
})) as typeof fetch,
createBitmap,
});
await expect(probe.probe(request())).resolves.toMatchObject({
ok: false,
error: { code: "LIMIT_EXCEEDED" },
});
expect(createBitmap).not.toHaveBeenCalled();
});
it("rejects non-identity content encoding and mismatched declared lengths", async () => {
const png = pngBytes(640, 360);
const createBitmap = vi.fn();
const cases = [
{
headers: {
"content-encoding": "gzip",
"content-length": String(png.byteLength),
},
code: "POLICY_REJECTED",
},
{
headers: {
"content-length": String(png.byteLength + 1),
},
code: "INTEGRITY_FAILED",
},
];
for (const invalid of cases) {
const headers = publicImageHeaders("image/png");
for (const [name, value] of Object.entries(invalid.headers)) {
headers.set(name, value);
}
const probe = createBrowserImageProbe({
fetcher: (async () =>
responseAt(imageUrl, png, {
status: 200,
headers,
})) as typeof fetch,
createBitmap,
});
await expect(probe.probe(request())).resolves.toMatchObject({
ok: false,
error: { code: invalid.code },
});
}
expect(createBitmap).not.toHaveBeenCalled();
});
it("rejects malicious dimensions and animated PNG/WebP before native decode", async () => {
const createBitmap = vi.fn(async () => ({
width: 640,
height: 360,
close: vi.fn(),
}));
const cases = [
{
bytes: pngBytes(20_000, 20_000),
mediaType: "image/png" as const,
code: "LIMIT_EXCEEDED",
},
{
bytes: pngBytes(320, 180),
mediaType: "image/png" as const,
code: "INTEGRITY_FAILED",
},
{
bytes: jpegBytes(320, 180),
mediaType: "image/jpeg" as const,
code: "INTEGRITY_FAILED",
},
{
bytes: webpBytes(10_000, 10_000),
mediaType: "image/webp" as const,
code: "LIMIT_EXCEEDED",
},
{
bytes: avifBytes(20_000, 20_000),
mediaType: "image/avif" as const,
code: "LIMIT_EXCEEDED",
},
{
bytes: pngBytes(640, 360, true),
mediaType: "image/png" as const,
code: "INTEGRITY_FAILED",
},
{
bytes: webpBytes(640, 360, true),
mediaType: "image/webp" as const,
code: "INTEGRITY_FAILED",
},
{
bytes: avifBytes(640, 360, "avis"),
mediaType: "image/avif" as const,
code: "INTEGRITY_FAILED",
},
];
for (const malicious of cases) {
const url = imageUrl.replace(
"format=png",
`format=${malicious.mediaType.slice("image/".length)}`,
);
const probe = createBrowserImageProbe({
fetcher: (async () =>
responseAt(url, malicious.bytes, {
status: 200,
headers: publicImageHeaders(
malicious.mediaType,
malicious.bytes.byteLength,
),
})) as typeof fetch,
createBitmap,
});
await expect(
probe.probe(
request({
absoluteUrl: url,
expectedMediaType: malicious.mediaType,
}),
),
).resolves.toMatchObject({
ok: false,
error: { code: malicious.code },
});
}
expect(createBitmap).not.toHaveBeenCalled();
});
it("enforces private no-store, omitted credentials and the exact final URL", async () => {
const png = pngBytes(640, 360);
const fetcher = vi.fn(async () =>
responseAt(imageUrl, png, {
status: 200,
headers: {
// TR-RR-09. A private response carries `no-store` and nothing else
// that describes cacheability.
"cache-control": "no-store",
"content-type": "image/png",
},
}),
);
const probe = createBrowserImageProbe({
fetcher: fetcher as typeof fetch,
createBitmap: async () => ({
width: 640,
height: 360,
close: vi.fn(),
}),
});
await expect(
probe.probe(
request({
delivery: "PRIVATE_SIGNED",
minimumPublicMaxAgeSeconds: 0,
}),
),
).resolves.toMatchObject({ ok: true });
expect(fetcher).toHaveBeenCalledWith(
imageUrl,
expect.objectContaining({
cache: "no-store",
credentials: "omit",
redirect: "error",
}),
);
for (const response of [
responseAt(imageUrl, png, {
status: 200,
headers: {
"cache-control": "private, no-store=value",
"content-type": "image/png",
},
}),
responseAt(imageUrl, png, {
status: 200,
headers: {
"cache-control": "public, no-store",
"content-type": "image/png",
},
}),
responseAt(
"https://images.example.test/v1/assets/other",
png,
{
status: 200,
headers: {
"cache-control": "private, no-store",
"content-type": "image/png",
},
},
),
]) {
const rejectingProbe = createBrowserImageProbe({
fetcher: (async () => response) as typeof fetch,
createBitmap: async () => ({
width: 640,
height: 360,
close: vi.fn(),
}),
});
await expect(
rejectingProbe.probe(
request({
delivery: "PRIVATE_SIGNED",
minimumPublicMaxAgeSeconds: 0,
}),
),
).resolves.toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
}
await expect(
probe.probe(
request({
expectedMediaType: "image/svg+xml",
} as unknown as Partial<ImageProbeRequest>),
),
).resolves.toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
});
/**
* TR-RR-09. The recorded BT-IMG-02 contract for a private response is a
* fail-closed matrix. Accepting `no-store` next to a directive that describes
* cacheability lets a self-contradictory policy read as acceptable.
*/
it("applies the full private Cache-Control matrix", async () => {
const png = pngBytes(640, 360);
const probeWith = async (cacheControl: string) => {
const probe = createBrowserImageProbe({
fetcher: (async () =>
responseAt(imageUrl, png, {
status: 200,
headers: {
"cache-control": cacheControl,
"content-type": "image/png",
},
})) as typeof fetch,
createBitmap: async () => ({
width: 640,
height: 360,
close: vi.fn(),
}),
});
return await probe.probe(
request({
delivery: "PRIVATE_SIGNED",
minimumPublicMaxAgeSeconds: 0,
}),
);
};
// Only `no-store`, plus a syntactically valid unknown extension.
expect(await probeWith("no-store")).toMatchObject({ ok: true });
expect(await probeWith('no-store, x-vendor="a,b"')).toMatchObject({
ok: true,
});
for (const companion of [
"public",
"private",
"immutable",
"max-age=60",
"s-maxage=60",
"no-cache",
"must-revalidate",
"proxy-revalidate",
]) {
expect(await probeWith(`no-store, ${companion}`)).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
}
for (const withoutNoStore of ["private", "no-cache", "max-age=0"]) {
expect(await probeWith(withoutNoStore)).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
}
});
it("times out a stalled body, aborts the composed signal and cancels its reader", async () => {
const manual = manualImageProbeScheduler();
const cancel = vi.fn(async () => undefined);
const releaseLock = vi.fn();
const read = vi.fn(
() =>
new Promise<ReadableStreamReadResult<Uint8Array>>(
() => undefined,
),
);
const response = {
body: {
getReader: () => ({ cancel, read, releaseLock }),
},
headers: publicImageHeaders("image/png"),
ok: true,
redirected: false,
status: 200,
type: "cors",
url: imageUrl,
} as unknown as Response;
const fetcher = vi.fn(
async (_input: RequestInfo | URL, _init?: RequestInit) =>
response,
);
const probe = createBrowserImageProbe({
fetcher: fetcher as typeof fetch,
createBitmap: vi.fn(),
timeoutMs: 1_000,
scheduler: manual.scheduler,
});
const probeRequest = request();
const pending = probe.probe(probeRequest);
await vi.waitFor(() => {
expect(read).toHaveBeenCalledOnce();
});
const composedSignal = fetcher.mock.calls[0]?.[1]?.signal as
| AbortSignal
| null
| undefined;
expect(composedSignal).not.toBe(probeRequest.signal);
manual.fire();
await expect(pending).resolves.toMatchObject({
ok: false,
error: {
code: "UNAVAILABLE",
retryable: true,
recovery: "RETRY",
},
});
expect(cancel).toHaveBeenCalledOnce();
expect(releaseLock).toHaveBeenCalledOnce();
expect(composedSignal?.aborted).toBe(true);
});
it("times out stalled decode and closes a bitmap that resolves late", async () => {
const manual = manualImageProbeScheduler();
const close = vi.fn();
let finishDecode:
((bitmap: {
width: number;
height: number;
close(): void;
}) => void) | undefined;
const createBitmap = vi.fn(
() =>
new Promise<{
width: number;
height: number;
close(): void;
}>((resolve) => {
finishDecode = resolve;
}),
);
const png = pngBytes(640, 360);
const probe = createBrowserImageProbe({
fetcher: (async () =>
responseAt(imageUrl, png, {
status: 200,
headers: publicImageHeaders("image/png", png.byteLength),
})) as typeof fetch,
createBitmap,
timeoutMs: 1_000,
scheduler: manual.scheduler,
});
const pending = probe.probe(request());
await vi.waitFor(() => {
expect(createBitmap).toHaveBeenCalledOnce();
});
manual.fire();
await expect(pending).resolves.toMatchObject({
ok: false,
error: { code: "UNAVAILABLE" },
});
finishDecode?.({ width: 640, height: 360, close });
await vi.waitFor(() => {
expect(close).toHaveBeenCalledOnce();
});
});
/**
* X-AUDIT-02. `probe()` promises a `BrowserDataResult`. A scheduler that
* cannot install the probe deadline must close the probe inside that contract
* rather than rejecting it, and must not leave the caller's listener behind.
*/
describe("scheduler boundary", () => {
const trackedSignal = () => {
const controller = new AbortController();
const added: string[] = [];
const removed: string[] = [];
const add = controller.signal.addEventListener.bind(controller.signal);
const remove = controller.signal.removeEventListener.bind(
controller.signal,
);
Object.defineProperty(controller.signal, "addEventListener", {
configurable: true,
value: (type: string, ...rest: readonly unknown[]) => {
added.push(type);
return (add as (...args: readonly unknown[]) => unknown)(
type,
...rest,
);
},
});
Object.defineProperty(controller.signal, "removeEventListener", {
configurable: true,
value: (type: string, ...rest: readonly unknown[]) => {
removed.push(type);
return (remove as (...args: readonly unknown[]) => unknown)(
type,
...rest,
);
},
});
return { controller, added, removed };
};
it("closes the probe when the scheduler cannot install the deadline", async () => {
const fetcher = vi.fn(async () => new Response(null, { status: 200 }));
const { controller, added, removed } = trackedSignal();
const probe = createBrowserImageProbe({
fetcher: fetcher as unknown as typeof fetch,
createBitmap: vi.fn(),
timeoutMs: 1_000,
scheduler: {
setTimeout: () => {
throw new TypeError("image scheduler install exploded");
},
clearTimeout: vi.fn(),
},
});
await expect(
probe.probe({ ...request(), signal: controller.signal }),
).resolves.toMatchObject({
ok: false,
error: { code: "UNAVAILABLE", retryable: true, recovery: "RETRY" },
});
expect(fetcher).not.toHaveBeenCalled();
expect(added.filter((type) => type === "abort")).toHaveLength(1);
expect(removed.filter((type) => type === "abort")).toHaveLength(1);
});
it("starts no timer and no fetch for an already aborted caller", async () => {
const fetcher = vi.fn(async () => new Response(null, { status: 200 }));
const setTimeout_ = vi.fn(() => 1);
const controller = new AbortController();
controller.abort();
const probe = createBrowserImageProbe({
fetcher: fetcher as unknown as typeof fetch,
createBitmap: vi.fn(),
timeoutMs: 1_000,
scheduler: { setTimeout: setTimeout_, clearTimeout: vi.fn() },
});
await expect(
probe.probe({ ...request(), signal: controller.signal }),
).resolves.toMatchObject({ ok: false, error: { code: "ABORTED" } });
expect(fetcher).not.toHaveBeenCalled();
expect(setTimeout_).not.toHaveBeenCalled();
});
it("keeps the classified outcome when clearing the deadline throws", async () => {
const png = pngBytes(640, 360);
const probe = createBrowserImageProbe({
fetcher: (async () =>
responseAt(imageUrl, png, {
status: 200,
headers: publicImageHeaders("image/png", png.byteLength),
})) as typeof fetch,
createBitmap: vi.fn(async () => ({
width: 640,
height: 360,
close: vi.fn(),
})),
timeoutMs: 1_000,
scheduler: {
setTimeout: (callback: () => void, milliseconds: number) =>
setTimeout(callback, milliseconds),
clearTimeout: () => {
throw new TypeError("image scheduler clear exploded");
},
},
});
await expect(probe.probe(request())).resolves.toMatchObject({ ok: true });
});
});
});
@@ -0,0 +1,85 @@
import { describe, expect, it } from "vitest";
import { createP256ImageCapabilityVerifier } from "../../src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts";
import { base64Url } from "./image-cdn-test-fixture.ts";
describe("P-256 image capability verifier", () => {
it("rejects an ECDSA public key on any curve other than P-256", async () => {
const generated = await globalThis.crypto.subtle.generateKey(
{ name: "ECDSA", namedCurve: "P-384" },
false,
["sign", "verify"],
);
if (!("publicKey" in generated)) {
throw new TypeError("Expected an ECDSA key pair.");
}
expect(() =>
createP256ImageCapabilityVerifier({
subtle: globalThis.crypto.subtle,
publicKeys: [
{
keyId: "image-signing-wrong-curve",
key: generated.publicKey,
},
],
}),
).toThrow(/public key binding/u);
});
it("verifies the exact canonical payload and rejects tampering", async () => {
const generated = await globalThis.crypto.subtle.generateKey(
{ name: "ECDSA", namedCurve: "P-256" },
false,
["sign", "verify"],
);
if (!("privateKey" in generated)) {
throw new TypeError("Expected an ECDSA key pair.");
}
const payload = new TextEncoder().encode(
'["image-cdn-capability-v1","bound"]',
);
const payloadBuffer = new Uint8Array(payload.byteLength);
payloadBuffer.set(payload);
const signature = await globalThis.crypto.subtle.sign(
{ name: "ECDSA", hash: "SHA-256" },
generated.privateKey,
payloadBuffer.buffer,
);
const verifier = createP256ImageCapabilityVerifier({
subtle: globalThis.crypto.subtle,
publicKeys: [
{
keyId: "image-signing-2026-01",
key: generated.publicKey,
},
],
});
expect(verifier.acceptsKey("image-signing-2026-01")).toBe(
true,
);
expect(verifier.acceptsKey("image-signing-unknown")).toBe(
false,
);
const signatureBase64Url = base64Url(
new Uint8Array(signature),
);
await expect(
verifier.verify({
algorithm: "ECDSA_P256_SHA256",
keyId: "image-signing-2026-01",
canonicalPayload: payload,
signatureBase64Url,
}),
).resolves.toBe(true);
const tampered = Uint8Array.from(payload);
tampered[0] ^= 1;
await expect(
verifier.verify({
algorithm: "ECDSA_P256_SHA256",
keyId: "image-signing-2026-01",
canonicalPayload: tampered,
signatureBase64Url,
}),
).resolves.toBe(false);
});
});
File diff suppressed because it is too large Load Diff
+309
View File
@@ -0,0 +1,309 @@
import { vi } from "vitest";
import type {
ImageProbeScheduler,
} from "../../src/adapters/browser-transfer/image-cdn/browser-image-probe.ts";
import type {
ImageCapabilityVerificationScheduler,
} from "../../src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts";
export function responseAt(
url: string,
body: Uint8Array,
init: ResponseInit,
): Response {
const responseBytes = new Uint8Array(body.byteLength);
responseBytes.set(body);
const response = new Response(responseBytes.buffer, init);
Object.defineProperty(response, "url", {
configurable: false,
enumerable: true,
value: url,
});
return response;
}
export function publicImageHeaders(
mediaType: string,
contentLength?: number,
): Headers {
const headers = new Headers({
"cache-control":
"public, max-age=31536000, s-maxage=31536000, immutable",
"content-type": mediaType,
vary: "Accept-Encoding",
});
if (contentLength !== undefined) {
headers.set("content-length", String(contentLength));
}
return headers;
}
export function pngBytes(
width: number,
height: number,
animated = false,
): Uint8Array {
const header = new Uint8Array(13);
const headerView = new DataView(header.buffer);
headerView.setUint32(0, width);
headerView.setUint32(4, height);
header[8] = 8;
header[9] = 6;
return concatenateBytes([
Uint8Array.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
]),
pngChunk("IHDR", header),
...(animated
? [pngChunk("acTL", new Uint8Array(8))]
: []),
pngChunk("IDAT", new Uint8Array()),
pngChunk("IEND", new Uint8Array()),
]);
}
function pngChunk(type: string, payload: Uint8Array): Uint8Array {
const chunk = new Uint8Array(12 + payload.byteLength);
const view = new DataView(chunk.buffer);
view.setUint32(0, payload.byteLength);
writeAscii(chunk, 4, type);
chunk.set(payload, 8);
return chunk;
}
export function jpegBytes(width: number, height: number): Uint8Array {
return Uint8Array.from([
0xff,
0xd8,
0xff,
0xc0,
0x00,
0x11,
0x08,
(height >>> 8) & 0xff,
height & 0xff,
(width >>> 8) & 0xff,
width & 0xff,
0x03,
0x01,
0x11,
0x00,
0x02,
0x11,
0x00,
0x03,
0x11,
0x00,
0xff,
0xda,
]);
}
export function webpBytes(
width: number,
height: number,
animated = false,
): Uint8Array {
const chunkType = animated ? "VP8X" : "VP8 ";
const payload = new Uint8Array(10);
if (animated) {
payload[0] = 0x02;
writeUint24LittleEndian(payload, 4, width - 1);
writeUint24LittleEndian(payload, 7, height - 1);
} else {
payload.set([0x9d, 0x01, 0x2a], 3);
const view = new DataView(payload.buffer);
view.setUint16(6, width, true);
view.setUint16(8, height, true);
}
const chunk = concatenateBytes([
asciiBytes(chunkType),
littleEndianUint32(payload.byteLength),
payload,
]);
return concatenateBytes([
asciiBytes("RIFF"),
littleEndianUint32(4 + chunk.byteLength),
asciiBytes("WEBP"),
chunk,
]);
}
export function avifBytes(
width: number,
height: number,
brand = "avif",
): Uint8Array {
const fileType = isoBox(
"ftyp",
concatenateBytes([
asciiBytes(brand),
new Uint8Array(4),
asciiBytes(brand),
]),
);
const spatialExtent = new Uint8Array(12);
const extentView = new DataView(spatialExtent.buffer);
extentView.setUint32(4, width);
extentView.setUint32(8, height);
const primaryItem = new Uint8Array(6);
new DataView(primaryItem.buffer).setUint16(4, 1);
const itemInfoEntry = new Uint8Array(13);
itemInfoEntry[0] = 2;
const itemInfoView = new DataView(itemInfoEntry.buffer);
itemInfoView.setUint16(4, 1);
writeAscii(itemInfoEntry, 8, "av01");
const itemInfo = new Uint8Array(6);
new DataView(itemInfo.buffer).setUint16(4, 1);
const propertyAssociation = new Uint8Array(12);
const associationView = new DataView(
propertyAssociation.buffer,
);
associationView.setUint32(4, 1);
associationView.setUint16(8, 1);
propertyAssociation[10] = 1;
propertyAssociation[11] = 0x81;
const properties = isoBox(
"iprp",
concatenateBytes([
isoBox("ipco", isoBox("ispe", spatialExtent)),
isoBox("ipma", propertyAssociation),
]),
);
const metadata = isoBox(
"meta",
concatenateBytes([
new Uint8Array(4),
isoBox("pitm", primaryItem),
isoBox(
"iinf",
concatenateBytes([
itemInfo,
isoBox("infe", itemInfoEntry),
]),
),
properties,
]),
);
return concatenateBytes([
fileType,
metadata,
isoBox("mdat", Uint8Array.of(0)),
]);
}
export function isoBox(type: string, payload: Uint8Array): Uint8Array {
const box = new Uint8Array(8 + payload.byteLength);
const view = new DataView(box.buffer);
view.setUint32(0, box.byteLength);
writeAscii(box, 4, type);
box.set(payload, 8);
return box;
}
export function littleEndianUint32(value: number): Uint8Array {
const bytes = new Uint8Array(4);
new DataView(bytes.buffer).setUint32(0, value, true);
return bytes;
}
export function writeUint24LittleEndian(
bytes: Uint8Array,
offset: number,
value: number,
): void {
bytes[offset] = value & 0xff;
bytes[offset + 1] = (value >>> 8) & 0xff;
bytes[offset + 2] = (value >>> 16) & 0xff;
}
export function asciiBytes(value: string): Uint8Array {
return Uint8Array.from(
[...value].map((character) => character.charCodeAt(0)),
);
}
export function writeAscii(
target: Uint8Array,
offset: number,
value: string,
): void {
target.set(asciiBytes(value), offset);
}
export function concatenateBytes(
chunks: readonly Uint8Array[],
): Uint8Array {
const combined = new Uint8Array(
chunks.reduce((total, chunk) => total + chunk.byteLength, 0),
);
let offset = 0;
for (const chunk of chunks) {
combined.set(chunk, offset);
offset += chunk.byteLength;
}
return combined;
}
export function manualImageProbeScheduler(): Readonly<{
scheduler: ImageProbeScheduler;
fire(): void;
}> {
let callback: (() => void) | undefined;
return {
scheduler: {
setTimeout(nextCallback) {
callback = nextCallback;
return 1;
},
clearTimeout: vi.fn(),
},
fire() {
if (!callback) {
throw new TypeError("No image probe timeout is scheduled.");
}
callback();
},
};
}
export function manualCapabilityVerificationScheduler(): Readonly<{
scheduler: ImageCapabilityVerificationScheduler;
delays: readonly number[];
clearTimeout: ReturnType<typeof vi.fn>;
fire(): void;
}> {
let callback: (() => void) | undefined;
const delays: number[] = [];
const clearTimeout = vi.fn();
return {
scheduler: {
setTimeout(nextCallback, milliseconds) {
callback = nextCallback;
delays.push(milliseconds);
return 1;
},
clearTimeout,
},
delays,
clearTimeout,
fire() {
if (!callback) {
throw new TypeError(
"No capability verification timeout is scheduled.",
);
}
callback();
},
};
}
export function base64Url(bytes: Uint8Array): string {
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary)
.replace(/\+/gu, "-")
.replace(/\//gu, "_")
.replace(/=+$/gu, "");
}
+886
View File
@@ -0,0 +1,886 @@
import { describe, expect, it, vi } from "vitest";
import {
createIndexedDbConnection,
deleteIndexedDbDatabase,
openIndexedDbDatabase,
type IndexedDbFailureCause,
type IndexedDbTranslate,
} from "../../src/adapters/platform/indexeddb-connection.ts";
import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts";
/**
* IDB-X-01 golden tests. The kernel owns connection mechanics only: it must
* never name an operation label, a failure code or a schema. Every assertion
* below reads the cause the kernel reported, not a taxonomy it chose.
*/
type TestFailure = Readonly<{ cause: IndexedDbFailureCause["kind"]; detail?: unknown }>;
/**
* A `translate` written as a total switch over the union. This is the extension
* point `abortable-operation.ts:11` lacked: adding a cause member breaks every
* translate at compile time instead of silently changing behavior, and the
* union never appears in a return type.
*/
function recordingTranslate(
seen: IndexedDbFailureCause["kind"][],
): IndexedDbTranslate<TestFailure> {
return (cause) => {
seen.push(cause.kind);
switch (cause.kind) {
case "NATIVE_EXCEPTION":
return { cause: cause.kind, detail: cause.error };
case "BLOCKED":
return {
cause: cause.kind,
detail: { oldVersion: cause.oldVersion, newVersion: cause.newVersion },
};
case "BLOCKED_DEADLINE":
case "CALLER_ABORT":
case "CLOSED":
case "NO_VALUE_PRODUCED":
case "UNSUPPORTED":
return { cause: cause.kind };
case "UPGRADE_REJECTED":
return { cause: cause.kind, detail: cause.detail };
case "ADMISSION_REJECTED":
return { cause: cause.kind, detail: cause.detail };
default: {
const exhaustive: never = cause;
return exhaustive;
}
}
};
}
function manualTimers(): Readonly<{
snapshot: Readonly<{
setTimer: (callback: () => void, delayMs: number) => unknown;
clearTimer: (handle: unknown) => void;
}>;
pending: Array<Readonly<{ callback: () => void; delayMs: number }>>;
cleared: unknown[];
}> {
const pending: Array<Readonly<{ callback: () => void; delayMs: number }>> = [];
const cleared: unknown[] = [];
return {
pending,
cleared,
snapshot: {
setTimer: (callback, delayMs) => {
pending.push({ callback, delayMs });
return pending.length;
},
clearTimer: (handle) => {
cleared.push(handle);
},
},
};
}
async function flush(): Promise<void> {
for (let attempt = 0; attempt < 30; attempt += 1) {
await new Promise<void>((resolve) => {
globalThis.setTimeout(resolve, 0);
});
}
}
type StubOpenRequest = {
result: IDBDatabase;
error: DOMException | null;
transaction: IDBTransaction | null;
onsuccess: ((event: Event) => unknown) | null;
onerror: ((event: Event) => unknown) | null;
onblocked: ((event: IDBVersionChangeEvent) => unknown) | null;
onupgradeneeded: ((event: IDBVersionChangeEvent) => unknown) | null;
};
type StubFactory = Readonly<{
factory: IDBFactory;
opened: StubOpenRequest[];
deleted: StubOpenRequest[];
}>;
/**
* The memory fake models a real database. These stubs model only the request
* object, so paths the fake cannot reach — a null `newVersion`, a cancellable
* upgrade transaction, `deleteDatabase` — are still exercised.
*/
function stubFactory(): StubFactory {
const opened: StubOpenRequest[] = [];
const deleted: StubOpenRequest[] = [];
const request = (): StubOpenRequest => ({
result: { close: vi.fn() } as unknown as IDBDatabase,
error: null,
transaction: null,
onsuccess: null,
onerror: null,
onblocked: null,
onupgradeneeded: null,
});
return {
opened,
deleted,
factory: {
open: () => {
const next = request();
opened.push(next);
return next as unknown as IDBOpenDBRequest;
},
deleteDatabase: () => {
const next = request();
deleted.push(next);
return next as unknown as IDBOpenDBRequest;
},
} as unknown as IDBFactory,
};
}
function versionChangeEvent(
oldVersion: number,
newVersion: number | null,
): IDBVersionChangeEvent {
return { oldVersion, newVersion } as IDBVersionChangeEvent;
}
describe("shared IndexedDB connection mechanics", () => {
it("opens a database and hands the caller the live connection", async () => {
const memory = new MemoryIndexedDbFactory();
const seen: IndexedDbFailureCause["kind"][] = [];
const result = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate(seen),
upgrade: ({ database }) => {
database.createObjectStore("rows", { keyPath: "id" });
return { kind: "APPLIED" };
},
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.version).toBe(1);
expect(memory.hasStore("rows")).toBe(true);
expect(seen).toEqual([]);
});
it("reports a native throw from the factory as NATIVE_EXCEPTION", async () => {
const boom = new Error("no factory");
const result = await openIndexedDbDatabase<TestFailure>({
factory: {
open: () => {
throw boom;
},
} as unknown as IDBFactory,
databaseName: "kernel",
translate: recordingTranslate([]),
});
expect(result).toEqual({
ok: false,
error: { cause: "NATIVE_EXCEPTION", detail: boom },
});
});
it("routes a request-level error through translate", async () => {
const memory = new MemoryIndexedDbFactory();
await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 2,
translate: recordingTranslate([]),
upgrade: () => ({ kind: "APPLIED" }),
});
// Opening an older version makes the fake fill `request.error` and fire
// `onerror`; the kernel must report that error rather than a generic cause.
const result = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
upgrade: () => ({ kind: "APPLIED" }),
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.cause).toBe("NATIVE_EXCEPTION");
expect((result.error.detail as DOMException).name).toBe("VersionError");
});
it("settles with BLOCKED when onblocked fires and no deadline is configured", async () => {
const memory = new MemoryIndexedDbFactory();
const observed: Array<Readonly<{ oldVersion: number; newVersion: number | null }>> = [];
memory.blockNextOpen();
const result = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 3,
translate: recordingTranslate([]),
onBlocked: (event) => {
observed.push(event);
throw new Error("an observer cannot change the outcome");
},
});
expect(observed).toEqual([{ oldVersion: 0, newVersion: 3 }]);
expect(result).toEqual({
ok: false,
error: {
cause: "BLOCKED",
detail: { oldVersion: 0, newVersion: 3 },
},
});
});
it("waits the configured deadline before settling with BLOCKED_DEADLINE", async () => {
const memory = new MemoryIndexedDbFactory();
const timers = manualTimers();
memory.blockNextOpen();
let settled = false;
const pending = openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 3,
translate: recordingTranslate([]),
blockedTimeoutMs: 10_000,
timers: timers.snapshot,
});
void pending.then(() => {
settled = true;
});
await flush();
expect(settled).toBe(false);
expect(timers.pending).toHaveLength(1);
expect(timers.pending[0]?.delayMs).toBe(10_000);
timers.pending[0]?.callback();
await expect(pending).resolves.toEqual({
ok: false,
error: { cause: "BLOCKED_DEADLINE" },
});
});
it("rejects a positive blocked deadline that has no timer snapshot", () => {
const memory = new MemoryIndexedDbFactory();
expect(() =>
openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
translate: recordingTranslate([]),
blockedTimeoutMs: 10_000,
}),
).toThrow(TypeError);
});
it("aborts the versionchange transaction when upgrade rejects, so no schema commits", async () => {
const memory = new MemoryIndexedDbFactory();
const result = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
upgrade: ({ database }) => {
database.createObjectStore("rows", { keyPath: "id" });
return { kind: "REJECTED", detail: "POLICY" };
},
});
expect(result).toEqual({
ok: false,
error: { cause: "UPGRADE_REJECTED", detail: "POLICY" },
});
// The store the rejected upgrade created must not be visible afterwards.
expect(memory.hasStore("rows")).toBe(false);
const oldVersions: number[] = [];
await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
upgrade: ({ oldVersion }) => {
oldVersions.push(oldVersion);
return { kind: "APPLIED" };
},
});
expect(oldVersions).toEqual([0]);
});
it("treats a throw from upgrade as a rejection and carries the thrown value", async () => {
const memory = new MemoryIndexedDbFactory();
const boom = new Error("migration defect");
const result = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
upgrade: () => {
throw boom;
},
});
expect(result).toEqual({
ok: false,
error: { cause: "UPGRADE_REJECTED", detail: boom },
});
expect(memory.hasStore("rows")).toBe(false);
});
it("treats any upgrade as unexpected when no upgrade callback is given", async () => {
const memory = new MemoryIndexedDbFactory();
const result = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.cause).toBe("UPGRADE_REJECTED");
});
it("reports UPGRADE_REJECTED before running upgrade when newVersion is null", async () => {
const stub = stubFactory();
const upgrade = vi.fn(() => ({ kind: "APPLIED" as const }));
const pending = openIndexedDbDatabase<TestFailure>({
factory: stub.factory,
databaseName: "kernel",
translate: recordingTranslate([]),
upgrade,
});
const request = stub.opened[0];
expect(request).toBeDefined();
if (!request) return;
const abort = vi.fn();
request.transaction = { abort } as unknown as IDBTransaction;
request.onupgradeneeded?.(versionChangeEvent(4, null));
request.error = new DOMException("aborted", "AbortError");
request.onerror?.(new Event("error"));
expect(upgrade).not.toHaveBeenCalled();
expect(abort).toHaveBeenCalledTimes(1);
await expect(pending).resolves.toEqual({
ok: false,
error: { cause: "UPGRADE_REJECTED", detail: undefined },
});
});
it("admits a successful open and lets an async admission run", async () => {
const memory = new MemoryIndexedDbFactory();
const result = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
upgrade: () => ({ kind: "APPLIED" }),
admit: async (database) => {
await Promise.resolve();
return database.objectStoreNames.contains("rows")
? { kind: "ADMIT" }
: { kind: "REJECT", detail: "STORE" };
},
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toEqual({ cause: "ADMISSION_REJECTED", detail: "STORE" });
// A rejected admission must close the connection the caller never saw.
expect(memory.isConnectionClosed()).toBe(true);
});
it("closes the connection when admission fails with an explicit cause", async () => {
const memory = new MemoryIndexedDbFactory();
const result = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
upgrade: () => ({ kind: "APPLIED" }),
admit: () => ({ kind: "FAIL", cause: { kind: "CALLER_ABORT" } }),
});
expect(result).toEqual({ ok: false, error: { cause: "CALLER_ABORT" } });
expect(memory.isConnectionClosed()).toBe(true);
});
it("admits every successful open when no admit callback is given", async () => {
const memory = new MemoryIndexedDbFactory();
const result = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
upgrade: () => ({ kind: "APPLIED" }),
});
expect(result.ok).toBe(true);
expect(memory.isConnectionClosed()).toBe(false);
});
it("returns CALLER_ABORT without touching the factory for an already aborted signal", async () => {
const stub = stubFactory();
const controller = new AbortController();
controller.abort();
const result = await openIndexedDbDatabase<TestFailure>({
factory: stub.factory,
databaseName: "kernel",
translate: recordingTranslate([]),
signal: controller.signal,
});
expect(result).toEqual({ ok: false, error: { cause: "CALLER_ABORT" } });
expect(stub.opened).toHaveLength(0);
});
it("aborts a pending upgrade transaction when the caller signal fires", async () => {
const stub = stubFactory();
const controller = new AbortController();
const pending = openIndexedDbDatabase<TestFailure>({
factory: stub.factory,
databaseName: "kernel",
translate: recordingTranslate([]),
signal: controller.signal,
});
const request = stub.opened[0];
expect(request).toBeDefined();
if (!request) return;
const abort = vi.fn();
request.transaction = { abort } as unknown as IDBTransaction;
controller.abort();
expect(abort).toHaveBeenCalledTimes(1);
await expect(pending).resolves.toEqual({
ok: false,
error: { cause: "CALLER_ABORT" },
});
});
it("closes a connection that arrives after the caller gave up", async () => {
const memory = new MemoryIndexedDbFactory();
const controller = new AbortController();
let release: ((admission: { kind: "ADMIT" }) => void) | undefined;
const pending = openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
signal: controller.signal,
upgrade: () => ({ kind: "APPLIED" }),
admit: () =>
new Promise<{ kind: "ADMIT" }>((resolve) => {
release = resolve;
}),
});
await flush();
controller.abort();
await expect(pending).resolves.toEqual({
ok: false,
error: { cause: "CALLER_ABORT" },
});
release?.({ kind: "ADMIT" });
await flush();
expect(memory.isConnectionClosed()).toBe(true);
});
it("calls translate for every cause the kernel can report", async () => {
const seen: IndexedDbFailureCause["kind"][] = [];
const translate = recordingTranslate(seen);
// NATIVE_EXCEPTION
await openIndexedDbDatabase<TestFailure>({
factory: {
open: () => {
throw new Error("boom");
},
} as unknown as IDBFactory,
databaseName: "kernel",
translate,
});
// UPGRADE_REJECTED
const rejecting = new MemoryIndexedDbFactory();
await openIndexedDbDatabase<TestFailure>({
factory: rejecting.factory,
databaseName: "kernel",
version: 1,
translate,
});
// BLOCKED
const blocking = new MemoryIndexedDbFactory();
blocking.blockNextOpen();
await openIndexedDbDatabase<TestFailure>({
factory: blocking.factory,
databaseName: "kernel",
version: 1,
translate,
});
// BLOCKED_DEADLINE
const deadline = new MemoryIndexedDbFactory();
const timers = manualTimers();
deadline.blockNextOpen();
const deadlinePending = openIndexedDbDatabase<TestFailure>({
factory: deadline.factory,
databaseName: "kernel",
version: 1,
translate,
blockedTimeoutMs: 5,
timers: timers.snapshot,
});
await flush();
timers.pending[0]?.callback();
await deadlinePending;
// ADMISSION_REJECTED
const admitting = new MemoryIndexedDbFactory();
await openIndexedDbDatabase<TestFailure>({
factory: admitting.factory,
databaseName: "kernel",
version: 1,
translate,
upgrade: () => ({ kind: "APPLIED" }),
admit: () => ({ kind: "REJECT", detail: "POLICY" }),
});
// CALLER_ABORT
const aborted = new AbortController();
aborted.abort();
await openIndexedDbDatabase<TestFailure>({
factory: new MemoryIndexedDbFactory().factory,
databaseName: "kernel",
translate,
signal: aborted.signal,
});
// CLOSED
const handle = createIndexedDbConnection<TestFailure>({
open: () => new Promise(() => undefined),
translate,
});
const closing = handle.acquire();
handle.close();
await closing;
expect(new Set(seen)).toEqual(
new Set([
"NATIVE_EXCEPTION",
"UPGRADE_REJECTED",
"BLOCKED",
"BLOCKED_DEADLINE",
"ADMISSION_REJECTED",
"CALLER_ABORT",
"CLOSED",
]),
);
});
});
describe("single-flight IndexedDB connection handle", () => {
function handleFor(
memory: MemoryIndexedDbFactory,
overrides: Partial<Parameters<typeof createIndexedDbConnection<TestFailure>>[0]> = {},
) {
const opens = vi.fn((signal: AbortSignal | undefined) =>
openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
signal,
upgrade: ({ database }) => {
if (!database.objectStoreNames.contains("rows")) {
database.createObjectStore("rows", { keyPath: "id" });
}
return { kind: "APPLIED" };
},
}),
);
return {
opens,
handle: createIndexedDbConnection<TestFailure>({
open: opens,
translate: recordingTranslate([]),
...overrides,
}),
};
}
it("shares one in-flight open and then reuses the cached connection", async () => {
const memory = new MemoryIndexedDbFactory();
const { handle, opens } = handleFor(memory);
const [first, second] = await Promise.all([
handle.acquire(),
handle.acquire(),
]);
const third = await handle.acquire();
expect(opens).toHaveBeenCalledTimes(1);
expect(first.ok && second.ok && third.ok).toBe(true);
expect(handle.current()).not.toBeNull();
});
it("drops and closes the cached connection on versionchange, then reopens", async () => {
const memory = new MemoryIndexedDbFactory();
const events: string[] = [];
const { handle, opens } = handleFor(memory, {
onVersionChange: () => {
events.push("VERSION_CHANGE");
throw new Error("a notification defect cannot keep the connection");
},
});
await handle.acquire();
memory.triggerVersionChange(2);
expect(events).toEqual(["VERSION_CHANGE"]);
expect(handle.current()).toBeNull();
expect(memory.isConnectionClosed()).toBe(true);
await handle.acquire();
expect(opens).toHaveBeenCalledTimes(2);
});
it("drops the cached connection when the browser forces it closed", async () => {
const memory = new MemoryIndexedDbFactory();
const events: string[] = [];
const { handle } = handleFor(memory, {
onForcedClose: () => events.push("FORCED"),
});
await handle.acquire();
memory.triggerForcedClose();
expect(events).toEqual(["FORCED"]);
expect(handle.current()).toBeNull();
expect(handle.isClosed()).toBe(false);
});
it("settles an in-flight open with CLOSED rather than CALLER_ABORT", async () => {
const seen: IndexedDbFailureCause["kind"][] = [];
let openSignal: AbortSignal | undefined;
const handle = createIndexedDbConnection<TestFailure>({
open: (signal) => {
openSignal = signal;
return new Promise(() => undefined);
},
translate: recordingTranslate(seen),
});
const pending = handle.acquire();
handle.close();
handle.close();
await expect(pending).resolves.toEqual({
ok: false,
error: { cause: "CLOSED" },
});
expect(seen).toEqual(["CLOSED"]);
expect(handle.isClosed()).toBe(true);
// The in-flight native request is still cancelled, so a pending upgrade
// transaction does not outlive the handle.
expect(openSignal?.aborted).toBe(true);
await expect(handle.acquire()).resolves.toEqual({
ok: false,
error: { cause: "CLOSED" },
});
});
it("closes a connection that arrives after the handle was closed", async () => {
const memory = new MemoryIndexedDbFactory();
let release: ((result: { ok: true; value: IDBDatabase }) => void) | undefined;
const handle = createIndexedDbConnection<TestFailure>({
open: () =>
new Promise((resolve) => {
release = resolve as typeof release;
}),
translate: recordingTranslate([]),
});
const pending = handle.acquire();
handle.close();
await pending;
const opened = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate([]),
upgrade: () => ({ kind: "APPLIED" }),
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
release?.({ ok: true, value: opened.value });
await flush();
expect(memory.isConnectionClosed()).toBe(true);
expect(handle.current()).toBeNull();
});
it("aborts one caller without cancelling the shared open", async () => {
const memory = new MemoryIndexedDbFactory();
const { handle, opens } = handleFor(memory);
const controller = new AbortController();
const abandoned = handle.acquire(controller.signal);
const kept = handle.acquire();
controller.abort();
await expect(abandoned).resolves.toEqual({
ok: false,
error: { cause: "CALLER_ABORT" },
});
const survivor = await kept;
expect(survivor.ok).toBe(true);
expect(opens).toHaveBeenCalledTimes(1);
expect(handle.current()).not.toBeNull();
});
it("reports CALLER_ABORT for an already aborted acquire without opening", async () => {
const memory = new MemoryIndexedDbFactory();
const { handle, opens } = handleFor(memory);
const controller = new AbortController();
controller.abort();
await expect(handle.acquire(controller.signal)).resolves.toEqual({
ok: false,
error: { cause: "CALLER_ABORT" },
});
expect(opens).not.toHaveBeenCalled();
});
it("closes the cached connection and reports it through current()", async () => {
const memory = new MemoryIndexedDbFactory();
const { handle } = handleFor(memory);
await handle.acquire();
expect(handle.current()).not.toBeNull();
handle.close();
expect(handle.current()).toBeNull();
expect(memory.isConnectionClosed()).toBe(true);
});
it("retries after a failed open instead of caching the failure", async () => {
const attempts: number[] = [];
const handle = createIndexedDbConnection<TestFailure>({
open: () => {
attempts.push(attempts.length);
return Promise.resolve({
ok: false as const,
error: { cause: "NATIVE_EXCEPTION" as const },
});
},
translate: recordingTranslate([]),
});
await handle.acquire();
await handle.acquire();
expect(attempts).toHaveLength(2);
});
});
describe("IndexedDB database deletion", () => {
it("reports DELETED and settles the caller's registration exactly once", async () => {
const stub = stubFactory();
const settled = vi.fn();
const pending = deleteIndexedDbDatabase<TestFailure>({
factory: stub.factory,
databaseName: "kernel",
translate: recordingTranslate([]),
onSettled: settled,
});
const request = stub.deleted[0];
expect(request).toBeDefined();
request?.onsuccess?.(new Event("success"));
request?.onsuccess?.(new Event("success"));
await expect(pending).resolves.toEqual({ ok: true, value: { kind: "DELETED" } });
expect(settled).toHaveBeenCalledTimes(1);
});
it("routes a delete error through translate and still settles the registration", async () => {
const stub = stubFactory();
const settled = vi.fn();
const pending = deleteIndexedDbDatabase<TestFailure>({
factory: stub.factory,
databaseName: "kernel",
translate: recordingTranslate([]),
onSettled: settled,
});
const request = stub.deleted[0];
if (!request) throw new Error("no delete request");
request.error = new DOMException("nope", "UnknownError");
request.onerror?.(new Event("error"));
const result = await pending;
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.cause).toBe("NATIVE_EXCEPTION");
expect(settled).toHaveBeenCalledTimes(1);
});
it("reports BLOCKED_DEADLINE without settling, then settles when the request lands", async () => {
const stub = stubFactory();
const timers = manualTimers();
const settled = vi.fn();
const pending = deleteIndexedDbDatabase<TestFailure>({
factory: stub.factory,
databaseName: "kernel",
translate: recordingTranslate([]),
blockedTimeoutMs: 5_000,
timers: timers.snapshot,
onSettled: settled,
});
const request = stub.deleted[0];
if (!request) throw new Error("no delete request");
request.onblocked?.(versionChangeEvent(1, null));
expect(timers.pending).toHaveLength(1);
timers.pending[0]?.callback();
await expect(pending).resolves.toEqual({
ok: true,
value: { kind: "BLOCKED_DEADLINE" },
});
// A dispatched deleteDatabase cannot be cancelled, so the deadline is not
// the end of the request: the registration is released only when it lands.
expect(settled).not.toHaveBeenCalled();
request.onsuccess?.(new Event("success"));
expect(settled).toHaveBeenCalledTimes(1);
});
it("settles with BLOCKED when no deadline is configured", async () => {
const stub = stubFactory();
const pending = deleteIndexedDbDatabase<TestFailure>({
factory: stub.factory,
databaseName: "kernel",
translate: recordingTranslate([]),
});
stub.deleted[0]?.onblocked?.(versionChangeEvent(2, null));
await expect(pending).resolves.toEqual({
ok: false,
error: { cause: "BLOCKED", detail: { oldVersion: 2, newVersion: null } },
});
});
});
+171 -3
View File
@@ -205,6 +205,7 @@ function createMaintenance(
now?: () => number;
nowEpochMilliseconds?: () => number;
observe?: (event: IndexedDbObservation) => void;
factory?: IDBFactory;
}> = {},
) {
return createIndexedDbMaintenance<CurrentPayload>({
@@ -225,6 +226,63 @@ function createMaintenance(
});
}
/**
* Records every `transaction.abort()` the adapter itself calls, with the mode
* of the transaction it aborted.
*
* A failure code alone cannot tell `fail` (record and abort) from
* `requestFailed` (record only): the fake aborts a transaction on a request
* error by itself, so both end at the same code while only one of them stops
* the writes queued behind it. Swapping the two is exactly the mistake this
* counter makes visible.
*/
function trackAborts(memory: MemoryIndexedDbFactory): Readonly<{
factory: IDBFactory;
aborts: readonly string[];
}> {
const aborts: string[] = [];
const wrapped = new WeakSet<object>();
const wrapDatabase = (database: IDBDatabase): IDBDatabase => {
if (wrapped.has(database)) return database;
wrapped.add(database);
const openTransaction = database.transaction.bind(database);
Object.defineProperty(database, "transaction", {
configurable: true,
value: (...args: Parameters<IDBDatabase["transaction"]>) => {
const transaction = openTransaction(...args);
const abort = transaction.abort.bind(transaction);
Object.defineProperty(transaction, "abort", {
configurable: true,
value: () => {
aborts.push(transaction.mode);
abort();
},
});
return transaction;
},
});
return database;
};
const factory = {
cmp: (first: IDBValidKey, second: IDBValidKey) =>
memory.factory.cmp(first, second),
open: (name: string, version?: number) => {
const request = memory.factory.open(name, version);
let stored: IDBDatabase | undefined = request.result;
if (stored) wrapDatabase(stored);
Object.defineProperty(request, "result", {
configurable: true,
get: () => stored,
set: (value: IDBDatabase | undefined) => {
stored = value ? wrapDatabase(value) : value;
},
});
return request;
},
} as unknown as IDBFactory;
return Object.freeze({ factory, aborts });
}
function seedReceipt(
memory: MemoryIndexedDbFactory,
idempotencyKey: string,
@@ -299,6 +357,101 @@ describe("IndexedDB bounded codec maintenance", () => {
});
});
it("reports a blocked open immediately instead of waiting out a deadline", async () => {
const memory = new MemoryIndexedDbFactory();
await prepareSchema(memory);
seedLegacy(memory, "blocked", "waiting");
const maintenance = createMaintenance(memory, defaultPolicy());
memory.blockNextOpen();
// MT-1. The blocked open is never released here. A blocked deadline could
// only settle from a timer, and no amount of microtask draining reaches a
// timer, so a batch that has already landed proves the blocked event
// itself is terminal. Give maintenance a blocked timeout and this test
// stops finishing instead of failing on a code.
let landed = false;
const pending = maintenance
.migrateCodecBatch({ maxRows: 10, maxDurationMs: 10_000 })
.then((result) => {
landed = true;
return result;
});
for (let tick = 0; tick < 50; tick += 1) await Promise.resolve();
expect(landed).toBe(true);
expect(await pending).toEqual({
ok: false,
error: {
code: "BLOCKED",
operation: "INDEXEDDB_MIGRATE",
retryable: true,
recovery: "RELOAD_OTHER_CONTEXTS",
},
});
// The connection the caller already gave up on is closed, not leaked.
memory.releaseBlockedOpen();
expect(memory.isConnectionClosed()).toBe(true);
expect(memory.readRaw("records", "blocked")).toMatchObject({
codecVersion: 1,
});
});
it("rejects an unexpected schema upgrade without creating the schema", async () => {
const memory = new MemoryIndexedDbFactory();
// No prepareSchema: the database does not exist yet, so opening at the
// exact schema version is an upgrade.
const maintenance = createMaintenance(memory, defaultPolicy());
expect(
await maintenance.migrateCodecBatch({
maxRows: 10,
maxDurationMs: 10_000,
}),
).toEqual({
ok: false,
error: {
code: "MIGRATION_FAILED",
operation: "INDEXEDDB_MIGRATE",
retryable: false,
recovery: "READ_ONLY",
},
});
// MT-2. Maintenance owns no schema, so a rejected upgrade must leave the
// database untouched rather than open it at the right version with the
// wrong contents. Applying the upgrade instead would fail with the same
// code here and only surface later, as a database nobody can use.
expect(memory.hasStore("records")).toBe(false);
expect(memory.hasStore("governance")).toBe(false);
await prepareSchema(memory);
expect(memory.hasStore("records")).toBe(true);
});
it("closes the maintenance connection when another context needs a version change", async () => {
const memory = new MemoryIndexedDbFactory();
await prepareSchema(memory);
seedReceipt(memory, "versionchange-receipt", 100);
const maintenance = createMaintenance(memory, defaultPolicy(), {
nowEpochMilliseconds: () => 200,
});
memory.clearLastTransaction();
memory.pauseTransactions();
const pending = maintenance.pruneExpiredReceipts({
maxRows: 10,
maxDurationMs: 10_000,
});
await waitForWriteTransaction(memory);
expect(memory.isConnectionClosed()).toBe(false);
// MT-3. The listener is registered on the successful open path only, so it
// covers exactly the window in which a batch holds the connection.
memory.triggerVersionChange(2);
expect(memory.isConnectionClosed()).toBe(true);
memory.resumeTransactions();
await pending;
});
it("resumes from a durable checkpoint and completes in bounded row batches", async () => {
const memory = new MemoryIndexedDbFactory();
await prepareSchema(memory);
@@ -667,7 +820,10 @@ describe("IndexedDB bounded codec maintenance", () => {
...defaultPolicy(),
measureStoredBytes: () => 2_000_000,
};
const maintenance = createMaintenance(memory, policy);
const tracker = trackAborts(memory);
const maintenance = createMaintenance(memory, policy, {
factory: tracker.factory,
});
expect(
await maintenance.migrateCodecBatch({
@@ -681,6 +837,10 @@ describe("IndexedDB bounded codec maintenance", () => {
recovery: "READ_ONLY",
},
});
// The budget verdict aborts the commit transaction rather than only
// recording a failure, so the writes already queued behind it cannot
// commit. Recording without aborting would end at the same failure code.
expect(tracker.aborts).toEqual(["readwrite"]);
expect(memory.readRaw("records", "oversized")).toMatchObject({
codecVersion: 1,
});
@@ -749,10 +909,11 @@ describe("IndexedDB bounded codec maintenance", () => {
const memory = new MemoryIndexedDbFactory();
await prepareSchema(memory);
seedReceipt(memory, "quota-receipt", 100);
const tracker = trackAborts(memory);
const maintenance = createMaintenance(
memory,
defaultPolicy(),
{ nowEpochMilliseconds: () => 200 },
{ nowEpochMilliseconds: () => 200, factory: tracker.factory },
);
memory.failNextWriteCommit(
new DOMException("private receipt", "QuotaExceededError"),
@@ -767,6 +928,9 @@ describe("IndexedDB bounded codec maintenance", () => {
ok: false,
error: { code: "QUOTA_EXCEEDED" },
});
// The commit is what failed, so the adapter never aborts anything itself;
// the quota code has to come from the transaction's own error.
expect(tracker.aborts).toEqual([]);
expect(
memory.readRaw("receipts", "quota-receipt"),
).toBeDefined();
@@ -776,10 +940,11 @@ describe("IndexedDB bounded codec maintenance", () => {
const memory = new MemoryIndexedDbFactory();
await prepareSchema(memory);
seedReceipt(memory, "abort-receipt", 100);
const tracker = trackAborts(memory);
const maintenance = createMaintenance(
memory,
defaultPolicy(),
{ nowEpochMilliseconds: () => 200 },
{ nowEpochMilliseconds: () => 200, factory: tracker.factory },
);
memory.clearLastTransaction();
memory.pauseTransactions();
@@ -796,6 +961,9 @@ describe("IndexedDB bounded codec maintenance", () => {
ok: false,
error: { code: "ABORTED" },
});
// Exactly one abort: the caller's signal. A second one would mean the
// cursor pump and the transaction both claim the abort.
expect(tracker.aborts).toEqual(["readwrite"]);
memory.resumeTransactions();
await Promise.resolve();
expect(
+311
View File
@@ -95,17 +95,98 @@ function prepared(
};
}
/**
* Records every `transaction.abort()` the journal itself calls, with the mode
* of the transaction it aborted.
*
* A failure code alone cannot tell `fail` (record and abort) from
* `requestFailed` (record only): the fake aborts a transaction on a request
* error by itself, so both land on the same code while only one of them stops
* the writes queued behind it.
*/
function trackAborts(memory: MemoryIndexedDbFactory): Readonly<{
factory: IDBFactory;
aborts: readonly string[];
}> {
const aborts: string[] = [];
const wrapped = new WeakSet<object>();
const wrapDatabase = (database: IDBDatabase): IDBDatabase => {
if (wrapped.has(database)) return database;
wrapped.add(database);
const openTransaction = database.transaction.bind(database);
Object.defineProperty(database, "transaction", {
configurable: true,
value: (...args: Parameters<IDBDatabase["transaction"]>) => {
const transaction = openTransaction(...args);
const abort = transaction.abort.bind(transaction);
Object.defineProperty(transaction, "abort", {
configurable: true,
value: () => {
aborts.push(transaction.mode);
abort();
},
});
return transaction;
},
});
return database;
};
const factory = {
cmp: (first: IDBValidKey, second: IDBValidKey) =>
memory.factory.cmp(first, second),
open: (name: string, version?: number) => {
const request = memory.factory.open(name, version);
let stored: IDBDatabase | undefined = request.result;
if (stored) wrapDatabase(stored);
Object.defineProperty(request, "result", {
configurable: true,
get: () => stored,
set: (value: IDBDatabase | undefined) => {
stored = value ? wrapDatabase(value) : value;
},
});
return request;
},
} as unknown as IDBFactory;
return Object.freeze({ factory, aborts });
}
function createHarness(factory = new MemoryIndexedDbFactory()) {
let tokenSequence = 0;
const journal = createIndexedDbOpfsJournal({
authorityToken,
factory: factory.factory,
// `listCommittedObjects` is the only caller that needs a key range, and
// this environment has no global one.
keyRange: factory.keyRange,
createFencingToken: () =>
`fencing_${String(++tokenSequence).padStart(8, "0")}`,
});
return { factory, journal };
}
async function commitObject(
journal: ReturnType<typeof createHarness>["journal"],
transactionId: string,
objectId: string,
byteLength: number,
): Promise<void> {
const input = beginInput(transactionId, objectId, byteLength);
const begun = await journal.begin(input);
if (!begun.ok) throw new Error(`begin failed for ${objectId}`);
const token = begun.value.fencingToken;
const ready = await journal.markFilesReady(
transactionId,
token,
prepared(input),
);
if (!ready.ok) throw new Error(`markFilesReady failed for ${objectId}`);
const committed = await journal.commitPut(transactionId, token);
if (!committed.ok) throw new Error(`commitPut failed for ${objectId}`);
const completed = await journal.complete(transactionId, token);
if (!completed.ok) throw new Error(`complete failed for ${objectId}`);
}
describe("IndexedDB OPFS journal", () => {
it("fences stale writers and atomically publishes object, budget and chunk refs", async () => {
const { factory, journal } = createHarness();
@@ -428,4 +509,234 @@ describe("IndexedDB OPFS journal", () => {
error: { code: "CORRUPT_DATA" },
});
});
it("reports a unique logical-key violation as the request's own ConstraintError", async () => {
// OP-1. Two open journal rows for one object collide on the `by-logical-key`
// index, which is the only `unique: true` index in `src/adapters`. The
// violation belongs to the `add` request, not to the transaction: the
// journal never asks for the row's uniqueness, it asks the index to enforce
// it, so the answer has to be the request's `ConstraintError` rather than
// whatever the transaction happened to abort with.
const memory = new MemoryIndexedDbFactory();
const tracker = trackAborts(memory);
let tokenSequence = 0;
const journal = createIndexedDbOpfsJournal({
authorityToken,
factory: tracker.factory,
createFencingToken: () =>
`fencing_${String(++tokenSequence).padStart(8, "0")}`,
});
const first = await journal.begin(
beginInput("transaction_dupe0001", "object_dupe_1234", 1),
);
expect(first).toMatchObject({ ok: true });
expect(
await journal.begin(
beginInput("transaction_dupe0002", "object_dupe_1234", 1),
),
).toEqual({
ok: false,
error: {
code: "CONFLICT",
operation: "INDEXEDDB_WRITE",
retryable: false,
recovery: "NONE",
},
});
// `mapIndexedDbException`'s ConstraintError arm carries no recovery, while
// the journal's own `conflict()` helper carries REOPEN. The NONE above is
// what proves the answer came from the native error rather than from a
// predicate the journal evaluated itself.
expect(tracker.aborts).toEqual([]);
// The losing transaction rolled back whole: no budget reservation from the
// second `begin` survives, so the partition still admits its full budget.
expect(memory.readRaw("opfs-budgets", `${scope.authorityToken}|${scope.namespaceToken}|${scope.partitionToken}`)).toMatchObject({
reservedBytes: 1,
});
expect(
(await journal.listIncomplete(10)) as unknown,
).toMatchObject({
ok: true,
value: { transactions: [{ transactionId: "transaction_dupe0001" }] },
});
});
it("lets the first explicit failure win over a later success in the same transaction", async () => {
// OP-2. `begin` runs two independent request chains: the scope-binding
// chain can fail while the object/budget chain is still queued to succeed.
// The binding chain's `get` is issued first, so its verdict always lands
// first and the later `succeed` never reaches the caller. The abort count
// is what separates "the journal rejected this" from "the store did".
const memory = new MemoryIndexedDbFactory();
const tracker = trackAborts(memory);
let tokenSequence = 0;
const journal = createIndexedDbOpfsJournal({
authorityToken,
factory: tracker.factory,
createFencingToken: () =>
`fencing_${String(++tokenSequence).padStart(8, "0")}`,
});
const bound = await journal.begin(
beginInput("transaction_order001", "object_order_1234", 1),
);
if (!bound.ok) throw new Error("binding begin failed");
await journal.rollback(
"transaction_order001",
bound.value.fencingToken,
);
const abortsBefore = tracker.aborts.length;
expect(
await journal.begin({
...beginInput("transaction_order002", "object_order_5678", 1),
targetStoragePolicy: { ...policy, owner: "rebound-owner" },
}),
).toEqual({
ok: false,
error: {
code: "POLICY_REJECTED",
operation: "INDEXEDDB_WRITE",
retryable: false,
recovery: "READ_ONLY",
},
});
// Exactly one abort, from the binding chain's `fail`. A second would mean
// the budget chain also reached a verdict.
expect(tracker.aborts.length - abortsBefore).toBe(1);
expect(memory.readRaw("opfs-journal", "transaction_order002")).toBeUndefined();
});
it("keeps a commit failure attributable to the transaction rather than a request", async () => {
// The commit itself fails, so no request ever errors. The journal must not
// claim an abort it did not perform, and the quota code has to come from
// the transaction's own error.
const memory = new MemoryIndexedDbFactory();
const tracker = trackAborts(memory);
let tokenSequence = 0;
const journal = createIndexedDbOpfsJournal({
authorityToken,
factory: tracker.factory,
createFencingToken: () =>
`fencing_${String(++tokenSequence).padStart(8, "0")}`,
});
memory.failNextWriteCommit(
new DOMException("quota", "QuotaExceededError"),
);
expect(
await journal.begin(
beginInput("transaction_quota001", "object_quota_1234", 1),
),
).toEqual({
ok: false,
error: {
code: "QUOTA_EXCEEDED",
operation: "INDEXEDDB_WRITE",
retryable: false,
recovery: "READ_ONLY",
},
});
expect(tracker.aborts).toEqual([]);
});
it("pages incomplete transactions and validates a row before the page limit", async () => {
const { factory, journal } = createHarness();
for (const index of [1, 2, 3]) {
const id = `transaction_page000${index}`;
expect(
await journal.begin(
beginInput(id, `object_page_000${index}`, 1),
),
).toMatchObject({ ok: true });
}
expect(await journal.listIncomplete(2)).toMatchObject({
ok: true,
value: { moreAvailable: true },
});
const page = await journal.listIncomplete(2);
if (!page.ok) throw new Error("listIncomplete failed");
expect(page.value.transactions).toHaveLength(2);
const whole = await journal.listIncomplete(10);
if (!whole.ok) throw new Error("listIncomplete failed");
expect(whole.value.transactions).toHaveLength(3);
expect(whole.value.moreAvailable).toBe(false);
// A corrupt row one past the requested page still fails the read. The
// journal validates a row before it checks the limit, so a page that is
// already full does not hide the next row's damage behind `moreAvailable`.
factory.seed("opfs-journal", {
transactionId: "transaction_page9999",
startedAtEpochMs: 9_000,
corrupt: true,
});
expect(await journal.listIncomplete(3)).toMatchObject({
ok: false,
error: { code: "CORRUPT_DATA", recovery: "READ_ONLY" },
});
});
it("pages committed objects and reports where the next page resumes", async () => {
const { journal } = createHarness();
await commitObject(journal, "transaction_obj00001", "object_aaaa0001", 1);
await commitObject(journal, "transaction_obj00002", "object_bbbb0002", 1);
await commitObject(journal, "transaction_obj00003", "object_cccc0003", 1);
const first = await journal.listCommittedObjects({ scope, limit: 2 });
if (!first.ok) throw new Error("listCommittedObjects failed");
expect(first.value.objects.map((o) => o.descriptor.objectId)).toEqual([
"object_aaaa0001",
"object_bbbb0002",
]);
// A page cut short by the limit names the cursor the caller resumes from.
expect(first.value.moreAvailable).toBe(true);
expect(first.value.nextObjectId).toBe("object_bbbb0002");
const second = await journal.listCommittedObjects({
scope,
limit: 2,
afterObjectId: first.value.nextObjectId ?? undefined,
});
if (!second.ok) throw new Error("listCommittedObjects failed");
expect(second.value.objects.map((o) => o.descriptor.objectId)).toEqual([
"object_cccc0003",
]);
// An exhausted scan has nothing to resume from, so it reports neither.
expect(second.value.moreAvailable).toBe(false);
expect(second.value.nextObjectId).toBeNull();
});
it("answers UNSUPPORTED once the journal is closed", async () => {
const { factory, journal } = createHarness();
expect(
await journal.getCommittedObject(scope, "object_12345678"),
).toEqual({ ok: true, value: null });
journal.close();
expect(factory.isConnectionClosed()).toBe(true);
// A closed journal is not a retryable outage and not an abort: the store
// is gone for this realm, so the caller is told to work online. The
// failure names INDEXEDDB_OPEN rather than the operation that asked,
// because it belongs to the open that never happened.
expect(
await journal.getCommittedObject(scope, "object_12345678"),
).toEqual({
ok: false,
error: {
code: "UNSUPPORTED",
operation: "INDEXEDDB_OPEN",
retryable: false,
recovery: "ONLINE_ONLY",
},
});
expect(
await journal.begin(
beginInput("transaction_closed001", "object_closed_001", 1),
),
).toMatchObject({ ok: false, error: { code: "UNSUPPORTED" } });
});
});
+206 -15
View File
@@ -152,6 +152,33 @@ function dependencies(
};
}
/**
* Counts the aborts the adapter asks for. A failure code on its own cannot
* tell `fail`, which aborts, from `requestFailed`, which only records: both
* report the same code once the transaction unwinds, and only the abort
* decides whether the writes already queued can still commit.
*/
function trackAborts(
memory: MemoryIndexedDbFactory,
): Readonly<{ count: number }> {
const tracker = { count: 0 };
let current = memory.lastTransaction;
Object.defineProperty(memory, "lastTransaction", {
configurable: true,
get: () => current,
set: (transaction: MemoryIndexedDbFactory["lastTransaction"]) => {
current = transaction;
if (!transaction) return;
const abort = transaction.abort.bind(transaction);
transaction.abort = () => {
tracker.count += 1;
abort();
};
},
});
return tracker;
}
async function waitForTransaction(
memory: MemoryIndexedDbFactory,
): Promise<void> {
@@ -464,7 +491,7 @@ describe("IndexedDB runtime", () => {
});
});
it("retains native open ownership after a blocked timeout until late success", async () => {
it("reopens after a blocked deadline and ignores the abandoned request", async () => {
const memory = new MemoryIndexedDbFactory();
memory.blockNextOpen();
const nativeOpen = vi.spyOn(memory.factory, "open");
@@ -489,23 +516,59 @@ describe("IndexedDB runtime", () => {
ok: false,
error: { code: "BLOCKED" },
});
const second = runtime.open();
await Promise.resolve();
const nativeOpenCountBeforeLateSuccess = nativeOpen.mock.calls.length;
memory.releaseBlockedOpen();
await expect(second).resolves.toMatchObject({
ok: false,
error: { code: "BLOCKED" },
});
await Promise.resolve();
expect(nativeOpenCountBeforeLateSuccess).toBe(1);
expect(memory.isConnectionClosed()).toBe(true);
expect(runtime.getStatus()).toEqual({
kind: "CLOSED",
reason: "NOT_OPENED",
});
// The deadline ends the caller's wait, not the native request. A retry
// therefore dispatches a second open instead of answering from the
// abandoned one, which is the one behavior the connection kernel does not
// preserve: it cannot report when an open it already settled lands.
expect(await runtime.open()).toEqual({ ok: true, value: undefined });
expect(nativeOpen).toHaveBeenCalledTimes(2);
expect(runtime.getStatus()).toEqual({
kind: "READY",
schemaVersion: 1,
});
// The abandoned request lands late. Its connection is closed inside the
// kernel and must not disturb the one the retry established.
memory.releaseBlockedOpen();
await Promise.resolve();
expect(runtime.getStatus()).toEqual({
kind: "READY",
schemaVersion: 1,
});
expect(await runtime.read("late-arrival")).toEqual({
ok: true,
value: null,
});
});
it("ends an open in flight with UNAVAILABLE when the runtime closes", async () => {
const memory = new MemoryIndexedDbFactory();
memory.blockNextOpen();
const runtime = createIndexedDbRuntime(dependencies(memory));
const pending = runtime.open();
await Promise.resolve();
expect(runtime.getStatus()).toMatchObject({ kind: "BLOCKED" });
runtime.close();
// Closing the runtime is not the caller aborting. The open is reported as
// UNAVAILABLE/REOPEN so a caller builds a new runtime rather than reading
// its own cancellation into someone else's shutdown.
expect(await pending).toEqual({
ok: false,
error: {
code: "UNAVAILABLE",
operation: "INDEXEDDB_OPEN",
retryable: true,
recovery: "REOPEN",
},
});
expect(runtime.getStatus()).toEqual({ kind: "DISPOSED" });
});
it("closes immediately on versionchange and isolates listener failures", async () => {
@@ -735,7 +798,24 @@ describe("IndexedDB runtime", () => {
recovery: "READ_ONLY",
},
});
expect(memory.isConnectionClosed()).toBe(true);
// Rejecting the upgrade aborts the versionchange transaction, so the
// half-created schema is rolled back instead of being committed at
// version 1. Only this assertion separates a rejected upgrade from an
// upgrade that was allowed to commit and then refused at admission —
// `NotFoundError` maps to MIGRATION_FAILED either way.
expect([...memory.storeNames()]).toEqual([]);
// A failed open request never exposes a connection, so fail-closed is
// asserted through the runtime rather than through the fake's last
// database handle: no status claiming a live schema, and no read that can
// reach one.
expect(runtime.getStatus()).toEqual({
kind: "CLOSED",
reason: "NOT_OPENED",
});
expect(await runtime.read("any-key")).toMatchObject({
ok: false,
error: { code: "UNAVAILABLE", recovery: "REOPEN" },
});
});
it("derives physical identity only from opaque scope and rejects an override", () => {
@@ -902,6 +982,117 @@ describe("IndexedDB runtime", () => {
).not.toContain("ttl_authority_proof_001");
});
it("reports a batch that ran out of both budgets as time-exhausted", async () => {
const memory = new MemoryIndexedDbFactory();
const base = dependencies(memory);
// The start of the batch and the first row are inside the deadline; the
// second row is not, and by then the row budget is spent as well.
let monotonicCalls = 0;
const runtime = createIndexedDbRuntime({
...base,
storagePolicy: {
...TEST_STORAGE_POLICY,
retention: { kind: "SESSION" },
},
authorizeLifecycle: () => ({
authorized: true as const,
proofToken: "budget_authority_proof_001",
}),
nowMonotonicMilliseconds: () => (monotonicCalls++ < 2 ? 0 : 5_000),
});
expect(await runtime.open()).toMatchObject({ ok: true });
for (const key of ["budget-one", "budget-two"]) {
expect(
await runtime.compareAndSwap({
key,
value: { label: key, rank: 1 },
expectedRevision: null,
idempotencyKey: `${key}-create`,
}),
).toMatchObject({ ok: true });
}
// Both budgets are spent at the same row. The receipt says the deadline
// did it, because a caller that reads `budgetExhausted` as "the clock ran
// out" would otherwise schedule the next batch as if it had room.
expect(
await runtime.enforceLifecycleBatch({
action: "SESSION_END",
maxRows: 1,
maxDurationMs: 1_000,
}),
).toEqual({
ok: true,
value: {
state: "MORE",
scannedRows: 1,
deletedRows: 1,
budgetExhausted: true,
},
});
});
it("aborts a sweep whose budget row cannot account for the deleted bytes", async () => {
const memory = new MemoryIndexedDbFactory();
let epochMs = 1_000;
const runtime = createIndexedDbRuntime(
dependencies(memory, {
storagePolicy: {
...TEST_STORAGE_POLICY,
retention: { kind: "TTL", maxAgeMs: 10 },
},
keyRange:
memory.keyRange as NonNullable<
IndexedDbRuntimeDependencies<Item, Item, Query>["keyRange"]
>,
nowEpochMilliseconds: () => epochMs,
nowMonotonicMilliseconds: () => 0,
authorizeLifecycle: () => ({
authorized: true,
proofToken: "sweep_authority_proof_001",
}),
}),
);
expect(await runtime.open()).toMatchObject({ ok: true });
expect(
await runtime.compareAndSwap({
key: "sweep-record",
value: { label: "expires", rank: 1 },
expectedRevision: null,
idempotencyKey: "sweep-create",
}),
).toMatchObject({ ok: true });
// A budget that cannot account for the record's bytes is corrupt, and the
// sweep only discovers it after both deletions have already succeeded
// inside the transaction.
memory.seed("governance", {
bindingKey: "dataset-budget",
budgetVersion: 1,
usedBytes: 0,
receiptCount: 1,
});
const aborts = trackAborts(memory);
epochMs = 1_011;
expect(
await runtime.enforceLifecycleBatch({
action: "RETENTION_SWEEP",
maxRows: 10,
maxDurationMs: 1_000,
}),
).toMatchObject({
ok: false,
error: { code: "CORRUPT_DATA" },
});
// `fail` aborts. Recording the failure without aborting would report the
// same code while letting the two deletions commit against a budget that
// never moved.
expect(aborts.count).toBe(1);
expect(memory.readRaw("records", "sweep-record")).toBeDefined();
expect(memory.readRaw("retention", "sweep-record")).toBeDefined();
});
it("requires lifecycle authority and only deletes sync-confirmed rows", async () => {
const memory = new MemoryIndexedDbFactory();
const authorizeLifecycle = vi
+716
View File
@@ -0,0 +1,716 @@
import { describe, expect, it, vi } from "vitest";
import type {
IndexedDbFailureCause,
IndexedDbTranslate,
} from "../../src/adapters/platform/indexeddb-connection.ts";
import { openIndexedDbDatabase } from "../../src/adapters/platform/indexeddb-connection.ts";
import {
onIndexedDbRequest,
openIndexedDbTransaction,
runIndexedDbTransaction,
walkIndexedDbCursor,
type IndexedDbCursorStep,
type IndexedDbRequestSink,
type IndexedDbWalkSummary,
} from "../../src/adapters/platform/indexeddb-transaction.ts";
import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts";
/**
* IDB-X-02 golden tests. Four hand-written copies of this state machine already
* disagree about request errors, value-less completions and durability. Every
* one of those choices has to remain expressible at the call site, so the tests
* assert the mechanics and never a taxonomy.
*/
type TestFailure = Readonly<{ cause: IndexedDbFailureCause["kind"]; detail?: unknown }>;
function recordingTranslate(
seen: IndexedDbFailureCause["kind"][] = [],
): IndexedDbTranslate<TestFailure> {
return (cause) => {
seen.push(cause.kind);
switch (cause.kind) {
case "NATIVE_EXCEPTION":
return { cause: cause.kind, detail: cause.error };
case "BLOCKED":
return { cause: cause.kind };
case "BLOCKED_DEADLINE":
case "CALLER_ABORT":
case "CLOSED":
case "NO_VALUE_PRODUCED":
case "UNSUPPORTED":
return { cause: cause.kind };
case "UPGRADE_REJECTED":
case "ADMISSION_REJECTED":
return { cause: cause.kind, detail: cause.detail };
default: {
const exhaustive: never = cause;
return exhaustive;
}
}
};
}
type Row = Readonly<{ id: string; rank: number }>;
const ROWS: readonly Row[] = Object.freeze([
Object.freeze({ id: "a", rank: 1 }),
Object.freeze({ id: "b", rank: 2 }),
Object.freeze({ id: "c", rank: 3 }),
Object.freeze({ id: "d", rank: 4 }),
]);
async function seededDatabase(
rows: readonly Row[] = ROWS,
): Promise<Readonly<{ memory: MemoryIndexedDbFactory; database: IDBDatabase }>> {
const memory = new MemoryIndexedDbFactory();
const opened = await openIndexedDbDatabase<TestFailure>({
factory: memory.factory,
databaseName: "kernel",
version: 1,
translate: recordingTranslate(),
upgrade: ({ database }) => {
database.createObjectStore("rows", { keyPath: "id" });
return { kind: "APPLIED" };
},
});
if (!opened.ok) throw new Error("fixture database did not open");
for (const row of rows) memory.seed("rows", row);
return { memory, database: opened.value };
}
type StubTransaction = {
error: DOMException | null;
abort: () => void;
oncomplete: ((event: Event) => unknown) | null;
onerror: ((event: Event) => unknown) | null;
onabort: ((event: Event) => unknown) | null;
objectStore: (name: string) => IDBObjectStore;
};
/**
* A transaction the test drives by hand. The memory fake aborts on every
* request error, so "recorded but not aborted" and "abort() itself throws" —
* the two behaviors the four copies disagree about — are only observable here.
*/
function stubDatabase(
options: Readonly<{ abortThrows?: boolean; rejectOptionsBag?: boolean }> = {},
): Readonly<{
database: IDBDatabase;
transactions: StubTransaction[];
calls: unknown[][];
}> {
const transactions: StubTransaction[] = [];
const calls: unknown[][] = [];
const database = {
transaction: (...args: unknown[]) => {
calls.push(args);
if (options.rejectOptionsBag === true && args.length > 2) {
throw new TypeError("This engine has no durability option.");
}
const transaction: StubTransaction = {
error: null,
abort: vi.fn(() => {
if (options.abortThrows === true) {
throw new DOMException("already finished", "InvalidStateError");
}
}),
oncomplete: null,
onerror: null,
onabort: null,
objectStore: () => ({}) as IDBObjectStore,
};
transactions.push(transaction);
return transaction as unknown as IDBTransaction;
},
} as unknown as IDBDatabase;
return { database, transactions, calls };
}
function stubSink(): Readonly<{
sink: IndexedDbRequestSink<TestFailure>;
failures: TestFailure[];
requestErrors: unknown[];
}> {
const failures: TestFailure[] = [];
const requestErrors: unknown[] = [];
return {
failures,
requestErrors,
sink: {
fail: (failure) => failures.push(failure),
requestFailed: (error) => requestErrors.push(error),
},
};
}
describe("shared IndexedDB transaction mechanics", () => {
it("returns the value the queue produced once the transaction commits", async () => {
const { database, memory } = await seededDatabase();
const result = await runIndexedDbTransaction<string, TestFailure>({
database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (transaction, context) => {
const store = transaction.objectStore("rows");
onIndexedDbRequest(store.put({ id: "e", rank: 5 }), context, () => {
context.succeed("written");
});
},
});
expect(result).toEqual({ ok: true, value: "written" });
expect(memory.readRaw("rows", "e")).toEqual({ id: "e", rank: 5 });
});
it("reports NO_VALUE_PRODUCED when a transaction completes without succeed", async () => {
const { database } = await seededDatabase();
const seen: IndexedDbFailureCause["kind"][] = [];
const result = await runIndexedDbTransaction<string, TestFailure>({
database,
stores: ["rows"],
mode: "readonly",
translate: recordingTranslate(seen),
queue: (transaction, context) => {
onIndexedDbRequest(
transaction.objectStore("rows").get("a"),
context,
() => undefined,
);
},
});
expect(result).toEqual({
ok: false,
error: { cause: "NO_VALUE_PRODUCED" },
});
expect(seen).toEqual(["NO_VALUE_PRODUCED"]);
});
it("aborts on fail() and reports the recorded failure", async () => {
const { database, memory } = await seededDatabase();
const result = await runIndexedDbTransaction<string, TestFailure>({
database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (transaction, context) => {
const store = transaction.objectStore("rows");
onIndexedDbRequest(store.put({ id: "e", rank: 5 }), context, () => {
context.fail({ cause: "ADMISSION_REJECTED", detail: "policy" });
});
},
});
expect(result).toEqual({
ok: false,
error: { cause: "ADMISSION_REJECTED", detail: "policy" },
});
// The aborted transaction must not have committed the write.
expect(memory.readRaw("rows", "e")).toBeUndefined();
});
it("routes a request-level error into the sink", async () => {
const { database } = await seededDatabase();
const result = await runIndexedDbTransaction<string, TestFailure>({
database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (transaction, context) => {
const store = transaction.objectStore("rows");
// `add` on an existing key is a request-level ConstraintError, the
// exact case `indexeddb-opfs-journal.ts` never wires today.
onIndexedDbRequest(store.add({ id: "a", rank: 9 }), context, () => {
context.succeed("unreachable");
});
},
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.cause).toBe("NATIVE_EXCEPTION");
expect((result.error.detail as DOMException).name).toBe("ConstraintError");
});
it("records a request error without aborting, while fail() aborts", () => {
const stub = stubDatabase();
void runIndexedDbTransaction<string, TestFailure>({
database: stub.database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (_transaction, context) => {
context.requestFailed(new Error("recorded only"));
},
});
const transaction = stub.transactions[0];
expect(transaction).toBeDefined();
expect(transaction?.abort).not.toHaveBeenCalled();
});
it("never claims a caller abort when transaction.abort() throws", async () => {
// CP-4. A transaction can be durably committed while its completion event
// is still queued. Reporting ABORTED for it would call a committed write a
// failure, so the transaction's own events decide the outcome.
const stub = stubDatabase({ abortThrows: true });
const controller = new AbortController();
const pending = runIndexedDbTransaction<string, TestFailure>({
database: stub.database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
signal: controller.signal,
queue: (_transaction, context) => {
context.succeed("committed");
},
});
controller.abort();
stub.transactions[0]?.oncomplete?.(new Event("complete"));
await expect(pending).resolves.toEqual({ ok: true, value: "committed" });
});
it("reports CALLER_ABORT when the signal aborts the transaction", async () => {
const stub = stubDatabase();
const controller = new AbortController();
const pending = runIndexedDbTransaction<string, TestFailure>({
database: stub.database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
signal: controller.signal,
queue: () => undefined,
});
controller.abort();
expect(stub.transactions[0]?.abort).toHaveBeenCalledTimes(1);
stub.transactions[0]?.onabort?.(new Event("abort"));
await expect(pending).resolves.toEqual({
ok: false,
error: { cause: "CALLER_ABORT" },
});
});
it("returns CALLER_ABORT without opening a transaction for an aborted signal", async () => {
const stub = stubDatabase();
const controller = new AbortController();
controller.abort();
await expect(
runIndexedDbTransaction<string, TestFailure>({
database: stub.database,
stores: ["rows"],
mode: "readonly",
translate: recordingTranslate(),
signal: controller.signal,
queue: () => undefined,
}),
).resolves.toEqual({ ok: false, error: { cause: "CALLER_ABORT" } });
expect(stub.calls).toHaveLength(0);
});
it("maps a throw from transaction creation", async () => {
const boom = new DOMException("closed", "InvalidStateError");
const database = {
transaction: () => {
throw boom;
},
} as unknown as IDBDatabase;
await expect(
runIndexedDbTransaction<string, TestFailure>({
database,
stores: ["rows"],
mode: "readonly",
translate: recordingTranslate(),
queue: () => undefined,
}),
).resolves.toEqual({
ok: false,
error: { cause: "NATIVE_EXCEPTION", detail: boom },
});
});
it("maps a throw from the queue callback and aborts", async () => {
const { database, memory } = await seededDatabase();
const boom = new Error("queue defect");
const result = await runIndexedDbTransaction<string, TestFailure>({
database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (transaction) => {
transaction.objectStore("rows").put({ id: "e", rank: 5 });
throw boom;
},
});
expect(result).toEqual({
ok: false,
error: { cause: "NATIVE_EXCEPTION", detail: boom },
});
expect(memory.readRaw("rows", "e")).toBeUndefined();
});
it("an abort after succeed reports a failure rather than the value", async () => {
const stub = stubDatabase();
const pending = runIndexedDbTransaction<string, TestFailure>({
database: stub.database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (_transaction, context) => {
context.succeed("value");
context.fail({ cause: "CLOSED" });
},
});
const transaction = stub.transactions[0];
if (!transaction) throw new Error("no transaction");
transaction.error = new DOMException("aborted", "AbortError");
transaction.onabort?.(new Event("abort"));
const result = await pending;
expect(result.ok).toBe(false);
if (result.ok) return;
// The first candidate wins, so the later `fail` never becomes the value;
// an aborted transaction still cannot report the success it never kept.
expect(result.error.cause).toBe("NATIVE_EXCEPTION");
});
});
describe("IndexedDB transaction factory", () => {
it("omits the options bag entirely for an undefined durability", () => {
const stub = stubDatabase();
openIndexedDbTransaction(stub.database, ["rows"], "readonly");
expect(stub.calls).toEqual([[["rows"], "readonly"]]);
});
it("passes a named durability as an options bag", () => {
const stub = stubDatabase();
openIndexedDbTransaction(stub.database, ["rows"], "readwrite", "strict");
expect(stub.calls).toEqual([
[["rows"], "readwrite", { durability: "strict" }],
]);
});
it("falls back to the no-options form when the engine rejects the bag", () => {
const stub = stubDatabase({ rejectOptionsBag: true });
openIndexedDbTransaction(stub.database, ["rows"], "readwrite", "relaxed");
expect(stub.calls).toEqual([
[["rows"], "readwrite", { durability: "relaxed" }],
[["rows"], "readwrite"],
]);
});
it("rethrows a non-TypeError from transaction creation", () => {
const boom = new DOMException("closed", "InvalidStateError");
const database = {
transaction: () => {
throw boom;
},
} as unknown as IDBDatabase;
expect(() =>
openIndexedDbTransaction(database, ["rows"], "readonly", "strict"),
).toThrow(boom);
});
});
describe("IndexedDB cursor pump", () => {
async function walk(
input: Readonly<{
visit: (
visit: Readonly<{
cursor: IDBCursorWithValue;
scannedRows: number;
resume: (step: IndexedDbCursorStep) => void;
}>,
) => IndexedDbCursorStep;
budget?: Parameters<typeof walkIndexedDbCursor<TestFailure>>[0]["budget"];
signal?: AbortSignal;
store?: IDBObjectStore | undefined;
}>,
): Promise<
Readonly<{
result: Awaited<ReturnType<typeof runIndexedDbTransaction<IndexedDbWalkSummary, TestFailure>>>;
}>
> {
const { database } = await seededDatabase();
const result = await runIndexedDbTransaction<
IndexedDbWalkSummary,
TestFailure
>({
database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (transaction, context) => {
const store = transaction.objectStore("rows");
walkIndexedDbCursor<TestFailure>({
request: store.openCursor(),
sink: context,
translate: recordingTranslate(),
...(input.budget ? { budget: input.budget } : {}),
...(input.signal ? { signal: input.signal } : {}),
visit: input.visit,
done: (summary) => context.succeed(summary),
});
},
});
return { result };
}
it("visits every row and reports EXHAUSTED", async () => {
const visited: string[] = [];
const { result } = await walk({
visit: ({ cursor }) => {
visited.push((cursor.value as Row).id);
return { kind: "CONTINUE" };
},
});
expect(visited).toEqual(["a", "b", "c", "d"]);
expect(result).toEqual({
ok: true,
value: { reason: "EXHAUSTED", scannedRows: 4 },
});
});
it("ends the walk where the visitor stops it", async () => {
const { result } = await walk({
visit: ({ scannedRows }) =>
scannedRows === 2 ? { kind: "STOP" } : { kind: "CONTINUE" },
});
expect(result).toEqual({
ok: true,
value: { reason: "STOPPED", scannedRows: 2 },
});
});
it("resumes a row after the visitor's own nested request chain", async () => {
// Without SUSPEND the pump is unusable by runtime and maintenance: every
// walk there issues nested requests before advancing.
const order: string[] = [];
const { database } = await seededDatabase();
const result = await runIndexedDbTransaction<
IndexedDbWalkSummary,
TestFailure
>({
database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (transaction, context) => {
const store = transaction.objectStore("rows");
walkIndexedDbCursor<TestFailure>({
request: store.openCursor(),
sink: context,
translate: recordingTranslate(),
visit: ({ cursor, resume }) => {
const id = (cursor.value as Row).id;
order.push(`visit:${id}`);
onIndexedDbRequest(store.get(id), context, (value) => {
order.push(`nested:${(value as Row).id}`);
resume({ kind: "CONTINUE" });
// Idempotent: a second resume cannot advance the cursor twice.
resume({ kind: "CONTINUE" });
});
return { kind: "SUSPEND" };
},
done: (summary) => context.succeed(summary),
});
},
});
expect(result).toEqual({
ok: true,
value: { reason: "EXHAUSTED", scannedRows: 4 },
});
expect(order).toEqual([
"visit:a",
"nested:a",
"visit:b",
"nested:b",
"visit:c",
"nested:c",
"visit:d",
"nested:d",
]);
});
it("supports both keyed resume forms", async () => {
const skipped: string[] = [];
const { result } = await walk({
visit: ({ cursor, scannedRows }) => {
skipped.push((cursor.value as Row).id);
if (scannedRows === 1) return { kind: "CONTINUE_FROM", key: "c" };
if (scannedRows === 2) {
return { kind: "CONTINUE_PRIMARY", key: "d", primaryKey: "d" };
}
return { kind: "CONTINUE" };
},
});
expect(skipped).toEqual(["a", "c", "d"]);
expect(result).toEqual({
ok: true,
value: { reason: "EXHAUSTED", scannedRows: 3 },
});
});
it("stops on a row budget and on a time budget with distinct reasons", async () => {
const rowBudget = await walk({
budget: {
admit: (scannedRows) =>
scannedRows >= 2
? { ok: true, value: "ROW_BUDGET" }
: { ok: true, value: "CONTINUE" },
},
visit: () => ({ kind: "CONTINUE" }),
});
expect(rowBudget.result).toEqual({
ok: true,
value: { reason: "ROW_BUDGET", scannedRows: 2 },
});
const timeBudget = await walk({
budget: {
admit: (scannedRows) =>
scannedRows >= 1
? { ok: true, value: "TIME_BUDGET" }
: { ok: true, value: "CONTINUE" },
},
visit: () => ({ kind: "CONTINUE" }),
});
expect(timeBudget.result).toEqual({
ok: true,
value: { reason: "TIME_BUDGET", scannedRows: 1 },
});
});
it("routes an unreadable budget clock into the sink instead of continuing", async () => {
const { result } = await walk({
budget: {
admit: () => ({ ok: false, error: { cause: "UNSUPPORTED" } }),
},
visit: () => ({ kind: "CONTINUE" }),
});
expect(result).toEqual({ ok: false, error: { cause: "UNSUPPORTED" } });
});
it("aborts the transaction and ends the walk when the caller signal fired", async () => {
const controller = new AbortController();
const { result } = await walk({
signal: controller.signal,
visit: ({ cursor }) => {
if ((cursor.value as Row).id === "a") controller.abort();
return { kind: "CONTINUE" };
},
});
expect(result).toEqual({ ok: false, error: { cause: "CALLER_ABORT" } });
});
it("routes a native advance failure through the sink", async () => {
const { result } = await walk({
visit: ({ cursor }) => {
// Advancing twice is an InvalidStateError in the engine; the pump must
// report it rather than let it escape the event handler.
cursor.continue();
return { kind: "CONTINUE" };
},
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.cause).toBe("NATIVE_EXCEPTION");
});
it("reports a cursor request error through requestFailed and stops", () => {
const stub = stubSink();
const request = {
result: null,
error: new DOMException("gone", "UnknownError"),
onsuccess: null as ((event: Event) => unknown) | null,
onerror: null as ((event: Event) => unknown) | null,
};
const done = vi.fn();
walkIndexedDbCursor<TestFailure>({
request: request as unknown as IDBRequest<IDBCursorWithValue | null>,
sink: stub.sink,
translate: recordingTranslate(),
visit: () => ({ kind: "CONTINUE" }),
done,
});
request.onerror?.(new Event("error"));
expect(stub.requestErrors).toEqual([request.error]);
// The transaction's own outcome decides the result; the walk has no value.
expect(done).not.toHaveBeenCalled();
});
it("routes a throw from the visitor into the sink", () => {
const stub = stubSink();
const boom = new Error("visitor defect");
const request = {
result: { value: { id: "a" }, continue: vi.fn() },
error: null,
onsuccess: null as ((event: Event) => unknown) | null,
onerror: null as ((event: Event) => unknown) | null,
};
walkIndexedDbCursor<TestFailure>({
request: request as unknown as IDBRequest<IDBCursorWithValue | null>,
sink: stub.sink,
translate: recordingTranslate(),
visit: () => {
throw boom;
},
done: vi.fn(),
});
request.onsuccess?.(new Event("success"));
// A defective visitor must abort rather than let a partial write commit.
expect(stub.failures).toEqual([
{ cause: "NATIVE_EXCEPTION", detail: boom },
]);
});
it("ignores resume when the visitor did not suspend", () => {
const stub = stubSink();
const advance = vi.fn();
const request = {
result: { value: { id: "a" }, continue: advance },
error: null,
onsuccess: null as ((event: Event) => unknown) | null,
onerror: null as ((event: Event) => unknown) | null,
};
walkIndexedDbCursor<TestFailure>({
request: request as unknown as IDBRequest<IDBCursorWithValue | null>,
sink: stub.sink,
translate: recordingTranslate(),
visit: ({ resume }) => {
resume({ kind: "CONTINUE" });
return { kind: "STOP" };
},
done: vi.fn(),
});
request.onsuccess?.(new Event("success"));
expect(advance).not.toHaveBeenCalled();
});
});
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { createCursorPaginationRuntime } from "../../src/adapters/query-cache/cursor-pagination-runtime.ts";
import { createCursorPaginationRuntime } from "../../src/adapters/query-cache/index.ts";
import {
defineMutationIntent,
isValidIdempotencyKey,
@@ -8,8 +8,8 @@ import {
import type {
CursorPage,
CursorPaginationProfile,
} from "../../src/contracts/cursor-pagination.ts";
import type { Result } from "../../src/application/result.ts";
} from "../../src/adapters/query-cache/index.ts";
import type { Result } from "../../src/contracts/result.ts";
const PROFILE: CursorPaginationProfile = Object.freeze({
profileId: "TEST_PAGINATION_V1",
@@ -0,0 +1,420 @@
import { describe, expect, it, vi } from "vitest";
import {
BrowserFilePolicyRegistry,
browserFilePolicyReference,
} from "../../src/adapters/browser-files/browser-file-policy-registry.ts";
import {
createDownloadDeliveryAdapter,
type SaveFileHandle,
} from "../../src/adapters/browser-files/download-delivery-adapter.ts";
import {
CHECKSUM_HEADER,
CONTROL_ENDPOINT,
DATA_ORIGIN,
DIGEST_HEADER,
DOWNLOAD_HREF,
DOWNLOAD_PATH,
NOW,
POLICY_HEADER,
REQUEST_BINDING_SHA256,
UPLOAD_SESSION_ID,
collect,
createHarness,
downloadCapabilityPayload,
downloadResponse,
jsonResponse,
responseWithUrl,
uploadCapabilityPayload,
} from "./presigned-transfer-fixture.ts";
describe("presigned DownloadDelivery integration", () => {
it("connects an issued capability to DownloadDeliveryPort without caller digest input", async () => {
const bytes = new TextEncoder().encode("verified");
const payload = downloadCapabilityPayload(bytes);
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: downloadResponse(bytes.slice().buffer, payload),
) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const issued = await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
const policy = browserFilePolicyReference(
"download",
"presigned-stream",
);
const policies = new BrowserFilePolicyRegistry({
profiles: [
{
reference: policy,
download: {
strategy: "PROMPT_AND_STREAM",
mediaType: "application/octet-stream",
safeExtension: ".bin",
maxTransferBytes: 64,
maxBufferedBytes: 8,
integrity: "REQUIRED",
},
},
],
hardLimits: {
maxInspectionBytes: 64,
maxRetainedFileBytes: 64,
maxPreviewBytes: 64,
maxObjectUrlBytes: 64,
maxTransferBytes: 64,
},
});
const written: number[] = [];
const handle: SaveFileHandle = {
async createWritable() {
return new WritableStream<Uint8Array>({
write(chunk) {
written.push(...chunk);
},
});
},
};
const downloads = createDownloadDeliveryAdapter({
host: { handoff() {} },
policies,
hardMaxObjectUrlBytes: 64,
hardMaxTransferBytes: 64,
browserManagedCapabilities: {
resolve() {
throw new TypeError("not used");
},
},
openAuthorizedSource:
executor.downloadSources.open.bind(executor.downloadSources),
showSaveFilePicker: async () => handle,
userActivation: { isActive: true },
now: () => NOW,
});
const result = await downloads.deliver({
policy,
source: {
kind: "AUTHORIZED_STREAM_RESOURCE",
resourceId: "resource-1",
capability: issued.value,
},
suggestedFileName: "artifact.bin",
signal: new AbortController().signal,
onProgress() {},
});
expect(result).toMatchObject({
ok: true,
value: {
kind: "SAVED",
integrity: "VERIFIED",
bytesWritten: bytes.byteLength,
},
});
expect(written).toEqual([...bytes]);
});
/**
* TR-RR-04. A presigned byte source owns a fetch reader and a capability
* lease, and its port requires `close()`. The delivery consumer never called
* it, so every outcome — success, validation failure, writer failure and
* abort — leaked both.
*/
it.each([
{ label: "success", mode: "SUCCESS" as const },
{ label: "writer failure", mode: "WRITER_FAILURE" as const },
{ label: "abort", mode: "ABORT" as const },
])("closes the presigned source exactly once on $label", async ({ mode }) => {
const bytes = new Uint8Array([1, 2, 3]);
let closes = 0;
const controller = new AbortController();
const source = {
byteLength: bytes.byteLength,
integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" as const,
capability: undefined as never,
close() {
closes += 1;
},
async *stream() {
if (mode === "ABORT") controller.abort();
yield { ok: true as const, value: bytes };
},
};
const capability = Object.freeze({
capabilityReceipt: "capability-close-1",
method: "GET" as const,
binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" },
mediaType: "application/octet-stream",
byteLength: bytes.byteLength,
maxBytes: bytes.byteLength,
expectedSha256: "a".repeat(64),
expiresAtEpochMs: NOW + 60_000,
});
source.capability = capability as never;
const closePolicy = browserFilePolicyReference(
"download",
"presigned-close",
);
const policies = new BrowserFilePolicyRegistry({
profiles: [
{
reference: closePolicy,
download: {
strategy: "PROMPT_AND_STREAM",
mediaType: "application/octet-stream",
safeExtension: ".bin",
maxTransferBytes: 64,
maxBufferedBytes: 8,
integrity: "REQUIRED",
},
},
],
hardLimits: {
maxInspectionBytes: 64,
maxRetainedFileBytes: 64,
maxPreviewBytes: 64,
maxObjectUrlBytes: 64,
maxTransferBytes: 64,
},
});
const handle: SaveFileHandle = {
async createWritable() {
return new WritableStream<Uint8Array>({
write() {
if (mode === "WRITER_FAILURE") {
throw new TypeError("writer exploded");
}
},
});
},
};
const downloads = createDownloadDeliveryAdapter({
host: { handoff() {} },
policies,
hardMaxObjectUrlBytes: 64,
hardMaxTransferBytes: 64,
browserManagedCapabilities: {
resolve() {
throw new TypeError("not used");
},
},
openAuthorizedSource: async () =>
({ ok: true, value: source }) as never,
showSaveFilePicker: async () => handle,
userActivation: { isActive: true },
now: () => NOW,
});
const deliveryResult = await downloads.deliver({
policy: closePolicy,
source: {
kind: "AUTHORIZED_STREAM_RESOURCE",
resourceId: "resource-1",
capability: capability as never,
},
suggestedFileName: "artifact.bin",
signal: controller.signal,
onProgress() {},
});
void deliveryResult;
expect(closes).toBe(1);
});
/**
* TR-02. A lease that resolved after the abort already ended the delivery
* never reached the holder, so nothing closed it: the fetch reader and the
* capability lease outlived the terminal result.
*/
it("closes a source lease that arrives after the delivery was aborted", async () => {
const bytes = new Uint8Array([1, 2, 3]);
let closes = 0;
const controller = new AbortController();
let releaseOpen:
| ((value: { ok: true; value: unknown }) => void)
| undefined;
const source = {
byteLength: bytes.byteLength,
integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" as const,
capability: undefined as never,
close() {
closes += 1;
},
async *stream() {
yield { ok: true as const, value: bytes };
},
};
const capability = Object.freeze({
capabilityReceipt: "capability-late-1",
method: "GET" as const,
binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" },
mediaType: "application/octet-stream",
byteLength: bytes.byteLength,
maxBytes: bytes.byteLength,
expectedSha256: "a".repeat(64),
expiresAtEpochMs: NOW + 60_000,
});
source.capability = capability as never;
const latePolicy = browserFilePolicyReference("download", "presigned-late");
const policies = new BrowserFilePolicyRegistry({
profiles: [
{
reference: latePolicy,
download: {
strategy: "PROMPT_AND_STREAM",
mediaType: "application/octet-stream",
safeExtension: ".bin",
maxTransferBytes: 64,
maxBufferedBytes: 8,
integrity: "REQUIRED",
},
},
],
hardLimits: {
maxInspectionBytes: 64,
maxRetainedFileBytes: 64,
maxPreviewBytes: 64,
maxObjectUrlBytes: 64,
maxTransferBytes: 64,
},
});
const downloads = createDownloadDeliveryAdapter({
host: { handoff() {} },
policies,
hardMaxObjectUrlBytes: 64,
hardMaxTransferBytes: 64,
browserManagedCapabilities: {
resolve() {
throw new TypeError("not used");
},
},
// Ignores the signal entirely and resolves only when the test says so.
openAuthorizedSource: () =>
new Promise((resolve) => {
releaseOpen = resolve as never;
}) as never,
showSaveFilePicker: async () => ({
async createWritable() {
return new WritableStream<Uint8Array>({ write() {} });
},
}),
userActivation: { isActive: true },
now: () => NOW,
});
const delivering = downloads.deliver({
policy: latePolicy,
source: {
kind: "AUTHORIZED_STREAM_RESOURCE",
resourceId: "resource-1",
capability: capability as never,
},
suggestedFileName: "artifact.bin",
signal: controller.signal,
onProgress() {},
});
await new Promise((resolve) => setTimeout(resolve, 0));
controller.abort();
const delivered = await delivering;
expect(delivered.ok).toBe(false);
// The lease arrives only now, long after the terminal result.
releaseOpen?.({ ok: true, value: source });
await new Promise((resolve) => setTimeout(resolve, 0));
expect(closes).toBe(1);
});
it("does not leave a late rejection unhandled after an abort", async () => {
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown) => unhandled.push(reason);
process.on("unhandledRejection", onUnhandled);
try {
const controller = new AbortController();
let rejectOpen: ((reason: unknown) => void) | undefined;
const rejectPolicy = browserFilePolicyReference(
"download",
"presigned-late-reject",
);
const policies = new BrowserFilePolicyRegistry({
profiles: [
{
reference: rejectPolicy,
download: {
strategy: "PROMPT_AND_STREAM",
mediaType: "application/octet-stream",
safeExtension: ".bin",
maxTransferBytes: 64,
maxBufferedBytes: 8,
integrity: "REQUIRED",
},
},
],
hardLimits: {
maxInspectionBytes: 64,
maxRetainedFileBytes: 64,
maxPreviewBytes: 64,
maxObjectUrlBytes: 64,
maxTransferBytes: 64,
},
});
const downloads = createDownloadDeliveryAdapter({
host: { handoff() {} },
policies,
hardMaxObjectUrlBytes: 64,
hardMaxTransferBytes: 64,
browserManagedCapabilities: {
resolve() {
throw new TypeError("not used");
},
},
openAuthorizedSource: () =>
new Promise((_resolve, reject) => {
rejectOpen = reject;
}) as never,
showSaveFilePicker: async () => ({
async createWritable() {
return new WritableStream<Uint8Array>({ write() {} });
},
}),
userActivation: { isActive: true },
now: () => NOW,
});
const delivering = downloads.deliver({
policy: rejectPolicy,
source: {
kind: "AUTHORIZED_STREAM_RESOURCE",
resourceId: "resource-1",
capability: Object.freeze({
capabilityReceipt: "capability-late-2",
method: "GET" as const,
binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" },
mediaType: "application/octet-stream",
byteLength: 3,
maxBytes: 3,
expectedSha256: "a".repeat(64),
expiresAtEpochMs: NOW + 60_000,
}) as never,
},
suggestedFileName: "artifact.bin",
signal: controller.signal,
onProgress() {},
});
await new Promise((resolve) => setTimeout(resolve, 0));
controller.abort();
await delivering;
rejectOpen?.(new Error("late open failure"));
await new Promise((resolve) => setTimeout(resolve, 10));
expect(unhandled).toEqual([]);
} finally {
process.off("unhandledRejection", onUnhandled);
}
});});
@@ -0,0 +1,650 @@
import { describe, expect, it, vi } from "vitest";
import { PRESIGNED_TRANSFER_PROTOCOL } from "../../src/application/ports/browser-transfer/presigned-transfer.ts";
import { createPresignedCapabilityVault } from "../../src/adapters/browser-transfer/presigned/presigned-capability-vault.ts";
import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts";
import {
CHECKSUM_HEADER,
CONTROL_ENDPOINT,
DATA_ORIGIN,
DIGEST_HEADER,
DOWNLOAD_HREF,
DOWNLOAD_PATH,
NOW,
POLICY_HEADER,
REQUEST_BINDING_SHA256,
UPLOAD_SESSION_ID,
collect,
createHarness,
downloadCapabilityPayload,
downloadResponse,
jsonResponse,
responseWithUrl,
uploadCapabilityPayload,
} from "./presigned-transfer-fixture.ts";
describe("presigned download stream lifecycle", () => {
describe("TR-01 the stored capability is the one that was validated", () => {
const baseRegistration = () => ({
protocol: PRESIGNED_TRANSFER_PROTOCOL,
capabilityReceipt: "capability-snapshot-1",
method: "GET" as const,
binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" },
href: `${DATA_ORIGIN}${DOWNLOAD_PATH}`,
origin: DATA_ORIGIN,
path: DOWNLOAD_PATH,
allowedQueryParameters: [],
requestHeaders: [{ name: "x-safe", value: "1" }],
requiredResponseHeaders: [],
digestRequestHeader: null,
digestResponseHeader: null,
receiptResponseHeader: null,
expectedStatus: 200,
expectedResponseByteLength: 3,
mediaType: "application/octet-stream",
byteLength: 3,
maxBytes: 3,
expectedSha256: "a".repeat(64),
expiresAtEpochMs: NOW + 60_000,
});
const freshVault = () =>
createPresignedCapabilityVault({
now: () => NOW,
maxActiveCapabilities: 4,
});
it("refuses a header row that answers differently on a second read", () => {
const vault = freshVault();
let nameReads = 0;
const header = new Proxy(
{ name: "x-safe", value: "1" },
{
getOwnPropertyDescriptor(target, key) {
if (key === "name") {
nameReads += 1;
return {
configurable: true,
enumerable: true,
value: nameReads > 1 ? "authorization" : "x-safe",
};
}
return Reflect.getOwnPropertyDescriptor(target, key);
},
},
);
const registered = vault.register({
...baseRegistration(),
requestHeaders: [header],
} as never);
if (registered.ok) {
// A single read means the value that was checked is the value stored.
const resolved = vault.resolve(registered.value);
expect(resolved.ok).toBe(true);
if (resolved.ok) {
expect(resolved.value.requestHeaders.map((row) => row.name)).toEqual([
"x-safe",
]);
}
}
vault.dispose();
});
const hostileRegistrations: readonly (readonly [string, () => unknown])[] = [
[
"an accessor field",
() =>
Object.defineProperty(baseRegistration(), "href", {
enumerable: true,
get: () => `${DATA_ORIGIN}${DOWNLOAD_PATH}`,
}),
],
[
"an inherited field",
() => Object.assign(Object.create({ injected: true }), baseRegistration()),
],
[
"a symbol field",
() => ({ ...baseRegistration(), [Symbol.for("injected")]: true }),
],
[
"a non-enumerable own field",
() =>
Object.defineProperty(baseRegistration(), "injected", {
enumerable: false,
value: true,
}),
],
[
"a throwing ownKeys trap",
() =>
new Proxy(baseRegistration(), {
ownKeys() {
throw new TypeError("hostile ownKeys trap");
},
}),
],
[
"a null header array",
() => ({ ...baseRegistration(), requestHeaders: null }),
],
[
"a non-iterable header array",
() => ({ ...baseRegistration(), requestHeaders: { length: 1 } }),
],
[
"a header row with an extra field",
() => ({
...baseRegistration(),
requestHeaders: [{ name: "x-safe", value: "1", injected: true }],
}),
],
[
"an accessor header name",
() => ({
...baseRegistration(),
requestHeaders: [
Object.defineProperty({ value: "1" }, "name", {
enumerable: true,
get: () => "x-safe",
}),
],
}),
],
[
"a binding with an extra field",
() => ({
...baseRegistration(),
binding: { kind: "DOWNLOAD", resourceId: "r", injected: true },
}),
],
[
"a null binding",
() => ({ ...baseRegistration(), binding: null }),
],
];
for (const [label, build] of hostileRegistrations) {
it(`rejects ${label} as POLICY_REJECTED`, () => {
const vault = freshVault();
expect(vault.register(build() as never)).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
vault.dispose();
});
}
it("does not observe a mutation of the issuer's object after registration", () => {
const vault = freshVault();
const registration = baseRegistration();
const registered = vault.register(registration as never);
expect(registered.ok).toBe(true);
if (!registered.ok) return;
registration.requestHeaders[0]!.name = "authorization";
registration.expiresAtEpochMs = NOW + 999_999;
const resolved = vault.resolve(registered.value);
expect(resolved.ok).toBe(true);
if (!resolved.ok) return;
expect(resolved.value.requestHeaders.map((row) => row.name)).toEqual([
"x-safe",
]);
expect(resolved.value.expiresAtEpochMs).toBe(NOW + 60_000);
vault.dispose();
});
});
it("does not fetch a presigned download until stream consumption", async () => {
const bytes = new Uint8Array([1, 2, 3]);
const responsePayload = downloadCapabilityPayload(bytes);
let downloadFetches = 0;
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) === CONTROL_ENDPOINT) {
return jsonResponse(responsePayload);
}
downloadFetches += 1;
return downloadResponse(bytes.slice().buffer, responsePayload);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const signal = new AbortController().signal;
const issued = await provider.issueDownload({
resourceId: "resource-1",
signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
const opened = await executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
// BT-PRE-01. open() performs no network I/O.
expect(downloadFetches).toBe(0);
for await (const chunk of opened.value.stream(signal)) {
expect(chunk.ok).toBe(true);
}
expect(downloadFetches).toBe(1);
opened.value.close();
});
it("closes an unused download source without network I/O", async () => {
const bytes = new Uint8Array([1, 2, 3]);
const responsePayload = downloadCapabilityPayload(bytes);
let downloadFetches = 0;
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) === CONTROL_ENDPOINT) {
return jsonResponse(responsePayload);
}
downloadFetches += 1;
return downloadResponse(bytes.slice().buffer, responsePayload);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const signal = new AbortController().signal;
const issued = await provider.issueDownload({
resourceId: "resource-1",
signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
const opened = await executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
opened.value.close();
// close() is idempotent and never starts the transfer.
opened.value.close();
expect(downloadFetches).toBe(0);
// A stream after close is one terminal conflict, still without fetching.
const results = [];
for await (const chunk of opened.value.stream(signal)) {
results.push(chunk);
}
expect(results).toMatchObject([
{ ok: false, error: { code: "CONFLICT" } },
]);
expect(downloadFetches).toBe(0);
});
it.each([
{
name: "truncation",
body: new Uint8Array([1, 2]),
expectedCode: "INTEGRITY_FAILED",
},
{
name: "overrun",
body: new Uint8Array([1, 2, 3, 4]),
expectedCode: "INTEGRITY_FAILED",
},
])("closes $name as a terminal stream failure", async ({ body, expectedCode }) => {
const declared = new Uint8Array([1, 2, 3]);
const payload = downloadCapabilityPayload(declared);
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: downloadResponse(body.slice().buffer, payload),
) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const issued = await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
const opened = await executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: new AbortController().signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
const results = await collect(opened.value);
expect(results.at(-1)).toMatchObject({
ok: false,
error: { code: expectedCode },
});
const firstFailure = results.findIndex((result) => !result.ok);
expect(results.slice(firstFailure + 1)).toEqual([]);
});
it("closes native body errors without throwing across the port", async () => {
const bytes = new Uint8Array([1, 2, 3]);
const payload = downloadCapabilityPayload(bytes);
const failingBody = new ReadableStream<Uint8Array>({
pull(controller) {
controller.error(new DOMException("secret native detail", "NetworkError"));
},
});
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: downloadResponse(failingBody, payload),
) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const issued = await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
const opened = await executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: new AbortController().signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
await expect(collect(opened.value)).resolves.toMatchObject([
{
ok: false,
error: {
code: "NOT_READABLE",
recovery: "REISSUE_CAPABILITY",
},
},
]);
});
it("closes active abort and timeout without leaking native rejection", async () => {
const bytes = new Uint8Array([1]);
const payload = downloadCapabilityPayload(bytes);
const neverBody = () =>
new ReadableStream<Uint8Array>({ pull() {} });
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: downloadResponse(neverBody(), payload),
) as unknown as typeof fetch;
const controller = new AbortController();
let harness = createHarness({ fetcher });
let issued = await harness.provider.issueDownload({
resourceId: "resource-1",
signal: controller.signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
let opened = await harness.executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: controller.signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
const aborted = collect(opened.value, controller.signal);
controller.abort("user");
expect(await aborted).toMatchObject([
{ ok: false, error: { code: "ABORTED" } },
]);
let timeoutCallback: (() => void) | undefined;
const scheduler = {
setTimeout(callback: () => void) {
timeoutCallback = callback;
return 1;
},
clearTimeout() {},
};
harness = createHarness({ fetcher, scheduler });
issued = await harness.provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
opened = await harness.executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: new AbortController().signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
const timedOut = collect(opened.value);
timeoutCallback?.();
expect(await timedOut).toMatchObject([
{
ok: false,
error: {
code: "UNAVAILABLE",
recovery: "REISSUE_CAPABILITY",
},
},
]);
});
it("rejects an expired capability before data-plane fetch", async () => {
const bytes = new Uint8Array([1]);
const payload = downloadCapabilityPayload(bytes);
let current = NOW;
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: downloadResponse(bytes.slice().buffer, payload),
) as unknown as typeof fetch;
const { provider, executor } = createHarness({
fetcher,
now: () => current,
});
const issued = await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
current = Number(payload.expiresAtEpochMs) + 1;
expect(
await executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: new AbortController().signal,
}),
).toMatchObject({
ok: false,
error: {
code: "EXPIRED_RESOURCE",
recovery: "REISSUE_CAPABILITY",
},
});
expect(fetcher).toHaveBeenCalledTimes(1);
});
it("rejects capabilities below the configured minimum remaining lifetime", async () => {
const bytes = new Uint8Array([1]);
const nearExpiryPayload = downloadCapabilityPayload(bytes, {
expiresAtEpochMs: NOW + 999,
});
let fetcher = vi.fn(async () =>
jsonResponse(nearExpiryPayload),
) as unknown as typeof fetch;
let harness = createHarness({ fetcher });
expect(
await harness.provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
}),
).toMatchObject({
ok: false,
error: {
code: "EXPIRED_RESOURCE",
recovery: "REISSUE_CAPABILITY",
},
});
const acceptedPayload = downloadCapabilityPayload(bytes, {
expiresAtEpochMs: NOW + 2_000,
});
let current = NOW;
fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(acceptedPayload)
: downloadResponse(bytes.slice().buffer, acceptedPayload),
) as unknown as typeof fetch;
harness = createHarness({
fetcher,
now: () => current,
});
const issued = await harness.provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
current = NOW + 1_001;
expect(
await harness.executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: new AbortController().signal,
}),
).toMatchObject({
ok: false,
error: {
code: "EXPIRED_RESOURCE",
recovery: "REISSUE_CAPABILITY",
},
});
expect(fetcher).toHaveBeenCalledTimes(1);
});
it("closes malformed AbortSignal inputs at every public boundary", async () => {
const bytes = new Uint8Array([1, 2]);
const payload = downloadCapabilityPayload(bytes);
const uploadChecksum = sha256Hex(bytes);
const uploadPayload = uploadCapabilityPayload({
bytes,
checksum: uploadChecksum,
});
const fetcher = vi.fn(
async (input: RequestInfo | URL, init?: RequestInit) => {
if (String(input) === CONTROL_ENDPOINT) {
const request = JSON.parse(String(init?.body)) as {
method: string;
};
return jsonResponse(
request.method === "GET" ? payload : uploadPayload,
);
}
if (String(input) === DOWNLOAD_HREF) {
return downloadResponse(bytes.slice().buffer, payload);
}
return responseWithUrl(
new Response(null, {
status: 200,
headers: {
[POLICY_HEADER]: "v1",
"Content-Length": "0",
ETag: "\"part-etag-1\"",
},
}),
String(uploadPayload.href),
);
},
) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const malformed = {} as AbortSignal;
expect(
await provider.issueDownload({
resourceId: "resource-1",
signal: malformed,
}),
).toMatchObject({
ok: false,
error: { code: "INVALID_INPUT" },
});
expect(
await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: uploadChecksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: malformed,
}),
).toMatchObject({
ok: false,
error: { code: "INVALID_INPUT" },
});
const issuedDownload = await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issuedDownload.ok).toBe(true);
if (!issuedDownload.ok) return;
expect(
await executor.downloadSources.open({
resourceId: "resource-1",
capability: issuedDownload.value,
signal: malformed,
}),
).toMatchObject({
ok: false,
error: { code: "INVALID_INPUT" },
});
const opened = await executor.downloadSources.open({
resourceId: "resource-1",
capability: issuedDownload.value,
signal: new AbortController().signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
expect(await collect(opened.value, malformed)).toMatchObject([
{ ok: false, error: { code: "INVALID_INPUT" } },
]);
expect(await collect(opened.value)).toMatchObject([
{ ok: false, error: { code: "CONFLICT" } },
]);
const issuedUpload = await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: uploadChecksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
expect(issuedUpload.ok).toBe(true);
if (!issuedUpload.ok) return;
expect(
await executor.uploadParts.put({
capability: issuedUpload.value,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: uploadChecksum,
idempotencyKey: "part-attempt-1",
bytes,
signal: malformed,
}),
).toMatchObject({
ok: false,
error: { code: "INVALID_INPUT" },
});
});
});
+247
View File
@@ -0,0 +1,247 @@
import { PRESIGNED_TRANSFER_PROTOCOL } from "../../src/application/ports/browser-transfer/presigned-transfer.ts";
import type {
PresignedDownloadByteSource,
} from "../../src/application/ports/browser-transfer/presigned-transfer.ts";
import { RESUMABLE_UPLOAD_PROTOCOL } from "../../src/application/ports/browser-transfer/resumable-upload.ts";
import type { BrowserDataObservation } from "../../src/application/ports/browser-file-storage/shared.ts";
import {
createPresignedCapabilityVault,
createSingleUsePresignedReplayGuard,
} from "../../src/adapters/browser-transfer/presigned/presigned-capability-vault.ts";
import { createPresignedCapabilityHttpProvider } from "../../src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts";
import {
createPresignedTransferExecutor,
type PresignedTransferExecutorOptions,
} from "../../src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts";
import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts";
export const NOW = 1_000_000;
export const CONTROL_ENDPOINT = "https://api.example/capabilities";
export const DATA_ORIGIN = "https://objects.example";
export const DOWNLOAD_PATH = "/files/resource-1";
export const DOWNLOAD_HREF =
`${DATA_ORIGIN}${DOWNLOAD_PATH}?sig=do-not-log-this`;
export const POLICY_HEADER = "x-policy-version";
export const DIGEST_HEADER = "x-content-sha256";
export const CHECKSUM_HEADER = "x-checksum-sha256";
export const UPLOAD_SESSION_ID = "upload-session-1";
export const REQUEST_BINDING_SHA256 = "c".repeat(64);
export function downloadCapabilityPayload(
bytes: Uint8Array,
overrides: Readonly<Record<string, unknown>> = {},
) {
const digest = sha256Hex(bytes);
return {
protocol: PRESIGNED_TRANSFER_PROTOCOL,
capabilityReceipt: "capability-download-1",
method: "GET",
binding: {
kind: "DOWNLOAD",
resourceId: "resource-1",
},
href: DOWNLOAD_HREF,
origin: DATA_ORIGIN,
path: DOWNLOAD_PATH,
allowedQueryParameters: ["sig"],
requestHeaders: [
{ name: "accept", value: "application/octet-stream" },
],
requiredResponseHeaders: [
{ name: POLICY_HEADER, value: "v1" },
],
digestRequestHeader: null,
digestResponseHeader: DIGEST_HEADER,
receiptResponseHeader: null,
expectedStatus: 200,
expectedResponseByteLength: null,
mediaType: "application/octet-stream",
byteLength: bytes.byteLength,
maxBytes: 64,
expectedSha256: digest,
expiresAtEpochMs: NOW + 30_000,
singleUse: true,
...overrides,
};
}
export type CapabilityPayload = ReturnType<typeof downloadCapabilityPayload>;
export function uploadCapabilityPayload(input: Readonly<{
bytes: Uint8Array;
checksum: string;
}>, overrides: Readonly<Record<string, unknown>> = {}) {
return {
protocol: PRESIGNED_TRANSFER_PROTOCOL,
capabilityReceipt: "capability-upload-1",
method: "PUT",
binding: {
kind: "UPLOAD_PART",
protocol: RESUMABLE_UPLOAD_PROTOCOL,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
idempotencyKey: "part-attempt-1",
},
href: `${DATA_ORIGIN}/uploads/session-1/part-1?sig=secret`,
origin: DATA_ORIGIN,
path: "/uploads/session-1/part-1",
allowedQueryParameters: ["sig"],
requestHeaders: [
{ name: "content-type", value: "application/octet-stream" },
{ name: CHECKSUM_HEADER, value: input.checksum },
],
requiredResponseHeaders: [
{ name: POLICY_HEADER, value: "v1" },
],
digestRequestHeader: CHECKSUM_HEADER,
digestResponseHeader: null,
receiptResponseHeader: "etag",
expectedStatus: 200,
expectedResponseByteLength: 0,
mediaType: "application/octet-stream",
byteLength: input.bytes.byteLength,
maxBytes: 64,
expectedSha256: input.checksum,
expiresAtEpochMs: NOW + 30_000,
singleUse: true,
...overrides,
};
}
export function jsonResponse(
value: unknown,
url = CONTROL_ENDPOINT,
): Response {
return responseWithUrl(
new Response(JSON.stringify(value), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
url,
);
}
export function downloadResponse(
body: BodyInit | null,
payload: CapabilityPayload,
headers: Record<string, string> = {},
): Response {
return responseWithUrl(
new Response(body, {
status: payload.expectedStatus as number,
headers: {
"Content-Type": String(payload.mediaType),
"Content-Length": String(payload.byteLength),
[DIGEST_HEADER]: String(payload.expectedSha256),
[POLICY_HEADER]: "v1",
...headers,
},
}),
String(payload.href),
);
}
export function responseWithUrl(response: Response, href: string): Response {
Object.defineProperty(response, "url", {
configurable: true,
value: href,
});
return response;
}
export function createHarness(input: Readonly<{
fetcher: typeof fetch;
maxActiveCapabilities?: number;
now?: () => number;
digestBytes?: PresignedTransferExecutorOptions["digestBytes"];
scheduler?: PresignedTransferExecutorOptions["scheduler"];
observer?: Readonly<{
record(observation: BrowserDataObservation): void;
}>;
}>) {
const now = input.now ?? (() => NOW);
const vault = createPresignedCapabilityVault({
maxActiveCapabilities: input.maxActiveCapabilities ?? 16,
now,
});
const replayGuard = createSingleUsePresignedReplayGuard();
const provider = createPresignedCapabilityHttpProvider({
endpoint: CONTROL_ENDPOINT,
vault,
allowedDataOrigins: [DATA_ORIGIN],
allowedDataPathPrefixes: ["/files/", "/uploads/"],
allowedQueryParameters: ["sig"],
allowedRequestHeaders: [
"accept",
"content-type",
CHECKSUM_HEADER,
],
allowedResponseHeaders: [
POLICY_HEADER,
DIGEST_HEADER,
"etag",
],
hardMaxTransferBytes: 64,
hardMaxUploadResponseBytes: 16,
maxCapabilityTtlMs: 60_000,
minimumRemainingLifetimeMs: 1_000,
timeoutMs: 5_000,
fetcher: input.fetcher,
now,
scheduler: input.scheduler,
observer: input.observer,
});
const executor = createPresignedTransferExecutor({
vault,
replayGuard,
hardMaxTransferBytes: 64,
hardMaxChunkBytes: 2,
hardMaxUploadResponseBytes: 16,
minimumRemainingLifetimeMs: 1_000,
timeoutMs: 5_000,
fetcher: input.fetcher,
now,
scheduler: input.scheduler,
digestBytes: input.digestBytes,
observer: input.observer,
});
return { provider, executor, vault };
}
export async function collect(
source: PresignedDownloadByteSource,
signal = new AbortController().signal,
) {
const results = [];
for await (const result of source.stream(signal)) {
results.push(result);
}
return results;
}
/**
* BT-PRE-01. The download lease is lazy, so a response-shape rejection is
* observed on first consumption rather than at open().
*/
export async function firstStreamResult(
opened: Awaited<
ReturnType<
ReturnType<typeof createHarness>["executor"]["downloadSources"]["open"]
>
>,
): Promise<unknown> {
if (!opened.ok) return opened;
try {
for await (const chunk of opened.value.stream(
new AbortController().signal,
)) {
if (!chunk.ok) return chunk;
}
return { ok: true };
} finally {
opened.value.close();
}
}
@@ -0,0 +1,549 @@
import { describe, expect, it, vi } from "vitest";
import type { BrowserDataObservation } from "../../src/application/ports/browser-file-storage/shared.ts";
import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts";
import {
CHECKSUM_HEADER,
CONTROL_ENDPOINT,
DATA_ORIGIN,
DIGEST_HEADER,
DOWNLOAD_HREF,
DOWNLOAD_PATH,
NOW,
POLICY_HEADER,
REQUEST_BINDING_SHA256,
UPLOAD_SESSION_ID,
collect,
createHarness,
downloadCapabilityPayload,
downloadResponse,
jsonResponse,
responseWithUrl,
uploadCapabilityPayload,
} from "./presigned-transfer-fixture.ts";
describe("presigned upload part execution", () => {
it("snapshots, verifies and uploads a PUT part with a separate response receipt", async () => {
const original = new Uint8Array([9, 8, 7]);
const checksum = sha256Hex(original);
const payload = uploadCapabilityPayload({
bytes: original,
checksum,
});
let releaseDigest: (() => void) | undefined;
const digestGate = new Promise<void>((resolve) => {
releaseDigest = resolve;
});
const sentBodies: number[][] = [];
const dataCalls: RequestInit[] = [];
const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
if (String(input) === CONTROL_ENDPOINT) return jsonResponse(payload);
dataCalls.push(init ?? {});
sentBodies.push([
...new Uint8Array(init?.body as ArrayBuffer),
]);
return responseWithUrl(
new Response(null, {
status: 200,
headers: {
[POLICY_HEADER]: "v1",
"Content-Length": "0",
ETag: "\"part-etag-1\"",
},
}),
String(payload.href),
);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({
fetcher,
digestBytes: async (bytes) => {
await digestGate;
return sha256Hex(bytes);
},
});
const issued = await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: original.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
const request = {
capability: issued.value,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: original.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes: original,
signal: new AbortController().signal,
};
const pending = executor.uploadParts.put(request);
original.fill(0);
request.sessionId = "mutated-session";
request.requestBindingSha256 = "d".repeat(64);
request.checksumSha256 = "f".repeat(64);
releaseDigest?.();
expect(await pending).toEqual({
ok: true,
value: {
bytesWritten: 3,
checksumSha256: checksum,
receiptToken: "part-etag-1",
},
});
expect(sentBodies).toEqual([[9, 8, 7]]);
expect(dataCalls[0]).toMatchObject({
method: "PUT",
credentials: "omit",
redirect: "error",
referrerPolicy: "no-referrer",
});
expect(
(dataCalls[0]?.headers as Headers).get(CHECKSUM_HEADER),
).toBe(checksum);
});
it.each(["sessionId", "requestBindingSha256"] as const)(
"rejects an actual PUT whose %s differs from the capability",
async (field) => {
const bytes = new Uint8Array([3, 2, 1]);
const checksum = sha256Hex(bytes);
const payload = uploadCapabilityPayload({ bytes, checksum });
const fetcher = vi.fn(async () =>
jsonResponse(payload),
) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const issued = await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
expect(
await executor.uploadParts.put({
capability: issued.value,
sessionId:
field === "sessionId"
? "different-session"
: UPLOAD_SESSION_ID,
requestBindingSha256:
field === "requestBindingSha256"
? "d".repeat(64)
: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes,
signal: new AbortController().signal,
}),
).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
expect(fetcher).toHaveBeenCalledTimes(1);
},
);
it("rejects URL-shaped upload receipts", async () => {
const bytes = new Uint8Array([4, 5, 6]);
const checksum = sha256Hex(bytes);
const payload = uploadCapabilityPayload({ bytes, checksum });
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) === CONTROL_ENDPOINT) {
return jsonResponse(payload);
}
return responseWithUrl(
new Response(null, {
status: 200,
headers: {
[POLICY_HEADER]: "v1",
"Content-Length": "0",
ETag: "\"https://objects.example/authorizing-token\"",
},
}),
String(payload.href),
);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const issued = await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
expect(
await executor.uploadParts.put({
capability: issued.value,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes,
signal: new AbortController().signal,
}),
).toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED" },
});
});
it("drains a bounded successful PUT acknowledgement without cancelling it", async () => {
const bytes = new Uint8Array([4, 5, 6]);
const checksum = sha256Hex(bytes);
const payload = uploadCapabilityPayload(
{ bytes, checksum },
{ expectedResponseByteLength: 2 },
);
let cancelled = false;
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) === CONTROL_ENDPOINT) {
return jsonResponse(payload);
}
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array([8, 9]));
controller.close();
},
cancel() {
cancelled = true;
},
});
return responseWithUrl(
new Response(body, {
status: 200,
headers: {
[POLICY_HEADER]: "v1",
"Content-Length": "2",
ETag: "\"part-etag-1\"",
},
}),
String(payload.href),
);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const issued = await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
expect(
await executor.uploadParts.put({
capability: issued.value,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes,
signal: new AbortController().signal,
}),
).toMatchObject({
ok: true,
value: { receiptToken: "part-etag-1" },
});
expect(cancelled).toBe(false);
});
it("accepts an empty 204 PUT acknowledgement", async () => {
const bytes = new Uint8Array([4, 5, 6]);
const checksum = sha256Hex(bytes);
const payload = uploadCapabilityPayload(
{ bytes, checksum },
{
expectedStatus: 204,
expectedResponseByteLength: 0,
},
);
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: responseWithUrl(
new Response(null, {
status: 204,
headers: {
[POLICY_HEADER]: "v1",
ETag: "\"part-etag-204\"",
},
}),
String(payload.href),
),
) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const issued = await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
expect(
await executor.uploadParts.put({
capability: issued.value,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes,
signal: new AbortController().signal,
}),
).toMatchObject({
ok: true,
value: { receiptToken: "part-etag-204" },
});
});
it("cancels a PUT acknowledgement whose declared length violates its binding", async () => {
const bytes = new Uint8Array([4, 5, 6]);
const checksum = sha256Hex(bytes);
const payload = uploadCapabilityPayload({ bytes, checksum });
let cancelled = false;
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
if (String(input) === CONTROL_ENDPOINT) {
return jsonResponse(payload);
}
const body = new ReadableStream<Uint8Array>({
pull() {},
cancel() {
cancelled = true;
},
});
return responseWithUrl(
new Response(body, {
status: 200,
headers: {
[POLICY_HEADER]: "v1",
"Content-Length": "1",
ETag: "\"part-etag-1\"",
},
}),
String(payload.href),
);
}) as unknown as typeof fetch;
const { provider, executor } = createHarness({ fetcher });
const issued = await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
expect(
await executor.uploadParts.put({
capability: issued.value,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes,
signal: new AbortController().signal,
}),
).toMatchObject({
ok: false,
error: { code: "POLICY_REJECTED" },
});
expect(cancelled).toBe(true);
});
it("observes only safe operation, outcome, failure and byte buckets", async () => {
const bytes = new Uint8Array([7, 8, 9]);
const downloadPayload = downloadCapabilityPayload(bytes);
const checksum = sha256Hex(bytes);
const uploadPayload = uploadCapabilityPayload({ bytes, checksum });
const observations: BrowserDataObservation[] = [];
const fetcher = vi.fn(
async (input: RequestInfo | URL, init?: RequestInit) => {
if (String(input) === CONTROL_ENDPOINT) {
const request = JSON.parse(String(init?.body)) as {
method: string;
};
return jsonResponse(
request.method === "GET"
? downloadPayload
: uploadPayload,
);
}
if (String(input) === DOWNLOAD_HREF) {
return downloadResponse(
bytes.slice().buffer,
downloadPayload,
);
}
return responseWithUrl(
new Response(null, {
status: 200,
headers: {
[POLICY_HEADER]: "v1",
"Content-Length": "0",
ETag: "\"part-etag-secret\"",
},
}),
String(uploadPayload.href),
);
},
) as unknown as typeof fetch;
const { provider, executor } = createHarness({
fetcher,
observer: {
record(observation) {
observations.push(observation);
},
},
});
const issuedDownload = await provider.issueDownload({
resourceId: "resource-1",
signal: new AbortController().signal,
});
expect(issuedDownload.ok).toBe(true);
if (!issuedDownload.ok) return;
const opened = await executor.downloadSources.open({
resourceId: "resource-1",
capability: issuedDownload.value,
signal: new AbortController().signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
expect((await collect(opened.value)).every((result) => result.ok)).toBe(
true,
);
const issuedUpload = await provider.issueUploadPart({
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
mediaType: "application/octet-stream",
idempotencyKey: "part-attempt-1",
signal: new AbortController().signal,
});
expect(issuedUpload.ok).toBe(true);
if (!issuedUpload.ok) return;
expect(
await executor.uploadParts.put({
capability: issuedUpload.value,
sessionId: UPLOAD_SESSION_ID,
requestBindingSha256: REQUEST_BINDING_SHA256,
uploadBindingSha256: "b".repeat(64),
partNumber: 1,
offset: 0,
byteLength: bytes.byteLength,
checksumSha256: checksum,
idempotencyKey: "part-attempt-1",
bytes,
signal: new AbortController().signal,
}),
).toMatchObject({ ok: true });
expect(observations).toEqual([
{
operation: "PRESIGNED_TRANSFER",
outcome: "SUCCEEDED",
byteBucket: "LT1MIB",
},
{
operation: "PRESIGNED_TRANSFER",
outcome: "SUCCEEDED",
byteBucket: "LT1MIB",
},
{
operation: "DOWNLOAD",
outcome: "SUCCEEDED",
byteBucket: "LT1MIB",
},
{
operation: "PRESIGNED_TRANSFER",
outcome: "SUCCEEDED",
byteBucket: "LT1MIB",
},
{
operation: "UPLOAD_PART",
outcome: "SUCCEEDED",
byteBucket: "LT1MIB",
},
]);
const serialized = JSON.stringify(observations);
for (const secret of [
DOWNLOAD_HREF,
"do-not-log-this",
checksum,
"capability-download-1",
"capability-upload-1",
"part-etag-secret",
"resource-1",
]) {
expect(serialized).not.toContain(secret);
}
});
});
File diff suppressed because it is too large Load Diff
+20 -16
View File
@@ -17,7 +17,7 @@ import {
} from "../../src/features/installed-feature-contracts.ts";
const COMPILED = Object.freeze([
Object.freeze({ featureId: "reference-feature" }),
Object.freeze({ featureId: "alpha-feature" }),
Object.freeze({ featureId: "billing" }),
]);
@@ -27,7 +27,7 @@ describe("build-time product selection", () => {
expect(
selectCompiledProductFeatures(COMPILED, declared).map((f) => f.featureId),
String(declared),
).toEqual(["reference-feature", "billing"]);
).toEqual(["alpha-feature", "billing"]);
}
});
@@ -36,10 +36,10 @@ describe("build-time product selection", () => {
selectCompiledProductFeatures(COMPILED, "billing").map((f) => f.featureId),
).toEqual(["billing"]);
expect(
selectCompiledProductFeatures(COMPILED, " billing , reference-feature ").map(
selectCompiledProductFeatures(COMPILED, " billing , alpha-feature ").map(
(f) => f.featureId,
),
).toEqual(["reference-feature", "billing"]);
).toEqual(["alpha-feature", "billing"]);
});
it("selects nothing only when asked explicitly", () => {
@@ -80,13 +80,13 @@ describe("build-time product selection", () => {
describe("runtime product feature resolution", () => {
it("reports active, disabled and not-installed distinctly", () => {
const statuses = resolveProductFeatures(
["reference-feature", "billing"],
["reference-feature"],
{ "reference-feature": "DISABLED" },
["alpha-feature", "billing"],
["alpha-feature"],
{ "alpha-feature": "DISABLED" },
);
expect(statuses).toEqual([
{ featureId: "alpha-feature", state: "DISABLED_BY_CONFIG" },
{ featureId: "billing", state: "NOT_INSTALLED" },
{ featureId: "reference-feature", state: "DISABLED_BY_CONFIG" },
]);
expect(activeProductFeatureIds(statuses)).toEqual([]);
});
@@ -104,11 +104,11 @@ describe("runtime product feature resolution", () => {
// A shared runtime document may cover several builds, so a stale key is
// inert rather than fatal.
const statuses = resolveProductFeatures(
["reference-feature"],
["reference-feature"],
["alpha-feature"],
["alpha-feature"],
{ analytics: "DISABLED" },
);
expect(activeProductFeatureIds(statuses)).toEqual(["reference-feature"]);
expect(activeProductFeatureIds(statuses)).toEqual(["alpha-feature"]);
});
it("leaves an installed feature active without an override", () => {
@@ -141,15 +141,15 @@ describe("runtime config carries the switch", () => {
expect(
runtimeConfigV2ArtifactSchema.parse({
...base,
FEATURE_OVERRIDES: { "reference-feature": "DISABLED" },
FEATURE_OVERRIDES: { "alpha-feature": "DISABLED" },
}).FEATURE_OVERRIDES,
).toEqual({ "reference-feature": "DISABLED" });
).toEqual({ "alpha-feature": "DISABLED" });
// There is no "ENABLED": the vocabulary itself is what makes the rule
// unbreakable, not a check somewhere downstream.
expect(
runtimeConfigV2ArtifactSchema.safeParse({
...base,
FEATURE_OVERRIDES: { "reference-feature": "ENABLED" },
FEATURE_OVERRIDES: { "alpha-feature": "ENABLED" },
}).success,
).toBe(false);
});
@@ -233,12 +233,16 @@ describe("route ownership", () => {
expect(ROUTE_FEATURE_OWNER["NOT_FOUND"]).toBeUndefined();
});
it("owns exactly the routes the registry received from features", () => {
it("owns exactly routes that exist in the composed registry", () => {
// Template merge. `owned` is empty in this product: the only installed
// feature's screens were removed by the UI migration. The invariant still
// holds and starts asserting again the moment a feature route returns.
for (const routeId of Object.keys(ROUTE_FEATURE_OWNER)) {
const owned = Object.keys(ROUTE_FEATURE_OWNER);
for (const routeId of owned) {
expect(Object.keys(ROUTE_REGISTRY), routeId).toContain(routeId);
}
expect(
owned.every((routeId) => ROUTE_FEATURE_OWNER[routeId] !== undefined),
).toBe(true);
});
});
File diff suppressed because it is too large Load Diff
+137
View File
@@ -0,0 +1,137 @@
import type {
PublicCacheAsset,
PublicCacheReleaseManifest,
} from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts";
import {
createDefaultPublicCachePolicy,
type PublicCacheRuntimePolicy,
} from "../../src/adapters/cache-storage/public-cache-policy.ts";
import {
computePublicCacheManifestDigestHex,
type PublicCacheMutationLock,
} from "../../src/adapters/cache-storage/public-response-cache-adapter.ts";
export class MemoryCache {
readonly responses: Array<Readonly<{
request: Request;
response: Response;
}>> = [];
async match(request: RequestInfo | URL): Promise<Response | undefined> {
const url =
request instanceof Request ? request.url : new URL(String(request)).href;
const nativeRequest =
request instanceof Request ? request : new Request(url);
return this.responses
.find(
(entry) =>
entry.request.url === url &&
varyMatches(entry.request, nativeRequest, entry.response),
)
?.response.clone();
}
async put(request: RequestInfo | URL, response: Response): Promise<void> {
const url =
request instanceof Request ? request.url : new URL(String(request)).href;
const nativeRequest =
request instanceof Request ? request.clone() : new Request(url);
const existing = this.responses.findIndex(
(entry) =>
entry.request.url === url &&
varyMatches(entry.request, nativeRequest, response),
);
const entry = {
request: nativeRequest,
response: response.clone(),
};
if (existing >= 0) this.responses.splice(existing, 1, entry);
else this.responses.push(entry);
}
}
function varyMatches(
storedRequest: Request,
incomingRequest: Request,
response: Response,
): boolean {
const vary = response.headers.get("vary");
if (!vary) return true;
return vary
.split(",")
.map((name) => name.trim().toLowerCase())
.every(
(name) =>
storedRequest.headers.get(name) ===
incomingRequest.headers.get(name),
);
}
export class MemoryCacheStorage {
readonly caches = new Map<string, MemoryCache>();
async open(name: string): Promise<Cache> {
let cache = this.caches.get(name);
if (!cache) {
cache = new MemoryCache();
this.caches.set(name, cache);
}
return cache as unknown as Cache;
}
async keys(): Promise<string[]> {
return [...this.caches.keys()];
}
async delete(name: string): Promise<boolean> {
return this.caches.delete(name);
}
}
export const immediateLock: PublicCacheMutationLock = {
async run(_signal, task) {
return await task();
},
};
export function deferred<Value>() {
let settle: ((value: Value) => void) | undefined;
const promise = new Promise<Value>((resolve) => {
settle = resolve;
});
return Object.freeze({
promise,
resolve(value: Value): void {
settle?.(value);
},
});
}
export async function digestHex(bytes: Uint8Array): Promise<string> {
const digest = await globalThis.crypto.subtle.digest(
"SHA-256",
Uint8Array.from(bytes),
);
return [...new Uint8Array(digest)]
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
export async function manifestFor(
releaseRegistryId: string,
assets: readonly PublicCacheAsset[],
policy: PublicCacheRuntimePolicy = createDefaultPublicCachePolicy(
"https://assets.example.test",
),
): Promise<PublicCacheReleaseManifest> {
return {
releaseRegistryId,
assets,
manifestDigestHex: await computePublicCacheManifestDigestHex(
globalThis.crypto,
releaseRegistryId,
assets,
policy,
),
};
}
@@ -0,0 +1,207 @@
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";
/**
* STO-RR-04 / STO-RR-05. A release cache that is currently serving traffic is
* the last thing a repair may destroy. A transient marker read failure is not
* evidence of damage, and a repair that has not yet fetched anything has not
* yet earned the right to delete what still works.
*/
describe("public response cache repair is failure-atomic", () => {
async function stagedRelease(releaseRegistryId: string) {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
const firstBytes = new Uint8Array([1, 1, 1, 1]);
const secondBytes = new Uint8Array([2, 2, 2, 2]);
const assets: readonly PublicCacheAsset[] = [
{
absoluteUrl: "https://assets.example.test/first.js",
expectedByteLength: firstBytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(firstBytes),
},
},
{
absoluteUrl: "https://assets.example.test/second.js",
expectedByteLength: secondBytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(secondBytes),
},
},
];
const bodies = new Map<string, Uint8Array>([
[assets[0]!.absoluteUrl, firstBytes],
[assets[1]!.absoluteUrl, secondBytes],
]);
const cacheStorage = new MemoryCacheStorage();
const fetchLog: string[] = [];
let failFrom: string | null = null;
const adapter = createPublicResponseCacheAdapter({
cacheStorage: cacheStorage as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
fetcher: async (request: Request) => {
fetchLog.push(request.url);
if (failFrom !== null && request.url === failFrom) {
throw new TypeError("network is down");
}
const body = bodies.get(request.url);
if (!body) throw new TypeError(`unknown asset ${request.url}`);
return new Response(Uint8Array.from(body), {
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
});
},
});
const manifest = await manifestFor(releaseRegistryId, assets, policy);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
),
).toMatchObject({ ok: true });
const cacheName = [...cacheStorage.caches.keys()].find((name) =>
name.includes(releaseRegistryId),
);
if (!cacheName) throw new Error("staged cache missing");
return {
adapter,
assets,
cacheName,
cacheStorage,
fetchLog,
manifest,
setFailure(url: string | null) {
failFrom = url;
},
};
}
it("does not delete an active candidate when the marker read fails transiently", async () => {
const release = await stagedRelease("transient-marker");
const cache = release.cacheStorage.caches.get(release.cacheName)!;
const realMatch = cache.match.bind(cache);
let markerReads = 0;
const assetUrls = new Set(release.assets.map((asset) => asset.absoluteUrl));
cache.match = async (request: RequestInfo | URL) => {
const url =
request instanceof Request ? request.url : String(request);
if (!assetUrls.has(url)) {
markerReads += 1;
throw new DOMException("Storage is busy", "InvalidStateError");
}
return await realMatch(request);
};
const restaged = await release.adapter.admin.stageRelease(release.manifest);
expect(markerReads).toBeGreaterThan(0);
expect(restaged.ok).toBe(false);
expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true);
cache.match = realMatch;
expect(
await release.adapter.responses.matchActiveExact({
absoluteUrl: release.assets[0]!.absoluteUrl,
}),
).toMatchObject({ ok: true });
});
it("keeps every healthy asset when one repair fetch fails", async () => {
const release = await stagedRelease("partial-repair");
const cache = release.cacheStorage.caches.get(release.cacheName)!;
// Corrupt only the first asset's stored bytes.
const corrupted = cache.responses.findIndex(
(entry) => entry.request.url === release.assets[0]!.absoluteUrl,
);
expect(corrupted).toBeGreaterThanOrEqual(0);
cache.responses.splice(corrupted, 1);
release.setFailure(release.assets[0]!.absoluteUrl);
const restaged = await release.adapter.admin.stageRelease(release.manifest);
expect(restaged.ok).toBe(false);
// The cache still exists and the healthy asset is still served.
expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true);
expect(
await release.adapter.responses.matchActiveExact({
absoluteUrl: release.assets[1]!.absoluteUrl,
}),
).toMatchObject({ ok: true });
});
it("still removes a candidate this call created when staging fails", async () => {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
const bytes = new Uint8Array([7, 7, 7, 7]);
const asset: PublicCacheAsset = {
absoluteUrl: "https://assets.example.test/fresh.js",
expectedByteLength: bytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(bytes),
},
};
const cacheStorage = new MemoryCacheStorage();
const adapter = createPublicResponseCacheAdapter({
cacheStorage: cacheStorage as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
fetcher: async () => {
throw new TypeError("network is down");
},
});
const manifest = await manifestFor("fresh-release", [asset], policy);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: false,
});
expect(await cacheStorage.keys()).toEqual([]);
});
it("repairs an evicted asset in place and keeps the release usable", async () => {
const release = await stagedRelease("in-place-repair");
const cache = release.cacheStorage.caches.get(release.cacheName)!;
const evicted = cache.responses.findIndex(
(entry) => entry.request.url === release.assets[1]!.absoluteUrl,
);
cache.responses.splice(evicted, 1);
expect(
await release.adapter.admin.stageRelease(release.manifest),
).toMatchObject({ ok: true });
expect(
await release.adapter.responses.matchActiveExact({
absoluteUrl: release.assets[1]!.absoluteUrl,
}),
).toMatchObject({ ok: true });
expect(
await release.adapter.responses.matchActiveExact({
absoluteUrl: release.assets[0]!.absoluteUrl,
}),
).toMatchObject({ ok: true });
});
});
+7 -321
View File
@@ -10,135 +10,17 @@ import {
type PublicCacheRuntimePolicy,
} from "../../src/adapters/cache-storage/public-cache-policy.ts";
import {
computePublicCacheManifestDigestHex,
createPublicResponseCacheAdapter,
type PublicCacheMutationLock,
} from "../../src/adapters/cache-storage/public-response-cache-adapter.ts";
class MemoryCache {
readonly responses: Array<Readonly<{
request: Request;
response: Response;
}>> = [];
async match(request: RequestInfo | URL): Promise<Response | undefined> {
const url =
request instanceof Request ? request.url : new URL(String(request)).href;
const nativeRequest =
request instanceof Request ? request : new Request(url);
return this.responses
.find(
(entry) =>
entry.request.url === url &&
varyMatches(entry.request, nativeRequest, entry.response),
)
?.response.clone();
}
async put(request: RequestInfo | URL, response: Response): Promise<void> {
const url =
request instanceof Request ? request.url : new URL(String(request)).href;
const nativeRequest =
request instanceof Request ? request.clone() : new Request(url);
const existing = this.responses.findIndex(
(entry) =>
entry.request.url === url &&
varyMatches(entry.request, nativeRequest, response),
);
const entry = {
request: nativeRequest,
response: response.clone(),
};
if (existing >= 0) this.responses.splice(existing, 1, entry);
else this.responses.push(entry);
}
}
function varyMatches(
storedRequest: Request,
incomingRequest: Request,
response: Response,
): boolean {
const vary = response.headers.get("vary");
if (!vary) return true;
return vary
.split(",")
.map((name) => name.trim().toLowerCase())
.every(
(name) =>
storedRequest.headers.get(name) ===
incomingRequest.headers.get(name),
);
}
class MemoryCacheStorage {
readonly caches = new Map<string, MemoryCache>();
async open(name: string): Promise<Cache> {
let cache = this.caches.get(name);
if (!cache) {
cache = new MemoryCache();
this.caches.set(name, cache);
}
return cache as unknown as Cache;
}
async keys(): Promise<string[]> {
return [...this.caches.keys()];
}
async delete(name: string): Promise<boolean> {
return this.caches.delete(name);
}
}
const immediateLock: PublicCacheMutationLock = {
async run(_signal, task) {
return await task();
},
};
function deferred<Value>() {
let settle: ((value: Value) => void) | undefined;
const promise = new Promise<Value>((resolve) => {
settle = resolve;
});
return Object.freeze({
promise,
resolve(value: Value): void {
settle?.(value);
},
});
}
async function digestHex(bytes: Uint8Array): Promise<string> {
const digest = await globalThis.crypto.subtle.digest(
"SHA-256",
Uint8Array.from(bytes),
);
return [...new Uint8Array(digest)]
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
async function manifestFor(
releaseRegistryId: string,
assets: readonly PublicCacheAsset[],
policy: PublicCacheRuntimePolicy = createDefaultPublicCachePolicy(
"https://assets.example.test",
),
): Promise<PublicCacheReleaseManifest> {
return {
releaseRegistryId,
assets,
manifestDigestHex: await computePublicCacheManifestDigestHex(
globalThis.crypto,
releaseRegistryId,
assets,
policy,
),
};
}
import {
MemoryCacheStorage,
deferred,
digestHex,
immediateLock,
manifestFor,
} from "./public-response-cache-fixture.ts";
describe("public response Cache Storage adapter", () => {
it("rejects a policy that enables variants but strips Vary", () => {
@@ -1513,199 +1395,3 @@ describe("public response Cache Storage adapter", () => {
expect(await cacheStorage.keys()).toEqual([]);
});
});
/**
* STO-RR-04 / STO-RR-05. A release cache that is currently serving traffic is
* the last thing a repair may destroy. A transient marker read failure is not
* evidence of damage, and a repair that has not yet fetched anything has not
* yet earned the right to delete what still works.
*/
describe("public response cache repair is failure-atomic", () => {
async function stagedRelease(releaseRegistryId: string) {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
const firstBytes = new Uint8Array([1, 1, 1, 1]);
const secondBytes = new Uint8Array([2, 2, 2, 2]);
const assets: readonly PublicCacheAsset[] = [
{
absoluteUrl: "https://assets.example.test/first.js",
expectedByteLength: firstBytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(firstBytes),
},
},
{
absoluteUrl: "https://assets.example.test/second.js",
expectedByteLength: secondBytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(secondBytes),
},
},
];
const bodies = new Map<string, Uint8Array>([
[assets[0]!.absoluteUrl, firstBytes],
[assets[1]!.absoluteUrl, secondBytes],
]);
const cacheStorage = new MemoryCacheStorage();
const fetchLog: string[] = [];
let failFrom: string | null = null;
const adapter = createPublicResponseCacheAdapter({
cacheStorage: cacheStorage as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
fetcher: async (request: Request) => {
fetchLog.push(request.url);
if (failFrom !== null && request.url === failFrom) {
throw new TypeError("network is down");
}
const body = bodies.get(request.url);
if (!body) throw new TypeError(`unknown asset ${request.url}`);
return new Response(Uint8Array.from(body), {
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
});
},
});
const manifest = await manifestFor(releaseRegistryId, assets, policy);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: true,
});
expect(
await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
),
).toMatchObject({ ok: true });
const cacheName = [...cacheStorage.caches.keys()].find((name) =>
name.includes(releaseRegistryId),
);
if (!cacheName) throw new Error("staged cache missing");
return {
adapter,
assets,
cacheName,
cacheStorage,
fetchLog,
manifest,
setFailure(url: string | null) {
failFrom = url;
},
};
}
it("does not delete an active candidate when the marker read fails transiently", async () => {
const release = await stagedRelease("transient-marker");
const cache = release.cacheStorage.caches.get(release.cacheName)!;
const realMatch = cache.match.bind(cache);
let markerReads = 0;
const assetUrls = new Set(release.assets.map((asset) => asset.absoluteUrl));
cache.match = async (request: RequestInfo | URL) => {
const url =
request instanceof Request ? request.url : String(request);
if (!assetUrls.has(url)) {
markerReads += 1;
throw new DOMException("Storage is busy", "InvalidStateError");
}
return await realMatch(request);
};
const restaged = await release.adapter.admin.stageRelease(release.manifest);
expect(markerReads).toBeGreaterThan(0);
expect(restaged.ok).toBe(false);
expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true);
cache.match = realMatch;
expect(
await release.adapter.responses.matchActiveExact({
absoluteUrl: release.assets[0]!.absoluteUrl,
}),
).toMatchObject({ ok: true });
});
it("keeps every healthy asset when one repair fetch fails", async () => {
const release = await stagedRelease("partial-repair");
const cache = release.cacheStorage.caches.get(release.cacheName)!;
// Corrupt only the first asset's stored bytes.
const corrupted = cache.responses.findIndex(
(entry) => entry.request.url === release.assets[0]!.absoluteUrl,
);
expect(corrupted).toBeGreaterThanOrEqual(0);
cache.responses.splice(corrupted, 1);
release.setFailure(release.assets[0]!.absoluteUrl);
const restaged = await release.adapter.admin.stageRelease(release.manifest);
expect(restaged.ok).toBe(false);
// The cache still exists and the healthy asset is still served.
expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true);
expect(
await release.adapter.responses.matchActiveExact({
absoluteUrl: release.assets[1]!.absoluteUrl,
}),
).toMatchObject({ ok: true });
});
it("still removes a candidate this call created when staging fails", async () => {
const policy = createDefaultPublicCachePolicy(
"https://assets.example.test",
);
const bytes = new Uint8Array([7, 7, 7, 7]);
const asset: PublicCacheAsset = {
absoluteUrl: "https://assets.example.test/fresh.js",
expectedByteLength: bytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256",
digestHex: await digestHex(bytes),
},
};
const cacheStorage = new MemoryCacheStorage();
const adapter = createPublicResponseCacheAdapter({
cacheStorage: cacheStorage as unknown as CacheStorage,
crypto: globalThis.crypto,
mutationLock: immediateLock,
policy,
fetcher: async () => {
throw new TypeError("network is down");
},
});
const manifest = await manifestFor("fresh-release", [asset], policy);
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
ok: false,
});
expect(await cacheStorage.keys()).toEqual([]);
});
it("repairs an evicted asset in place and keeps the release usable", async () => {
const release = await stagedRelease("in-place-repair");
const cache = release.cacheStorage.caches.get(release.cacheName)!;
const evicted = cache.responses.findIndex(
(entry) => entry.request.url === release.assets[1]!.absoluteUrl,
);
cache.responses.splice(evicted, 1);
expect(
await release.adapter.admin.stageRelease(release.manifest),
).toMatchObject({ ok: true });
expect(
await release.adapter.responses.matchActiveExact({
absoluteUrl: release.assets[1]!.absoluteUrl,
}),
).toMatchObject({ ok: true });
expect(
await release.adapter.responses.matchActiveExact({
absoluteUrl: release.assets[0]!.absoluteUrl,
}),
).toMatchObject({ ok: true });
});
});
@@ -80,6 +80,155 @@ function deletingFactory(
} as IDBFactory;
}
/**
* A database the test drives by hand. The memory fake commits or aborts on its
* own, so the three places the checkpoint store deliberately disagrees with the
* other IndexedDB adapters — a commit that produced no value, a request error
* that must abort, and an `abort()` that throws — are only observable here.
*
* The scope-binding transaction is driven automatically because no test below
* is about it; only checkpoint transactions are handed to the test.
*/
type ScriptedRequest = {
result: unknown;
error: DOMException | null;
onsuccess: ((event: Event) => unknown) | null;
onerror: ((event: Event) => unknown) | null;
};
type ScriptedTransaction = {
abortCalls: number;
error: DOMException | null;
oncomplete: ((event: Event) => unknown) | null;
onerror: ((event: Event) => unknown) | null;
onabort: ((event: Event) => unknown) | null;
readonly requests: ScriptedRequest[];
objectStore(name: string): IDBObjectStore;
abort(): void;
complete(): void;
};
function scriptedFactory(
options: Readonly<{ abortThrows?: boolean }> = {},
): Readonly<{
factory: IDBFactory;
/** One entry per `database.transaction(...)` call, holding its argument count. */
transactionArguments: number[];
checkpoints: ScriptedTransaction[];
}> {
const transactionArguments: number[] = [];
const checkpoints: ScriptedTransaction[] = [];
const scriptedRequest = (): ScriptedRequest => ({
result: undefined,
error: null,
onsuccess: null,
onerror: null,
});
const makeTransaction = (): ScriptedTransaction => {
const requests: ScriptedRequest[] = [];
const transaction: ScriptedTransaction = {
abortCalls: 0,
error: null,
oncomplete: null,
onerror: null,
onabort: null,
requests,
objectStore: () => {
const queue = () => {
const request = scriptedRequest();
requests.push(request);
return request as unknown as IDBRequest;
};
return {
get: queue,
add: queue,
put: queue,
delete: queue,
} as unknown as IDBObjectStore;
},
abort() {
transaction.abortCalls += 1;
if (options.abortThrows === true) {
throw new DOMException("Transaction is finished.", "InvalidStateError");
}
transaction.error = new DOMException("Transaction aborted.", "AbortError");
transaction.onerror?.(new Event("error"));
transaction.onabort?.(new Event("abort"));
},
complete() {
transaction.oncomplete?.(new Event("complete"));
},
};
return transaction;
};
const database = {
close() {},
transaction: (...args: unknown[]) => {
transactionArguments.push(args.length);
const requested = args[0];
const names =
typeof requested === "string"
? [requested]
: [...(requested as Iterable<string>)];
const transaction = makeTransaction();
if (names.includes("governance")) {
queueMicrotask(() => {
transaction.requests[0]?.onsuccess?.(new Event("success"));
queueMicrotask(() => {
transaction.requests[1]?.onsuccess?.(new Event("success"));
queueMicrotask(() => {
transaction.complete();
});
});
});
} else {
checkpoints.push(transaction);
}
return transaction as unknown as IDBTransaction;
},
} as unknown as IDBDatabase;
const factory = {
open: () => {
const request = {
result: database,
error: null,
transaction: null,
onsuccess: null,
onerror: null,
onblocked: null,
onupgradeneeded: null,
} as unknown as IDBOpenDBRequest;
queueMicrotask(() => request.onsuccess?.(new Event("success")));
return request;
},
cmp: () => 0,
databases: async () => [],
} as unknown as IDBFactory;
return { factory, transactionArguments, checkpoints };
}
async function flushTasks(): Promise<void> {
for (let tick = 0; tick < 5; tick += 1) {
await new Promise<void>((resolve) => {
setTimeout(resolve, 0);
});
}
}
async function openedCheckpointTransaction(
scripted: ReturnType<typeof scriptedFactory>,
): Promise<ScriptedTransaction> {
await flushTasks();
const transaction = scripted.checkpoints[0];
if (!transaction) throw new Error("no checkpoint transaction was opened");
return transaction;
}
describe("IndexedDB resumable upload checkpoint", () => {
it("length-prefixes scope tuples so delimiter placement cannot collide", () => {
const first = uploadCheckpointDatabaseName({
@@ -262,4 +411,112 @@ describe("IndexedDB resumable upload checkpoint", () => {
error: { code: "ABORTED" },
});
});
// CP-1. Three IndexedDB adapters report a value-less commit as UNAVAILABLE;
// this one reports CORRUPT_DATA/RECONCILE because a checkpoint read that
// committed while producing nothing means the stored row could not be turned
// into a checkpoint, and the caller has to reconcile rather than retry.
it("reports a checkpoint commit that produced no value as CORRUPT_DATA", async () => {
const scripted = scriptedFactory();
const store = createIndexedDbResumableUploadCheckpointStore({
scope,
factory: scripted.factory,
});
const pending = store.read("upload_key_01");
const transaction = await openedCheckpointTransaction(scripted);
transaction.complete();
expect(await pending).toMatchObject({
ok: false,
error: {
code: "CORRUPT_DATA",
operation: "UPLOAD_RECONCILE",
recovery: "RECONCILE",
},
});
});
// CP-2. A third argument would be a `{durability}` options bag. An engine
// that has never seen the bag treats it differently from no bag at all, so
// checkpoint writes stay on whatever the engine defaults to.
it("opens checkpoint transactions without a durability options bag", async () => {
const scripted = scriptedFactory();
const store = createIndexedDbResumableUploadCheckpointStore({
scope,
factory: scripted.factory,
});
const pending = store.read("upload_key_01");
const transaction = await openedCheckpointTransaction(scripted);
transaction.complete();
await pending;
expect(scripted.transactionArguments).toEqual([2, 2]);
});
// CP-3. Recording the error and letting the transaction run on would let
// `compareAndSwap`'s put commit after its get had already failed.
it("aborts the checkpoint transaction as soon as a request fails", async () => {
const scripted = scriptedFactory();
const store = createIndexedDbResumableUploadCheckpointStore({
scope,
factory: scripted.factory,
});
const pending = store.read("upload_key_01");
const transaction = await openedCheckpointTransaction(scripted);
const read = transaction.requests[0];
if (!read) throw new Error("the checkpoint read queued no request");
read.error = new DOMException("disk is unreadable", "NotReadableError");
read.onerror?.(new Event("error"));
expect(transaction.abortCalls).toBe(1);
expect(await pending).toMatchObject({
ok: false,
error: { code: "NOT_READABLE", retryable: true, recovery: "REOPEN" },
});
});
// CP-4. The transaction can already be durably committed while its completion
// event is still queued, which is when `abort()` throws. Claiming the abort
// would report a committed checkpoint as ABORTED.
it("keeps a committed checkpoint when the abort call itself throws", async () => {
const scripted = scriptedFactory({ abortThrows: true });
const store = createIndexedDbResumableUploadCheckpointStore({
scope,
factory: scripted.factory,
});
const controller = new AbortController();
const stored = checkpoint(1);
const pending = store.read(stored.uploadKey, controller.signal);
const transaction = await openedCheckpointTransaction(scripted);
const read = transaction.requests[0];
if (!read) throw new Error("the checkpoint read queued no request");
read.result = stored;
read.onsuccess?.(new Event("success"));
controller.abort();
expect(transaction.abortCalls).toBe(1);
transaction.complete();
expect(await pending).toEqual({ ok: true, value: stored });
});
// CP-5. The blocked deadline is the only bound on an open that another
// context is holding up, so it has to fire from the scheduler the store was
// built with rather than leave the read pending forever.
it("bounds a blocked open with the configured deadline", async () => {
const memory = new MemoryIndexedDbFactory();
const store = createIndexedDbResumableUploadCheckpointStore({
scope,
factory: memory.factory,
blockedTimeoutMs: 1,
});
memory.blockNextOpen();
expect(await store.read("upload_key_01")).toMatchObject({
ok: false,
error: { code: "BLOCKED", retryable: true, recovery: "RESUME" },
});
});
});
@@ -0,0 +1,341 @@
import { vi } from "vitest";
import type {
ResumableUploadCheckpoint,
ResumableUploadCheckpointStore,
ResumableUploadControlPlane,
ResumableUploadSource,
UploadPartExecutor,
UploadPartReceipt,
UploadProviderResult,
UploadSession,
} from "../../src/application/ports/browser-transfer/resumable-upload.ts";
import { RESUMABLE_UPLOAD_PROTOCOL } from "../../src/application/ports/browser-transfer/resumable-upload.ts";
import type {
BrowserDataResult,
} from "../../src/application/ports/browser-file-storage/shared.ts";
import {
browserDataFailure,
browserDataSuccess,
} from "../../src/adapters/browser-file-storage/result.ts";
import { resolveResumableUploadRuntimePolicy } from "../../src/adapters/browser-transfer/resumable-upload/runtime-policy.ts";
import type {
UploadCancellationChannel,
UploadCancellationListener,
} from "../../src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts";
import type { UploadMutationLock } from "../../src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts";
export type TestCapability = Readonly<{ id: string }>;
export const activeSignal = new AbortController().signal;
export const noContentionLock: UploadMutationLock = Object.freeze({
async run<Value>(
_uploadKey: string,
_signal: AbortSignal,
task: () => Promise<Value>,
): Promise<Value> {
return await task();
},
});
export function createSerialMutationLock(): UploadMutationLock {
let tail = Promise.resolve();
return Object.freeze({
run<Value>(
_uploadKey: string,
signal: AbortSignal,
task: () => Promise<Value>,
): Promise<Value> {
const result = tail.then(async () => {
if (signal.aborted) {
throw new DOMException(
"The operation was aborted.",
"AbortError",
);
}
return await task();
});
tail = result.then(
() => undefined,
() => undefined,
);
return result;
},
});
}
export function createMemoryCancellationPair(): readonly [
UploadCancellationChannel,
UploadCancellationChannel,
] {
const listeners = [
new Set<UploadCancellationListener>(),
new Set<UploadCancellationListener>(),
] as const;
const channels = listeners.map((ownListeners, ownIndex) => {
let closed = false;
return Object.freeze({
publish(uploadKey: string) {
if (closed) return false;
for (const [index, peerListeners] of listeners.entries()) {
if (index === ownIndex) continue;
for (const listener of [...peerListeners]) {
listener(uploadKey);
}
}
return true;
},
subscribe(listener: UploadCancellationListener) {
if (closed) throw new TypeError("closed");
ownListeners.add(listener);
return () => ownListeners.delete(listener);
},
close() {
closed = true;
ownListeners.clear();
},
});
});
return channels as unknown as readonly [
UploadCancellationChannel,
UploadCancellationChannel,
];
}
export class MemoryCheckpointStore implements ResumableUploadCheckpointStore {
readonly rows = new Map<string, ResumableUploadCheckpoint>();
closed = false;
async read(
uploadKey: string,
): Promise<BrowserDataResult<ResumableUploadCheckpoint | null>> {
return browserDataSuccess(
structuredClone(this.rows.get(uploadKey) ?? null),
);
}
async compareAndSwap(
input: Parameters<
ResumableUploadCheckpointStore["compareAndSwap"]
>[0],
): Promise<BrowserDataResult<ResumableUploadCheckpoint>> {
const current = this.rows.get(input.checkpoint.uploadKey);
if (
(input.expectedRevision === null && current) ||
(input.expectedRevision !== null &&
current?.revision !== input.expectedRevision)
) {
return browserDataFailure("CONFLICT", "UPLOAD_RECONCILE", {
recovery: "RECONCILE",
});
}
const snapshot = structuredClone(input.checkpoint);
this.rows.set(snapshot.uploadKey, snapshot);
return browserDataSuccess(snapshot);
}
async remove(
input: Parameters<ResumableUploadCheckpointStore["remove"]>[0],
): Promise<BrowserDataResult<void>> {
const current = this.rows.get(input.uploadKey);
if (current?.revision !== input.expectedRevision) {
return browserDataFailure("CONFLICT", "UPLOAD_RECONCILE", {
recovery: "RECONCILE",
});
}
this.rows.delete(input.uploadKey);
return browserDataSuccess(undefined);
}
close(): void {
this.closed = true;
}
}
export function rangeSource(bytes: Uint8Array): ResumableUploadSource {
return Object.freeze({
kind: "RANGE_READER" as const,
reader: Object.freeze({
byteLength: bytes.byteLength,
async readRange(input: Readonly<{
offset: number;
length: number;
signal: AbortSignal;
}>) {
if (input.signal.aborted) {
return browserDataFailure("ABORTED", "FILE_READ");
}
return browserDataSuccess(
bytes.slice(input.offset, input.offset + input.length),
);
},
}),
});
}
export function byteStreamSource(bytes: Uint8Array): ResumableUploadSource {
return Object.freeze({
kind: "FILE_BYTE_SOURCE" as const,
bytes: Object.freeze({
byteLength: bytes.byteLength,
async *stream(signal: AbortSignal) {
if (signal.aborted) {
yield browserDataFailure("ABORTED", "FILE_READ");
return;
}
yield browserDataSuccess(bytes.slice(0, 3));
yield browserDataSuccess(bytes.slice(3));
},
}),
});
}
export function runtimePolicy(
overrides: Partial<
Parameters<typeof resolveResumableUploadRuntimePolicy>[0]
> = {},
) {
return {
partSizeBytes: 4,
maxFileBytes: 100,
maxPartCount: 25,
maxConcurrency: 3,
maxInFlightBytes: 48,
partBufferCopyFactor: 4,
maxSourceChunkBytes: 8,
maxRetries: 2,
retryBaseDelayMs: 1,
retryMaxDelayMs: 10,
maxRetryAfterMs: 100,
capabilityRefreshSkewMs: 5,
maxSessionLifetimeMs: 10_000,
providerAttemptTimeoutMs: 100,
...overrides,
};
}
export type ControlHarness = Readonly<{
control: ResumableUploadControlPlane<TestCapability>;
accepted: Map<number, UploadPartReceipt>;
issued: ReturnType<typeof vi.fn>;
completedParts: UploadPartReceipt[][];
getSession(): UploadSession | null;
}>;
export function createControlHarness(options: Readonly<{
now?: number;
serverMaxConcurrency?: number;
sessionId?: (createIndex: number) => string;
statusParts?: (
session: UploadSession,
accepted: Map<number, UploadPartReceipt>,
) => readonly UploadPartReceipt[];
issueCapability?: (
input: Parameters<
ResumableUploadControlPlane<TestCapability>["issuePartCapability"]
>[0],
callIndex: number,
) => UploadProviderResult<Readonly<{
capability: TestCapability;
uploadBindingSha256: string;
expiresAtEpochMs: number;
}>>;
}> = {}): ControlHarness {
const now = options.now ?? 1_000;
const accepted = new Map<number, UploadPartReceipt>();
const completedParts: UploadPartReceipt[][] = [];
let session: UploadSession | null = null;
let createCount = 0;
let issueCount = 0;
const issued = vi.fn();
const control: ResumableUploadControlPlane<TestCapability> = {
async createSession(input) {
createCount += 1;
session = Object.freeze({
protocol: RESUMABLE_UPLOAD_PROTOCOL,
sessionId:
options.sessionId?.(createCount) ?? "session_01",
requestBindingSha256: input.requestBindingSha256,
fingerprint: input.fingerprint,
partSizeBytes: input.requestedPartSizeBytes,
partCount: input.fingerprint.partCount,
maxConcurrency: options.serverMaxConcurrency ?? 2,
expiresAtEpochMs: now + 5_000,
});
return browserDataSuccess(session);
},
async getStatus() {
if (!session) {
return browserDataFailure("NOT_FOUND", "UPLOAD_RECONCILE");
}
const parts =
options.statusParts?.(session, accepted) ??
[...accepted.values()].sort(
(left, right) => left.partNumber - right.partNumber,
);
return browserDataSuccess({
state: "ACTIVE",
session,
acceptedParts: parts,
});
},
async issuePartCapability(input) {
issueCount += 1;
issued(input);
return (
options.issueCapability?.(input, issueCount) ??
browserDataSuccess({
capability: Object.freeze({ id: `cap-${issueCount}` }),
uploadBindingSha256: input.uploadBindingSha256,
expiresAtEpochMs: now + 4_000,
})
);
},
async complete(input) {
completedParts.push([...input.orderedParts]);
return browserDataSuccess({
state: "QUARANTINED",
protocol: RESUMABLE_UPLOAD_PROTOCOL,
sessionId: input.sessionId,
requestBindingSha256: input.requestBindingSha256,
fingerprint: input.fingerprint,
resourceId: "resource_01",
});
},
async abort() {
return browserDataSuccess({ state: "ABORTED" });
},
};
return {
control,
accepted,
issued,
completedParts,
getSession: () => session,
};
}
export function executorFor(
harness: ControlHarness,
options: Readonly<{
delay?: () => Promise<void>;
onActive?: (active: number) => void;
}> = {},
): UploadPartExecutor<TestCapability> {
let active = 0;
return {
async uploadPart(input) {
active += 1;
options.onActive?.(active);
await options.delay?.();
active -= 1;
const receipt = Object.freeze({
...input.part,
receiptToken: `etag-part-${input.part.partNumber}`,
});
harness.accepted.set(input.part.partNumber, receipt);
return browserDataSuccess(receipt);
},
};
}
@@ -0,0 +1,188 @@
import { describe, expect, it, vi } from "vitest";
import { browserDataFailure } from "../../src/adapters/browser-file-storage/result.ts";
import { createResumableUploadRuntime } from "../../src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts";
import {
activeSignal,
byteStreamSource,
createControlHarness,
executorFor,
MemoryCheckpointStore,
noContentionLock,
runtimePolicy,
} from "./resumable-upload-runtime-fixture.ts";
/**
* TR-RR-06. A non-cooperative mutation lock or provider must not make teardown
* unbounded: `dispose()` bounds its drain and reports honestly when the runtime
* is still CLOSING, and an abort is admitted physical work it cannot step over.
*/
describe("TR-RR-06 bounded resumable teardown", () => {
it("reports an unproved drain instead of waiting forever", async () => {
const checkpoints = new MemoryCheckpointStore();
const harness = createControlHarness();
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness, { delay: async () => {} }),
checkpoints,
// A lock that never grants: dispose must still be bounded.
mutationLock: Object.freeze({
async run<Value>(): Promise<Value> {
return await new Promise<never>(() => {});
},
}),
crypto,
policy: runtimePolicy({ cleanupDeadlineMs: 20 }),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
void runtime.upload({
uploadKey: "upload_key_hung",
purpose: "attachment",
mediaType: "application/octet-stream",
source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
await Promise.resolve();
await Promise.resolve();
const disposed = await runtime.dispose();
expect(disposed.ok).toBe(false);
// Still CLOSING: physical work the caller must not treat as finished.
expect(runtime.lifecycle()).toBe("CLOSING");
expect(checkpoints.closed).toBe(false);
});
it("closes once every admitted operation settles", async () => {
const checkpoints = new MemoryCheckpointStore();
const harness = createControlHarness();
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness, { delay: async () => {} }),
checkpoints,
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy({ cleanupDeadlineMs: 200 }),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
const disposed = await runtime.dispose();
expect(disposed).toMatchObject({ ok: true });
expect(runtime.lifecycle()).toBe("CLOSED");
expect(checkpoints.closed).toBe(true);
});
});
/**
* TR-04. `dispose()` proved quiescence from the wrapper registry only. A
* provider that ignored its attempt deadline let the wrapper settle first and
* leave the set empty, so teardown reported a drained runtime — and closed the
* checkpoint store — while the provider was still running.
*/
describe("TR-04 teardown waits for raw provider work, not only its wrapper", () => {
it("refuses to report a drained runtime while a provider is still running", async () => {
const harness = createControlHarness();
const checkpoints = new MemoryCheckpointStore();
const closeStore = vi.spyOn(checkpoints, "close");
let releaseProvider: (() => void) | undefined;
// Ignores the attempt signal entirely and outlives its own deadline.
harness.control.createSession = () =>
new Promise((resolve) => {
releaseProvider = () =>
resolve(
browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", {
retryable: true,
recovery: "RESUME",
}),
);
});
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness),
checkpoints,
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy({
providerAttemptTimeoutMs: 5,
cleanupDeadlineMs: 25,
maxRetries: 0,
}),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
const uploading = runtime.upload({
uploadKey: "upload_key_raw",
purpose: "attachment",
mediaType: "application/octet-stream",
source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
await vi.waitFor(() => expect(releaseProvider).toBeDefined());
// The wrapper has already given up on the attempt.
await uploading;
const disposed = await runtime.dispose();
expect(disposed.ok).toBe(false);
if (!disposed.ok) {
expect(disposed.error.code).toBe("UNAVAILABLE");
expect(disposed.error.recovery).toBe("RESUME");
}
// The store stays open while something could still write a checkpoint.
expect(closeStore).not.toHaveBeenCalled();
releaseProvider?.();
});
it("reports a drained runtime once the raw provider settles", async () => {
const harness = createControlHarness();
const checkpoints = new MemoryCheckpointStore();
let releaseProvider: (() => void) | undefined;
harness.control.createSession = () =>
new Promise((resolve) => {
releaseProvider = () =>
resolve(
browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", {
retryable: true,
recovery: "RESUME",
}),
);
});
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness),
checkpoints,
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy({
providerAttemptTimeoutMs: 5,
cleanupDeadlineMs: 1_000,
maxRetries: 0,
}),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
const uploading = runtime.upload({
uploadKey: "upload_key_raw_2",
purpose: "attachment",
mediaType: "application/octet-stream",
source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
await vi.waitFor(() => expect(releaseProvider).toBeDefined());
await uploading;
const disposing = runtime.dispose();
releaseProvider?.();
await expect(disposing).resolves.toMatchObject({ ok: true });
expect(runtime.lifecycle()).toBe("CLOSED");
});
});
+13 -487
View File
@@ -32,319 +32,19 @@ import type {
} from "../../src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts";
import type { UploadMutationLock } from "../../src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts";
type TestCapability = Readonly<{ id: string }>;
const activeSignal = new AbortController().signal;
const noContentionLock: UploadMutationLock = Object.freeze({
async run<Value>(
_uploadKey: string,
_signal: AbortSignal,
task: () => Promise<Value>,
): Promise<Value> {
return await task();
},
});
function createSerialMutationLock(): UploadMutationLock {
let tail = Promise.resolve();
return Object.freeze({
run<Value>(
_uploadKey: string,
signal: AbortSignal,
task: () => Promise<Value>,
): Promise<Value> {
const result = tail.then(async () => {
if (signal.aborted) {
throw new DOMException(
"The operation was aborted.",
"AbortError",
);
}
return await task();
});
tail = result.then(
() => undefined,
() => undefined,
);
return result;
},
});
}
function createMemoryCancellationPair(): readonly [
UploadCancellationChannel,
UploadCancellationChannel,
] {
const listeners = [
new Set<UploadCancellationListener>(),
new Set<UploadCancellationListener>(),
] as const;
const channels = listeners.map((ownListeners, ownIndex) => {
let closed = false;
return Object.freeze({
publish(uploadKey: string) {
if (closed) return false;
for (const [index, peerListeners] of listeners.entries()) {
if (index === ownIndex) continue;
for (const listener of [...peerListeners]) {
listener(uploadKey);
}
}
return true;
},
subscribe(listener: UploadCancellationListener) {
if (closed) throw new TypeError("closed");
ownListeners.add(listener);
return () => ownListeners.delete(listener);
},
close() {
closed = true;
ownListeners.clear();
},
});
});
return channels as unknown as readonly [
UploadCancellationChannel,
UploadCancellationChannel,
];
}
class MemoryCheckpointStore implements ResumableUploadCheckpointStore {
readonly rows = new Map<string, ResumableUploadCheckpoint>();
closed = false;
async read(
uploadKey: string,
): Promise<BrowserDataResult<ResumableUploadCheckpoint | null>> {
return browserDataSuccess(
structuredClone(this.rows.get(uploadKey) ?? null),
);
}
async compareAndSwap(
input: Parameters<
ResumableUploadCheckpointStore["compareAndSwap"]
>[0],
): Promise<BrowserDataResult<ResumableUploadCheckpoint>> {
const current = this.rows.get(input.checkpoint.uploadKey);
if (
(input.expectedRevision === null && current) ||
(input.expectedRevision !== null &&
current?.revision !== input.expectedRevision)
) {
return browserDataFailure("CONFLICT", "UPLOAD_RECONCILE", {
recovery: "RECONCILE",
});
}
const snapshot = structuredClone(input.checkpoint);
this.rows.set(snapshot.uploadKey, snapshot);
return browserDataSuccess(snapshot);
}
async remove(
input: Parameters<ResumableUploadCheckpointStore["remove"]>[0],
): Promise<BrowserDataResult<void>> {
const current = this.rows.get(input.uploadKey);
if (current?.revision !== input.expectedRevision) {
return browserDataFailure("CONFLICT", "UPLOAD_RECONCILE", {
recovery: "RECONCILE",
});
}
this.rows.delete(input.uploadKey);
return browserDataSuccess(undefined);
}
close(): void {
this.closed = true;
}
}
function rangeSource(bytes: Uint8Array): ResumableUploadSource {
return Object.freeze({
kind: "RANGE_READER" as const,
reader: Object.freeze({
byteLength: bytes.byteLength,
async readRange(input: Readonly<{
offset: number;
length: number;
signal: AbortSignal;
}>) {
if (input.signal.aborted) {
return browserDataFailure("ABORTED", "FILE_READ");
}
return browserDataSuccess(
bytes.slice(input.offset, input.offset + input.length),
);
},
}),
});
}
function byteStreamSource(bytes: Uint8Array): ResumableUploadSource {
return Object.freeze({
kind: "FILE_BYTE_SOURCE" as const,
bytes: Object.freeze({
byteLength: bytes.byteLength,
async *stream(signal: AbortSignal) {
if (signal.aborted) {
yield browserDataFailure("ABORTED", "FILE_READ");
return;
}
yield browserDataSuccess(bytes.slice(0, 3));
yield browserDataSuccess(bytes.slice(3));
},
}),
});
}
function runtimePolicy(
overrides: Partial<
Parameters<typeof resolveResumableUploadRuntimePolicy>[0]
> = {},
) {
return {
partSizeBytes: 4,
maxFileBytes: 100,
maxPartCount: 25,
maxConcurrency: 3,
maxInFlightBytes: 48,
partBufferCopyFactor: 4,
maxSourceChunkBytes: 8,
maxRetries: 2,
retryBaseDelayMs: 1,
retryMaxDelayMs: 10,
maxRetryAfterMs: 100,
capabilityRefreshSkewMs: 5,
maxSessionLifetimeMs: 10_000,
providerAttemptTimeoutMs: 100,
...overrides,
};
}
type ControlHarness = Readonly<{
control: ResumableUploadControlPlane<TestCapability>;
accepted: Map<number, UploadPartReceipt>;
issued: ReturnType<typeof vi.fn>;
completedParts: UploadPartReceipt[][];
getSession(): UploadSession | null;
}>;
function createControlHarness(options: Readonly<{
now?: number;
serverMaxConcurrency?: number;
sessionId?: (createIndex: number) => string;
statusParts?: (
session: UploadSession,
accepted: Map<number, UploadPartReceipt>,
) => readonly UploadPartReceipt[];
issueCapability?: (
input: Parameters<
ResumableUploadControlPlane<TestCapability>["issuePartCapability"]
>[0],
callIndex: number,
) => UploadProviderResult<Readonly<{
capability: TestCapability;
uploadBindingSha256: string;
expiresAtEpochMs: number;
}>>;
}> = {}): ControlHarness {
const now = options.now ?? 1_000;
const accepted = new Map<number, UploadPartReceipt>();
const completedParts: UploadPartReceipt[][] = [];
let session: UploadSession | null = null;
let createCount = 0;
let issueCount = 0;
const issued = vi.fn();
const control: ResumableUploadControlPlane<TestCapability> = {
async createSession(input) {
createCount += 1;
session = Object.freeze({
protocol: RESUMABLE_UPLOAD_PROTOCOL,
sessionId:
options.sessionId?.(createCount) ?? "session_01",
requestBindingSha256: input.requestBindingSha256,
fingerprint: input.fingerprint,
partSizeBytes: input.requestedPartSizeBytes,
partCount: input.fingerprint.partCount,
maxConcurrency: options.serverMaxConcurrency ?? 2,
expiresAtEpochMs: now + 5_000,
});
return browserDataSuccess(session);
},
async getStatus() {
if (!session) {
return browserDataFailure("NOT_FOUND", "UPLOAD_RECONCILE");
}
const parts =
options.statusParts?.(session, accepted) ??
[...accepted.values()].sort(
(left, right) => left.partNumber - right.partNumber,
);
return browserDataSuccess({
state: "ACTIVE",
session,
acceptedParts: parts,
});
},
async issuePartCapability(input) {
issueCount += 1;
issued(input);
return (
options.issueCapability?.(input, issueCount) ??
browserDataSuccess({
capability: Object.freeze({ id: `cap-${issueCount}` }),
uploadBindingSha256: input.uploadBindingSha256,
expiresAtEpochMs: now + 4_000,
})
);
},
async complete(input) {
completedParts.push([...input.orderedParts]);
return browserDataSuccess({
state: "QUARANTINED",
protocol: RESUMABLE_UPLOAD_PROTOCOL,
sessionId: input.sessionId,
requestBindingSha256: input.requestBindingSha256,
fingerprint: input.fingerprint,
resourceId: "resource_01",
});
},
async abort() {
return browserDataSuccess({ state: "ABORTED" });
},
};
return {
control,
accepted,
issued,
completedParts,
getSession: () => session,
};
}
function executorFor(
harness: ControlHarness,
options: Readonly<{
delay?: () => Promise<void>;
onActive?: (active: number) => void;
}> = {},
): UploadPartExecutor<TestCapability> {
let active = 0;
return {
async uploadPart(input) {
active += 1;
options.onActive?.(active);
await options.delay?.();
active -= 1;
const receipt = Object.freeze({
...input.part,
receiptToken: `etag-part-${input.part.partNumber}`,
});
harness.accepted.set(input.part.partNumber, receipt);
return browserDataSuccess(receipt);
},
};
}
import {
activeSignal,
byteStreamSource,
createControlHarness,
createMemoryCancellationPair,
createSerialMutationLock,
executorFor,
MemoryCheckpointStore,
noContentionLock,
rangeSource,
runtimePolicy,
type TestCapability,
} from "./resumable-upload-runtime-fixture.ts";
describe("production resumable upload runtime", () => {
it("disposes through one drain that proves quiescence", async () => {
@@ -1280,177 +980,3 @@ describe("production resumable upload runtime", () => {
}
});
});
/**
* TR-RR-06. A non-cooperative mutation lock or provider must not make teardown
* unbounded: `dispose()` bounds its drain and reports honestly when the runtime
* is still CLOSING, and an abort is admitted physical work it cannot step over.
*/
describe("TR-RR-06 bounded resumable teardown", () => {
it("reports an unproved drain instead of waiting forever", async () => {
const checkpoints = new MemoryCheckpointStore();
const harness = createControlHarness();
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness, { delay: async () => {} }),
checkpoints,
// A lock that never grants: dispose must still be bounded.
mutationLock: Object.freeze({
async run<Value>(): Promise<Value> {
return await new Promise<never>(() => {});
},
}),
crypto,
policy: runtimePolicy({ cleanupDeadlineMs: 20 }),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
void runtime.upload({
uploadKey: "upload_key_hung",
purpose: "attachment",
mediaType: "application/octet-stream",
source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
await Promise.resolve();
await Promise.resolve();
const disposed = await runtime.dispose();
expect(disposed.ok).toBe(false);
// Still CLOSING: physical work the caller must not treat as finished.
expect(runtime.lifecycle()).toBe("CLOSING");
expect(checkpoints.closed).toBe(false);
});
it("closes once every admitted operation settles", async () => {
const checkpoints = new MemoryCheckpointStore();
const harness = createControlHarness();
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness, { delay: async () => {} }),
checkpoints,
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy({ cleanupDeadlineMs: 200 }),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
const disposed = await runtime.dispose();
expect(disposed).toMatchObject({ ok: true });
expect(runtime.lifecycle()).toBe("CLOSED");
expect(checkpoints.closed).toBe(true);
});
});
/**
* TR-04. `dispose()` proved quiescence from the wrapper registry only. A
* provider that ignored its attempt deadline let the wrapper settle first and
* leave the set empty, so teardown reported a drained runtime — and closed the
* checkpoint store — while the provider was still running.
*/
describe("TR-04 teardown waits for raw provider work, not only its wrapper", () => {
it("refuses to report a drained runtime while a provider is still running", async () => {
const harness = createControlHarness();
const checkpoints = new MemoryCheckpointStore();
const closeStore = vi.spyOn(checkpoints, "close");
let releaseProvider: (() => void) | undefined;
// Ignores the attempt signal entirely and outlives its own deadline.
harness.control.createSession = () =>
new Promise((resolve) => {
releaseProvider = () =>
resolve(
browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", {
retryable: true,
recovery: "RESUME",
}),
);
});
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness),
checkpoints,
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy({
providerAttemptTimeoutMs: 5,
cleanupDeadlineMs: 25,
maxRetries: 0,
}),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
const uploading = runtime.upload({
uploadKey: "upload_key_raw",
purpose: "attachment",
mediaType: "application/octet-stream",
source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
await vi.waitFor(() => expect(releaseProvider).toBeDefined());
// The wrapper has already given up on the attempt.
await uploading;
const disposed = await runtime.dispose();
expect(disposed.ok).toBe(false);
if (!disposed.ok) {
expect(disposed.error.code).toBe("UNAVAILABLE");
expect(disposed.error.recovery).toBe("RESUME");
}
// The store stays open while something could still write a checkpoint.
expect(closeStore).not.toHaveBeenCalled();
releaseProvider?.();
});
it("reports a drained runtime once the raw provider settles", async () => {
const harness = createControlHarness();
const checkpoints = new MemoryCheckpointStore();
let releaseProvider: (() => void) | undefined;
harness.control.createSession = () =>
new Promise((resolve) => {
releaseProvider = () =>
resolve(
browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", {
retryable: true,
recovery: "RESUME",
}),
);
});
const runtime = createResumableUploadRuntime({
controlPlane: harness.control,
partExecutor: executorFor(harness),
checkpoints,
mutationLock: noContentionLock,
crypto,
policy: runtimePolicy({
providerAttemptTimeoutMs: 5,
cleanupDeadlineMs: 1_000,
maxRetries: 0,
}),
now: () => 1_000,
random: () => 0,
sleep: async () => {},
});
const uploading = runtime.upload({
uploadKey: "upload_key_raw_2",
purpose: "attachment",
mediaType: "application/octet-stream",
source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])),
signal: activeSignal,
});
await vi.waitFor(() => expect(releaseProvider).toBeDefined());
await uploading;
const disposing = runtime.dispose();
releaseProvider?.();
await expect(disposing).resolves.toMatchObject({ ok: true });
expect(runtime.lifecycle()).toBe("CLOSED");
});
});
+543
View File
@@ -0,0 +1,543 @@
import {
createHash,
generateKeyPairSync,
sign,
type KeyObject,
} from "node:crypto";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { localEvidenceAssessmentArtifactSchema } from "../../scripts/contracts/release-artifacts.ts";
import { PROMOTED_FILE_NAMES } from "../../scripts/contracts/promotion-artifacts.ts";
import {
PROMOTION_VERIFIER_ID,
providerEvidenceSignaturePayload,
trustPolicySha256,
} from "../../scripts/lib/provider-evidence.ts";
import { LOCAL_EVIDENCE_VERIFIER_ID } from "../../scripts/lib/local-release-evidence.ts";
import {
LOCAL_EVIDENCE_ASSESSMENT_PATH,
distSha256,
type ReleaseCandidateManifest,
} from "../../scripts/lib/release-candidate.ts";
import { supplyChainDigest } from "../../scripts/lib/supply-chain.ts";
export const PROCESS_HEAVY_TIMEOUT_MS = 30_000;
export const digest = (value: string): string =>
createHash("sha256").update(value).digest("hex");
export const digestBytes = (value: Buffer): string =>
createHash("sha256").update(value).digest("hex");
export function passingAssessment(): any {
return {
schemaVersion: 1 as const,
artifactType: "local-evidence-assessment" as const,
generatedAt: "2026-08-02T00:00:00.000Z",
status: "PASS" as const,
verifier: {
id: LOCAL_EVIDENCE_VERIFIER_ID,
version: "1",
sourceSha256: digest("verifier source"),
},
source: {
revision: "a".repeat(40),
sourceSetSha256: digest("source set"),
},
candidate: {
distSha256: digest("dist"),
lockfileSha256: digest("lockfile"),
sbomSha256: digest("sbom"),
},
secretScan: {
policySha256: digest("secret policy"),
sarifSha256: digest("secret sarif"),
scanInputSha256: digest("secret scan input"),
},
policyInputs: [
{
path: "config/security/dependency-policy.json",
bytes: 3,
sha256: digest("{}\n"),
},
],
evidenceInputs: [
{ path: "pnpm-lock.yaml", bytes: 9, sha256: digest("lockfile\n") },
],
checks: {
release: "PASS" as const,
supplyChain: "PASS" as const,
dependencyPolicy: "PASS" as const,
licensePolicy: "PASS" as const,
vulnerabilityPolicy: "PASS" as const,
secretScan: "PASS" as const,
},
failures: [] as string[],
};
}
export function providerExpectedContext() {
return {
run: { id: "run-42", attempt: 1 },
source: { revision: "b".repeat(40), sourceSetSha256: digest("provider source") },
candidate: {
archiveSha256: digest("archive"),
bundleSha256: digest("bundle"),
distSha256: digest("provider dist"),
lockfileSha256: digest("provider lockfile"),
},
secretScanAttestation: {
status: "PASS" as const,
localEvidenceAssessmentSha256: digest("provider assessment"),
sourceSetSha256: digest("provider source"),
policySha256: digest("provider secret policy"),
sarifSha256: digest("provider secret sarif"),
scanInputSha256: digest("provider secret input"),
},
} as const;
}
export function privatePromotionFiles() {
return PROMOTED_FILE_NAMES.map((name) => {
const bytes = Buffer.from(`${name}\n`);
return { name, bytes, sha256: digestBytes(bytes) };
});
}
export function syntheticSignedPromotionBundle() {
const vulnerabilityKeys = generateKeyPairSync("ed25519");
const provenanceKeys = generateKeyPairSync("ed25519");
const archiveBytes = Buffer.from("synthetic signed replay archive\n");
const run = { id: "signed-run", attempt: 1 } as const;
const source = {
revision: "a".repeat(40),
sourceSetSha256: digest("synthetic-source-set"),
} as const;
const candidate = {
archiveSha256: digestBytes(archiveBytes),
bundleSha256: digest("synthetic-bundle"),
distSha256: digest("synthetic-dist"),
lockfileSha256: digest("synthetic-lock"),
} as const;
const vulnerability = signedProviderV2(
{
schemaVersion: 2,
evidenceType: "vulnerability-report",
provider: "synthetic-vulnerability-provider",
issuedAt: "2026-08-02T01:00:00.000Z",
expiresAt: "2026-08-02T02:00:00.000Z",
run: { ...run, invocationNonce: "1".repeat(64) },
source,
candidate,
secretScanAttestation: {
status: "PASS",
localEvidenceAssessmentSha256: digest("synthetic-assessment"),
sourceSetSha256: source.sourceSetSha256,
policySha256: digest("synthetic-policy"),
sarifSha256: digest("synthetic-sarif"),
scanInputSha256: digest("synthetic-scan-input"),
},
findings: [],
},
"synthetic-vulnerability",
vulnerabilityKeys.publicKey,
vulnerabilityKeys.privateKey,
);
const provenance = signedProviderV2(
{
schemaVersion: 2,
evidenceType: "provenance-attestation",
provider: "synthetic-provenance-provider",
signer: "synthetic-signer",
issuedAt: "2026-08-02T01:00:00.000Z",
expiresAt: "2026-08-02T02:00:00.000Z",
run: { ...run, invocationNonce: "2".repeat(64) },
source,
candidate,
subject: { name: "dist", digest: { sha256: candidate.distSha256 } },
},
"synthetic-provenance",
provenanceKeys.publicKey,
provenanceKeys.privateKey,
);
const vulnerabilityBytes = Buffer.from(`${JSON.stringify(vulnerability)}\n`);
const provenanceBytes = Buffer.from(`${JSON.stringify(provenance)}\n`);
const vulnerabilityTrust = trust("synthetic-vulnerability", vulnerabilityKeys.publicKey);
const provenanceTrust = trust("synthetic-provenance", provenanceKeys.publicKey);
const providerEvidence = {
vulnerabilityReportSha256: digestBytes(vulnerabilityBytes),
provenanceAttestationSha256: digestBytes(provenanceBytes),
vulnerabilityInvocationNonce: "1".repeat(64),
provenanceInvocationNonce: "2".repeat(64),
vulnerabilityKeyId: vulnerabilityTrust.keyId,
vulnerabilityKeyFingerprint: vulnerabilityTrust.publicKeyFingerprint,
provenanceKeyId: provenanceTrust.keyId,
provenanceKeyFingerprint: provenanceTrust.publicKeyFingerprint,
secretScanAttestation: vulnerability.secretScanAttestation,
};
const common = {
schemaVersion: 3,
verifiedAt: "2026-08-02T01:00:00.000Z",
status: "PASS",
verifier: {
id: PROMOTION_VERIFIER_ID,
version: "3",
},
run,
source,
candidate,
providerEvidence,
trustPolicySha256: trustPolicySha256({ vulnerabilityTrust, provenanceTrust }),
failures: [],
};
const providerBytes = Buffer.from(
`${JSON.stringify({
...common,
artifactType: "provider-verification",
vulnerabilityStatus: "PASS",
provenanceAttestationStatus: "PASS",
}, null, 2)}\n`,
);
const promotionBytes = Buffer.from(
`${JSON.stringify({
...common,
artifactType: "promotion-verification",
localEvidenceStatus: "PASS",
localEvidenceAssessmentSha256: digest("synthetic-assessment"),
providerVerificationSha256: digestBytes(providerBytes),
}, null, 2)}\n`,
);
return {
files: {
"release-candidate.tar.gz": archiveBytes,
"vulnerability-report.json": vulnerabilityBytes,
"provenance-attestation.json": provenanceBytes,
"provider-verification.json": providerBytes,
"promotion-verification.json": promotionBytes,
},
verification: {
vulnerabilityTrust,
provenanceTrust,
nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"),
expected: {
run,
sourceRevision: source.revision,
sourceSetSha256: source.sourceSetSha256,
archiveSha256: candidate.archiveSha256,
bundleSha256: candidate.bundleSha256,
distSha256: candidate.distSha256,
lockfileSha256: candidate.lockfileSha256,
},
},
vulnerabilityPem: vulnerabilityKeys.publicKey.export({ type: "spki", format: "pem" }),
provenancePem: provenanceKeys.publicKey.export({ type: "spki", format: "pem" }),
};
}
export function fingerprint(publicKey: KeyObject): string {
return `sha256:${createHash("sha256")
.update(publicKey.export({ type: "spki", format: "der" }))
.digest("hex")}`;
}
export function trust(keyId: string, publicKey: KeyObject) {
return { keyId, publicKey, publicKeyFingerprint: fingerprint(publicKey) };
}
export function signedProviderV2(
unsigned: Record<string, unknown>,
keyId: string,
publicKey: KeyObject,
privateKey: KeyObject,
fingerprintOverride?: string,
): Record<string, any> {
const { signature: existingSignature, ...payload } = unsigned;
const value = {
...payload,
signature: {
algorithm: "Ed25519" as const,
keyId,
publicKeyFingerprint:
fingerprintOverride ??
(existingSignature && typeof existingSignature === "object" &&
"publicKeyFingerprint" in existingSignature
? String(existingSignature.publicKeyFingerprint)
: fingerprint(publicKey)),
value: "",
},
};
value.signature.value = sign(
null,
providerEvidenceSignaturePayload(value),
privateKey,
).toString("base64");
return value;
}
export function providerUnsigned(
kind: "vulnerability" | "provenance",
expected: ReturnType<typeof providerExpectedContext>,
): Record<string, any> {
const common = {
source: expected.source,
candidate: expected.candidate,
schemaVersion: 2,
evidenceType:
kind === "vulnerability"
? "vulnerability-report"
: "provenance-attestation",
provider: `fixture-${kind}`,
issuedAt: "2026-08-02T01:00:00.000Z",
expiresAt: "2026-08-02T02:00:00.000Z",
run: {
...expected.run,
invocationNonce: kind === "vulnerability" ? "1".repeat(64) : "2".repeat(64),
},
};
return kind === "vulnerability"
? {
...common,
secretScanAttestation: expected.secretScanAttestation,
findings: [],
}
: {
...common,
signer: "fixture-workload",
subject: {
name: "dist",
digest: { sha256: expected.candidate.distSha256 },
},
};
}
export async function createArchivedAssessmentFixture(): Promise<{
root: string;
manifest: ReleaseCandidateManifest;
assessmentSha256: string;
}> {
const root = await mkdtemp(path.join(tmpdir(), "archived-assessment-"));
const sourceRevision = "a".repeat(40);
const sourceSetSha256 = digest("source set");
const releaseManifestBytes = Buffer.from(
`${JSON.stringify({
schemaVersion: 1,
appVersion: "1.0.0",
buildId: "build-1",
commitSha: sourceRevision,
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: digest("vite manifest"),
releaseId: "release-1",
builtAt: "2026-08-02T00:00:00.000Z",
routeChunks: { home: "assets/home.js" },
})}\n`,
);
const distInputs = [
{ path: "dist/app.js", bytes: Buffer.byteLength("app\n"), sha256: digest("app\n"), gzipBytes: 0 },
{
path: "dist/release-manifest.json",
bytes: releaseManifestBytes.byteLength,
sha256: digestBytes(releaseManifestBytes),
gzipBytes: 0,
},
];
const candidateDist = distSha256(distInputs);
const sbomBytes = Buffer.from(
`${JSON.stringify({
bomFormat: "CycloneDX",
specVersion: "1.6",
serialNumber: "urn:uuid:00000000-0000-4000-8000-000000000001",
version: 1,
metadata: {
component: { type: "application", name: "fixture", version: "1.0.0" },
properties: [],
},
components: [],
dependencies: [],
})}\n`,
);
const sbomSha256 = digestBytes(sbomBytes);
const lockfileBytes = Buffer.from("lockfile\n");
const lockfileDigest = digestBytes(lockfileBytes);
const buildManifest = {
schemaVersion: 1,
buildId: "build-1",
commitSha: sourceRevision,
releaseId: "release-1",
moduleInventoryHash: digest("module inventory"),
generatedAt: "2026-08-02T00:00:00.000Z",
buildContext: {
nodeVersion: "v24.0.0",
packageManagerVersion: "11.0.0",
runnerImage: "linux-x64",
sourceDateEpoch: "1785638400",
},
outputs: {
directory: "dist",
viteManifest: "dist/.vite/manifest.json",
moduleInventory: "artifacts/quality/vite-module-inventory.json",
routeChunks: { home: "assets/home.js" },
runtimeConfigSchema: "dist/runtime-config.schema.json",
},
};
const provenance = {
_type: "https://in-toto.io/Statement/v1",
subject: [{ name: "dist", digest: { sha256: candidateDist } }],
predicateType: "https://slsa.dev/provenance/v1",
predicate: {
buildDefinition: {
buildType: "https://vite.dev/build/v1",
externalParameters: {},
internalParameters: {},
resolvedDependencies: [
{ uri: "pnpm-lock.yaml", digest: { sha256: lockfileDigest } },
],
},
runDetails: {
builder: { id: "fixture-builder" },
metadata: { invocationId: "LOCAL_UNSIGNED" },
},
materials: { lockfileSha256: lockfileDigest, sourceSetSha256, sbomSha256 },
},
};
const supplyVerification = {
schemaVersion: 1,
localStatus: "PASS",
promotionStatus: "FAIL_UNVERIFIED",
lockfileSha256: lockfileDigest,
sourceSetSha256,
distSha256: candidateDist,
sbomSha256,
dependencyDiff: { added: [], removed: [], changed: [], upgrades: [] },
highRiskReview: [],
vulnerabilityStatus: "FAIL_UNVERIFIED",
provenanceAttestationStatus: "FAIL_UNVERIFIED",
failures: [],
};
const members = new Map<string, Buffer>([
["dist/app.js", Buffer.from("app\n")],
["dist/release-manifest.json", releaseManifestBytes],
["pnpm-lock.yaml", lockfileBytes],
["artifacts/release/build-manifest.json", Buffer.from(`${JSON.stringify(buildManifest)}\n`)],
["artifacts/release/provenance.json", Buffer.from(`${JSON.stringify(provenance)}\n`)],
[
"artifacts/security/supply-chain-verification.json",
Buffer.from(`${JSON.stringify(supplyVerification)}\n`),
],
["artifacts/release/sbom.cdx.json", sbomBytes],
]);
const evidenceInputs = [...members.entries()]
.map(([memberPath, bytes]) => ({
path: memberPath,
bytes: bytes.byteLength,
sha256: digestBytes(bytes),
}))
.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
const policyPaths = [
"config/security/dependency-baseline.approval.json",
"config/security/dependency-baseline.json",
"config/security/dependency-change-evidence.json",
"config/security/dependency-policy.json",
"config/security/secret-scan-policy.json",
"config/security/vulnerability-exceptions.json",
"config/security/vulnerability-policy.json",
"schemas/artifacts/build-manifest.schema.json",
"schemas/artifacts/dependency-inventory.schema.json",
"schemas/artifacts/supply-chain-verification.schema.json",
"scripts/contracts/release-artifacts.ts",
"scripts/create-release-candidate.ts",
"scripts/generate-supply-chain.ts",
"scripts/lib/build-manifest-outputs.ts",
"scripts/lib/json-schema.ts",
"scripts/lib/local-policy-evidence.ts",
"scripts/lib/local-release-evidence.ts",
"scripts/lib/release-candidate.ts",
"scripts/lib/release-input-evidence.ts",
"scripts/lib/release-runtime-coherence.ts",
"scripts/lib/repository-file-inventory.ts",
"scripts/lib/secret-scan-evaluator.ts",
"scripts/lib/secret-scan-policy.ts",
"scripts/lib/secret-scan.ts",
"scripts/lib/supply-chain.ts",
"scripts/lib/validated-json-artifact.ts",
"src/contracts/release-artifacts.ts",
"src/features/installed-contract-contributions.ts",
"src/features/installed-feature-contracts.ts",
];
const sbomRow = evidenceInputs.find(
({ path: memberPath }) => memberPath === "artifacts/release/sbom.cdx.json",
)!;
const policyInputs = policyPaths.map((policyPath) => ({
path: policyPath,
bytes: 2,
sha256: digest(`policy:${policyPath}`),
}));
const verifierPaths = new Set([
"scripts/contracts/release-artifacts.ts",
"scripts/create-release-candidate.ts",
"scripts/generate-supply-chain.ts",
"scripts/lib/build-manifest-outputs.ts",
"scripts/lib/json-schema.ts",
"scripts/lib/local-policy-evidence.ts",
"scripts/lib/local-release-evidence.ts",
"scripts/lib/release-candidate.ts",
"scripts/lib/release-input-evidence.ts",
"scripts/lib/release-runtime-coherence.ts",
"scripts/lib/repository-file-inventory.ts",
"scripts/lib/secret-scan-evaluator.ts",
"scripts/lib/secret-scan-policy.ts",
"scripts/lib/secret-scan.ts",
"scripts/lib/supply-chain.ts",
"scripts/lib/validated-json-artifact.ts",
"src/contracts/release-artifacts.ts",
"src/features/installed-contract-contributions.ts",
"src/features/installed-feature-contracts.ts",
]);
const assessment = localEvidenceAssessmentArtifactSchema.parse({
...passingAssessment(),
verifier: {
id: LOCAL_EVIDENCE_VERIFIER_ID,
version: "1",
sourceSha256: supplyChainDigest(
policyInputs.filter(({ path: policyPath }) => verifierPaths.has(policyPath)),
),
},
source: { revision: sourceRevision, sourceSetSha256 },
candidate: {
distSha256: candidateDist,
lockfileSha256: evidenceInputs.find(({ path: memberPath }) => memberPath === "pnpm-lock.yaml")!
.sha256,
sbomSha256: sbomRow.sha256,
},
policyInputs,
evidenceInputs,
});
const assessmentBytes = Buffer.from(`${JSON.stringify(assessment)}\n`);
members.set(LOCAL_EVIDENCE_ASSESSMENT_PATH, assessmentBytes);
for (const [memberPath, bytes] of members) {
await mkdir(path.dirname(path.join(root, memberPath)), { recursive: true });
await writeFile(path.join(root, memberPath), bytes);
}
const files = [...members.entries()]
.map(([memberPath, bytes]) => ({
path: memberPath,
bytes: bytes.byteLength,
sha256: digestBytes(bytes),
}))
.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
const manifest: ReleaseCandidateManifest = {
schemaVersion: 1,
distSha256: assessment.candidate.distSha256,
lockfileSha256: assessment.candidate.lockfileSha256,
bundleSha256: supplyChainDigest(files),
files,
};
await mkdir(path.join(root, "artifacts/release"), { recursive: true });
await writeFile(
path.join(root, "artifacts/release/release-candidate.json"),
`${JSON.stringify(manifest)}\n`,
);
return { root, manifest, assessmentSha256: digestBytes(assessmentBytes) };
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,370 @@
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import {
chmod,
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
rename,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { describe, expect, it } from "vitest";
import { PROMOTED_FILE_NAMES } from "../../scripts/contracts/promotion-artifacts.ts";
import { publishPrivatePromotionStaging } from "../../scripts/lib/promotion-stager.ts";
import { verifyExactPromotionBundle } from "../../scripts/lib/exact-promotion-bundle.ts";
import {
PROCESS_HEAVY_TIMEOUT_MS,
privatePromotionFiles,
syntheticSignedPromotionBundle,
} from "./security-followup-fixture.ts";
describe("security private promotion staging contracts", () => {
it("forces exact private staging modes in an isolated child with umask 077", async () => {
const root = await mkdtemp(path.join(tmpdir(), "promotion-umask-"));
try {
const stagerUrl = pathToFileURL(
path.join(process.cwd(), "scripts/lib/promotion-stager.ts"),
).href;
const contractsUrl = pathToFileURL(
path.join(process.cwd(), "scripts/contracts/promotion-artifacts.ts"),
).href;
const childPath = path.join(root, "umask-child.mjs");
const resultPath = path.join(root, "result.json");
await writeFile(resultPath, "{}\n", { mode: 0o600 });
await writeFile(
childPath,
[
`import { lstat, writeFile } from "node:fs/promises";`,
`import path from "node:path";`,
`import { createHash } from "node:crypto";`,
`import { cleanupFinalizedPromotion, publishPrivatePromotionStaging } from ${JSON.stringify(stagerUrl)};`,
`import { PROMOTED_FILE_NAMES } from ${JSON.stringify(contractsUrl)};`,
`process.umask(Number.parseInt(process.argv[2], 8));`,
`const runnerTempRoot = process.argv[3];`,
`const files = PROMOTED_FILE_NAMES.map((name) => { const bytes = Buffer.from(name); return { name, bytes, sha256: createHash("sha256").update(bytes).digest("hex") }; });`,
`const finalized = await publishPrivatePromotionStaging(runnerTempRoot, { id: "umask", attempt: 1 }, files, () => Buffer.alloc(16, 1));`,
`const directoryMode = (await lstat(finalized.stagingRoot)).mode & 0o777;`,
`const fileModes = await Promise.all(PROMOTED_FILE_NAMES.map(async (name) => (await lstat(path.join(finalized.stagingRoot, name))).mode & 0o777));`,
`await cleanupFinalizedPromotion({ runnerTempRoot, stagingRoot: finalized.stagingRoot, cleanupToken: finalized.cleanupToken, runnerTempIdentity: finalized.runnerTempIdentity, stagingIdentity: finalized.stagingIdentity });`,
`await writeFile(process.argv[4], JSON.stringify({ directoryMode, fileModes }));`,
].join("\n"),
);
const child = spawnSync(process.execPath, [childPath, "077", root, resultPath], {
cwd: root,
encoding: "utf8",
timeout: 30_000,
});
expect(child.status, `${child.stdout}\n${child.stderr}`).toBe(0);
expect(JSON.parse(await readFile(resultPath, "utf8"))).toEqual({
directoryMode: 0o700,
fileModes: [0o400, 0o400, 0o400, 0o400, 0o400],
});
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("rejects a staged file unlinked and recreated after its original write", async () => {
const root = await mkdtemp(path.join(tmpdir(), "promotion-seal-recreate-"));
const files = privatePromotionFiles();
const token = `promotion-seal-1-${"11".repeat(16)}`;
try {
await expect(
publishPrivatePromotionStaging(
root,
{ id: "seal", attempt: 1 },
files,
() => Buffer.alloc(16, 0x11),
undefined,
async (name) => {
if (name !== PROMOTED_FILE_NAMES.at(-1)) return;
const first = path.join(root, token, PROMOTED_FILE_NAMES[0]);
await rm(first);
await writeFile(first, "replacement bytes\n", { mode: 0o400 });
},
),
).rejects.toThrow(/staged.*digest|inode|seal/u);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("rejects staged mode drift before returning the upload root", async () => {
const root = await mkdtemp(path.join(tmpdir(), "promotion-seal-mode-"));
const files = privatePromotionFiles();
const token = `promotion-seal-1-${"12".repeat(16)}`;
try {
await expect(
publishPrivatePromotionStaging(
root,
{ id: "seal", attempt: 1 },
files,
() => Buffer.alloc(16, 0x12),
undefined,
async (name) => {
if (name === PROMOTED_FILE_NAMES.at(-1)) {
await chmod(path.join(root, token, PROMOTED_FILE_NAMES[0]), 0o600);
}
},
),
).rejects.toThrow(/mode.*0400|staged.*mode|seal/u);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("rejects staging leaf replacement between mkdir and descriptor open", async () => {
const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-replace-"));
const files = privatePromotionFiles();
const token = `promotion-preopen-1-${"13".repeat(16)}`;
const displaced = path.join(root, `${token}-displaced`);
const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]);
try {
await expect(
publishPrivatePromotionStaging(
root,
{ id: "preopen", attempt: 1 },
files,
() => Buffer.alloc(16, 0x13),
undefined,
undefined,
undefined,
async (stagingRoot) => {
await rename(stagingRoot, displaced);
await mkdir(stagingRoot, { mode: 0o700 });
await writeFile(replacementCanary, "external replacement canary\n");
},
),
).rejects.toThrow(/staging leaf.*changed|mkdir.*open|identity/u);
await expect(readFile(replacementCanary, "utf8")).resolves.toBe(
"external replacement canary\n",
);
await expect(readdir(displaced)).resolves.toEqual([]);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("does not scan a crowded parent to recover an unverified pre-open leaf", async () => {
const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-bounded-"));
const files = privatePromotionFiles();
const token = `promotion-preopen-bound-1-${"14".repeat(16)}`;
const displaced = path.join(root, `${token}-displaced`);
const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]);
try {
for (let offset = 0; offset < 4_097; offset += 128) {
await Promise.all(
Array.from(
{ length: Math.min(128, 4_097 - offset) },
(_, index) =>
mkdir(
path.join(
root,
`noise-${String(offset + index).padStart(4, "0")}`,
),
),
),
);
}
let failure: unknown;
try {
await publishPrivatePromotionStaging(
root,
{ id: "preopen-bound", attempt: 1 },
files,
() => Buffer.alloc(16, 0x14),
undefined,
undefined,
undefined,
async (stagingRoot) => {
await rename(stagingRoot, displaced);
await mkdir(stagingRoot, { mode: 0o700 });
await writeFile(replacementCanary, "external replacement canary\n");
},
);
} catch (error) {
failure = error;
}
expect(failure).toBeInstanceOf(Error);
expect(failure).not.toBeInstanceOf(AggregateError);
expect((failure as Error).message).toMatch(/staging leaf.*identity/i);
await expect(readdir(displaced)).resolves.toEqual([]);
await expect(readFile(replacementCanary, "utf8")).resolves.toBe(
"external replacement canary\n",
);
} finally {
await rm(root, { recursive: true, force: true });
}
}, 20_000);
it("leaves a non-empty moved original untouched after pre-open mismatch", async () => {
const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-nonempty-"));
const files = privatePromotionFiles();
const token = `promotion-preopen-nonempty-1-${"15".repeat(16)}`;
const displaced = path.join(root, `${token}-displaced`);
const ownedResidual = path.join(displaced, "owned-residual");
const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]);
try {
let failure: unknown;
try {
await publishPrivatePromotionStaging(
root,
{ id: "preopen-nonempty", attempt: 1 },
files,
() => Buffer.alloc(16, 0x15),
undefined,
undefined,
undefined,
async (stagingRoot) => {
await rename(stagingRoot, displaced);
await writeFile(ownedResidual, "owned residual\n");
await mkdir(stagingRoot, { mode: 0o700 });
await writeFile(replacementCanary, "external replacement canary\n");
},
);
} catch (error) {
failure = error;
}
expect(failure).toBeInstanceOf(Error);
expect(failure).not.toBeInstanceOf(AggregateError);
expect((failure as Error).message).toMatch(/staging leaf.*identity/i);
await expect(readFile(ownedResidual, "utf8")).resolves.toBe(
"owned residual\n",
);
await expect(readFile(replacementCanary, "utf8")).resolves.toBe(
"external replacement canary\n",
);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("does not search outside the parent for a moved unverified original", async () => {
const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-missing-"));
const outside = await mkdtemp(path.join(tmpdir(), "promotion-preopen-moved-"));
const files = privatePromotionFiles();
const token = `promotion-preopen-missing-1-${"16".repeat(16)}`;
const displaced = path.join(outside, token);
const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]);
try {
let failure: unknown;
try {
await publishPrivatePromotionStaging(
root,
{ id: "preopen-missing", attempt: 1 },
files,
() => Buffer.alloc(16, 0x16),
undefined,
undefined,
undefined,
async (stagingRoot) => {
await rename(stagingRoot, displaced);
await mkdir(stagingRoot, { mode: 0o700 });
await writeFile(replacementCanary, "external replacement canary\n");
},
);
} catch (error) {
failure = error;
}
expect(failure).toBeInstanceOf(Error);
expect(failure).not.toBeInstanceOf(AggregateError);
expect((failure as Error).message).toMatch(/staging leaf.*identity/i);
await expect(lstat(displaced)).resolves.toEqual(
expect.objectContaining({ dev: expect.any(Number), ino: expect.any(Number) }),
);
await expect(readFile(replacementCanary, "utf8")).resolves.toBe(
"external replacement canary\n",
);
} finally {
await rm(root, { recursive: true, force: true });
await rm(outside, { recursive: true, force: true });
}
});
it("rejects a fresh signed exact-five bundle replayed under a different expected run", async () => {
const fixture = syntheticSignedPromotionBundle();
await expect(
verifyExactPromotionBundle(fixture.files, {
...fixture.verification,
expected: {
...fixture.verification.expected,
run: { id: "different-run", attempt: 1 },
},
}),
).rejects.toThrow(/external expected run.*mismatch|expected promotion run/u);
});
it("requires every external expected identity variable at the exact promotion CLI", async () => {
const fixture = syntheticSignedPromotionBundle();
const root = await mkdtemp(path.join(tmpdir(), "promotion-replay-cli-"));
const bundleRoot = path.join(root, "bundle");
try {
await mkdir(bundleRoot);
for (const [name, bytes] of Object.entries(fixture.files)) {
await writeFile(path.join(bundleRoot, name), bytes);
}
await writeFile(path.join(root, "vulnerability.pem"), fixture.vulnerabilityPem);
await writeFile(path.join(root, "provenance.pem"), fixture.provenancePem);
const cliPath = path.join(process.cwd(), "scripts/verify-exact-promotion-bundle.ts");
const baseEnvironment: NodeJS.ProcessEnv = {
...process.env,
PROMOTION_BUNDLE_ROOT: bundleRoot,
VULNERABILITY_PUBLIC_KEY_PATH: "vulnerability.pem",
VULNERABILITY_KEY_ID: "synthetic-vulnerability",
PROVENANCE_PUBLIC_KEY_PATH: "provenance.pem",
PROVENANCE_KEY_ID: "synthetic-provenance",
EXPECTED_PROMOTION_RUN_ID: fixture.verification.expected.run.id,
EXPECTED_PROMOTION_RUN_ATTEMPT: String(
fixture.verification.expected.run.attempt,
),
EXPECTED_PROMOTION_SOURCE_REVISION:
fixture.verification.expected.sourceRevision,
EXPECTED_PROMOTION_ARCHIVE_SHA256:
fixture.verification.expected.archiveSha256,
};
const requiredExpected = [
"EXPECTED_PROMOTION_RUN_ID",
"EXPECTED_PROMOTION_RUN_ATTEMPT",
"EXPECTED_PROMOTION_SOURCE_REVISION",
"EXPECTED_PROMOTION_ARCHIVE_SHA256",
] as const;
for (const missing of requiredExpected) {
const environment = { ...baseEnvironment };
delete environment[missing];
const result = spawnSync(process.execPath, [cliPath], {
cwd: root,
encoding: "utf8",
env: environment,
});
expect(result.status, missing).not.toBe(0);
expect(result.stderr, missing).toContain(
`exact promotion verification environment is missing ${missing}`,
);
}
for (const [name, value, diagnostic] of [
["EXPECTED_PROMOTION_RUN_ID", "different-run", /external expected run.*mismatch/u],
["EXPECTED_PROMOTION_RUN_ATTEMPT", "2", /external expected run.*mismatch/u],
["EXPECTED_PROMOTION_SOURCE_REVISION", "f".repeat(40), /external expected source revision.*mismatch/u],
["EXPECTED_PROMOTION_ARCHIVE_SHA256", "0".repeat(64), /external expected archive digest.*mismatch/u],
] as const) {
const result = spawnSync(process.execPath, [cliPath], {
cwd: root,
encoding: "utf8",
env: { ...baseEnvironment, [name]: value },
});
expect(result.status, name).not.toBe(0);
expect(result.stderr, name).toMatch(diagnostic);
}
} finally {
await rm(root, { recursive: true, force: true });
}
}, PROCESS_HEAVY_TIMEOUT_MS);
});
@@ -0,0 +1,708 @@
import { generateKeyPairSync } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { EventEmitter } from "node:events";
import { describe, expect, it } from "vitest";
import {
evaluatePromotionEvidence,
providerPublicKeyFingerprint,
validateProviderEvidence,
} from "../../scripts/lib/provider-evidence.ts";
import { readProviderTrust } from "../../scripts/lib/provider-trust.ts";
import { superviseProviderEvidence } from "../../scripts/lib/provider-supervisor.ts";
import { runProviderProcess } from "../../scripts/lib/provider-process-runner.ts";
import { runStageVerifiedPromotionCli } from "../../scripts/lib/stage-verified-promotion-cli.ts";
import type { ReleaseCandidateManifest } from "../../scripts/lib/release-candidate.ts";
import {
digest,
providerExpectedContext,
providerUnsigned,
signedProviderV2,
trust,
} from "./security-followup-fixture.ts";
describe("security provider evidence contracts", () => {
it("accepts signed provider v2 evidence only for the exact run, source, archive, and nonce", () => {
const now = Date.parse("2026-08-02T01:00:00.000Z");
const vulnerabilityKeys = generateKeyPairSync("ed25519");
const provenanceKeys = generateKeyPairSync("ed25519");
const expected = providerExpectedContext();
const vulnerability = signedProviderV2(
{
source: expected.source,
candidate: expected.candidate,
schemaVersion: 2,
evidenceType: "vulnerability-report",
provider: "fixture-vulnerability",
issuedAt: "2026-08-02T01:00:00.000Z",
expiresAt: "2026-08-02T02:00:00.000Z",
run: { ...expected.run, invocationNonce: "1".repeat(64) },
secretScanAttestation: expected.secretScanAttestation,
findings: [],
},
"vulnerability-key",
vulnerabilityKeys.publicKey,
vulnerabilityKeys.privateKey,
);
const provenance = signedProviderV2(
{
source: expected.source,
candidate: expected.candidate,
schemaVersion: 2,
evidenceType: "provenance-attestation",
provider: "fixture-provenance",
signer: "fixture-workload",
issuedAt: "2026-08-02T01:00:00.000Z",
expiresAt: "2026-08-02T02:00:00.000Z",
run: { ...expected.run, invocationNonce: "2".repeat(64) },
subject: { name: "dist", digest: { sha256: expected.candidate.distSha256 } },
},
"provenance-key",
provenanceKeys.publicKey,
provenanceKeys.privateKey,
);
const result = evaluatePromotionEvidence({
expected: {
...expected,
vulnerabilityInvocationNonce: "1".repeat(64),
provenanceInvocationNonce: "2".repeat(64),
},
localStatus: "PASS",
vulnerabilityReport: vulnerability,
provenanceAttestation: provenance,
vulnerabilityTrust: trust("vulnerability-key", vulnerabilityKeys.publicKey),
provenanceTrust: trust("provenance-key", provenanceKeys.publicKey),
nowEpochMs: () => now,
});
expect(result).toEqual({
status: "PASS",
vulnerabilityStatus: "PASS",
provenanceAttestationStatus: "PASS",
failures: [],
});
const replayed = evaluatePromotionEvidence({
expected: {
...expected,
run: { id: expected.run.id, attempt: 2 },
vulnerabilityInvocationNonce: "1".repeat(64),
provenanceInvocationNonce: "2".repeat(64),
},
localStatus: "PASS",
vulnerabilityReport: vulnerability,
provenanceAttestation: provenance,
vulnerabilityTrust: trust("vulnerability-key", vulnerabilityKeys.publicKey),
provenanceTrust: trust("provenance-key", provenanceKeys.publicKey),
nowEpochMs: () => now,
});
expect(replayed.status).toBe("FAIL_UNVERIFIED");
expect(replayed.failures).toEqual(
expect.arrayContaining([
"vulnerability report run identity mismatch",
"provenance attestation run identity mismatch",
]),
);
});
it("rejects a signed vulnerability PASS when the captured SARIF attestation differs", () => {
const keys = generateKeyPairSync("ed25519");
const expected = providerExpectedContext();
const secretScanAttestation = {
status: "PASS" as const,
localEvidenceAssessmentSha256: digest("assessment"),
sourceSetSha256: expected.source.sourceSetSha256,
policySha256: digest("secret policy"),
sarifSha256: digest("real sarif"),
scanInputSha256: digest("scan input"),
};
const report = signedProviderV2(
{
schemaVersion: 2,
evidenceType: "vulnerability-report",
provider: "fixture-vulnerability",
issuedAt: "2026-08-02T01:00:00.000Z",
expiresAt: "2026-08-02T02:00:00.000Z",
run: { ...expected.run, invocationNonce: "1".repeat(64) },
source: expected.source,
candidate: expected.candidate,
secretScanAttestation,
findings: [],
},
"vulnerability-key",
keys.publicKey,
keys.privateKey,
);
const validated = validateProviderEvidence({
kind: "vulnerability",
value: report,
expected: {
...expected,
vulnerabilityInvocationNonce: "1".repeat(64),
provenanceInvocationNonce: "2".repeat(64),
secretScanAttestation: {
...secretScanAttestation,
sarifSha256: digest("forged empty sarif"),
},
},
trust: trust("vulnerability-key", keys.publicKey),
nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"),
});
expect(validated.status).toBe("FAIL_UNVERIFIED");
expect(validated.failures).toContain(
"vulnerability report secret scan attestation mismatch",
);
const forged = structuredClone(report);
forged.secretScanAttestation.sarifSha256 = digest("forged empty sarif");
const forgedValidation = validateProviderEvidence({
kind: "vulnerability",
value: forged,
expected: {
...expected,
vulnerabilityInvocationNonce: "1".repeat(64),
provenanceInvocationNonce: "2".repeat(64),
secretScanAttestation: forged.secretScanAttestation,
},
trust: trust("vulnerability-key", keys.publicKey),
nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"),
});
expect(forgedValidation.failures).toContain(
"vulnerability report signature verification failed",
);
const provenanceKeys = generateKeyPairSync("ed25519");
const provenance = signedProviderV2(
{
schemaVersion: 2,
evidenceType: "provenance-attestation",
provider: "fixture-provenance",
signer: "fixture-workload",
issuedAt: "2026-08-02T01:00:00.000Z",
expiresAt: "2026-08-02T02:00:00.000Z",
run: { ...expected.run, invocationNonce: "2".repeat(64) },
source: expected.source,
candidate: expected.candidate,
subject: { name: "dist", digest: { sha256: expected.candidate.distSha256 } },
},
"provenance-key",
provenanceKeys.publicKey,
provenanceKeys.privateKey,
);
const evaluated = evaluatePromotionEvidence({
expected: {
...expected,
vulnerabilityInvocationNonce: "1".repeat(64),
provenanceInvocationNonce: "2".repeat(64),
secretScanAttestation: {
...secretScanAttestation,
sarifSha256: digest("forged empty sarif"),
},
},
localStatus: "PASS",
vulnerabilityReport: report,
provenanceAttestation: provenance,
vulnerabilityTrust: trust("vulnerability-key", keys.publicKey),
provenanceTrust: trust("provenance-key", provenanceKeys.publicKey),
nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"),
});
expect(evaluated.vulnerabilityStatus).toBe("FAIL_UNVERIFIED");
expect(evaluated.failures).toContain(
"vulnerability report secret scan attestation mismatch",
);
});
it.each(["vulnerability", "provenance"] as const)(
"rejects correctly re-signed %s v2 context/time/replay drift",
(kind) => {
const now = Date.parse("2026-08-02T01:00:00.000Z");
const vulnerabilityKeys = generateKeyPairSync("ed25519");
const provenanceKeys = generateKeyPairSync("ed25519");
const expected = providerExpectedContext();
const baseVulnerability = providerUnsigned("vulnerability", expected);
const baseProvenance = providerUnsigned("provenance", expected);
const validVulnerability = signedProviderV2(
baseVulnerability,
"vulnerability-key",
vulnerabilityKeys.publicKey,
vulnerabilityKeys.privateKey,
);
const validProvenance = signedProviderV2(
baseProvenance,
"provenance-key",
provenanceKeys.publicKey,
provenanceKeys.privateKey,
);
const rawCases: Array<readonly [
string,
(value: Record<string, any>) => Record<string, any>,
RegExp,
]> = [
["schema v1", (value) => ({ ...value, schemaVersion: 1 }), /missing or invalid/u],
[
"evidence type",
(value) => ({
...value,
evidenceType:
kind === "vulnerability"
? "provenance-attestation"
: "vulnerability-report",
}),
/missing or invalid/u,
],
...(["archiveSha256", "bundleSha256", "distSha256", "lockfileSha256"] as const).map(
(field) => [
`candidate ${field}`,
(value: Record<string, any>) => ({
...value,
candidate: { ...value.candidate, [field]: "f".repeat(64) },
...(kind === "provenance" && field === "distSha256"
? {
subject: {
name: "dist",
digest: { sha256: "f".repeat(64) },
},
}
: {}),
}),
/candidate identity|subject dist/u,
] as const,
),
[
"different archive with same dist and lockfile",
(value) => ({
...value,
candidate: { ...value.candidate, archiveSha256: "e".repeat(64) },
}),
/candidate identity/u,
],
[
"source revision",
(value) => ({ ...value, source: { ...value.source, revision: "c".repeat(40) } }),
/source identity/u,
],
[
"source set",
(value) => ({ ...value, source: { ...value.source, sourceSetSha256: "c".repeat(64) } }),
/source identity/u,
],
[
"run id",
(value) => ({ ...value, run: { ...value.run, id: "other-run" } }),
/run identity/u,
],
[
"run attempt replay",
(value) => ({ ...value, run: { ...value.run, attempt: 2 } }),
/run identity/u,
],
[
"different nonce",
(value) => ({ ...value, run: { ...value.run, invocationNonce: "3".repeat(64) } }),
/invocation nonce/u,
],
[
"missing nonce",
(value) => {
const run = { ...value.run };
delete run.invocationNonce;
return { ...value, run };
},
/missing or invalid/u,
],
[
"uppercase nonce",
(value) => ({ ...value, run: { ...value.run, invocationNonce: "A".repeat(64) } }),
/missing or invalid/u,
],
[
"short nonce",
(value) => ({ ...value, run: { ...value.run, invocationNonce: "1".repeat(62) } }),
/missing or invalid/u,
],
[
"issued future boundary",
(value) => ({ ...value, issuedAt: "2026-08-02T01:05:00.001Z" }),
/future skew/u,
],
[
"expiry equality",
(value) => ({ ...value, expiresAt: "2026-08-02T01:00:00.000Z" }),
/expired/u,
],
[
"expiry past",
(value) => ({ ...value, expiresAt: "2026-08-02T00:59:59.999Z" }),
/expired/u,
],
[
"zero lifetime",
(value) => ({
...value,
issuedAt: "2026-08-02T01:01:00.000Z",
expiresAt: "2026-08-02T01:01:00.000Z",
}),
/not positive/u,
],
[
"negative lifetime",
(value) => ({
...value,
issuedAt: "2026-08-02T01:02:00.000Z",
expiresAt: "2026-08-02T01:01:59.999Z",
}),
/not positive/u,
],
[
"lifetime above two hours",
(value) => ({
...value,
issuedAt: "2026-08-02T01:00:00.000Z",
expiresAt: "2026-08-02T03:00:00.001Z",
}),
/exceeds two hours/u,
],
[
"wrong fingerprint",
(value) => ({
...value,
signature: {
...value.signature,
publicKeyFingerprint: `sha256:${"d".repeat(64)}`,
},
}),
/trust identity/u,
],
];
const cases = rawCases.map(([name, mutate, failure]) => ({
name,
mutate,
failure,
}));
for (const testCase of cases) {
const base = kind === "vulnerability" ? baseVulnerability : baseProvenance;
const mutated = testCase.mutate(structuredClone(base));
const resigned = signedProviderV2(
mutated,
kind === "vulnerability" ? "vulnerability-key" : "provenance-key",
kind === "vulnerability" ? vulnerabilityKeys.publicKey : provenanceKeys.publicKey,
kind === "vulnerability" ? vulnerabilityKeys.privateKey : provenanceKeys.privateKey,
"signature" in mutated && mutated.signature?.publicKeyFingerprint
? mutated.signature.publicKeyFingerprint
: undefined,
);
const result = evaluatePromotionEvidence({
expected: {
...expected,
vulnerabilityInvocationNonce: "1".repeat(64),
provenanceInvocationNonce: "2".repeat(64),
},
localStatus: "PASS",
vulnerabilityReport:
kind === "vulnerability" ? resigned : validVulnerability,
provenanceAttestation:
kind === "provenance" ? resigned : validProvenance,
vulnerabilityTrust: trust("vulnerability-key", vulnerabilityKeys.publicKey),
provenanceTrust: trust("provenance-key", provenanceKeys.publicKey),
nowEpochMs: () => now,
});
expect(result.status, testCase.name).toBe("FAIL_UNVERIFIED");
expect(result.failures.join("\n"), testCase.name).toMatch(testCase.failure);
}
},
);
it("canonicalizes provider fingerprints from DER SPKI across PEM wrapping and rejects Ed448", async () => {
const root = await mkdtemp(path.join(tmpdir(), "provider-fingerprint-"));
try {
const ed25519 = generateKeyPairSync("ed25519").publicKey;
const pem = ed25519.export({ type: "spki", format: "pem" }).toString();
const body = pem.replace(/-----[^-]+-----|\s/gu, "");
const wrapped = (width: number) =>
`-----BEGIN PUBLIC KEY-----\n${body.match(new RegExp(`.{1,${width}}`, "gu"))!.join("\n")}\n-----END PUBLIC KEY-----\n`;
await writeFile(path.join(root, "a.pem"), wrapped(64));
await writeFile(path.join(root, "b.pem"), wrapped(32));
const first = await readProviderTrust(root, "a.pem", "fixture-key");
const second = await readProviderTrust(root, "b.pem", "fixture-key");
expect(first?.publicKeyFingerprint).toBe(providerPublicKeyFingerprint(ed25519));
expect(second?.publicKeyFingerprint).toBe(first?.publicKeyFingerprint);
const ed448 = generateKeyPairSync("ed448").publicKey;
await writeFile(root + "/ed448.pem", ed448.export({ type: "spki", format: "pem" }));
await expect(readProviderTrust(root, "ed448.pem", "fixture-key")).resolves.toBeNull();
expect(() => providerPublicKeyFingerprint(ed448)).toThrow(/must be Ed25519/u);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("captures the downloaded archive pathname exactly once in the provider supervisor", async () => {
const keys = generateKeyPairSync("ed25519");
const expected = providerExpectedContext();
let captureCount = 0;
let receivedEnvironment: Readonly<Record<string, string>> | undefined;
const manifest: ReleaseCandidateManifest = {
schemaVersion: 1,
distSha256: expected.candidate.distSha256,
lockfileSha256: expected.candidate.lockfileSha256,
bundleSha256: expected.candidate.bundleSha256,
files: [{ path: "pnpm-lock.yaml", bytes: 1, sha256: expected.candidate.lockfileSha256 }],
};
const result = await superviseProviderEvidence(
{
kind: "vulnerability",
archivePath: "/downloads/candidate.tar.gz",
expectedArchiveSha256: expected.candidate.archiveSha256,
expectedRun: {
id: expected.run.id,
attempt: expected.run.attempt,
sourceRevision: expected.source.revision,
},
trust: trust("vulnerability-key", keys.publicKey),
executeProvider: async ({ environment }) => {
receivedEnvironment = environment;
},
captureReport: async () => Buffer.from("{}\n"),
},
{
captureArchive: async (input) => {
captureCount += 1;
expect(input).toEqual({
archivePath: "/downloads/candidate.tar.gz",
expectedSha256: expected.candidate.archiveSha256,
});
return {
bytes: Buffer.from("captured archive"),
archiveSha256: expected.candidate.archiveSha256,
};
},
withVerifiedCandidate: (async (input: any) =>
input.verify({ extractionRoot: "/captured/extraction", manifest })) as any,
verifyLocalEvidence: async () => ({
status: "PASS",
identity: {
sourceRevision: expected.source.revision,
sourceSetSha256: expected.source.sourceSetSha256,
assessmentSha256: digest("assessment"),
secretScan: {
policySha256: digest("provider secret policy"),
sarifSha256: digest("provider secret sarif"),
scanInputSha256: digest("provider secret input"),
},
},
failures: [],
}),
validateUpload: (async (input: any) => {
expect("archivePath" in input).toBe(false);
return { sealed: true };
}) as any,
randomBytes: () => Buffer.alloc(32, 0x11),
nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"),
},
);
expect(captureCount).toBe(1);
expect(receivedEnvironment).toEqual(
expect.objectContaining({
PROVIDER_EVIDENCE_SCHEMA_VERSION: "2",
PROVIDER_INVOCATION_NONCE: "11".repeat(32),
PROVIDER_ISSUED_AT: "2026-08-02T01:00:00.000Z",
PROVIDER_EXPIRES_AT: "2026-08-02T02:00:00.000Z",
CI_RUN_ID: expected.run.id,
CI_RUN_ATTEMPT: "1",
SOURCE_REVISION: expected.source.revision,
CANDIDATE_ARCHIVE_SHA256: expected.candidate.archiveSha256,
}),
);
expect(result.evidence).toEqual({ sealed: true });
});
it("samples provider freshness after report capture instead of reusing issuance time", async () => {
const keys = generateKeyPairSync("ed25519");
const expected = providerExpectedContext();
const manifest: ReleaseCandidateManifest = {
schemaVersion: 1,
distSha256: expected.candidate.distSha256,
lockfileSha256: expected.candidate.lockfileSha256,
bundleSha256: expected.candidate.bundleSha256,
files: [{ path: "pnpm-lock.yaml", bytes: 1, sha256: expected.candidate.lockfileSha256 }],
};
const issuedSample = Date.parse("2026-08-02T01:00:00.000Z");
const validationSample = Date.parse("2026-08-02T02:00:00.001Z");
const samples = [issuedSample, validationSample];
let issuedAt = "";
await expect(
superviseProviderEvidence(
{
kind: "vulnerability",
archivePath: "/downloads/candidate.tar.gz",
expectedArchiveSha256: expected.candidate.archiveSha256,
expectedRun: {
id: expected.run.id,
attempt: expected.run.attempt,
sourceRevision: expected.source.revision,
},
trust: trust("vulnerability-key", keys.publicKey),
executeProvider: async ({ environment }) => {
issuedAt = environment.PROVIDER_ISSUED_AT!;
},
captureReport: async () => Buffer.from("{}\n"),
},
{
captureArchive: async () => ({
bytes: Buffer.from("captured archive"),
archiveSha256: expected.candidate.archiveSha256,
}),
withVerifiedCandidate: (async (input: any) =>
input.verify({ extractionRoot: "/captured/extraction", manifest })) as any,
verifyLocalEvidence: async () => ({
status: "PASS",
identity: {
sourceRevision: expected.source.revision,
sourceSetSha256: expected.source.sourceSetSha256,
assessmentSha256: digest("assessment"),
secretScan: {
policySha256: digest("provider secret policy"),
sarifSha256: digest("provider secret sarif"),
scanInputSha256: digest("provider secret input"),
},
},
failures: [],
}),
validateUpload: (async (input: any) => {
expect(input.nowEpochMs()).toBe(validationSample);
throw new Error("provider report expired during execution");
}) as any,
randomBytes: () => Buffer.alloc(32, 0x33),
nowEpochMs: () => samples.shift()!,
},
),
).rejects.toThrow(/expired during execution/u);
expect(issuedAt).toBe("2026-08-02T01:00:00.000Z");
});
it("kills a timed-out provider but settles only after the child closes", async () => {
const child = new EventEmitter() as EventEmitter & {
kill(signal: NodeJS.Signals): boolean;
};
let killedWith: NodeJS.Signals | undefined;
child.kill = (signal) => {
killedWith = signal;
return true;
};
let fireTimeout: (() => void) | undefined;
let settled = false;
const running = runProviderProcess(
{ executable: "/usr/bin/bwrap", arguments: [], environment: {}, timeoutMs: 1 },
{
spawnChild: () => child as any,
setTimer: (callback) => {
fireTimeout = callback;
return 1 as any;
},
clearTimer: () => undefined,
},
).finally(() => {
settled = true;
});
fireTimeout?.();
await Promise.resolve();
expect(killedWith).toBe("SIGKILL");
expect(settled).toBe(false);
child.emit("close", null, "SIGKILL");
await expect(running).rejects.toThrow(/timed out/u);
expect(settled).toBe(true);
});
it("captures process-group kill errors, attempts child fallback, and settles after close", async () => {
const child = new EventEmitter() as EventEmitter & {
pid: number;
kill(signal: NodeJS.Signals): boolean;
};
child.pid = 12_346;
let fallbackSignal: NodeJS.Signals | undefined;
child.kill = (signal) => {
fallbackSignal = signal;
return true;
};
let fireTimeout: (() => void) | undefined;
const running = runProviderProcess(
{ executable: "/usr/bin/bwrap", arguments: [], environment: {}, timeoutMs: 1 },
{
spawnChild: () => child as any,
setTimer: (callback) => {
fireTimeout = callback;
return 1 as any;
},
clearTimer: () => undefined,
killProcessGroup: () => {
throw Object.assign(new Error("group kill denied"), { code: "EPERM" });
},
},
);
expect(() => fireTimeout?.()).not.toThrow();
expect(fallbackSignal).toBe("SIGKILL");
child.emit("close", null, "SIGKILL");
await expect(running).rejects.toThrow(/timed out.*kill failed.*close/u);
});
it.each(["open failure", "partial write failure"])(
"cleans finalized staging from memory when GITHUB_OUTPUT has a %s",
async (failureKind) => {
const finalized = {
stagingRoot: "/runner/promotion-run-1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
cleanupToken: "promotion-run-1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
runnerTempIdentity: { dev: 10, ino: 20 },
stagingIdentity: { dev: 30, ino: 40 },
files: [],
} as const;
let cleanupInput: unknown;
let appendCalls = 0;
const environment = {
CANDIDATE_ARCHIVE_PATH: "candidate.tar.gz",
CANDIDATE_ARCHIVE_SHA256: "a".repeat(64),
VULNERABILITY_REPORT_PATH: "vulnerability.json",
PROVENANCE_ATTESTATION_PATH: "provenance.json",
VULNERABILITY_PUBLIC_KEY_PATH: "vulnerability.pem",
VULNERABILITY_KEY_ID: "vulnerability-key",
PROVENANCE_PUBLIC_KEY_PATH: "provenance.pem",
PROVENANCE_KEY_ID: "provenance-key",
CI_RUN_ID: "run",
CI_RUN_ATTEMPT: "1",
VITE_COMMIT_SHA: "b".repeat(40),
VULNERABILITY_INVOCATION_NONCE: "c".repeat(64),
PROVENANCE_INVOCATION_NONCE: "d".repeat(64),
RUNNER_TEMP: "/runner",
GITHUB_OUTPUT: "/runner/github-output",
};
await expect(
runStageVerifiedPromotionCli(environment, {
cwd: () => "/workspace",
finalize: async () => finalized as any,
appendOutput: async () => {
appendCalls += 1;
if (failureKind === "partial write failure") {
// The output sink accepted an unspecified prefix before rejecting.
}
throw new Error(failureKind);
},
cleanup: async (input) => {
cleanupInput = input;
},
writeStdout: () => undefined,
}),
).rejects.toThrow(new RegExp(failureKind, "u"));
expect(appendCalls).toBe(1);
expect(cleanupInput).toEqual({
runnerTempRoot: "/runner",
stagingRoot: finalized.stagingRoot,
cleanupToken: finalized.cleanupToken,
runnerTempIdentity: finalized.runnerTempIdentity,
stagingIdentity: finalized.stagingIdentity,
});
},
);
});
@@ -190,9 +190,11 @@ describe("selective Task 3 contract closure", () => {
// FE-GATE-007, bringing the totals to 84/96/130. The dev release manifest
// drift fix added `check-dev-release-manifest` to FE-GATE-010: 85/97/130.
expect(canonical.gates).toHaveLength(27);
expect(canonical.commands).toHaveLength(85);
expect(canonical.gates.reduce((sum, gate) => sum + gate.commandIds.length, 0)).toBe(97);
expect(canonical.artifacts).toHaveLength(139);
// Template sync (ebea300). Recomputed from the merged config/ci/gates.json:
// neither 85/97/139 (this product) nor 91/103/109 (the template) describes it.
expect(canonical.commands).toHaveLength(94);
expect(canonical.gates.reduce((sum, gate) => sum + gate.commandIds.length, 0)).toBe(106);
expect(canonical.artifacts).toHaveLength(141);
expect(canonical.stages).toHaveLength(5);
expect(canonical.retention.classes).toHaveLength(5);