Skip to content

css: escape custom pseudo-class/element names when printing - #31404

Merged
Jarred-Sumner merged 2 commits into
mainfrom
farm/638d5828/css-escape-custom-pseudo-names
May 25, 2026
Merged

Jarred-Sumner merged 2 commits into
mainfrom
farm/638d5828/css-escape-custom-pseudo-names

Conversation

@robobun

@robobun robobun commented May 25, 2026

Copy link
Copy Markdown
Collaborator

What

Fuzzer-found round-trip violation (invariant:css:minified CSS does not reparse): a 6-byte CSS input whose selector is a pseudo-class named with an escaped space (:\ ) minifies to a bare : , and the minifier's own output no longer parses.

BUN_FEATURE_FLAG_INTERNAL_FOR_TESTING=1 bun -e 'require("bun:internal-for-testing").cssInternals.minifyTest(":\\ {w:", "")'

Before: the input :\ {w: prints as : {w:}, and re-parsing that output fails with Invalid selector. Expected identifier in pseudo-element, found: .

Cause

Unknown (custom) pseudo-class and pseudo-element names are stored unescaped by the tokenizer, but serialize_pseudo_class / serialize_pseudo_element in src/css/selectors/selector.rs wrote them back raw:

PseudoClass::Custom { name } => {
    dest.write_char(b':')?;
    return dest.write_str(name);
}

So any name containing characters that require escaping (a space, a colon, etc.) loses its escapes on output, producing CSS that no longer parses. Other identifier-bearing selector parts (classes, ids, :lang() arguments) already re-escape via serialize_identifier; the four custom pseudo arms (Custom / CustomFunction for both pseudo-classes and pseudo-elements) did not.

Fix

Serialize custom pseudo-class/element names with Printer::serialize_identifier instead of write_str, so escapes are regenerated on output. Ordinary names (letters, digits, hyphens, vendor prefixes) are unaffected — serialize_identifier only escapes when needed.

Now :\ {w: prints as :\ {w:}, which reparses to the same stylesheet.

Verification

  • New test test/js/bun/css/custom-pseudo-ident-escape.test.ts covers the fuzzer-minimized input, escaped names in custom pseudo-classes/elements/functions, round-trip stability of the minified output, and that ordinary unknown pseudo names are unchanged. 3 of 4 tests fail without the fix.
  • test/js/bun/css/css.test.ts (1087 pass), the other CSS test files, and test/bundler/css/ all pass with the change.

Unknown pseudo-class and pseudo-element names are unescaped during
parsing but were printed raw, so a name that needs escaping (e.g. an
escaped space, `:\ `) serialized as a bare `: ` and the minified
output no longer parsed. Serialize these names with
`serialize_identifier`, matching how classes, ids, and :lang()
arguments are printed.
@coderabbitai

coderabbitai Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This PR updates CSS selector serialization to properly escape custom pseudo-class and pseudo-element identifiers using serialize_identifier() instead of raw string writes. Three test cases validate that escaped custom pseudo names are re-escaped consistently, round-trip correctly after minification, and that ordinary unknown pseudo names remain unchanged aside from CSS whitespace removal.

Changes

Custom Pseudo-Class/Element Identifier Escaping

Layer / File(s) Summary
Custom pseudo-class and pseudo-element serialization with identifier escaping
src/css/selectors/selector.rs
serialize_pseudo_class handles Custom and CustomFunction variants using dest.serialize_identifier(name) with early returns instead of raw strings. serialize_pseudo_element Custom variant similarly updated to use identifier escaping with early return.
Test coverage for custom pseudo-identifier escaping
test/js/bun/css/custom-pseudo-ident-escape.test.ts
Three Bun test cases validate re-escaping behavior for custom escaped pseudo names, verify minified output round-trips correctly, and confirm ordinary unknown pseudo names (vendor/extended forms and functional pseudos) remain unchanged aside from CSS minification.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: escaping custom pseudo-class/element names during serialization to fix a round-trip parsing violation.
Description check ✅ Passed The description fully addresses both required template sections with comprehensive detail: 'What' explains the fuzzer-found issue and root cause, and 'How did you verify' describes the new test and passing test suites.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@robobun

robobun commented May 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 2:48 PM PT - May 25th, 2026

❌ @robobun, your commit ef24f98 has 2 failures in Build #58011 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 31404

That installs a local version of the PR into your bun-31404 executable, so you can run:

bun-31404 --bun

@claude claude Bot left a comment

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.

LGTM — straightforward fix swapping raw write_str for serialize_identifier so custom pseudo names round-trip correctly.

Extended reasoning...

Overview

This PR changes four match arms in src/css/selectors/selector.rs (PseudoClass::Custom, PseudoClass::CustomFunction, PseudoElement::Custom, PseudoElement::CustomFunction) to serialize the stored name via Printer::serialize_identifier instead of write_str. It adds a new test file with four tests covering the fuzzer-minimized input, escaped names in pseudo-classes/elements/functions, round-trip stability, and that ordinary unknown pseudo names are unchanged.

Security risks

None. This is purely a CSS serialization correctness fix — it makes the printer more conservative by escaping identifier characters that need escaping, rather than emitting them raw. No untrusted input handling, auth, or privilege boundaries are touched.

Level of scrutiny

Low. The diff is ~8 lines of mechanical substitution in the serializer, and serialize_identifier is already the established pattern in the same function (the :lang() arm just above uses it). The behavior for ordinary identifiers (letters, digits, hyphens, vendor prefixes) is unchanged since serialize_identifier only escapes when necessary, and the new test explicitly asserts this.

Other factors

  • The PR description shows the existing CSS test suite (1087 tests) and bundler CSS tests pass.
  • No CODEOWNERS entry covers src/css/.
  • The bug hunting system found no issues.
  • No outstanding human review comments.

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Delete your code comments.

@robobun

robobun commented May 25, 2026

Copy link
Copy Markdown
Collaborator Author

Removed.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/bun/css/custom-pseudo-ident-escape.test.ts`:
- Around line 18-23: Replace the manual for-loop inside the test titled
"minified output with escaped pseudo names round-trips" with a parameterized
describe.each over the array of source strings so each case becomes its own
subtest; iterate the matrix via describe.each([...]) and inside create a single
test (or it) that calls minifyTest(source, "") and asserts
expect(minifyTest(minified, "")).toBe(minified), keeping the existing minifyTest
calls and assertion logic intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f5f59ce2-cd6c-4a65-85f9-54c3796f3a33

📥 Commits

Reviewing files that changed from the base of the PR and between cd1ad59 and ef24f98.

📒 Files selected for processing (2)
  • src/css/selectors/selector.rs
  • test/js/bun/css/custom-pseudo-ident-escape.test.ts

Comment on lines +18 to +23
test("minified output with escaped pseudo names round-trips", () => {
for (const source of [":\\ {w:", ":\\ {color: red}", "::\\ {color: red}", ":hover\\:focus {color: red}"]) {
const minified = minifyTest(source, "");
expect(minifyTest(minified, "")).toBe(minified);
}
});

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use describe.each() for the round-trip matrix instead of a manual loop.

Line 19 packs multiple cases into one test, which makes failures less actionable and diverges from the repo’s parameterized-test style.

♻️ Suggested refactor
-import { expect, test } from "bun:test";
+import { describe, expect, test } from "bun:test";
@@
-test("minified output with escaped pseudo names round-trips", () => {
-  for (const source of [":\\ {w:", ":\\ {color: red}", "::\\ {color: red}", ":hover\\:focus {color: red}"]) {
-    const minified = minifyTest(source, "");
-    expect(minifyTest(minified, "")).toBe(minified);
-  }
-});
+describe.each([":\\ {w:", ":\\ {color: red}", "::\\ {color: red}", ":hover\\:focus {color: red}"])(
+  "minified output with escaped pseudo names round-trips: %s",
+  source => {
+    const minified = minifyTest(source, "");
+    expect(minifyTest(minified, "")).toBe(minified);
+  },
+);

As per coding guidelines: Use describe.each() for parameterized tests.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test("minified output with escaped pseudo names round-trips", () => {
for (const source of [":\\ {w:", ":\\ {color: red}", "::\\ {color: red}", ":hover\\:focus {color: red}"]) {
const minified = minifyTest(source, "");
expect(minifyTest(minified, "")).toBe(minified);
}
});
import { describe, expect, test } from "bun:test";
describe.each([":\\ {w:", ":\\ {color: red}", "::\\ {color: red}", ":hover\\:focus {color: red}"])(
"minified output with escaped pseudo names round-trips: %s",
source => {
const minified = minifyTest(source, "");
expect(minifyTest(minified, "")).toBe(minified);
},
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/js/bun/css/custom-pseudo-ident-escape.test.ts` around lines 18 - 23,
Replace the manual for-loop inside the test titled "minified output with escaped
pseudo names round-trips" with a parameterized describe.each over the array of
source strings so each case becomes its own subtest; iterate the matrix via
describe.each([...]) and inside create a single test (or it) that calls
minifyTest(source, "") and asserts expect(minifyTest(minified,
"")).toBe(minified), keeping the existing minifyTest calls and assertion logic
intact.

@claude claude Bot left a comment

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.

LGTM — straightforward fix swapping write_str for serialize_identifier on custom pseudo names, matching how :lang() and other identifier-bearing parts already serialize.

Extended reasoning...

Overview

This PR fixes a fuzzer-found CSS round-trip bug: custom (unknown) pseudo-class and pseudo-element names were written back raw via write_str, dropping escapes that the tokenizer had decoded. The fix changes four match arms in src/css/selectors/selector.rs (PseudoClass::Custom, PseudoClass::CustomFunction, PseudoElement::Custom, PseudoElement::CustomFunction) to call dest.serialize_identifier(name) instead. A new test file exercises the fuzzer-minimized input, several escaped-name variants, round-trip stability, and confirms ordinary unknown pseudo names are unchanged.

Security risks

None. This is purely a CSS serialization correctness fix — it makes output more escaped (and thus more conservative), not less. No auth, crypto, filesystem, or network surface is touched.

Level of scrutiny

Low. The diff is four one-line substitutions of write_str → serialize_identifier, which is exactly the helper already used in the same function for :lang() arguments and elsewhere in the printer for class/id/attribute identifiers. serialize_identifier is a no-op for ordinary identifier characters and only adds escapes when needed, so there's no behavior change for valid real-world pseudo names — confirmed by the "ordinary unknown pseudo names are unchanged" test and the 1087 passing existing CSS tests reported in the description.

Other factors

  • No CODEOWNERS entries cover src/css/ or the new test file.
  • The bug-hunting system found no issues.
  • The PR description is thorough (cause, fix, verification) and the test coverage is solid: it includes both the fuzzer repro and regression guards for the no-change case.
  • No outstanding reviewer comments.

@robobun

robobun commented May 25, 2026

Copy link
Copy Markdown
Collaborator Author

CI status: the only hard failure on the latest run (build #58011, commit ef24f98) is test/bundler/transpiler/transpiler.test.js — "Bun.Transpiler.transformSync stack overflows" did not throw — on the 🪟 2019 x64 lane. The other annotations are soft failures that passed on retry (serve-body-leak.test.ts memory threshold on the ASAN lane, duckdb.test.ts on x64-baseline).

None of these involve this PR: the diff is confined to CSS selector serialization, and the new CSS test passes on every lane in both runs. The same transpiler stack-overflow failure currently appears on most PR builds regardless of their contents (e.g. builds 58007, 57973, 57963, 57947, 57944, 57940, 57935), and it passed on the latest main build (58003) — an existing Windows flake, not something introduced here.

@Jarred-Sumner
Jarred-Sumner merged commit 984bc1e into main May 25, 2026
75 of 78 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/638d5828/css-escape-custom-pseudo-names branch May 25, 2026 23:52
springmin pushed a commit to springmin/bun that referenced this pull request May 26, 2026
* oven/main (10 new commits):
  Optimize TextEncoder.encode: restore SIMD ASCII fast paths lost in the Rust port (oven-sh#31385)
  js_parser: sanitize auto-generated default export name for digit-named modules (oven-sh#31403)
  fetch: run checkServerIdentity before writing the request (oven-sh#31325)
  ffi: avoid copying the threadsafe callback wrapper on the calling thread (oven-sh#31332)
  install: gate the exit-callback cache teardown to the main thread (oven-sh#31376)
  fix(node:module): don't register native helpers as their own constructors (oven-sh#31393)
  css: escape custom pseudo-class/element names when printing (oven-sh#31404)
  Deepen the lots-of-for-loop fixture so the transpiler stack-overflow tests throw on Windows (oven-sh#31382)
  Hardening: input validation and bounds tightening across 36 subsystems (round 4) (oven-sh#31339)
  Speed up FormData multipart serialization (oven-sh#31379)

Auto-merged: src/install/PackageManager.rs, src/runtime/cli/upgrade_command.rs, src/runtime/webcore/Blob.rs, src/sys/lib.rs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants