mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-21 02:54:25 +00:00
Compare commits
2 Commits
dependabot
...
fix/codeql
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
035b02bcd1 | ||
|
|
380b6a7786 |
1
changelog.d/fixes/20819-operator-only-path-roots.md
Normal file
1
changelog.d/fixes/20819-operator-only-path-roots.md
Normal 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)
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
79
src/lib/deniedRootDirectories.ts
Normal file
79
src/lib/deniedRootDirectories.ts
Normal 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)));
|
||||
});
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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}` };
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
236
tests/unit/operator-only-path-roots-codeql-1371.test.ts
Normal file
236
tests/unit/operator-only-path-roots-codeql-1371.test.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user