Skip to content

Boost: stop stripping SVG markup from Critical CSS while keeping style-tag breakout protection#49547

Open
kraftbj wants to merge 7 commits into
trunkfrom
claude/boost-audit-prioritize-09rf6a-ccss-svg
Open

Boost: stop stripping SVG markup from Critical CSS while keeping style-tag breakout protection#49547
kraftbj wants to merge 7 commits into
trunkfrom
claude/boost-audit-prioritize-09rf6a-ccss-svg

Conversation

@kraftbj

@kraftbj kraftbj commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Fixes #42321

Supersedes #43050 — an earlier, already-closed attempt at the same issue that took a heavier approach (added the enshrined/svg-sanitize dependency plus a wp_kses SVG allowlist, and a wp_unslash() in storage). This PR fixes the same bug more simply with no new dependency, also covers the CSS proxy path, and adds regression tests. (#43050 is already closed, so nothing new auto-closes; this is for traceability.)

Proposed changes

  • Stop running wp_strip_all_tags() on Critical CSS when printing it into the front-end <style id="jetpack-boost-critical-css"> block; it corrupted valid CSS values containing markup, e.g. background-image: url("data:image/svg+xml,<svg ...></svg>").
  • Replace it with a targeted sanitizer (Display_Critical_CSS::sanitize_css()) that neutralizes only the sequence that can terminate a <style> element early: any case-insensitive </style becomes <\/style (\/ is a valid CSS escape for / inside strings/url() tokens, so legitimate CSS keeps its meaning). The insertion-only rewrite cannot recreate </style, including via nested tricks like <</style/style — covered by tests. Style-tag breakout/XSS remains impossible.
  • Apply the same treatment in the Critical CSS proxy (boost_proxy_css admin-ajax endpoint), which previously stripped SVG markup out of external source stylesheets before the generator ever saw them — meaning corrupted CSS was generated and persisted even before display-time stripping. Also adds X-Content-Type-Options: nosniff to the proxy response.
  • Finding on the issue's second hypothesis (double quotes stripped on DB save): the storage/ingestion path (Critical_CSS_Storage / Storage_Post_Type / Set_Provider_CSS / Cloud CSS endpoint) contains no quote-stripping — CSS is base64-encoded before wp_insert_post, so quotes already survive persistence. Rather than changing code that wasn't broken, new round-trip regression tests lock that behavior in.
  • Adds PHPUnit coverage: SVG data-URIs and double quotes survive display output; </style> injection (any case) is still neutralized; quotes and SVG markup survive a store/load round-trip.

Note for reviewers: this intentionally changes security-relevant sanitization (blanket tag-stripping → targeted </style neutralization). Please give the escaping approach in sanitize_css() a close look.

Related product discussion/links

Does this pull request change what data or activity we track or use?

No.

Testing instructions

  1. Add this to your theme's stylesheet, plus a matching <div class="test-svg-background"></div> near the top of the header template so it's above the fold:
    .test-svg-background {
        width: 200px;
        height: 200px;
        background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'><circle cx='4' cy='4' r='4' fill='%23f00'/></svg>");
    }
  2. In Jetpack Boost, enable Optimize Critical CSS Loading and generate Critical CSS.
  3. View the front-end source and inspect <style id="jetpack-boost-critical-css">:
    • Before: the rule appears as url("data:image/svg+xml,") (SVG stripped) and the red circle is missing.
    • After: the full SVG data-URI, including its quotes, is intact and the red circle renders before stylesheets load (throttle the network to confirm).
  4. Security check: store CSS containing </style><script>alert(1)</script> (via the same flow, or by editing the stored provider CSS) and confirm the printed block contains <\/style> instead, the style element is not terminated early, and no script executes.
  5. Tests: cd projects/plugins/boost && vendor/bin/phpunit-select-config phpunit.#.xml.dist --bootstrap tests/bootstrap.php --testsuite with-wordpress --filter "Display_Critical_CSS_Test|Critical_CSS_Storage_Test" (16 tests, 48 assertions passing; unit suite also green at 114 tests. The with-wordpress suite has 2 pre-existing Jetpack_Boost_Test errors reproducible on clean trunk in this environment, unrelated to this change).

https://claude.ai/code/session_01PgpTrtTCH4hpz6Krh3ssho


Generated by Claude Code

Critical CSS containing valid CSS values with markup, e.g.
background-image: url("data:image/svg+xml,<svg ...></svg>"), was being
corrupted in two places:

