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
8 changes: 7 additions & 1 deletion packages/compiler/src/shadow_css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1021,7 +1021,13 @@ const _commentWithHashPlaceHolderRe = new RegExp(COMMENT_PLACEHOLDER, 'g');

const BLOCK_PLACEHOLDER = '%BLOCK%';
const _ruleRe = new RegExp(
`(\\s*(?:${COMMENT_PLACEHOLDER}\\s*)*)([^;\\{\\}]+?)(\\s*)((?:{%BLOCK%}?\\s*;?)|(?:\\s*;))`,
// The lookahead (?=[^;{}]*[;{]) ensures the regex fails fast on malformed CSS
// that lacks a terminator, preventing O(k²) backtracking when many comment
// placeholders are followed by content with no closing `;' or `{'.
// Group 1 uses a flat alternation instead of nested \s* quantifiers.
// Group 2 requires a non-whitespace lead so the boundary with group 1 is
// unambiguous and the engine cannot redistribute spaces between the two groups.
`(?=[^;\{\}]*[;\{])((?:${COMMENT_PLACEHOLDER}|\s)*)([^;\{\}\s][^;\{\}]*?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))`,
'g',
);
const CONTENT_PAIRS = new Map([['{', '}']]);
Expand Down
16 changes: 16 additions & 0 deletions packages/compiler/test/shadow_css/process_rules_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,20 @@ describe('ShadowCss, processRules', () => {
).toEqual('a {b2}');
});
});

describe('ReDoS hardening', () => {
it('should complete in linear time with many comment placeholders and no terminator', () => {
// Regression test for polynomial backtracking in _ruleRe.
// Before the fix, a CSS string with k COMMENT placeholders followed by
// content without a `;' or `{' terminator caused O(k²) backtracking.
// The test verifies that processRules returns promptly; a hanging test
// is the observable symptom of the unfixed regex.
const manyComments = ' /* a comment */ '.repeat(200) + 'unclosed-selector';
const start = Date.now();
processRules(manyComments, (rule) => rule);
const elapsed = Date.now() - start;
// Should complete well under 1 second even with 200 comment tokens.
expect(elapsed).toBeLessThan(1000);
});
});
});
Loading