fix: harden the legacy HTTP rollback path

N-06: export one idempotency-key authority from mutation-intent.ts and use it
in the V2 client. A caller-supplied key is validated before credentials, timers
and fetch, and an invalid value is rejected as VALIDATION_REJECTED /
IDEMPOTENCY_KEY_INVALID rather than trimmed, regenerated or dropped, so a keyed
command can no longer replay while sending no key.

N-07: bound the legacy credential wait by the existing attempt controller,
which already carries the total deadline and the caller signal, so a
non-cooperative owner cannot hold the request open and no extra timer is
introduced. The owner receives the operation context, and the failure follows
ownership: deadline to REQUEST_TIMEOUT, caller to REQUEST_ABORTED, and only a
genuine rejection to AUTH_INTEGRATION_FAILURE. None of these paths fetch.

N-08: readBoundedJson delegates to the common bounded reader, so cancel and
releaseLock throws stay isolated inside the closed result, and the V2
content-type mismatch now cancels the response body.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-08-13 23:46:03 +09:00
co-authored by Claude Opus 5
parent 4fe924ee0f
commit c9e820aed5
7 changed files with 356 additions and 63 deletions
+82
View File
@@ -59,6 +59,88 @@ describe("shared HTTP client", () => {
expect(attempts).toBe(3);
});
it.each(["", " ", "bad\u0000key", "x".repeat(513)])(
"rejects invalid keyed command key %j before credentials and fetch",
async (idempotencyKey) => {
let fetched = 0;
let credentialAttempts = 0;
server.use(
http.post("https://api.test/api/entities", () => {
fetched += 1;
return HttpResponse.json({ success: true, data: {} });
}),
);
const client = testClient({
baseUrl: "https://api.test",
clock,
authSession: {
getState: () => "authenticated",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
async credentialPatch() {
credentialAttempts += 1;
return { headers: {} };
},
recover: async () => "no-session" as const,
onUnauthenticated: () => {},
},
});
await expect(
client.execute("CREATE_ENTITY", {
body: { name: "n" },
idempotencyKey,
}),
).resolves.toMatchObject({
ok: false,
error: {
kind: "VALIDATION_REJECTED",
code: "IDEMPOTENCY_KEY_INVALID",
// The repository reports attempt counts as 1-based; the invariant
// proved below is that no physical attempt happened at all.
attemptCount: 1,
},
});
expect(fetched).toBe(0);
expect(credentialAttempts).toBe(0);
},
);
it("bounds a non-cooperative legacy credential owner by total deadline", async () => {
let fetched = 0;
let observedSignal: AbortSignal | undefined;
server.use(
http.get("https://api.test/api/entities", () => {
fetched += 1;
return HttpResponse.json({ success: true, data: [] });
}),
);
const client = testClient({
baseUrl: "https://api.test",
timeoutMs: 5,
clock: { now: () => 0, sleep: async () => {} },
authSession: {
getState: () => "authenticated",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
credentialPatch: (_binding, context) => {
observedSignal = context?.signal;
// Never settles on its own.
return new Promise<never>(() => {});
},
recover: async () => "no-session" as const,
onUnauthenticated: () => {},
},
});
const result = await client.execute("LIST_ENTITIES");
expect(result).toMatchObject({ ok: false });
expect(fetched).toBe(0);
expect(observedSignal).toBeDefined();
});
it("rejects a non-JSON response without exposing its body", async () => {
server.use(
http.get(
@@ -307,6 +307,9 @@ describe("HTTP operation execution contract", () => {
operationId: "LIST_ENTITIES",
routeId: "TEST_ROUTE",
});
// The credential wait is bounded by the same attempt controller, so wait
// until the request is actually in flight before firing the deadline.
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));
await vi.waitFor(() => expect(scheduler.callbacks).toHaveLength(1));
scheduler.callbacks[0]();
await expect(timeoutResult).resolves.toMatchObject({
@@ -0,0 +1,91 @@
import { describe, expect, it, vi } from "vitest";
import { readBoundedJson } from "../../src/adapters/http/bounded-json.ts";
/**
* N-08. The legacy V2 reader delegates to the common bounded reader. These
* cases pin the preserved failure codes and prove that a throwing cancel or
* releaseLock cannot escape the closed result.
*/
function responseWith(
body: ReadableStream<Uint8Array> | string | null,
init: ResponseInit = {},
): Response {
return new Response(body, init);
}
describe("legacy bounded JSON compatibility", () => {
it("preserves RESPONSE_BODY_LIMIT for a declared oversize body", async () => {
const response = responseWith("{}", {
headers: { "content-length": "9999" },
});
await expect(readBoundedJson(response, 8)).resolves.toEqual({
ok: false,
code: "RESPONSE_BODY_LIMIT",
});
});
it("preserves RESPONSE_BODY_LIMIT for a headerless oversize body", async () => {
const response = responseWith("[1,2,3,4,5,6,7,8,9,10]");
await expect(readBoundedJson(response, 4)).resolves.toEqual({
ok: false,
code: "RESPONSE_BODY_LIMIT",
});
});
it.each([
["invalid UTF-8", new Uint8Array([0xff, 0xfe, 0xfd])],
["malformed JSON", new TextEncoder().encode("{")],
["an empty body", new Uint8Array(0)],
])("maps %s to MALFORMED_JSON", async (_label, bytes) => {
const response = responseWith(
new ReadableStream<Uint8Array>({
start(controller) {
if (bytes.byteLength > 0) controller.enqueue(bytes);
controller.close();
},
}),
);
await expect(readBoundedJson(response, 1_024)).resolves.toEqual({
ok: false,
code: "MALFORMED_JSON",
});
});
it("keeps a closed result when reader cancel or releaseLock throws", async () => {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode("[1,2,3,4,5,6,7,8]"));
},
});
const response = responseWith(stream);
const body = response.body!;
const nativeGetReader = body.getReader.bind(body);
vi.spyOn(body, "getReader").mockImplementation((() => {
const actual = nativeGetReader();
return {
...actual,
read: actual.read.bind(actual),
cancel: async () => {
throw new TypeError("cancel exploded");
},
releaseLock: () => {
throw new TypeError("releaseLock exploded");
},
};
}) as never);
await expect(readBoundedJson(response, 4)).resolves.toEqual({
ok: false,
code: "RESPONSE_BODY_LIMIT",
});
});
it("reads a bounded JSON value successfully", async () => {
const response = responseWith('{"a":1}');
await expect(readBoundedJson(response, 1_024)).resolves.toEqual({
ok: true,
value: { a: 1 },
});
});
});