Skip to content

fix: enforce single-property validation in CSSStyleDeclaration.setProperty - #60

Open
JeanMeche wants to merge 1 commit into
angular:mainfrom
JeanMeche:fix/css-property-injection
Open

JeanMeche wants to merge 1 commit into
angular:mainfrom
JeanMeche:fix/css-property-injection

Conversation

@JeanMeche

Copy link
Copy Markdown
Member

Summary

Fixes CSS property injection in CSSStyleDeclaration.prototype.setProperty where values containing both ; and the substring data: bypassed the semicolon guard (if (value.includes(";") && !value.includes("data:")) return;), causing parseStyles(property + ":" + value) to parse and serialize multiple CSS declarations into the style attribute.

Changes

  • Replaced the substring data: check and multi-property parseStyles loop in CSSStyleDeclaration.prototype.setProperty with CSS Syntax Level 3–aligned single-declaration validation (isValidPropertyName and isValidStyleValue):
    • Rejects top-level ; (while still allowing semicolons inside valid strings, comments, balanced parentheses/brackets, and url(...) tokens such as url(data:image/png;base64,...)).
    • Rejects unbalanced or mismatched (), [], {} delimiters, unclosed quotes or comments, unescaped newlines in strings (<bad-string-token>), malformed unquoted url(...) tokens (where /* is not a comment), escaped function names (e.g. \75 rl(...)), trailing/invalid backslashes, and !important inside the value.
    • Validates the property name and writes only styles.property[property].
  • Added comprehensive unit tests in test/domino.js (styleSetPropertyValidation) covering both rejected injection/parser-differential payloads and legitimate CSS values.

@JeanMeche
JeanMeche force-pushed the fix/css-property-injection branch from 046c175 to 0f37c66 Compare November 24, 2026 22:27
@alan-agius4
alan-agius4 marked this pull request as ready for review November 25, 2026 07:55

@alan-agius4 alan-agius4 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for putting this fix together. The SIMPLE_VALUE_RE fast path is a nice win for common values, and moving .trim() inside if (value !== NO_CHANGE) also fixes an existing crash in setPropertyPriority().

There are a few things worth addressing before landing: a parser differential between isValidStyleValue and lib/style_parser.js when styles are reparsed, Object.prototype collisions on property names like constructor and __proto__, and a hot path perf/allocation regression on CSS function values (rgba(), calc(), var(), translate3d(), etc.).

See the inline comments for details.

}

const IMPORTANT_BANG = '!important';
const INVALID_PROPERTY_NAME_RE = /[\s:;'"(){}\[\]\/\\!]/;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things on property name handling:

  1. parseStyles() initializes property: {} and priority: {} as plain objects, so Object.prototype keys collide. Calling el.style.setProperty('constructor', 'red') reads inherited Object.prototype.constructor in _serialize() and emits style="constructor: red !function Object() { [native code] };". Also, el.style.setProperty('__proto__', 'red') regresses from returning early (getAttribute('style') === null) to writing style="", because isValidPropertyName('__proto__') passes and _serialize() still runs after the silent assignment. Can we initialize both with Object.create(null) in parseStyles()?
  2. Because INVALID_PROPERTY_NAME_RE is a denylist, it still accepts invalid CSS property names like '--', '123', '@import', 'a<b', and '\x00'. Since property is already lowercased in setProperty(), can we switch to an allowlist regex instead?
const VALID_PROPERTY_NAME_RE = /^(?:--[^\x00-\x20:;'"(){}\[\]\/\\!\x7f]+|-?[a-z_][a-z0-9_-]*)$/;

const CSS_WS_RE = /[ \t\n\r\f]+/y;
const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//y;
const CSS_STRING_RE = /"(?:\\(?:\r\n|[\s\S])|[^"\\\n\r\f])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\n\r\f])*'/y;
const CSS_IDENT_RE = /(?:[a-zA-Z0-9_-]|[^\x00-\x7f]|\\(?:[0-9a-fA-F]{1,6}(?:\r\n|[ \t\n\r\f])?|[^\n\r\f]))+/y;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of notes on the token regexes:

  1. Perf on data: URIs: In CSS_STRING_RE and CSS_UNQUOTED_URL_RE, the common unescaped branch has no + quantifier, so V8 loops per character through the alternation on every byte of a long URL or string. Unrolling them (e.g. "[^"\\\n\r\f]*(?:\\(?:\r\n|[\s\S])[^"\\\n\r\f]*)*" and (?:[^'"()\\ \t\n\r\f\x00-\x08\x0b\x0e-\x1f\x7f]+|\\[^\n\r\f])+) roughly halves validation latency on 1KB to 500KB data: URIs (~960 us down to ~487 us at 500KB) while keeping disjoint first sets (O(n)).
  2. Nit: [^\x00-\x7f] in CSS_IDENT_RE merges whitespace and punctuation above U+007F (like \u00a0 or \u200b) into a following url( token ("\u00a0url"), skipping the unquoted URL check. Current Blink still treats all >= U+0080 as ident code points so it does not trigger today, but CSS Syntax Level 3 narrowed non-ASCII ident code point to exclude these ranges. Tightening that range avoids a future engine differential.
  3. Minor: CSS_UNQUOTED_URL_RE (\\[^\n\r\f]) rejects valid hex escape plus consumed whitespace/newline URLs like url(a\20 b.png), and CSS_STRING_RE rejects "a\61\nb" (both accepted by Chrome).


// Whitespace (ignored for !important tracking)
CSS_WS_RE.lastIndex = i;
if (CSS_WS_RE.exec(value)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On SSR hot paths, SIMPLE_VALUE_RE gives a ~5 to 8x speedup over parseStyles on simple values, but values containing CSS functions (rgba(...), translate3d(...), calc(...), var(...), linear-gradient(...)) regress ~1.3 to 2.5x in validation (~1.05 to 1.41x end to end) and allocate up to 3.3x more heap (~2.4 KB/op on linear-gradient(...) + url(...)).

The main overhead in this loop comes from:

  1. Calling CSS_WS_RE.exec(value) on every character (even when it is not whitespace) and CSS_IDENT_RE.exec(value) on every punctuation character (,, ., %, /, #, !), allocating a match array and substring on every match, including inside parens where token is discarded.
  2. Using .exec() on CSS_COMMENT_RE, CSS_STRING_RE, CSS_QUOTED_URL_OPEN_RE, and CSS_UNQUOTED_URL_RE even though the return value is ignored. Switching to .test() still updates .lastIndex on /y regexes without allocating match arrays or slices, and value.indexOf('*/', i + 2) is much faster for comments.
  3. Eagerly allocating const stack = [] even when there are no brackets (16 / 9, "Helvetica Neue", url(data:...)).

Switching to .test() with charCodeAt guards, indexOf('*/', i + 2), and a lazy stack recovers ~2 to 2.6x on CSS functions (~1.25 to 1.4x end to end SSR) with ~0 B/op. Going a step further with a charCodeAt loop (similar to lib/style_parser.js, delegating quoted strings and unquoted url(...) to unrolled .test() regexes) gets ~5.7 to 6.7x on CSS functions while keeping the fast data: URI path.

Nit: SIMPLE_VALUE_RE also excludes / unconditionally, so 16 / 9 or 14px/1.5 take the slow path even though / only matters before *.

// Validate that `property` and `value` represent a single CSS declaration
// without top-level semicolons, unbalanced delimiters/quotes/comments, or
// trailing `!important` priority.
if (!isValidPropertyName(property) || !isValidStyleValue(value)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things here:

  1. Reparse differential with lib/style_parser.js: isValidStyleValue now accepts ; inside CSS comments (/* ; */), escaped semicolons (\;), escaped parens in unquoted url(...) (\)), escaped quotes (\"), and []/{} blocks. However, lib/style_parser.js (used whenever style is reparsed on HTML round trips, setAttribute('style', ...), or cssText) does not handle comments, []/{} nesting, unquoted url(...), or backslash escapes. In fact, style_parser.js lines 50 and 61 check value.charCodeAt(i - 1) !== 92 after i++, which inspects the quote itself instead of the preceding \. As a result, a value like setProperty('color', 'red /* ; position: fixed; --a: */') or setProperty('font-family', 'Foo\\; position: fixed') is accepted, gets split into separate properties on reparse, and if the original property is subsequently removed or updated, position: fixed; becomes a live CSS declaration. Can we update lib/style_parser.js to stay consistent with these tokenization rules (keeping a fast path when /, \, [, { are not present)?
  2. Perf: var styles = this._parsed; currently runs on line 331 before validation, so rejected calls on elements with unparsed styles still read getAttribute('style'), run parseStyles(), and delete this._names. Moving var styles = this._parsed; after this guard (and inside the value === NO_CHANGE branch) avoids that wasted work (~1.3 to 1.7x faster on rejected calls).

Comment thread test/domino.js
(a.getAttribute('style') === null).should.equal(true);
a.style.backgroundImage = 'url(data:image/png;base64,iVBORw0KGgo=)';
a.getAttribute('style').should.equal('background-image: url(data:image/png;base64,iVBORw0KGgo=);');
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also add tests for:

  1. Reparse round trips (domino.createDocument(el.outerHTML) followed by removeProperty/getPropertyValue) for values containing /* ; */, \;, \", \) in url(), [], and {}.
  2. Prototype and invalid property names ('constructor', '__proto__', '--', '123', '@import', '\x00').
  3. setPropertyPriority (covering the NO_CHANGE.trim() fix) and verifying a rejected setProperty does not overwrite an existing valid style attribute.
  4. Standalone / values (rgb(255 0 0 / 50%), calc(100% / 2)), /*/, and a large data: URI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants