Skip to content

Commit 41bdde6

Browse files
committed
throw a LimitError for the fixed limits of SVG rendering, and halve the base filter budget
1 parent 6dfdfa0 commit 41bdde6

6 files changed

Lines changed: 25 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ Upgrading from 3.x? Upgrade to the latest 3.x release first, fix the deprecation
114114

115115
### New
116116

117+
- `renderSVG()`'s fixed limits of work throw a `LimitError` like its options' limits (an `Error` in 3.x): elements drawn through `<use>` references, nested masks, clip paths, patterns, markers and filter images, and entity expansion. `LimitError` is a `RangeError`, so `catch` blocks that test for `Error` still catch them.
117118
- `GainMap.decode(data, { maxPixels })` takes the limit of `Image.decode()`, and the `LimitError` that these limits throw is exported (with `name` `'LimitError'`).
118119
- `rotate(angle, { expand: false })` keeps the image's size for quarter turns, too: the turned image is centered and what doesn't fit is cut off (they swapped width and height).
119120
- `renderSVG()` throws for masks, clip paths, patterns, markers and filter images nested in each other so deeply that they would multiply (three per level took minutes at ten levels), and stops at 24 `feTurbulence` octaves, which are all that its output can hold. Shapes far outside the image no longer make rendering hang.
@@ -175,7 +176,7 @@ Upgrading from 3.x? Upgrade to the latest 3.x release first, fix the deprecation
175176
- AVIF 4:2:0 images of an odd width decode the last column like libavif: it took the chroma of the column to its left too (off by up to 51).
176177
- `Animation.decode()` counts every frame as at least 1024 pixels of `maxPixels`: a frame takes memory however small it is, so a 4.6 MB GIF of 200000 frames of 1x1 took 720 MB.
177178
- `renderSVG()` bounds the work of markers: their elements count against the 100,000 elements of `<use>` references, and one render draws at most 10,000 markers (120,000 vertices with `marker-mid` took 135 s).
178-
- `renderSVG()` bounds the work of filters: their primitives may work on 2^26 pixels plus 16 per pixel of the output in one render (once per pass: an `feConvolveMatrix` per 9 taps of its kernel, an `feTurbulence` per octave, an `feMerge` per node), more throws a `LimitError`; a filter's region counts against `maxLayerPixels` like the other layers (one of more than 2^26 pixels was left out without a word) (600 blurs and morphologies over a megapixel, 37 KB of SVG, took more than 3 GB and minutes), and the results a filter keeps for `result=` references count against `maxLayerPixels`.
179+
- `renderSVG()` bounds the work of filters: their primitives may work on 2^25 pixels plus 16 per pixel of the output in one render (once per pass: an `feConvolveMatrix` per 9 taps of its kernel, an `feTurbulence` per octave, an `feMerge` per node), more throws a `LimitError`; a filter's region counts against `maxLayerPixels` like the other layers (one of more than 2^26 pixels was left out without a word) (600 blurs and morphologies over a megapixel, 37 KB of SVG, took more than 3 GB and minutes), and the results a filter keeps for `result=` references count against `maxLayerPixels`.
179180
- `renderSVG()` parses `transform` lists in linear time: a long list of unclosed functions took 4.8 s at 280 KB.
180181

181182
## 3.20.3