- Display_Critical_CSS used wp_strip_all_tags() when printing the CSS
  inside the <style> block, removing the SVG markup (and the quoted
  attributes inside it).
- CSS_Proxy used wp_strip_all_tags() on proxied source stylesheets, so
  the generator never saw the SVG and the corrupted CSS was persisted.

Replace the blanket tag-stripping with a targeted sanitizer that only
neutralizes the one dangerous sequence inside a <style> element: a
case-insensitive </style closing tag, which is escaped to <\/style
(a valid CSS escape inside strings/url() tokens), so the CSS can never
terminate the style element early. The CSS proxy also now sends
X-Content-Type-Options: nosniff.

Adds regression tests covering: SVG data-URIs and double quotes
surviving display output, a </style> injection attempt still being
neutralized, and double quotes/SVG markup surviving a Critical CSS
storage save/load round-trip.

https://claude.ai/code/session_01PgpTrtTCH4hpz6Krh3ssho
@kraftbj kraftbj added [Status] In Progress [Plugin] Boost A feature to speed up the site and improve performance. [Boost Feature] Critical CSS Issues involving the Critical CSS feature in Boost [Tests] Includes Tests labels Jun 11, 2026 — with Claude
@github-actions

Copy link
Copy Markdown
Contributor

Thank you for your PR!

When contributing to Jetpack, we have a few suggestions that can help us test and review your patch:

  • ✅ Include a description of your PR changes.
  • ✅ Add a "[Status]" label (In Progress, Needs Review, ...).
  • ✅ Add testing instructions.
  • ✅ Specify whether this PR includes any changes to data or privacy.
  • ✅ Add changelog entries to affected projects

This comment will be updated as you work on your PR and make changes. If you think that some of those checks are not needed for your PR, please explain why you think so. Thanks for cooperation 🤖


Follow this PR Review Process:

  1. Ensure all required checks appearing at the bottom of this PR are passing.
  2. Make sure to test your changes on all platforms that it applies to. You're responsible for the quality of the code you ship.
  3. You can use GitHub's Reviewers functionality to request a review.
  4. When it's reviewed and merged, you will be pinged in Slack to deploy the changes to WordPress.com simple once the build is done.

If you have questions about anything, reach out in #jetpack-developers for guidance!


Boost plugin:

No scheduled milestone found for this plugin.

If you have any questions about the release process, please ask in the #jetpack-releases channel on Slack.

@jp-launch-control

jp-launch-control Bot commented Jun 11, 2026

Copy link
Copy Markdown

Code Coverage Summary

Coverage changed in 4 files.

File Coverage Δ% Δ Uncovered
projects/plugins/boost/app/lib/critical-css/class-display-critical-css.php 28/30 (93.33%) 0.23% 0 💚
projects/plugins/boost/app/modules/optimizations/critical-css/class-css-proxy.php 16/40 (40.00%) 40.00% -10 💚
projects/plugins/boost/app/lib/critical-css/class-critical-css-storage.php 14/16 (87.50%) 81.25% -13 💚
projects/plugins/boost/app/lib/class-storage-post-type.php 60/112 (53.57%) 39.29% -44 💚

Full summary · PHP report · JS report

Copilot AI 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.

Pull request overview

This PR updates Jetpack Boost’s Critical CSS handling to preserve valid CSS values containing inline SVG markup/data URIs and double quotes, while still preventing <style>-tag breakout by neutralizing </style sequences. It also aligns the Critical CSS proxy endpoint with the same sanitization approach and adds regression coverage for both display-time output and storage round-trips.

Changes:

  • Replace blanket tag stripping with targeted </style neutralization via Display_Critical_CSS::sanitize_css() for inline Critical CSS output.
  • Apply the same sanitization to the boost_proxy_css admin-ajax CSS proxy response and add X-Content-Type-Options: nosniff.
  • Add PHPUnit coverage for style-breakout neutralization, SVG data-URI preservation, quote preservation, and storage round-trips; register the new tests in PHPUnit suites and add a changelog entry.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
projects/plugins/boost/app/lib/critical-css/class-display-critical-css.php Switches Critical CSS output sanitization from tag stripping to targeted </style neutralization via sanitize_css().
projects/plugins/boost/app/modules/optimizations/critical-css/class-css-proxy.php Updates proxy response headers and sanitization approach for proxied CSS content.
projects/plugins/boost/tests/php/lib/critical-css/Display_Critical_CSS_Test.php Replaces “strip HTML” expectations with explicit style-breakout neutralization tests; adds SVG/quote preservation assertions.
projects/plugins/boost/tests/php/lib/critical-css/Critical_CSS_Storage_Test.php Adds new tests to lock in storage round-trip preservation of SVG markup and quotes.
projects/plugins/boost/phpunit.9.xml.dist Registers the new storage test under the with-wordpress suite and excludes it from unit.
projects/plugins/boost/phpunit.11.xml.dist Registers the new storage test under the with-wordpress suite and excludes it from unit.
projects/plugins/boost/changelog/fix-critical-css-svg-stripping Adds a patch/fixed changelog entry describing the behavior change.

Comment thread projects/plugins/boost/app/modules/optimizations/critical-css/class-css-proxy.php Outdated
On a transient cache hit $response held the cached CSS string but $css
was only populated in the cold-fetch branch, so cache hits returned an
empty response and fed the Critical CSS generator no CSS at all.

https://claude.ai/code/session_01PgpTrtTCH4hpz6Krh3ssho
…adversarial tests

Round 1/2 review follow-ups (ce-code-review personas + codex adversarial):

- Rename Display_Critical_CSS::sanitize_css() to neutralize_style_closing_tags().
  The old name over-promised general CSS sanitization for a public method that
  only neutralizes the </style breakout sequence; tighten the docblock to say so.
- CSS proxy: only cache non-empty fetch bodies. The is_string() cache-hit branch
  otherwise replayed an empty/failed fetch for the full hour TTL, pinning empty
  CSS for a resource after one transient hiccup.
- Add a data-provider unit test exercising the breakout sanitizer directly with
  adversarial inputs (nested/overlap/EOF/whitespace/mixed-case), locking in the
  no-reconstruction invariant shared by the display block and the proxy.
- Correct the case-insensitive display assertion (str_ireplace substitutes the
  lowercase replacement) and mirror get_post_by_name()'s post_status=publish
  filter in the storage test's WP_Query emulator.

Copilot AI 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.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Comment thread projects/plugins/boost/app/modules/optimizations/critical-css/class-css-proxy.php Outdated
…ent type

- Make provide_style_breakout_inputs() static. PHPUnit 12 (PHP 8.2+ runs)
  requires data providers to be static and errored on the #[DataProvider]
  attribute the linter added; the PHPUnit 9 runs (7.x/8.1) had tolerated the
  non-static method via the docblock.
- CSS proxy: check is_wp_error() on the wp_safe_remote_get() response before
  reading its content-type header, so a transport failure is reported (and not
  cached) as a real error instead of a misleading 'Invalid content type', and
  drop the now-dead trailing is_wp_error() block. (Raised by Copilot and the
  correctness review; pre-existing on trunk.)

Copilot AI 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.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 4 comments.

Comment thread projects/plugins/boost/app/modules/optimizations/critical-css/class-css-proxy.php Outdated
The emulate_name_query filter now returns immediately when $posts is already
non-null, so it preserves any short-circuit result set by an earlier filter
instead of overwriting it. (Copilot review.)
@kraftbj kraftbj marked this pull request as ready for review June 13, 2026 21:24
@kraftbj kraftbj requested a review from LiamSarsfield June 13, 2026 21:24
kraftbj added 2 commits June 13, 2026 16:32
Coverage gate flagged class-css-proxy.php at 0% (the handler was untestable
because it ends in die()). Extract the cache/fetch resolution into a private
get_proxied_css() method and add CSS_Proxy_Test exercising it directly:

- cache hit replays the stored body,
- cache miss fetches the body and caches it,
- an empty body is returned but not cached,
- a non-CSS response is rejected (and the error cached) via wp_die().

HTTP is mocked with pre_http_request and wp_die is made to throw via its
handler filters. Behavior of handle_css_proxy() is unchanged. Registers the
test in the with-wordpress suite for both phpunit configs.
ReflectionMethod::setAccessible() is deprecated as of PHP 8.5 and tripped
failOnDeprecation on the PHP 8.5 job (the tests themselves passed). Make
get_proxied_css() protected and call it through an anonymous subclass instead,
which works across the full PHP 7.2-8.5 matrix with no reflection.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Boost Feature] Critical CSS Issues involving the Critical CSS feature in Boost [Plugin] Boost A feature to speed up the site and improve performance. [Status] In Progress [Tests] Includes Tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Boost: Inline SVGs stripped out of Critical CSS

3 participants