fix: carry the proxy deadline's identity, correct the rounding note (#2319 round 9)

A deadline enforced by the backend could not arrive as an
OAuthRequestTimeoutError: /api/fetch serialized it as a 500 and
createRemoteFetch turned that into a plain Error, so every instanceof
check downstream was false — including the one that lets a stalled
probe escape withRfc8414OidcCompat. That matters most where no
client-side wrapper exists to have fired first: the discovery the SDK
runs from inside the transport. The route now answers 504 with a typed
marker (OAUTH_TIMEOUT_WIRE_CODE plus url and timeoutMs) and
createRemoteFetch reconstructs the error from it, guarded by a shape
check so an upstream's own JSON cannot forge one.

The route's deadline becomes a `fetchTimeoutMs` option defaulting to
the shared constant, so the backstop can be proven to fire in
milliseconds instead of thirty seconds of wall clock — and because a
very slow authorization server is a legitimate reason to want a longer
one.

The rounding rationale was wrong: setTimeout accepts a fractional delay
and truncates it (verified on Node 26); ERR_OUT_OF_RANGE is
AbortSignal.timeout's behaviour, which this wrapper never calls. The
rounding stays, for the reason that is actually true — the budget is
interpolated into the message and exposed as timeoutMs, and a
performance.now() budget would otherwise report 1000.4000000953674ms.

Also drops a sentence in the discarded-stream test that contradicted
the qualification above it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YFnM6RqB4nXqNysgUYmjmq
Signed-off-by: cliffhall <cliff@futurescale.com>
This commit is contained in:
cliffhall 2026-09-11 04:16:15 -04:00
commit baefc96806
7 changed files with 247 additions and 20 deletions

View file

