SPB Git

Repository Public

renderer.sanitize.test.ts 6.9 KB 87 lines typescript

1import { describe, expect, it } from "vitest";2import { createElement } from "react";3import { renderToStaticMarkup } from "react-dom/server";4import { SvgNodeSchema, type SvgNode } from "@/schema";5import { sanitizeSvg, svgTreeToMarkup, safeSvgAttr, safeStyle } from "@/renderer/sanitize-svg";6import { SvgTree } from "@/renderer/blocks/SvgTree";78const clean = (markup: string) => { const r = sanitizeSvg(markup); if (!r.ok) throw new Error(r.error); return r; };9const FORBIDDEN = /<script|onload|onclick|onerror|foreignObject|javascript:|<image|<use|<style|<a\b|<iframe|data:|https?:\/\/evil|url\((?!#)|@import|expression\(|<animate|<set\b/i;1011const HOSTILE: Record<string, string> = {12  script: '<svg viewBox="0 0 10 10"><script>alert(1)</script><rect width="10" height="10"/></svg>',13  "script with CDATA": '<svg viewBox="0 0 10 10"><script type="text/ecmascript"><![CDATA[alert(1)]]></script><rect width="1" height="1"/></svg>',14  onload: '<svg viewBox="0 0 10 10" onload="alert(1)"><rect width="10" height="10" onclick="alert(2)" ONERROR="x"/></svg>',15  foreignObject: '<svg viewBox="0 0 10 10"><foreignObject width="10" height="10"><iframe xmlns="http://www.w3.org/1999/xhtml" src="javascript:alert(1)"></iframe></foreignObject><circle r="2"/></svg>',16  "javascript href": '<svg viewBox="0 0 10 10" xmlns:xlink="http://www.w3.org/1999/xlink"><a xlink:href="javascript:alert(1)"><rect width="10" height="10"/></a><linearGradient id="g" href="javascript:alert(1)"/><linearGradient id="h" xlink:href=" java\tscript:alert(1)"/></svg>',17  "external image": '<svg viewBox="0 0 10 10"><image href="https://evil.example/x.png" width="10" height="10"/><image xlink:href="data:image/svg+xml;base64,AAAA"/><rect width="1" height="1"/></svg>',18  "css url": '<svg viewBox="0 0 10 10"><rect width="10" height="10" style="fill: url(https://evil.example/a.svg#x); background: url(\'javascript:alert(1)\')" fill="url(https://evil.example/p.svg#p)"/><circle r="1" style="fill:red; behavior: expression(alert(1)); stroke: blue"/></svg>',19  "style element": '<svg viewBox="0 0 10 10"><style>@import url("https://evil.example/x.css"); rect { fill: url(https://evil.example) }</style><rect width="10" height="10"/></svg>',20  "external use": '<svg viewBox="0 0 10 10"><use href="https://evil.example/sprite.svg#a"/><use xlink:href="#local"/><rect id="local" width="1" height="1"/></svg>',21  animation: '<svg viewBox="0 0 10 10"><rect width="1" height="1"><animate attributeName="href" values="javascript:alert(1)"/><set attributeName="onclick" to="alert(1)"/></rect></svg>',22  "entity tricks": '<svg viewBox="0 0 10 10"><linearGradient id="g" href="&#106;avascript:alert(1)"/><rect width="1" height="1" fill="url(&#x6a;avascript:alert(1))"/></svg>',23  "unknown elements": '<svg viewBox="0 0 10 10"><metadata>x</metadata><filter id="f"><feImage href="https://evil.example/a.png"/></filter><rect width="1" height="1" filter="url(#f)" class="x" data-x="1"/></svg>',24};2526describe("sanitizeSvg", () => {27  for (const [name, markup] of Object.entries(HOSTILE)) {28    it(`neutralises: ${name}`, () => {29      const r = clean(markup);30      expect(r.removed.length).toBeGreaterThan(0);31      expect(SvgNodeSchema.safeParse(r.tree).success).toBe(true);32      const out = svgTreeToMarkup(r.tree);33      expect(out).not.toMatch(FORBIDDEN);34      const rendered = renderToStaticMarkup(createElement(SvgTree, { tree: r.tree, idPrefix: "p" }));35      expect(rendered).not.toMatch(FORBIDDEN);36      // The harmless shapes survive.37      expect(JSON.stringify(r.tree)).toMatch(/"tag":"(rect|circle|linearGradient)"/);38    });39  }4041  it("keeps a clean drawing intact and round-trips", () => {42    const markup = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50"><title>Titre</title><defs><linearGradient id="g" x1="0" x2="1"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f" stop-opacity="0.5"/></linearGradient><clipPath id="c"><rect width="50" height="50"/></clipPath></defs><g transform="translate(1 2)" clip-path="url(#c)"><path d="M0 0L10 10Z" fill="url(#g)" stroke="#000" stroke-width="2" stroke-linecap="round"/><text x="5" y="20" font-size="8" text-anchor="middle">A &amp; B <tspan font-weight="700">gras</tspan></text></g></svg>';43    const r = clean(markup);44    expect(r.removed).toEqual([]);45    const out = svgTreeToMarkup(r.tree);46    expect(out).toContain('fill="url(#g)"'); expect(out).toContain('clip-path="url(#c)"'); expect(out).toContain("A &amp; B");47    expect(clean(out).tree).toEqual(r.tree);48  });4950  it("rejects non-SVG input, empty input and oversize input", () => {51    expect(sanitizeSvg("").ok).toBe(false);52    expect(sanitizeSvg("<html><body>x</body></html>").ok).toBe(false);53    expect(sanitizeSvg("<svg/><svg/>").ok).toBe(false);54    expect(sanitizeSvg('<!DOCTYPE svg [<!ENTITY x "y">]><svg>&x;</svg>').ok).toBe(false);55    expect(sanitizeSvg(`<svg viewBox="0 0 1 1"><path d="${"M0 0L1 1".repeat(60000)}"/></svg>`).ok).toBe(false);56  });5758  it("derives a viewBox from width and height", () => {59    expect(clean('<svg width="40" height="20"><rect width="1" height="1"/></svg>').tree.attrs.viewBox).toBe("0 0 40 20");60  });6162  it("checks attributes one by one", () => {63    expect(safeSvgAttr("fill", "url(#a)")).toBe(true); expect(safeSvgAttr("fill", "url(#a) url(//x)")).toBe(false);64    expect(safeSvgAttr("href", "#a")).toBe(true); expect(safeSvgAttr("href", "//evil")).toBe(false); expect(safeSvgAttr("href", "#a onclick=1")).toBe(false);65    expect(safeSvgAttr("onmouseover", "x")).toBe(false); expect(safeSvgAttr("d", "M0 0 java\nscript:1")).toBe(false);66    expect(safeSvgAttr("class", "x")).toBe(false);67    expect(safeStyle("fill: red; position: fixed; stroke: url(#a); opacity: .5")).toEqual([["fill", "red"], ["opacity", ".5"]]);68  });69});7071describe("SvgTree (render-time checks on a stored tree)", () => {72  it("drops what a hand-written document could smuggle in", () => {73    const tree = { tag: "svg", attrs: { viewBox: "0 0 10 10", onload: "alert(1)" }, children: [74      { tag: "script", attrs: {}, children: ["alert(1)"] },75      { tag: "foreignObject", attrs: {}, children: [] },76      { tag: "rect", attrs: { width: "5", height: "5", onclick: "alert(1)", href: "https://evil.example", "xlink:href": "javascript:alert(1)", style: "fill: url(https://evil.example/x)", fill: "javascript:alert(1)", stroke: "red" }, children: [] },77      { tag: "circle", attrs: { r: "2", style: "fill: red; background: expression(1); @import 'x'" }, children: [] },78      { tag: "path", attrs: { d: "M0 0", id: "a", fill: "url(#b)" }, children: [] },79    ] } as unknown as SvgNode;80    const out = renderToStaticMarkup(createElement(SvgTree, { tree, idPrefix: "blk", title: "Alt" }));81    expect(out).not.toMatch(FORBIDDEN);82    expect(out).toContain('stroke="red"'); expect(out).toContain('id="blk-a"'); expect(out).toContain('fill="url(#blk-b)"');83    expect(out).toContain('role="img"'); expect(out).toContain("<title>Alt</title>");84    expect(out).not.toContain("alert");85  });86});87
Files main
Menu

Theme