Files
Kelx/scripts/verify-branding-asset-hardening.js
2026-11-30 16:32:37 +00:00

308 lines
14 KiB
JavaScript

// Verification harness for the audit section-2 remediation of the login
// background / branding asset pipeline ("POST /api/admin/login-background"):
// 1. SVG cannot pass any gate of the background pipeline — filename
// whitelist, URL extension whitelist, and magic-byte content validation
// (uses the REAL utils/branding.js functions the endpoint calls).
// 2. The explicit SVG URL rejection regex added to both branding endpoints
// matches path/query/fragment variants and never the allowed formats.
// 3. The single-flight + negative-cache logic added to
// loadBrandingRemoteAsset (exact copy) collapses N concurrent cache
// misses into ONE origin fetch, serves repeats from cache, and stops a
// remote outage from producing one origin fetch per request.
// 4. The brandingAssetRateLimiter config (exact copy) returns 429 past its
// budget and keeps independent buckets per source IP.
// Run: node scripts/verify-branding-asset-hardening.js
const assert = require("assert");
const express = require("express");
const http = require("http");
const { rateLimit } = require("express-rate-limit");
const branding = require("../utils/branding.js");
let checks = 0;
function ok(name, cond) {
assert.ok(cond, `FAILED: ${name}`);
checks += 1;
console.log(` ok - ${name}`);
}
// ---------------------------------------------------------------------------
// 1. SVG rejection through the real gates used by POST /api/admin/login-background
// ---------------------------------------------------------------------------
console.log("[1] SVG rejection gates (utils/branding.js, as called by the endpoint)");
ok("getMediaTypeFromFilename('x.svg') is null (upload gate)",
branding.getMediaTypeFromFilename("x.svg") === null);
ok("getValidatedExtension('x.svg') is null (upload gate)",
branding.getValidatedExtension("x.svg") === null);
ok("getMediaTypeFromFilename('x.png.svg') is null (trailing-ext smuggling)",
branding.getMediaTypeFromFilename("x.png.svg") === null);
ok("getMediaTypeFromFilename('x.png%00.svg') is null",
branding.getMediaTypeFromFilename("x.png%00.svg") === null);
for (const url of [
"https://cdn.example.com/bg.svg",
"https://cdn.example.com/bg.SVG",
"https://cdn.example.com/bg.svg?v=2",
"https://cdn.example.com/dir/bg.svg"
]) {
ok(`getMediaTypeFromUrl('${url}') is null (URL gate)`,
branding.getMediaTypeFromUrl(url) === null);
ok(`getExtensionFromUrl('${url}') is null (URL gate)`,
branding.getExtensionFromUrl(url) === null);
}
// A .svg fragment is not part of URL.pathname (the remote server never sees
// it), so the URL gate correctly resolves that URL to png — the SVG payload
// is stopped by the content gate instead. The pipeline's invariant is the
// composition: no URL can deliver an SVG body into public/images because any
// body that passes the URL gate must still match binary magic bytes.
ok("getMediaTypeFromUrl('...x.png#.svg') -> image (fragment ignored by design)",
branding.getMediaTypeFromUrl("https://cdn.example.com/x.png#.svg") === "image");
// Content gate: even a mislabeled SVG body (e.g. served as .png) cannot pass
// magic-byte validation — SVG is a text document, not a binary image format.
const svgBody = Buffer.from('<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>');
ok("validateImageBuffer rejects an SVG body (content gate)",
branding.validateImageBuffer(svgBody).valid === false);
ok("validateImageBuffer error mentions SVG rejection",
/svg/i.test(branding.validateImageBuffer(svgBody).error || ""));
ok("composed invariant: SVG body can never pass the content gate",
branding.validateImageBuffer(svgBody).valid === false);
// svgz is a distinct extension and must also fail the whitelist.
ok("getExtensionFromUrl('...bg.svgz') is null",
branding.getExtensionFromUrl("https://cdn.example.com/bg.svgz") === null);
// Positive controls: the allowed formats still pass their gates.
ok("getMediaTypeFromUrl('...img.png') -> image (positive control)",
branding.getMediaTypeFromUrl("https://cdn.example.com/img.png") === "image");
ok("getMediaTypeFromUrl('...bg.webm') -> video (positive control)",
branding.getMediaTypeFromUrl("https://cdn.example.com/bg.webm") === "video");
ok("getMediaTypeFromUrl('...bg.avif') -> image (positive control)",
branding.getMediaTypeFromUrl("https://cdn.example.com/bg.avif") === "image");
const pngBody = Buffer.concat([Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]), Buffer.alloc(64)]);
ok("validateImageBuffer accepts a PNG body (positive control)",
branding.validateImageBuffer(pngBody).valid === true);
// ---------------------------------------------------------------------------
// 2. Explicit SVG URL rejection regex (exact copies from the two endpoints)
// ---------------------------------------------------------------------------
console.log("[2] Explicit SVG URL rejection regex (parity check on both endpoints)");
const SVG_PATH_RE = /\.svg(\?|#|$)/i;
for (const pathname of ["/bg.svg", "/dir/bg.SVG", "/bg.svg?v=2", "/bg.svg#frag"]) {
ok(`SVG regex matches '${pathname}' (rejected with explicit error)`,
SVG_PATH_RE.test(pathname));
}
for (const pathname of ["/bg.png", "/bg.webm", "/bg.avif", "/bg.svgz", "/bg.svg2", "/mysvg"]) {
ok(`SVG regex does NOT match '${pathname}' (allowed formats untouched)`,
!SVG_PATH_RE.test(pathname));
}
// ---------------------------------------------------------------------------
// 3. Single-flight + negative cache (exact copy of the new loadBrandingRemoteAsset)
// ---------------------------------------------------------------------------
console.log("[3] Single-flight + negative-cache in loadBrandingRemoteAsset");
class TTLCache {
constructor({ ttlMs = 60000, maxSize = Infinity } = {}) {
this._ttlMs = ttlMs;
this._maxSize = maxSize;
this._map = new Map();
}
get(key) {
const entry = this._map.get(key);
if (!entry) return undefined;
if (entry.expiresAt > 0 && Date.now() >= entry.expiresAt) {
this._map.delete(key);
return undefined;
}
return entry.value;
}
set(key, value, ttlMs) {
const ttl = ttlMs !== undefined ? ttlMs : this._ttlMs;
if (this._map.size >= this._maxSize && !this._map.has(key)) {
const oldestKey = this._map.keys().next().value;
if (oldestKey !== undefined) this._map.delete(oldestKey);
}
this._map.set(key, { value, expiresAt: ttl > 0 ? Date.now() + ttl : 0 });
}
clear(predicate) {
if (!predicate) { this._map.clear(); return; }
for (const key of [...this._map.keys()]) {
if (predicate(key)) this._map.delete(key);
}
}
}
const REMOTE_ASSET_CACHE = new TTLCache({ ttlMs: 300000 });
const REMOTE_ASSET_INFLIGHT = new Map();
const REMOTE_ASSET_RECENT_FAILURES = new TTLCache({ ttlMs: 10000 });
let originFetches = 0;
let originShouldFail = false;
let originBody = Buffer.alloc(0);
async function httpGetRawStub() {
originFetches += 1;
await new Promise((r) => setTimeout(r, 25)); // emulate network latency
if (originShouldFail) throw new Error("HTTP 503");
return originBody;
}
// Exact copy of the remediated loadBrandingRemoteAsset from index.js, with
// httpGetRaw swapped for the stub above and the cache instances hoisted.
async function loadBrandingRemoteAsset(assetConfig) {
const cacheKey = `${assetConfig.kind}|${assetConfig.sourceUrl}`;
const cached = REMOTE_ASSET_CACHE.get(cacheKey);
if (cached) return cached;
if (REMOTE_ASSET_RECENT_FAILURES.get(cacheKey)) {
throw new Error("Branding media temporarily unavailable");
}
const existing = REMOTE_ASSET_INFLIGHT.get(cacheKey);
if (existing) return existing;
const task = (async () => {
const rawBuffer = await httpGetRawStub(assetConfig.sourceUrl, { maxBytes: assetConfig.maxBytes });
if (!rawBuffer || rawBuffer.length === 0) throw new Error("Invalid branding media");
const asset = { buffer: rawBuffer, mimeType: assetConfig.mimeType };
REMOTE_ASSET_CACHE.set(cacheKey, asset);
return asset;
})();
REMOTE_ASSET_INFLIGHT.set(cacheKey, task);
try {
return await task;
} catch (err) {
REMOTE_ASSET_RECENT_FAILURES.set(cacheKey, Date.now());
throw err;
} finally {
REMOTE_ASSET_INFLIGHT.delete(cacheKey);
}
}
function clearBrandingRemoteAssetCache(kind = "") {
const normalizedKind = String(kind || "").trim().toLowerCase();
if (!normalizedKind) {
REMOTE_ASSET_CACHE.clear();
REMOTE_ASSET_RECENT_FAILURES.clear();
return;
}
const matchesKind = (key) => key.startsWith(`${normalizedKind}|`);
REMOTE_ASSET_CACHE.clear(matchesKind);
REMOTE_ASSET_RECENT_FAILURES.clear(matchesKind);
}
const ASSET = { kind: "login-background", sourceUrl: "https://cdn.example.com/bg.webm", maxBytes: 40 * 1024 * 1024, mimeType: "video/webm" };
(async () => {
originBody = Buffer.alloc(1024, 7);
// Flash crowd: 50 concurrent requests on a cold cache share ONE download.
originFetches = 0;
const burst = await Promise.all(Array.from({ length: 50 }, () =>
loadBrandingRemoteAsset(ASSET).then((a) => a.buffer)));
ok("50 concurrent cache misses trigger exactly ONE origin fetch", originFetches === 1);
ok("all 50 concurrent callers receive the same buffer",
burst.every((b) => b.length === 1024 && b[0] === 7));
// Warm cache serves repeats without touching the origin.
await loadBrandingRemoteAsset(ASSET);
await loadBrandingRemoteAsset(ASSET);
ok("repeat requests after success are served from cache (still 1 fetch)", originFetches === 1);
// Remote outage: first caller fails, subsequent callers fail fast with no
// new origin fetch (negative cache) instead of one fetch per request.
clearBrandingRemoteAssetCache("login-background");
originShouldFail = true;
originFetches = 0;
await assert.rejects(() => loadBrandingRemoteAsset(ASSET), /HTTP 503/);
const duringOutage = await Promise.allSettled(Array.from({ length: 20 }, () =>
loadBrandingRemoteAsset(ASSET)));
ok("failure marks the asset negative (1 origin fetch)", originFetches === 1);
ok("all follow-up requests during the failure window fail fast without origin fetches",
duringOutage.every((r) => r.status === "rejected" && /temporarily unavailable/.test(r.reason.message)) && originFetches === 1);
// Admin re-save clears the negative marker even for the same URL.
clearBrandingRemoteAssetCache("login-background");
originShouldFail = false;
originFetches = 0;
const afterClear = await loadBrandingRemoteAsset(ASSET);
ok("clearBrandingRemoteAssetCache lifts the negative marker (fetch succeeds again)",
afterClear.buffer.length === 1024 && originFetches === 1);
// A failure for one kind must not poison another kind sharing the cache.
clearBrandingRemoteAssetCache("login-background");
originShouldFail = true;
await assert.rejects(() => loadBrandingRemoteAsset(ASSET));
originShouldFail = false;
originFetches = 0;
const logoAsset = { ...ASSET, kind: "logo", sourceUrl: "https://cdn.example.com/logo.webp" };
const logoResult = await loadBrandingRemoteAsset(logoAsset);
ok("negative marker is kind-scoped (logo kind unaffected)",
logoResult.buffer.length === 1024 && originFetches === 1);
// ---------------------------------------------------------------------------
// 4. brandingAssetRateLimiter (exact copy of the new config)
// ---------------------------------------------------------------------------
console.log("[4] brandingAssetRateLimiter contract through a real express app");
function getRequestIp(req) {
return req.socket.remoteAddress || "unknown";
}
const limiter = rateLimit({
windowMs: 60 * 1000,
max: 240,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => `branding-asset:${getRequestIp(req)}`,
handler: (req, res) => {
res.status(429).type("text/plain").send("Too many requests");
}
});
const app = express();
app.disable("x-powered-by");
app.get("/branding-media/login-background", limiter, (req, res) => res.type("video/webm").send(Buffer.alloc(16)));
const server = http.createServer(app);
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const { port } = server.address();
function get(localAddress) {
return new Promise((resolve) => {
const req = http.request({ host: "127.0.0.1", port, localAddress, path: "/branding-media/login-background" }, (res) => {
const chunks = [];
res.on("data", (c) => chunks.push(c));
res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks).toString() }));
});
req.on("error", (err) => resolve({ status: 0, headers: {}, body: "", error: err.message }));
req.end();
});
}
let last = null;
for (let i = 0; i < 240; i += 1) last = await get("127.0.0.1");
ok("requests 1..240 within the window succeed (200)", last.status === 200);
ok("success responses carry RateLimit headers", !!last.headers["ratelimit-limit"]);
last = await get("127.0.0.1");
ok("request 241 from the same IP is rejected with 429 text/plain",
last.status === 429 && /text\/plain/i.test(last.headers["content-type"]) && /too many requests/i.test(last.body));
// A spoofed X-Forwarded-For header must not rotate the bucket: the key uses
// the direct socket IP (trusted-proxy resolution happens in getRequestIp).
const spoofed = await get("127.0.0.1");
ok("spoofed X-Forwarded-For does not reset the exhausted bucket (429)",
spoofed.status === 429);
const otherIp = await get("127.0.0.2");
ok("a genuinely different source IP still gets 200 (independent buckets)", otherIp.status === 200);
server.close();
console.log(`\nAll ${checks} checks passed.`);
})().catch((err) => {
console.error(err.message);
process.exit(1);
});