Files
OmniRoute/tests/unit/obsidian-webdav-route.test.ts
Diego Rodrigues de Sa e Souza 3d4f3e4960 test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966) (#11968)
* test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966)

Two shards on release/v3.8.51 went red in one day with the same signature —
"ENOTEMPTY, Directory not empty: /tmp/omniroute-<test>-XXXXXX" — from
combo-same-provider-cascade (Unit Tests fast-path 4/4, on a PR that touches only
.github/) and auth-policy-embeddings-webfetch-7785 (the 20k-test TIA step). Both pass
alone and on re-run: the cleanup races something still writing into the directory
(SQLite WAL/-shm checkpoint, a worker, the backup) and under a loaded hosted runner
the window opens. 1154 test files do their own cleanup with
fs.rmSync(dir, { recursive: true, force: true }); 57 already asked for retries.

One-shot codemod (scripts/ad-hoc/codemod-rm-maxretries.mjs, kept for the record):
every rm / rmSync / rmdirSync option object with `recursive: true` and no
`maxRetries` gains `maxRetries: 5, retryDelay: 100` — Node itself then retries
ENOTEMPTY/EBUSY/EPERM for up to ~0.5 s before giving up. 2243 call sites in 1292
files under tests/, the shared tests/_setup/isolateDataDir.ts exit hook included.
Only the option object changes: no call site, assertion or import is touched.

Validation: prettier and ESLint (with the frozen suppressions) clean on all 1292
files; a random 20-file sample runs green (quota-redis-store hangs identically on
the untouched tree — it needs a Redis on localhost, an environment matter). The
four unit shards on this PR are the full run.

* fix(quality): let check-forgotten-sibling-tests read a 1,000-file diff

The gate shells out to `git diff` through execFileSync with Node's default 1 MB
maxBuffer; the 1,292-file codemod in this PR is the first diff large enough to
overflow it, and the gate died with `spawnSync git ENOBUFS` before comparing
anything. 64 MB is far above any real PR and costs nothing when unused.
2026-08-29 01:17:40 -03:00

358 lines
14 KiB
TypeScript

