Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

17.4 KB
Raw Blame
/**
 * 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 {
  // These tests exercise the handler in the fresh-install open mode (no password
  // configured, requireLogin default). That mode is loopback-only, and loopback is
  // decided from the real peer — never from the `http://localhost` URL
  // (GHSA-7pq4-8pvv-rx7r) — so give the direct-call Request a loopback socket peer.
  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 }),
    })
  );
}

async function errorMessageOf(res: Response): Promise<string | undefined> {
  const body = (await res.json()) as Record<string, unknown>;
  return (body.error as Record<string, unknown> | undefined)?.message as string | undefined;
}

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}`
  );
});

// ── GHSA-7pq4-8pvv-rx7r — the vault root must never expose the data directory ──
//
// The WebDAV file service (scripts/dev/webdav-handler.mjs) serves the vault root
// to anyone holding the Basic credentials, before Next.js and outside the authz
// pipeline. Pointing it at DATA_DIR (or a parent of it) hands out server.env —
// JWT_SECRET / STORAGE_ENCRYPTION_KEY / API_KEY_SECRET — and storage.sqlite.

test("POST rejects a vaultPath that IS the data directory → 400 (GHSA-7pq4-8pvv-rx7r)", async () => {
  const res = await postVault(TEST_DATA_DIR);
  assert.equal(res.status, 400);
  const msg = await errorMessageOf(res);
  assert.ok(msg && /data directory/i.test(msg), `expected a data-directory refusal, got: ${msg}`);
  assert.ok(!msg.includes("at /"), "error must not carry a stack trace");
  assert.ok(!msg.includes(TEST_DATA_DIR), "error must not echo the data directory location");
  assert.equal(obsidianDb.getWebdavEnabled(), false, "WebDAV must stay disabled");
  assert.equal(obsidianDb.getObsidianVaultPath(), null, "vault path must not be stored");
});

test("POST rejects a vaultPath that CONTAINS the data directory (parent dir) → 400 (GHSA-7pq4-8pvv-rx7r)", async () => {
  const res = await postVault(path.dirname(TEST_DATA_DIR));
  assert.equal(res.status, 400);
  const msg = await errorMessageOf(res);
  assert.ok(msg && /data directory/i.test(msg), `expected a data-directory refusal, got: ${msg}`);
  assert.equal(obsidianDb.getWebdavEnabled(), false);
});

test("POST rejects a vaultPath INSIDE the data directory → 400 (GHSA-7pq4-8pvv-rx7r)", async () => {
  const inside = path.join(TEST_DATA_DIR, "db_backups");
  fs.mkdirSync(inside, { recursive: true });
  const res = await postVault(inside);
  assert.equal(res.status, 400);
  assert.equal(obsidianDb.getWebdavEnabled(), false);
});

test("POST rejects a symlink that resolves to the data directory → 400 (GHSA-7pq4-8pvv-rx7r)", async () => {
  const linkParent = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault-link-"));
  const link = path.join(linkParent, "vault");
  try {
    fs.symlinkSync(TEST_DATA_DIR, link, "dir");
  } catch {
    fs.rmSync(linkParent, { recursive: true, force: true });
    return; // platform without symlink permission — nothing to assert
  }
  try {
    const res = await postVault(link);
    assert.equal(res.status, 400);
    assert.equal(obsidianDb.getWebdavEnabled(), false);
  } finally {
    fs.rmSync(linkParent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
  }
});

test("POST with a directory unrelated to the data directory still succeeds (sibling in tmp)", async () => {
  const vaultDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-vault-ok-"));
  try {
    const res = await postVault(vaultDir);
    assert.equal(res.status, 200);
    const body = (await res.json()) as Record<string, unknown>;
    assert.equal(body.vaultPath, path.resolve(vaultDir));
    assert.equal(obsidianDb.getWebdavEnabled(), true);
  } finally {
    fs.rmSync(vaultDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
  }
});

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"
  );
});