Compare commits

...

2 Commits

Author SHA1 Message Date
diegosouzapw
4625936608 chore(changelog): number the media polling fragment for #20824 2026-11-20 18:32:15 -03:00
diegosouzapw
0d56007238 fix(security): clamp media polling and guard syntx provider rules (CodeQL #1389, #1392)
Caller-supplied poll_interval_ms, timeout_ms and poll_timeout_ms on the
NanoBanana, Magnific, Black Forest Labs and RenderHour image handlers are
clamped (30 s interval, 10 min window) by a shared helper that never
shortens a default. The RenderHour poller passes the request abort signal
to sleep(). applySyntxProviderRules only runs own entries of the rules
table.
2026-11-20 18:22:31 -03:00
10 changed files with 315 additions and 18 deletions

View File

@@ -0,0 +1 @@
- **fix(security):** Image generation on NanoBanana, Magnific, Black Forest Labs and RenderHour caps a caller's `poll_interval_ms` at 30 s and `timeout_ms` / `poll_timeout_ms` at 10 minutes (defaults unchanged), and RenderHour stops waiting between polls when the request is aborted; SYNTX provider rules only run for names defined in the rules table, so an `ai_name` such as `constructor` or `__proto__` no longer reaches an inherited `Object.prototype` member (CodeQL #1389, #1392) ([#20824](https://github.com/cheaper-inference/OmniRoute/pull/20824))

View File

@@ -24,6 +24,7 @@ import { mapImageSize } from "../translator/image/sizeMapper.ts";
import { getCodexClientVersion, getCodexUserAgent } from "../config/codexClient.ts";
import { isCodexFreePlan } from "../executors/codex/tools.ts";
import { sleep } from "../utils/sleep.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
import { codexReferenceImageUrl } from "./imageGeneration/providers/codexReferences.ts";
export { shrinkCodexReferenceImage } from "./imageGeneration/providers/codexReferences.ts";
import {
@@ -2965,11 +2966,11 @@ async function handleNanoBananaImageGeneration({
return { success: false, status: 500, error: errorText };
}
const timeoutMs = normalizePositiveNumber(
const timeoutMs = clampPollTimeoutMs(
body.timeout_ms,
normalizePositiveNumber(process.env.NANOBANANA_POLL_TIMEOUT_MS, 120000)
);
const pollIntervalMs = normalizePositiveNumber(
const pollIntervalMs = clampPollIntervalMs(
body.poll_interval_ms,
normalizePositiveNumber(process.env.NANOBANANA_POLL_INTERVAL_MS, 2500)
);

View File

@@ -7,11 +7,11 @@
import { mapImageSize } from "../../../translator/image/sizeMapper.ts";
import { sleep } from "../../../utils/sleep.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
import { sanitizeErrorMessage } from "../../../utils/error.ts";
import {
extractImageInputs,
isHttpUrl,
normalizePositiveNumber,
normalizeProviderImagePayload,
normalizeRequestedImageFormat,
parseSizeToDimensions,
@@ -180,8 +180,8 @@ export async function handleBlackForestLabsImageGeneration({
}
async function pollBlackForestLabsResult({ pollingUrl, token, body, log }) {
const timeoutMs = normalizePositiveNumber(body.timeout_ms, 300000);
const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, 1500);
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, 1500);
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {

View File

@@ -9,6 +9,7 @@
import { saveCallLog } from "../../imageResult.ts";
import { sleep } from "../../../utils/sleep.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
import { sanitizeErrorMessage } from "../../../utils/error.ts";
import {
UPSTREAM_MEDIA_LIMITS,
@@ -19,12 +20,6 @@ import {
const DEFAULT_POLL_INTERVAL_MS = 4000;
const DEFAULT_POLL_TIMEOUT_MS = 180000;
function normalizePositiveNumber(value: unknown, fallback: number): number {
const n = Number(value);
if (!Number.isFinite(n) || n <= 0) return fallback;
return Math.floor(n);
}
interface MagnificProviderConfig {
baseUrl: string;
statusUrl?: string;
@@ -267,8 +262,8 @@ export async function handleMagnificImageGeneration({
const startTime = Date.now();
const token = credentials?.apiKey || "";
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
const pollTimeoutMs = normalizePositiveNumber(body.poll_timeout_ms, DEFAULT_POLL_TIMEOUT_MS);
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
const pollTimeoutMs = clampPollTimeoutMs(body.poll_timeout_ms, DEFAULT_POLL_TIMEOUT_MS);
if (log) {
log.info(
"IMAGE",

View File

@@ -10,7 +10,6 @@ import {
renderhourBaseUrl,
renderhourConfig,
renderhourFailure,
renderhourNumber,
renderhourToken,
runRenderhourJob,
uploadRenderhourInputs,
@@ -22,6 +21,7 @@ import {
saveImageErrorResult,
saveImageSuccessResult,
} from "../../imageGeneration.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
const MAX_IMAGES_PER_JOB = 4;
@@ -72,8 +72,8 @@ export async function handleRenderhourImageGeneration({
baseUrl,
token,
request,
timeoutMs: renderhourNumber(body.timeout_ms, 300_000),
pollIntervalMs: renderhourNumber(body.poll_interval_ms, 2000),
timeoutMs: clampPollTimeoutMs(body.timeout_ms, 300_000),
pollIntervalMs: clampPollIntervalMs(body.poll_interval_ms, 2000),
log,
signal,
});

View File

@@ -302,7 +302,7 @@ async function pollRenderhourJob({
error: `RenderHour job ${job.id} did not finish within ${Math.round(timeoutMs / 1000)} s`,
};
}
await sleep(delay);
await sleep(delay, signal);
delay = pollIntervalMs;
// Asking about a job also moves it forward on RenderHour's side.
const response = await fetch(`${baseUrl}/v1/generations/${encodeURIComponent(job.id)}`, {

View File

@@ -172,8 +172,10 @@ export function applySyntxProviderRules(
settings: JsonRecord,
ctx: { modelType: string; fileCount?: number }
): void {
// aiName comes from the caller's model id: only the table's own entries may run, never a
// member inherited from Object.prototype ("constructor", "__proto__", ...). CodeQL #1392.
if (!Object.hasOwn(PROVIDER_RULES, aiName)) return;
const handler = PROVIDER_RULES[aiName];
if (!handler) return;
handler(ctx.modelType || "", ctx.fileCount ?? 0, settings);
}

View File

@@ -0,0 +1,42 @@
/**
* Upper bounds for the polling knobs a caller may send to async media jobs
* (`poll_interval_ms`, `timeout_ms`, `poll_timeout_ms`).
*
* Those values feed `sleep()` and the polling deadline. Without a ceiling one request could hold
* a handler for days while the server kept polling the upstream with the operator's credential
* (CodeQL #1389, js/resource-exhaustion). Same pattern as `resolveCursorImageTimeoutMs` in
* handlers/imageGeneration/providers/cursorAgentImage.ts: only the untrusted request value is
* clamped; the fallback (a built-in or operator-configured default) is trusted and kept as is.
*/
/** Longest single wait between two polls; matches MAX_POLL_RETRY_DELAY_MS in pollRetry.ts. */
export const MAX_CALLER_POLL_INTERVAL_MS = 30_000;
/** Longest total polling window a caller may ask for (10 minutes). */
export const MAX_CALLER_POLL_TIMEOUT_MS = 600_000;
/** A whole number of milliseconds ≥ 1 from the request, or null when absent or unusable. */
function positiveWholeMs(value: unknown): number | null {
const n = Number(value);
if (!Number.isFinite(n)) return null;
const ms = Math.floor(n);
return ms >= 1 ? ms : null;
}
/**
* The caller's value clamped to `ceiling`, or `fallback` when the caller sent none. A fallback
* above the ceiling stays reachable, so a ceiling never shortens a default.
*/
export function clampCallerMs(value: unknown, fallback: number, ceiling: number): number {
const requested = positiveWholeMs(value);
if (requested === null) return fallback;
return Math.min(requested, Math.max(ceiling, fallback));
}
export function clampPollIntervalMs(value: unknown, fallback: number): number {
return clampCallerMs(value, fallback, MAX_CALLER_POLL_INTERVAL_MS);
}
export function clampPollTimeoutMs(value: unknown, fallback: number): number {
return clampCallerMs(value, fallback, MAX_CALLER_POLL_TIMEOUT_MS);
}

View File

@@ -0,0 +1,212 @@
// CodeQL #1389 (js/resource-exhaustion): `poll_interval_ms`, `timeout_ms` and
// `poll_timeout_ms` from the request body reached `sleep()` (open-sse/utils/sleep.ts) and the
// polling deadline with no upper bound, so one request could hold a handler for days while the
// server kept polling the upstream with the operator's credential.
//
// The handlers are driven against a fake upstream that never finishes. Timers created by
// `sleep()` are intercepted (identified by the call stack), recorded, and fired at once while a
// virtual clock advances by the requested delay, so a multi-day wait runs in milliseconds.
import test from "node:test";
import assert from "node:assert/strict";
import { handleImageGeneration } from "../../open-sse/handlers/imageGeneration.ts";
import {
MAX_CALLER_POLL_INTERVAL_MS,
MAX_CALLER_POLL_TIMEOUT_MS,
clampCallerMs,
clampPollIntervalMs,
clampPollTimeoutMs,
} from "../../open-sse/utils/pollBounds.ts";
const HUGE_MS = 1e12; // ~31 years
const INTERVAL_CEILING = 30_000;
const TIMEOUT_CEILING = 600_000;
const originalFetch = globalThis.fetch;
const originalSetTimeout = globalThis.setTimeout;
const originalDateNow = Date.now;
type SleepTrace = { sleeps: number[]; elapsedMs: () => number };
/** Intercepts timers created by utils/sleep.ts and drives a virtual clock with them. */
function installVirtualSleep(): SleepTrace {
const start = originalDateNow();
let offset = 0;
const sleeps: number[] = [];
Date.now = () => start + offset;
globalThis.setTimeout = ((fn: (...args: unknown[]) => void, ms?: number, ...args: unknown[]) => {
const stack = new Error().stack ?? "";
if (!stack.includes("utils/sleep.ts")) return originalSetTimeout(fn, ms, ...args);
const delay = Number(ms) || 0;
sleeps.push(delay);
offset += delay;
return originalSetTimeout(fn, 0, ...args);
}) as typeof setTimeout;
return { sleeps, elapsedMs: () => offset };
}
function restore() {
globalThis.fetch = originalFetch;
globalThis.setTimeout = originalSetTimeout;
Date.now = originalDateNow;
}
test.afterEach(restore);
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json" },
});
}
/** Upstream fakes that accept the job and report it as still running on every poll. */
const NEVER_FINISHING_UPSTREAMS: Record<string, { model: string; fetch: typeof fetch }> = {
nanobanana: {
model: "nanobanana/nanobanana-flash",
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.includes("/record-info")) return json({ data: { successFlag: 0 } });
return json({ data: { taskId: "task-1" } });
}) as typeof fetch,
},
magnific: {
model: "magnific/realism",
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.endsWith("/task-1"))
return json({ data: { task_id: "task-1", status: "IN_PROGRESS" } });
return json({ data: { task_id: "task-1", status: "CREATED" } });
}) as typeof fetch,
},
"black-forest-labs": {
model: "black-forest-labs/flux-2-pro",
fetch: (async (input: string | URL) => {
const url = String(input);
if (url === "https://api.bfl.ai/result/1") return json({ status: "Pending" });
return json({ id: "1", polling_url: "https://api.bfl.ai/result/1" });
}) as typeof fetch,
},
renderhour: {
model: "renderhour/z-image",
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.endsWith("/v1/generations")) return json({ id: "job-1", status: "queued" }, 201);
return json({ id: "job-1", status: "running" });
}) as typeof fetch,
},
};
async function runNeverFinishing(provider: string, extraBody: Record<string, unknown>) {
const upstream = NEVER_FINISHING_UPSTREAMS[provider];
globalThis.fetch = upstream.fetch;
const trace = installVirtualSleep();
const result = await handleImageGeneration({
body: { model: upstream.model, prompt: "a lighthouse", ...extraBody },
credentials: { apiKey: "test-key" },
log: null,
});
restore();
return { result, trace };
}
for (const provider of Object.keys(NEVER_FINISHING_UPSTREAMS)) {
test(`${provider}: a huge caller poll interval and timeout are clamped to the ceilings`, async () => {
const { result, trace } = await runNeverFinishing(provider, {
poll_interval_ms: HUGE_MS,
timeout_ms: HUGE_MS,
poll_timeout_ms: HUGE_MS,
});
assert.equal(result.success, false, "a job that never finishes must fail");
assert.ok(trace.sleeps.length > 0, "the handler polled at least once");
assert.ok(
Math.max(...trace.sleeps) <= INTERVAL_CEILING,
`longest single sleep ${Math.max(...trace.sleeps)}ms exceeds ${INTERVAL_CEILING}ms`
);
assert.ok(
trace.elapsedMs() <= TIMEOUT_CEILING + INTERVAL_CEILING,
`polling ran for ${trace.elapsedMs()}ms of virtual time, above the ${TIMEOUT_CEILING}ms ceiling`
);
});
test(`${provider}: a small caller poll interval is used as given`, async () => {
const { trace } = await runNeverFinishing(provider, {
poll_interval_ms: 1_000,
timeout_ms: 5_000,
poll_timeout_ms: 5_000,
});
assert.ok(trace.sleeps.length > 0);
assert.ok(
trace.sleeps.every((ms) => ms === 1_000),
`sleeps: ${trace.sleeps.join(",")}`
);
});
}
test("default poll intervals are unchanged when the caller sends none", async () => {
const expected: Record<string, number> = {
nanobanana: 2_500,
magnific: 4_000,
"black-forest-labs": 1_500,
renderhour: 2_000,
};
for (const [provider, interval] of Object.entries(expected)) {
const { trace } = await runNeverFinishing(provider, {});
assert.equal(trace.sleeps[0], interval, `${provider} default poll interval`);
}
});
test("timeout error messages report the clamped value", async () => {
// A huge interval too, so the unclamped code ends after one sleep instead of polling
// ~400 million times (which is the defect itself).
const huge = { timeout_ms: HUGE_MS, poll_interval_ms: HUGE_MS };
const nano = await runNeverFinishing("nanobanana", huge);
assert.match(String(nano.result.error), /timeout after 600000ms/);
const bfl = await runNeverFinishing("black-forest-labs", huge);
assert.match(String(bfl.result.error), /timed out after 600000ms/);
const rh = await runNeverFinishing("renderhour", huge);
assert.match(String(rh.result.error), /within 600 s/);
});
test("renderhour: aborting the request ends the wait between polls", async () => {
globalThis.fetch = (async (input: string | URL, init: RequestInit = {}) => {
init.signal?.throwIfAborted();
const url = String(input);
if (url.endsWith("/v1/generations")) return json({ id: "job-1", status: "queued" }, 201);
return json({ id: "job-1", status: "running" });
}) as typeof fetch;
const controller = new AbortController();
const timer = originalSetTimeout(() => controller.abort(), 50);
const startedAt = originalDateNow();
const result = await handleImageGeneration({
body: { model: "renderhour/z-image", prompt: "a lighthouse", poll_interval_ms: 30_000 },
credentials: { apiKey: "test-key" },
log: null,
signal: controller.signal,
});
clearTimeout(timer);
assert.equal(result.success, false);
assert.ok(
originalDateNow() - startedAt < 10_000,
"the 30 s sleep should end as soon as the request is aborted"
);
});
test("clampCallerMs: bounds caller values, never shrinks the fallback", () => {
assert.equal(MAX_CALLER_POLL_INTERVAL_MS, INTERVAL_CEILING);
assert.equal(MAX_CALLER_POLL_TIMEOUT_MS, TIMEOUT_CEILING);
assert.equal(clampCallerMs(HUGE_MS, 2_000, 30_000), 30_000);
assert.equal(clampCallerMs("1500.9", 2_000, 30_000), 1_500);
assert.equal(clampCallerMs(undefined, 2_000, 30_000), 2_000);
assert.equal(clampCallerMs(0, 2_000, 30_000), 2_000);
assert.equal(clampCallerMs(-5, 2_000, 30_000), 2_000);
assert.equal(clampCallerMs(Number.NaN, 2_000, 30_000), 2_000);
assert.equal(clampCallerMs(Infinity, 2_000, 30_000), 2_000);
assert.equal(clampCallerMs(0.5, 2_000, 30_000), 2_000, "sub-millisecond values would spin");
// A fallback above the ceiling (an operator default) is kept, and a caller may ask for it.
assert.equal(clampCallerMs(undefined, 900_000, 600_000), 900_000);
assert.equal(clampCallerMs(HUGE_MS, 900_000, 600_000), 900_000);
assert.equal(clampPollIntervalMs(HUGE_MS, 2_500), INTERVAL_CEILING);
assert.equal(clampPollTimeoutMs(HUGE_MS, 300_000), TIMEOUT_CEILING);
});

View File

@@ -0,0 +1,44 @@
// CodeQL #1392 (js/unvalidated-dynamic-method-call): applySyntxProviderRules indexed a plain
// object literal with the caller-chosen `aiName` (the text before "/" in the requested model), so
// names such as "constructor", "__proto__", "hasOwnProperty" or "valueOf" resolved to members
// inherited from Object.prototype and were invoked. Only the rules defined in the table may run;
// any other name takes the "no rule" path and leaves the settings untouched.
import { describe, it } from "node:test";
import assert from "node:assert/strict";
const { applySyntxProviderRules } = await import("../../open-sse/services/syntxMedia.ts");
const INHERITED_NAMES = ["constructor", "__proto__", "hasOwnProperty", "valueOf", "toString"];
describe("applySyntxProviderRules: only own rule entries run", () => {
for (const aiName of INHERITED_NAMES) {
it(`"${aiName}" takes the no-rule path without a TypeError`, () => {
const settings = { aspect_ratio: "1:1", resolution: "1K", style: "x" };
assert.doesNotThrow(() =>
applySyntxProviderRules(aiName, settings, { modelType: "m", fileCount: 0 })
);
assert.deepEqual(settings, { aspect_ratio: "1:1", resolution: "1K", style: "x" });
});
}
it("never invokes the inherited Object.prototype.constructor", () => {
const original = Object.prototype.constructor;
let calls = 0;
// Swap the inherited member for a spy; a plain-object lookup of "constructor" reaches it.
Object.prototype.constructor = function spy() {
calls += 1;
} as unknown as ObjectConstructor;
try {
applySyntxProviderRules("constructor", {}, { modelType: "m" });
} finally {
Object.prototype.constructor = original;
}
assert.equal(calls, 0);
});
it("an own rule still applies", () => {
const settings = { model_type: "seedream-4.5", resolution: "1K" };
applySyntxProviderRules("seedream", settings, { modelType: "seedream-4.5" });
assert.equal(settings.resolution, "2K");
});
});