Files
billion-context/tests/proxy-stream-error.test.ts
T
review-fix b3c983bb94 fix(review): close follow-up gaps on PR #141 hardening batch
- #115: pin Host to trusted hosts BEFORE the no-Origin early-return; a
  same-origin rebinding GET carries no Origin and previously bypassed
  the Host check entirely
- #117: cap update-lock steal age (LOCK_MAX_AGE_MS=30min) so a crashed
  holder whose pid was reused by an unrelated process cannot block
  auto-update forever (shouldStealLock pure fn, exported)
- #116: verifyTarballIntegrity fails closed on unknown hash algorithms
  instead of throwing; exported for tests
- #77: CONNECT 403 uses end() so the response flushes; consolidate
  duplicated isLoopback into shared isLoopbackAddress (mitm copy missed
  ::ffff:127.x)
- #118: handshake timeout env-tunable for tests

Tests (+14): responses error-path full item lifecycle; MITM e2e
(happy path, handshake timeout, non-loopback 403); admin rebinding
e2e incl. no-Origin case; integrity + lock-steal units; hop-by-hop
static + Connection-named stripping e2e. Fix withTmpCa helper: a bare
'return fn()' ran finally on first await, restoring env mid-test.

typecheck clean, 389/389 tests, build 2.04 MB
2026-08-14 23:34:10 +08:00

100 lines
3.9 KiB
TypeScript

import { test } from "node:test";
import assert from "node:assert/strict";
import http from "node:http";
import { emitStreamError } from "../src/stream-error.ts";
/** Collect all bytes written to a ServerResponse into a string. */
function makeCollector(): { res: http.ServerResponse; chunks: Buffer[]; done: Promise<string> } {
const chunks: Buffer[] = [];
// Minimal stub mimicking the methods emitStreamError uses.
const res = {
write(chunk: string | Buffer) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
return true;
},
end() {
return this;
},
} as unknown as http.ServerResponse;
return { res, chunks, done: Promise.resolve("") };
}
test("emitStreamError: openai emits error delta + finish + [DONE]", async () => {
const { res, chunks } = makeCollector();
emitStreamError(res, "openai", "test failure");
const out = Buffer.concat(chunks).toString("utf8");
assert.match(out, /test failure/);
assert.match(out, /finish_reason.*stop/);
assert.match(out, /\[DONE\]/);
});
test("emitStreamError: anthropic emits content_block_delta + message_stop", async () => {
const { res, chunks } = makeCollector();
emitStreamError(res, "anthropic", "boom");
const out = Buffer.concat(chunks).toString("utf8");
assert.match(out, /content_block_delta/);
assert.match(out, /boom/);
assert.match(out, /message_stop/);
});
test("emitStreamError: responses emits a full item lifecycle (added → delta → done → completed)", async () => {
const { res, chunks } = makeCollector();
emitStreamError(res, "responses", "kaboom");
const out = Buffer.concat(chunks).toString("utf8");
// Ordered: every delta must be preceded by output_item.added and followed
// by the done events — a bare delta crashes strict clients (#62).
const order = [
"response.output_item.added",
"response.content_part.added",
"response.output_text.delta",
"response.output_text.done",
"response.content_part.done",
"response.output_item.done",
"response.completed",
];
let cursor = -1;
for (const ev of order) {
const at = out.indexOf(ev);
assert.notEqual(at, -1, `missing event ${ev}`);
assert.ok(at > cursor, `${ev} out of order`);
cursor = at;
}
assert.match(out, /kaboom/);
// Every item-scoped event carries the same item_id and output_index, so
// strict clients can associate the delta with the added item.
const itemId = "msg_acp_error";
const itemEvents = out.split("\n\n").filter((block) => block.includes("item_id"));
assert.ok(itemEvents.length >= 4, "expected item-scoped events");
for (const block of itemEvents) {
assert.match(block, new RegExp(`"item_id":"${itemId}"`));
assert.match(block, /"output_index":0/);
}
// The completed response contains the error item in its output array.
const completed = out.split("\n\n").find((b) => b.includes("response.completed"));
assert.ok(completed);
const data = JSON.parse((completed?.split("data: ")[1] ?? "").trim());
assert.equal(data.response.output.length, 1);
assert.equal(data.response.output[0].id, itemId);
assert.ok(data.response.output[0].content[0].text.includes("kaboom"));
});
test("emitStreamError: never throws even if write throws (client gone)", () => {
const res = {
write() {
throw new Error("write EPIPE");
},
end() {
throw new Error("end EPIPE");
},
} as unknown as http.ServerResponse;
assert.doesNotThrow(() => emitStreamError(res, "openai", "x"));
});
test("emitStreamError: calls the optional log callback", () => {
const { res } = makeCollector();
let logged = "";
emitStreamError(res, "openai", "logged-msg", (m) => (logged = m));
assert.match(logged, /stream aborted/);
assert.match(logged, /logged-msg/);
});