Repository navigation
Conversation
046c175 to
0f37c66
Compare
alan-agius4
left a comment
There was a problem hiding this comment.
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:;'"(){}\[\]\/\\!]/; |
There was a problem hiding this comment.
Two things on property name handling:
parseStyles()initializesproperty: {}andpriority: {}as plain objects, soObject.prototypekeys collide. Callingel.style.setProperty('constructor', 'red')reads inheritedObject.prototype.constructorin_serialize()and emitsstyle="constructor: red !function Object() { [native code] };". Also,el.style.setProperty('__proto__', 'red')regresses from returning early (getAttribute('style') === null) to writingstyle="", becauseisValidPropertyName('__proto__')passes and_serialize()still runs after the silent assignment. Can we initialize both withObject.create(null)inparseStyles()?- Because
INVALID_PROPERTY_NAME_REis a denylist, it still accepts invalid CSS property names like'--','123','@import','a<b', and'\x00'. Sincepropertyis already lowercased insetProperty(), 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; |
There was a problem hiding this comment.
A couple of notes on the token regexes:
- Perf on
data:URIs: InCSS_STRING_REandCSS_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 500KBdata:URIs (~960 us down to ~487 us at 500KB) while keeping disjoint first sets (O(n)). - Nit:
[^\x00-\x7f]inCSS_IDENT_REmerges whitespace and punctuation above U+007F (like\u00a0or\u200b) into a followingurl(token ("\u00a0url"), skipping the unquoted URL check. Current Blink still treats all>= U+0080as ident code points so it does not trigger today, but CSS Syntax Level 3 narrowednon-ASCII ident code pointto exclude these ranges. Tightening that range avoids a future engine differential. - Minor:
CSS_UNQUOTED_URL_RE(\\[^\n\r\f]) rejects valid hex escape plus consumed whitespace/newline URLs likeurl(a\20 b.png), andCSS_STRING_RErejects"a\61\nb"(both accepted by Chrome).
|
|
||
| // Whitespace (ignored for !important tracking) | ||
| CSS_WS_RE.lastIndex = i; | ||
| if (CSS_WS_RE.exec(value)) { |
There was a problem hiding this comment.
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:
- Calling
CSS_WS_RE.exec(value)on every character (even when it is not whitespace) andCSS_IDENT_RE.exec(value)on every punctuation character (,,.,%,/,#,!), allocating a match array and substring on every match, including inside parens wheretokenis discarded. - Using
.exec()onCSS_COMMENT_RE,CSS_STRING_RE,CSS_QUOTED_URL_OPEN_RE, andCSS_UNQUOTED_URL_REeven though the return value is ignored. Switching to.test()still updates.lastIndexon/yregexes without allocating match arrays or slices, andvalue.indexOf('*/', i + 2)is much faster for comments. - 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)) { |
There was a problem hiding this comment.
Two things here:
- Reparse differential with
lib/style_parser.js:isValidStyleValuenow accepts;inside CSS comments (/* ; */), escaped semicolons (\;), escaped parens in unquotedurl(...)(\)), escaped quotes (\"), and[]/{}blocks. However,lib/style_parser.js(used wheneverstyleis reparsed on HTML round trips,setAttribute('style', ...), orcssText) does not handle comments,[]/{}nesting, unquotedurl(...), or backslash escapes. In fact,style_parser.jslines 50 and 61 checkvalue.charCodeAt(i - 1) !== 92afteri++, which inspects the quote itself instead of the preceding\. As a result, a value likesetProperty('color', 'red /* ; position: fixed; --a: */')orsetProperty('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 updatelib/style_parser.jsto stay consistent with these tokenization rules (keeping a fast path when/,\,[,{are not present)? - Perf:
var styles = this._parsed;currently runs on line 331 before validation, so rejected calls on elements with unparsed styles still readgetAttribute('style'), runparseStyles(), and deletethis._names. Movingvar styles = this._parsed;after this guard (and inside thevalue === NO_CHANGEbranch) avoids that wasted work (~1.3 to 1.7x faster on rejected calls).
| (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=);'); | ||
| }; |
There was a problem hiding this comment.
Can we also add tests for:
- Reparse round trips (
domino.createDocument(el.outerHTML)followed byremoveProperty/getPropertyValue) for values containing/* ; */,\;,\",\)inurl(),[], and{}. - Prototype and invalid property names (
'constructor','__proto__','--','123','@import','\x00'). setPropertyPriority(covering theNO_CHANGE.trim()fix) and verifying a rejectedsetPropertydoes not overwrite an existing validstyleattribute.- Standalone
/values (rgb(255 0 0 / 50%),calc(100% / 2)),/*/, and a largedata:URI.
Summary
Fixes CSS property injection in
CSSStyleDeclaration.prototype.setPropertywhere values containing both;and the substringdata:bypassed the semicolon guard (if (value.includes(";") && !value.includes("data:")) return;), causingparseStyles(property + ":" + value)to parse and serialize multiple CSS declarations into thestyleattribute.Changes
data:check and multi-propertyparseStylesloop inCSSStyleDeclaration.prototype.setPropertywith CSS Syntax Level 3–aligned single-declaration validation (isValidPropertyNameandisValidStyleValue):;(while still allowing semicolons inside valid strings, comments, balanced parentheses/brackets, andurl(...)tokens such asurl(data:image/png;base64,...)).(),[],{}delimiters, unclosed quotes or comments, unescaped newlines in strings (<bad-string-token>), malformed unquotedurl(...)tokens (where/*is not a comment), escaped function names (e.g.\75 rl(...)), trailing/invalid backslashes, and!importantinside the value.styles.property[property].test/domino.js(styleSetPropertyValidation) covering both rejected injection/parser-differential payloads and legitimate CSS values.