Files
Kelx/tests/csp-hardening.test.js
2026-11-30 16:32:37 +00:00

304 lines
12 KiB
JavaScript

"use strict";
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 indexSource = fs.readFileSync(INDEX_JS, "utf8");
// Allowed immutable, version-pinned jsDelivr script prefixes (trailing slash = directory prefix).
// Monaco is no longer here: it is self-hosted under public/vendor/monaco-editor
// (sha512-verified against the npm registry) and covered by script-src 'self'.
const ALLOWED_JSDELIVR_PATHS = [
"https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/",
];
// Extract the array literal body of a `name: [` ... `]` directive, robust to whitespace.
function extractDirectiveArray(source, name) {
const marker = new RegExp(`${name}\\s*:\\s*\\[`);
const match = marker.exec(source);
assert.ok(match, `directive ${name} not found in index.js`);
const bodyStart = match.index + match[0].length;
let depth = 1;
let end = -1;
for (let i = bodyStart; i < source.length; i += 1) {
if (source[i] === "[") depth += 1;
else if (source[i] === "]") {
depth -= 1;
if (depth === 0) {
end = i;
break;
}
}
}
assert.ok(end > bodyStart, `unbalanced brackets in directive ${name}`);
return source.slice(bodyStart, end);
}
// Pull the quoted string tokens out of the directive body (skips comments, commas, whitespace,
// and non-string entries such as the nonce function's identifiers).
function extractSources(body) {
const tokenRe = /"([^"]*)"|'([^']*)'|`([^`]*)`/g;
const sources = [];
let m;
while ((m = tokenRe.exec(body)) !== null) {
const value = m[1] !== undefined ? m[1] : m[2] !== undefined ? m[2] : m[3];
if (value && value.trim().length > 0) sources.push(value.trim());
}
return sources;
}
const scriptSrcBody = extractDirectiveArray(indexSource, "scriptSrc");
const scriptSources = extractSources(scriptSrcBody);
const styleSrcBody = extractDirectiveArray(indexSource, "styleSrc");
const styleSources = extractSources(styleSrcBody);
const styleSrcAttrBody = extractDirectiveArray(indexSource, "styleSrcAttr");
const styleSrcAttrSources = extractSources(styleSrcAttrBody);
test("CSP hardening: scriptSrc excludes broad cdnjs.cloudflare.com host", () => {
for (const source of scriptSources) {
assert.ok(
source !== "https://cdnjs.cloudflare.com" && !source.startsWith("https://cdnjs.cloudflare.com/"),
`scriptSrc must not allow cdnjs.cloudflare.com, found: ${source}`
);
}
});
test("CSP hardening: scriptSrc excludes bare cdnjs.cloudflare.com anywhere in the directive", () => {
assert.ok(
!scriptSrcBody.includes("cdnjs.cloudflare.com"),
"scriptSrc directive body must not reference cdnjs.cloudflare.com at all"
);
});
// adpanel:auth-csp-no-cdnjs — the auth-page CSP builder (buildAuthPageCsp) must
// never allow a third-party style or font origin. The login and forgot-password
// pages load all CSS and icon fonts same-origin (views/login.ejs), and an
// unused allowance for a documented CSP-bypass host like cdnjs.cloudflare.com
// is pure attack surface for the next markup-injection bug. The GLOBAL helmet
// config further down intentionally keeps cdnjs for the non-auth pages that
// still load FontAwesome from it — this pin covers ONLY the auth-page builder.
// Like login-dead-assets.test.js: strip line comments so the builder's own
// adpanel: comment (which names the removed option/host for auditor
// greppability) does not trip the ban.
function extractFunctionSource(source, signature) {
const start = source.indexOf(signature);
assert.ok(start >= 0, `${signature} not found`);
assert.strictEqual(
source.indexOf(signature, start + 1),
-1,
`${signature} must appear exactly once in index.js`
);
let depth = 0;
for (let i = start + signature.length - 1; i < source.length; i += 1) {
if (source[i] === "{") depth += 1;
else if (source[i] === "}") {
depth -= 1;
if (depth === 0) return source.slice(start, i + 1);
}
}
assert.fail(`unbalanced braces after ${signature}`);
}
const buildAuthPageCspSource = extractFunctionSource(
indexSource,
"function buildAuthPageCsp(req, res, options = {}) {"
);
const buildAuthPageCspCode = buildAuthPageCspSource.replace(/^[ \t]*\/\/.*$/gm, "");
test("CSP hardening: auth-page styleSrc/fontSrc never allow cdnjs.cloudflare.com", () => {
assert.ok(
!buildAuthPageCspCode.includes("cdnjs.cloudflare.com"),
"buildAuthPageCsp must not allow cdnjs.cloudflare.com in ANY directive it emits (style-src, font-src, script-src, ...): auth pages load no third-party styles or fonts"
);
assert.ok(
buildAuthPageCspCode.includes(`const styleSrc = ["'self'", nonce];`),
"the auth-page styleSrc must stay 'self' + nonce only (no third-party style origin)"
);
assert.ok(
buildAuthPageCspCode.includes(`const fontSrc = ["'self'", "data:"];`),
"the auth-page fontSrc must stay 'self' + data: only (no third-party font origin)"
);
});
test("CSP hardening: the dead includeFontAwesome option stays removed from the auth-page builder", () => {
const codeWithoutComments = indexSource.replace(/^[ \t]*\/\/.*$/gm, "");
assert.ok(
!codeWithoutComments.includes("includeFontAwesome"),
"includeFontAwesome was removed as a dead option (its cdnjs pushes were unused: the login page loads FontAwesome same-origin); do not reintroduce it"
);
});
test("CSP hardening: scriptSrc allows only the pinned jsDelivr paths, never the bare host", () => {
for (const source of scriptSources) {
if (source === "https://cdn.jsdelivr.net") {
assert.fail("scriptSrc must not allow the bare https://cdn.jsdelivr.net host");
}
if (source.startsWith("https://cdn.jsdelivr.net/") && !ALLOWED_JSDELIVR_PATHS.includes(source)) {
assert.fail(
`scriptSrc contains non-pinned jsDelivr path: ${source}; only ${ALLOWED_JSDELIVR_PATHS.join(", ")} are allowed`
);
}
}
});
test("CSP hardening: scriptSrc retains self and the pinned editor CDN paths only", () => {
assert.ok(scriptSources.includes("'self'"), "scriptSrc must keep 'self'");
for (const allowed of ALLOWED_JSDELIVR_PATHS) {
assert.ok(
scriptSources.includes(allowed),
`scriptSrc must include pinned path ${allowed}`
);
}
assert.ok(
!scriptSources.some((s) => s.includes("monaco-editor")),
"scriptSrc must not allow the Monaco CDN path: Monaco is self-hosted under /vendor/monaco-editor"
);
});
test("CSP hardening: styleSrc excludes 'unsafe-inline' (inline styles are nonce-gated)", () => {
assert.ok(
!styleSources.includes("'unsafe-inline'"),
"styleSrc must not allow 'unsafe-inline'"
);
assert.ok(
!styleSrcBody.includes("'unsafe-inline'"),
"styleSrc directive body must not reference 'unsafe-inline' at all"
);
});
test("CSP hardening: styleSrc includes the per-request nonce source", () => {
assert.ok(
styleSrcBody.includes("nonce-${res.locals.cspNonce}"),
"styleSrc must include the nonce function (req, res) => `nonce-${res.locals.cspNonce}`"
);
assert.ok(
styleSources.includes("'nonce-${res.locals.cspNonce}'"),
"styleSrc token list must include the nonce source value"
);
});
test("CSP hardening: styleSrcAttr keeps 'unsafe-inline' for style= attributes", () => {
assert.ok(
styleSrcAttrSources.includes("'unsafe-inline'"),
"styleSrcAttr must keep 'unsafe-inline': templates and client JS rely on 600+ style attributes"
);
});
test("CSP hardening: every <style> tag in views/*.ejs carries a nonce attribute", () => {
const viewsDir = path.join(ROOT, "views");
const viewFiles = fs.readdirSync(viewsDir).filter((f) => f.endsWith(".ejs"));
assert.ok(viewFiles.length > 0, "expected at least one view template");
const openTagRe = /<style[^>]*>/g;
for (const file of viewFiles) {
const content = fs.readFileSync(path.join(viewsDir, file), "utf8");
const tags = content.match(openTagRe) || [];
for (const tag of tags) {
assert.ok(
/nonce=/.test(tag),
`${file} has a <style> opening tag without a nonce attribute: ${tag}`
);
}
}
});
// adpanel:captcha-csp-scoping — the captcha provider hosts are known CSP-bypass
// hosts and only the pre-auth login page renders a captcha widget (that page
// builds its own provider-scoped CSP via buildAuthPageCsp). The GLOBAL helmet
// config must therefore carry them ONLY as per-request conditional entries
// (utils/captcha-csp-origins.js, scoped to the live configured provider), never
// as static entries allowed on every authenticated page regardless of provider.
const CAPTCHA_CSP_HOSTS = [
"https://challenges.cloudflare.com",
"https://www.google.com",
"https://www.gstatic.com",
"https://hcaptcha.com",
"https://*.hcaptcha.com",
];
// The expected conditional entries per global directive, mirroring
// buildAuthPageCsp's per-provider pushes exactly.
const EXPECTED_CAPTCHA_CONDITIONAL_ENTRIES = {
scriptSrc: CAPTCHA_CSP_HOSTS,
styleSrc: ["https://hcaptcha.com", "https://*.hcaptcha.com"],
connectSrc: [
"https://www.google.com",
"https://www.gstatic.com",
"https://challenges.cloudflare.com",
"https://hcaptcha.com",
"https://*.hcaptcha.com",
],
frameSrc: CAPTCHA_CSP_HOSTS,
};
// The GLOBAL helmet config is the region from `contentSecurityPolicy: {` to its
// matching closing brace. Directive-name extraction must run INSIDE this slice:
// a naive whole-file `frameSrc\s*:\s*\[` search would first hit the ternary in
// buildContentSecurityPolicy's auth-page mapping (`frameSrc : ["'none'"]`).
function extractHelmetCspSource(source) {
const marker = "contentSecurityPolicy: {";
const start = source.indexOf(marker);
assert.ok(start >= 0, "the global helmet contentSecurityPolicy config must exist in index.js");
let depth = 0;
let end = -1;
for (let i = start + marker.length - 1; i < source.length; i += 1) {
if (source[i] === "{") depth += 1;
else if (source[i] === "}") {
depth -= 1;
if (depth === 0) {
end = i;
break;
}
}
}
assert.ok(end > start, "unbalanced braces in the helmet contentSecurityPolicy config");
return source.slice(start, end);
}
const helmetCspSource = extractHelmetCspSource(indexSource);
test("CSP hardening: captcha hosts in the global config are only conditional provider-scoped entries", () => {
for (const [directive, expectedHosts] of Object.entries(EXPECTED_CAPTCHA_CONDITIONAL_ENTRIES)) {
const body = extractDirectiveArray(helmetCspSource, directive);
const stripped = body.replace(/captchaCsp\.cspOrigin\(\s*"[a-z]+"\s*,\s*"[^"]*"\s*\)/g, "");
for (const host of CAPTCHA_CSP_HOSTS) {
assert.ok(
!stripped.includes(host),
`${directive} must not carry ${host} as an unconditional static entry`
);
}
for (const host of expectedHosts) {
assert.ok(
body.includes(`captchaCsp.cspOrigin("${directive.replace(/Src$/, "").toLowerCase()}", "${host}")`),
`${directive} must keep the conditional entry for ${host}`
);
}
assert.ok(
body.includes("captchaCsp.cspOrigin("),
`${directive} must wire the shared captcha-csp-origins source`
);
}
assert.ok(
indexSource.includes('require("./utils/captcha-csp-origins")'),
"index.js must require the shared captcha-csp-origins module (no inline copies)"
);
});
test("CSP hardening: scriptSrc and styleSrc keep the per-request nonce functions", () => {
assert.ok(
scriptSrcBody.includes("nonce-${res.locals.cspNonce}"),
"scriptSrc must keep the nonce directive function"
);
assert.ok(
styleSrcBody.includes("nonce-${res.locals.cspNonce}"),
"styleSrc must keep the nonce directive function"
);
});