Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
40 changes: 39 additions & 1 deletion src/css/css_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2665,12 +2665,50 @@
};

if self.rules.minify(&mut minify_ctx, false).is_err() {
panic!("TODO: Handle");
// Minify errors report the rich error out-of-band through the
// context (the in-band error is just a tag).
let err = minify_ctx
.err
.take()
.expect("CssRuleList::minify returned an error without setting MinifyContext::err");
return Err(self.minify_error_with_location(err));
}

// When CSS nesting is compiled away, the printer substitutes `&` with
// the parent selector list, so the printed size of a nested rule is
// the product of the selector list lengths along its nesting chain —
// exponential in the nesting depth. Reject rules whose expansion would
// be unreasonably large before attempting to print them.
if options
.targets
.should_compile_same(compat::Feature::Nesting)
&& let Some(loc) = css_rules::exceeds_nesting_expansion_limit(&self.rules, false, 1)
{
return Err(self.minify_error_with_location(MinifyError {
kind: MinifyErrorKind::nesting_expansion_limit_exceeded,
loc,
}));
}

Check notice on line 2691 in src/css/css_parser.rs

View check run for this annotation

Claude / Claude Code Review

Path-2 expansion check assumes minify and print targets match

Heads-up (pre-existing, not introduced here): the path-2 check is gated on `MinifyOptions.targets`, but the print-time `&`-substitution it guards uses `PrinterOptions.targets`, and `transpiler.rs::build_css_output` (the `bun build --no-bundle file.css` path) calls `minify(&MinifyOptions::default())` — no targets, so the check is skipped — and then `to_css` with `Targets::for_bundler_target(...)`, which does compile nesting away. The exponential expansion is therefore still unguarded on that path
Comment on lines +2682 to 2691

Copy link
Copy Markdown
Contributor

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 uses PrinterOptions.targets, and transpiler.rs::build_css_output (the bun build --no-bundle file.css path) calls minify(&MinifyOptions::default()) — no targets, so the check is skipped — and then to_css with Targets::for_bundler_target(...), which does compile nesting away. The exponential expansion is therefore still unguarded on that path. The primary bun build / ParseTask.rs path is correctly protected; consider either having transpiler.rs pass for_bundler_target() to minify() the way ParseTask.rs:1260 does, or running the cheap O(rules) exceeds_nesting_expansion_limit check unconditionally.

Extended reasoning...

The new path-2 guard at css_parser.rs:2682-2691 runs only when options.targets.should_compile_same(compat::Feature::Nesting) is true, where options is the MinifyOptions passed to StyleSheet::minify. Its purpose is to bound the print-time &-substitution explosion in serialize_nesting, but the printer decides whether to compile nesting based on PrinterOptions.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:3240 calls sheet.minify(alloc, &MinifyOptions::default(), &extra). With MinifyOptions::default(), targets.browsers = None and include/exclude are empty. In targets.rs:152-156, is_compatible(Nesting) returns true when browsers is None, so should_compile_same(Nesting) evaluates to false || (true && !true) = false and the path-2 check is skipped. The path-1 check inside minify_style_arm does not fire either, because should_compile_selectors() (targets.rs:148-150) is also false when browsers is None, so incompatible stays empty. Immediately after, transpiler.rs:3249-3252 calls sheet.to_css(...) with PrinterOptions { targets: Targets::for_bundler_target(self.options.target), ... }. For target = Browser that returns browser_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_output is reached via build_command.rs:553 when ctx.bundler_options.transform_only is set, i.e. bun build --no-bundle file.css (and the legacy/v1 transpiler entry points that go through build_with_resolve_result_eager). The PR's bun build test uses --outdir without --no-bundle, so it exercises the BundleV2 / ParseTask.rs path, which correctly passes for_bundler_target() to minify() at ParseTask.rs:1257-1263 and is protected.

Step-by-step proof. Take the fuzzer's 26-level ::part(header), ::part(body) input and run bun build --no-bundle part-nesting.css:

  1. transpiler.rs:3240 calls minify with default targets → should_compile_same(Nesting) = false → path-2 check at css_parser.rs:2682 not entered.
  2. Inside minify_style_arm, context.targets.should_compile_selectors() is false (no browsers) → incompatible is empty → path-1 check at rules/mod.rs:835 not entered. Minify completes with the nested tree intact.
  3. transpiler.rs:3252 calls to_css with for_bundler_target(Browser) → printer's targets lack native nesting → serialize_nesting substitutes & 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 default bun build path.

Why this is pre-existing, not a regression. The OOM through transpiler.rs::build_css_output exists on main today; this PR does not touch transpiler.rs and does not change its behavior. The new guard is correctly gated on the only targets minify() 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:3240 to pass MinifyOptions { targets: Targets::for_bundler_target(self.options.target), .. } so it matches what it later passes to to_css (mirroring ParseTask.rs:1260), or (b) drop the should_compile_same(Nesting) gate and run exceeds_nesting_expansion_limit unconditionally — it is O(rules), short-circuits on rules.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.


Ok(())
}

/// Attaches the filename for `err.loc`'s source index so the error can
/// be reported with a proper location.
fn minify_error_with_location(&self, err: MinifyError) -> Err<MinifyErrorKind> {
Err {
kind: err.kind,
loc: self
.sources
.get(err.loc.source_index as usize)
.map(|filename| ErrorLocation {
filename: std::ptr::from_ref::<[u8]>(&**filename),
line: err.loc.line,
column: err.loc.column,
}),
}
}

pub fn to_css_with_writer<'a>(
&'a self,
arena: &'a Bump,
Expand Down
8 changes: 8 additions & 0 deletions src/css/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,9 @@ pub enum MinifyErrorKind {
/// The source location of the `@custom-media` rule with unsupported boolean logic.
custom_media_loc: Location,
},
/// Compiling CSS nesting for the configured browser targets would expand a
/// rule into more selector combinations than the allowed maximum.
nesting_expansion_limit_exceeded,
}

