Compare commits

..

3 Commits

Author SHA1 Message Date
diegosouzapw
2a48a0a823 Merge remote-tracking branch 'origin/release/v3.8.55' into fix/codeql-redos-compression
# Conflicts:
#	open-sse/services/compression/engines/headroom/gcf/scalar.ts
#	open-sse/services/compression/engines/rtk/rawOutput.ts
2026-11-21 00:25:29 -03:00
diegosouzapw
c13cee2357 chore(changelog): prefix the fragment with PR #20825 2026-11-20 18:33:25 -03:00
diegosouzapw
eca9826d29 fix(security): bound regex work in compression engines (CodeQL #1301, #1302, #1349)
- headroom GCF needsQuote: inline-array regex excludes '[' from the bracket body (same .test verdict, linear on '[' runs).
- RTK raw-output: cut the tool_use command to 256 chars before the slug replaces.
- CCR grep: reject patterns with more than one unbounded quantifier and run the scan under a 1000 ms vm timeout.
2026-11-20 18:31:14 -03:00
51 changed files with 494 additions and 1805 deletions

View File

@@ -1 +0,0 @@
- **fix(security):** an HTTP 400 counts subscription/plan quota wording ("usage limit reached", "plan limit", weekly/session usage limits) as quota exhaustion only when the structured error code is a credit/quota code or the provider documents a message-only 400 form (`command-code`, `bai`, `openai-compatible-*`), the same contract as #20567, so such a phrase echoed from the request no longer puts a shared LLM or search connection on hold

View File

@@ -1 +0,0 @@
- **fix(security):** Choosing the local corpus root (`POST /api/settings/local-corpus`) or the Obsidian WebDAV vault (`POST /api/settings/obsidian/webdav`) now needs a dashboard session or the local CLI: API keys and access tokens of any scope get 403. Both routes also refuse the filesystem root, the home directory itself and system directories (`/etc`, `/usr`, `/bin`, `/sbin`, `/var`, `/proc`, `/sys`, `/dev`, `/boot`, `/root`) with a fixed 400 (CodeQL #1371, #1372, #1373)

View File

@@ -1 +0,0 @@
- **fix(security):** The internal chat admission bypass and the internal upstream-start cap are granted only on a per-process token held in memory; the deployment env key (`OMNIROUTE_API_KEY` / `ROUTER_API_KEY`) still authenticates requests but no longer marks them as internal

View File

@@ -1 +0,0 @@
- **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

@@ -0,0 +1 @@
- **fix(security):** Compression engines bound their regex work on hostile input: the headroom GCF inline-array check and the RTK raw-output command slug run in linear time, and CCR `grep` rejects patterns with more than one unbounded quantifier and stops a scan that exceeds a 1 s time budget (CodeQL #1301, #1302, #1349)

View File

@@ -1 +0,0 @@
- **fix(security):** The remaining async media handlers (Kie image, video and music; Runway; DashScope; Novita; MiniMax video; the video job presets; RenderHour video and speech; UC image and video) cap a caller's `poll_interval_ms` at 30 s and `timeout_ms` at 10 minutes, or at the built-in default when that is longer; defaults are unchanged (CodeQL #1389) ([#20867](https://github.com/cheaper-inference/OmniRoute/pull/20867))

View File

@@ -24,7 +24,6 @@ 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 {
@@ -1006,8 +1005,8 @@ async function handleKieImageGeneration({
}: KieImageOptions) {
const startTime = Date.now();
const token = credentials?.apiKey || credentials?.accessToken;
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, 2500);
const timeoutMs = normalizePositiveNumber(body.timeout_ms, 300000);
const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, 2500);
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
const size = typeof body.size === "string" ? body.size : undefined;
@@ -2966,11 +2965,11 @@ async function handleNanoBananaImageGeneration({
return { success: false, status: 500, error: errorText };
}
const timeoutMs = clampPollTimeoutMs(
const timeoutMs = normalizePositiveNumber(
body.timeout_ms,
normalizePositiveNumber(process.env.NANOBANANA_POLL_TIMEOUT_MS, 120000)
);
const pollIntervalMs = clampPollIntervalMs(
const pollIntervalMs = normalizePositiveNumber(
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 = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, 1500);
const timeoutMs = normalizePositiveNumber(body.timeout_ms, 300000);
const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, 1500);
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {

View File

@@ -9,7 +9,6 @@
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,
@@ -20,6 +19,12 @@ 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;
@@ -262,8 +267,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 = clampPollIntervalMs(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
const pollTimeoutMs = clampPollTimeoutMs(body.poll_timeout_ms, DEFAULT_POLL_TIMEOUT_MS);
const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
const pollTimeoutMs = normalizePositiveNumber(body.poll_timeout_ms, DEFAULT_POLL_TIMEOUT_MS);
if (log) {
log.info(
"IMAGE",

View File

@@ -10,6 +10,7 @@ import {
renderhourBaseUrl,
renderhourConfig,
renderhourFailure,
renderhourNumber,
renderhourToken,
runRenderhourJob,
uploadRenderhourInputs,
@@ -21,7 +22,6 @@ 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: clampPollTimeoutMs(body.timeout_ms, 300_000),
pollIntervalMs: clampPollIntervalMs(body.poll_interval_ms, 2000),
timeoutMs: renderhourNumber(body.timeout_ms, 300_000),
pollIntervalMs: renderhourNumber(body.poll_interval_ms, 2000),
log,
signal,
});

View File

@@ -34,7 +34,6 @@ import { resolveUcCredential } from "../../../executors/uc/credentials.ts";
import { mintUcSessionToken } from "../../../executors/uc/clerkAuth.ts";
import { UC_ORIGIN } from "../../../executors/uc/constants.ts";
import { sanitizeErrorMessage } from "../../../utils/error.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
import { saveImageErrorResult, saveImageSuccessResult } from "../../imageGeneration.ts";
/** Persona web image-gen endpoint (immediate response + result-URL polling). */
@@ -309,11 +308,11 @@ async function handleUcPersonaImage(
});
}
const timeoutMs = clampPollTimeoutMs(
const timeoutMs = normalizePositiveNumber(
body.timeout_ms,
normalizePositiveNumber(process.env.UC_IMAGE_POLL_TIMEOUT_MS, UC_POLL_TIMEOUT_MS_DEFAULT)
);
const pollIntervalMs = clampPollIntervalMs(
const pollIntervalMs = normalizePositiveNumber(
body.poll_interval_ms,
normalizePositiveNumber(process.env.UC_IMAGE_POLL_INTERVAL_MS, UC_POLL_INTERVAL_MS_DEFAULT)
);

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, signal);
await sleep(delay);
delay = pollIntervalMs;
// Asking about a job also moves it forward on RenderHour's side.
const response = await fetch(`${baseUrl}/v1/generations/${encodeURIComponent(job.id)}`, {
@@ -365,6 +365,11 @@ export async function runRenderhourJob({
return pollRenderhourJob({ baseUrl, token, job, timeoutMs, pollIntervalMs, log, signal });
}
/** A positive number from the request (e.g. `timeout_ms`), else the fallback. */
export function renderhourNumber(value: unknown, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
}
/** Turns a thrown upload / network error into the handlers' failure shape. */
export function renderhourFailure(err: unknown): { status: number; error: string } {
if (err instanceof RenderhourRequestError) {

View File

@@ -16,7 +16,6 @@
import { getMusicProvider, parseMusicModel } from "../config/musicRegistry.ts";
import { kieExecutor } from "../executors/kie.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
import { vertexGenerateMusic } from "../executors/vertexMedia.ts";
import {
submitComfyWorkflow,
@@ -362,8 +361,8 @@ async function handleKieMusicGeneration({
} | null;
}) {
const startTime = Date.now();
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, 2500);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
const token = credentials?.apiKey || credentials?.accessToken;
const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");

View File

@@ -9,10 +9,10 @@ import { errorResponse } from "../utils/error.ts";
import {
renderhourBaseUrl,
renderhourFailure,
renderhourNumber,
renderhourToken,
runRenderhourJob,
} from "./mediaGeneration/renderhour.ts";
import { clampPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
export async function handleRenderhourSpeech({
providerConfig,
@@ -37,8 +37,8 @@ export async function handleRenderhourSpeech({
baseUrl: renderhourBaseUrl(credentials, providerConfig.baseUrl),
token,
request: { model: modelId, text },
timeoutMs: clampPollTimeoutMs(body.timeout_ms, 180_000),
pollIntervalMs: clampPollIntervalMs(body.poll_interval_ms, 2000),
timeoutMs: renderhourNumber(body.timeout_ms, 180_000),
pollIntervalMs: renderhourNumber(body.poll_interval_ms, 2000),
});
if (result.ok === false) return errorResponse(result.status, result.error);
return audioStreamResponse(await fetch(result.job.outputs[0].url));

View File

@@ -16,7 +16,7 @@ import { fetchWithCheckedRedirects, isRegistryEndpoint } from "./redirectGuard.t
import type { SearchUrlGuard } from "./baseUrl.ts";
import { HTTP_STATUS } from "../../config/constants.ts";
import { lockBorrowedSearchKey } from "./borrowedKeyLock.ts";
import { isSubscriptionQuotaForStatus } from "../../services/quotaTextCooldowns.ts";
import { isSubscriptionQuotaText } from "../../services/quotaTextCooldowns.ts";
import type { SearchProviderConfig } from "../../config/searchRegistry.ts";
import type { SearchResult } from "../search.ts";
import {
@@ -53,9 +53,7 @@ export function shouldCoolDownSearchConnection(status: number, errorText: string
if (SEARCH_COOLDOWN_STATUSES.has(status)) return true;
const lower = errorText.toLowerCase();
if (SEARCH_CREDIT_EXHAUSTION_PHRASES.some((phrase) => lower.includes(phrase))) return true;
// A 400 can quote the caller's query back: plan/usage-limit wording counts on 400
// only with a structured quota code (same status contract as LLM fallback).
return isSubscriptionQuotaForStatus(status, null, errorText);
return isSubscriptionQuotaText(lower);
}
/** Post-dispatch state cleanup shared by JSON and SSE search providers. */

View File

@@ -30,11 +30,11 @@ import {
} from "./videoGeneration/job.ts";
import { abortedVideoResult, POLL_ABORTED, pollJsonAfter } from "./videoGeneration/abort.ts";
import { sleep } from "../utils/sleep.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
import {
downloadResultVideo,
extractRunwayFailureMessage,
normalizeRunwayVideoResult,
resolvePositiveInteger,
resultVideoErrorText,
resolveRunwayDuration,
resolveRunwayPromptImage,
@@ -135,11 +135,12 @@ function resolveVideoJobPollingOverrides(body: Record<string, unknown>): {
pollIntervalMs?: number;
} {
const maxPolls = Number(body.max_polls);
// 0 marks "not sent": the preset's own interval (2-5 s) then applies.
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 0);
const pollIntervalMs = Number(body.poll_interval_ms);
return {
...(Number.isFinite(maxPolls) && maxPolls > 0 ? { maxPolls: Math.floor(maxPolls) } : {}),
...(pollIntervalMs > 0 ? { pollIntervalMs } : {}),
...(Number.isFinite(pollIntervalMs) && pollIntervalMs > 0
? { pollIntervalMs: Math.floor(pollIntervalMs) }
: {}),
};
}
@@ -866,8 +867,8 @@ async function handleKieVideoGeneration({
} | null;
}) {
const startTime = Date.now();
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 2500);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
const token = credentials?.apiKey || credentials?.accessToken;
const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
@@ -976,8 +977,8 @@ async function handleRunwayVideoGeneration({
const ratio = resolveRunwayRatio(body);
const duration = resolveRunwayDuration(body);
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 5000);
const timeoutMs = resolvePositiveInteger(body.timeout_ms, 300000);
const pollIntervalMs = resolvePositiveInteger(body.poll_interval_ms, 5000);
const submitUrl = buildRunwayApiUrl(
useImageToVideo ? "/image_to_video" : "/text_to_video",
providerConfig.baseUrl

View File

@@ -3,7 +3,6 @@ import { saveCallLog } from "@/lib/usageDb";
import { resolveAlibabaProviderMediaBaseUrl } from "@/shared/constants/alibabaProviderRegions";
import { sanitizeErrorMessage } from "../../utils/error.ts";
import { sleep } from "../../utils/sleep.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
import { abortedVideoResult } from "./abort.ts";
// Shared with the DashScope TTS executor so the engine keeps a single import of this app
@@ -64,8 +63,8 @@ export async function handleDashscopeVideoGeneration({
signal?: AbortSignal | null;
}) {
const startTime = Date.now();
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, 2500);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
const token = credentials?.apiKey || credentials?.accessToken;
const isAlibabaManagedMediaProvider =
provider === "alibaba" ||

View File

@@ -16,7 +16,6 @@ import {
} from "@/shared/utils/fetchTimeout";
import { sanitizeErrorMessage } from "../../utils/error.ts";
import { sleep } from "../../utils/sleep.ts";
import { MAX_CALLER_POLL_TIMEOUT_MS } from "../../utils/pollBounds.ts";
import {
MAX_CONSECUTIVE_POLL_RETRIES,
computePollRetryDelayMs,
@@ -512,18 +511,8 @@ async function runVideoJobGeneration({
}
// Poll loop.
const maxPolls = maxPollsOverride ?? preset.maxPolls;
const pollInterval = pollIntervalOverride ?? preset.pollIntervalMs;
// A preset has no deadline: its window is maxPolls x interval. Caller overrides of either
// may not stretch it past the larger of the preset's own window and the caller ceiling
// (CodeQL #1389); with no override this leaves the preset's maxPolls unchanged.
const windowCeilingMs = Math.max(
preset.maxPolls * preset.pollIntervalMs,
MAX_CALLER_POLL_TIMEOUT_MS
);
const maxPolls = Math.min(
maxPollsOverride ?? preset.maxPolls,
Math.max(1, Math.floor(windowCeilingMs / pollInterval))
);
let consecutiveRetries = 0;
let nextDelay = pollInterval;

View File

@@ -12,7 +12,6 @@
import { saveCallLog } from "@/lib/usageDb";
import { sanitizeErrorMessage } from "../../utils/error.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
import { isJsonObject } from "../../utils/kieTask.ts";
import {
MAX_CONSECUTIVE_POLL_RETRIES,
@@ -197,8 +196,9 @@ export async function handleMinimaxVideoGeneration({
log?: MinimaxLog;
}): Promise<VideoResult> {
const startTime = Date.now();
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, DEFAULT_TIMEOUT_MS);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : DEFAULT_TIMEOUT_MS;
const pollIntervalMs =
Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : DEFAULT_POLL_INTERVAL_MS;
const token = credentials?.apiKey || credentials?.accessToken;
const request = buildMinimaxVideoRequestBody(

View File

@@ -9,7 +9,6 @@
import { sanitizeErrorMessage } from "../../utils/error.ts";
import { sleep } from "../../utils/sleep.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
import { abortedVideoResult } from "./abort.ts";
import {
buildNovitaPollUrl,
@@ -73,8 +72,9 @@ function resolveNovitaTiming(body: NovitaHandlerArgs["body"]): {
timeoutMs: number;
pollIntervalMs: number;
} {
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, DEFAULT_TIMEOUT_MS);
const pollIntervalMs = clampVideoPollIntervalMs(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : DEFAULT_TIMEOUT_MS;
const pollIntervalMs =
Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : DEFAULT_POLL_INTERVAL_MS;
return { timeoutMs, pollIntervalMs };
}

View File

@@ -57,7 +57,6 @@ import { resolveUcCredential } from "../../../executors/uc/credentials.ts";
import { mintUcSessionToken } from "../../../executors/uc/clerkAuth.ts";
import { UC_ORIGIN } from "../../../executors/uc/constants.ts";
import { sanitizeErrorMessage } from "../../../utils/error.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
/** Persona signed-upload-URL endpoint (for the image-to-video input image). */
export const UC_PERSONA_SIGNED_URL = "https://internal-6.pubyar.com/generate-signed-url";
@@ -560,8 +559,8 @@ async function handleUcPersonaVideo(ctx: PersonaContext): Promise<UcVideoResult>
Number.isFinite(timeoutSeconds) && timeoutSeconds > 0
? timeoutSeconds * 1000
: normalizePositiveNumber(process.env.UC_VIDEO_POLL_TIMEOUT_MS, UC_POLL_TIMEOUT_MS_DEFAULT);
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, defaultTimeoutMs);
const pollIntervalMs = clampVideoPollIntervalMs(
const timeoutMs = normalizePositiveNumber(body.timeout_ms, defaultTimeoutMs);
const pollIntervalMs = normalizePositiveNumber(
body.poll_interval_ms,
normalizePositiveNumber(process.env.UC_VIDEO_POLL_INTERVAL_MS, UC_POLL_INTERVAL_MS_DEFAULT)
);
@@ -703,8 +702,8 @@ async function handleUcDirectVideo(ctx: DirectContext): Promise<UcVideoResult> {
// Poll status_url until complete or timeout.
const statusUrl = extracted.statusUrl;
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, UC_POLL_TIMEOUT_MS_DEFAULT);
const pollIntervalMs = clampVideoPollIntervalMs(
const timeoutMs = normalizePositiveNumber(body.timeout_ms, UC_POLL_TIMEOUT_MS_DEFAULT);
const pollIntervalMs = normalizePositiveNumber(
body.poll_interval_ms,
UC_POLL_INTERVAL_MS_DEFAULT
);

View File

@@ -15,13 +15,13 @@ import {
renderhourBaseUrl,
renderhourConfig,
renderhourFailure,
renderhourNumber,
renderhourSeconds,
renderhourToken,
runRenderhourJob,
uploadRenderhourInputs,
type RenderhourUploadTarget,
} from "../mediaGeneration/renderhour.ts";
import { clampVideoPollIntervalMs, clampPollTimeoutMs } from "../../utils/pollBounds.ts";
type Body = Record<string, unknown>;
@@ -112,8 +112,8 @@ async function runVideoJob({
baseUrl,
token,
request,
timeoutMs: clampPollTimeoutMs(body.timeout_ms, 900_000),
pollIntervalMs: clampVideoPollIntervalMs(body.poll_interval_ms, 5000),
timeoutMs: renderhourNumber(body.timeout_ms, 900_000),
pollIntervalMs: renderhourNumber(body.poll_interval_ms, 5000),
log,
signal,
});

View File

@@ -86,6 +86,12 @@ function clampRunwayDuration(value) {
return Math.min(10, Math.max(2, duration));
}
export function resolvePositiveInteger(value, fallback) {
const numeric = Number(value);
if (!Number.isFinite(numeric) || numeric <= 0) return fallback;
return Math.floor(numeric);
}
function extractRunwayOutputUrls(task) {
const rawOutput = Array.isArray(task?.output)
? task.output

View File

@@ -138,10 +138,7 @@ import { resolveApiKeyForbiddenFallback } from "./accountFallback/nonRetryableUp
import * as exactModelLock from "./accountFallback/exactModelLock.ts";
import { isCreditsExhaustedWithSharedWallet } from "./accountFallback/sharedWalletCredits.ts";
import { CREDITS_EXHAUSTED_SIGNALS } from "./accountFallback/creditExhaustionSignals.ts";
import {
isCreditsExhaustedForStatus,
quotaTextSignalCountsForStatus,
} from "./accountFallback/creditsExhaustedForStatus.ts";
import { isCreditsExhaustedForStatus } from "./accountFallback/creditsExhaustedForStatus.ts";
export { CREDITS_EXHAUSTED_SIGNALS } from "./accountFallback/creditExhaustionSignals.ts";
import { isMistralAmbiguous401 } from "./accountFallback/mistralAmbiguousAuth.ts";
import { isRegisteredFeatureFlagEnabled } from "../utils/registeredFeatureFlag.ts";
@@ -2309,20 +2306,8 @@ export function checkFallbackError(
// UNCONDITIONALLY (not gated by shouldUseQuotaSignal) because it targets
// apikey-category providers like ollama-cloud, which the oauth-only
// shouldUseQuotaSignal gate deliberately excludes from the subscription
// check above. On 400 none of these quota TEXT signals counts without a structured
// code or an allow-listed provider: the message may quote the caller's own input.
const quotaTextCounts = quotaTextSignalCountsForStatus(
status,
provider,
errorStr,
structuredError?.code
);
if (
quotaTextCounts &&
shouldUseQuotaSignal &&
!isCreditsExhausted(errorStr) &&
!isDailyQuotaExhausted(errorStr)
) {
// check above.
if (shouldUseQuotaSignal && !isCreditsExhausted(errorStr) && !isDailyQuotaExhausted(errorStr)) {
const subResult = buildSubscriptionQuotaFallback(
errorStr,
getUpstreamRetryHint,
@@ -2332,17 +2317,14 @@ export function checkFallbackError(
);
if (subResult) return subResult;
}
const weeklyResult = quotaTextCounts
? buildWeeklyQuotaFallback(errorStr, undefined, provider)
: null;
const weeklyResult = buildWeeklyQuotaFallback(errorStr, undefined, provider);
if (weeklyResult) return weeklyResult;
// Issue #7071 (session usage cap) is the same sibling gap as #3709 above —
// runs UNCONDITIONALLY for the same reason: apikey-category providers
// like ollama-cloud are excluded from the oauth-only shouldUseQuotaSignal
// gate.
const sessionResult = quotaTextCounts
? (buildSessionQuotaFallback(errorStr) ?? buildRolling24hQuotaFallback(errorStr))
: null;
const sessionResult =
buildSessionQuotaFallback(errorStr) ?? buildRolling24hQuotaFallback(errorStr);
if (sessionResult) return sessionResult;
const detectedRetryHint = detectRetryHint();
@@ -2354,7 +2336,6 @@ export function checkFallbackError(
? "body"
: undefined;
if (
quotaTextCounts &&
shouldUseQuotaSignal &&
quotaResetHintMs &&
classifyErrorText(errorStr) === RateLimitReason.QUOTA_EXHAUSTED

View File

@@ -60,25 +60,6 @@ function hasCreditErrorCode(text: string, structured: unknown): boolean {
return codes.some((code) => CREDIT_ERROR_CODES.has(code.trim().toLowerCase()));
}
/**
* Whether a quota/credit TEXT signal found in an upstream error may count at this
* status. Every status except 400 keeps the plain text match; on 400 the signal
* counts only with a structured credit code or for an allow-listed provider (see
* the header). Shared by the credit check below and the subscription/plan quota
* text checks in quotaTextCooldowns.ts.
*/
export function quotaTextSignalCountsForStatus(
status: number,
provider: string | null | undefined,
errorText: string,
structured?: unknown
): boolean {
if (status !== 400) return true;
return (
allowsMessageOnlyCredit400(provider) || hasCreditErrorCode(String(errorText || ""), structured)
);
}
/**
* Status-aware credit exhaustion check shared by the classifier, the fallback
* engine and terminal-status resolution. `structured` is what the caller holds
@@ -92,5 +73,6 @@ export function isCreditsExhaustedForStatus(
): boolean {
const text = String(errorText || "");
if (!isCreditsExhaustedWithSharedWallet(text, CREDITS_EXHAUSTED_SIGNALS)) return false;
return quotaTextSignalCountsForStatus(status, provider, text, structured);
if (status !== 400) return true;
return allowsMessageOnlyCredit400(provider) || hasCreditErrorCode(text, structured);
}

View File

@@ -3,9 +3,12 @@
*
* `full`/absent → whole text (backward-compat). All modes are fail-safe:
* incoherent params or an unsafe regex yield { error }, never throw. The grep
* mode validates the pattern with `safe-regex` (no catastrophic backtracking)
* before compiling, and bounds matches/pattern length.
* mode validates the pattern with `safe-regex` (no nested quantifiers), allows at
* most one unbounded quantifier, bounds matches/pattern length, and runs the scan
* under a wall-clock budget (CodeQL #1349): a caller-supplied pattern can still be
* super-linear (`.*x` is quadratic per line), so the budget is the hard bound.
*/
import vm from "node:vm";
import safeRegex from "safe-regex";
export type CcrMode = "full" | "head" | "tail" | "lines" | "grep" | "stats";
@@ -24,6 +27,8 @@ export type CcrQueryResult = { content: string } | { error: string };
export const MAX_RANGE_LINES = 10_000;
export const MAX_GREP_MATCHES = 1_000;
export const MAX_PATTERN_LEN = 512;
/** Wall-clock budget for one grep scan over a block (ms). */
export const GREP_TIME_BUDGET_MS = 1_000;
const err = (m: string): CcrQueryResult => ({ error: m });
const ok = (c: string): CcrQueryResult => ({ content: c });
@@ -53,30 +58,104 @@ function sliceLines(lines: string[], start?: number, end?: number): CcrQueryResu
return ok(lines.slice(start - 1, Math.min(end, lines.length)).join("\n"));
}
function grepLines(lines: string[], pattern?: string, unique?: boolean): CcrQueryResult {
/**
* Number of unbounded quantifiers (`*`, `+`, `{n,}`) outside character classes and
* escapes. Two or more in sequence make the backtracking polynomial in the line length
* (`.*.*.*.*x` is O(n^4)), which `safe-regex`'s star-height check does not catch.
*/
export function countUnboundedQuantifiers(pattern: string): number {
let count = 0;
let i = 0;
while (i < pattern.length) {
const c = pattern[i];
if (c === "\\") {
i += 2;
} else if (c === "[") {
i = classEnd(pattern, i);
} else {
if (c === "*" || c === "+" || (c === "{" && isOpenRange(pattern, i))) count++;
i++;
}
}
return count;
}
/** Index just past the character class that opens at `start` (escapes honoured). */
function classEnd(pattern: string, start: number): number {
let i = start + 1;
while (i < pattern.length && pattern[i] !== "]") i += pattern[i] === "\\" ? 2 : 1;
return i + 1;
}
/** True when an open range quantifier `{n,}` starts at `start`. */
function isOpenRange(pattern: string, start: number): boolean {
let j = start + 1;
while (j < pattern.length && pattern[j] >= "0" && pattern[j] <= "9") j++;
return j > start + 1 && pattern[j] === "," && pattern[j + 1] === "}";
}
// The scan runs in a dedicated context only so `timeout` can stop a runaway regex.
// No host object enters it: inputs are primitives, the result leaves as a JSON string.
const GREP_SCRIPT = new vm.Script(`(() => {
"use strict";
let re;
try { re = new RegExp(grepPattern); } catch { return JSON.stringify({ invalid: true }); }
const matched = [];
let truncated = false;
for (const line of grepText.split("\\n")) {
if (re.test(line)) {
matched.push(line);
if (matched.length >= grepMaxMatches) { truncated = true; break; }
}
}
return JSON.stringify({ matched, truncated });
})()`);
let grepContext: vm.Context | null = null;
function runGrepScan(
text: string,
pattern: string
): { matched: string[]; truncated: boolean } | "invalid" | "timeout" {
grepContext ??= vm.createContext(Object.create(null), {
codeGeneration: { strings: false, wasm: false },
});
grepContext.grepPattern = pattern;
grepContext.grepText = text;
grepContext.grepMaxMatches = MAX_GREP_MATCHES;
let raw: unknown;
try {
raw = GREP_SCRIPT.runInContext(grepContext, { timeout: GREP_TIME_BUDGET_MS });
} catch (e) {
if ((e as { code?: string })?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT") return "timeout";
throw e;
} finally {
grepContext.grepText = "";
grepContext.grepPattern = "";
}
const parsed = JSON.parse(String(raw)) as {
invalid?: boolean;
matched?: string[];
truncated?: boolean;
};
if (parsed.invalid === true) return "invalid";
return { matched: parsed.matched ?? [], truncated: parsed.truncated === true };
}
function grepLines(text: string, pattern?: string, unique?: boolean): CcrQueryResult {
if (!pattern) return err("grep requires a 'pattern'");
if (pattern.length > MAX_PATTERN_LEN) return err(`pattern exceeds ${MAX_PATTERN_LEN} chars`);
if (!safeRegex(pattern)) return err("pattern rejected: potentially catastrophic backtracking");
let re: RegExp;
try {
re = new RegExp(pattern);
} catch {
return err("invalid regex pattern");
if (countUnboundedQuantifiers(pattern) > 1) {
return err("pattern rejected: at most one unbounded quantifier (*, +, {n,}) is allowed");
}
const matched: string[] = [];
let truncated = false;
for (const line of lines) {
if (re.test(line)) {
matched.push(line);
if (matched.length >= MAX_GREP_MATCHES) {
truncated = true;
break;
}
}
const scan = runGrepScan(text, pattern);
if (scan === "invalid") return err("invalid regex pattern");
if (scan === "timeout") {
return err(`grep exceeded its ${GREP_TIME_BUDGET_MS} ms time budget; use a narrower pattern`);
}
const out = unique ? [...new Set(matched)] : matched;
const out = unique ? [...new Set(scan.matched)] : scan.matched;
const body = out.join("\n");
return ok(truncated ? `${body}\n…[truncated at ${MAX_GREP_MATCHES} matches]` : body);
return ok(scan.truncated ? `${body}\n…[truncated at ${MAX_GREP_MATCHES} matches]` : body);
}
function blockStats(text: string, lines: string[]): CcrQueryResult {
@@ -101,7 +180,7 @@ export function queryBlock(text: string, q: CcrQuery): CcrQueryResult {
case "lines":
return sliceLines(lines, q.start, q.end);
case "grep":
return grepLines(lines, q.pattern, q.unique);
return grepLines(text, q.pattern, q.unique);
case "stats":
return blockStats(text, lines);
default:

View File

@@ -5,7 +5,7 @@ import {
isDailyQuotaExhausted,
isOAuthInvalidToken,
} from "./accountFallback.ts";
import { isSubscriptionQuotaForStatus } from "./quotaTextCooldowns.ts";
import { isSubscriptionQuotaText } from "./quotaTextCooldowns.ts";
import { isCreditsExhaustedForStatus } from "./accountFallback/creditsExhaustedForStatus.ts";
import { isProviderSafetyRefusalBody } from "../utils/providerSafety.ts";
import { isModelScopedAccessDenial } from "./accountFallback/modelScopedAccessDenial.ts";
@@ -453,9 +453,8 @@ export function classifyProviderError(
const bodyStr = responseBodyToString(responseBody);
const creditsExhausted = isCreditsExhaustedForStatus(statusCode, provider, bodyStr);
// Claude's native weekly 429 wording is provider-scoped; omitting provider
// silently classified the long-window quota as a short RPM rate limit. On 400 the
// phrase needs a structured code (same contract as the credit signal above).
const subscriptionQuotaExhausted = isSubscriptionQuotaForStatus(statusCode, provider, bodyStr);
// silently classified the long-window quota as a short RPM rate limit.
const subscriptionQuotaExhausted = isSubscriptionQuotaText(bodyStr.toLowerCase(), provider);
const accountDeactivated = isAccountDeactivated(bodyStr);
const oauthInvalid = isOAuthInvalidToken(bodyStr);
const preserveQuota429 = shouldPreserveQuotaSignalsFor429(provider);

View File

@@ -12,7 +12,6 @@
import { RateLimitReason } from "../config/constants.ts";
import { parseDayGranularityResetMs, parseIsoDateTimeResetMs } from "./quotaResetParsing.ts";
import { quotaTextSignalCountsForStatus } from "./accountFallback/creditsExhaustedForStatus.ts";
type RateLimitReasonValue = (typeof RateLimitReason)[keyof typeof RateLimitReason];
@@ -65,26 +64,6 @@ export function isSubscriptionQuotaText(lower: string, provider?: string | null)
);
}
/**
* Status-aware form of isSubscriptionQuotaText, under the same contract as the
* credit signal (creditsExhaustedForStatus.ts): a 400 often quotes the caller's
* own input back in its message, so on 400 the phrase counts only with a
* structured credit/quota code or for a provider whose documented 400 form is
* message-only. Every other status keeps the plain text match.
*/
export function isSubscriptionQuotaForStatus(
status: number,
provider: string | null | undefined,
errorText: string,
structured?: unknown
): boolean {
const text = String(errorText || "");
return (
isSubscriptionQuotaText(text.toLowerCase(), provider) &&
quotaTextSignalCountsForStatus(status, provider, text, structured)
);
}
export const SUBSCRIPTION_QUOTA_COOLDOWN_MS = 60 * 60 * 1000; // 1 hour
/** Same value space as accountFallback.ts's RetryHintProvenance (kept local to avoid a circular import). */

View File

@@ -172,10 +172,8 @@ 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

@@ -1,53 +0,0 @@
/**
* 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 single wait between two polls of a VIDEO job. A video takes minutes to render, and
* providers such as Agnes document one-minute polling, so callers may ask for up to 2 minutes.
*/
export const MAX_CALLER_VIDEO_POLL_INTERVAL_MS = 120_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);
}
/** Same as clampPollIntervalMs with the video ceiling (MAX_CALLER_VIDEO_POLL_INTERVAL_MS). */
export function clampVideoPollIntervalMs(value: unknown, fallback: number): number {
return clampCallerMs(value, fallback, MAX_CALLER_VIDEO_POLL_INTERVAL_MS);
}
export function clampPollTimeoutMs(value: unknown, fallback: number): number {
return clampCallerMs(value, fallback, MAX_CALLER_POLL_TIMEOUT_MS);
}

View File

@@ -11,7 +11,6 @@ import {
getConfiguredLocalCorpusStatus,
resetLocalCorpusIndex,
} from "@/lib/localCorpus/configured";
import { requireOperatorCredential } from "@/lib/api/operatorCredential";
import { isAuthenticated } from "@/shared/utils/apiAuth";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
@@ -21,11 +20,6 @@ const localCorpusSchema = z
})
.strict();
// CodeQL #1371: the root is indexed and served by the MCP local-corpus search tools, so choosing
// it is an operator action. A machine credential (an API key of any scope) gets 403.
const LOCAL_CORPUS_ROOT_FORBIDDEN_MESSAGE =
"Choosing the local corpus root requires a signed-in dashboard session or the local CLI; API keys and access tokens cannot change it.";
export async function GET(request: NextRequest) {
if (!(await isAuthenticated(request))) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
@@ -46,10 +40,6 @@ export async function POST(request: NextRequest) {
if (!(await isAuthenticated(request))) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const operatorVerdict = await requireOperatorCredential(request, {
forbiddenMessage: LOCAL_CORPUS_ROOT_FORBIDDEN_MESSAGE,
});
if (operatorVerdict.ok === false) return operatorVerdict.response;
let body: unknown;
try {

View File

@@ -2,7 +2,6 @@ import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { isAuthenticated } from "@/shared/utils/apiAuth";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { requireOperatorCredential } from "@/lib/api/operatorCredential";
import { buildErrorBody } from "@omniroute/open-sse/utils/error";
import {
getObsidianSyncStatus,
@@ -16,12 +15,6 @@ const enableSchema = z
})
.strict();
// CodeQL #1372/#1373: the vault becomes the root of a read/write WebDAV service with freshly
// minted credentials, so choosing it is an operator action. The route is ALWAYS_PROTECTED, so an
// open instance (login disabled) does not make a machine credential the operator either.
const WEBDAV_VAULT_FORBIDDEN_MESSAGE =
"Choosing the WebDAV vault requires a signed-in dashboard session or the local CLI; API keys and access tokens cannot change it.";
export async function GET(request: NextRequest) {
if (!(await isAuthenticated(request))) {
return NextResponse.json(buildErrorBody(401, "Authentication required"), { status: 401 });
@@ -39,7 +32,8 @@ export async function GET(request: NextRequest) {
return NextResponse.json({
webdavEnabled: status.webdavEnabled,
webdavUsername: status.webdavEnabled ? status.webdavUsername : null,
webdavPassword: status.webdavEnabled && hasManagement ? status.webdavPassword : null,
webdavPassword:
status.webdavEnabled && hasManagement ? status.webdavPassword : null,
webdavPasswordSet: status.webdavEnabled && Boolean(status.webdavPassword),
vaultPath: status.vaultPath,
});
@@ -53,11 +47,6 @@ export async function POST(request: NextRequest) {
if (!(await isAuthenticated(request))) {
return NextResponse.json(buildErrorBody(401, "Authentication required"), { status: 401 });
}
const operatorVerdict = await requireOperatorCredential(request, {
forbiddenMessage: WEBDAV_VAULT_FORBIDDEN_MESSAGE,
alwaysRequireAuth: true,
});
if (operatorVerdict.ok === false) return operatorVerdict.response;
let rawBody: unknown;
try {
@@ -68,7 +57,10 @@ export async function POST(request: NextRequest) {
const parsed = enableSchema.safeParse(rawBody);
if (!parsed.success) {
return NextResponse.json(buildErrorBody(400, "Missing or invalid vaultPath"), { status: 400 });
return NextResponse.json(
buildErrorBody(400, "Missing or invalid vaultPath"),
{ status: 400 }
);
}
const result = await enableObsidianVaultSync(parsed.data.vaultPath);

View File

@@ -1,79 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
/**
* System directories that must never become the root of a host-filesystem surface (the local
* corpus indexed for the MCP search tools, the read/write Obsidian WebDAV vault). The directory
* itself and everything below it are refused, unless the canonical path lives inside the user's
* home directory (a service account whose home is `/root` or `/var/lib/<app>` keeps its folders).
* POSIX only: on Windows the drive root and the home directory itself are refused.
*/
const POSIX_SYSTEM_DIRECTORIES = [
"/etc",
"/usr",
"/bin",
"/sbin",
"/var",
"/proc",
"/sys",
"/dev",
"/boot",
"/root",
] as const;
/** Fixed refusal message: it never echoes the requested path back to the caller. */
export const DENIED_ROOT_DIRECTORY_ERROR =
"This directory cannot be used as a root: choose a dedicated folder, not the filesystem root, the home directory itself or a system directory";
/** Canonical (symlink-resolved) absolute form of a path; falls back to the lexical resolve. */
function canonicalPath(target: string): string {
const resolved = path.resolve(target);
try {
return fs.realpathSync.native(resolved);
} catch {
return resolved;
}
}
/** True when `child` is `parent` itself or lives anywhere below it. */
function isSameOrInside(parent: string, child: string): boolean {
const rel = path.relative(parent, child);
if (rel === "") return true;
if (path.isAbsolute(rel)) return false; // different drive (win32)
return rel !== ".." && !rel.startsWith(`..${path.sep}`);
}
function isFilesystemRoot(target: string): boolean {
return path.parse(target).root === target;
}
/**
* Is `candidate` a directory that must not be exposed as a corpus or vault root? Both the lexical
* (`path.resolve`) and canonical (`realpath`) forms are checked, so a symlink cannot dodge the
* comparison in either direction. Refused: the filesystem root (`/`, a drive root on Windows), the
* user's home directory itself (its subfolders stay allowed) and the POSIX system directories
* above.
*/
export function isDeniedRootDirectory(candidate: string): boolean {
const lexical = path.resolve(candidate);
const canonical = canonicalPath(candidate);
const forms = lexical === canonical ? [canonical] : [lexical, canonical];
if (forms.some(isFilesystemRoot)) return true;
const homeForms = [path.resolve(os.homedir()), canonicalPath(os.homedir())];
if (forms.some((form) => homeForms.includes(form))) return true;
if (process.platform === "win32") return false;
const canonicalHome = homeForms[1];
if (isFilesystemRoot(canonicalHome) === false && isSameOrInside(canonicalHome, canonical)) {
return false;
}
return POSIX_SYSTEM_DIRECTORIES.some((dir) => {
const dirForms = [dir, canonicalPath(dir)];
return dirForms.some((dirForm) => forms.some((form) => isSameOrInside(dirForm, form)));
});
}

View File

@@ -7,7 +7,6 @@ import { fetchRemoteImage } from "@/shared/network/remoteImageFetch";
import { getGuardedDispatcher } from "@omniroute/open-sse/utils/connectGuardDispatcher";
import { getRuntimePorts } from "@/lib/runtime/ports";
import { resolveSelfLoopBearer } from "@/shared/middleware/chatBodyAdmission";
import { ownListenerSelfHopToken, SELF_HOP_HEADER } from "@omniroute/open-sse/utils/selfHop";
import { getBestVisionModel, getFallbackModels, recordLatency } from "./visionBridgeRouter";
import { combineCredentialChecks } from "./visionBridgeKeyScope";
import { REGISTRY } from "@omniroute/open-sse/config/providers";
@@ -819,10 +818,10 @@ async function callVisionModelSingle(
// When routing through OmniRoute's own API, omit the vision-bridge
// guardrail on the sub-request to prevent infinite recursion.
// OmniRoute's own listener authenticates the self-loop bearer (the env key or the
// per-process secret, both accepted by API-key validation). Any other endpoint —
// api.openai.com, or another localhost server set as VISION_BRIDGE_BASE_URL — gets
// only the provider key and never an OmniRoute credential; with no provider key the
// header is omitted.
// per-process secret, both accepted by API-key validation), which the admission
// bypass below also requires. Any other endpoint — api.openai.com, or another
// localhost server set as VISION_BRIDGE_BASE_URL — gets only the provider key and
// never an OmniRoute credential; with no provider key the header is omitted.
// A bare-id call to our own listener keeps an operator VISION_BRIDGE_API_KEY.
const selfLoopBearer =
isOwnOmniRouteBaseUrl(baseUrl) && (useFullModelId || !resolvedApiKey)
@@ -852,13 +851,10 @@ async function callVisionModelSingle(
// Internal self-loop sub-request: the parent request already holds the
// single heavyweight admission lease (`CHAT_MAX_HEAVY_IN_FLIGHT=1`), so a
// large base64-image describe body would be rejected with 503
// `chat_admission_busy` before it is described. The route grants the bypass
// only on the per-process token, never on this header or the bearer (the env
// key is a key clients can hold). Production injects undici fetch, which
// skips proxyFetch's own-listener stamp, so the token is set here; this branch
// only runs for our own listener, so the token never leaves the process.
// `chat_admission_busy` before it is described. The route only honors
// this header when the bearer is the self-loop bearer (set above), so
// external clients cannot use it to bypass admission.
headers["x-omniroute-admission-bypass"] = "internal";
headers[SELF_HOP_HEADER] = ownListenerSelfHopToken();
// Scope the sub-request to the caller's key: the receiving chat request
// applies that key's connection/model policy (honored only alongside the
// self-loop bearer, so it can only narrow access).

View File

@@ -2,8 +2,6 @@ import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { DENIED_ROOT_DIRECTORY_ERROR, isDeniedRootDirectory } from "../deniedRootDirectories";
const DEFAULT_ALLOWED_EXTENSIONS = new Set([
".cfg",
".csv",
@@ -280,9 +278,6 @@ export async function canonicalizeLocalCorpusRoot(inputPath: string): Promise<st
} catch {
throw new Error("Local corpus root is not accessible");
}
if (isDeniedRootDirectory(canonical)) {
throw new Error(DENIED_ROOT_DIRECTORY_ERROR);
}
if (!stat.isDirectory()) {
throw new Error("Local corpus root must point to a directory");
}

View File

@@ -1,7 +1,6 @@
import fs from "node:fs";
import path from "node:path";
import { resolveDataDir } from "./dataPaths";
import { DENIED_ROOT_DIRECTORY_ERROR, isDeniedRootDirectory } from "./deniedRootDirectories";
import {
getObsidianVaultPath,
setObsidianVaultPath,
@@ -76,12 +75,6 @@ export async function enableObsidianVaultSync(
): Promise<ObsidianSyncEnableResult> {
const resolvedPath = path.resolve(vaultPath);
// The vault root is served read/write by the WebDAV file service: the filesystem root, the
// home directory itself and system directories are never a vault (CodeQL #1372/#1373).
if (isDeniedRootDirectory(resolvedPath)) {
return { success: false, error: DENIED_ROOT_DIRECTORY_ERROR };
}
if (!fs.existsSync(resolvedPath)) {
return { success: false, error: `Vault directory not found: ${resolvedPath}` };
}

View File

@@ -1,11 +1,11 @@
import { createHmac, randomBytes } from "crypto";
import { isOwnListenerSelfHop, SELF_HOP_HEADER } from "@omniroute/open-sse/utils/selfHop.ts";
import { timingSafeCompare } from "@/shared/utils/timingSafeCompare";
import { getProcessStore, sharedSymbol } from "@/shared/utils/processSingleton";
const ADMISSION_BYPASS_VALUE = "internal";
const FINGERPRINT_KEY = "omniroute-admission-fingerprint-v1";
// Descriptive marker an internal sub-request sends next to the process token. It is
// never trusted on its own: any client can set it.
export const ADMISSION_BYPASS_HEADER = "x-omniroute-admission-bypass";
export function resolveSessionId(request: Request): string {
@@ -25,9 +25,9 @@ export function resolveSessionId(request: Request): string {
// operator hasn't set OMNIROUTE_API_KEY/ROUTER_API_KEY (#13679: the previous fallback
// was the checked-in literal "sk_omniroute", a predictable shared secret anyone reading
// the source could forge). Both the in-process caller (audioBridgeHelpers /
// visionBridgeHelpers) and the verifier (API-key validation) read this same value. It
// lives on globalThis because the proxy (Next middleware bundle) and the route handlers
// load separate copies of this module.
// visionBridgeHelpers) and the verifiers (isInternalAdmissionBypass, API-key
// validation) read this same value. It lives on globalThis because the proxy (Next
// middleware bundle) and the route handlers load separate copies of this module.
const SELF_LOOP_SECRET_KEY = sharedSymbol("selfLoopSecret");
const selfLoopStore = globalThis as unknown as Record<symbol, string | undefined>;
@@ -48,16 +48,20 @@ export function resolveSelfLoopBearer(): string {
);
}
/**
* True only for a request this process sent to its own listener: our own fetches (#13593)
* and the internal sub-requests that also send ADMISSION_BYPASS_HEADER (the vision bridge
* describe call) carry the per-process token, held in memory only. The bypass header and
* any API key, the deployment env key (OMNIROUTE_API_KEY / ROUTER_API_KEY) included, are
* things a client can send, so neither vouches for the bypass (same rule as the internal
* test mark, #19292). The token compare is constant-time (isOwnListenerSelfHop).
*/
export function isInternalAdmissionBypass(request: Request): boolean {
return isOwnListenerSelfHop(request.headers.get(SELF_HOP_HEADER));
// #13593: our own fetch to this listener already holds the parent lease.
if (isOwnListenerSelfHop(request.headers.get(SELF_HOP_HEADER))) return true;
const bypass =
request.headers.get(ADMISSION_BYPASS_HEADER)?.trim().toLowerCase() === ADMISSION_BYPASS_VALUE;
if (!bypass) return false;
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());
}
function fingerprint(value: string): string {

View File

@@ -1,198 +0,0 @@
// The admission bypass (skip the heavyweight lease, honor the internal upstream-start
// cap) is only for calls this process makes to its own listener. An API key proves
// nothing about where a request came from: the deployment env key
// (OMNIROUTE_API_KEY / ROUTER_API_KEY) is an ordinary key a client can hold. So, as
// with the internal test mark (#19292), only the per-process token held in memory can
// vouch for the bypass.
import test from "node:test";
import assert from "node:assert/strict";
const core = await import("../../src/lib/db/core.ts");
const providersDb = await import("../../src/lib/db/providers.ts");
const { callVisionModel } = await import("../../src/lib/guardrails/visionBridgeHelpers.ts");
const { admitChatRequest, ChatAdmissionController } =
await import("../../src/shared/middleware/chatBodyAdmission.ts");
const { isInternalAdmissionBypass } =
await import("../../src/shared/middleware/chatAdmissionIdentity.ts");
const { INTERNAL_UPSTREAM_START_TIMEOUT_HEADER, resolveInternalUpstreamStartTimeoutMs } =
await import("../../src/sse/services/internalUpstreamStartTimeout.ts");
const { SELF_HOP_HEADER, ownListenerSelfHopToken } =
await import("../../open-sse/utils/selfHop.ts");
const DEPLOY_KEY = "sk-deployment-env-key";
const ENV_KEYS = ["OMNIROUTE_API_KEY", "ROUTER_API_KEY", "VISION_BRIDGE_BASE_URL"] as const;
const savedEnv = new Map(ENV_KEYS.map((key) => [key, process.env[key]]));
function setDeployKey(value: string | undefined) {
delete process.env.ROUTER_API_KEY;
if (value === undefined) delete process.env.OMNIROUTE_API_KEY;
else process.env.OMNIROUTE_API_KEY = value;
}
test.before(async () => {
delete process.env.VISION_BRIDGE_BASE_URL;
await providersDb.createProviderConnection({
provider: "openai",
authType: "apikey",
name: "admission-bypass-openai",
apiKey: "sk-test-openai",
});
});
test.afterEach(() => {
for (const [key, value] of savedEnv) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
test.after(() => {
core.resetDbInstance();
});
const bigBody = () =>
JSON.stringify({
model: "openai/gpt-4o-mini",
messages: [{ role: "user", content: "x".repeat(512 * 1024) }],
});
function chatRequest(headers: Record<string, string>, body = bigBody()) {
return new Request("http://localhost/v1/chat/completions", {
method: "POST",
headers: {
"content-type": "application/json",
"content-length": String(body.length),
...headers,
},
body,
});
}
/** Admission outcome while the single heavyweight slot is held by a parent request. */
async function admitWhileBusy(request: Request) {
const controller = new ChatAdmissionController(1);
const parentLease = controller.tryAcquireHeavy();
assert.ok(parentLease);
try {
const result = await admitChatRequest(request, {
controller,
largeBodyBytes: 32,
hardMaxBytes: 10 * 1024 * 1024,
heapPressureCheck: () => true,
});
return { result, activeHeavy: controller.activeHeavy };
} finally {
parentLease.release();
}
}
/** The headers the vision bridge sends on its describe call to this process's listener. */
async function visionSelfLoopHeaders(): Promise<Record<string, string>> {
let headers: Record<string, string> = {};
const fetchImpl: typeof fetch = async (_input, init) => {
headers = { ...((init?.headers ?? {}) as Record<string, string>) };
return Response.json({ choices: [{ message: { content: "A green square" } }] });
};
const result = await callVisionModel("data:image/png;base64,iVBORw0KGgo", {
model: "openai/gpt-4o-mini",
prompt: "Describe",
timeoutMs: 30_000,
maxImages: 1,
routeThroughOmniRoute: true,
fetchImpl,
});
assert.equal(result, "A green square");
return headers;
}
test("a client holding the deployment env key cannot claim the admission bypass", async () => {
setDeployKey(DEPLOY_KEY);
const headers = {
"x-omniroute-admission-bypass": "internal",
authorization: `Bearer ${DEPLOY_KEY}`,
};
assert.equal(isInternalAdmissionBypass(chatRequest(headers)), false);
const { result, activeHeavy } = await admitWhileBusy(chatRequest(headers));
assert.equal(result.admit, false, "the deployment key alone must not skip the admission queue");
if (!result.admit) assert.equal(result.response.status, 503);
assert.equal(activeHeavy, 1);
});
test("a client holding the deployment env key cannot set the internal upstream-start cap", () => {
setDeployKey(DEPLOY_KEY);
const request = chatRequest({
"x-omniroute-admission-bypass": "internal",
authorization: `Bearer ${DEPLOY_KEY}`,
[INTERNAL_UPSTREAM_START_TIMEOUT_HEADER]: "1000",
});
assert.equal(resolveInternalUpstreamStartTimeoutMs(request), undefined);
});
test("a forged or empty process token does not grant the bypass", () => {
setDeployKey(DEPLOY_KEY);
const base = {
"x-omniroute-admission-bypass": "internal",
authorization: `Bearer ${DEPLOY_KEY}`,
};
assert.equal(
isInternalAdmissionBypass(chatRequest({ ...base, [SELF_HOP_HEADER]: "0".repeat(64) })),
false
);
assert.equal(isInternalAdmissionBypass(chatRequest({ ...base, [SELF_HOP_HEADER]: "" })), false);
assert.equal(
isInternalAdmissionBypass(chatRequest({ ...base, [SELF_HOP_HEADER]: DEPLOY_KEY })),
false
);
});
for (const [label, deployKey] of [
["with a deployment env key", DEPLOY_KEY],
["without a deployment env key", undefined],
] as const) {
test(`the vision bridge describe call is still an internal bypass ${label}`, async () => {
setDeployKey(deployKey);
const headers = await visionSelfLoopHeaders();
assert.equal(headers[SELF_HOP_HEADER], ownListenerSelfHopToken());
assert.notEqual(headers[SELF_HOP_HEADER], DEPLOY_KEY);
assert.equal(isInternalAdmissionBypass(chatRequest(headers)), true);
const { result, activeHeavy } = await admitWhileBusy(chatRequest(headers));
assert.equal(result.admit, true, "the describe call must not wait behind its own parent");
assert.equal(activeHeavy, 1, "the bypass must not reserve a second lease");
const capped = chatRequest({ ...headers, [INTERNAL_UPSTREAM_START_TIMEOUT_HEADER]: "5000" });
assert.equal(resolveInternalUpstreamStartTimeoutMs(capped), 5000);
});
}
test("the process token never goes to another endpoint", async () => {
setDeployKey(DEPLOY_KEY);
process.env.VISION_BRIDGE_BASE_URL = "http://localhost:11434/v1";
await providersDb.createProviderConnection({
provider: "gemini",
authType: "apikey",
name: "admission-bypass-gemini",
apiKey: "sk-test-gemini",
});
let headers: Record<string, string> = {};
const fetchImpl: typeof fetch = async (_input, init) => {
headers = { ...((init?.headers ?? {}) as Record<string, string>) };
return Response.json({ choices: [{ message: { content: "A green square" } }] });
};
await callVisionModel("data:image/png;base64,iVBORw0KGgo", {
model: "gemini/gemini-2.5-flash",
prompt: "Describe",
timeoutMs: 30_000,
maxImages: 1,
fetchImpl,
});
assert.equal(headers[SELF_HOP_HEADER], undefined);
assert.equal(headers["x-omniroute-admission-bypass"], undefined);
});

View File

@@ -16,8 +16,6 @@ const {
resolveSelfLoopBearer,
} = admissionModule;
const { withEarlyStreamKeepalive } = await import("../../open-sse/utils/earlyStreamKeepalive.ts");
const { SELF_HOP_HEADER, ownListenerSelfHopToken } =
await import("../../open-sse/utils/selfHop.ts");
const { getActiveRequestCount } = await import("../../src/lib/gracefulShutdown.ts");
/**
@@ -635,8 +633,6 @@ function selfLoopChatRequest(
// test wraps itself in withSelfLoopEnv({}) so it is deterministic even when
// the developer's shell has OMNIROUTE_API_KEY set).
authorization: `Bearer ${resolveSelfLoopBearer()}`,
// The per-process token is what grants the bypass; the header and bearer alone do not.
[SELF_HOP_HEADER]: ownListenerSelfHopToken(),
};
if (contentLength !== null) headers["content-length"] = contentLength;
return new Request("http://x/v1/chat/completions", {
@@ -831,7 +827,7 @@ test("resolveSelfLoopBearer uses ROUTER_API_KEY when OMNIROUTE_API_KEY is unset"
}
});
test("env-key self-loop call bypasses admission when it carries the process token (REQUIRE_API_KEY deployment)", async () => {
test("env-key bearer is honored as a self-loop admission bypass (REQUIRE_API_KEY deployment)", async () => {
const restore = withSelfLoopEnv({ OMNIROUTE_API_KEY: "env-key" });
try {
const controller = new ChatAdmissionController(1);
@@ -849,7 +845,6 @@ test("env-key self-loop call bypasses admission when it carries the process toke
"content-type": "application/json",
"x-omniroute-admission-bypass": "internal",
authorization: "Bearer env-key",
[SELF_HOP_HEADER]: ownListenerSelfHopToken(),
"content-length": String(body.length),
},
body,

View File

@@ -0,0 +1,219 @@
/**
* Regex work in the compression engines stays bounded on hostile input
* (CodeQL #1301, #1302, #1349).
*
* - #1301 headroom/gcf needsQuote(): the inline-array check ran in O(n^2) on runs of `[`.
* - #1302 rtk maybePersistRtkRawOutput(): the command slug trim ran in O(n^2) on runs of `_`
* from a client-supplied tool_use command of unbounded length.
* - #1349 ccr grep: a caller-supplied pattern such as `.*.*.*.*x` passed the star-height
* gate and blocked the event loop for minutes on a single long line.
*
* Each block pairs a timing assertion (the pathological input finishes fast or is refused)
* with a behaviour assertion (ordinary input gives the same result as before).
*/
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { needsQuote } from "../../../open-sse/services/compression/engines/headroom/gcf/scalar.ts";
import { maybePersistRtkRawOutput } from "../../../open-sse/services/compression/engines/rtk/rawOutput.ts";
import { queryBlock } from "../../../open-sse/services/compression/engines/ccr/ccrQuery.ts";
/** Ceiling for the fixed paths. They run in a few ms when idle; before the fix the same
* inputs took 10 s (#1301), 21 s (#1302) and minutes (#1349). The headroom absorbs a loaded
* CI runner (one fixed case reached 806 ms at load average 44) without hiding a regression. */
const FAST_MS = 1_000;
/** Upper bound for a grep stopped by its 1 s time budget (budget plus scheduling slack). */
const BUDGET_CEILING_MS = 5_000;
function timed<T>(fn: () => T): { value: T; ms: number } {
const t0 = performance.now();
const value = fn();
return { value, ms: performance.now() - t0 };
}
/** Reference semantics of the SPEC 2.4 inline-array rule: some `[` whose first following
* `]` is followed by optional whitespace and a `:`. Written as a plain linear scan. */
function hasInlineArrayHeader(s: string): boolean {
for (let i = 0; i < s.length; i++) {
if (s[i] !== "[") continue;
const close = s.indexOf("]", i + 1);
if (close === -1) return false;
let k = close + 1;
while (k < s.length && /\s/.test(s[k])) k++;
if (s[k] === ":") return true;
}
return false;
}
/** Deterministic PRNG (mulberry32) so the equivalence sample is reproducible. */
function prng(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
describe("#1301 headroom/gcf needsQuote inline-array check", () => {
it("finishes fast on 50k '[' characters", () => {
for (const s of [
"[".repeat(50_000),
"a" + "[".repeat(50_000) + "]",
"[".repeat(50_000) + "]x",
]) {
const { value, ms } = timed(() => needsQuote(s));
assert.equal(value, false);
assert.ok(ms < FAST_MS, `needsQuote took ${ms.toFixed(1)}ms on ${s.length} chars`);
}
});
it("keeps the same verdict on ordinary values", () => {
assert.equal(needsQuote("ERR[404]: Not Found"), true);
assert.equal(needsQuote("[Speaker 1]: Hello"), true);
assert.equal(needsQuote("a[[b]: c"), true);
assert.equal(needsQuote("x[a[b] :y"), true);
assert.equal(needsQuote("arr[0] index"), false);
assert.equal(needsQuote("a]: [b"), false);
assert.equal(needsQuote("a[b] c: d"), false);
});
it("matches the reference rule on a random sample", () => {
const rand = prng(1301);
const alphabet = "[]: ab";
for (let n = 0; n < 20_000; n++) {
const len = Math.floor(rand() * 12);
let body = "";
for (let i = 0; i < len; i++) body += alphabet[Math.floor(rand() * alphabet.length)];
// Leading/trailing 'a' keeps the other needsQuote rules (edge space, numeric, '#'…)
// out of the way, so the verdict depends only on the inline-array rule.
const s = `a${body}a`;
assert.equal(needsQuote(s), hasInlineArrayHeader(s), JSON.stringify(s));
}
});
});
describe("#1302 rtk raw-output command slug", () => {
function persist(command: string) {
const base = process.env.DATA_DIR || os.tmpdir();
const dataDir = fs.mkdtempSync(path.join(base, "rtk-slug-"));
const previous = process.env.DATA_DIR;
process.env.DATA_DIR = dataDir;
try {
return timed(() =>
maybePersistRtkRawOutput("error: build failed\nline 2", { retention: "always", command })
);
} finally {
if (previous === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = previous;
fs.rmSync(dataDir, { recursive: true, force: true });
}
}
function slugOf(pointerPath: string): string {
const match = /^\d+-(.*)-[0-9a-f]{24}\.log$/.exec(path.basename(pointerPath));
assert.ok(match, pointerPath);
return match[1];
}
it("finishes fast on a 50k-underscore command", () => {
for (const command of ["_".repeat(50_000) + "x", "x" + "_".repeat(50_000) + "x"]) {
const { value, ms } = persist(command);
assert.ok(value, "pointer expected");
assert.ok(ms < FAST_MS, `slug took ${ms.toFixed(1)}ms on ${command.length} chars`);
}
});
it("keeps the same slug for ordinary commands", () => {
const cases: Array<[string, string]> = [
["git status --short", "git_status_--short"],
[" npm test -- --watch=false ", "npm_test_--_--watch_false"],
["__init__", "init"],
["cargo build --release && ./target/release/app", "cargo_build_--release_target_release_app"],
["a".repeat(100), "a".repeat(48)],
];
for (const [command, expected] of cases) {
const { value } = persist(command);
assert.ok(value);
assert.equal(slugOf(value.path), expected, command);
}
const { value } = persist("");
assert.ok(value);
assert.equal(slugOf(value.path), "tool-output");
});
});
describe("#1349 ccr grep pattern", () => {
it("refuses a multi-quantifier pattern on a 500+ char line quickly", () => {
const text = "a".repeat(600);
const { value, ms } = timed(() => queryBlock(text, { mode: "grep", pattern: ".*.*.*.*x" }));
assert.ok("error" in value, JSON.stringify(value));
assert.ok(ms < FAST_MS, `grep took ${ms.toFixed(1)}ms`);
});
it("stops a single-quantifier pattern that exceeds the time budget", () => {
// 2 MiB of 4096-char lines: `.*x` is quadratic per line (minutes before the fix).
const text = Array.from({ length: 512 }, () => "a".repeat(4095)).join("\n");
const { value, ms } = timed(() => queryBlock(text, { mode: "grep", pattern: ".*x" }));
assert.ok("error" in value, JSON.stringify(value).slice(0, 200));
assert.match((value as { error: string }).error, /time budget/);
assert.ok(ms < BUDGET_CEILING_MS, `grep took ${ms.toFixed(1)}ms`);
});
it("counts only unbounded quantifiers outside classes and escapes", () => {
const tooMany = ["a.*b.*c", "\\d+\\.\\d+", "x{2,}y+", "a.*?b.+?c"];
for (const pattern of tooMany) {
const r = queryBlock("abc", { mode: "grep", pattern });
assert.ok("error" in r, pattern);
assert.match((r as { error: string }).error, /unbounded quantifier/, pattern);
}
const text = ["l1 ERROR upstream timeout", "l2 *+ literal", "l3 {2,} braces", "l4 ok"].join(
"\n"
);
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "ERROR.*timeout" }), {
content: "l1 ERROR upstream timeout",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "[*+]+ literal" }), {
content: "l2 *+ literal",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "\\*\\+ lit.*" }), {
content: "l2 *+ literal",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "\\{2,\\} b.*s" }), {
content: "l3 {2,} braces",
});
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "l[0-9]{1,2} (ok|ERROR)" }), {
content: "l1 ERROR upstream timeout\nl4 ok",
});
});
it("keeps grep results unchanged on an ordinary log block", () => {
const lines = Array.from(
{ length: 5_000 },
(_, i) => `2026-11-20T10:00:${String(i % 60).padStart(2, "0")}Z INFO req=${i} status=200`
);
lines[1234] = "2026-11-20T10:00:34Z ERROR req=1234 upstream timeout";
lines[4321] = "2026-11-20T10:00:01Z WARN req=4321 slow upstream";
const text = lines.join("\n");
const expected = (re: RegExp) => lines.filter((l) => re.test(l)).join("\n");
for (const pattern of ["ERROR", "(WARN|ERROR) req=", "req=12\\d\\d ", "^\\S+ WARN"]) {
assert.deepEqual(
queryBlock(text, { mode: "grep", pattern }),
{ content: expected(new RegExp(pattern)) },
pattern
);
}
assert.deepEqual(queryBlock(text, { mode: "grep", pattern: "INFO", unique: true }), {
content: lines
.filter((l) => l.includes("INFO"))
.slice(0, 1000)
.join("\n")
.concat("\n…[truncated at 1000 matches]"),
});
});
});

View File

@@ -467,7 +467,7 @@ test("stampOwnListenerSelfHop stamps only requests to this process's own listene
assert.equal(new Headers(presetOpts.headers).get("x-omniroute-self-hop"), "preset");
});
test("vision-bridge describe self-loop: recursion-guard headers and the process token sent", async () => {
test("vision-bridge describe self-loop: recursion-guard headers sent, no self-hop header", async () => {
await createProviderConnection({
provider: "openai",
authType: "apikey",
@@ -495,10 +495,13 @@ test("vision-bridge describe self-loop: recursion-guard headers and the process
assert.equal(headers["x-omniroute-compression"], "off");
assert.equal(headers["x-omniroute-admission-bypass"], "internal");
assert.equal(headers.Authorization, `Bearer ${resolveSelfLoopBearer()}`);
// characterization: production injects undici fetch (visionBridge.ts), which bypasses
// proxyFetch's stamp, so the describe call sets x-omniroute-self-hop itself: admission
// grants the bypass only on that per-process token, never on the header + bearer alone.
assert.equal(headers["x-omniroute-self-hop"], selfHop.ownListenerSelfHopToken());
// characterization: the describe call is built WITHOUT x-omniroute-self-hop. Production
// injects undici fetch (visionBridge.ts) which bypasses proxyFetch's stamp, so admission
// relies on x-omniroute-admission-bypass + the self-loop bearer instead.
assert.equal(
Object.keys(headers).some((h) => h.toLowerCase() === "x-omniroute-self-hop"),
false
);
// The receiving chat route resolves the recursion-guard header into a disable list that
// makes the nested pre-call pass skip both bridges.

View File

@@ -194,8 +194,8 @@ test("proxyFetch stamps the self-hop header before any dispatch decision", () =>
test("characterization: the vision-bridge describe call uses undici fetch, bypassing the self-hop stamp", () => {
// VisionBridgeGuardrail injects `undiciFetch` as fetchImpl, so the describe self-call never
// passes through proxyFetch.patchedFetchUnrecorded and is never stamped there; the describe
// call sets x-omniroute-self-hop itself, the only thing admission trusts for the bypass
// passes through proxyFetch.patchedFetchUnrecorded and carries no x-omniroute-self-hop
// header; admission instead relies on x-omniroute-admission-bypass + the self-loop bearer
// (pinned behaviorally in guardrail-pipeline-characterization.test.ts).
const bridge = read("src/lib/guardrails/visionBridge.ts");
assert.match(bridge, /import \{ fetch as undiciFetch \} from "undici";/);
@@ -205,13 +205,7 @@ test("characterization: the vision-bridge describe call uses undici fetch, bypas
/fetchImpl: undiciFetch as unknown as typeof fetch,/
);
const helpers = read("src/lib/guardrails/visionBridgeHelpers.ts");
// The token is set by hand, and only inside the own-listener (self-loop bearer) branch.
const selfLoopBranch = indexOrFail(helpers, "if (selfLoopBearer) {");
assert.match(
helpers.slice(selfLoopBranch, selfLoopBranch + 1200),
/headers\[SELF_HOP_HEADER\] = ownListenerSelfHopToken\(\);/
);
assert.equal(helpers.match(/ownListenerSelfHopToken\(\)/g)?.length, 1);
assert.doesNotMatch(helpers, /self-hop|selfHop/);
assert.match(helpers, /headers\["x-omniroute-disabled-guardrails"\] = routeThroughOmniRoute/);
});

View File

@@ -4,7 +4,6 @@ import {
INTERNAL_UPSTREAM_START_TIMEOUT_HEADER,
resolveInternalUpstreamStartTimeoutMs,
} from "../../src/sse/services/internalUpstreamStartTimeout.ts";
import { SELF_HOP_HEADER, ownListenerSelfHopToken } from "../../open-sse/utils/selfHop.ts";
const oldKey = process.env.OMNIROUTE_API_KEY;
process.env.OMNIROUTE_API_KEY = "trusted-internal-test-key";
@@ -14,19 +13,15 @@ test.after(() => {
else process.env.OMNIROUTE_API_KEY = oldKey;
});
function req(
value: string,
bearer = "trusted-internal-test-key",
bypass = "internal",
selfHop: string | null = ownListenerSelfHopToken()
) {
const headers: Record<string, string> = {
authorization: `Bearer ${bearer}`,
"x-omniroute-admission-bypass": bypass,
[INTERNAL_UPSTREAM_START_TIMEOUT_HEADER]: value,
};
if (selfHop !== null) headers[SELF_HOP_HEADER] = selfHop;
return new Request("http://127.0.0.1:20128/v1/chat/completions", { method: "POST", headers });
function req(value: string, bearer = "trusted-internal-test-key", bypass = "internal") {
return new Request("http://127.0.0.1:20128/v1/chat/completions", {
method: "POST",
headers: {
authorization: `Bearer ${bearer}`,
"x-omniroute-admission-bypass": bypass,
[INTERNAL_UPSTREAM_START_TIMEOUT_HEADER]: value,
},
});
}
test("trusted internal caller may set a bounded upstream-start cap", () => {
@@ -36,22 +31,9 @@ test("trusted internal caller may set a bounded upstream-start cap", () => {
});
test("ordinary or forged callers cannot set the internal upstream-start cap", () => {
const envKey = "trusted-internal-test-key";
// The deployment env key is a key clients hold: with the bypass header it still proves nothing.
assert.equal(resolveInternalUpstreamStartTimeoutMs(req("5000", "wrong-key")), undefined);
assert.equal(
resolveInternalUpstreamStartTimeoutMs(req("5000", envKey, "internal", null)),
undefined
);
assert.equal(
resolveInternalUpstreamStartTimeoutMs(req("5000", "wrong-key", "internal", null)),
undefined
);
assert.equal(
resolveInternalUpstreamStartTimeoutMs(req("5000", envKey, "internal", "0".repeat(64))),
undefined
);
assert.equal(
resolveInternalUpstreamStartTimeoutMs(req("5000", envKey, "internal", "")),
resolveInternalUpstreamStartTimeoutMs(req("5000", "trusted-internal-test-key", "no")),
undefined
);
});

View File

@@ -1,459 +0,0 @@
// CodeQL #1389 (js/resource-exhaustion), remaining sites after #20824: `poll_interval_ms` and
// `timeout_ms` from the request body still reached `sleep()` and the polling deadline with no
// upper bound in the Kie (image / video / music), Runway, DashScope, Novita, MiniMax, video
// job-preset, RenderHour video / speech and UC (image / video) handlers.
//
// Each handler is driven against a fake upstream that never finishes. Timers created by the
// polling 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. The
// UC handlers take an injectable sleep, so there the stub records the delay directly.
import test from "node:test";
import assert from "node:assert/strict";
import { handleImageGeneration } from "../../open-sse/handlers/imageGeneration.ts";
import { handleVideoGeneration } from "../../open-sse/handlers/videoGeneration.ts";
import { handleMusicGeneration } from "../../open-sse/handlers/musicGeneration.ts";
import { handleAudioSpeech } from "../../open-sse/handlers/audioSpeech.ts";
import { handleUcImageGeneration } from "../../open-sse/handlers/imageGeneration/providers/ucImage.ts";
import {
handleUcVideoGeneration,
UC_DIRECT_VIDEO_URL,
UC_PERSONA_TEXT_TO_VIDEO_URL,
} from "../../open-sse/handlers/videoGeneration/providers/ucVideo.ts";
import { UC_PERSONA_IMAGE_URL } from "../../open-sse/handlers/imageGeneration/providers/ucImage.ts";
import { isUcClerkMintUrl } from "./helpers/ucClerkUrl.ts";
const HUGE_MS = 1e12; // ~31 years
const INTERVAL_CEILING = 30_000;
// Video jobs render for minutes; their caller interval ceiling is longer (pollBounds.ts).
const VIDEO_INTERVAL_CEILING = 120_000;
const intervalCeilingFor = (name: string) =>
/video|runway|dashscope|novita|minimax/i.test(name) ? VIDEO_INTERVAL_CEILING : INTERVAL_CEILING;
const TIMEOUT_CEILING = 600_000;
const originalFetch = globalThis.fetch;
const originalSetTimeout = globalThis.setTimeout;
const originalDateNow = Date.now;
type SleepTrace = { sleeps: number[]; elapsedMs: () => number };
/** Files whose `setTimeout` is the polling sleep of a handler under test. */
const SLEEP_FRAMES = ["utils/sleep.ts", "videoGeneration/minimaxHandler.ts"];
/** Intercepts timers created by the polling sleeps 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 (!SLEEP_FRAMES.some((frame) => stack.includes(frame))) {
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 };
}
/** A virtual clock driven by an injected `sleepImpl` (UC handlers). */
function virtualSleepImpl(): SleepTrace & { sleepImpl: (ms: number) => Promise<void> } {
const start = originalDateNow();
let offset = 0;
const sleeps: number[] = [];
Date.now = () => start + offset;
return {
sleeps,
elapsedMs: () => offset,
sleepImpl: async (ms: number) => {
sleeps.push(ms);
offset += ms;
},
};
}
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" },
});
}
/** Kie: every create endpoint returns a task id, every record-info poll says "pending". */
const kieFetch = (async (input: string | URL) => {
const url = String(input);
if (url.includes("record-info") || url.includes("recordInfo")) {
return json({ code: 200, data: { status: "GENERATING" } });
}
return json({ code: 200, data: { taskId: "kie-task-1" } });
}) as typeof fetch;
/** RenderHour: the job is accepted and stays "running". */
const renderhourFetch = (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;
type Site = {
/** Default poll interval the handler uses when the caller sends none. */
defaultIntervalMs: number;
/** Default polling window; a default above the ceiling stays the effective ceiling. */
defaultTimeoutMs: number;
fetch: typeof fetch;
run: (extraBody: Record<string, unknown>) => Promise<unknown>;
};
const SITES: Record<string, Site> = {
"kie image": {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: kieFetch,
run: (extra) =>
handleImageGeneration({
body: { model: "kie/gpt4o-image", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "kie-key" },
log: null,
}),
},
"kie video": {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: kieFetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "kie/kling-3.0/video", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "kie-key" },
log: null,
}),
},
"kie music": {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: kieFetch,
run: (extra) =>
handleMusicGeneration({
body: { model: "kie/V4", prompt: "a sea shanty", ...extra },
credentials: { apiKey: "kie-key" },
log: null,
}),
},
runway: {
defaultIntervalMs: 5_000,
defaultTimeoutMs: 300_000,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.endsWith("_to_video")) return json({ id: "task-1" });
return json({ id: "task-1", status: "RUNNING" });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "runwayml/gen4.5", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "runway-key" },
log: null,
}),
},
dashscope: {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.endsWith("/video-synthesis")) {
return json({ output: { task_id: "ali-task-1", task_status: "PENDING" } });
}
return json({ output: { task_id: "ali-task-1", task_status: "RUNNING" } });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "alibaba/wan2.7-t2v-2026-06-12", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "alibaba-key", providerSpecificData: { region: "global-sg" } },
log: null,
}),
},
novita: {
defaultIntervalMs: 2_500,
defaultTimeoutMs: 300_000,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.includes("/task-result")) {
return json({ task: { task_id: "n-1", status: "TASK_STATUS_PROCESSING" } });
}
return json({ task_id: "n-1" });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "novita/wan-t2v", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "novita-key" },
log: null,
}),
},
minimax: {
defaultIntervalMs: 5_000,
defaultTimeoutMs: 300_000,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.includes("/query/video_generation")) {
return json({ task_id: "mm-1", status: "Processing", base_resp: { status_code: 0 } });
}
return json({ task_id: "mm-1", base_resp: { status_code: 0, status_msg: "success" } });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "minimax/MiniMax-Hailuo-02", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "minimax-key" },
log: null,
}),
},
"video job preset (agnes)": {
defaultIntervalMs: 2_000,
// No deadline here: the window is the preset's poll count (60) times the interval.
defaultTimeoutMs: 60 * INTERVAL_CEILING,
fetch: (async (input: string | URL) => {
const url = String(input);
if (url.endsWith("/v1/videos")) return json({ video_id: "vid-1" });
return json({ status: "processing" });
}) as typeof fetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "agnes/agnes-video-v2.0", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "agnes-key" },
log: null,
}),
},
"renderhour video": {
defaultIntervalMs: 5_000,
defaultTimeoutMs: 900_000,
fetch: renderhourFetch,
run: (extra) =>
handleVideoGeneration({
body: { model: "renderhour/kling-3.0", prompt: "a lighthouse", ...extra },
credentials: { apiKey: "rh_key" },
log: null,
}),
},
"renderhour speech": {
defaultIntervalMs: 2_000,
defaultTimeoutMs: 180_000,
fetch: renderhourFetch,
run: (extra) =>
handleAudioSpeech({
body: { model: "renderhour/eleven-v4", input: "Hello there", ...extra },
credentials: { apiKey: "rh_key" },
}),
},
};
async function runSite(name: string, extraBody: Record<string, unknown>) {
const site = SITES[name];
globalThis.fetch = site.fetch;
const trace = installVirtualSleep();
const result = await site.run(extraBody);
restore();
return { result, trace };
}
function isFailure(result: unknown): boolean {
if (result instanceof Response) return result.status >= 400;
return (result as { success?: boolean }).success === false;
}
const HUGE_BODY = { poll_interval_ms: HUGE_MS, timeout_ms: HUGE_MS * 10 };
test("video job preset (agnes): a huge caller max_polls cannot stretch the polling window", async () => {
const { result, trace } = await runSite("video job preset (agnes)", {
poll_interval_ms: HUGE_MS,
max_polls: 1e9,
});
assert.equal((result as { success: boolean }).success, false);
assert.ok(
trace.elapsedMs() <= TIMEOUT_CEILING + VIDEO_INTERVAL_CEILING,
`polling ran for ${trace.elapsedMs()}ms of virtual time`
);
});
for (const [name, site] of Object.entries(SITES)) {
test(`${name}: a huge caller poll interval and timeout are clamped to the ceilings`, async () => {
const { result, trace } = await runSite(name, HUGE_BODY);
assert.ok(isFailure(result), "a job that never finishes must fail");
assert.ok(trace.sleeps.length > 0, "the handler polled at least once");
const longest = Math.max(...trace.sleeps);
assert.ok(
longest <= intervalCeilingFor(name),
`longest single sleep ${longest}ms > ${intervalCeilingFor(name)}`
);
const window = Math.max(TIMEOUT_CEILING, site.defaultTimeoutMs);
assert.ok(
trace.elapsedMs() <= window + intervalCeilingFor(name),
`polling ran for ${trace.elapsedMs()}ms of virtual time, above the ${window}ms window`
);
});
test(`${name}: a small caller poll interval is used as given`, async () => {
const { trace } = await runSite(name, { poll_interval_ms: 1_000, timeout_ms: 5_000 });
assert.ok(trace.sleeps.length > 0);
assert.ok(
trace.sleeps.every((ms) => ms === 1_000),
`sleeps: ${trace.sleeps.join(",")}`
);
});
test(`${name}: the default poll interval is unchanged when the caller sends none`, async () => {
const { trace } = await runSite(name, {});
assert.equal(trace.sleeps[0], site.defaultIntervalMs);
});
}
test("renderhour video: an operator default above the ceiling stays reachable", async () => {
// 900 s is the built-in RenderHour video window; a caller may ask for it but not for more.
// A huge interval too, so the unclamped code ends after one sleep instead of polling
// ~33 million times (which is the defect itself).
const { result, trace } = await runSite("renderhour video", {
poll_interval_ms: HUGE_MS,
timeout_ms: HUGE_MS,
});
assert.match(String((result as { error?: unknown }).error), /within 900 s/);
assert.ok(trace.elapsedMs() > TIMEOUT_CEILING, `elapsed ${trace.elapsedMs()}ms`);
assert.ok(
trace.elapsedMs() <= 900_000 + VIDEO_INTERVAL_CEILING,
`elapsed ${trace.elapsedMs()}ms`
);
});
// --- UC (injectable sleep) ---------------------------------------------------------------------
const UC_PERSONA_CRED = {
providerSpecificData: {
ucClientCookie: "clientcookie-abc",
ucSid: "sess_123",
ucUid: "b03dd963-d0c1-4193-99c9-f5a9d0c66b7f",
ucCookies: { __client: "clientcookie-abc", __cf_bm: "cf" },
},
};
const UC_DIRECT_CRED = { apiKey: "uai_sk_live_deadbeef" };
function fakeJwt(): string {
const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");
const exp = Math.floor(originalDateNow() / 1000) + 3600 * 24 * 365 * 100;
return `${b64({ alg: "RS256" })}.${b64({ uid: "uid", exp, sub: "user_1", sid: "sess_123" })}.sig`;
}
function ucResponse(ok: boolean, status: number, body: unknown = {}): Response {
return {
ok,
status,
headers: { get: () => "" },
async json() {
return body;
},
async text() {
return typeof body === "string" ? body : JSON.stringify(body);
},
} as unknown as Response;
}
/** UC persona: mint, accept the job, keep the result URL pending forever. */
function ucPersonaFetch(submitUrl: string, resultUrl: string): typeof fetch {
const jwt = fakeJwt();
return (async (url: string) => {
if (isUcClerkMintUrl(url)) return ucResponse(true, 200, { object: "token", jwt });
if (url === submitUrl) return ucResponse(true, 200, { status: "pending", url: resultUrl });
if (url === resultUrl) return ucResponse(false, 403, "");
throw new Error(`unexpected fetch to ${url}`);
}) as unknown as typeof fetch;
}
const UC_SITES: Record<
string,
{
defaultIntervalMs: number;
run: (
extra: Record<string, unknown>,
sleepImpl: (ms: number) => Promise<void>
) => Promise<unknown>;
}
> = {
"uc image (persona)": {
defaultIntervalMs: 2_000,
run: (extra, sleepImpl) =>
handleUcImageGeneration({
model: "uc/seedream-v5",
provider: "uc",
body: { prompt: "x", ...extra },
credentials: UC_PERSONA_CRED,
fetchImpl: ucPersonaFetch(UC_PERSONA_IMAGE_URL, "https://gen.moveinwater.com/never.png"),
sleepImpl,
}),
},
"uc video (persona)": {
defaultIntervalMs: 3_000,
run: (extra, sleepImpl) =>
handleUcVideoGeneration({
model: "uc/wan-2.2-spicy",
provider: "uc",
body: { prompt: "x", ...extra },
credentials: UC_PERSONA_CRED,
fetchImpl: ucPersonaFetch(
UC_PERSONA_TEXT_TO_VIDEO_URL,
"https://videogen.moveinwater.com/never"
),
sleepImpl,
}),
},
"uc video (direct)": {
defaultIntervalMs: 3_000,
run: (extra, sleepImpl) =>
handleUcVideoGeneration({
model: "uc-direct/t2v-standard",
provider: "uc",
body: { prompt: "x", ...extra },
credentials: UC_DIRECT_CRED,
fetchImpl: (async (url: string) => {
const statusUrl = "https://api.uncensored.com/api/v1/videos/status/1";
if (url === UC_DIRECT_VIDEO_URL) {
return ucResponse(true, 200, { status: "pending", status_url: statusUrl, id: "job_1" });
}
if (url === statusUrl) return ucResponse(true, 200, { status: "processing" });
throw new Error(`unexpected fetch to ${url}`);
}) as unknown as typeof fetch,
sleepImpl,
}),
},
};
for (const [name, site] of Object.entries(UC_SITES)) {
test(`${name}: a huge caller poll interval and timeout are clamped to the ceilings`, async () => {
const clock = virtualSleepImpl();
const result = (await site.run(HUGE_BODY, clock.sleepImpl)) as { success: boolean };
restore();
assert.equal(result.success, false, "a job that never finishes must fail");
assert.ok(clock.sleeps.length > 0, "the handler polled at least once");
const longest = Math.max(...clock.sleeps);
assert.ok(
longest <= intervalCeilingFor(name),
`longest single sleep ${longest}ms > ${intervalCeilingFor(name)}`
);
assert.ok(
clock.elapsedMs() <= TIMEOUT_CEILING + intervalCeilingFor(name),
`polling ran for ${clock.elapsedMs()}ms of virtual time`
);
});
test(`${name}: the default poll interval is unchanged when the caller sends none`, async () => {
const clock = virtualSleepImpl();
await site.run({ timeout_ms: 20_000 }, clock.sleepImpl);
restore();
assert.equal(clock.sleeps[0], site.defaultIntervalMs);
});
}

View File

@@ -1,212 +0,0 @@
// 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

@@ -49,22 +49,14 @@ function makeRequest(url: string, options?: RequestInit): NextRequest {
return Object.assign(new Request(url, options), { ip: "127.0.0.1" }) as unknown as NextRequest;
}
/**
* POST carrying an operator credential (dashboard session). Choosing the vault is an
* operator-only action on this ALWAYS_PROTECTED route (CodeQL #1372/#1373): the handler no
* longer treats an anonymous open-mode caller as the operator — the authz pipeline already
* refused that caller over HTTP — so the tests below that enable WebDAV sign in first.
*/
async function makeOperatorPost(body: Record<string, unknown>): Promise<NextRequest> {
const req = await makeManagementSessionRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
body,
});
return Object.assign(req, { ip: "127.0.0.1" }) as unknown as NextRequest;
}
async function postVault(vaultPath: string): Promise<Response> {
return route.POST(await makeOperatorPost({ vaultPath }));
function postVault(vaultPath: string): Promise<Response> {
return route.POST(
makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath }),
})
);
}
async function errorMessageOf(res: Response): Promise<string | undefined> {
@@ -121,7 +113,11 @@ test("GET with no config → webdavEnabled:false, all creds null", async () => {
test("POST with a valid temp dir → returns { username, password }, GET shows enabled", async () => {
const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault-"));
try {
const req = await makeOperatorPost({ vaultPath: vaultDir });
const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
});
const res = await route.POST(req);
assert.equal(res.status, 200);
@@ -158,7 +154,13 @@ test("GET masks the WebDAV password for anonymous callers but reveals it to a ma
const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault-62vw-"));
try {
// Enable WebDAV so there is a stored password to leak.
const enableRes = await route.POST(await makeOperatorPost({ vaultPath: vaultDir }));
const enableRes = await route.POST(
makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
})
);
assert.equal(enableRes.status, 200);
// Anonymous (open-mode) caller: password masked, flag still set.
@@ -190,7 +192,11 @@ test("GET masks the WebDAV password for anonymous callers but reveals it to a ma
test("POST with a non-existent path → 400, body does NOT contain a stack trace", async () => {
const nonExistentPath = path.join(os.tmpdir(), "omni-nonexistent-vault-" + Date.now());
const req = await makeOperatorPost({ vaultPath: nonExistentPath });
const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: nonExistentPath }),
});
const res = await route.POST(req);
assert.equal(res.status, 400);
@@ -270,7 +276,11 @@ test("POST with a directory unrelated to the data directory still succeeds (sibl
});
test("POST with invalid body (missing vaultPath) → 400", async () => {
const req = await makeOperatorPost({});
const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({}),
});
const res = await route.POST(req);
assert.equal(res.status, 400);
});
@@ -279,7 +289,11 @@ test("DELETE after enable → webdavEnabled:false, creds cleared in GET", async
const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault2-"));
try {
// Enable first
const enableReq = await makeOperatorPost({ vaultPath: vaultDir });
const enableReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
});
const enableRes = await route.POST(enableReq);
assert.equal(enableRes.status, 200);
@@ -308,7 +322,11 @@ test("GET when disabled does not leak password even if stale data exists", async
const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault3-"));
try {
// Enable, then disable
const enableReq = await makeOperatorPost({ vaultPath: vaultDir });
const enableReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
});
await route.POST(enableReq);
const deleteReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "DELETE",

View File

@@ -1,236 +0,0 @@
// CodeQL js/path-injection #1371 (src/lib/localCorpus/index.ts) and #1372/#1373
// (src/lib/obsidianSync.ts): the caller-chosen directory behind
// - POST /api/settings/local-corpus (`rootPath`, indexed and served by the MCP search tools)
// - POST /api/settings/obsidian/webdav (`vaultPath`, root of a read/write WebDAV service)
// is a host-filesystem root. Choosing it is an operator action:
// - a machine credential (a manage-scoped API key) gets 403, on both routes;
// - an operator (dashboard session) still sets an ordinary folder such as ~/Documents/vault;
// - the filesystem root, the home directory itself and system directories (/etc, ...) are
// refused with a fixed 400 message that never echoes the requested path.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-path-roots-data-"));
const FAKE_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-path-roots-home-"));
const ORIGINAL_ENV = {
DATA_DIR: process.env.DATA_DIR,
HOME: process.env.HOME,
API_KEY_SECRET: process.env.API_KEY_SECRET,
JWT_SECRET: process.env.JWT_SECRET,
INITIAL_PASSWORD: process.env.INITIAL_PASSWORD,
OMNIROUTE_DISABLE_REDIS_AUTH_CACHE: process.env.OMNIROUTE_DISABLE_REDIS_AUTH_CACHE,
};
process.env.DATA_DIR = TEST_DATA_DIR;
// os.homedir() follows $HOME on POSIX: the "home directory itself" case and the ordinary
// ~/Documents/vault folder both live in a throwaway directory, never in the real home.
process.env.HOME = FAKE_HOME;
process.env.API_KEY_SECRET = "path-roots-api-key-secret";
process.env.JWT_SECRET = "path-roots-jwt-secret";
process.env.OMNIROUTE_DISABLE_REDIS_AUTH_CACHE = "1";
delete process.env.INITIAL_PASSWORD;
const core = await import("../../src/lib/db/core.ts");
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const settingsDb = await import("../../src/lib/db/settings.ts");
const localCorpusDb = await import("../../src/lib/db/localCorpus.ts");
const obsidianDb = await import("../../src/lib/db/obsidian.ts");
const managementPassword = await import("../../src/lib/auth/managementPassword.ts");
const localCorpusRoute = await import("../../src/app/api/settings/local-corpus/route.ts");
const webdavRoute = await import("../../src/app/api/settings/obsidian/webdav/route.ts");
const LOCAL_CORPUS_URL = "http://localhost:20128/api/settings/local-corpus";
const WEBDAV_URL = "http://localhost:20128/api/settings/obsidian/webdav";
const DENIED_ROOT_MESSAGE =
"This directory cannot be used as a root: choose a dedicated folder, not the filesystem root, the home directory itself or a system directory";
const ORDINARY_VAULT = path.join(FAKE_HOME, "Documents", "vault");
fs.mkdirSync(ORDINARY_VAULT, { recursive: true });
await settingsDb.updateSettings({
requireLogin: true,
setupComplete: true,
password: await managementPassword.hashManagementPassword("path-roots-operator-secret"),
});
const manageKey = await apiKeysDb.createApiKey("manage-automation", "machine-paths", ["manage"]);
test.after(() => {
apiKeysDb.resetApiKeyState();
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.rmSync(FAKE_HOME, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
test.beforeEach(() => {
localCorpusDb.clearLocalCorpusRoot();
obsidianDb.clearObsidianVaultPath();
obsidianDb.clearWebdavEnabled();
});
function keyRequest(url: string, body: Record<string, unknown>): Request {
return new Request(url, {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${manageKey.key}` },
body: JSON.stringify(body),
});
}
async function sessionRequest(url: string, body: Record<string, unknown>): Promise<Request> {
return makeManagementSessionRequest(url, { method: "POST", body });
}
type RouteHandler = (request: never) => Promise<Response>;
function post(handler: RouteHandler, request: Request): Promise<Response> {
return (handler as (request: Request) => Promise<Response>)(request);
}
/**
* Error text of either body shape: `{ error: "..." }` (local corpus, which renders the thrown
* Error as "Error: <message>") or `{ error: { message } }` (WebDAV, buildErrorBody).
*/
async function errorText(response: Response): Promise<string> {
const body = (await response.json()) as { error?: unknown };
if (typeof body.error === "string") return body.error.replace(/^Error: /, "");
const nested = body.error as { message?: unknown } | undefined;
return typeof nested?.message === "string" ? nested.message : JSON.stringify(body);
}
// ─── (a) a manage-scoped API key cannot choose the root ────────────────────────────────
test("a manage-scoped API key cannot set the local corpus root (403)", async () => {
const response = await post(
localCorpusRoute.POST,
keyRequest(LOCAL_CORPUS_URL, { rootPath: ORDINARY_VAULT })
);
assert.equal(response.status, 403, await response.clone().text());
assert.equal(localCorpusDb.getLocalCorpusRoot(), null, "root must not be stored");
});
test("a manage-scoped API key cannot set the WebDAV vault path (403)", async () => {
const response = await post(
webdavRoute.POST,
keyRequest(WEBDAV_URL, { vaultPath: ORDINARY_VAULT })
);
assert.equal(response.status, 403, await response.clone().text());
assert.equal(obsidianDb.getWebdavEnabled(), false, "WebDAV must stay disabled");
assert.equal(obsidianDb.getObsidianVaultPath(), null, "vault path must not be stored");
});
test("with login disabled, a manage-scoped API key still cannot set the WebDAV vault path (403)", async () => {
// /api/settings/obsidian is ALWAYS_PROTECTED: an open instance does not turn a machine
// credential into the operator for this credential-issuing surface.
await settingsDb.updateSettings({ requireLogin: false });
try {
const response = await post(
webdavRoute.POST,
keyRequest(WEBDAV_URL, { vaultPath: ORDINARY_VAULT })
);
assert.equal(response.status, 403, await response.clone().text());
assert.equal(obsidianDb.getWebdavEnabled(), false);
} finally {
await settingsDb.updateSettings({ requireLogin: true });
}
});
// ─── (b) the dashboard session keeps working with an ordinary folder ───────────────────
test("a dashboard session sets an ordinary folder (~/Documents/vault) as the local corpus root", async () => {
const response = await post(
localCorpusRoute.POST,
await sessionRequest(LOCAL_CORPUS_URL, { rootPath: ORDINARY_VAULT })
);
assert.equal(response.status, 200, await response.clone().text());
const body = (await response.json()) as { rootPath?: string };
assert.equal(body.rootPath, fs.realpathSync(ORDINARY_VAULT));
assert.equal(localCorpusDb.getLocalCorpusRoot(), fs.realpathSync(ORDINARY_VAULT));
});
test("a dashboard session sets an ordinary folder (~/Documents/vault) as the WebDAV vault", async () => {
const response = await post(
webdavRoute.POST,
await sessionRequest(WEBDAV_URL, { vaultPath: ORDINARY_VAULT })
);
assert.equal(response.status, 200, await response.clone().text());
const body = (await response.json()) as Record<string, unknown>;
assert.equal(body.vaultPath, path.resolve(ORDINARY_VAULT));
assert.ok(typeof body.password === "string" && body.password.length > 0);
assert.equal(obsidianDb.getWebdavEnabled(), true);
});
// ─── (c) dangerous roots are refused with a fixed message ──────────────────────────────
const DENIED_ROOTS: Array<{ label: string; value: () => string }> = [
{ label: "the filesystem root", value: () => path.parse(process.cwd()).root },
{ label: "the home directory itself", value: () => FAKE_HOME },
{ label: "/etc", value: () => "/etc" },
];
for (const denied of DENIED_ROOTS) {
test(`local corpus refuses ${denied.label} with a fixed 400`, async () => {
const response = await post(
localCorpusRoute.POST,
await sessionRequest(LOCAL_CORPUS_URL, { rootPath: denied.value() })
);
assert.equal(response.status, 400);
assert.equal(await errorText(response), DENIED_ROOT_MESSAGE);
assert.equal(localCorpusDb.getLocalCorpusRoot(), null, "root must not be stored");
});
test(`WebDAV vault refuses ${denied.label} with a fixed 400`, async () => {
const response = await post(
webdavRoute.POST,
await sessionRequest(WEBDAV_URL, { vaultPath: denied.value() })
);
assert.equal(response.status, 400);
assert.equal(await errorText(response), DENIED_ROOT_MESSAGE);
assert.equal(obsidianDb.getWebdavEnabled(), false, "WebDAV must stay disabled");
assert.equal(obsidianDb.getObsidianVaultPath(), null, "vault path must not be stored");
});
}
test("a symlink inside the home directory that resolves to /etc is refused on both routes", async () => {
const link = path.join(FAKE_HOME, "etc-link");
try {
fs.symlinkSync("/etc", link, "dir");
} catch {
return; // platform without symlink permission — nothing to assert
}
try {
const corpus = await post(
localCorpusRoute.POST,
await sessionRequest(LOCAL_CORPUS_URL, { rootPath: link })
);
assert.equal(corpus.status, 400);
assert.equal(await errorText(corpus), DENIED_ROOT_MESSAGE);
const vault = await post(
webdavRoute.POST,
await sessionRequest(WEBDAV_URL, { vaultPath: link })
);
assert.equal(vault.status, 400);
assert.equal(await errorText(vault), DENIED_ROOT_MESSAGE);
} finally {
fs.rmSync(link, { force: true });
}
});
// ─── helper: which directories are denied ──────────────────────────────────────────────
test("isDeniedRootDirectory: system directories and their children, root and home itself", async () => {
const { isDeniedRootDirectory } = await import("../../src/lib/deniedRootDirectories.ts");
for (const denied of ["/", FAKE_HOME, `${FAKE_HOME}/`, "/etc", "/etc/ssh", "/usr/local/bin"]) {
assert.equal(isDeniedRootDirectory(denied), true, denied);
}
for (const allowed of [ORDINARY_VAULT, path.join(FAKE_HOME, "Documents"), TEST_DATA_DIR]) {
assert.equal(isDeniedRootDirectory(allowed), false, allowed);
}
});

View File

@@ -1,212 +0,0 @@
// Same status contract as tests/unit/credits-signal-400-status-gate.test.ts, applied to
// the subscription/plan quota text signals ("usage limit reached", "plan limit",
// "weekly usage limit", ...). A 400 is how upstreams reject the caller's own input, and
// many of them quote that input back in error.message, so on 400 such a phrase counts
// only when the structured error code is a credit/quota code, or the provider is one
// whose documented 400 form is message-only (command-code, bai, openai-compatible-*).
// 429, 403 and every other status keep the plain text match.
import assert from "node:assert/strict";
import test from "node:test";
import { createChatPipelineHarness } from "../integration/_chatPipelineHarness.ts";
const h = await createChatPipelineHarness("subscription-quota-400-status-gate");
const providersDb = await import("../../src/lib/db/providers.ts");
const { checkFallbackError } = await import("../../open-sse/services/accountFallback.ts");
const { classifyProviderError, PROVIDER_ERROR_TYPES } =
await import("../../open-sse/services/errorClassifier.ts");
const { RateLimitReason } = await import("../../open-sse/config/constants.ts");
const { shouldCoolDownSearchConnection } =
await import("../../open-sse/handlers/search/searchProxy.ts");
const originalFetch = globalThis.fetch;
const ECHO_MARKER = "ECHO-MARKER-REQUEST";
// Typed invalid_request_error repeating a caller-chosen subscription-quota phrase.
const TYPED_ECHO_400 = {
error: {
message: "Unknown parameter: 'usage limit reached'.",
type: "invalid_request_error",
},
};
// Untyped 400 outside the param-validation patterns, same phrase family.
const UNTYPED_ECHO_400 = {
error: {
message: "Invalid value 'you have reached your usage limit' for model",
type: "api_error",
},
};
const ECHOED_PHRASES = [
"Unknown parameter: 'usage limit reached'.",
"Invalid value 'plan limit exceeded' for model",
"Unknown parameter: 'this request exceeds your plan'.",
"Unknown parameter: 'you have reached your weekly usage limit'.",
"Unknown parameter: 'session usage limit'.",
"Unknown parameter: 'usage limit reached, try again in 30 minutes'.",
];
test.afterEach(() => {
globalThis.fetch = originalFetch;
});
test.after(() => h.cleanup());
function stubUpstream(echoBody: unknown) {
const calls = { echo: 0, clean: 0 };
globalThis.fetch = (async (_url: unknown, init?: RequestInit) => {
const sent = typeof init?.body === "string" ? init.body : "";
if (sent.includes(ECHO_MARKER)) {
calls.echo++;
return new Response(JSON.stringify(echoBody), {
status: 400,
headers: { "content-type": "application/json" },
});
}
calls.clean++;
return h.buildOpenAIResponse("served");
}) as typeof fetch;
return calls;
}
function chatRequest(content: string) {
return h.buildRequest({
body: {
model: "openai/gpt-4o-mini",
stream: false,
messages: [{ role: "user", content }],
},
});
}
function isOnHold(conn: { rateLimitedUntil?: unknown; testStatus?: unknown } | null): boolean {
const until = conn?.rateLimitedUntil;
const untilMs = typeof until === "string" ? Date.parse(until) : Number(until ?? 0);
return conn?.testStatus === "unavailable" || (Number.isFinite(untilMs) && untilMs > Date.now());
}
for (const [label, echoBody] of [
["typed invalid_request_error", TYPED_ECHO_400],
["untyped 400 outside the param-validation patterns", UNTYPED_ECHO_400],
] as const) {
test(`${label}: a caller-echoed subscription-quota phrase never puts a shared openai connection on hold`, async () => {
await h.resetStorage();
const conns = [];
for (let i = 0; i < 3; i++) {
conns.push(await h.seedConnection("openai", { name: `shared-${i}` }));
}
const calls = stubUpstream(echoBody);
for (let i = 0; i < 3; i++) {
const res = await h.handleChat(chatRequest(`hello ${ECHO_MARKER} ${i}`));
await res.text();
}
assert.ok(calls.echo >= 3, `expected the echo requests to reach upstream, got ${calls.echo}`);
for (const conn of conns) {
const after = await providersDb.getProviderConnectionById(conn.id);
assert.equal(isOnHold(after), false, `connection ${after?.name} put on hold`);
assert.notEqual(after?.lastErrorType, "quota_exhausted", `${after?.name} quota_exhausted`);
}
const clean = await h.handleChat(chatRequest("a clean request"));
const body = await clean.text();
assert.equal(clean.status, 200, `clean request was not served: ${body}`);
assert.ok(calls.clean >= 1);
});
}
test("echoed 400 subscription-quota phrases are not QUOTA_EXHAUSTED for openai", () => {
for (const message of ECHOED_PHRASES) {
const text = JSON.stringify({ error: { message, type: "invalid_request_error" } });
assert.notEqual(
classifyProviderError(400, text, "openai"),
PROVIDER_ERROR_TYPES.QUOTA_EXHAUSTED,
text
);
const result = checkFallbackError(400, text, 0, "gpt-4o-mini", "openai");
assert.notEqual(result.reason, RateLimitReason.QUOTA_EXHAUSTED, text);
}
});
test("search: an echoed 400 subscription-quota phrase does not cool down the connection", () => {
assert.equal(
shouldCoolDownSearchConnection(400, "Invalid query: 'usage limit reached for this plan'"),
false
);
});
test("control: 429 with the same subscription-quota text stays QUOTA_EXHAUSTED", () => {
const text = JSON.stringify({ error: { message: "Usage limit reached for your plan." } });
// OAuth provider and provider-less callers keep the 429 quota semantics.
assert.equal(classifyProviderError(429, text, "claude"), PROVIDER_ERROR_TYPES.QUOTA_EXHAUSTED);
assert.equal(classifyProviderError(429, text), PROVIDER_ERROR_TYPES.QUOTA_EXHAUSTED);
const result = checkFallbackError(429, "Usage Limit Reached", 0, null, "claude");
assert.equal(result.reason, RateLimitReason.QUOTA_EXHAUSTED);
assert.equal(result.cooldownMs, 60 * 60 * 1000);
assert.equal(
checkFallbackError(429, "you have reached your weekly usage limit", 0, null, "ollama-cloud")
.reason,
RateLimitReason.QUOTA_EXHAUSTED
);
assert.equal(shouldCoolDownSearchConnection(429, "usage limit reached"), true);
});
test("control: 403 subscription-quota text stays QUOTA_EXHAUSTED", () => {
const text = JSON.stringify({
error: { message: "You've reached your usage limit for this billing cycle." },
});
assert.equal(
classifyProviderError(403, text, "kimi-coding"),
PROVIDER_ERROR_TYPES.QUOTA_EXHAUSTED
);
});
test("control: a 400 with a structured quota code still counts on openai", () => {
for (const code of ["insufficient_quota", "billing_hard_limit_reached"]) {
const body = JSON.stringify({ error: { message: "Usage limit reached for your plan.", code } });
assert.equal(
classifyProviderError(400, body, "openai"),
PROVIDER_ERROR_TYPES.QUOTA_EXHAUSTED,
code
);
// The structured code held apart from the text (executor-parsed) also counts.
const result = checkFallbackError(
400,
"Usage limit reached for your plan.",
0,
"gpt-4o-mini",
"openai",
null,
null,
{ code }
);
assert.equal(result.shouldFallback, true, code);
assert.equal(result.reason, RateLimitReason.QUOTA_EXHAUSTED, code);
assert.equal(result.cooldownMs, 60 * 60 * 1000, code);
}
assert.equal(
shouldCoolDownSearchConnection(
400,
JSON.stringify({ error: { message: "plan limit exceeded", code: "insufficient_quota" } })
),
true
);
});
test("control: a message-only 400 on an allow-listed provider still counts", () => {
for (const provider of ["command-code", "bai", "openai-compatible-my-gateway"]) {
const text = "Usage limit reached for your plan.";
assert.equal(
classifyProviderError(400, text, provider),
PROVIDER_ERROR_TYPES.QUOTA_EXHAUSTED,
provider
);
const result = checkFallbackError(400, text, 0, "m", provider);
assert.equal(result.reason, RateLimitReason.QUOTA_EXHAUSTED, provider);
}
});
test("the message-only allow-list is the id prefix, not a substring anywhere in the id", () => {
assert.notEqual(
classifyProviderError(400, "Usage limit reached", "my-openai-compatible-x"),
PROVIDER_ERROR_TYPES.QUOTA_EXHAUSTED
);
});

View File

@@ -1,44 +0,0 @@
// 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");
});
});

View File

@@ -52,19 +52,10 @@ test("the OIDC callback validates `state` with the constant-time helper", () =>
);
});
test("the internal admission bypass compares its process token in constant time", () => {
// The bypass is granted only on the per-process token, checked by isOwnListenerSelfHop.
test("the internal admission bypass compares its bearer in constant time", () => {
const source = sourceOf("src/shared/middleware/chatAdmissionIdentity.ts");
assert.match(
source,
/isInternalAdmissionBypass\(request: Request\): boolean \{\s*return isOwnListenerSelfHop\(/,
"isInternalAdmissionBypass gates a bypass on a shared secret — it must go through isOwnListenerSelfHop"
);
const selfHop = sourceOf("open-sse/utils/selfHop.ts");
const check = selfHop.slice(selfHop.indexOf("export function isOwnListenerSelfHop"));
assert.match(
check.slice(0, check.indexOf("\n}\n")),
/timingSafeEqual\(got, expected\)/,
"isOwnListenerSelfHop must compare the token in constant time"
assert.ok(
source.includes("timingSafeCompare"),
"isInternalAdmissionBypass gates a bypass on a shared secret — compare it in constant time"
);
});

View File

@@ -20,8 +20,6 @@ const { checkBodySize, getBodySizeLimit } =
await import("../../src/shared/middleware/bodySizeGuard.ts");
const { admitChatRequest, ChatAdmissionController, resolveSelfLoopBearer } =
await import("../../src/shared/middleware/chatBodyAdmission.ts");
const { SELF_HOP_HEADER, ownListenerSelfHopToken } =
await import("../../open-sse/utils/selfHop.ts");
const paths = [
"/api/v1/chat/completions",
@@ -44,7 +42,6 @@ function request(pathname: string, bytes: number, declared?: number, internal =
if (internal) {
headers.set("x-omniroute-admission-bypass", "internal");
headers.set("authorization", `Bearer ${resolveSelfLoopBearer()}`);
headers.set(SELF_HOP_HEADER, ownListenerSelfHopToken());
}
const body = new ReadableStream<Uint8Array>(
{