Carries 359 template commits, tag v0.2.0 plus one documentation commit: the generator-built feature index with its app, bounded-context and feature declarations, the src/platform kernel and scale tooling, the 2026-09-24 src review fixes, and the 2026-09-25 maturity review round with its CHANGELOG [보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them merged with product changes; 127 are not carried. Product identity is unchanged: name, version 0.1.0, routes, design and the TechLog domain. Three decisions worth naming. TechLog stays composed directly, as the last two syncs recorded; its directory carries a NOT_INSTALLED marker that says so, and every installed-* composer takes the template's projection with TechLog added on top. The reference sample is no longer installed: the template now installs a feature only through feature-module.ts and context-routes.ts, which load the screens this product deleted, so its three operations, six schemas and one topic leave the registries, recorded as registry change evidence. And AppRouter mounts the platform and TechLog routes only; the template's bounded-context route gateway waits for a generator-installed feature. Required fixes: readSubject on the BFF session owner (without it every HTTP Studio session would close as integration-failed), zod through the facade in nine TechLog files, noUnusedLocals, and public/config.json written out to match the local profile. Derived baselines were recomputed after reproducing both sides' values: CI contract 101 commands / 106 references / 141 artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime config schema baseline equals the schema at8210d48. Verified here: types, lint, architecture, adapter inventory, CI contract, i18n, design system, diagnostics, browser security, dev release manifest, TechLog contract and build pass; 220 component, 155 integration, 15 contract, 418 TechLog, 43 reference-feature, 18 recipe and 46 release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at8210d48first and unchanged: check:registries (byte-identical), test:runtime-schema, verify:documentation. Brought by the template and escalated rather than suppressed: check:request-fanout on TechLog's cursor pagination, check:remediation-ledger (fails upstream too), the shared-chunk hash test, and the registry-dependent sample removal and second-feature tests. Playwright suites were not run. Full record, the five open questions and the follow-ups in docs/operations/template-sync-2026-09-29.md. (cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
880 lines
28 KiB
TypeScript
880 lines
28 KiB
TypeScript
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 {
|
|
CONTROL_ENDPOINT,
|
|
DATA_ORIGIN,
|
|
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();
|
|
});
|
|
}
|
|
|
|
// Q-6.1-11. The duplicate check read the issuer's object again after the
|
|
// snapshot, so a stateful object could show it a receipt the vault had
|
|
// never stored while the snapshot carried one it already held.
|
|
it("checks a duplicate receipt against the snapshot, not the issuer's object", () => {
|
|
const vault = freshVault();
|
|
expect(vault.register(baseRegistration() as never).ok).toBe(true);
|
|
const replay = new Proxy(baseRegistration(), {
|
|
get(target, key, receiver) {
|
|
return key === "capabilityReceipt"
|
|
? "capability-never-registered"
|
|
: Reflect.get(target, key, receiver);
|
|
},
|
|
});
|
|
expect(vault.register(replay as never)).toMatchObject({
|
|
ok: false,
|
|
error: { code: "CONFLICT", recovery: "REISSUE_CAPABILITY" },
|
|
});
|
|
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("ends a pending read when only the stream consumer signal aborts", async () => {
|
|
// R3-2 characterization: the consumer signal is composed into the read
|
|
// scope separately from the owner signal, which stays live here.
|
|
const bytes = new Uint8Array([1]);
|
|
const payload = downloadCapabilityPayload(bytes);
|
|
let cancelled = false;
|
|
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
|
|
String(input) === CONTROL_ENDPOINT
|
|
? jsonResponse(payload)
|
|
: downloadResponse(
|
|
new ReadableStream<Uint8Array>({
|
|
pull() {},
|
|
cancel() {
|
|
cancelled = true;
|
|
},
|
|
}),
|
|
payload,
|
|
),
|
|
) as unknown as typeof fetch;
|
|
const harness = createHarness({ fetcher });
|
|
const owner = new AbortController();
|
|
const issued = await harness.provider.issueDownload({
|
|
resourceId: "resource-1",
|
|
signal: owner.signal,
|
|
});
|
|
expect(issued.ok).toBe(true);
|
|
if (!issued.ok) return;
|
|
const opened = await harness.executor.downloadSources.open({
|
|
resourceId: "resource-1",
|
|
capability: issued.value,
|
|
signal: owner.signal,
|
|
});
|
|
expect(opened.ok).toBe(true);
|
|
if (!opened.ok) return;
|
|
const consumer = new AbortController();
|
|
const pending = collect(opened.value, consumer.signal);
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
consumer.abort("consumer");
|
|
expect(await pending).toMatchObject([
|
|
{ ok: false, error: { code: "ABORTED" } },
|
|
]);
|
|
expect(owner.signal.aborted).toBe(false);
|
|
expect(cancelled).toBe(true);
|
|
});
|
|
|
|
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" },
|
|
});
|
|
// 01-07. The refused open released the capability from the vault.
|
|
expect(
|
|
await executor.downloadSources.open({
|
|
resourceId: "resource-1",
|
|
capability: issuedDownload.value,
|
|
signal: new AbortController().signal,
|
|
}),
|
|
).toMatchObject({ ok: false, error: { code: "POLICY_REJECTED" } });
|
|
const reissuedDownload = await provider.issueDownload({
|
|
resourceId: "resource-1",
|
|
signal: new AbortController().signal,
|
|
});
|
|
expect(reissuedDownload.ok).toBe(true);
|
|
if (!reissuedDownload.ok) return;
|
|
const opened = await executor.downloadSources.open({
|
|
resourceId: "resource-1",
|
|
capability: reissuedDownload.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" },
|
|
});
|
|
});
|
|
|
|
});
|
|
|
|
describe("presigned transfer time limits (01-03)", () => {
|
|
async function openDownload(
|
|
bytes: Uint8Array,
|
|
pull: (controller: ReadableStreamDefaultController<Uint8Array>) => Promise<void> | void,
|
|
options: Readonly<{ minTransferBytesPerSecond: number; idleTimeoutMs?: number }>,
|
|
) {
|
|
const payload = downloadCapabilityPayload(bytes);
|
|
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
|
|
String(input) === CONTROL_ENDPOINT
|
|
? jsonResponse(payload)
|
|
: downloadResponse(new ReadableStream<Uint8Array>({ pull }), payload),
|
|
) as unknown as typeof fetch;
|
|
const harness = createHarness({ fetcher, ...options });
|
|
const issued = await harness.provider.issueDownload({
|
|
resourceId: "resource-1",
|
|
signal: new AbortController().signal,
|
|
});
|
|
if (!issued.ok) throw new Error("issue failed");
|
|
const opened = await harness.executor.downloadSources.open({
|
|
resourceId: "resource-1",
|
|
capability: issued.value,
|
|
signal: new AbortController().signal,
|
|
});
|
|
if (!opened.ok) throw new Error("open failed");
|
|
return opened.value;
|
|
}
|
|
|
|
it("keeps a slow but progressing download past the base deadline", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const bytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
|
|
let offset = 0;
|
|
// Two bytes every 3 s: 12 s in total against a 5 s base deadline.
|
|
const source = await openDownload(
|
|
bytes,
|
|
async (controller) => {
|
|
await new Promise((resolve) => setTimeout(resolve, 3_000));
|
|
controller.enqueue(bytes.slice(offset, offset + 2));
|
|
offset += 2;
|
|
if (offset >= bytes.byteLength) controller.close();
|
|
},
|
|
{ minTransferBytesPerSecond: 1 },
|
|
);
|
|
const pending = collect(source);
|
|
await vi.advanceTimersByTimeAsync(12_500);
|
|
const results = await pending;
|
|
|
|
expect(results.every((result) => result.ok)).toBe(true);
|
|
expect(results).toHaveLength(4);
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it("ends a download whose stream stops making progress at the idle limit", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const bytes = new Uint8Array([1, 2, 3, 4]);
|
|
let pulls = 0;
|
|
const source = await openDownload(
|
|
bytes,
|
|
(controller) => {
|
|
pulls += 1;
|
|
if (pulls === 1) controller.enqueue(bytes.slice(0, 2));
|
|
// Then the connection stalls: no more chunks, no close.
|
|
return pulls === 1 ? undefined : new Promise<void>(() => {});
|
|
},
|
|
{ minTransferBytesPerSecond: 1, idleTimeoutMs: 2_000 },
|
|
);
|
|
let settled = false;
|
|
const pending = collect(source).finally(() => {
|
|
settled = true;
|
|
});
|
|
await vi.advanceTimersByTimeAsync(1_900);
|
|
expect(settled).toBe(false);
|
|
await vi.advanceTimersByTimeAsync(200);
|
|
expect(settled).toBe(true);
|
|
|
|
expect((await pending).at(-1)).toMatchObject({
|
|
ok: false,
|
|
error: { code: "UNAVAILABLE", recovery: "REISSUE_CAPABILITY" },
|
|
});
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it("extends a PUT deadline by the part's byte allowance", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const original = new Uint8Array(60).fill(7);
|
|
const checksum = sha256Hex(original);
|
|
const payload = uploadCapabilityPayload({ bytes: original, checksum });
|
|
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
|
|
if (String(input) === CONTROL_ENDPOINT) return jsonResponse(payload);
|
|
// 30 ms past the 5 s base deadline; 60 bytes at 1000 B/s allow 60 ms.
|
|
await new Promise((resolve) => setTimeout(resolve, 5_030));
|
|
return responseWithUrl(
|
|
new Response(null, {
|
|
status: 200,
|
|
headers: {
|
|
[POLICY_HEADER]: "v1",
|
|
"Content-Length": "0",
|
|
ETag: "\"part-etag-slow\"",
|
|
},
|
|
}),
|
|
String(payload.href),
|
|
);
|
|
}) as unknown as typeof fetch;
|
|
const { provider, executor } = createHarness({
|
|
fetcher,
|
|
minTransferBytesPerSecond: 1_000,
|
|
digestBytes: async (bytes) => 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,
|
|
});
|
|
if (!issued.ok) throw new Error("issue failed");
|
|
const pending = executor.uploadParts.put({
|
|
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,
|
|
});
|
|
await vi.advanceTimersByTimeAsync(5_040);
|
|
|
|
expect(await pending).toMatchObject({
|
|
ok: true,
|
|
value: { receiptToken: "part-etag-slow" },
|
|
});
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
});
|