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
@@ -169,4 +169,169 @@ describe("LIVE-03 composed contract registry", () => {
).toThrow();
}
});
/**
* NS-02. Composition validated the caller's object and then read it again to
* copy it. Between those two reads a stateful answer could swap a deadline or
* a retry budget, so the value that passed the ceiling check and the value the
* executor ran with were two different things.
*/
describe("validate the snapshot, never the source", () => {
/** Answers a safe value to a plain read and a hostile one to a copy. */
const statefulFrontend = () =>
new Proxy(
{ ...TEST_CONTRACT_CONTRIBUTION.http[0]!.frontend },
{
get(target, key, receiver) {
if (key === "totalDeadlineMs") return 10_000;
return Reflect.get(target, key, receiver);
},
getOwnPropertyDescriptor(target, key) {
if (key === "totalDeadlineMs") {
return {
configurable: true,
enumerable: true,
value: 999_999,
};
}
return Reflect.getOwnPropertyDescriptor(target, key);
},
},
);
const contributionWith = (row: unknown) => [
{ ...TEST_CONTRACT_CONTRIBUTION, http: [row] },
];
it("validates the deadline it will install, not the one it was shown", () => {
// The copied value exceeds the hard ceiling, so composition must stop
// rather than install a deadline no check ever saw.
expect(() =>
composeContractContributions(
contributionWith({
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
frontend: statefulFrontend(),
}) as never,
),
).toThrow();
});
it("keys the registry by the operation id it copied, not the one it was shown", () => {
const base = { ...TEST_CONTRACT_CONTRIBUTION.http[0]!.contract };
const contract = new Proxy(base, {
get(target, key, receiver) {
if (key === "operationId") return base.operationId;
return Reflect.get(target, key, receiver);
},
getOwnPropertyDescriptor(target, key) {
if (key === "operationId") {
return {
configurable: true,
enumerable: true,
value: "SwappedOperation",
};
}
return Reflect.getOwnPropertyDescriptor(target, key);
},
});
const composed = composeContractContributions(
contributionWith({
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
contract,
}) as never,
);
expect([...composed.httpByOperationId.keys()]).toEqual([
"SwappedOperation",
]);
expect(
composed.httpByOperationId.get("SwappedOperation")!.contract
.operationId,
).toBe("SwappedOperation");
});
const hostileRows = [
{
label: "an installed row with an extra own field",
row: () => ({
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
injected: true,
}),
},
{
label: "an installed row with a symbol field",
row: () => ({
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
[Symbol.for("injected")]: true,
}),
},
{
label: "an installed row with a custom prototype",
row: () =>
Object.assign(Object.create({ injected: true }), {
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
}),
},
{
label: "an installed row hiding a non-enumerable own field",
row: () =>
Object.defineProperty(
{ ...TEST_CONTRACT_CONTRIBUTION.http[0]! },
"injected",
{ enumerable: false, value: true },
),
},
{
label: "an installed row behind a throwing ownKeys trap",
row: () =>
new Proxy(
{ ...TEST_CONTRACT_CONTRIBUTION.http[0]! },
{
ownKeys() {
throw new TypeError("hostile ownKeys trap");
},
},
),
},
];
for (const { label, row } of hostileRows) {
it(`refuses to compose ${label}`, () => {
expect(() =>
composeContractContributions(contributionWith(row()) as never),
).toThrow();
});
}
it("refuses a contribution whose own shape is not exact", () => {
for (const contribution of [
{ ...TEST_CONTRACT_CONTRIBUTION, injected: true },
Object.assign(Object.create({ injected: true }), {
...TEST_CONTRACT_CONTRIBUTION,
}),
{
...TEST_CONTRACT_CONTRIBUTION,
[Symbol.for("injected")]: true,
},
]) {
expect(() =>
composeContractContributions([contribution] as never),
).toThrow();
}
});
it("refuses an event contract whose own shape is not exact", () => {
const events = TEST_CONTRACT_CONTRIBUTION.events;
if (events.length === 0) return;
for (const event of [
{ ...events[0]!, injected: true },
Object.assign(Object.create({ injected: true }), { ...events[0]! }),
]) {
expect(() =>
composeContractContributions([
{ ...TEST_CONTRACT_CONTRIBUTION, events: [event] },
] as never),
).toThrow();
}
});
});
});
@@ -158,3 +158,121 @@ describe("bounded cursor pagination runtime", () => {
});
});
});
/**
* NS-07. The profile was validated once and then re-read on every page, so
* raising `maxPages` after construction widened a cap that had already been
* checked — the runtime issued more requests and returned more items than the
* validated profile allowed.
*/
describe("NS-07 the caps are the ones that were validated", () => {
it("keeps the page cap captured at construction", async () => {
const mutable: {
profileId: string;
maxPages: number;
maxTotalItems: number;
maxEstimatedBytes: number;
maxCursorBytes: number;
allowSparsePage: boolean;
} = { ...profile, maxPages: 1 };
const loadPage = vi.fn(async () => ({
ok: true as const,
value: {
items: [1],
nextCursor: `cursor-${loadPage.mock.calls.length}`,
hasMore: true,
snapshotToken: "snapshot-a",
},
}));
const runtime = createCursorPaginationRuntime({
definitionId: "LIST_ALL",
profile: mutable,
loadPage,
});
mutable.maxPages = 3;
mutable.maxTotalItems = 99;
await expect(runtime.loadAll({})).resolves.toMatchObject({
ok: false,
error: { code: "PAGINATION_PAGE_LIMIT" },
});
expect(loadPage).toHaveBeenCalledTimes(1);
});
it("keeps the loader captured at construction", async () => {
const original = vi.fn(async () => ({
ok: true as const,
value: {
items: [1],
nextCursor: null,
hasMore: false,
snapshotToken: null,
},
}));
const replacement = vi.fn();
const dependencies = {
definitionId: "LIST_ALL",
profile,
loadPage: original,
};
const runtime = createCursorPaginationRuntime(dependencies);
dependencies.loadPage = replacement as never;
await expect(runtime.loadAll({})).resolves.toMatchObject({ ok: true });
expect(original).toHaveBeenCalledTimes(1);
expect(replacement).not.toHaveBeenCalled();
});
const hostileProfiles: readonly (readonly [string, () => unknown])[] = [
[
"an accessor cap",
() =>
Object.defineProperty({ ...profile }, "maxPages", {
enumerable: true,
get: () => 3,
}),
],
[
"an inherited cap",
() => Object.create({ ...profile }) as unknown,
],
["an extra own field", () => ({ ...profile, injected: true })],
[
"a symbol field",
() => ({ ...profile, [Symbol.for("injected")]: true }),
],
[
"a non-enumerable own field",
() =>
Object.defineProperty({ ...profile }, "injected", {
enumerable: false,
value: true,
}),
],
[
"a throwing ownKeys trap",
() =>
new Proxy(
{ ...profile },
{
ownKeys() {
throw new TypeError("hostile ownKeys trap");
},
},
),
],
];
for (const [label, build] of hostileProfiles) {
it(`refuses to build a runtime from ${label}`, () => {
expect(() =>
createCursorPaginationRuntime({
definitionId: "LIST_ALL",
profile: build() as never,
loadPage: vi.fn(),
}),
).toThrow(TypeError);
});
}
});
-14
View File
@@ -74,7 +74,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher: async () =>
Response.json(
@@ -106,7 +105,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
const attachCredentials = vi.fn(() => ({
kind: "READY" as const,
headers: {},
credentials: "omit" as const,
}));
const fetcher = vi.fn();
const executor = createContractHttpExecutor({
@@ -145,7 +143,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
const attachCredentials = vi.fn(() => ({
kind: "READY" as const,
headers: {},
credentials: "omit" as const,
}));
const fetcher = vi.fn();
const executor = createContractHttpExecutor({
@@ -191,7 +188,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
const attachCredentials = vi.fn(() => ({
kind: "READY" as const,
headers: { [headerName]: "credential-owned-key" },
credentials: "omit" as const,
}));
const fetcher = vi.fn();
const executor = createContractHttpExecutor({
@@ -236,7 +232,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher,
sleep: async () => {},
@@ -277,7 +272,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher,
});
@@ -302,7 +296,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher: vi.fn(async (input) => {
urls.push(String(input));
@@ -351,7 +344,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher,
});
@@ -371,7 +363,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher: vi.fn(),
});
@@ -409,7 +400,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher: vi.fn(async () => Response.json({ malformed: true }, { status: 201 })),
});
@@ -445,7 +435,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher: vi.fn(async () => {
current = false;
@@ -582,7 +571,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher,
monotonicNow: () => 0,
@@ -636,7 +624,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher: vi.fn(async () =>
Response.json(
@@ -678,7 +665,6 @@ describe("descriptor-driven HTTP execution lifetime", () => {
attachCredentials: () => ({
kind: "READY",
headers: {},
credentials: "omit",
}),
fetcher: vi.fn(async () => new Response(body, { status: 200 })),
});