Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 176 additions & 29 deletions lib/CSSStyleDeclaration.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,166 @@ function CSSStyleDeclaration(elt) {
}

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 SIMPLE_VALUE_RE = /^[^;'"()[\]{}/\\!]+$/;

// Sticky CSS Syntax Level 3 token matchers (disjoint first-sets -> O(n), no ReDoS)
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).

const CSS_QUOTED_URL_OPEN_RE = /\([ \t\n\r\f]*(?=['"])/y;
const CSS_UNQUOTED_URL_RE = /\([ \t\n\r\f]*(?:(?:\\[^\n\r\f]|[^'"()\\ \t\n\r\f\x00-\x08\x0b\x0e-\x1f\x7f])+[ \t\n\r\f]*)?\)/y;
const MATCHING_CLOSE = { '(': ')', '[': ']', '{': '}' };

function isValidPropertyName(property) {
return property.length > 0 && !INVALID_PROPERTY_NAME_RE.test(property);
}

/**
* Validates that a CSS property value represents a single declaration value
* without top-level semicolons, unbalanced delimiters/quotes/comments,
* malformed tokens, or trailing `!important` priority.
*/
function isValidStyleValue(value) {
if (SIMPLE_VALUE_RE.test(value)) {
return true;
}

const len = value.length;
const stack = [];
let prevToken = '';
let lastToken = '';
let i = 0;

while (i < len) {
const ch = value[i];

// 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 *.

i = CSS_WS_RE.lastIndex;
continue;
}

// CSS comment: /* ... */ (unclosed /* is invalid)
if (ch === '/' && value[i + 1] === '*') {
CSS_COMMENT_RE.lastIndex = i;
if (!CSS_COMMENT_RE.exec(value)) {
return false;
}
i = CSS_COMMENT_RE.lastIndex;
continue;
}

// String token: "..." or '...' (unclosed or unescaped newline is invalid)
if (ch === '"' || ch === "'") {
CSS_STRING_RE.lastIndex = i;
if (!CSS_STRING_RE.exec(value)) {
return false;
}
if (stack.length === 0) {
prevToken = lastToken;
lastToken = '"';
}
i = CSS_STRING_RE.lastIndex;
continue;
}

// Top-level semicolon is invalid in a single-property value
if (ch === ';' && stack.length === 0) {
return false;
}

// Brackets: (), [], {}
if (ch === '(' || ch === '[' || ch === '{') {
stack.push(MATCHING_CLOSE[ch]);
if (stack.length === 1) {
prevToken = lastToken;
lastToken = ch;
}
i++;
continue;
}
if (ch === ')' || ch === ']' || ch === '}') {
if (stack.length === 0 || stack.pop() !== ch) {
return false;
}
if (stack.length === 0) {
prevToken = lastToken;
lastToken = ch;
}
i++;
continue;
}

// Ident / number / dimension / escape sequence
CSS_IDENT_RE.lastIndex = i;
const identMatch = CSS_IDENT_RE.exec(value);
if (identMatch) {
const token = identMatch[0];
i = CSS_IDENT_RE.lastIndex;

if (value[i] === '(') {
// Reject escaped function names (e.g. `\75 rl(...)`) that could disguise a <url-token>
if (token.includes('\\')) {
return false;
}
if (token.toLowerCase() === 'url') {
CSS_QUOTED_URL_OPEN_RE.lastIndex = i;
if (CSS_QUOTED_URL_OPEN_RE.exec(value)) {
stack.push(')');
if (stack.length === 1) {
prevToken = lastToken;
lastToken = 'url(';
}
i = CSS_QUOTED_URL_OPEN_RE.lastIndex;
continue;
}
CSS_UNQUOTED_URL_RE.lastIndex = i;
if (!CSS_UNQUOTED_URL_RE.exec(value)) {
return false;
}
if (stack.length === 0) {
prevToken = lastToken;
lastToken = 'url()';
}
i = CSS_UNQUOTED_URL_RE.lastIndex;
continue;
}
}

if (stack.length === 0) {
prevToken = lastToken;
lastToken = token;
}
continue;
}

// Trailing or invalid backslash escape (e.g., `\` at EOF or `\` + newline)
if (ch === '\\') {
return false;
}

// Other punctuation / delimiters
if (stack.length === 0) {
prevToken = lastToken;
lastToken = ch;
}
i++;
}

if (stack.length !== 0) {
return false;
}

// Reject trailing `!important` (including escaped forms like `!\69 mportant`)
if (prevToken === '!' && (lastToken.toLowerCase() === 'important' || lastToken.includes('\\'))) {
return false;
}

return true;
}

// Utility function for parsing style declarations
// Pass in a string like "margin-left: 5px; border-style: solid"
Expand Down Expand Up @@ -156,13 +316,11 @@ CSSStyleDeclaration.prototype = Object.create(Object.prototype, {

// String coercion
if (value !== NO_CHANGE) {
value = "" + value;
}

value = value.trim();
if (value === "") {
this.removeProperty(property);
return;
value = ("" + value).trim();
if (value === "") {
this.removeProperty(property);
return;
}
}

if (priority !== "" && priority !== NO_CHANGE &&
Expand All @@ -181,30 +339,19 @@ CSSStyleDeclaration.prototype = Object.create(Object.prototype, {
delete styles.priority[property];
}
} else {
// We don't just accept the property value. Instead
// we parse it to ensure that it is something valid.
// If it contains a semicolon it is invalid, except base64-encoded
// URLs (e.g. `background-image: url(data:image/png;base64,...`)
if (value.includes(";") && !value.includes("data:")) return;

var newprops = parseStyles(property + ":" + value);
if (Object.getOwnPropertyNames(newprops.property).length === 0) {
return; // no valid property found
// 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).

return;
}
if (Object.getOwnPropertyNames(newprops.priority).length !== 0) {
return; // if the value included '!important' it wasn't valid.
}

// XXX handle shorthand properties

for (var p in newprops.property) {
styles.property[p] = newprops.property[p];
if (priority === NO_CHANGE) {
continue;
} else if (priority !== "") {
styles.priority[p] = "important";
} else if (styles.priority[p]) {
delete styles.priority[p];
styles.property[property] = value;
if (priority !== NO_CHANGE) {
if (priority !== "") {
styles.priority[property] = "important";
} else if (styles.priority[property]) {
delete styles.priority[property];
}
}
}
Expand Down
124 changes: 124 additions & 0 deletions test/domino.js
Original file line number Diff line number Diff line change
Expand Up @@ -2638,3 +2638,127 @@ exports.nativeEventDispatch = function() {
createdKeyEvent.type.should.equal('keyup');
createdKeyEvent.key.should.equal('a');
};

exports.styleSetPropertyValidation = function() {
function setStyle(prop, val, priority) {
var doc = domino.createDocument('<div></div>');
var el = doc.querySelector('div');
if (priority !== undefined) {
el.style.setProperty(prop, val, priority);
} else {
el.style.setProperty(prop, val);
}
return el.getAttribute('style');
}

// Reject multi-property injection (including `data:` guard bypasses and parser differentials)
var rejected = [
// data: substring bypasses
['color', "red; position: fixed; inset: 0px; z-index: 2147483647; background-image: url('https://attacker.example/phish.png?data:')"],
['width', '100px; position: fixed; top: 10px; z-index: 2147483646; --bypass: data:; --pad: 1px'],
['--accent', 'blue; position: fixed; top: 20px; z-index: 2147483645; --bypass: data:'],
// Top-level semicolons
['color', 'red; position: fixed'],
['color', 'red;'],
['color', '; position: fixed'],
['color', 'red; color: blue'],
['background-image', 'url(data:image/png;base64,AAA); position: fixed'],
['background-image', 'url("data:image/png;base64,AAA"); position: fixed'],
// Parentheses inside quotes / unmatched delimiters
['color', "'(' ; position: fixed"],
['color', '"(" ; position: fixed'],
['background-image', 'url("("); position: fixed'],
['color', 'red) ; position: fixed'],
['color', 'red] ; position: fixed'],
['color', 'red} ; position: fixed'],
['color', 'rgb(1, 2'],
['grid-template-columns', '[main-start'],
['--x', '{'],
['--x', '([)]'],
// Unclosed strings, escaped backslashes before closing quote, unescaped newlines in strings
['content', '"hello'],
['content', "'hello"],
['content', '"hello\\"'],
['content', '"foo\\\\" ; position: fixed'],
['content', "'foo\\\\' ; position: fixed"],
['content', '"foo\n; position: fixed; --x: "'],
['content', '"foo\r; position: fixed; --x: "'],
['content', '"foo\f; position: fixed; --x: "'],
['content', "'foo\n; position: fixed; --x: '"],
// CSS comments
['color', "/* ' */ ; position: fixed"],
['color', '/* ( */ ; position: fixed'],
['color', 'red /* unclosed comment'],
// Unquoted url(...) parser differentials
['background-image', 'url(https://example.com/*); position: fixed; --a: /* */ )'],
['background-image', "url(https://example.com/'foo); position: fixed; --a: '"],
['background-image', 'url(https://example.com/"foo); position: fixed; --a: "'],
['background-image', 'url(https://example.com/(foo); position: fixed; --a: )'],
['background-image', 'url(https://example.com/a b)'],
['background-image', 'url(https://example.com/a\nb)'],
['background-image', 'url(data:image/png;base64,AAA'],
// Escaped url( obfuscation
['background-image', '\\75 rl(https://example.com/*); position: fixed; --a: /* */ )'],
['background-image', '\\75\\72\\6c(https://example.com/*); position: fixed; --a: /* */ )'],
// Trailing / invalid backslashes
['color', 'red\\'],
['color', 'red\\\\\\'],
['color', 'red\\\n; position: fixed'],
// !important inside value
['color', 'red !important'],
['color', 'red !IMPORTANT'],
['color', 'red ! important'],
['color', 'red !/*c*/important /* trailing */'],
['color', 'red !\\69 mportant'],
// Invalid property names
['color: red; position', 'fixed'],
['color; position', 'fixed'],
['', 'red'],
];

rejected.forEach(function(entry) {
(setStyle(entry[0], entry[1]) === null).should.equal(true);
});

// Accept legitimate single-property CSS values (including semicolons inside strings/urls/parens/comments)
var accepted = [
['color', 'red', 'color: red;'],
['width', '100px', 'width: 100px;'],
['width', 'calc(100% - 20px)', 'width: calc(100% - 20px);'],
['color', 'var(--my-color, rgba(0, 0, 0, 0.5))', 'color: var(--my-color, rgba(0, 0, 0, 0.5));'],
['background-image', 'url(data:image/png;base64,iVBORw0KGgo=)', 'background-image: url(data:image/png;base64,iVBORw0KGgo=);'],
['background-image', 'URL(data:image/png;base64,iVBORw0KGgo=)', 'background-image: URL(data:image/png;base64,iVBORw0KGgo=);'],
['background-image', 'url( data:image/svg+xml;charset=utf-8,%3Csvg%3E%3C/svg%3E )', 'background-image: url( data:image/svg+xml;charset=utf-8,%3Csvg%3E%3C/svg%3E );'],
['background-image', 'url("data:image/png;base64,iVBORw0KGgo=")', 'background-image: url("data:image/png;base64,iVBORw0KGgo=");'],
['background-image', "url('data:image/png;base64,iVBORw0KGgo=')", "background-image: url('data:image/png;base64,iVBORw0KGgo=');"],
['background-image', 'url("https://example.com/a;b=1")', 'background-image: url("https://example.com/a;b=1");'],
['background-image', 'url("foo\\"bar;baz")', 'background-image: url("foo\\"bar;baz");'],
['background-image', 'url("foo\\\\")', 'background-image: url("foo\\\\");'],
['background-image', 'url()', 'background-image: url();'],
['background-image', 'linear-gradient(to right, red, blue), url(data:image/png;base64,AAA)', 'background-image: linear-gradient(to right, red, blue), url(data:image/png;base64,AAA);'],
['content', '"a; b"', 'content: "a; b";'],
['content', "'hello; world'", "content: 'hello; world';"],
['content', '"foo !important"', 'content: "foo !important";'],
['font-family', '"Helvetica Neue", Arial, sans-serif', 'font-family: "Helvetica Neue", Arial, sans-serif;'],
['grid-template-columns', '[main-start] 1fr [main-end]', 'grid-template-columns: [main-start] 1fr [main-end];'],
['color', 'red /* comment ; with semicolon */', 'color: red /* comment ; with semicolon */;'],
['--custom', '"a; b"', '--custom: "a; b";'],
['--custom', '(a; b)', '--custom: (a; b);'],
['font-family', 'Foo\\;Bar', 'font-family: Foo\\;Bar;'],
];

accepted.forEach(function(entry) {
setStyle(entry[0], entry[1]).should.equal(entry[2]);
});

// Explicit priority argument still works
setStyle('color', 'red', 'important').should.equal('color: red !important;');

// Proxy property assignment enforces the same validation
var doc = domino.createDocument('<a id="badge">hi</a>');
var a = doc.getElementById('badge');
a.style.color = "red; position: fixed; inset: 0px; z-index: 2147483647; background-image: url('https://attacker.example/phish.png?data:')";
(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.

Loading