Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions src/provider/veryfront-cloud/provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1976,6 +1976,116 @@ describe("provider/veryfront-cloud vendor-neutral routes", () => {
}
});

it("keeps an upstream error body readable through its stream on a neutral route", async () => {
// Provider error classification reads the body stream, not text(): an
// unreadable body falls back to status rules and turns a hard quota
// error into a retryable rate limit.
const body =
'{"error":{"message":"Quota exceeded","type":"insufficient_quota","code":"insufficient_quota"}}';
installMockFetch(() =>
Promise.resolve(
new Response(body, { status: 429, headers: { "content-type": "application/json" } }),
)
);
const wrappedFetch = createVeryfrontCloudFetch(
"vf_test_provider",
"https://api.veryfront.com/ai/v1",
undefined,
{ wireModelProvider: "openai" },
);
const response = await wrappedFetch("https://api.veryfront.com/ai/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "gpt-5.5" }),
});
restoreMockFetch();
const stream = response.body;
if (!stream) throw new Error("Expected an error body");
assertEquals([response.status, await new Response(stream).text()], [429, body]);
});

it("keeps a neutral-route error response's own accessors after project code replaces Response.prototype", async () => {
// Project code shares this realm. The classifier must read the upstream
// status and body, not a replaced prototype getter that hides a hard
// quota error or rewrites it into a retryable one.
const quota =
'{"error":{"message":"Quota exceeded","type":"insufficient_quota","code":"insufficient_quota"}}';
const cases: ReadonlyArray<readonly [number, unknown, string]> = [
[429, JSON.parse(quota), quota],
[
402,
{
error: {
message: "AI credit limit exceeded",
type: "insufficient_quota",
param: null,
code: "insufficient-credits",
veryfront: { balance_credits: 0, required_credits: 0.25 },
},
},
JSON.stringify({
error: "AI credit limit exceeded",
balance: 0,
required: 0.25,
slug: "insufficient-credits",
}),
],
];
const prototype = Response.prototype;
const replaced = ["body", "headers", "ok", "status", "statusText"] as const;
// Some runtimes (Bun) make these accessors non-configurable, so project
// code cannot replace them there and there is nothing to protect against.
if (
replaced.some((name) =>
Object.getOwnPropertyDescriptor(prototype, name)?.configurable !== true
)
) {
return;
}
for (const [status, envelope, expected] of cases) {
installMockFetch(() => Promise.resolve(Response.json(envelope, { status })));
const wrappedFetch = createVeryfrontCloudFetch(
"vf_test_provider",
"https://api.veryfront.com/ai/v1",
undefined,
{ wireModelProvider: "openai" },
);
const response = await wrappedFetch("https://api.veryfront.com/ai/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "gpt-5.5" }),
});
restoreMockFetch();
const originals = replaced.map((name) => Object.getOwnPropertyDescriptor(prototype, name)!);
const fakeHeaders = new Headers({ "content-type": "text/plain" });
const fakeBody = new Response("rate limited").body;
Object.defineProperties(prototype, {
body: { configurable: true, get: () => fakeBody },
headers: { configurable: true, get: () => fakeHeaders },
ok: { configurable: true, get: () => true },
status: { configurable: true, get: () => 200 },
statusText: { configurable: true, get: () => "OK" },
});
let seen: [number, boolean, string | null, ReadableStream<Uint8Array> | null];
try {
seen = [
response.status,
response.ok,
response.headers.get("content-type"),
response.body,
];
} finally {
replaced.forEach((name, index) =>
Object.defineProperty(prototype, name, originals[index]!)
);
}
const [seenStatus, seenOk, seenContentType, stream] = seen;
if (!stream) throw new Error("Expected an error body");
assertEquals(
[seenStatus, seenOk, seenContentType, await new Response(stream).text()],
[status, false, "application/json", expected],
);
}
});

