"use strict"; // Adversarial test suite for the parse-and-rebuild SVG sanitizer. // // The previous sanitizer filtered raw text with regexes; this one parses with // a vetted XML parser (@xmldom/xmldom), validates every node against // whitelists, and RE-SERIALIZES the output from validated names/values. The // tests below cover both the classic payload set and the mangled-input class // that motivated the rewrite: anything the strict parser cannot read is // rejected outright, and everything that survives is re-emitted with // attacker-controlled bytes escaped or dropped. // // The structural guarantee locked here: sanitized output must itself parse as // well-formed XML under the same strict parser (no undeclared prefixes, no // broken tags), so a "sanitized" file can never end up as a parse-error // document on the serving side. const test = require("node:test"); const assert = require("node:assert"); const { DOMParser } = require("@xmldom/xmldom"); const { sanitizeSvg, validateSvgBuffer, ALLOWED_TAGS, DANGEROUS_BLOCK_TAGS } = require("./svg-sanitizer.js"); // Re-parse sanitized output with the same strict rules the sanitizer uses. function assertWellFormedXml(output, label) { const errors = []; const parser = new DOMParser({ onError: (severity, message) => errors.push(`${severity}: ${message}`) }); let doc = null; try { doc = parser.parseFromString(output, "image/svg+xml"); } catch (err) { assert.fail(`${label}: sanitized output is not well-formed XML: ${err.message}`); } assert.ok(doc && doc.documentElement, `${label}: sanitized output has a document element`); assert.deepEqual(errors, [], `${label}: sanitized output produced no parser diagnostics`); } function sanitizeOk(input) { const res = sanitizeSvg(input); assert.equal(res.valid, true, `expected valid, got: ${res.error || "?"}`); assert.ok(Buffer.isBuffer(res.sanitized), "sanitized output is a Buffer"); return res.sanitized.toString("utf8"); } function sanitizeRejected(input, errorHint) { const res = sanitizeSvg(input); assert.equal(res.valid, false, `expected rejection, got output: ${res.sanitized && res.sanitized.toString("utf8").slice(0, 120)}`); if (errorHint) { assert.ok(new RegExp(errorHint, "i").test(String(res.error || "")), `error "${res.error}" should match /${errorHint}/i`); } return res.error; } const SVG_OPEN = ''; // --------------------------------------------------------------------------- // Classic active-content payloads // --------------------------------------------------------------------------- test("script tag and its body are dropped entirely", () => { const out = sanitizeOk(`${SVG_OPEN} `); assert.ok(!/ `); assert.ok(!out.toLowerCase().includes("script")); assert.ok(!out.includes("evil.com")); assert.ok(out.includes(" { const out = sanitizeOk(`${SVG_OPEN} ]]> `); assert.ok(!out.includes(" { // A literal `` inside style text is malformed XML (style content is // ordinary text content in XML) — rejected fail-closed, never mangled into // live markup the way a text-filtering sanitizer would. sanitizeRejected(`${SVG_OPEN}"; }`, "not well-formed|parse"); // The well-formed way to carry those characters: entity references. They // must survive as ESCAPED text so the emitted markup cannot be broken out of. const out = sanitizeOk(`${SVG_OPEN}`); assert.ok(!out.includes("([\s\S]*?)<\/style>/); assert.ok(styleMatch, "style element present"); assert.ok(styleMatch[1].includes("</style>"), "breakout sequence stays escaped inside style content"); assertWellFormedXml(out, "style-breakout"); }); test("processing instructions and xml-stylesheet are dropped", () => { const out = sanitizeOk(` ${SVG_OPEN}`); assert.ok(!out.includes(" { const out = sanitizeOk(`${SVG_OPEN}`); assert.ok(!out.includes("xml:base")); assert.ok(!out.includes("evil.com")); assert.ok(out.includes('href="logo.png"')); assertWellFormedXml(out, "xml-base"); }); test("unknown-namespace attribute metadata is dropped, keeping the output well-formed", () => { // Declared design-tool namespace: parser accepts it, rebuild drops the // attribute (its declaration is never carried over — emitting it would // produce undeclared prefixes). const out = sanitizeOk(''); assert.ok(!out.includes("serif")); assert.ok(out.includes("', "namespace"); }); test("undeclared xlink prefix is repaired with a constant declaration and the output stays well-formed", () => { // Common real-world shape: xlink used, xmlns:xlink forgotten. The parser // would reject it; the pre-parse repair injects the FIXED declaration. const out = sanitizeOk(''); assert.ok(out.includes('xlink:href="#icon"')); assert.ok(/xmlns:xlink="http:\/\/www\.w3\.org\/1999\/xlink"/.test(out), "repaired usage keeps a declared prefix"); assert.ok(!/xmlns:xlink/.test(out.split("'); assertWellFormedXml(out2, "xlink-repair-2"); }); // --------------------------------------------------------------------------- // XXE / DoS // --------------------------------------------------------------------------- test("DOCTYPE and ENTITY declarations are rejected outright (XXE / Billion Laughs)", () => { sanitizeRejected(']>&xxe;', "DOCTYPE|ENTITY"); sanitizeRejected(`]> &lol2;`, "ENTITY"); }); test("null bytes and oversize input are rejected", () => { sanitizeRejected('\0', "null"); // 600000 × 10-byte comments = 6MB, past the 5MB cap. sanitizeRejected(`${"".repeat(600000)}`, "maximum size"); sanitizeRejected("", "empty"); }); test("pathological nesting depth is rejected instead of exhausting the stack", () => { const depth = 400; const doc = `${SVG_OPEN}${"".repeat(depth)}${"".repeat(depth)}`; sanitizeRejected(doc, "deep"); }); test("pathological element count is rejected (DoS bound)", () => { const doc = `${SVG_OPEN}${"".repeat(60000)}`; sanitizeRejected(doc, "complex"); }); // --------------------------------------------------------------------------- // Legitimate logo preservation // --------------------------------------------------------------------------- test("a realistic branded logo survives with its features intact", () => { const logo = ` Brand Logo Company logo ADPanel `; const out = sanitizeOk(logo); // Tag names are lowercased on rebuild (SVG is case-sensitive; the canonical // SVG spelling of these elements is camelCase, but lowercased local names // resolve to the same SVG elements when served as image/svg+xml). for (const feature of [ "Brand Logo", " { const out = sanitizeOk(""); assert.ok(out.includes(' { assert.ok(ALLOWED_TAGS.has("path") && ALLOWED_TAGS.has("svg") && ALLOWED_TAGS.has("use")); assert.ok(!ALLOWED_TAGS.has("script") && !ALLOWED_TAGS.has("foreignObject")); assert.ok(DANGEROUS_BLOCK_TAGS.has("script") && DANGEROUS_BLOCK_TAGS.has("foreignobject") && DANGEROUS_BLOCK_TAGS.has("animate")); }); test("validateSvgBuffer keeps its Buffer-in/Buffer-out contract", () => { const okRes = validateSvgBuffer(Buffer.from('')); assert.equal(okRes.valid, true); assert.ok(Buffer.isBuffer(okRes.data)); const badRes = validateSvgBuffer(Buffer.from('')); // Script-only content: subtree dropped leaves an empty svg root, still valid. assert.equal(badRes.valid, true); assert.ok(!badRes.data.toString("utf8").includes("script")); const notBuffer = validateSvgBuffer(""); assert.equal(notBuffer.valid, false); }); test("final output never contains prohibited tokens even when input games every rule", () => { const payload = `${SVG_OPEN}