‎guides/Migrating to 4.0.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,10 @@ of a small SVG. The default is `4 * maxPixels`; an SVG over it throws a `RangeEr
344344
`maxPixels` (64 for the layers, up to 20 for the images, 4 for the output), so `maxPixels: 4096 ** 2` keeps rendering
345345
around 1.5 GB.
346346

347+
Its fixed limits of work (elements drawn through `<use>` references and markers, masks, clip paths, patterns and
348+
filter images nested inside each other, entity expansion, filters) throw a `LimitError` too, where 3.x threw an
349+
`Error`; code that tests for `Error` still catches them.
350+
347351
`Image.renderText()` takes `maxPixels` too (default `16383 ** 2`), which counts the outline (`strokeWidth`), checked
348352
before anything is allocated.
349353

‎src/image.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ export interface SVGResourceOptions {
494494
* small SVG takes. Exceeding it throws a {@link LimitError} (a RangeError). With the defaults, rendering can take about 90 bytes per pixel
495495
* of `maxPixels` (64 for the layers, up to 20 for the images, 4 for the output): lower `maxPixels` to bound it for
496496
* untrusted SVGs. Filters have a limit of their own that these options don't change: all the filters' primitives
497-
* together may work on 2²⁶ pixels plus 16 per pixel of the output (a primitive counts its region's pixels once
497+
* together may work on 2²⁵ pixels plus 16 per pixel of the output (a primitive counts its region's pixels once
498498
* per pass: an `feConvolveMatrix` per 9 taps of its kernel, an `feTurbulence` per octave, an `feMerge` per node),
499499
* else a {@link LimitError} is thrown
500500
* @defaultValue `4 * maxPixels`; `Infinity` disables the limit
@@ -2992,12 +2992,13 @@ export class Image {
29922992
* @param svg The SVG content
29932993
* @param options See {@link RenderSVGOptions}
29942994
* @return The rendered SVG graphic
2995-
* @throws {@link LimitError} if the output, the layers or the images exceed the limits of the options
2995+
* @throws {@link LimitError} if the output, the layers or the images exceed the limits of the options, or the SVG
2996+
* exceeds a fixed limit of the work it may take: more than 100000 elements drawn through `<use>` references and
2997+
* markers, more than 10000 markers, masks, clip paths, patterns, markers and filter images nested so deeply that
2998+
* they would multiply, entities that expand past the size limit, or filters past their budget
29962999
* @throws `RangeError` if the requested size is below 1 pixel (or a scale isn't above 0)
2997-
* @throws `Error` if the SVG can't be parsed (it has no `<svg>` element), an image in it can't be drawn (it isn't given
2998-
* or can't be decoded), masks, clip paths, patterns, markers and filter images are nested so deeply that they
2999-
* would multiply, or it draws more than 100000 elements through `<use>` references and markers or more than
3000-
* 10000 markers
3000+
* @throws `Error` if the SVG can't be parsed (it has no `<svg>` element) or an image in it can't be drawn (it isn't
3001+
* given or can't be decoded)
30013002
*/
30023003
static renderSVG(svg: string | BinaryData, options?: RenderSVGOptions): Promise<Image>;
30033004
static async renderSVG(svg: string | BinaryData, options: RenderSVGOptions = {}): Promise<Image> {

‎src/render/svg.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,7 @@ function parseXML(text: string): XNode {
386386
rest = rest.replace(/&([\w.-]+);/g, (match: string, name: string): string => {
387387
if (!(name in custom)) return match;
388388
size += custom[name].length - match.length;
389-
if (size > limit) throw new Error('SVG: entity expansion exceeds the size limit');
389+
if (size > limit) throw new LimitError('SVG too complex: entity expansion exceeds the size limit');
390390
return custom[name];
391391
});
392392
}
@@ -738,9 +738,9 @@ const MAX_CROSSINGS = 2 ** 27;
738738
// what is left of it in the render that runs (rendering is synchronous), unlimited outside of one
739739
let crossingsLeft = Infinity;
740740
// the most pixels the primitives of filters work on in one render (a primitive takes about 0.15 s per megapixel):
741-
// 2^26 and 16 per pixel of the output, so a small SVG with hundreds of primitives (it took minutes) stops after about
742-
// 10 s while a drop shadow on a large image has room (the time it allows grows with the output's size). What is left of it in the render that runs
743-
const MAX_FILTER_WORK = 2 ** 26, FILTER_WORK_PER_PIXEL = 16;
741+
// 2^25 and 16 per pixel of the output, so a small SVG with hundreds of primitives (it took minutes) stops after about
742+
// 5 s while a drop shadow on a large image has room (the time it allows grows with the output's size). What is left of it in the render that runs
743+
const MAX_FILTER_WORK = 2 ** 25, FILTER_WORK_PER_PIXEL = 16;
744744
let filterWorkLeft = Infinity;
745745
// the work of filters, and the results they keep, against the render's budgets
746746
const filterBudget: FilterBudget = {
@@ -941,7 +941,7 @@ class Document {
941941
renderNode(node: XNode, context: Context, root = false): void {
942942
if (!node.svg || UNSUPPORTED.has(node.name) || context.depth > 32 || !this.passesConditions(node)) return;
943943
// <use> references can multiply each other ("billion laughs"), markers repeat at every vertex: their elements are counted
944-
if (context.instanced && ++this.budget.instances > MAX_INSTANCES) throw new Error(`SVG: more than ${MAX_INSTANCES} elements rendered through <use> references, markers or embedded SVGs`);
944+
if (context.instanced && ++this.budget.instances > MAX_INSTANCES) throw new LimitError(`SVG too complex: more than ${MAX_INSTANCES} elements rendered through <use> references, markers or embedded SVGs`);
945945

946946
const style = this.computeStyle(node, context.style);
947947
if (style.display === 'none') return;
@@ -1699,7 +1699,7 @@ class Document {
16991699

17001700
// (a marker is rendered at every vertex: its elements count like those of <use> references, and the
17011701
// markers themselves too, each a render of its own)
1702-
if (++this.budget.markers > MAX_MARKERS) throw new Error(`SVG: more than ${MAX_MARKERS} markers`);
1702+
if (++this.budget.markers > MAX_MARKERS) throw new LimitError(`SVG too complex: more than ${MAX_MARKERS} markers`);
17031703
const inner = { ...ctx, matrix, style: markerStyle, depth: ctx.depth + 1, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : ctx.viewport, contextElement, instanced: true };
17041704
this.active.add(marker);
17051705
this.indirect(0, () => {
@@ -2378,7 +2378,7 @@ class Document {
23782378
indirect<T>(pixels: number, render: () => T): T {
23792379
const budget = this.budget;
23802380
if (budget.nesting > 0 && (budget.nested += Math.max(pixels, MIN_NESTED)) > MAX_NESTED)
2381-
throw new Error('SVG: too many masks, clip paths, patterns, markers or filter images inside each other');
2381+
throw new LimitError('SVG too complex: too many masks, clip paths, patterns, markers or filter images inside each other');
23822382
budget.nesting++;
23832383
try {
23842384
return render();

‎tests/regressions.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ const rgba = (image, x, y) => Colors.toRGBA(image.getPixelAt(x, y));
218218
const svg = `<!DOCTYPE svg [${dtd}]><svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><desc>${'&e4;'.repeat(50)}</desc></svg>`;
219219
let error = null;
220220
try { await Image.renderSVG(svg); } catch (err) { error = err; }
221-
assert(error instanceof Error, 'SVG: entity expansion should be limited');
221+
assert(error instanceof LimitError, `SVG: entity expansion should be limited with a LimitError (${error})`);
222222
}
223223

224224
// resizing filters average instead of skipping pixels, in premultiplied alpha
@@ -981,7 +981,7 @@ const rgba = (image, x, y) => Colors.toRGBA(image.getPixelAt(x, y));
981981
for (let i = 1; i <= 9; i++) defs += `<g id="l${i}">${`<use href="#l${i - 1}"/>`.repeat(10)}</g>`;
982982
let start = Date.now(), error = null;
983983
try { await Image.renderSVG(`<svg ${NS} width="100" height="100"><defs>${defs}</defs><use href="#l9"/></svg>`, {width: 100}); } catch (err) { error = err; }
984-
assert(error instanceof Error && Date.now() - start < 10000, `billion laughs should throw quickly (${error && error.message}, ${Date.now() - start} ms)`);
984+
assert(error instanceof LimitError && Date.now() - start < 10000, `billion laughs should throw quickly (${error && error.message}, ${Date.now() - start} ms)`);
985985

986986
start = Date.now();
987987
const dashed = await Image.renderSVG(`<svg ${NS} width="100" height="100"><path d="M0 50 L100000000 50" stroke="black" stroke-width="4" stroke-dasharray="0.0001"/></svg>`, {width: 100});

‎tests/svg-dos.js‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ const timed = async (name, svg, limit = 5000) => {
113113
const ordinary = await timed(`${name}, 3 levels`, `<svg ${NS} width="100" height="100">${vector(3)}</svg>`);
114114
if (ordinary.error) panic(`${name}, 3 levels: ${ordinary.error.message}`);
115115
const {error} = await timed(`${name}, 14 levels`, `<svg ${NS} width="100" height="100">${vector(14)}</svg>`, 30000);
116-
if (!(error instanceof Error)) panic(`${name}, 14 levels: should throw (${error})`);
116+
if (!error || error.name !== 'LimitError') panic(`${name}, 14 levels: should throw a LimitError (${error})`);
117117
}
118118
}
119119

@@ -172,7 +172,7 @@ const timed = async (name, svg, limit = 5000) => {
172172
try { await Image.renderSVG(chain(600)); } catch (err) { error = err; }
173173
const time = Date.now() - start;
174174
if (!error || error.name !== 'LimitError') panic(`filter chain: expected a LimitError, got ${error} after ${time} ms`);
175-
if (time > 15000 * slack) panic(`filter chain: took ${time} ms`);
175+
if (time > 30000 * slack) panic(`filter chain: took ${time} ms`);
176176
error = null;
177177
try { await Image.renderSVG(chain(8), {maxLayerPixels: 4e6}); } catch (err) { error = err; }
178178
if (!error || error.name !== 'LimitError') panic(`filter chain within maxLayerPixels: expected a LimitError, got ${error}`);
@@ -215,7 +215,7 @@ const timed = async (name, svg, limit = 5000) => {
215215
const begin = Date.now();
216216
error = null;
217217
try { await Image.renderSVG(markers); } catch (err) { error = err; }
218-
if (!error || !/markers/.test(error.message) || Date.now() - begin > 30000 * slack) panic(`120000 markers: expected the marker limit within 30 s, got ${error} after ${Date.now() - begin} ms`);
218+
if (!error || error.name !== 'LimitError' || !/markers/.test(error.message) || Date.now() - begin > 30000 * slack) panic(`120000 markers: expected the marker limit within 30 s, got ${error} after ${Date.now() - begin} ms`);
219219
}
220220
// a real filter on a large image still renders
221221
const shadow = await Image.renderSVG(`<svg ${NS} width="2000" height="2000"><filter id="s"><feGaussianBlur in="SourceAlpha" stdDeviation="8"/><feOffset dx="10" dy="10" result="b"/><feFlood flood-color="#0004"/><feComposite in2="b" operator="in"/><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter><rect x="100" y="100" width="1700" height="1700" fill="red" filter="url(#s)"/></svg>`);

0 commit comments

Comments
 (0)