Repository navigation
css: bound selector expansion when compiling nesting for older targets #31278
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import { cssInternals } from "bun:internal-for-testing"; | ||
| import { expect, test } from "bun:test"; | ||
| import { bunEnv, bunExe, tempDir } from "harness"; | ||
| import path from "node:path"; | ||
|
|
||
| const { minifyTest } = cssInternals; | ||
|
|
||
| // Regression test for unbounded memory growth when compiling CSS nesting away | ||
| // for older browser targets. | ||
| // | ||
| // Compiling nesting multiplies selectors: every selector of a nested rule is | ||
| // combined with every selector of every ancestor rule, either by splitting | ||
| // rules apart during minification (targets without `:is()` support, which | ||
| // includes `bun build`'s default browser targets) or by substituting `&` with | ||
| // `:is(<parent list>)` while printing (targets with `:is()` but without CSS | ||
| // nesting). The expansion is the product of the selector list lengths along | ||
| // the nesting chain, so ~1KB of adversarial CSS — 26 nested two-selector | ||
| // `::part()` lists — demanded 2^26 selector combinations and grew past 4GB of | ||
| // memory. Such rules are now rejected with an error once they exceed 65536 | ||
| // combinations instead of exhausting memory. | ||
|
|
||
| const EXPANSION_ERROR = "selector combinations"; | ||
|
|
||
| // Two selectors per nesting level; `::part()` cannot be wrapped in `:is()`, so | ||
| // downleveling must combine every parent selector with every child selector. | ||
| function nestedPartLists(depth: number): string { | ||
| return ".foo::part(header), .foo::part(body) {\n".repeat(depth) + "display: none\n}"; | ||
| } | ||
|
|
||
| async function buildCSS(name: string, css: string) { | ||
| using dir = tempDir("css-nesting-expansion-limit", { [name]: css }); | ||
| const outdir = path.join(String(dir), "out"); | ||
| await using proc = Bun.spawn({ | ||
| cmd: [bunExe(), "build", path.join(String(dir), name), "--outdir", outdir], | ||
| env: bunEnv, | ||
| cwd: String(dir), | ||
| stdout: "pipe", | ||
| stderr: "pipe", | ||
| // Kill switch: before the fix this build allocated gigabytes while | ||
| // expanding 2^26 selector combinations. Let the child terminate itself so | ||
| // a regression fails the assertions below instead of exhausting memory. | ||
| timeout: 15_000, | ||
| killSignal: "SIGKILL", | ||
| }); | ||
| const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); | ||
| return { stdout, stderr, exitCode }; | ||
| } | ||
|
|
||
| test("nested multi-selector lists error instead of exhausting memory when splitting for old targets", () => { | ||
| // chrome 87 has no `:is()` support, so every nested rule is split into one | ||
| // rule per selector, cloning its nested subtree each time: 2^19 rules. | ||
| expect(() => minifyTest(nestedPartLists(19), "", { chrome: 87 << 16 })).toThrow(EXPANSION_ERROR); | ||
| }); | ||
|
|
||
| test("nested multi-selector lists error instead of exhausting memory when compiling nesting with :is()", () => { | ||
| // chrome 100 supports `:is()` but not CSS nesting, so `&` is substituted | ||
| // with `:is(<parent list>)` at print time, doubling the output per level. | ||
| expect(() => minifyTest(nestedPartLists(18), "", { chrome: 100 << 16 })).toThrow(EXPANSION_ERROR); | ||
| }); | ||
|
|
||
| test("bun build rejects exponential nesting expansion instead of running out of memory", async () => { | ||
| // The fuzzer-reported input: 26 nested two-selector `::part()` lists (~1KB) | ||
| // built with bun build's default browser targets. | ||
| const { stderr, exitCode } = await buildCSS("part-nesting.css", nestedPartLists(26)); | ||
| expect(stderr).toContain(EXPANSION_ERROR); | ||
| expect(exitCode).toBe(1); | ||
| }); | ||
|
|
||
| test("shallow nested multi-selector lists still expand for old targets", () => { | ||
| const output = minifyTest(nestedPartLists(3), "", { chrome: 87 << 16 }); | ||
| // The cartesian product is still produced when it is small. | ||
| expect(output).toContain(".foo::part(header) .foo::part(header)"); | ||
| expect(output).toContain(".foo::part(body) .foo::part(body)"); | ||
| expect(output).toContain("display:none"); | ||
| }); | ||
|
|
||
| test("deep nesting with single-selector lists does not hit the limit", () => { | ||
| // The expansion is the product of selector list lengths, so single-selector | ||
| // lists stay linear no matter how deep they nest. | ||
| const input = ".foo::part(header) {\n".repeat(40) + "display: none\n}"; | ||
| const output = minifyTest(input, "", { chrome: 87 << 16 }); | ||
| expect(output).toContain("display:none"); | ||
| }); | ||
|
|
||
| test("deeply nested multi-selector lists are fine when no targets are configured", () => { | ||
| // Without browser targets nothing is downleveled, so nesting is preserved | ||
| // as written and no expansion takes place. | ||
| const output = minifyTest(nestedPartLists(26), "", ""); | ||
| expect(output).toContain("&"); | ||
| expect(output).toContain("display:none"); | ||
| }); | ||
|
|
||
| test("deeply nested multi-selector lists are fine when targets support CSS nesting", () => { | ||
| const output = minifyTest(nestedPartLists(26), "", { chrome: 130 << 16 }); | ||
| expect(output).toContain("display:none"); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟣 Heads-up (pre-existing, not introduced here): the path-2 check is gated on
MinifyOptions.targets, but the print-time&-substitution it guards usesPrinterOptions.targets, andtranspiler.rs::build_css_output(thebun build --no-bundle file.csspath) callsminify(&MinifyOptions::default())— no targets, so the check is skipped — and thento_csswithTargets::for_bundler_target(...), which does compile nesting away. The exponential expansion is therefore still unguarded on that path. The primarybun build/ParseTask.rspath is correctly protected; consider either havingtranspiler.rspassfor_bundler_target()tominify()the wayParseTask.rs:1260does, or running the cheap O(rules)exceeds_nesting_expansion_limitcheck unconditionally.Extended reasoning...
The new path-2 guard at
css_parser.rs:2682-2691runs only whenoptions.targets.should_compile_same(compat::Feature::Nesting)is true, whereoptionsis theMinifyOptionspassed toStyleSheet::minify. Its purpose is to bound the print-time&-substitution explosion inserialize_nesting, but the printer decides whether to compile nesting based onPrinterOptions.targets, which callers supply independently. So the guard is sound only under the implicit contract "minify targets == print targets", and at least one in-tree caller violates that contract.Concrete code path.
src/bundler/transpiler.rs:3240callssheet.minify(alloc, &MinifyOptions::default(), &extra). WithMinifyOptions::default(),targets.browsers = Noneandinclude/excludeare empty. Intargets.rs:152-156,is_compatible(Nesting)returnstruewhenbrowsersisNone, soshould_compile_same(Nesting)evaluates tofalse || (true && !true) = falseand the path-2 check is skipped. The path-1 check insideminify_style_armdoes not fire either, becauseshould_compile_selectors()(targets.rs:148-150) is alsofalsewhenbrowsersisNone, soincompatiblestays empty. Immediately after,transpiler.rs:3249-3252callssheet.to_css(...)withPrinterOptions { targets: Targets::for_bundler_target(self.options.target), ... }. Fortarget = Browserthat returnsbrowser_default()(targets.rs:109) — chrome 87 / safari 14 / etc. — and the printer does compile nesting away, triggering the exponential&-substitution that this PR set out to bound.Reachability.
build_css_outputis reached viabuild_command.rs:553whenctx.bundler_options.transform_onlyis set, i.e.bun build --no-bundle file.css(and the legacy/v1 transpiler entry points that go throughbuild_with_resolve_result_eager). The PR'sbun buildtest uses--outdirwithout--no-bundle, so it exercises the BundleV2 /ParseTask.rspath, which correctly passesfor_bundler_target()tominify()atParseTask.rs:1257-1263and is protected.Step-by-step proof. Take the fuzzer's 26-level
::part(header), ::part(body)input and runbun build --no-bundle part-nesting.css:transpiler.rs:3240callsminifywith default targets →should_compile_same(Nesting) = false→ path-2 check atcss_parser.rs:2682not entered.minify_style_arm,context.targets.should_compile_selectors()isfalse(no browsers) →incompatibleis empty → path-1 check atrules/mod.rs:835not entered. Minify completes with the nested tree intact.transpiler.rs:3252callsto_csswithfor_bundler_target(Browser)→ printer's targets lack native nesting →serialize_nestingsubstitutes&with the parent selector list at every level → output doubles per level → 2^26 combinations → multi-GB output / OOM, exactly the behavior this PR fixes for the defaultbun buildpath.Why this is pre-existing, not a regression. The OOM through
transpiler.rs::build_css_outputexists onmaintoday; this PR does not touchtranspiler.rsand does not change its behavior. The new guard is correctly gated on the only targetsminify()has access to, and the primary fuzzer-hit path (ParseTask.rs) is now protected. This is an incomplete-fix observation about a secondary entry point, not a defect introduced by the PR.Suggested follow-up. Either (a) change
transpiler.rs:3240to passMinifyOptions { targets: Targets::for_bundler_target(self.options.target), .. }so it matches what it later passes toto_css(mirroringParseTask.rs:1260), or (b) drop theshould_compile_same(Nesting)gate and runexceeds_nesting_expansion_limitunconditionally — it is O(rules), short-circuits onrules.v.is_empty(), and is effectively free for stylesheets without deep multi-selector nesting, so the guard no longer depends on callers keeping minify and print targets in sync.