Boost: stop stripping SVG markup from Critical CSS while keeping style-tag breakout protection#49547
Boost: stop stripping SVG markup from Critical CSS while keeping style-tag breakout protection#49547kraftbj wants to merge 7 commits into
Conversation
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
|
Thank you for your PR! When contributing to Jetpack, we have a few suggestions that can help us test and review your patch:
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:
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. |
Code Coverage SummaryCoverage changed in 4 files.
|
There was a problem hiding this comment.
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
</styleneutralization viaDisplay_Critical_CSS::sanitize_css()for inline Critical CSS output. - Apply the same sanitization to the
boost_proxy_cssadmin-ajax CSS proxy response and addX-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. |
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.
…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.)
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.)
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.
Fixes #42321
Supersedes #43050 — an earlier, already-closed attempt at the same issue that took a heavier approach (added the
enshrined/svg-sanitizedependency plus awp_ksesSVG allowlist, and awp_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
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>").Display_Critical_CSS::sanitize_css()) that neutralizes only the sequence that can terminate a<style>element early: any case-insensitive</stylebecomes<\/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.boost_proxy_cssadmin-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 addsX-Content-Type-Options: nosniffto the proxy response.Critical_CSS_Storage/Storage_Post_Type/Set_Provider_CSS/ Cloud CSS endpoint) contains no quote-stripping — CSS is base64-encoded beforewp_insert_post, so quotes already survive persistence. Rather than changing code that wasn't broken, new round-trip regression tests lock that behavior in.</style>injection (any case) is still neutralized; quotes and SVG markup survive a store/load round-trip.Related product discussion/links
document.write) and Boost: fully remove boost-cache directory on uninstall and make cleanup resilient on very large caches #49546 (Page Cache uninstall cleanup).Does this pull request change what data or activity we track or use?
No.
Testing instructions
<div class="test-svg-background"></div>near the top of the header template so it's above the fold:<style id="jetpack-boost-critical-css">:url("data:image/svg+xml,")(SVG stripped) and the red circle is missing.</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.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;unitsuite also green at 114 tests. Thewith-wordpresssuite has 2 pre-existingJetpack_Boost_Testerrors reproducible on clean trunk in this environment, unrelated to this change).https://claude.ai/code/session_01PgpTrtTCH4hpz6Krh3ssho
Generated by Claude Code