Compare commits

..

2 Commits

Author SHA1 Message Date
diegosouzapw
035b02bcd1 chore(changelog): number the fragment for #20819 2026-11-20 18:12:44 -03:00
diegosouzapw
380b6a7786 fix(security): operator-only credential and denied roots for corpus and vault paths (CodeQL #1371, #1372, #1373)
POST /api/settings/local-corpus (rootPath) and POST /api/settings/obsidian/webdav
(vaultPath) now require an operator credential (dashboard session or local CLI) through
requireOperatorCredential; API keys of any scope and access tokens get 403. The webdav
route passes alwaysRequireAuth because /api/settings/obsidian is ALWAYS_PROTECTED.

Both roots also refuse the filesystem root, the home directory itself and the system
directories /etc /usr /bin /sbin /var /proc /sys /dev /boot /root (and below), compared
after path.resolve and realpath, with a fixed 400 message. The vault keeps its DATA_DIR
overlap refusal.
2026-11-20 18:05:40 -03:00
13 changed files with 379 additions and 264 deletions

View File

@@ -0,0 +1 @@
- **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):** GitHub Copilot Responses-only inference, model display names and the Context7 library id check use linear regexes, so a long crafted model or library id no longer blocks the event loop for seconds (CodeQL js/polynomial-redos #1325, #1324, #1296)

View File

@@ -48,9 +48,7 @@ export function isValidContext7LibraryId(id: string): id is string {
// Each segment: starts with alphanumeric (GitHub owner/repo convention —
// no leading '-'), path-safe chars, no trailing dot, no dot-run.
const seg = /^[A-Za-z0-9][\w-]*(?:\.[\w-]+)*$/; // starts alnum, dots only interior, no dot-run
// Segments split on '/' with [^/]+ (linear). `seg` rejects '/' and line terminators, so this
// accepts the same ids as the former /^\/(.+)\/(.+)$/, which was O(n^2) on a run of slashes.
const m = /^\/([^/]+)\/([^/]+)$/.exec(id);
const m = /^\/(.+)\/(.+)$/.exec(id);
return m !== null && seg.test(m[1]) && seg.test(m[2]);
}

View File

@@ -11,6 +11,7 @@ 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";
@@ -20,6 +21,11 @@ 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 });
@@ -40,6 +46,10 @@ 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,6 +2,7 @@ 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,
@@ -15,6 +16,12 @@ 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 });
@@ -32,8 +39,7 @@ 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,
});
@@ -47,6 +53,11 @@ 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 {
@@ -57,10 +68,7 @@ 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

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

@@ -2,6 +2,8 @@ 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",
@@ -278,6 +280,9 @@ 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,6 +1,7 @@
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,
@@ -75,6 +76,12 @@ 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

@@ -46,11 +46,8 @@ const DASH_VERSION_BRANDS = new Set(["gpt"]);
/** Release-date stamps at the end of ids ("claude-3-5-sonnet-20241022"). */
const DATE_TOKEN = /^(19|20)\d{6}$/;
/**
* "v4.1" / "V2.6" — an explicit version marker. One leading digit, then digits and dots: the
* same language as /^v\d+[.\d]*$/ without the overlapping quantifiers that made it O(n^2).
*/
const VERSION_MARKER = /^v\d[.\d]*$/i;
/** "v4.1" / "V2.6" — an explicit version marker. */
const VERSION_MARKER = /^v\d+([.\d]*)$/i;
/** Digits left over after the brand prefix ("qwen3.8" -> "qwen" + "3.8"). */
const BRANDED_VERSION = /^([A-Za-z]+)(\d[.\d]*)$/;

View File

@@ -19,19 +19,9 @@
* them.
*/
// Split from one /^(?:.*codex.*|gpt-(?:[6-9]|5\.[5-9]).*)$/i, which backtracked in O(n^2) on a
// long client model id (CodeQL js/polynomial-redos). Same accept set: that pattern's `.` never
// matched a line terminator, so an id holding one stays rejected.
const CODEX_FAMILY = /codex/i;
const RESPONSES_ONLY_GPT_PREFIX = /^gpt-(?:[6-9]|5\.[5-9])/i;
const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
const GITHUB_RESPONSES_ONLY_GPT = /^(?:.*codex.*|gpt-(?:[6-9]|5\.[5-9]).*)$/i;
const NON_RESPONSES_FAMILY = /claude|gemini/i;
function isResponsesOnlyModelId(modelId: string): boolean {
if (LINE_TERMINATOR.test(modelId)) return false;
return CODEX_FAMILY.test(modelId) || RESPONSES_ONLY_GPT_PREFIX.test(modelId);
}
export function inferGithubUnsyncedTargetFormat(
providerId: string,
modelId: string
@@ -40,7 +30,7 @@ export function inferGithubUnsyncedTargetFormat(
return undefined;
}
const bareModelId = modelId.replace(/^(?:github|gh|ghe-copilot)\//i, "");
if (!isResponsesOnlyModelId(bareModelId) || NON_RESPONSES_FAMILY.test(bareModelId)) {
if (!GITHUB_RESPONSES_ONLY_GPT.test(bareModelId) || NON_RESPONSES_FAMILY.test(bareModelId)) {
return undefined;
}
return "openai-responses";

View File

@@ -1,197 +0,0 @@
import test from "node:test";
import assert from "node:assert/strict";
// CodeQL js/polynomial-redos #1325, #1324, #1296: three model/library id regexes backtracked in
// O(n^2) on crafted ids. Each id reaches its regex without a length cap (a client model id
// "gh/<id>", an upstream /v1/models id, a raw Context7 search item id).
//
// Two checks per function:
// - a 50k-char pathological id returns fast (measured on the exported function);
// - a truth table generated by running the pre-fix functions (git show of the base) stays the
// same, so the linear rewrites keep the exact accept/reject behavior.
const { inferGithubUnsyncedTargetFormat } =
await import("../../src/sse/services/githubResponsesFallback.ts");
const { modelDisplayName } = await import("../../src/shared/utils/modelDisplayName.ts");
const { isValidContext7LibraryId } = await import("../../open-sse/executors/context7-fetch.ts");
const PATHOLOGICAL_LENGTH = 50_000;
const BUDGET_MS = 200;
function elapsedMs(fn: () => unknown): number {
const start = performance.now();
fn();
return performance.now() - start;
}
const GITHUB_TABLE: Array<[string, string, string | null]> = [
["gh", "gpt-6", "openai-responses"],
["gh", "gpt-6.1-sol", "openai-responses"],
["gh", "GPT-7-mini", "openai-responses"],
["gh", "gpt-9", "openai-responses"],
["gh", "gpt-60", "openai-responses"],
["gh", "gpt-5.5", "openai-responses"],
["gh", "gpt-5.9-codex", "openai-responses"],
["gh", "GPT-5.5", "openai-responses"],
["gh", "gpt-5.4", null],
["gh", "gpt-5", null],
["gh", "gpt-5.10", null],
["gh", "gpt-5-codex", "openai-responses"],
["gh", "gpt-4o", null],
["gh", "gpt-4.1", null],
["gh", "gpt-10", null],
["gh", "gpt-", null],
["gh", "gpt_6", null],
["gh", "agpt-6", null],
["gh", " gpt-6", null],
["gh", "gpt-6 ", "openai-responses"],
["gh", "codex-mini", "openai-responses"],
["gh", "my-CODEX", "openai-responses"],
["gh", "codex", "openai-responses"],
["gh", "Codex-Max", "openai-responses"],
["gh", "code-x", null],
["gh", "claude-codex", null],
["gh", "gemini-codex", null],
["gh", "gpt-6-claude", null],
["gh", "o3", null],
["gh", "", null],
["gh", "gpt-6\n", null],
["gh", "gpt-6\nx", null],
["gh", "\ngpt-6", null],
["gh", "codex\r", null],
["gh", "gpt-6\u2028x", null],
["gh", "x\u2029codex", null],
["gh", "codex\t", "openai-responses"],
["gh", "gpt-6\u0085", "openai-responses"],
["gh", "gh/gpt-6", "openai-responses"],
["gh", "github/gpt-6.1", "openai-responses"],
["gh", "GH/codex", "openai-responses"],
["gh", "ghe-copilot/gpt-5.5", "openai-responses"],
["github", "gpt-6", "openai-responses"],
["ghe-copilot", "gpt-5.6-codex", "openai-responses"],
["github", "claude-opus-5-5", null],
["openai", "gpt-6", null],
["codex", "codex-mini", null],
["gh", "openai/gpt-6", null],
["gh", "x/codex", "openai-responses"],
];
const DISPLAY_TABLE: Array<[string, string]> = [
["deepseek-v4.1-flash", "DeepSeek V4.1 Flash"],
["gpt-v2", "GPT-V2"],
["gpt-V2.6", "GPT-V2.6"],
["gpt-v", "GPT V"],
["gpt-v.", "GPT V."],
["gpt-v.1", "GPT V.1"],
["gpt-v1.", "GPT-V1."],
["gpt-v1..2", "GPT-V1..2"],
["gpt-v1x", "GPT V1x"],
["gpt-vx1", "GPT Vx1"],
["gpt-v12.3.4", "GPT-V12.3.4"],
["gpt-v1-turbo", "GPT-V1 Turbo"],
["gpt-vv1", "GPT Vv1"],
["gpt-4-v1", "GPT-4 V1"],
["foo-v2.6-bar", "Foo V2.6 Bar"],
["v1", "V1"],
["v", "V"],
["mistral-v0.1", "Mistral V0.1"],
["model-V2.6", "Model V2.6"],
["gpt-6.1-sol", "GPT-6.1 Sol"],
["claude-opus-5-5", "Claude Opus 5.5"],
["glm-5.3-flash", "GLM 5.3 Flash"],
["claude-3-5-sonnet-20241022", "Claude 3.5 Sonnet"],
["qwen3.8", "Qwen 3.8"],
["cmc/deepseek/deepseek-v4.1-flash", "DeepSeek V4.1 Flash"],
["gpt-v1 x", "GPT-V1 X"],
["", ""],
];
const CONTEXT7_TABLE: Array<[string, boolean]> = [
["/vercel/next.js", true],
["/upstash/context7", true],
["/a/b", true],
["/a.b/c-d_e", true],
["/a/b/c", false],
["//a", false],
["/a//b", false],
["/a/", false],
["a/b", false],
["/a/b/", false],
["/a/b\n", false],
["/a\n/b", false],
["/\n/b", false],
["/a/\n", false],
["/a/b\r", false],
["/a/b\u2028", false],
["/a\u2029/b", false],
["/./b", false],
["/a/..", false],
["/a/b..c", false],
["/-a/b", false],
["/a/b.", false],
["/a/.b", false],
["", false],
["/", false],
["//", false],
["///", false],
["/a", false],
["/a/b c", false],
["/A1/B2", true],
["/_a/b", false],
];
test("#1325 GitHub Responses-only inference is linear on a 'codex' run ending in a line break", () => {
const id = "codex".repeat(PATHOLOGICAL_LENGTH / 5) + "\n!";
let result: unknown = "unset";
const ms = elapsedMs(() => {
result = inferGithubUnsyncedTargetFormat("gh", id);
});
assert.equal(result, undefined);
assert.ok(ms < BUDGET_MS, `took ${ms.toFixed(1)}ms`);
});
test("#1325 GitHub Responses-only inference keeps the pre-fix truth table", () => {
for (const [providerId, modelId, expected] of GITHUB_TABLE) {
assert.equal(
inferGithubUnsyncedTargetFormat(providerId, modelId) ?? null,
expected,
JSON.stringify([providerId, modelId])
);
}
});
test("#1324 model display name is linear on a long version-marker token", () => {
const id = "gpt-v" + "0".repeat(PATHOLOGICAL_LENGTH - 6) + "x";
let result = "";
const ms = elapsedMs(() => {
result = modelDisplayName(id);
});
assert.ok(result.startsWith("GPT V0"));
assert.ok(ms < BUDGET_MS, `took ${ms.toFixed(1)}ms`);
});
test("#1324 model display name keeps the pre-fix truth table", () => {
for (const [id, expected] of DISPLAY_TABLE) {
assert.equal(modelDisplayName(id), expected, JSON.stringify(id));
}
});
test("#1296 Context7 library id check is linear on a run of slashes ending in a line break", () => {
for (const id of [
"/".repeat(PATHOLOGICAL_LENGTH - 1) + "\n",
"/a".repeat(PATHOLOGICAL_LENGTH / 2 - 1) + "\n",
]) {
let result: unknown = "unset";
const ms = elapsedMs(() => {
result = isValidContext7LibraryId(id);
});
assert.equal(result, false);
assert.ok(ms < BUDGET_MS, `took ${ms.toFixed(1)}ms`);
}
});
test("#1296 Context7 library id check keeps the pre-fix truth table", () => {
for (const [id, expected] of CONTEXT7_TABLE) {
assert.equal(isValidContext7LibraryId(id), expected, JSON.stringify(id));
}
});

View File

@@ -49,14 +49,22 @@ function makeRequest(url: string, options?: RequestInit): NextRequest {
return Object.assign(new Request(url, options), { ip: "127.0.0.1" }) as unknown as NextRequest;
}
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 }),
})
);
/**
* 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 }));
}
async function errorMessageOf(res: Response): Promise<string | undefined> {
@@ -113,11 +121,7 @@ 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 = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
});
const req = await makeOperatorPost({ vaultPath: vaultDir });
const res = await route.POST(req);
assert.equal(res.status, 200);
@@ -154,13 +158,7 @@ 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(
makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
})
);
const enableRes = await route.POST(await makeOperatorPost({ vaultPath: vaultDir }));
assert.equal(enableRes.status, 200);
// Anonymous (open-mode) caller: password masked, flag still set.
@@ -192,11 +190,7 @@ 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 = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: nonExistentPath }),
});
const req = await makeOperatorPost({ vaultPath: nonExistentPath });
const res = await route.POST(req);
assert.equal(res.status, 400);
@@ -276,11 +270,7 @@ test("POST with a directory unrelated to the data directory still succeeds (sibl
});
test("POST with invalid body (missing vaultPath) → 400", async () => {
const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({}),
});
const req = await makeOperatorPost({});
const res = await route.POST(req);
assert.equal(res.status, 400);
});
@@ -289,11 +279,7 @@ 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 = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
});
const enableReq = await makeOperatorPost({ vaultPath: vaultDir });
const enableRes = await route.POST(enableReq);
assert.equal(enableRes.status, 200);
@@ -322,11 +308,7 @@ 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 = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ vaultPath: vaultDir }),
});
const enableReq = await makeOperatorPost({ vaultPath: vaultDir });
await route.POST(enableReq);
const deleteReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "DELETE",

View File

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