x

`; const out = sanitizeOk(payload); for (const bad of [/]/i, /]/i, /]/i, /\son[a-z0-9_\-]+\s*=/i, /javascript\s*:/i, / { const out = sanitizeOk(` x `); assert.ok(out.includes('viewBox="0 0 200 50"'), `viewBox casing lost: ${out}`); assert.ok(out.includes('preserveAspectRatio="xMidYMid meet"'), `preserveAspectRatio casing lost: ${out}`); assert.ok(out.includes('gradientUnits="userSpaceOnUse"'), `gradientUnits casing lost: ${out}`); assert.ok(out.includes('patternContentUnits="objectBoundingBox"'), `patternContentUnits casing lost: ${out}`); assert.ok(out.includes('textLength="10"'), `textLength casing lost: ${out}`); assert.ok(out.includes('lengthAdjust="spacingAndGlyphs"'), `lengthAdjust casing lost: ${out}`); assert.ok(!/viewbox=/i.test(out.replace(/viewBox/g, "")), "no lowercased viewbox residue"); assertWellFormedXml(out, "attr-case"); }); test("prefixed attributes stay lowercase and well-formed while local attributes keep case", () => { // An uppercase-declared prefix parses as XML, but the rebuild only declares // the lowercase prefixes — so prefixed attributes must be emitted lowercase // or the output would reference an undeclared prefix. const out = sanitizeOk(` `); assert.ok(/xlink:href="#icon"/.test(out), `xlink:href missing: ${out}`); assert.ok(!/XLINK:HREF/.test(out), "upper-case prefixed attribute must not be emitted"); assert.ok(out.includes('viewBox="0 0 10 10"'), `viewBox casing lost: ${out}`); assertWellFormedXml(out, "prefixed-attr-case"); });