it("sends a body without a string model unchanged on a neutral route", async () => {
const sent: string[] = [];
installMockFetch(async (input, init) => {
Expand Down
78 changes: 61 additions & 17 deletions src/provider/veryfront-cloud/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from "#veryfront/platform/cloud/resolver.ts";
import { readResponseTextPrefix } from "#veryfront/utils/response-body.ts";
import {
bindHostResponseAccessors,
createVeryfrontApiOriginBoundOutboundFetch,
HOST_ALLOWED_INTERNAL_PROVIDER_ORIGINS_ENV,
isHostAllowedInternalProviderOrigin,
Expand Down Expand Up @@ -63,8 +64,11 @@ const PromisePrototypeThen = Promise.prototype.then;
const RequestMethodGet = Object.getOwnPropertyDescriptor(NativeRequest.prototype, "method")?.get;
const RequestPrototypeText = NativeRequest.prototype.text;
const SetPrototypeHas = Set.prototype.has;
const ResponseBodyGet = Object.getOwnPropertyDescriptor(Response.prototype, "body")?.get;
const ResponseHeadersGet = Object.getOwnPropertyDescriptor(Response.prototype, "headers")?.get;
const ResponsePrototypeClone = Response.prototype.clone;
const ReadableStreamCancel = ReadableStream.prototype.cancel;
const ReadableStreamGetReader = ReadableStream.prototype.getReader;
const ReadableStreamTee = ReadableStream.prototype.tee;
const ResponseStatusGet = Object.getOwnPropertyDescriptor(Response.prototype, "status")?.get;
const ResponseStatusTextGet = Object.getOwnPropertyDescriptor(Response.prototype, "statusText")
?.get;
Expand Down Expand Up @@ -679,7 +683,7 @@ const NEUTRAL_REFUSAL_MAX_BYTES = 8 * 1024;
* Successes, non-JSON bodies and upstream provider errors pass through untouched.
*/
async function normalizeNeutralGatewayRefusal(response: Response): Promise<Response> {
if (!ResponseStatusGet || !ResponseHeadersGet) return response;
if (!ResponseStatusGet || !ResponseHeadersGet || !ResponseBodyGet) return response;
const status = IntrinsicReflectApply(ResponseStatusGet, response, []) as number;
if (status < 400) return response;
const responseHeaders = IntrinsicReflectApply(ResponseHeadersGet, response, []) as Headers;
Expand All @@ -693,30 +697,70 @@ async function normalizeNeutralGatewayRefusal(response: Response): Promise<Respo
return response;
}

const body = IntrinsicReflectApply(ResponseBodyGet, response, []) as
| ReadableStream<Uint8Array>
| null;
if (body === null) return response;
// Split the body rather than clone the response: Bun's clone leaves an
// already-read body getter on an empty stream.
let probe: ReadableStream<Uint8Array>;
let live: ReadableStream<Uint8Array>;
try {
[probe, live] = IntrinsicReflectApply(ReadableStreamTee, body, []) as [
ReadableStream<Uint8Array>,
ReadableStream<Uint8Array>,
];
} catch {
return response;
}
const statusText = ResponseStatusTextGet
? IntrinsicReflectApply(ResponseStatusTextGet, response, []) as string
: "";
// Every response returned here is sealed like the transport's own, so the
// provider classifier reads the upstream status and body even after project
// code replaces the Response.prototype getters.
const passThrough = (): Response =>
bindHostResponseAccessors(
new NativeResponse(live, { status, statusText, headers: responseHeaders }),
);
Comment thread
kojiwakayama marked this conversation as resolved.
Resolved

let refusal: Record<string, unknown> | undefined;
try {
// A Veryfront refusal is small. Read a bounded prefix of a copy and cancel
// the rest, so a large upstream error is never buffered here; anything that
// does not fit is not a refusal and passes through untouched.
const copy = IntrinsicReflectApply(ResponsePrototypeClone, response, []) as Response;
const { text, truncated } = await readResponseTextPrefix(copy, NEUTRAL_REFUSAL_MAX_BYTES);
if (truncated) return response;
// A Veryfront refusal is small. Read a bounded prefix of one branch and
// cancel the rest, so a large upstream error is never buffered here;
// anything that does not fit is not a refusal and passes through untouched.
const reader = {
getReader: (): ReadableStreamDefaultReader<Uint8Array> =>
IntrinsicReflectApply(ReadableStreamGetReader, probe, []) as ReadableStreamDefaultReader<
Uint8Array
>,
};
const { text, truncated } = await readResponseTextPrefix(
{ body: reader },
NEUTRAL_REFUSAL_MAX_BYTES,
);
if (truncated) return passThrough();
refusal = toVendorRouteRefusal(JSONParse(text));
} catch {
return response;
return passThrough();
}
if (!refusal) return response;
if (!refusal) return passThrough();

// Cancelling the unread copy is best effort; its rejection is handled below.
void IntrinsicReflectApply(
PromisePrototypeThen,
IntrinsicReflectApply(ReadableStreamCancel, live, []),
[
undefined,
() => undefined,
],
);
const headers = new NativeHeaders(responseHeaders);
IntrinsicReflectApply(HeadersDelete, headers, ["content-length"]);
IntrinsicReflectApply(HeadersSet, headers, ["content-type", "application/json"]);
return new NativeResponse(JSONStringify(refusal) as string, {
status,
statusText: ResponseStatusTextGet
? IntrinsicReflectApply(ResponseStatusTextGet, response, []) as string
: "",
headers,
});
return bindHostResponseAccessors(
new NativeResponse(JSONStringify(refusal) as string, { status, statusText, headers }),
);
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/security/http/outbound-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,12 @@ export function __bindHostResponseAccessorsForTests(response: Response): Respons
return bindHostResponseAccessors(response);
}

function bindHostResponseAccessors(response: Response): Response {
/**
* Pin a host-owned response's body, headers, ok, status and statusText as own
* properties read through the native getters now, so later changes project
* code makes to Response.prototype cannot hide or rewrite them.
*/
export function bindHostResponseAccessors(response: Response): Response {
// Promise resolution reads then before returning the authenticated response.
IntrinsicReflectApply(ObjectDefineProperty, Object, [
response,
Expand Down
Loading
Loading