Files
Kelx/utils/svg-sanitizer.test.js
2026-11-30 16:32:37 +00:00

430 lines
21 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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 = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">';
// ---------------------------------------------------------------------------
// Classic active-content payloads
// ---------------------------------------------------------------------------
test("script tag and its body are dropped entirely", () => {
const out = sanitizeOk(`${SVG_OPEN}
<circle cx="50" cy="50" r="40" fill="red"/>
<script type="text/javascript">alert(document.cookie);fetch('/api/admin/delete-all');</script>
</svg>`);
assert.ok(!/<script/i.test(out));
assert.ok(!out.includes("document.cookie"));
assert.ok(!out.includes("delete-all"));
assert.ok(out.includes("<circle") && out.includes('fill="red"'));
assertWellFormedXml(out, "script-drop");
});
test("dangerous subtree removal keeps siblings: foreignObject, iframe, embed, object, animate, set", () => {
const out = sanitizeOk(`${SVG_OPEN}
<rect width="10" height="10"/>
<foreignObject><div xmlns="http://www.w3.org/1999/xhtml"><p>evil</p></div></foreignObject>
<iframe src="https://evil.com"></iframe>
<embed src="https://evil.com/x.swf"/>
<object data="https://evil.com/x"></object>
<animate attributeName="href" to="javascript:alert(1)"/>
<set attributeName="onload" to="alert(1)"/>
<circle r="1"/>
</svg>`);
for (const token of ["foreignobject", "iframe", "embed", "object", "animate", "<set", "evil.com", "alert(1)", "attributeName"]) {
assert.ok(!out.toLowerCase().includes(token), `output must not contain ${token}`);
}
assert.ok(out.includes("<rect") && out.includes("<circle"));
assertWellFormedXml(out, "dangerous-subtree");
});
test("event handler attributes are stripped, including prefixed and SMIL-flavored names", () => {
const out = sanitizeOk(`${SVG_OPEN}
<rect onload="alert(1)" ONERROR="alert(2)" onmouseover="alert(3)" xlink:onclick="alert(4)" onbegin="alert(5)"/>
</svg>`);
assert.ok(!/\son[a-z0-9_\-]*\s*=/i.test(out), "no on*= survives");
assert.ok(out.includes("<rect"));
assertWellFormedXml(out, "event-attrs");
});
test("javascript:/vbscript:/data:text-html pseudo-protocols are stripped from any attribute", () => {
const out = sanitizeOk(`${SVG_OPEN}
<a href="javascript:alert(1)"><path d="M0 0"/></a>
<filter id="f"><feImage xlink:href="vbscript:msgbox(1)"/></filter>
<rect fill="url(javascript:alert(1))" style="background:url('data:text/html;base64,PHNjcmlwdD4=')"/>
</svg>`);
assert.ok(!out.includes("javascript:"));
assert.ok(!out.includes("vbscript:"));
assert.ok(!out.includes("data:text/html"));
assert.ok(out.includes("<path"));
assertWellFormedXml(out, "pseudo-protocols");
});
test("entity- and double-entity-encoded protocols are decoded before the protocol checks", () => {
const out = sanitizeOk(`${SVG_OPEN}
<use href="&#106;avascript:alert(1)"/>
<use href="&#x6a;avascript:alert(2)"/>
<a href="&amp;#106;avascript:alert(3)"><circle r="1"/></a>
<rect style="fill:url(&#106;avascript:alert(4))"/>
</svg>`);
assert.ok(!out.includes("javascript:"));
assert.ok(!out.includes("&#106;"));
assert.ok(!out.includes("&#x6a;"));
assert.ok(out.includes("<circle") && out.includes("<rect"));
assertWellFormedXml(out, "encoded-protocols");
});
// ---------------------------------------------------------------------------
// <use> / <image> resource restrictions
// ---------------------------------------------------------------------------
test("<use> is restricted to local fragments, <image> to safe raster data or relative paths", () => {
const out = sanitizeOk(`${SVG_OPEN}
<defs><circle id="c" r="5"/></defs>
<use href="#c"/>
<use xlink:href="#c" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<use href="http://evil.com/x.svg#p"/>
<use xlink:href="//evil.com/y.svg#q" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<image href="data:image/png;base64,iVBORw0KGgo="/>
<image href="picsum.png"/>
<image href="/img/local.png"/>
<image href="../etc/passwd.png"/>
<image href="https://evil.com/x.png"/>
<image href="data:text/html;base64,PHNjcmlwdD4="/>
</svg>`);
assert.ok(out.includes('href="#c"'), "local use kept");
assert.ok(out.includes("data:image/png;base64,iVBORw0KGgo="), "safe raster data URI kept");
assert.ok(out.includes('href="picsum.png"') && out.includes('href="/img/local.png"'), "safe relative paths kept");
assert.ok(!out.includes("evil.com"));
assert.ok(!out.includes(".."));
assert.ok(!out.includes("data:text/html"));
assert.ok(/xmlns:xlink="http:\/\/www\.w3\.org\/1999\/xlink"/.test(out), "xlink declaration re-emitted when used");
assertWellFormedXml(out, "use-image-restrictions");
});
// ---------------------------------------------------------------------------
// Mangled / parser-hostile input (the class the rewrite exists to close)
// ---------------------------------------------------------------------------
test("comment-split markup cannot reconstruct a dangerous tag", () => {
// `<scr<!-- -->ipt>` is not well-formed XML — the old regex sanitizer
// mangled such input back into markup; the strict parser rejects it.
sanitizeRejected(`${SVG_OPEN}<path d="M0 0"/><scr<!-- -->ipt>alert(1)</scr<!-- -->ipt></svg>`, "not well-formed|parse");
// A well-formed comment carrying a script payload is dropped with the comment.
const out = sanitizeOk(`${SVG_OPEN}<path d="M0 0"/><!-- <script>alert(1)</script> --></svg>`);
assert.ok(!out.includes("ipt>alert"));
assert.ok(!out.includes("alert(1)"));
assert.ok(out.includes("<path"));
assertWellFormedXml(out, "comment-drop");
});
test("mismatched and unclosed tags are rejected, not mangled through", () => {
sanitizeRejected(`<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0"></rect></svg>`, "not well-formed|parse");
sanitizeRejected(`<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0"`, "not well-formed|parse");
sanitizeRejected(`<svg xmlns="http://www.w3.org/2000/svg"><g><path/></g></g></svg>`, "not well-formed|parse");
});
test("unquoted and backtick-quoted attributes cannot smuggle attribute boundaries", () => {
// In XML, unquoted attribute values are illegal — the old regex parser
// accepted and re-emitted them; the strict parse rejects the document.
sanitizeRejected('<svg xmlns="http://www.w3.org/2000/svg"><path d=M0 0 onload=alert(1)/></svg>', "not well-formed|parse");
sanitizeRejected('<svg xmlns="http://www.w3.org/2000/svg"><path d=`alert(1)`/></svg>', "not well-formed|parse");
});
test("undefined entities are rejected", () => {
sanitizeRejected('<svg xmlns="http://www.w3.org/2000/svg"><text>&foo;</text></svg>', "parse errors");
});
test("multiple root elements are rejected", () => {
sanitizeRejected('<svg xmlns="http://www.w3.org/2000/svg"/><svg xmlns="http://www.w3.org/2000/svg"/>', "not well-formed");
});
test("non-SVG root element is rejected", () => {
sanitizeRejected('<html xmlns="http://www.w3.org/1999/xhtml"><body>hi</body></html>', "root");
sanitizeRejected("just some text, no markup at all", "root|parse|well-formed");
});
test("namespaced dangerous tags are dropped: svg:script, xhtml:script, case games", () => {
const out = sanitizeOk(`<svg:svg xmlns:svg="http://www.w3.org/2000/svg">
<svg:script xlink:href="http://evil.com/xss.js" xmlns:xlink="http://www.w3.org/1999/xlink"></svg:script>
<ScRiPt>alert(1)</ScRiPt>
<path d="M10 10 H 90"/>
</svg:svg>`);
assert.ok(!out.toLowerCase().includes("script"));
assert.ok(!out.includes("evil.com"));
assert.ok(out.includes("<path"));
assertWellFormedXml(out, "namespaced-dangerous");
});
test("CDATA sections cannot smuggle markup anywhere", () => {
const out = sanitizeOk(`${SVG_OPEN}
<text><![CDATA[</text><script>alert(1)</script>]]></text>
<style><![CDATA[ circle { fill: red; } ]]></style>
</svg>`);
assert.ok(!out.includes("<script"));
assert.ok(out.includes("circle { fill: red; }"), "legit CSS in CDATA preserved");
assertWellFormedXml(out, "cdata-smuggle");
});
test("style-content breakouts are neutralized: raw markup is rejected, entity-encoded stays escaped", () => {
// A literal `</style>` 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}<style>p { content: "</style><script>alert(1)</script>"; }</style></svg>`, "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}<style>p { content: "&lt;/style&gt;&lt;script&gt;"; }</style><rect width="1" height="1"/></svg>`);
assert.ok(!out.includes("<script"));
const styleMatch = out.match(/<style>([\s\S]*?)<\/style>/);
assert.ok(styleMatch, "style element present");
assert.ok(styleMatch[1].includes("&lt;/style&gt;"), "breakout sequence stays escaped inside style content");
assertWellFormedXml(out, "style-breakout");
});
test("processing instructions and xml-stylesheet are dropped", () => {
const out = sanitizeOk(`<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="https://evil.com/xss.css"?>
${SVG_OPEN}<rect width="1" height="1"/></svg>`);
assert.ok(!out.includes("<?"));
assert.ok(!out.includes("evil.com"));
assert.ok(out.includes("<rect"));
assertWellFormedXml(out, "processing-instructions");
});
test("xml:base rebasing attribute is stripped", () => {
const out = sanitizeOk(`${SVG_OPEN}<image href="logo.png" xml:base="https://evil.com/"/></svg>`);
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('<svg xmlns="http://www.w3.org/2000/svg" xmlns:serif="http://www.serif.com/"><path serif:fill="red" d="M0 0"/></svg>');
assert.ok(!out.includes("serif"));
assert.ok(out.includes("<path"));
assertWellFormedXml(out, "unknown-ns-attr-declared");
// Undeclared unknown prefix: strict XML rejects the document outright.
sanitizeRejected('<svg xmlns="http://www.w3.org/2000/svg"><path serif:fill="red"/></svg>', "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('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><use xlink:href="#icon"/></svg>');
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("<use")[0].replace('xmlns:xlink="http://www.w3.org/1999/xlink"', "")) || true);
assertWellFormedXml(out, "xlink-repair");
// Self-closing root variant.
const out2 = sanitizeOk('<svg xmlns="http://www.w3.org/2000/svg"><use xlink:href="#a"/></svg>');
assertWellFormedXml(out2, "xlink-repair-2");
});
// ---------------------------------------------------------------------------
// XXE / DoS
// ---------------------------------------------------------------------------
test("DOCTYPE and ENTITY declarations are rejected outright (XXE / Billion Laughs)", () => {
sanitizeRejected('<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><svg xmlns="http://www.w3.org/2000/svg"><text>&xxe;</text></svg>', "DOCTYPE|ENTITY");
sanitizeRejected(`<?xml version="1.0"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">]>
<svg xmlns="http://www.w3.org/2000/svg"><text>&lol2;</text></svg>`, "ENTITY");
});
test("null bytes and oversize input are rejected", () => {
sanitizeRejected('<svg xmlns="http://www.w3.org/2000/svg">\0<rect/></svg>', "null");
// 600000 × 10-byte comments = 6MB, past the 5MB cap.
sanitizeRejected(`<svg xmlns="http://www.w3.org/2000/svg">${"<!-- x -->".repeat(600000)}</svg>`, "maximum size");
sanitizeRejected("", "empty");
});
test("pathological nesting depth is rejected instead of exhausting the stack", () => {
const depth = 400;
const doc = `${SVG_OPEN}${"<g>".repeat(depth)}<circle r="1"/>${"</g>".repeat(depth)}</svg>`;
sanitizeRejected(doc, "deep");
});
test("pathological element count is rejected (DoS bound)", () => {
const doc = `${SVG_OPEN}${"<circle r='1'/>".repeat(60000)}</svg>`;
sanitizeRejected(doc, "complex");
});
// ---------------------------------------------------------------------------
// Legitimate logo preservation
// ---------------------------------------------------------------------------
test("a realistic branded logo survives with its features intact", () => {
const logo = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 200 50" width="200" height="50">
<title>Brand Logo</title>
<desc>Company logo</desc>
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#4f46e5"/>
<stop offset="100%" stop-color="#06b6d4"/>
</linearGradient>
<mask id="m"><rect width="200" height="50" fill="#fff"/></mask>
<filter id="blur"><feGaussianBlur stdDeviation="1"/></filter>
<symbol id="icon"><circle cx="10" cy="10" r="5"/></symbol>
</defs>
<style>.brand { fill: url(#grad); font-family: sans-serif; }</style>
<g mask="url(#m)" filter="url(#blur)">
<rect class="brand" width="200" height="50" rx="8" fill="url(#grad)"/>
<text class="brand" x="20" y="30">ADPanel</text>
<use xlink:href="#icon" x="160" y="10"/>
<image href="data:image/png;base64,iVBORw0KGgo=" x="0" y="0" width="10" height="10"/>
</g>
</svg>`;
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 [
"<title>Brand Logo</title>",
"<lineargradient",
"stop-color",
"<mask",
"<fegaussianblur",
"<symbol",
".brand",
"fill: url(#grad)",
'xlink:href="#icon"',
"data:image/png;base64",
'xmlns="http://www.w3.org/2000/svg"',
'xmlns:xlink="http://www.w3.org/1999/xlink"',
]) {
assert.ok(out.toLowerCase().includes(feature.toLowerCase()), `feature preserved: ${feature}`);
}
assertWellFormedXml(out, "realistic-logo");
});
test("missing root xmlns is added to the rebuilt document", () => {
const out = sanitizeOk("<svg viewBox='0 0 10 10'><rect width='1' height='1'/></svg>");
assert.ok(out.includes('<svg') && out.includes('xmlns="http://www.w3.org/2000/svg"'), "SVG namespace declared");
assertWellFormedXml(out, "xmlns-added");
});
test("whitelists remain exported and unchanged", () => {
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('<svg xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1"/></svg>'));
assert.equal(okRes.valid, true);
assert.ok(Buffer.isBuffer(okRes.data));
const badRes = validateSvgBuffer(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'));
// 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("<svg xmlns='http://www.w3.org/2000/svg'/>");
assert.equal(notBuffer.valid, false);
});
test("final output never contains prohibited tokens even when input games every rule", () => {
const payload = `${SVG_OPEN}
<script>alert(1)</script>
<foreignObject><p>x</p></foreignObject>
<animate to="javascript:alert(2)"/>
<rect onload="alert(3)" width="1" height="1"/>
<style>a { background: url('javascript:alert(4)'); }</style>
</svg>`;
const out = sanitizeOk(payload);
for (const bad of [/<script[\s>]/i, /<foreignobject[\s>]/i, /<animate[\s>]/i, /\son[a-z0-9_\-]+\s*=/i, /javascript\s*:/i, /<!doctype/i, /<\?/]) {
assert.ok(!bad.test(out), `output must not match ${bad}`);
}
assertWellFormedXml(out, "kitchen-sink");
});
// ---------------------------------------------------------------------------
// Attribute case preservation (regression: lowercasing destroyed viewBox)
// ---------------------------------------------------------------------------
test("camelCase SVG attributes keep their original casing", () => {
const out = sanitizeOk(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 50" preserveAspectRatio="xMidYMid meet">
<linearGradient id="g" gradientUnits="userSpaceOnUse" spreadMethod="pad">
<stop offset="0" stop-color="#fff"/>
</linearGradient>
<pattern id="p" patternContentUnits="objectBoundingBox" patternTransform="rotate(45)"/>
<text textLength="10" lengthAdjust="spacingAndGlyphs">x</text>
<clipPath id="c" clipPathUnits="userSpaceOnUse"/>
<rect width="1" height="1" clip-path="url(#c)" fill="url(#g)"/>
</svg>`);
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(`<svg xmlns="http://www.w3.org/2000/svg" xmlns:XLINK="http://www.w3.org/1999/xlink" viewBox="0 0 10 10">
<use XLINK:HREF="#icon"/>
</svg>`);
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");
});