Compare commits

..

1 Commits

Author SHA1 Message Date
Markus Hartung
4d2abc313e fix(sse): cap streaming headers-wait timeout to a client-realistic ceiling (#11526)
The fetch-start (headers-wait) phase inherited the flat, non-adaptive
FETCH_TIMEOUT_MS (default 600_000ms) with no ceiling comparable to a real
client's patience, unlike the body-phase readiness watchdog which already
adapts per payload shape. Codex's own hard client-abort window for a
stalled turn is ~120s, 5x shorter than the old default — so when an
upstream never returned any response at all (not even headers, e.g. a
stalled NVIDIA target behind a tool-heavy Responses->Chat translation),
OmniRoute kept the connection open on keepalives only, guaranteeing the
client gave up first with an opaque 499 instead of OmniRoute detecting and
failing the stall fast.

Adds resolveFetchStartTimeout() (open-sse/utils/fetchStartTimeoutPolicy.ts)
that caps the headers-wait timeout to 110s for STREAMING requests only,
leaving non-streaming requests on the existing flat default. Wired into
BaseExecutor.execute(). The existing TimeoutError classification path
(chatCore.ts) already maps this to a 504, so no change was needed there.

Regression test: tests/unit/issue-11526-repro.test.ts.
2026-08-26 13:13:51 -03:00
8 changed files with 137 additions and 101 deletions

View File

@@ -0,0 +1 @@
- **fix(sse):** cap the upstream headers-wait phase for STREAMING requests to a client-realistic ceiling (110s, under Codex's own ~120s hard client-abort window) instead of the flat 10-minute `FETCH_TIMEOUT_MS` default — that default was 5x longer than the body-phase readiness watchdog's own adaptive bound, so a request whose upstream never returned any response at all (not even headers, e.g. a stalled NVIDIA target behind a tool-heavy Responses→Chat translation) kept the client connection alive on keepalives only, guaranteeing the client's own patience ran out first with an opaque 499 instead of OmniRoute detecting and failing the stall fast. Non-streaming requests are unaffected — they keep the existing flat default (`open-sse/utils/fetchStartTimeoutPolicy.ts`) (#11526)

View File

@@ -1,5 +1,6 @@
import { HTTP_STATUS, FETCH_TIMEOUT_MS } from "../config/constants.ts";
import { getRegistryEntry } from "../config/providerRegistry.ts";
import { resolveFetchStartTimeout } from "../utils/fetchStartTimeoutPolicy.ts";
import {
resolveAlternateFormat,
type AlternateFormat,
@@ -902,9 +903,24 @@ export class BaseExecutor {
clampNestedThinkingBudget(transformedBody, thinkingBudgetClampedMax);
}
// Timeout only covers response start; stream stalls are handled downstream.
// #11526: streaming requests cap the headers-wait phase to a client-realistic
// ceiling (see fetchStartTimeoutPolicy.ts) — non-streaming keeps the flat default.
// Declared outside the try/catch below so the catch's TIMEOUT log (on the
// error path) reports the same effective value the fetch actually used.
const fetchStartTimeoutPolicy = resolveFetchStartTimeout({
baseTimeoutMs: this.getTimeoutMs(),
stream,
});
const fetchStartTimeoutMs = fetchStartTimeoutPolicy.timeoutMs;
if (fetchStartTimeoutPolicy.capped) {
log?.debug?.(
"TIMEOUT",
`fetch-start timeout capped ${fetchStartTimeoutPolicy.baseTimeoutMs}ms -> ${fetchStartTimeoutMs}ms (streaming)`
);
}
try {
// Timeout only covers response start; stream stalls are handled downstream.
const fetchStartTimeoutMs = this.getTimeoutMs();
const fetchWithStartTimeout = async (requestUrl: string, requestOptions: RequestInit) => {
// GHSA-4f49: guard here (not only next to the first buildUrl) so retries
// and fallback URLs are validated too, before any bytes leave the host.
@@ -1713,7 +1729,7 @@ export class BaseExecutor {
// Distinguish timeout errors from other abort errors
const err = error instanceof Error ? error : new Error(String(error));
if (err.name === "TimeoutError") {
log?.warn?.("TIMEOUT", `Fetch timeout after ${this.getTimeoutMs()}ms on ${url}`);
log?.warn?.("TIMEOUT", `Fetch timeout after ${fetchStartTimeoutMs}ms on ${url}`);
}
lastError = err;
if (!skipUpstreamRetry && urlIndex + 1 < fallbackCount) {

View File

@@ -0,0 +1,52 @@
// #11526: the fetch-start (headers-wait) phase had no ceiling comparable to a
// real client's patience for STREAMING requests — it inherited the flat,
// non-adaptive FETCH_TIMEOUT_MS (default 600_000ms / 10 minutes), five times
// longer than Codex's own ~120s hard client-abort window. When an upstream
// never returns a response at all (not even headers), OmniRoute kept the
// connection open with nothing but keepalives, guaranteeing the client gave
// up first with an opaque 499 instead of OmniRoute detecting the stall and
// failing fast/over within a client-realistic window.
//
// This mirrors the adaptive philosophy of streamReadinessPolicy.ts's
// resolveStreamReadinessTimeout (which already protects the BODY phase, after
// headers arrive) but inverted: instead of bumping a small base timeout up for
// heavy payloads, it caps an oversized base timeout down for the HEADERS
// phase of streaming requests specifically. Non-streaming requests are left
// on the existing flat default — providers that are legitimately slow to
// accept a connection (but not streaming SSE) are unaffected.
export type FetchStartTimeoutPolicyInput = {
baseTimeoutMs: number;
/** Only streaming requests are capped — non-streaming keeps the flat default. */
stream?: boolean | null;
capMs?: number;
};
export type FetchStartTimeoutPolicyResult = {
timeoutMs: number;
baseTimeoutMs: number;
/** True when the base timeout was reduced by the streaming cap. */
capped: boolean;
};
// Codex's documented hard client-abort window for a stalled turn (nothing but
// keepalives in flight) is ~120s. Keep the cap safely under that so OmniRoute's
// own headers-phase watchdog always fires before the client gives up on its own.
export const CODEX_CLIENT_ABORT_MS = 120_000;
export const DEFAULT_FETCH_START_TIMEOUT_CAP_MS = 110_000;
export function resolveFetchStartTimeout(
input: FetchStartTimeoutPolicyInput
): FetchStartTimeoutPolicyResult {
const baseTimeoutMs = Math.max(0, Math.floor(input.baseTimeoutMs || 0));
if (baseTimeoutMs <= 0 || !input.stream) {
return { timeoutMs: baseTimeoutMs, baseTimeoutMs, capped: false };
}
const capMs = Math.max(0, Math.floor(input.capMs ?? DEFAULT_FETCH_START_TIMEOUT_CAP_MS));
if (capMs <= 0 || baseTimeoutMs <= capMs) {
return { timeoutMs: baseTimeoutMs, baseTimeoutMs, capped: false };
}
return { timeoutMs: capMs, baseTimeoutMs, capped: true };
}

View File

@@ -2,7 +2,6 @@ import { NextResponse } from "next/server";
import { getCachedSettings, updateSettings } from "@/lib/localDb";
import { SignJWT, jwtVerify, createRemoteJWKSet } from "jose";
import { cookies } from "next/headers";
import { timingSafeCompare } from "@/shared/utils/timingSafeCompare";
// Test seam (static) — allows tests to inject a cookie store and capture the minted auth_token.
// Mirrors the pattern in src/app/api/auth/login/route.ts
export const oidcCallbackInternals = {
@@ -55,10 +54,7 @@ export async function GET(request: Request) {
// Validate state from cookie (via seam so tests can capture)
const cookieStore = await oidcCallbackInternals.getCookieStore();
const storedState = cookieStore.get("oidc_state")?.value;
// Constant-time: `!==` short-circuits on the first differing byte, so
// rejection time correlates with matching-prefix length (GHSA-7434-6q4c-33fh).
// The sibling OAuth callback already compares `state` this way.
if (!storedState || !timingSafeCompare(storedState, returnedState)) {
if (!storedState || storedState !== returnedState) {
return NextResponse.redirect(new URL("/login?oidc_error=invalid_state", originEarly));
}

View File

@@ -1,5 +1,4 @@
import { createHmac } from "crypto";
import { timingSafeCompare } from "@/shared/utils/timingSafeCompare";
const ADMISSION_BYPASS_VALUE = "internal";
const SELF_LOOP_KEY = "sk_omniroute";
@@ -32,10 +31,7 @@ export function isInternalAdmissionBypass(request: Request): boolean {
const auth = request.headers.get("authorization") || "";
const match = /^bearer\s+(\S+)$/i.exec(auth.trim());
if (!match) return false;
// This gates an admission-lane bypass on a shared secret, so the compare is
// constant-time — `===` leaks matching-prefix length (GHSA-7434 class).
return timingSafeCompare(match[1].trim().toLowerCase(), resolveSelfLoopBearer().toLowerCase());
return Boolean(match && match[1].trim().toLowerCase() === resolveSelfLoopBearer().toLowerCase());
}
function fingerprint(value: string): string {

View File

@@ -1,27 +0,0 @@
import { timingSafeEqual } from "crypto";
/**
* Constant-time string comparison for secrets, tokens and single-use nonces.
*
* `===` short-circuits on the first differing byte, so rejection time
* correlates with how much of the value the caller already guessed (CWE-208).
* That is the comparison this repo already avoids in every OAuth callback, the
* A2A token check, the Telegram initData HMAC and the CLI token check — each of
* which grew its own private copy of these five lines. This is the shared one:
* reach for it instead of writing a ninth copy, and instead of `===`.
*
* Length is not secret here (it leaks through the early return, as it does in
* every other copy) — the value being protected is the content, not its size.
* `null`/`undefined` compare by identity so a missing secret never matches a
* present one.
*/
export function timingSafeCompare(
a: string | null | undefined,
b: string | null | undefined
): boolean {
if (a == null || b == null) return a === b;
const bufA = Buffer.from(String(a), "utf8");
const bufB = Buffer.from(String(b), "utf8");
if (bufA.length !== bufB.length) return false;
return timingSafeEqual(bufA, bufB);
}

View File

@@ -0,0 +1,63 @@
import test from "node:test";
import assert from "node:assert/strict";
import { resolveStreamReadinessTimeout } from "../../open-sse/utils/streamReadinessPolicy.ts";
import {
resolveFetchStartTimeout,
CODEX_CLIENT_ABORT_MS,
} from "../../open-sse/utils/fetchStartTimeoutPolicy.ts";
import { getUpstreamTimeoutConfig } from "../../src/shared/utils/runtimeTimeouts.ts";
function items(count: number): Array<{ role: string; content: string }> {
return Array.from({ length: count }, (_, index) => ({
role: "user",
content: `message ${index}`,
}));
}
function tools(count: number): Array<{ type: string; name: string }> {
return Array.from({ length: count }, (_, index) => ({ type: "function", name: `tool_${index}` }));
}
test("issue #11526: body-phase readiness watchdog stays comfortably under Codex's ~120s patience for the reported tool-heavy payload shape", () => {
const result = resolveStreamReadinessTimeout({
baseTimeoutMs: 80_000,
provider: "nvidia",
model: "some-nvidia-model",
body: { input: items(68), tools: tools(16) },
});
assert.ok(
result.timeoutMs < CODEX_CLIENT_ABORT_MS,
`body-phase watchdog (${result.timeoutMs}ms) must stay under Codex's ~120s patience`
);
});
test("issue #11526 (fixed): headers-phase watchdog for STREAMING requests is bounded under Codex's ~120s patience", () => {
const { fetchTimeoutMs } = getUpstreamTimeoutConfig({});
// Default FETCH_TIMEOUT_MS (600000ms) is still the flat non-streaming baseline —
// the fix does not touch that default, it caps how much of it a STREAMING
// request's headers-wait phase is allowed to consume.
assert.equal(fetchTimeoutMs, 600_000);
const streaming = resolveFetchStartTimeout({ baseTimeoutMs: fetchTimeoutMs, stream: true });
assert.ok(
streaming.timeoutMs <= CODEX_CLIENT_ABORT_MS,
`headers-phase watchdog for streaming requests (${streaming.timeoutMs}ms) must not exceed a realistic client abort window (${CODEX_CLIENT_ABORT_MS}ms)`
);
assert.ok(streaming.capped, "expected the oversized default to be capped for streaming requests");
});
test("issue #11526 scope guard: non-streaming requests keep the flat FETCH_TIMEOUT_MS default", () => {
const { fetchTimeoutMs } = getUpstreamTimeoutConfig({});
const nonStreaming = resolveFetchStartTimeout({ baseTimeoutMs: fetchTimeoutMs, stream: false });
assert.equal(nonStreaming.timeoutMs, fetchTimeoutMs);
assert.equal(nonStreaming.capped, false);
});
test("issue #11526 scope guard: a base timeout already under the cap is left untouched for streaming requests", () => {
const result = resolveFetchStartTimeout({ baseTimeoutMs: 30_000, stream: true });
assert.equal(result.timeoutMs, 30_000);
assert.equal(result.capped, false);
});

View File

@@ -1,61 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { timingSafeCompare } from "../../src/shared/utils/timingSafeCompare.ts";
// GHSA-7434-6q4c-33fh — the OIDC callback compared the CSRF `state` cookie with
// `!==` while every sibling callback already used a constant-time compare. Low
// severity on its own (single-use nonce), but the pattern gets copied, so the
// guard below pins the two callsites to the shared helper.
test("timingSafeCompare accepts identical values", () => {
assert.equal(timingSafeCompare("abc123", "abc123"), true);
assert.equal(timingSafeCompare("", ""), true);
});
test("timingSafeCompare rejects different values, including same-length ones", () => {
assert.equal(timingSafeCompare("abc123", "abc124"), false);
assert.equal(timingSafeCompare("abc123", "xbc123"), false);
assert.equal(timingSafeCompare("abc", "abcdef"), false);
assert.equal(timingSafeCompare("abcdef", "abc"), false);
});
test("timingSafeCompare compares null/undefined by identity, never as a match", () => {
assert.equal(timingSafeCompare(null, null), true);
assert.equal(timingSafeCompare(undefined, undefined), true);
assert.equal(timingSafeCompare(null, undefined), false);
assert.equal(timingSafeCompare(null, "abc"), false);
assert.equal(timingSafeCompare("abc", undefined), false);
assert.equal(timingSafeCompare(undefined, ""), false);
});
test("timingSafeCompare is byte-exact, not unicode-normalizing", () => {
// "é" precomposed vs decomposed — different bytes, must not match.
assert.equal(timingSafeCompare("é", "é"), false);
});
function sourceOf(relPath: string): string {
return readFileSync(fileURLToPath(new URL(`../../${relPath}`, import.meta.url)), "utf8");
}
test("the OIDC callback validates `state` with the constant-time helper", () => {
const source = sourceOf("src/app/api/auth/oidc/callback/route.ts");
assert.ok(
source.includes("timingSafeCompare"),
"oidc/callback must compare the state cookie in constant time (GHSA-7434-6q4c-33fh)"
);
assert.ok(
!/storedState\s*!==\s*returnedState/.test(source),
"the short-circuiting `!==` state comparison is back"
);
});
test("the internal admission bypass compares its bearer in constant time", () => {
const source = sourceOf("src/shared/middleware/chatAdmissionIdentity.ts");
assert.ok(
source.includes("timingSafeCompare"),
"isInternalAdmissionBypass gates a bypass on a shared secret — compare it in constant time"
);
});