Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+302
View File
@@ -0,0 +1,302 @@
"use strict";
// Tests for the webhook config step-up hardening (audit finding: "webhook
// audit-suppression requires no step-up").
//
// POST /api/settings/webhooks used to fire requireDestructiveActionStepUp only
// when the payload carried a URL (hasUrl). A bare { mode: "multiple",
// fallbackToSingle: false } — or any mode flip — from a hijacked admin session
// therefore re-routed dispatching with no re-verification: in strict isolation
// (multiple mode, fallback off, no category webhook for an event) events stop
// reaching the admin's Discord entirely, which is silent out-of-band log
// suppression stageable right before doing something noisy. The DELETE and
// test endpoints already stepped up unconditionally; the POST's hasUrl
// condition was the gap.
//
// The contract now locked here:
// - POST requires step-up for EVERY config-affecting payload (URL, mode,
// fallback), via the same grace-eligible unscoped grant as before —
// validation and the admin check still run first so a malformed or
// unauthorized request burns neither a grace use nor credential budget.
// - The step-up subject distinguishes the payload shapes for the security
// log / grace-grant record.
// - Both write routes log an out-of-band [SECURITY] console line after a
// durable save: the in-panel activity entry and the Discord announcement
// travel through the pipeline a config change can re-route; the server
// console is the one channel a hijacked browser session cannot suppress.
// - settings.js routes the mode/fallback toggles through
// sendGuardedRequestWithStepUp (grace rides silently, a challenge opens
// the shared verification modal), with the same one-shot token
// refresh+retry contract as the test/delete flows.
//
// index.js boots servers on require, so route-level behavior is locked with
// source assertions (same technique as webhook-dispatch-hardening.test.js /
// audit-p32-p41-p42.test.js).
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 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 settingsJsSource = fs.readFileSync(SETTINGS_JS, "utf8");
const settingsEjsSource = fs.readFileSync(SETTINGS_EJS, "utf8");
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}`);
}
const postStart = indexSource.indexOf('app.post("/api/settings/webhooks"');
assert.ok(postStart >= 0, "webhook POST route must exist");
const postEnd = endIndexOfFunction(indexSource.slice(postStart), "async (req, res) => {") + postStart;
const post = indexSource.slice(postStart, postEnd);
const deleteStart = indexSource.indexOf('app.delete("/api/settings/webhooks"');
assert.ok(deleteStart >= 0, "webhook DELETE route must exist");
const deleteEnd = indexSource.indexOf('app.post("/api/settings/webhooks/test"', deleteStart);
assert.ok(deleteEnd > deleteStart, "webhook DELETE handler slice must be bounded");
const del = indexSource.slice(deleteStart, deleteEnd);
// ---------------------------------------------------------------------------
// POST — step-up is unconditional
// ---------------------------------------------------------------------------
test("webhook POST: the hasUrl conditional step-up is gone, every payload verifies", () => {
// The old shape: a fake-ok stepUp initialized from the (possibly absent)
// grace state, replaced by a real verification only when a URL was present.
assert.ok(
!post.includes("let stepUp = { ok: true"),
"the fake-ok stepUp initialization must not come back"
);
// The pre-flight guard sweep hoisted the step-up result: `let stepUp = null;`
// is declared above the guard try and assigned by a bare `stepUp = await ...`
// inside it (mechanically required — the response snapshot below the guard
// reads stepUp.graceExpiresAt, and Express 4 does not catch async-handler
// rejections). The intent is unchanged: the step-up must always run for every
// config-affecting payload and must never be skipped or assigned
// conditionally. The needle now checks that shape: exactly one assignment,
// inside the guard try, still followed by the !stepUp.ok gate, and no other
// `stepUp =` anywhere in the handler (an if/else assignment would resurrect
// the hasUrl bug).
const stepUpAssign = "stepUp = await requireDestructiveActionStepUp(req, res, currentUser, stepUpSubject);";
assert.equal(
post.split(stepUpAssign).length - 1, 1,
"step-up must run unconditionally for every config-affecting payload (exactly one assignment)"
);
const stepUpAssignAt = post.indexOf(stepUpAssign);
const guardCatchAt = post.indexOf("} catch (err) {");
assert.ok(
stepUpAssignAt >= 0 && guardCatchAt > stepUpAssignAt,
"the step-up assignment must sit inside the pre-flight guard try"
);
assert.ok(
post.slice(stepUpAssignAt).includes("if (!stepUp.ok) return;"),
"the step-up result must still gate the handler before any mutation"
);
assert.equal(
(post.match(/stepUp\s*=(?!=)/g) || []).length, 2,
"the only stepUp '=' occurrences must be the sweep's hoisted declaration and the single unconditional assignment"
);
});
test("webhook POST: step-up subject distinguishes mode, fallback and URL payloads", () => {
assert.ok(post.includes('"Webhook set"'), "plain URL-set subject must be preserved");
assert.ok(post.includes('`Webhook set "${category}"`'), "per-category URL-set subject must be preserved");
assert.ok(post.includes('"Webhook mode switch"'), "a mode-only change needs its own subject");
assert.ok(post.includes('"Webhook fallback update"'), "a fallback-only change needs its own subject");
assert.ok(post.includes('"Webhook mode & fallback update"'), "a combined change needs its own subject");
});
test("webhook POST: ordering — validation and admin check before step-up, step-up before the write lock", () => {
const validationAt = post.indexOf('"Missing mode, webhook URL, or fallbackToSingle"');
const adminAt = post.indexOf("if (!currentUser || !currentUser.admin)");
const stepUpAt = post.indexOf("requireDestructiveActionStepUp");
const lockAt = post.indexOf("withWebhooksConfigWriteLock(");
assert.ok(validationAt >= 0 && adminAt >= 0 && stepUpAt >= 0 && lockAt >= 0,
"all ordering anchors must be present");
assert.ok(stepUpAt > validationAt,
"a malformed payload must be answered 400 before it can burn a grace use or credential budget");
assert.ok(stepUpAt > adminAt,
"the admin check must precede the step-up so non-admins learn nothing about the verification");
assert.ok(lockAt > stepUpAt,
"the config write lock must be taken after the step-up awaits so the critical section stays synchronous");
});
test("webhook POST: the step-up grant stays unscoped and grace-eligible", () => {
// No scopeKey and no options object: settings saves share the unscoped
// grant pool (getDestructiveActionGraceScopeHash returns "" for an empty
// key), so a grant minted by any fresh verification covers the settings
// workflow, while grants bound to a user/node/server target never do.
const callAt = post.indexOf("requireDestructiveActionStepUp(req, res, currentUser, stepUpSubject)");
assert.ok(callAt >= 0, "the unconditional call must pass the subject and nothing else");
assert.equal(
post.slice(callAt).indexOf("requireDestructiveActionStepUp(req, res, currentUser, stepUpSubject,"),
-1,
"the call must not grow an options object (no scopeKey, no allowGrace/persistGrant overrides)"
);
});
test("webhook POST: the success payload still carries the grace window", () => {
const payloadAt = post.indexOf("graceExpiresAt: stepUp.graceExpiresAt");
assert.ok(payloadAt >= 0, "the success payload must report graceExpiresAt from the step-up result");
assert.ok(payloadAt > post.indexOf("withWebhooksConfigWriteLock("),
"the grace report belongs to the success payload, not the pre-lock path");
});
// ---------------------------------------------------------------------------
// Out-of-band forensic trail (both write routes)
// ---------------------------------------------------------------------------
test("webhook POST: a [SECURITY] console line records the change after a durable save", () => {
const logMarker = "[SECURITY] Webhook configuration changed";
const logAt = post.indexOf(logMarker);
assert.ok(logAt >= 0, "the POST route must emit the out-of-band security log");
const notSavedAt = post.indexOf("if (!saved)");
assert.ok(notSavedAt >= 0 && logAt > notSavedAt,
"the log must sit behind the !saved gate: a failed save must not be logged as a change");
const logLine = post.slice(logAt, post.indexOf("\n", logAt));
assert.ok(/User: \$\{stripLogControlChars\(userEmail\)\}/.test(logLine), "the log must name the acting admin (identity stripped via adpanel:log-email-control-chars)");
assert.ok(/Change: \$\{webhookChangeDesc\}/.test(logLine), "the log must name the change");
assert.ok(/IP: \$\{getRequestIp\(req\)\}/.test(logLine), "the log must record the source IP");
});
test("webhook POST: the change description covers every payload shape for both audit surfaces", () => {
// recordActivity (in-panel) and the console log share webhookChangeDesc, so
// both surfaces always describe the same change.
assert.ok(post.includes("set_category:${category}"), "category URL changes must be described");
assert.ok(post.includes('"set_single"'), "single URL changes must be described");
assert.ok(post.includes("mode:${mode}"), "mode changes must be described");
assert.ok(post.includes("fallback_to_single:${fallbackToSingle}"), "fallback changes must be described");
});
test("webhook DELETE: unconditional step-up preserved, matching [SECURITY] log added", () => {
const stepUpAt = del.indexOf('requireDestructiveActionStepUp(req, res, currentUser, category ? `Webhook delete "${category}"` : "Webhook delete")');
assert.ok(stepUpAt >= 0, "the DELETE route must keep its unconditional step-up");
assert.ok(del.indexOf("if (!stepUp.ok) return;") > stepUpAt,
"the DELETE step-up result must gate the mutation");
const logMarker = "[SECURITY] Webhook configuration changed";
const logAt = del.indexOf(logMarker);
assert.ok(logAt >= 0, "the DELETE route must emit the out-of-band security log");
const notSavedAt = del.indexOf("if (!saved)");
assert.ok(notSavedAt >= 0 && logAt > notSavedAt,
"the DELETE log must sit behind the !saved gate");
const logLine = del.slice(logAt, del.indexOf("\n", logAt));
assert.ok(/Change: delete:\$\{deleteTarget\}/.test(logLine),
"the DELETE log must name the removed target");
});
// ---------------------------------------------------------------------------
// Frontend — settings.js routes the toggles through the guarded flow
// ---------------------------------------------------------------------------
test("settings.js: sendWebhookSaveWithGuards exists with the token + refresh-retry contract", () => {
assert.ok(settingsJsSource.includes("async function sendWebhookSaveWithGuards(body)"),
"the guarded save wrapper must exist");
const start = settingsJsSource.indexOf("async function sendWebhookSaveWithGuards(body)");
const end = settingsJsSource.indexOf("async function sendWebhookTestWithGuards(body)");
assert.ok(end > start, "the helper slice must be bounded");
const helper = settingsJsSource.slice(start, end);
assert.ok(helper.includes("'x-action-token': webhookActionTokens.saveWebhook || ''"),
"the wrapper must send the saveWebhook action token");
assert.ok(helper.includes("/action token/i"),
"the wrapper must detect token rejections separately from step-up challenges");
assert.ok(helper.includes("await loadWebhooks();"),
"the token retry must refresh the settings (and thereby the tokens) first");
assert.ok(helper.includes("sendGuardedRequestWithStepUp('/api/settings/webhooks', 'POST', body, requestCopy())"),
"the wrapper must delegate the challenge/retry flow to the shared guarded sender");
assert.ok(helper.includes('subtitle: \'Verify your identity to change webhook settings\''),
"the challenge modal must explain what is being authorized");
});
test("settings.js: the webhook modal save performs exactly one token refresh+retry on a token rejection", () => {
// The modal save sends the same multi-use saveWebhook token (300s TTL) as
// the toggles. When the admin lingers on the page past the TTL the server
// answers 403 ACTION_TOKEN_INVALID — and because the action-token gate runs
// before requireDestructiveActionStepUp, the typed credential was never
// consumed, so resending the same body once with a refreshed token is safe.
const start = settingsJsSource.indexOf("if (webhookModalSave) {");
const end = settingsJsSource.indexOf("if (webhookDeleteClose)");
assert.ok(start >= 0, "the modal save handler slice must have a start marker");
assert.ok(end > start, "the modal save handler slice must be bounded by the delete-close marker");
const handler = settingsJsSource.slice(start, end);
assert.ok(
handler.includes("const tokenRejected = res.status === 403 && /action token/i.test(String(data?.error || ''));"),
"the modal save must detect token rejections separately from step-up challenges"
);
const tokenRejectedAt = handler.indexOf("const tokenRejected = res.status === 403");
const refreshAt = handler.indexOf("await loadWebhooks();", tokenRejectedAt);
assert.ok(tokenRejectedAt >= 0 && refreshAt > tokenRejectedAt,
"the token retry must refresh the settings (and thereby the tokens) after the rejection is detected");
assert.ok(
handler.includes("res = await fetch('/api/settings/webhooks', requestCopy());"),
"the retry must resend via requestCopy() so it picks up the refreshed token"
);
assert.ok(
handler.includes("if (webhookActionTokens.saveWebhook) {"),
"the retry must be guarded by the refreshed saveWebhook token being present"
);
assert.ok(
handler.includes("webhookModalError.textContent = data.error || 'Failed to save';"),
"the raw error must still surface when the retry also fails"
);
assert.ok(
handler.includes("toggleWebhookModal(false);"),
"the success path must still close the modal"
);
});
test("settings.js: mode and fallback toggles go through the guarded save, no session-only fetch remains", () => {
assert.ok(settingsJsSource.includes("sendWebhookSaveWithGuards({ mode: 'single' })"),
"the single-mode toggle must use the guarded save");
assert.ok(settingsJsSource.includes("sendWebhookSaveWithGuards({ mode: 'multiple' })"),
"the multiple-mode toggle must use the guarded save");
assert.ok(settingsJsSource.includes("sendWebhookSaveWithGuards({ fallbackToSingle: next })"),
"the fallback toggle must use the guarded save");
// The old bare-fetch payloads (session-only writes) must not come back.
assert.ok(!settingsJsSource.includes("JSON.stringify({ mode: 'single' })"),
"a bare session-only mode write must not return to settings.js");
assert.ok(!settingsJsSource.includes("JSON.stringify({ mode: 'multiple' })"),
"a bare session-only mode write must not return to settings.js");
assert.ok(!settingsJsSource.includes("JSON.stringify({ fallbackToSingle: next })"),
"a bare session-only fallback write must not return to settings.js");
});
test("settings.js: cancelled verification leaves the config untouched and says so", () => {
// Each toggle catches the helper's cancellation throw and returns silently
// (the modal already told the admin nothing was modified); network errors
// surface a toast.
const cancelCount = (settingsJsSource.match(/\/cancel\/i\.test\(String\(e\?\.message \|\| ''\)\)/g) || []).length;
assert.ok(cancelCount >= 3,
"the mode×2 and fallback toggles must all handle the cancellation throw");
assert.ok(settingsJsSource.includes("'Webhook change cancelled — nothing was modified.'"),
"the cancellation message must promise no change, matching server behavior");
});
test("settings.ejs: the cache-buster is bumped so browsers cannot keep the session-only UI", () => {
// A stale settings.js would send bare mode/fallback writes and surface the
// server's step-up challenge as a bare error toast. Fail-closed, but a
// confusing first contact — the served UI must know the guarded flow.
assert.ok(settingsEjsSource.includes('/js/settings.js?v=20261117-account-identity1'),
"views/settings.ejs must reference the updated settings.js version");
assert.ok(!settingsEjsSource.includes('/js/settings.js?v=20260927-adminstepup1'),
"the pre-identity bundle cache-buster must not remain");
assert.ok(!settingsEjsSource.includes('/js/settings.js?v=20260919-webhooktokenretry1'),
"the stale cache-buster must not remain");
});