impl fmt::Display for MinifyErrorKind {
Expand All @@ -518,6 +521,11 @@ impl fmt::Display for MinifyErrorKind {
"Unsupported boolean logic in custom media rule at line {}, column {}",
custom_media_loc.line, custom_media_loc.column,
),
Self::nesting_expansion_limit_exceeded => write!(
f,
"Compiling CSS nesting for the configured browser targets would expand this rule into more than {} selector combinations. Reduce the number of selectors in nested selector lists, or target browsers that support CSS nesting.",
crate::rules::MAX_NESTING_EXPANSION,
),
}
}
}
Expand Down
121 changes: 121 additions & 0 deletions src/css/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,110 @@ impl<R> CssRuleList<R> {
// ── `.style` arm body — preserved verbatim port, gated on StyleRule
// behavior + selector helpers + DeclarationBlock::deep_clone. ──

/// Maximum number of selector combinations a single style rule may expand into
/// when CSS nesting is compiled away for the configured 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 during minification (`minify_style_arm`) or by substituting `&` with
/// `:is(...)` while printing. The expansion is the product of the selector
/// list lengths along the nesting chain, which grows exponentially with the
/// nesting depth — ~1KB of adversarial CSS (26 nested two-selector lists) asks
/// for 2^26 combinations and exhausts memory. Real-world stylesheets stay far
/// below this limit.
pub const MAX_NESTING_EXPANSION: usize = 65536;

/// Counts the rules in `list`, including nested rules, returning early once
/// the count exceeds `cap`. When the true count is `<= cap` the result is
/// exact; otherwise it is some value `> cap`.
fn count_rules_capped<R>(list: &CssRuleList<R>, cap: usize) -> usize {
let mut count: usize = 0;
for rule in list.v.iter() {
count += 1;
let nested: Option<&CssRuleList<R>> = match rule {
CssRule::Media(r) => Some(&r.rules),
CssRule::Supports(r) => Some(&r.rules),
CssRule::LayerBlock(r) => Some(&r.rules),
CssRule::MozDocument(r) => Some(&r.rules),
CssRule::Container(r) => Some(&r.rules),
CssRule::Scope(r) => Some(&r.rules),
CssRule::StartingStyle(r) => Some(&r.rules),
CssRule::Style(r) => Some(&r.rules),
CssRule::Nesting(r) => Some(&r.style.rules),
_ => None,
};
if let Some(nested) = nested {
count = count.saturating_add(count_rules_capped(nested, cap.saturating_sub(count)));
}
if count > cap {
return count;
}
}
count
}

/// Returns the location of the first nested style rule whose selectors would
/// expand into more than [`MAX_NESTING_EXPANSION`] combinations when CSS
/// nesting is compiled away (the printer substitutes `&` with the parent
/// selector list, so the printed size of a nested rule is the product of the
/// selector list lengths along its nesting chain).
///
/// `inside_style_rule` is whether `list` is nested within a style rule, and
/// `ancestor_product` is the product of the selector list lengths of the
/// enclosing style rules.
pub(crate) fn exceeds_nesting_expansion_limit<R>(
list: &CssRuleList<R>,
inside_style_rule: bool,
ancestor_product: usize,
) -> Option<Location> {
fn check_style_rule<R>(
sty: &style::StyleRule<R>,
inside_style_rule: bool,
ancestor_product: usize,
) -> Result<Option<(usize, &CssRuleList<R>)>, Location> {
let own_len = (sty.selectors.v.len() as usize).max(1);
let product = ancestor_product.saturating_mul(own_len);
if inside_style_rule && product > MAX_NESTING_EXPANSION {
return Err(sty.loc);
}
if sty.rules.v.is_empty() {
Ok(None)
} else {
Ok(Some((product, &sty.rules)))
}
}

for rule in list.v.iter() {
let nested: Option<(&CssRuleList<R>, bool, usize)> = match rule {
CssRule::Style(sty) => match check_style_rule(sty, inside_style_rule, ancestor_product)
{
Ok(nested) => nested.map(|(product, rules)| (rules, true, product)),
Err(loc) => return Some(loc),
},
CssRule::Nesting(r) => {
match check_style_rule(&r.style, inside_style_rule, ancestor_product) {
Ok(nested) => nested.map(|(product, rules)| (rules, true, product)),
Err(loc) => return Some(loc),
}
}
CssRule::Media(r) => Some((&r.rules, inside_style_rule, ancestor_product)),
CssRule::Supports(r) => Some((&r.rules, inside_style_rule, ancestor_product)),
CssRule::LayerBlock(r) => Some((&r.rules, inside_style_rule, ancestor_product)),
CssRule::MozDocument(r) => Some((&r.rules, inside_style_rule, ancestor_product)),
CssRule::Container(r) => Some((&r.rules, inside_style_rule, ancestor_product)),
CssRule::Scope(r) => Some((&r.rules, inside_style_rule, ancestor_product)),
CssRule::StartingStyle(r) => Some((&r.rules, inside_style_rule, ancestor_product)),
_ => None,
};
if let Some((rules, inside, product)) = nested {
if let Some(loc) = exceeds_nesting_expansion_limit(rules, inside, product) {
return Some(loc);
}
}
}
None
}

fn minify_style_arm<R: for<'b> css::generics::DeepClone<'b>>(
rule: &mut CssRule<R>,
rules: &mut Vec<CssRule<R>>,
Expand Down Expand Up @@ -722,6 +826,23 @@ fn minify_style_arm<R: for<'b> css::generics::DeepClone<'b>>(
SmallList::default()
};

// Each incompatible selector below clones this rule's entire nested subtree.
// Nested rules were minified (and possibly split the same way) first, so the
// subtree doubles at every nesting level whose selector list is incompatible
// — the total is the product of the selector list lengths along the nesting
// chain, which is exponential in the nesting depth. Bound the expansion and
// report an error instead of exhausting memory on adversarial input.
if incompatible.len() > 0 && !sty.rules.v.is_empty() {
let subtree_rules = count_rules_capped(&sty.rules, MAX_NESTING_EXPANSION);
if (incompatible.len() as usize).saturating_mul(subtree_rules) > MAX_NESTING_EXPANSION {
context.err = Some(css::error::MinifyError {
kind: css::error::MinifyErrorKind::nesting_expansion_limit_exceeded,
loc: sty.loc,
});
return Err(MinifyErr::minify_err);
}
}

sty.update_prefix(context);

// Attempt to merge the new rule with the last rule we added.
Expand Down
6 changes: 4 additions & 2 deletions src/css_jsc/error_jsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ where
T: Display,
{
let str = BunString::create_format(format_args!("{}", this.kind));
// `defer str.deref()` — `bun_core::String` is `Copy` and has no `Drop`, so deref explicitly.
// `bun_string_jsc::to_error_instance` consumes the caller's reference
// (it derefs internally), so do not deref again here — the string impl is
// shared with the JS error's message and an extra deref frees it while
// still referenced.
let js = bun_jsc::bun_string_jsc::to_error_instance(&str, global_this);
str.deref();
Ok(js)
}

Expand Down
96 changes: 96 additions & 0 deletions test/js/bun/css/nesting-expansion-limit.test.ts
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");
});
Loading