mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-22 16:55:29 +00:00
Compare commits
2 Commits
fix/codeql
...
fix/codeql
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4625936608 | ||
|
|
0d56007238 |
@@ -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)
|
||||
1
changelog.d/fixes/20824-media-poll-clamp-syntx-rules.md
Normal file
1
changelog.d/fixes/20824-media-poll-clamp-syntx-rules.md
Normal file
@@ -0,0 +1 @@
|
||||
- **fix(security):** Image generation on NanoBanana, Magnific, Black Forest Labs and RenderHour caps a caller's `poll_interval_ms` at 30 s and `timeout_ms` / `poll_timeout_ms` at 10 minutes (defaults unchanged), and RenderHour stops waiting between polls when the request is aborted; SYNTX provider rules only run for names defined in the rules table, so an `ai_name` such as `constructor` or `__proto__` no longer reaches an inherited `Object.prototype` member (CodeQL #1389, #1392) ([#20824](https://github.com/cheaper-inference/OmniRoute/pull/20824))
|
||||
@@ -24,6 +24,7 @@ import { mapImageSize } from "../translator/image/sizeMapper.ts";
|
||||
import { getCodexClientVersion, getCodexUserAgent } from "../config/codexClient.ts";
|
||||
import { isCodexFreePlan } from "../executors/codex/tools.ts";
|
||||
import { sleep } from "../utils/sleep.ts";
|
||||
import { clampPollIntervalMs, clampPollTimeoutMs } from "../utils/pollBounds.ts";
|
||||
import { codexReferenceImageUrl } from "./imageGeneration/providers/codexReferences.ts";
|
||||
export { shrinkCodexReferenceImage } from "./imageGeneration/providers/codexReferences.ts";
|
||||
import {
|
||||
@@ -2965,11 +2966,11 @@ async function handleNanoBananaImageGeneration({
|
||||
return { success: false, status: 500, error: errorText };
|
||||
}
|
||||
|
||||
const timeoutMs = normalizePositiveNumber(
|
||||
const timeoutMs = clampPollTimeoutMs(
|
||||
body.timeout_ms,
|
||||
normalizePositiveNumber(process.env.NANOBANANA_POLL_TIMEOUT_MS, 120000)
|
||||
);
|
||||
const pollIntervalMs = normalizePositiveNumber(
|
||||
const pollIntervalMs = clampPollIntervalMs(
|
||||
body.poll_interval_ms,
|
||||
normalizePositiveNumber(process.env.NANOBANANA_POLL_INTERVAL_MS, 2500)
|
||||
);
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
|
||||
import { mapImageSize } from "../../../translator/image/sizeMapper.ts";
|
||||
import { sleep } from "../../../utils/sleep.ts";
|
||||
import { clampPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
|
||||
import { sanitizeErrorMessage } from "../../../utils/error.ts";
|
||||
import {
|
||||
extractImageInputs,
|
||||
isHttpUrl,
|
||||
normalizePositiveNumber,
|
||||
normalizeProviderImagePayload,
|
||||
normalizeRequestedImageFormat,
|
||||
parseSizeToDimensions,
|
||||
@@ -180,8 +180,8 @@ export async function handleBlackForestLabsImageGeneration({
|
||||
}
|
||||
|
||||
async function pollBlackForestLabsResult({ pollingUrl, token, body, log }) {
|
||||
const timeoutMs = normalizePositiveNumber(body.timeout_ms, 300000);
|
||||
const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, 1500);
|
||||
const timeoutMs = clampPollTimeoutMs(body.timeout_ms, 300000);
|
||||
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, 1500);
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
import { saveCallLog } from "../../imageResult.ts";
|
||||
import { sleep } from "../../../utils/sleep.ts";
|
||||
import { clampPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
|
||||
import { sanitizeErrorMessage } from "../../../utils/error.ts";
|
||||
import {
|
||||
UPSTREAM_MEDIA_LIMITS,
|
||||
@@ -19,12 +20,6 @@ import {
|
||||
const DEFAULT_POLL_INTERVAL_MS = 4000;
|
||||
const DEFAULT_POLL_TIMEOUT_MS = 180000;
|
||||
|
||||
function normalizePositiveNumber(value: unknown, fallback: number): number {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n) || n <= 0) return fallback;
|
||||
return Math.floor(n);
|
||||
}
|
||||
|
||||
interface MagnificProviderConfig {
|
||||
baseUrl: string;
|
||||
statusUrl?: string;
|
||||
@@ -267,8 +262,8 @@ export async function handleMagnificImageGeneration({
|
||||
const startTime = Date.now();
|
||||
const token = credentials?.apiKey || "";
|
||||
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
|
||||
const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
|
||||
const pollTimeoutMs = normalizePositiveNumber(body.poll_timeout_ms, DEFAULT_POLL_TIMEOUT_MS);
|
||||
const pollIntervalMs = clampPollIntervalMs(body.poll_interval_ms, DEFAULT_POLL_INTERVAL_MS);
|
||||
const pollTimeoutMs = clampPollTimeoutMs(body.poll_timeout_ms, DEFAULT_POLL_TIMEOUT_MS);
|
||||
if (log) {
|
||||
log.info(
|
||||
"IMAGE",
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
renderhourBaseUrl,
|
||||
renderhourConfig,
|
||||
renderhourFailure,
|
||||
renderhourNumber,
|
||||
renderhourToken,
|
||||
runRenderhourJob,
|
||||
uploadRenderhourInputs,
|
||||
@@ -22,6 +21,7 @@ import {
|
||||
saveImageErrorResult,
|
||||
saveImageSuccessResult,
|
||||
} from "../../imageGeneration.ts";
|
||||
import { clampPollIntervalMs, clampPollTimeoutMs } from "../../../utils/pollBounds.ts";
|
||||
|
||||
const MAX_IMAGES_PER_JOB = 4;
|
||||
|
||||
@@ -72,8 +72,8 @@ export async function handleRenderhourImageGeneration({
|
||||
baseUrl,
|
||||
token,
|
||||
request,
|
||||
timeoutMs: renderhourNumber(body.timeout_ms, 300_000),
|
||||
pollIntervalMs: renderhourNumber(body.poll_interval_ms, 2000),
|
||||
timeoutMs: clampPollTimeoutMs(body.timeout_ms, 300_000),
|
||||
pollIntervalMs: clampPollIntervalMs(body.poll_interval_ms, 2000),
|
||||
log,
|
||||
signal,
|
||||
});
|
||||
|
||||
@@ -302,7 +302,7 @@ async function pollRenderhourJob({
|
||||
error: `RenderHour job ${job.id} did not finish within ${Math.round(timeoutMs / 1000)} s`,
|
||||
};
|
||||
}
|
||||
await sleep(delay);
|
||||
await sleep(delay, signal);
|
||||
delay = pollIntervalMs;
|
||||
// Asking about a job also moves it forward on RenderHour's side.
|
||||
const response = await fetch(`${baseUrl}/v1/generations/${encodeURIComponent(job.id)}`, {
|
||||
|
||||
@@ -172,8 +172,10 @@ export function applySyntxProviderRules(
|
||||
settings: JsonRecord,
|
||||
ctx: { modelType: string; fileCount?: number }
|
||||
): void {
|
||||
// aiName comes from the caller's model id: only the table's own entries may run, never a
|
||||
// member inherited from Object.prototype ("constructor", "__proto__", ...). CodeQL #1392.
|
||||
if (!Object.hasOwn(PROVIDER_RULES, aiName)) return;
|
||||
const handler = PROVIDER_RULES[aiName];
|
||||
if (!handler) return;
|
||||
handler(ctx.modelType || "", ctx.fileCount ?? 0, settings);
|
||||
}
|
||||
|
||||
|
||||
42
open-sse/utils/pollBounds.ts
Normal file
42
open-sse/utils/pollBounds.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Upper bounds for the polling knobs a caller may send to async media jobs
|
||||
* (`poll_interval_ms`, `timeout_ms`, `poll_timeout_ms`).
|
||||
*
|
||||
* Those values feed `sleep()` and the polling deadline. Without a ceiling one request could hold
|
||||
* a handler for days while the server kept polling the upstream with the operator's credential
|
||||
* (CodeQL #1389, js/resource-exhaustion). Same pattern as `resolveCursorImageTimeoutMs` in
|
||||
* handlers/imageGeneration/providers/cursorAgentImage.ts: only the untrusted request value is
|
||||
* clamped; the fallback (a built-in or operator-configured default) is trusted and kept as is.
|
||||
*/
|
||||
|
||||
/** Longest single wait between two polls; matches MAX_POLL_RETRY_DELAY_MS in pollRetry.ts. */
|
||||
export const MAX_CALLER_POLL_INTERVAL_MS = 30_000;
|
||||
|
||||
/** Longest total polling window a caller may ask for (10 minutes). */
|
||||
export const MAX_CALLER_POLL_TIMEOUT_MS = 600_000;
|
||||
|
||||
/** A whole number of milliseconds ≥ 1 from the request, or null when absent or unusable. */
|
||||
function positiveWholeMs(value: unknown): number | null {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return null;
|
||||
const ms = Math.floor(n);
|
||||
return ms >= 1 ? ms : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The caller's value clamped to `ceiling`, or `fallback` when the caller sent none. A fallback
|
||||
* above the ceiling stays reachable, so a ceiling never shortens a default.
|
||||
*/
|
||||
export function clampCallerMs(value: unknown, fallback: number, ceiling: number): number {
|
||||
const requested = positiveWholeMs(value);
|
||||
if (requested === null) return fallback;
|
||||
return Math.min(requested, Math.max(ceiling, fallback));
|
||||
}
|
||||
|
||||
export function clampPollIntervalMs(value: unknown, fallback: number): number {
|
||||
return clampCallerMs(value, fallback, MAX_CALLER_POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
export function clampPollTimeoutMs(value: unknown, fallback: number): number {
|
||||
return clampCallerMs(value, fallback, MAX_CALLER_POLL_TIMEOUT_MS);
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)));
|
||||
});
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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}` };
|
||||
}
|
||||
|
||||
212
tests/unit/media-poll-clamp.test.ts
Normal file
212
tests/unit/media-poll-clamp.test.ts
Normal file
@@ -0,0 +1,212 @@
|
||||
// CodeQL #1389 (js/resource-exhaustion): `poll_interval_ms`, `timeout_ms` and
|
||||
// `poll_timeout_ms` from the request body reached `sleep()` (open-sse/utils/sleep.ts) and the
|
||||
// polling deadline with no upper bound, so one request could hold a handler for days while the
|
||||
// server kept polling the upstream with the operator's credential.
|
||||
//
|
||||
// The handlers are driven against a fake upstream that never finishes. Timers created by
|
||||
// `sleep()` are intercepted (identified by the call stack), recorded, and fired at once while a
|
||||
// virtual clock advances by the requested delay, so a multi-day wait runs in milliseconds.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { handleImageGeneration } from "../../open-sse/handlers/imageGeneration.ts";
|
||||
import {
|
||||
MAX_CALLER_POLL_INTERVAL_MS,
|
||||
MAX_CALLER_POLL_TIMEOUT_MS,
|
||||
clampCallerMs,
|
||||
clampPollIntervalMs,
|
||||
clampPollTimeoutMs,
|
||||
} from "../../open-sse/utils/pollBounds.ts";
|
||||
|
||||
const HUGE_MS = 1e12; // ~31 years
|
||||
const INTERVAL_CEILING = 30_000;
|
||||
const TIMEOUT_CEILING = 600_000;
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
const originalSetTimeout = globalThis.setTimeout;
|
||||
const originalDateNow = Date.now;
|
||||
|
||||
type SleepTrace = { sleeps: number[]; elapsedMs: () => number };
|
||||
|
||||
/** Intercepts timers created by utils/sleep.ts and drives a virtual clock with them. */
|
||||
function installVirtualSleep(): SleepTrace {
|
||||
const start = originalDateNow();
|
||||
let offset = 0;
|
||||
const sleeps: number[] = [];
|
||||
Date.now = () => start + offset;
|
||||
globalThis.setTimeout = ((fn: (...args: unknown[]) => void, ms?: number, ...args: unknown[]) => {
|
||||
const stack = new Error().stack ?? "";
|
||||
if (!stack.includes("utils/sleep.ts")) return originalSetTimeout(fn, ms, ...args);
|
||||
const delay = Number(ms) || 0;
|
||||
sleeps.push(delay);
|
||||
offset += delay;
|
||||
return originalSetTimeout(fn, 0, ...args);
|
||||
}) as typeof setTimeout;
|
||||
return { sleeps, elapsedMs: () => offset };
|
||||
}
|
||||
|
||||
function restore() {
|
||||
globalThis.fetch = originalFetch;
|
||||
globalThis.setTimeout = originalSetTimeout;
|
||||
Date.now = originalDateNow;
|
||||
}
|
||||
|
||||
test.afterEach(restore);
|
||||
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
/** Upstream fakes that accept the job and report it as still running on every poll. */
|
||||
const NEVER_FINISHING_UPSTREAMS: Record<string, { model: string; fetch: typeof fetch }> = {
|
||||
nanobanana: {
|
||||
model: "nanobanana/nanobanana-flash",
|
||||
fetch: (async (input: string | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/record-info")) return json({ data: { successFlag: 0 } });
|
||||
return json({ data: { taskId: "task-1" } });
|
||||
}) as typeof fetch,
|
||||
},
|
||||
magnific: {
|
||||
model: "magnific/realism",
|
||||
fetch: (async (input: string | URL) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/task-1"))
|
||||
return json({ data: { task_id: "task-1", status: "IN_PROGRESS" } });
|
||||
return json({ data: { task_id: "task-1", status: "CREATED" } });
|
||||
}) as typeof fetch,
|
||||
},
|
||||
"black-forest-labs": {
|
||||
model: "black-forest-labs/flux-2-pro",
|
||||
fetch: (async (input: string | URL) => {
|
||||
const url = String(input);
|
||||
if (url === "https://api.bfl.ai/result/1") return json({ status: "Pending" });
|
||||
return json({ id: "1", polling_url: "https://api.bfl.ai/result/1" });
|
||||
}) as typeof fetch,
|
||||
},
|
||||
renderhour: {
|
||||
model: "renderhour/z-image",
|
||||
fetch: (async (input: string | URL) => {
|
||||
const url = String(input);
|
||||
if (url.endsWith("/v1/generations")) return json({ id: "job-1", status: "queued" }, 201);
|
||||
return json({ id: "job-1", status: "running" });
|
||||
}) as typeof fetch,
|
||||
},
|
||||
};
|
||||
|
||||
async function runNeverFinishing(provider: string, extraBody: Record<string, unknown>) {
|
||||
const upstream = NEVER_FINISHING_UPSTREAMS[provider];
|
||||
globalThis.fetch = upstream.fetch;
|
||||
const trace = installVirtualSleep();
|
||||
const result = await handleImageGeneration({
|
||||
body: { model: upstream.model, prompt: "a lighthouse", ...extraBody },
|
||||
credentials: { apiKey: "test-key" },
|
||||
log: null,
|
||||
});
|
||||
restore();
|
||||
return { result, trace };
|
||||
}
|
||||
|
||||
for (const provider of Object.keys(NEVER_FINISHING_UPSTREAMS)) {
|
||||
test(`${provider}: a huge caller poll interval and timeout are clamped to the ceilings`, async () => {
|
||||
const { result, trace } = await runNeverFinishing(provider, {
|
||||
poll_interval_ms: HUGE_MS,
|
||||
timeout_ms: HUGE_MS,
|
||||
poll_timeout_ms: HUGE_MS,
|
||||
});
|
||||
|
||||
assert.equal(result.success, false, "a job that never finishes must fail");
|
||||
assert.ok(trace.sleeps.length > 0, "the handler polled at least once");
|
||||
assert.ok(
|
||||
Math.max(...trace.sleeps) <= INTERVAL_CEILING,
|
||||
`longest single sleep ${Math.max(...trace.sleeps)}ms exceeds ${INTERVAL_CEILING}ms`
|
||||
);
|
||||
assert.ok(
|
||||
trace.elapsedMs() <= TIMEOUT_CEILING + INTERVAL_CEILING,
|
||||
`polling ran for ${trace.elapsedMs()}ms of virtual time, above the ${TIMEOUT_CEILING}ms ceiling`
|
||||
);
|
||||
});
|
||||
|
||||
test(`${provider}: a small caller poll interval is used as given`, async () => {
|
||||
const { trace } = await runNeverFinishing(provider, {
|
||||
poll_interval_ms: 1_000,
|
||||
timeout_ms: 5_000,
|
||||
poll_timeout_ms: 5_000,
|
||||
});
|
||||
assert.ok(trace.sleeps.length > 0);
|
||||
assert.ok(
|
||||
trace.sleeps.every((ms) => ms === 1_000),
|
||||
`sleeps: ${trace.sleeps.join(",")}`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test("default poll intervals are unchanged when the caller sends none", async () => {
|
||||
const expected: Record<string, number> = {
|
||||
nanobanana: 2_500,
|
||||
magnific: 4_000,
|
||||
"black-forest-labs": 1_500,
|
||||
renderhour: 2_000,
|
||||
};
|
||||
for (const [provider, interval] of Object.entries(expected)) {
|
||||
const { trace } = await runNeverFinishing(provider, {});
|
||||
assert.equal(trace.sleeps[0], interval, `${provider} default poll interval`);
|
||||
}
|
||||
});
|
||||
|
||||
test("timeout error messages report the clamped value", async () => {
|
||||
// A huge interval too, so the unclamped code ends after one sleep instead of polling
|
||||
// ~400 million times (which is the defect itself).
|
||||
const huge = { timeout_ms: HUGE_MS, poll_interval_ms: HUGE_MS };
|
||||
const nano = await runNeverFinishing("nanobanana", huge);
|
||||
assert.match(String(nano.result.error), /timeout after 600000ms/);
|
||||
const bfl = await runNeverFinishing("black-forest-labs", huge);
|
||||
assert.match(String(bfl.result.error), /timed out after 600000ms/);
|
||||
const rh = await runNeverFinishing("renderhour", huge);
|
||||
assert.match(String(rh.result.error), /within 600 s/);
|
||||
});
|
||||
|
||||
test("renderhour: aborting the request ends the wait between polls", async () => {
|
||||
globalThis.fetch = (async (input: string | URL, init: RequestInit = {}) => {
|
||||
init.signal?.throwIfAborted();
|
||||
const url = String(input);
|
||||
if (url.endsWith("/v1/generations")) return json({ id: "job-1", status: "queued" }, 201);
|
||||
return json({ id: "job-1", status: "running" });
|
||||
}) as typeof fetch;
|
||||
const controller = new AbortController();
|
||||
const timer = originalSetTimeout(() => controller.abort(), 50);
|
||||
const startedAt = originalDateNow();
|
||||
const result = await handleImageGeneration({
|
||||
body: { model: "renderhour/z-image", prompt: "a lighthouse", poll_interval_ms: 30_000 },
|
||||
credentials: { apiKey: "test-key" },
|
||||
log: null,
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timer);
|
||||
assert.equal(result.success, false);
|
||||
assert.ok(
|
||||
originalDateNow() - startedAt < 10_000,
|
||||
"the 30 s sleep should end as soon as the request is aborted"
|
||||
);
|
||||
});
|
||||
|
||||
test("clampCallerMs: bounds caller values, never shrinks the fallback", () => {
|
||||
assert.equal(MAX_CALLER_POLL_INTERVAL_MS, INTERVAL_CEILING);
|
||||
assert.equal(MAX_CALLER_POLL_TIMEOUT_MS, TIMEOUT_CEILING);
|
||||
assert.equal(clampCallerMs(HUGE_MS, 2_000, 30_000), 30_000);
|
||||
assert.equal(clampCallerMs("1500.9", 2_000, 30_000), 1_500);
|
||||
assert.equal(clampCallerMs(undefined, 2_000, 30_000), 2_000);
|
||||
assert.equal(clampCallerMs(0, 2_000, 30_000), 2_000);
|
||||
assert.equal(clampCallerMs(-5, 2_000, 30_000), 2_000);
|
||||
assert.equal(clampCallerMs(Number.NaN, 2_000, 30_000), 2_000);
|
||||
assert.equal(clampCallerMs(Infinity, 2_000, 30_000), 2_000);
|
||||
assert.equal(clampCallerMs(0.5, 2_000, 30_000), 2_000, "sub-millisecond values would spin");
|
||||
// A fallback above the ceiling (an operator default) is kept, and a caller may ask for it.
|
||||
assert.equal(clampCallerMs(undefined, 900_000, 600_000), 900_000);
|
||||
assert.equal(clampCallerMs(HUGE_MS, 900_000, 600_000), 900_000);
|
||||
assert.equal(clampPollIntervalMs(HUGE_MS, 2_500), INTERVAL_CEILING);
|
||||
assert.equal(clampPollTimeoutMs(HUGE_MS, 300_000), TIMEOUT_CEILING);
|
||||
});
|
||||
@@ -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",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
44
tests/unit/syntx-provider-rules-own-keys.test.ts
Normal file
44
tests/unit/syntx-provider-rules-own-keys.test.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// CodeQL #1392 (js/unvalidated-dynamic-method-call): applySyntxProviderRules indexed a plain
|
||||
// object literal with the caller-chosen `aiName` (the text before "/" in the requested model), so
|
||||
// names such as "constructor", "__proto__", "hasOwnProperty" or "valueOf" resolved to members
|
||||
// inherited from Object.prototype and were invoked. Only the rules defined in the table may run;
|
||||
// any other name takes the "no rule" path and leaves the settings untouched.
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const { applySyntxProviderRules } = await import("../../open-sse/services/syntxMedia.ts");
|
||||
|
||||
const INHERITED_NAMES = ["constructor", "__proto__", "hasOwnProperty", "valueOf", "toString"];
|
||||
|
||||
describe("applySyntxProviderRules: only own rule entries run", () => {
|
||||
for (const aiName of INHERITED_NAMES) {
|
||||
it(`"${aiName}" takes the no-rule path without a TypeError`, () => {
|
||||
const settings = { aspect_ratio: "1:1", resolution: "1K", style: "x" };
|
||||
assert.doesNotThrow(() =>
|
||||
applySyntxProviderRules(aiName, settings, { modelType: "m", fileCount: 0 })
|
||||
);
|
||||
assert.deepEqual(settings, { aspect_ratio: "1:1", resolution: "1K", style: "x" });
|
||||
});
|
||||
}
|
||||
|
||||
it("never invokes the inherited Object.prototype.constructor", () => {
|
||||
const original = Object.prototype.constructor;
|
||||
let calls = 0;
|
||||
// Swap the inherited member for a spy; a plain-object lookup of "constructor" reaches it.
|
||||
Object.prototype.constructor = function spy() {
|
||||
calls += 1;
|
||||
} as unknown as ObjectConstructor;
|
||||
try {
|
||||
applySyntxProviderRules("constructor", {}, { modelType: "m" });
|
||||
} finally {
|
||||
Object.prototype.constructor = original;
|
||||
}
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
it("an own rule still applies", () => {
|
||||
const settings = { model_type: "seedream-4.5", resolution: "1K" };
|
||||
applySyntxProviderRules("seedream", settings, { modelType: "seedream-4.5" });
|
||||
assert.equal(settings.resolution, "2K");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user