Files
Kelx/tests/audit-p32-p41-p42.test.js
T
2026-11-30 16:32:37 +00:00

223 lines
11 KiB
JavaScript

"use strict";
// Tests for audit findings P3.2, P4.1 and P4.2.
//
// P3.2: deleting a nonexistent resource reported success. deleteServerByName
// swept schedules/index for a name with no index row and returned ok:true, so
// the admin route went on to record a server_delete activity that deleted
// nothing; DELETE /api/settings/webhooks likewise cleared an already-null
// single webhook and logged a webhook_config_delete. Both now answer an
// explicit 404. An absent server cannot authorize name-only cleanup, which
// could affect a replacement created after the lookup.
//
// P4.1: the server :name routes double-decoded req.params.name
// (decodeURIComponent on a value Express has already decoded), which mangles
// names that legitimately contain "%"-sequences. The params are now used as
// the framework decoded them.
//
// P4.2: category webhooks are only dispatched while the mode is "multiple",
// yet the API accepted storing one while the request explicitly pinned the
// mode to "single" (a URL that never fires), and switching the mode back to
// "single" left configured category webhooks dormant with no indication in
// the UI. The API now refuses the contradictory save, warns on mode switches
// that create dormancy, and the settings UI renders a persistent
// saved-but-inactive notice.
//
// index.js boots servers on require, so route-level behavior is locked with
// source assertions (same technique as webhook-dispatch-hardening.test.js /
// server-delete-verified-alias.test.js); deleteServerByName is policy-only
// and is exercised directly with fakes.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const SERVER_DELETE_JS = path.join(ROOT, "utils", "server-delete.js");
const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js");
const SETTINGS_EJS = path.join(ROOT, "views", "settings.ejs");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const serverDeleteSource = fs.readFileSync(SERVER_DELETE_JS, "utf8");
const settingsJsSource = fs.readFileSync(SETTINGS_JS, "utf8");
const settingsEjsSource = fs.readFileSync(SETTINGS_EJS, "utf8");
const { deleteServerByName } = require("../utils/server-delete");
function endIndexOfFunction(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker ${startMarker} not found`);
const bodyStart = source.indexOf("{", start);
let depth = 0;
for (let i = bodyStart; i < source.length; i += 1) {
if (source[i] === "{") depth += 1;
else if (source[i] === "}") {
depth -= 1;
if (depth === 0) return i + 1;
}
}
assert.fail(`unbalanced braces after marker ${startMarker}`);
}
// ---------------------------------------------------------------------------
// P3.2 — deleteServerByName no longer reports success for a missing entry
// ---------------------------------------------------------------------------
function makeMissingEntryDeps() {
const calls = { schedules: [], indexRemovals: [], nodeRequests: [] };
return {
calls,
deps: {
findServer: async () => null,
isRemoteEntry: () => false,
deleteServerSchedules: async (n) => calls.schedules.push(n),
removeServerIndexEntry: async (n) => calls.indexRemovals.push(n),
removeAccessForServerName: async () => {},
markServerDeletingStatus: async () => ({ ok: true }),
httpRequestJson: async (url) => {
calls.nodeRequests.push(url);
return { status: 404, json: { error: "not found" } };
},
},
};
}
test("P3.2: deleting a server with no index entry reports not-found, not success", async () => {
const { deps } = makeMissingEntryDeps();
const result = await deleteServerByName(deps, "ghost");
assert.equal(result.ok, false);
assert.equal(result.statusCode, 404);
assert.equal(result.error, "server not found");
});
test("P3.2: a missing entry cannot authorize cleanup by name", async () => {
const { calls, deps } = makeMissingEntryDeps();
await deleteServerByName(deps, "ghost");
assert.deepEqual(calls.schedules, [], "no schedules may be removed without a claimed server row");
assert.deepEqual(calls.indexRemovals, [], "no index removal may target a server name alone");
assert.deepEqual(calls.nodeRequests, [], "no node calls may happen for a nonexistent server");
});
test("P3.2: a not-found server delete cannot reach the success-only audit path", () => {
// The admin route records server_delete activity and invalidates caches
// only behind the !result.ok gate; the 404 must exit before both.
const start = indexSource.indexOf('app.delete("/api/settings/servers/:name"');
assert.ok(start >= 0, "admin server delete route must exist");
const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start;
const handler = indexSource.slice(start, end);
const okGate = handler.indexOf("if (!result.ok)");
const recordAt = handler.indexOf("recordActivity");
assert.ok(okGate >= 0, "the !result.ok gate must be present");
assert.ok(recordAt > okGate, "activity recording must stay behind the ok gate");
assert.ok(handler.includes("result.statusCode || 500"), "the route must honour the policy statusCode");
});
// ---------------------------------------------------------------------------
// P3.2 — webhook delete answers 404 when there is nothing to delete
// ---------------------------------------------------------------------------
test("P3.2: webhook delete returns 404 for an absent single/category webhook", () => {
const start = indexSource.indexOf('app.delete("/api/settings/webhooks"');
assert.ok(start >= 0, "webhook delete route must exist");
const end = indexSource.indexOf('app.post("/api/settings/webhooks/test"', start);
assert.ok(end > start, "webhook delete handler slice must be bounded");
const handler = indexSource.slice(start, end);
assert.ok(handler.includes("No webhook is configured for this category"), "category branch must 404");
assert.ok(handler.includes("No single webhook is configured"), "single branch must 404");
assert.ok(handler.includes("status(404)"), "the not-found answers must be 404s");
});
test("P3.2: the webhook not-found probe runs after authorization but before step-up", () => {
const start = indexSource.indexOf('app.delete("/api/settings/webhooks"');
const end = indexSource.indexOf('app.post("/api/settings/webhooks/test"', start);
const handler = indexSource.slice(start, end);
const adminAt = handler.indexOf("currentUser.admin");
const notFoundAt = handler.indexOf("No single webhook is configured");
const stepUpAt = handler.indexOf("requireDestructiveActionStepUp");
assert.ok(adminAt >= 0, "admin check must be present");
assert.ok(adminAt < notFoundAt, "authorization must run before the not-found probe (no config-state leak to non-admins)");
assert.ok(notFoundAt < stepUpAt, "a no-op delete must not burn a destructive-action grace use");
});
// ---------------------------------------------------------------------------
// P4.1 — no double decodeURIComponent on the :name route params
// ---------------------------------------------------------------------------
test("P4.1: server :name routes use the already-decoded Express param", () => {
assert.ok(!indexSource.includes("nameParam"), "the decode-then-trim nameParam pattern must be gone");
const directReads = indexSource.split('String(req.params.name || "").trim()').length - 1;
assert.ok(
directReads >= 8,
`the :name routes must read req.params.name directly (found ${directReads}, need >= 8)`
);
});
test("P4.1: deleteServerByName expects a plain, already-decoded name", () => {
assert.ok(
!serverDeleteSource.includes("decodeURIComponent"),
"server-delete must not re-decode caller-provided names"
);
});
test("P4.1: non-param decodes stay in place (no overzealous sweep)", () => {
// req.path / URL.pathname segments are still percent-encoded raw, so their
// decodes are correct and must not be removed by the P4.1 remediation.
assert.ok(indexSource.includes("decodeServerPathSegment"), "raw req.path decodes must remain");
assert.ok(indexSource.includes("rawName = decodeURIComponent(rawName)"), "import filename decodes must remain");
});
// ---------------------------------------------------------------------------
// P4.2 — category webhooks can no longer be silently dormant
// ---------------------------------------------------------------------------
test("P4.2: POST refuses a category webhook while explicitly pinning mode to 'single'", () => {
const start = indexSource.indexOf('app.post("/api/settings/webhooks"');
assert.ok(start >= 0, "webhook POST route must exist");
const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start;
const handler = indexSource.slice(start, end);
assert.ok(
handler.includes("Category webhooks require webhook mode 'multiple'"),
"the contradictory combination must be rejected"
);
const rejectAt = handler.indexOf("Category webhooks require webhook mode 'multiple'");
// P3.1 moved the config load under the write lock (after the step-up), so
// the load marker is now the locked fresh read; the invariant is the same
// and stricter: validation must run before any config load or mutation.
const loadAt = handler.indexOf("loadWebhooksConfigFresh()");
const stepUpAt = handler.indexOf("requireDestructiveActionStepUp");
assert.ok(loadAt >= 0, "the locked fresh load must be present");
assert.ok(rejectAt < loadAt, "validation must run before the config is loaded or mutated");
assert.ok(rejectAt < stepUpAt, "validation must run before the step-up");
});
test("P4.2: POST warns when the saved state leaves category webhooks dormant", () => {
const start = indexSource.indexOf('app.post("/api/settings/webhooks"');
const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start;
const handler = indexSource.slice(start, end);
assert.ok(handler.includes("dormantCategoryCount"), "dormancy must be detected after the mutation block");
assert.ok(
handler.includes("payload.warning = saved.dormantCategoryWarning"),
"the success payload must carry the warning (P3.1 renamed the saved state carrier)"
);
});
test("P4.2: settings UI surfaces configured-but-dormant category webhooks", () => {
assert.ok(settingsEjsSource.includes('id="webhookDormantCategoriesNote"'), "settings.ejs must render the dormant note");
assert.ok(settingsEjsSource.includes('id="webhookDormantCategoriesText"'), "settings.ejs must render the dormant text");
assert.ok(settingsJsSource.includes("webhookDormantCategoriesNote"), "settings.js must wire the dormant note");
assert.ok(settingsJsSource.includes("webhookDormantCategoriesText.textContent"), "settings.js must describe the dormant state");
assert.ok(
settingsJsSource.split("data.warning").length - 1 >= 2,
"both mode-switch handlers must surface the server's dormancy warning"
);
});
test("P4.2: the shipped category-save flow always pins mode 'multiple' (400 cannot trigger)", () => {
assert.ok(
settingsJsSource.includes("webhookEditCategory ? 'multiple' : 'single'"),
"the modal must send mode 'multiple' for category saves so the new 400 never blocks the built-in UI"
);
});