Files
Kelx/tests/webhook-dispatch-result.test.js
T
2026-11-30 16:32:37 +00:00

481 lines
24 KiB
JavaScript

"use strict";
// Tests for the webhook dispatch delivery-result contract and the truthful
// webhook test endpoint.
//
// Bug: dispatchDiscordWebhook swallowed every failure mode (Discord 4xx such
// as a deleted webhook's 404, Discord 429s, network failures, its own 1s
// dedupe) and returned undefined, so POST /api/settings/webhooks/test always
// answered ok:true — the admin's "Test" green-lit webhooks that would never
// deliver.
//
// Remediation contract locked here:
// - dispatchDiscordWebhook is no-throw and returns a delivery result
// ({ ok, reason, status?, retryAfterMs?, detail? }); fire-and-forget
// activity dispatches keep ignoring it, the test endpoint is built on it.
// - Every suppression/failure mode is observable: local_rate_limited (1s
// dedupe), discord_error (non-2xx non-429, incl. 404 deleted webhook),
// discord_rate_limited (429 + Retry-After), timeout, network_error,
// invalid_url, payload_too_large.
// - The result never carries the webhook URL/token or a fetch exception
// message (undici embeds the requested URL in some errors); Discord error
// bodies are read under hard bounds and only their sanitized `message`
// travels as `detail`.
// - The test route gates ok:true behind result.ok and answers honest
// statuses (429 dedupe/Discord 429, 502 upstream, 504 timeout) with the
// same token/security envelope as successes.
//
// index.js boots servers on require, so the webhook pipeline is sliced out
// of the source and evaluated in a vm sandbox (same technique as
// webhook-dispatch-hardening.test.js).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const INDEX_JS = path.join(__dirname, "..", "index.js");
const SETTINGS_JS = path.join(__dirname, "..", "public", "js", "settings.js");
const CANONICAL_URL = "https://discord.com/api/webhooks/123456789012345678/AbCdEf-gh_Ijklmnop";
const TOKEN = "AbCdEf-gh_Ijklmnop";
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}`);
}
// The shared activity-email masker (maskActivityEntryEmails and its
// maskPlannerEmailToLocalPart base) lives before the webhook slice in
// index.js; dispatchDiscordWebhook calls it at field-build time, so the real
// sources are prepended to the evaluated script (adpanel:activity-user-masking).
function maskerHelperSources(source) {
const start = source.indexOf("function maskPlannerEmailToLocalPart(value) {");
const end = source.indexOf("async function fetchPlannerItemsForServer(");
assert.ok(start !== -1 && end !== -1 && end > start, "masker helper region not found in index.js");
return source.slice(start, end);
}
function buildDispatchModule(fetchImpl) {
const source = fs.readFileSync(INDEX_JS, "utf8");
const slice = source.slice(
source.indexOf("const WEBHOOKS_CONFIG_PATH"),
endIndexOfFunction(source, "function dispatchWebhookForActivity")
);
for (const marker of [
"async function dispatchDiscordWebhook",
"function readDiscordErrorBody",
"function parseRetryAfterMs",
"function describeDiscordHttpError",
]) {
assert.ok(slice.includes(marker), `slice must contain ${marker}`);
}
const exposed = {};
const fetchCalls = [];
const logLines = [];
const sandbox = {
fs: { existsSync: () => false },
path,
__dirname: "/tmp",
console: {
log() { },
warn: (...args) => logLines.push(args.map(String).join(" ")),
error: (...args) => logLines.push(args.map(String).join(" ")),
debug() { },
},
setInterval: () => ({ unref() { } }),
setTimeout,
clearTimeout,
AbortController,
Buffer,
Date,
Set,
Map,
fetch: async (url, opts) => {
fetchCalls.push({ url, opts });
return fetchImpl(url, opts);
},
__exports: (obj) => Object.assign(exposed, obj),
};
const context = vm.createContext(sandbox);
// adpanel:activity-user-masking — dispatchDiscordWebhook routes the
// acting-user field and email-shaped details values through the ONE shared
// activity masker (maskActivityEntryEmails -> maskPlannerEmailToLocalPart),
// which lives BEFORE the webhook slice in index.js; the real sources are
// prepended and evaluated too so the sandbox runs shipped code, not a copy.
vm.runInContext(maskerHelperSources(source), context);
vm.runInContext(
`${slice}\n;__exports({ dispatchDiscordWebhook, dispatchWebhookForActivity, readDiscordErrorBody,`
+ ` parseRetryAfterMs, describeDiscordHttpError, validateDiscordWebhookUrl, webhookRateLimit,`
+ ` WEBHOOK_RATE_LIMIT_MS });`,
context,
{ filename: "webhook-dispatch-result-slice.js" }
);
return { exposed, fetchCalls, logLines, context };
}
// A Discord-style response mock. headers is a plain object; only present
// headers are served, mirroring real behavior.
function discordResponse({ status, body, headers = {} }) {
const bodyText = body === undefined ? "" : (typeof body === "string" ? body : JSON.stringify(body));
const fullHeaders = { ...headers };
if (bodyText.length > 0 && fullHeaders["content-length"] === undefined) {
fullHeaders["content-length"] = String(Buffer.byteLength(bodyText));
}
return {
ok: status >= 200 && status < 300,
status,
headers: { get: (name) => (name && fullHeaders[name.toLowerCase()] !== undefined ? fullHeaders[name.toLowerCase()] : null) },
text: async () => bodyText,
};
}
function freshDispatch(fetchImpl) {
const mod = buildDispatchModule(fetchImpl);
// Each test gets a clean 1s dedupe map and a configured single webhook, so
// routing resolves without the file layer (same trick as
// webhook-dispatch-hardening.test.js's overrideConfig).
mod.exposed.webhookRateLimit.clear();
vm.runInContext(
`loadWebhooksConfig = () => ({ mode: "single", fallbackToSingle: true, single: ${JSON.stringify(CANONICAL_URL)}, multiple: {} });`,
mod.context
);
return mod;
}
test("result contract: a 2xx delivery reports ok with the upstream status", async () => {
const { exposed, fetchCalls } = freshDispatch(() => discordResponse({ status: 204 }));
const result = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "server_create", { msg: "hi" }, "admin", "srv1");
assert.deepEqual(result, { ok: true, status: 204 });
assert.equal(fetchCalls.length, 1);
});
// adpanel:activity-user-masking — the OUTBOUND embed masks emails exactly like
// the activity READ endpoint (the ONE shared maskActivityEntryEmails helper):
// the acting-user field and any email-shaped details value carry the local
// part only; free-text values that merely CONTAIN an email are untouched, and
// sanitizeFieldValue's other behavior (mention stripping, caps) is preserved.
test("outbound embed masks the acting-user email and email-shaped details values to the local part", async () => {
const { exposed, fetchCalls } = freshDispatch(() => discordResponse({ status: 204 }));
const result = await exposed.dispatchDiscordWebhook(
CANONICAL_URL,
"perms_change",
{ target: "co.user@example.com", note: "path /srv/user@example.com/file", count: 3 },
"actor@panel.example",
"srv1"
);
assert.equal(result.ok, true);
assert.equal(fetchCalls.length, 1);
const fields = JSON.parse(fetchCalls[0].opts.body).embeds[0].fields;
const byName = Object.fromEntries(fields.map((f) => [f.name, f.value]));
assert.equal(byName.User, "actor", "the acting-user field must carry the LOCAL PART only — full emails are login identifiers and webhook recipients are co-users");
assert.equal(byName.target, "co.user", "an email-shaped details value must be masked like the read endpoint masks it");
assert.equal(byName.note, "path /srv/user@example.com/file", "free-text values that merely contain an email must pass through unchanged (anchored match)");
assert.equal(byName.count, "3", "non-string details values keep sanitizeFieldValue's serialization");
assert.ok(!JSON.stringify(fields).includes("panel.example"), "no full email domain may leak into the embed");
});
test("outbound embed omits the User field entirely when no actor is given (no 'unknown' ghost)", async () => {
const { exposed, fetchCalls } = freshDispatch(() => discordResponse({ status: 204 }));
await exposed.dispatchDiscordWebhook(CANONICAL_URL, "server_start", { msg: "hi" }, null, "srv1");
const fields = JSON.parse(fetchCalls[0].opts.body).embeds[0].fields;
assert.ok(!fields.some((f) => f.name === "User"), "an embed without an actor must not grow a masked 'unknown' User field");
assert.ok(fields.some((f) => f.name === "Server" && f.value === "srv1"), "the server field is untouched");
});
// adpanel:webhook-markdown-link-injection — the planner create/update activity
// records put the item's TITLE into the details, and the embed renders field
// values as markdown. A planner-title-shaped link must land in the actual
// outbound payload as non-clickable plain text (the title detail composes with
// the email masking: maskActivityEntryEmails first, then sanitizeFieldValue).
test("outbound embed renders a planner-title-shaped markdown link as non-clickable plain text", async () => {
const { exposed, fetchCalls } = freshDispatch(() => discordResponse({ status: 204 }));
const result = await exposed.dispatchDiscordWebhook(
CANONICAL_URL,
"planner_item_create",
{ itemId: 41, title: "[Server compromised — verify now](https://evil.example)" },
"planner@panel.example",
"srv1"
);
assert.equal(result.ok, true);
assert.equal(fetchCalls.length, 1);
const fields = JSON.parse(fetchCalls[0].opts.body).embeds[0].fields;
const titleField = fields.find((f) => f.name === "title");
assert.ok(titleField, "the title detail must reach the embed as a field");
assert.equal(
titleField.value,
"Server compromised — verify now (link: https://evil.example)",
"the field value must be the link text plus the url as plain text — never a clickable markdown link inside the trusted embed"
);
assert.ok(!JSON.stringify(fields).includes("]("), "no markdown link syntax may survive anywhere in the embed fields");
});
// adpanel:webhook-markdown-link-injection — nested-bracket link text renders
// as a live CommonMark/Discord link too (balanced nested brackets are part of
// the link text): the REAL dispatch path must emit a doubly-bracketed planner
// title neutralized, and a shape deeper than the pattern's one nesting level
// must still be caught by the final substring defuse — the whole embed stays
// ]( -free at any bracket-nesting depth.
test("outbound embed defuses nested-bracket link text through the real dispatch path", async () => {
const { exposed, fetchCalls } = freshDispatch(() => discordResponse({ status: 204 }));
const result = await exposed.dispatchDiscordWebhook(
CANONICAL_URL,
"planner_item_create",
{
title: "[[Server compromised — verify now]](https://evil.example)",
deep: "[a [b [c]]](https://evil.example)",
},
"planner@panel.example",
"srv2"
);
assert.equal(result.ok, true);
assert.equal(fetchCalls.length, 1);
const fields = JSON.parse(fetchCalls[0].opts.body).embeds[0].fields;
const byName = Object.fromEntries(fields.map((f) => [f.name, f.value]));
assert.equal(
byName.title,
"[Server compromised — verify now] (link: https://evil.example)",
"a doubly-bracketed label (balanced nesting is part of the link text) must reach the embed neutralized, not clickable"
);
assert.equal(
byName.deep,
"[a [b [c]]] (https://evil.example)",
"a shape deeper than the pattern's one nesting level must be defused by the final substring break"
);
const payload = JSON.stringify(fields);
assert.ok(!payload.includes("]("), "no ]( adjacency may survive anywhere in the emitted embed JSON");
for (const f of fields) {
assert.ok(!/\[[^\[\]]*\]\(/.test(f.value), `field ${f.name} must contain no markdown label-destination sequence`);
}
});
test("result contract: a deleted webhook (Discord 404) is reported as discord_error with Discord's message — and never with the URL/token", async () => {
const { exposed, fetchCalls } = freshDispatch(() => discordResponse({
status: 404,
body: { message: "Unknown Webhook", code: 10015 },
}));
const result = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "Webhook test from ADPanel" }, "admin", "test");
assert.equal(result.ok, false);
assert.equal(result.reason, "discord_error");
assert.equal(result.status, 404);
assert.equal(result.detail, "Unknown Webhook");
const serialized = JSON.stringify(result);
assert.ok(!serialized.includes(TOKEN), "the webhook token must never appear in the result");
assert.ok(!serialized.includes(CANONICAL_URL), "the webhook URL must never appear in the result");
assert.equal(fetchCalls.length, 1);
});
test("result contract: Discord 429 reports discord_rate_limited with the header Retry-After", async () => {
const { exposed } = freshDispatch(() => discordResponse({
status: 429,
headers: { "retry-after": "1.5" },
body: { retry_after: 2, global: false, message: "You are being rate limited.", code: 0 },
}));
const result = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "x" }, "admin", "test");
assert.equal(result.ok, false);
assert.equal(result.reason, "discord_rate_limited");
assert.equal(result.status, 429);
assert.equal(result.retryAfterMs, 1500, "the Retry-After header must win over the body value");
assert.equal(result.detail, "You are being rate limited.");
});
test("result contract: Discord 429 falls back to the body retry_after when the header is missing", async () => {
const { exposed } = freshDispatch(() => discordResponse({
status: 429,
body: { retry_after: 0.4, message: "You are being rate limited." },
}));
const result = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "x" }, "admin", "test");
assert.equal(result.reason, "discord_rate_limited");
assert.equal(result.retryAfterMs, 400);
});
test("result contract: 429 without any retry info falls back to a conservative 5s", async () => {
const { exposed } = freshDispatch(() => discordResponse({ status: 429, body: "" }));
const result = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "x" }, "admin", "test");
assert.equal(result.reason, "discord_rate_limited");
assert.equal(result.retryAfterMs, 5000);
});
test("result contract: 401 from a revoked webhook reports discord_error with the credential wording", async () => {
const { exposed } = freshDispatch(() => discordResponse({
status: 401,
body: { message: "Unauthorized", code: 0 },
}));
const result = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "x" }, "admin", "test");
assert.equal(result.reason, "discord_error");
assert.equal(result.status, 401);
assert.equal(result.detail, "Unauthorized");
});
test("result contract: a network failure reports network_error and never echoes the exception message", async () => {
// undici embeds the requested URL in some of its error strings — simulate
// the worst case where the exception message carries the secret token.
const { exposed } = freshDispatch(async () => {
throw new Error(`fetch failed ${CANONICAL_URL}`);
});
const result = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "x" }, "admin", "test");
assert.equal(result.ok, false);
assert.equal(result.reason, "network_error");
assert.equal(result.detail, undefined);
const serialized = JSON.stringify(result);
assert.ok(!serialized.includes(TOKEN), "the token from the exception message must never reach the result");
assert.ok(!serialized.includes(CANONICAL_URL), "the URL from the exception message must never reach the result");
});
test("result contract: an aborted fetch reports timeout", async () => {
const { exposed } = freshDispatch(async () => {
const err = new Error("The operation was aborted");
err.name = "AbortError";
throw err;
});
const result = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "x" }, "admin", "test");
assert.equal(result.reason, "timeout");
});
test("result contract: undici's ABORT_ERR code is also classified as timeout", async () => {
const { exposed } = freshDispatch(async () => {
const err = new Error("The operation was aborted");
err.code = "ABORT_ERR";
throw err;
});
const result = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "x" }, "admin", "test");
assert.equal(result.reason, "timeout");
});
test("result contract: the 1s dedupe reports local_rate_limited instead of pretending to send", async () => {
const { exposed, fetchCalls } = freshDispatch(() => discordResponse({ status: 204 }));
const first = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "x" }, "admin", "test");
const second = await exposed.dispatchDiscordWebhook(CANONICAL_URL, "test", { message: "x" }, "admin", "test");
assert.equal(first.ok, true);
assert.equal(second.ok, false);
assert.equal(second.reason, "local_rate_limited");
assert.ok(second.retryAfterMs >= 1 && second.retryAfterMs <= exposed.WEBHOOK_RATE_LIMIT_MS,
"retryAfterMs must be the remaining dedupe window");
assert.equal(fetchCalls.length, 1, "the deduped dispatch must not reach the network");
});
test("result contract: an invalid URL is blocked as invalid_url with no network call", async () => {
const { exposed, fetchCalls } = freshDispatch(() => discordResponse({ status: 204 }));
const result = await exposed.dispatchDiscordWebhook("https://evil.example/api/webhooks/123/token", "test", { message: "x" }, "admin", "test");
assert.equal(result.ok, false);
assert.equal(result.reason, "invalid_url");
assert.equal(fetchCalls.length, 0);
});
test("result contract: fire-and-forget activity dispatch keeps working unchanged (no throw, logged failures)", async () => {
const { exposed, fetchCalls, logLines } = freshDispatch(() => discordResponse({
status: 404,
body: { message: "Unknown Webhook", code: 10015 },
}));
// Must not throw synchronously nor produce an unhandled rejection.
await exposed.dispatchWebhookForActivity("server_create", { msg: "hi" }, "admin", "srv1");
await new Promise((resolve) => setImmediate(resolve));
assert.equal(fetchCalls.length, 1);
assert.ok(logLines.some((line) => line.includes("404")), "failures must still be logged server-side");
assert.ok(logLines.every((line) => !line.includes(TOKEN)), "logs must never contain the webhook token");
});
test("readDiscordErrorBody: control characters are stripped and the message is capped at 200 chars", async () => {
const { exposed } = freshDispatch(() => discordResponse({ status: 400 }));
const hostile = `A${"\n".repeat(50)}B${"x".repeat(300)}`;
const parsed = await exposed.readDiscordErrorBody(discordResponse({
status: 400,
body: { message: hostile, code: 50035 },
}));
assert.equal(parsed.code, 50035);
assert.ok(!parsed.message.includes("\n"), "control chars must be stripped (log/response injection)");
assert.ok(parsed.message.length <= 200);
assert.equal(parsed.message[0], "A");
assert.ok(parsed.message.includes("B"), "content after the stripped run must survive");
});
test("readDiscordErrorBody: non-JSON (e.g. Cloudflare HTML) degrades to {}", async () => {
const { exposed } = freshDispatch(() => discordResponse({ status: 429, body: "<html>blocked</html>" }));
const parsed = await exposed.readDiscordErrorBody(discordResponse({ status: 429, body: "<html>blocked</html>" }));
assert.deepEqual(parsed, {});
});
test("readDiscordErrorBody: a missing or oversized content-length skips the body read entirely", async () => {
let textCalled = 0;
const { exposed } = freshDispatch(() => discordResponse({ status: 500 }));
const mkRes = (lenHeader) => ({
ok: false,
status: 500,
headers: { get: (name) => (name === "content-length" ? lenHeader : null) },
text: async () => { textCalled += 1; return '{"message":"secret-ish"}'; },
});
assert.deepEqual(await exposed.readDiscordErrorBody(mkRes(null)), {});
assert.deepEqual(await exposed.readDiscordErrorBody(mkRes("999999")), {});
assert.equal(textCalled, 0, "the body must not be read when the size cannot be bounded");
});
test("parseRetryAfterMs: header wins, body fills in, garbage falls back to 5s, values are clamped", async () => {
const { exposed } = freshDispatch(() => discordResponse({ status: 429 }));
const p = exposed.parseRetryAfterMs;
// The second parameter is already milliseconds (readDiscordErrorBody converts
// Discord's seconds-based retry_after).
assert.equal(p("2", 400), 2000);
assert.equal(p("abc", 400), 400);
assert.equal(p(null, 250), 250);
assert.equal(p(null, null), 5000);
assert.equal(p("", null), 5000);
assert.equal(p(" ", null), 5000);
assert.equal(p("-3", null), 5000, "negative headers fall through to the default");
assert.equal(p("99999", null), 3600000, "absurd values are clamped to 1h");
assert.equal(p(null, -1), 5000);
assert.equal(p(null, 7200000), 3600000, "absurd body values are clamped to 1h");
});
test("describeDiscordHttpError: 404/401 wordings are actionable and detail is appended, never substituted", async () => {
const { exposed } = freshDispatch(() => discordResponse({ status: 404 }));
const d = exposed.describeDiscordHttpError;
assert.match(d(404, null), /no longer exists/);
assert.match(d(404, "Unknown Webhook"), /no longer exists/);
assert.match(d(404, "Unknown Webhook"), /Discord said: "Unknown Webhook"/);
assert.match(d(401, null), /credentials/);
assert.match(d(403, null), /credentials/);
assert.match(d(500, null), /HTTP 500/);
});
test("route contract: the test endpoint gates ok:true behind the dispatch result and answers honest statuses", () => {
const source = fs.readFileSync(INDEX_JS, "utf8");
const start = source.indexOf('app.post("/api/settings/webhooks/test"');
const end = source.indexOf('app.get("/api/settings/alert"', start);
const handler = source.slice(start, end);
assert.match(handler, /const result = await dispatchDiscordWebhook\(webhookUrl/,
"the endpoint must await and use the delivery result");
assert.ok(handler.indexOf("if (result && result.ok)") < handler.indexOf("ok: true"),
"the ok:true response must sit behind the result.ok gate");
for (const reason of ["local_rate_limited", "discord_rate_limited", "discord_error", "timeout", "network_error"]) {
assert.ok(handler.includes(`reason === "${reason}"`), `the ${reason} outcome must be handled explicitly`);
}
assert.ok(handler.includes('status(429)'), "both rate-limit outcomes must answer 429");
assert.ok(handler.includes('status(502)'), "upstream rejections must answer 502");
assert.ok(handler.includes('status(504)'), "timeouts must answer 504");
assert.ok(handler.includes("describeDiscordHttpError(result.status, result.detail)"),
"404/401-style upstream rejections must use the safe status mapping");
assert.ok(!handler.includes("${webhookUrl"), "the webhook URL must never be interpolated into any response string");
assert.ok(handler.includes("{ ok: false, error: \"Failed to send test\" }"),
"even the defensive catch must answer with ok:false");
});
test("frontend contract: the settings UI renders the backend's error text for failed tests", () => {
const settingsJs = fs.readFileSync(SETTINGS_JS, "utf8");
assert.ok(settingsJs.includes("data.ok ? 'Test message sent!' : (data.error || 'Failed')"),
"the test button must show the backend error instead of a success toast");
assert.match(settingsJs, /escapeHtml\(msg\)/, "toast messages must be HTML-escaped");
});