/**
* TDD tests for /api/settings/obsidian/webdav route (PR1 of #3485).
*
* Covers:
* - GET: no config → disabled shape with null creds
* - POST: valid temp dir → enabled, returns { username, password }
* - POST: non-existent path → 400 with no stack trace leaked
* - DELETE: after enable → disabled, creds cleared
* - Unauthenticated → 401
* - Encryption round-trip: set password → raw DB value is NOT plaintext → get returns plaintext
*/
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 type { NextRequest } from "next/server";
import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omni-obsidian-webdav-route-"));
const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
const ORIGINAL_INITIAL_PASSWORD = process.env.INITIAL_PASSWORD;
const ORIGINAL_JWT_SECRET = process.env.JWT_SECRET;
const ORIGINAL_STORAGE_ENCRYPTION_KEY = process.env.STORAGE_ENCRYPTION_KEY;
// Set DATA_DIR before any module imports so the DB picks up the temp dir.
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
// Import settings to control auth requirements
const settingsDb = await import("../../src/lib/db/settings.ts");
// Import the route under test
const route = await import("../../src/app/api/settings/obsidian/webdav/route.ts");
// Import DB module to inspect raw stored values
const obsidianDb = await import("../../src/lib/db/obsidian.ts");
async function resetStorage() {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
function makeRequest(url: string, options?: RequestInit): NextRequest {
return new Request(url, options) as unknown as NextRequest;
}
test.beforeEach(async () => {
delete process.env.INITIAL_PASSWORD;
delete process.env.STORAGE_ENCRYPTION_KEY;
await resetStorage();
});
test.after(() => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
if (ORIGINAL_DATA_DIR === undefined) {
delete process.env.DATA_DIR;
} else {
process.env.DATA_DIR = ORIGINAL_DATA_DIR;
}
if (ORIGINAL_INITIAL_PASSWORD === undefined) {
delete process.env.INITIAL_PASSWORD;
} else {
process.env.INITIAL_PASSWORD = ORIGINAL_INITIAL_PASSWORD;
}
if (ORIGINAL_JWT_SECRET === undefined) {
delete process.env.JWT_SECRET;
} else {
process.env.JWT_SECRET = ORIGINAL_JWT_SECRET;
}
if (ORIGINAL_STORAGE_ENCRYPTION_KEY === undefined) {
delete process.env.STORAGE_ENCRYPTION_KEY;
} else {
process.env.STORAGE_ENCRYPTION_KEY = ORIGINAL_STORAGE_ENCRYPTION_KEY;
}
});
// ── Auth is disabled by default (requireLogin not set) so requests succeed ──
test("GET with no config → webdavEnabled:false, all creds null", async () => {
const req = makeRequest("http://localhost/api/settings/obsidian/webdav");
const res = await route.GET(req);
assert.equal(res.status, 200);
const body = (await res.json()) as Record<string, unknown>;
assert.equal(body.webdavEnabled, false);
assert.equal(body.webdavUsername, null);
assert.equal(body.webdavPassword, null);
assert.equal(body.vaultPath, null);
});
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 res = await route.POST(req);
assert.equal(res.status, 200);
const body = (await res.json()) as Record<string, unknown>;
assert.ok(
typeof body.username === "string" && (body.username as string).length > 0,
"username non-empty"
);
assert.ok(
typeof body.password === "string" && (body.password as string).length > 0,
"password non-empty"
);
assert.ok(typeof body.vaultPath === "string", "vaultPath returned");
// GET should now reflect enabled state
const getReq = makeRequest("http://localhost/api/settings/obsidian/webdav");
const getRes = await route.GET(getReq);
assert.equal(getRes.status, 200);
const getBody = (await getRes.json()) as Record<string, unknown>;
assert.equal(getBody.webdavEnabled, true);
assert.ok(
typeof getBody.webdavUsername === "string" && (getBody.webdavUsername as string).length > 0
);
// Anonymous GET (this request carries no management credential): the plaintext
// password is masked (GHSA-62vw), but the set/unset flag still reflects state.
assert.equal(getBody.webdavPassword, null);
assert.equal(getBody.webdavPasswordSet, true);
} finally {
fs.rmSync(vaultDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
test("GET masks the WebDAV password for anonymous callers but reveals it to a management session (GHSA-62vw)", async () => {
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 }),
})
);
assert.equal(enableRes.status, 200);
// Anonymous (open-mode) caller: password masked, flag still set.
const anonBody = (await (
await route.GET(makeRequest("http://localhost/api/settings/obsidian/webdav"))
).json()) as Record<string, unknown>;
assert.equal(anonBody.webdavEnabled, true);
assert.equal(
anonBody.webdavPassword,
null,
"anonymous caller must not receive the plaintext password"
);
assert.equal(anonBody.webdavPasswordSet, true);
// Genuine management session: the operator's reveal-password view still works.
const sessionReq = (await makeManagementSessionRequest(
"http://localhost/api/settings/obsidian/webdav"
)) as unknown as NextRequest;
const sessionBody = (await (await route.GET(sessionReq)).json()) as Record<string, unknown>;
assert.ok(
typeof sessionBody.webdavPassword === "string" &&
(sessionBody.webdavPassword as string).length > 0,
"a management session must still receive the plaintext password"
);
} finally {
fs.rmSync(vaultDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
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 res = await route.POST(req);
assert.equal(res.status, 400);
const body = (await res.json()) as Record<string, unknown>;
const errorMsg = (body.error as Record<string, unknown> | undefined)?.message as
string | undefined;
// Must not leak stack trace
assert.ok(
!errorMsg || !errorMsg.includes("at /"),
`Error message should not contain a stack trace, got: ${errorMsg}`
);
});
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 res = await route.POST(req);
assert.equal(res.status, 400);
});
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 enableRes = await route.POST(enableReq);
assert.equal(enableRes.status, 200);
// Delete
const deleteReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "DELETE",
});
const deleteRes = await route.DELETE(deleteReq);
assert.equal(deleteRes.status, 200);
const deleteBody = (await deleteRes.json()) as Record<string, unknown>;
assert.equal(deleteBody.success, true);
// GET should now show disabled
const getReq = makeRequest("http://localhost/api/settings/obsidian/webdav");
const getRes = await route.GET(getReq);
const getBody = (await getRes.json()) as Record<string, unknown>;
assert.equal(getBody.webdavEnabled, false);
assert.equal(getBody.webdavUsername, null);
assert.equal(getBody.webdavPassword, null);
} finally {
fs.rmSync(vaultDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
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 }),
});
await route.POST(enableReq);
const deleteReq = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "DELETE",
});
await route.DELETE(deleteReq);
// GET now: password must be null (not a stale value)
const getReq = makeRequest("http://localhost/api/settings/obsidian/webdav");
const getRes = await route.GET(getReq);
const getBody = (await getRes.json()) as Record<string, unknown>;
assert.equal(getBody.webdavEnabled, false);
assert.equal(getBody.webdavPassword, null);
} finally {
fs.rmSync(vaultDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
// ── Auth guard tests ──
test("Unauthenticated GET → 401 when auth is required", async () => {
process.env.INITIAL_PASSWORD = "bootstrap-password";
await settingsDb.updateSettings({ requireLogin: true, password: "" });
const req = makeRequest("http://localhost/api/settings/obsidian/webdav");
const res = await route.GET(req);
assert.equal(res.status, 401);
});
test("Unauthenticated POST → 401 when auth is required", async () => {
const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault4-"));
try {
process.env.INITIAL_PASSWORD = "bootstrap-password";
await settingsDb.updateSettings({ requireLogin: true, password: "" });
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, 401);
} finally {
fs.rmSync(vaultDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
test("Unauthenticated DELETE → 401 when auth is required", async () => {
process.env.INITIAL_PASSWORD = "bootstrap-password";
await settingsDb.updateSettings({ requireLogin: true, password: "" });
const req = makeRequest("http://localhost/api/settings/obsidian/webdav", {
method: "DELETE",
});
const res = await route.DELETE(req);
assert.equal(res.status, 401);
});
// ── Encryption round-trip ──
test("encryption round-trip: setWebdavPassword stores encrypted, getWebdavPassword returns plaintext", async () => {
// Enable encryption
process.env.STORAGE_ENCRYPTION_KEY = "test-encryption-key-for-webdav-route-tests";
// Invalidate cached encryption keys so the new env var is picked up.
// The encryption module caches keys in module-level vars; we reset via db instance.
core.resetDbInstance();
const plaintext = "super-secret-webdav-password-12345";
obsidianDb.setWebdavPassword(plaintext);
// Inspect raw DB row — it must NOT be the plaintext
const db = core.getDbInstance();
type KVRow = { value: string };
const row = db
.prepare("SELECT value FROM key_value WHERE namespace = ? AND key = ?")
.get("obsidian", "webdav_password") as KVRow | undefined;
assert.ok(row !== undefined, "Row should exist");
// The stored JSON string — parse to get inner value
const storedInner = JSON.parse(row!.value) as string;
assert.notEqual(
storedInner,
plaintext,
"Raw DB value must NOT be plaintext when encryption is enabled"
);
assert.ok(
storedInner.startsWith("enc:v1:"),
`Raw DB value should start with enc:v1: prefix, got: ${storedInner.slice(0, 40)}`
);
// getWebdavPassword must round-trip back to plaintext
const retrieved = obsidianDb.getWebdavPassword();
assert.equal(retrieved, plaintext, "getWebdavPassword must return original plaintext");
// Clean up env for other tests
delete process.env.STORAGE_ENCRYPTION_KEY;
core.resetDbInstance();
});
test("encryption graceful fallback: plaintext stored without key reads back correctly", async () => {
// No encryption key set — store plaintext
const plaintext = "plaintext-webdav-password";
obsidianDb.setWebdavPassword(plaintext);
// Must read back the same value
const retrieved = obsidianDb.getWebdavPassword();
assert.equal(
retrieved,
plaintext,
"Plaintext value must read back unchanged when no encryption key"
);
});