fix: validate the snapshot that installs, not the object that was shown

Three trust boundaries checked a caller's object and then read it again to
use it. Between those two reads an accessor or a Proxy can answer
differently, so the value that passed validation and the value that was
installed were not the same value.

A credential owner's answer was read field by field outside the auth
boundary: a throwing `kind` getter escaped into the transport catch and an
auth outage reached operators as `NETWORK_FAILURE`. Contract composition
validated a contribution and then copied it, so a policy that answered
10,000 to the ceiling check and 999,999 to the copy installed the second
value. The cursor runtime validated its profile once and re-read it on
every page, so raising `maxPages` after construction widened a cap that
had already been checked.

`src/contracts/exact-snapshot.ts` is the one descriptor-based decoder they
now share: every property is read exactly once, an accessor, a symbol, an
inherited or non-enumerable field and a throwing trap all resolve to a
typed failure, and validation runs on the owned copy.

Separately, the `responseBody: NONE` probe awaited a bare `read()`. The
deadline produced a bounded public result while the raw reader kept its
lease, so the body stayed locked and the outer compensator could not
cancel it. The probe now takes the operation lifetime and owns the cancel
and the lock release itself.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-08-15 01:25:12 +09:00
co-authored by Claude Opus 5
parent cc91fc6ae0
commit df18349682
12 changed files with 943 additions and 79 deletions
@@ -71,7 +71,6 @@ describe("HTTP operation execution contract", () => {
const attachCredentials = vi.fn(() => ({
kind: "READY" as const,
headers: {},
credentials: "omit" as const,
}));
const observedKeys: Array<string | null> = [];
const fetcher = vi.fn(
@@ -99,6 +99,188 @@ describe("LIVE-01 credential integration failures are not user session failures"
});
}
/**
* NS-01. Reading `patch.kind` and `patch.headers` off the raw answer put the
* credential decode outside the auth boundary: a throwing getter escaped into
* the transport catch and the outage was reported as `NETWORK_FAILURE`, so
* the operator saw a network incident instead of an auth integration one.
*/
const hostileOwners = [
{
label: "exposes a throwing kind getter",
attach: () =>
Object.defineProperty({}, "kind", {
enumerable: true,
get() {
throw new TypeError("hostile kind getter");
},
}) as never,
},
{
label: "exposes a throwing headers getter",
attach: () =>
Object.defineProperty({ kind: "READY" }, "headers", {
enumerable: true,
get() {
throw new TypeError("hostile headers getter");
},
}) as never,
},
{
label: "throws from an ownKeys trap",
attach: () =>
new Proxy(
{ kind: "READY", headers: { authorization: "Bearer ok" } },
{
ownKeys() {
throw new TypeError("hostile ownKeys trap");
},
},
) as never,
},
{
label: "throws from a getOwnPropertyDescriptor trap",
attach: () =>
new Proxy(
{ kind: "READY", headers: { authorization: "Bearer ok" } },
{
getOwnPropertyDescriptor() {
throw new TypeError("hostile descriptor trap");
},
},
) as never,
},
{
label: "carries the outcome only on its prototype",
attach: () =>
Object.create({
kind: "READY",
headers: { authorization: "Bearer ok" },
}) as never,
},
{
label: "carries an extra own field",
attach: () =>
Object.freeze({
kind: "READY",
headers: Object.freeze({ authorization: "Bearer ok" }),
injected: true,
}) as never,
},
{
label: "carries a symbol field",
attach: () =>
Object.freeze({
kind: "READY",
headers: Object.freeze({ authorization: "Bearer ok" }),
[Symbol.for("injected")]: true,
}) as never,
},
{
label: "hides the outcome behind a non-enumerable own field",
attach: () =>
Object.defineProperties(
{ kind: "READY" },
{
headers: {
enumerable: false,
value: { authorization: "Bearer ok" },
},
},
) as never,
},
];
for (const owner of hostileOwners) {
it(`closes as AUTH_INTEGRATION_FAILURE when the owner ${owner.label}`, async () => {
const fetcher = vi.fn(async () => jsonResponse([]));
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
authProfiles: TEST_PROFILES,
attachCredentials: owner.attach,
fetcher: fetcher as unknown as typeof fetch,
});
const outcome = await executor.execute(
bearerOperation(),
{ limit: 1 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect(outcome.kind).toBe("AUTH_INTEGRATION_FAILURE");
expect(outcome.effect).toBe("NOT_APPLICABLE");
expect(fetcher).toHaveBeenCalledTimes(0);
});
}
it("reads each field exactly once so a stateful answer cannot swap it", async () => {
const fetcher = vi.fn(async () => jsonResponse([]));
const kindReads: string[] = [];
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
authProfiles: TEST_PROFILES,
attachCredentials: () =>
new Proxy(
{ kind: "READY", headers: { authorization: "Bearer first" } },
{
getOwnPropertyDescriptor(target, key) {
if (key === "kind") {
kindReads.push(key);
return {
configurable: true,
enumerable: true,
// A second read would answer with a different verdict.
value: kindReads.length > 1 ? "UNAUTHENTICATED" : "READY",
};
}
return Reflect.getOwnPropertyDescriptor(target, key);
},
},
) as never,
fetcher: fetcher as unknown as typeof fetch,
});
const outcome = await executor.execute(
bearerOperation(),
{ limit: 1 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect(outcome.kind).toBe("SUCCESS");
expect(kindReads).toHaveLength(1);
});
it("sends an owned header snapshot rather than the owner's live object", async () => {
const headers: Record<string, string> = { authorization: "Bearer first" };
let sentHeaders: Record<string, string> | undefined;
const fetcher = vi.fn(async (_url: unknown, init?: RequestInit) => {
sentHeaders = init?.headers as Record<string, string>;
return jsonResponse([]);
});
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
authProfiles: TEST_PROFILES,
// The owner keeps a live reference to the object it handed over.
attachCredentials: () => ({ kind: "READY", headers }) as never,
fetcher: fetcher as unknown as typeof fetch,
});
const outcome = await executor.execute(
bearerOperation(),
{ limit: 1 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect(outcome.kind).toBe("SUCCESS");
headers.authorization = "Bearer swapped";
expect(sentHeaders?.["Authorization"] ?? sentHeaders?.["authorization"]).toBe(
"Bearer first",
);
});
it("still reports a real absent session as UNAUTHENTICATED", async () => {
const fetcher = vi.fn(async () => jsonResponse([]));
const executor = createContractHttpExecutor({
@@ -153,6 +335,61 @@ describe("LIVE-04 the total deadline owns every physical wait", () => {
).toBe("TIMEOUT");
});
/**
* NS-03. The `NONE` probe used to await `reader.read()` with no signal, so a
* deadline produced a bounded public result while the raw reader kept its
* lease on the body: the connection and the buffer stayed held after the
* operation had already ended.
*/
it("cancels and releases the NONE probe reader when the deadline owns the execution", async () => {
let pulls = 0;
let cancels = 0;
const neverEndingBody = new ReadableStream<Uint8Array>({
pull() {
pulls += 1;
return new Promise<void>(() => {});
},
cancel() {
cancels += 1;
},
});
const response = new Response(neverEndingBody, { status: 200 });
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
authProfiles: TEST_PROFILES,
attachCredentials: () =>
Object.freeze({
kind: "READY" as const,
headers: { authorization: "Bearer t" },
}),
fetcher: (async () => response) as unknown as typeof fetch,
});
const noBodyOperation = {
...bearerOperation(20),
contract: {
...bearerOperation(20).contract,
responseBody: "NONE" as const,
},
};
const outcome = await executor.execute(
noBodyOperation as never,
{ limit: 1 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect(outcome.kind).toBe("TRANSPORT_FAILURE");
expect(
outcome.kind === "TRANSPORT_FAILURE" ? outcome.failure.kind : null,
).toBe("TIMEOUT");
expect(pulls).toBe(1);
await vi.waitFor(() => {
expect(cancels).toBe(1);
});
expect(response.body?.locked).toBe(false);
});
it("does not wait for a non-cooperative body reader past the deadline", async () => {
const neverEndingBody = new ReadableStream<Uint8Array>({
pull() {
@@ -106,7 +106,6 @@ describe("V3 HTTP observability projection", () => {
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
credentials: "omit" as const,
}),
fetcher: testCase.fetcher,
observe: sinks.projector,
@@ -152,7 +151,6 @@ describe("V3 HTTP observability projection", () => {
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
credentials: "omit" as const,
}),
fetcher: (async () => {
throw new TypeError("network down");
@@ -195,7 +193,6 @@ describe("V3 HTTP observability projection", () => {
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
credentials: "omit" as const,
}),
fetcher: (async () =>
Response.json([{ id: "a", name: "A" }])) as unknown as typeof fetch,
@@ -221,7 +218,6 @@ describe("V3 HTTP observability projection", () => {
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
credentials: "omit" as const,
}),
fetcher: (async () =>
Response.json([{ id: "a", name: "A" }])) as unknown as typeof fetch,
@@ -288,7 +284,6 @@ describe("V3 HTTP observability projection", () => {
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
credentials: "omit" as const,
}),
fetcher: (async () =>
Response.json({ id: "created", name: "Created" }, {