@ -318,10 +318,12 @@ describe("withOAuthRequestTimeout", () => {
await expect(wrapped(URL_UNDER_TEST)).rejects.toBe(boom);
});
it("rounds a fractional budget, because setTimeout takes an integer", async () => {
it("rounds a fractional budget, which is reported to the caller", async () => {
vi.useFakeTimers();
// A budget derived from `performance.now()` arrives fractional; a fractional
// delay throws ERR_OUT_OF_RANGE before the request is ever made.
// `setTimeout` would accept the fraction and truncate it. The rounding is
// for the budget's *reported* form: a `performance.now()` subtraction would
// otherwise name "1000.4000000953674ms" in the message and expose a
// non-integer `timeoutMs`.
const wrapped = withOAuthRequestTimeout(neverSettles, 1000.4);
const assertion = wrapped(URL_UNDER_TEST).catch((err: unknown) => err);

View file

@ -1,5 +1,9 @@
import { describe, it, expect, vi } from "vitest";
import { createRemoteFetch } from "@inspector/core/mcp/remote/createRemoteFetch.js";
import {
OAUTH_TIMEOUT_WIRE_CODE,
OAuthRequestTimeoutError,
} from "@inspector/core/auth/requestTimeout.js";
function ok(body: object): Response {
return new Response(JSON.stringify(body), {
@ -241,4 +245,83 @@ describe("createRemoteFetch", () => {
expect(signalOf(fetchFn)).toBeUndefined();
});
});
describe("proxy-side deadline (#2319)", () => {
function remoteReturning(status: number, body: string) {
const fetchFn = vi.fn<typeof fetch>().mockResolvedValue(
new Response(body, {
status,
headers: { "content-type": "application/json" },
}),
);
return createRemoteFetch({
baseUrl: "http://remote.example",
fetchFn: fetchFn as unknown as typeof fetch,
});
}
it("rebuilds an OAuthRequestTimeoutError from the route's marker", async () => {
// The one path where a timeout reaches the browser without a client-side
// wrapper having fired first: the discovery the SDK runs from inside the
// transport has no wrapper at all, so the backend's deadline is the only
// one, and it arrives as an ordinary error response.
const remoteFetch = remoteReturning(
504,
JSON.stringify({
error: "proxied request to https://as.example.com/x timed out",
code: OAUTH_TIMEOUT_WIRE_CODE,
url: "https://as.example.com/x",
timeoutMs: 30000,
}),
);
const err = await remoteFetch("https://as.example.com/x").catch(
(e: unknown) => e,
);
expect(err).toBeInstanceOf(OAuthRequestTimeoutError);
const timeout = err as OAuthRequestTimeoutError;
expect(timeout.url).toBe("https://as.example.com/x");
expect(timeout.timeoutMs).toBe(30000);
});
it("leaves an ordinary error response as a plain Error", async () => {
const remoteFetch = remoteReturning(
500,
JSON.stringify({ error: "connect ECONNREFUSED" }),
);
const err = await remoteFetch("https://as.example.com/x").catch(
(e: unknown) => e,
);
expect(err).not.toBeInstanceOf(OAuthRequestTimeoutError);
expect((err as Error).message).toMatch(/Remote fetch failed \(500\)/);
});
it("ignores a non-JSON error body rather than throwing on the parse", async () => {
const remoteFetch = remoteReturning(502, "<html>bad gateway</html>");
const err = await remoteFetch("https://as.example.com/x").catch(
(e: unknown) => e,
);
expect((err as Error).message).toMatch(/Remote fetch failed \(502\)/);
});
it("ignores a marker whose fields are the wrong shape", async () => {
// An upstream could serve JSON of its own through a failing proxy; the
// guard checks the field types, not just the code.
const remoteFetch = remoteReturning(
504,
JSON.stringify({ code: OAUTH_TIMEOUT_WIRE_CODE, url: 5 }),
);
const err = await remoteFetch("https://as.example.com/x").catch(
(e: unknown) => e,
);
expect(err).not.toBeInstanceOf(OAuthRequestTimeoutError);
});
});
});

View file

@ -51,6 +51,7 @@ interface StartOpts {
secretStore?: SecretStore;
logger?: pinoType.Logger;
seedConfig?: string;
fetchTimeoutMs?: number;
}
async function start(opts: StartOpts = {}): Promise<Harness> {
@ -65,6 +66,9 @@ async function start(opts: StartOpts = {}): Promise<Harness> {
initialConfig: { defaultEnvironment: {} },
secretStore: opts.secretStore ?? new InMemorySecretStore(),
logger: opts.logger,
...(opts.fetchTimeoutMs !== undefined && {
fetchTimeoutMs: opts.fetchTimeoutMs,
}),
});
const { baseUrl, server } = await new Promise<{
baseUrl: string;
@ -465,11 +469,42 @@ describe("server.ts supplemental coverage", () => {
const payload = (await res.json()) as { status: number; body?: string };
expect(payload.status).toBe(200);
expect(payload.body).toBeUndefined();
// The upstream sees its connection go away once the handler returns.
// Without the cancel this never resolves and the test times out.
// The observable contract: the route does not leave the upstream stream
// running after it has answered. (Per the qualification above, this does
// not isolate the explicit `cancel()` as the cause.)
await openStreamClosed;
});
it("answers 504 with a typed marker when its own deadline fires (#2319)", async () => {
// The backstop, on its own short budget so this costs milliseconds rather
// than the production thirty seconds. It matters because this is the only
// deadline on the transport-internal discovery path, which has no
// client-side wrapper — so its error has to survive the hop as something
// an `instanceof OAuthRequestTimeoutError` check can still recognize.
await stop(h);
h = await start({ fetchTimeoutMs: 120 });
const res = await fetch(`${h.baseUrl}/api/fetch`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ url: `${targetUrl}/stall` }),
});
expect(res.status).toBe(504);
const payload = (await res.json()) as {
error: string;
code: string;
url: string;
timeoutMs: number;
};
expect(payload.code).toBe("oauth_request_timeout");
expect(payload.url).toBe(`${targetUrl}/stall`);
expect(payload.timeoutMs).toBe(120);
expect(payload.error).toContain("timed out after 120ms");
// And the upstream is released rather than left running.
await stallClosed;
});
it("routes the outbound request through HTTP_PROXY (#2067)", async () => {
// /api/fetch is the browser's ONLY way out to the network — the web
// client's `environment.fetch` is `createRemoteFetch()`, which forwards

View file

@ -54,9 +54,12 @@ export {
// OAuth-path request deadline (#2319)
export {
DEFAULT_OAUTH_REQUEST_TIMEOUT_MS,
OAUTH_TIMEOUT_WIRE_CODE,
OAuthRequestTimeoutError,
isOAuthRequestTimeoutWire,
withOAuthRequestTimeout,
} from "./requestTimeout.js";
export type { OAuthRequestTimeoutWire } from "./requestTimeout.js";
// Storage
export type {

View file

@ -83,6 +83,40 @@ export class OAuthRequestTimeoutError extends Error {
}
}
/**
* How a proxy-side deadline is carried back to the browser (#2319).
*
* `/api/fetch` serializes its failures as a JSON error response, and
* `createRemoteFetch` turns any non-OK answer into a plain `Error` — so a
* timeout enforced by the *backend* would arrive as an untyped error and the
* `instanceof OAuthRequestTimeoutError` checks downstream would all be false
* (Copilot). That matters most exactly where there is no client-side wrapper to
* have fired first: the discovery the SDK runs from inside the transport. So
* the route stamps this marker and `createRemoteFetch` reconstructs the typed
* error from it.
*/
export const OAUTH_TIMEOUT_WIRE_CODE = "oauth_request_timeout";
/** The body `/api/fetch` returns when its own deadline fired. */
export interface OAuthRequestTimeoutWire {
code: typeof OAUTH_TIMEOUT_WIRE_CODE;
url: string;
timeoutMs: number;
}
/** Whether a parsed `/api/fetch` error body is a proxy-side deadline. */
export function isOAuthRequestTimeoutWire(
value: unknown,
): value is OAuthRequestTimeoutWire {
if (typeof value !== "object" || value === null) return false;
const candidate = value as Record<string, unknown>;
return (
candidate.code === OAUTH_TIMEOUT_WIRE_CODE &&
typeof candidate.url === "string" &&
typeof candidate.timeoutMs === "number"
);
}
/** The request URL, whatever form `fetch`'s first argument took. */
function requestUrlOf(input: RequestInfo | URL): string {
if (typeof input === "string") return input;
@ -187,12 +221,20 @@ export function withOAuthRequestTimeout(
fetchFn: typeof fetch,
timeoutMs: number = DEFAULT_OAUTH_REQUEST_TIMEOUT_MS,
): typeof fetch {
// Whole milliseconds, because `setTimeout` and `AbortSignal.timeout` both
// take an integer: Node throws `ERR_OUT_OF_RANGE` on a fractional delay —
// before the fetch, so the request is never sent and the caller sees a failed
// operation rather than a timeout. A budget derived from `performance.now()`
// is fractional, so this is reachable. `revocation.ts:253` carries the same
// note for the same reason.
// Whole milliseconds. Not for the reason `revocation.ts:253` gives — that one
// calls `AbortSignal.timeout`, which really does throw `ERR_OUT_OF_RANGE` on
// a fractional delay (verified on Node 26) and so would fail before the
// request was sent. This wrapper drives its deadline with `setTimeout` and an
// `AbortController`, and `setTimeout` accepts a fractional delay and
// truncates it, so nothing here would throw (Copilot).
//
// The real reason is that the budget is *reported*: it is interpolated into
// the timeout message and exposed as `OAuthRequestTimeoutError.timeoutMs`. A
// caller whose budget came from a `performance.now()` subtraction would
// otherwise produce "timed out after 1000.4000000953674ms" and a non-integer
// public field. Rounding rather than flooring so a caller's own
// whole-millisecond timeout survives the trip through that clock and is still
// the number the message names.
const budget = Math.max(0, Math.round(timeoutMs));
return async (input, init) => {

View file

@ -21,6 +21,11 @@
* the web client against a strict modern server, same as from the CLI/TUI.
*/
import {
isOAuthRequestTimeoutWire,
OAuthRequestTimeoutError,
} from "../../auth/requestTimeout.js";
export interface RemoteFetchOptions {
/** Base URL of the remote server (e.g. http://localhost:3000) */
baseUrl: string;
@ -158,6 +163,22 @@ export function createRemoteFetch(options: RemoteFetchOptions): typeof fetch {
if (!res.ok) {
const text = await res.text();
// A deadline the backend enforced arrives as an ordinary error response;
// rebuild the typed error from its marker so the `instanceof` checks
// downstream — most importantly the one that lets a stalled probe escape
// `withRfc8414OidcCompat` — still see a timeout for what it is (#2319,
// Copilot). This is the only path on which such a timeout can reach the
// browser without a client-side wrapper having fired first: the discovery
// the SDK runs from inside the transport has no wrapper at all.
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
parsed = undefined;
}
if (isOAuthRequestTimeoutWire(parsed)) {
throw new OAuthRequestTimeoutError(parsed.url, parsed.timeoutMs);
}
throw new Error(`Remote fetch failed (${res.status}): ${text}`);
}

View file

@ -28,7 +28,10 @@ import { bodyLimit } from "hono/body-limit";
import { watch as chokidarWatch, type FSWatcher } from "chokidar";
import { createTransportNode } from "../../node/transport.js";
import { createProxyFetch } from "../../node/proxyFetch.js";
import { DEFAULT_OAUTH_REQUEST_TIMEOUT_MS } from "../../../auth/requestTimeout.js";
import {
DEFAULT_OAUTH_REQUEST_TIMEOUT_MS,
OAUTH_TIMEOUT_WIRE_CODE,
} from "../../../auth/requestTimeout.js";
import type {
RemoteConnectRequest,
RemoteSendRequest,
@ -235,6 +238,21 @@ export interface RemoteServerOptions {
/** Optional path for the user's server list file (/api/servers). Default: ~/.mcp-inspector/mcp.json */
mcpConfigPath?: string;
/**
* Deadline for the outbound request `/api/fetch` makes, in milliseconds
* (#2319). Defaults to {@link DEFAULT_OAUTH_REQUEST_TIMEOUT_MS}, the same
* budget the browser-side `withOAuthRequestTimeout` uses, so the two agree on
* when an attempt is hopeless.
*
* This is the backstop for a client that vanishes without aborting; the
* primary mechanism is the caller's own signal, which `createRemoteFetch`
* forwards onto this hop. Exposed rather than hardcoded so a test can prove
* the backstop actually fires without spending thirty seconds of wall clock
* on it — and because a very slow authorization server is a legitimate reason
* to want a longer one.
*/
fetchTimeoutMs?: number;
/**
* When false, the server list is read-only for this session: all
* `/api/servers` mutations (POST/PUT/DELETE/order) are rejected with 403,
@ -570,6 +588,10 @@ export function createRemoteApp(
options: RemoteServerOptions,
): CreateRemoteAppResult {
const dangerouslyOmitAuth = !!options.dangerouslyOmitAuth;
const fetchTimeoutMs = Math.max(
0,
Math.round(options.fetchTimeoutMs ?? DEFAULT_OAUTH_REQUEST_TIMEOUT_MS),
);
// Determine auth token when auth is enabled: options > env var > generate
const authToken = dangerouslyOmitAuth
@ -1227,6 +1249,11 @@ export function createRemoteApp(
// client that vanishes without aborting, and it matches the client-side
// budget so the two agree on when this is hopeless.
const controller = new AbortController();
// Set by the timer below and read in the `catch`. The fetch rejects with
// the signal's abort reason, but which of several aborts won is not worth
// inferring from the error — the flag says it directly, the same
// normalization `withOAuthRequestTimeout` uses.
let deadlineFired = false;
const clientSignal: AbortSignal | undefined = c.req.raw.signal;
const signal = clientSignal
? AbortSignal.any([controller.signal, clientSignal])
@ -1235,15 +1262,14 @@ export function createRemoteApp(
// the body has been either read or explicitly cancelled — this route never
// hands a live stream to its caller, so there is nothing left for the timer
// to protect and nothing it could sever.
const timer = setTimeout(
() =>
controller.abort(
new Error(
`proxied request to ${url} timed out after ${DEFAULT_OAUTH_REQUEST_TIMEOUT_MS}ms`,
),
const timer = setTimeout(() => {
deadlineFired = true;
controller.abort(
new Error(
`proxied request to ${url} timed out after ${fetchTimeoutMs}ms`,
),
DEFAULT_OAUTH_REQUEST_TIMEOUT_MS,
);
);
}, fetchTimeoutMs);
try {
// Proxy-aware, not the bare global. This route is the browser's ONLY way
@ -1296,6 +1322,21 @@ export function createRemoteApp(
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (deadlineFired) {
// Stamped so the browser can rebuild an `OAuthRequestTimeoutError`
// rather than receiving a plain `Error` that no `instanceof` check
// downstream can recognize (Copilot). 504 because that is what this
// is — the gateway gave up on the upstream, not a fault in the route.
return c.json(
{
error: msg,
code: OAUTH_TIMEOUT_WIRE_CODE,
url,
timeoutMs: fetchTimeoutMs,
},
504,
);
}
return c.json({ error: msg }, 500);
} finally {
clearTimeout(timer);