Skip to content

KSES: Add wp_kses_sanitize_srcset() for image candidate lists - #14811

Open
adamsilverstein wants to merge 6 commits into
WordPress:trunkfrom
adamsilverstein:ticket/29807-srcset-parser
Open

adamsilverstein wants to merge 6 commits into
WordPress:trunkfrom
adamsilverstein:ticket/29807-srcset-parser

Conversation

@adamsilverstein

@adamsilverstein adamsilverstein commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Trac ticket: https://core.trac.wordpress.org/ticket/29807

First of a small stack splitting up #6184 along the lines @dmsnell suggested there: the srcset parser on its own, then wiring it into KSES by tag and attribute, then the allowed-HTML additions for picture, source and srcset.

This PR only adds wp_kses_sanitize_srcset( string $srcset, array $allowed_protocols ): string plus tests. Nothing calls it yet.

What it does:

  • Splits the value into image candidates following https://html.spec.whatwg.org/multipage/images.html#parsing-a-srcset-attribute - a URL is a run of non-whitespace characters, and a comma only separates candidates when it ends the URL or the descriptors, so commas inside CDN resizer URLs stay put.
  • Checks each URL with wp_kses_bad_protocol() and drops the whole candidate, descriptors included, when that check would change it. Descriptors are skipped, not validated.
  • Takes decoded attribute text and returns decoded text. No entity handling inside; callers re-encode.
  • Returns the input string itself when every candidate is allowed. When a candidate is dropped, the remaining candidates are rejoined with , and trailing whitespace trimmed.

Changes from the version in #6184, all following the review feedback there: no "multi-URI attributes" concept or filter, no , /   lookahead, no wp_kses_no_null() or whitespace tolerance inside schemes, and no validation of descriptors. Parentheses in descriptors are tracked only to find where a candidate ends, as the spec does, so a comma inside them does not split the candidate. The a.jpg 2q,javascript:... case that was documented as a known limitation is now handled, since the comma after an invalid descriptor ends the candidate the same way it does in the browser.

Naming: I went with wp_kses_sanitize_srcset() since srcset (and imagesrcset on link) is the only attribute with this syntax. Happy to rename if something like image_candidates reads better.

Testing

npm run test:php -- --group kses - the new tests are in tests/phpunit/tests/kses/wpKsesSanitizeSrcset.php. PHPStan at level 10 is clean on the new code.

AI Use

Claude Code drafted the code and this description from the review thread on #6184, and I steered. I will review and test.

A srcset value is a comma-separated list of image candidate strings,
not a single URL, so passing it through wp_kses_bad_protocol() or
esc_url() either misses candidates or corrupts the list. This function
segments the value following the HTML specification's srcset parsing
algorithm and removes candidates whose URL uses a disallowed protocol.

It takes decoded attribute text and returns decoded text, leaving HTML
decoding and encoding to the caller, and returns the input string
itself when every candidate is allowed. Nothing calls it yet; wiring
it into KSES by tag and attribute follows separately.

See https://core.trac.wordpress.org/ticket/29807
@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs.

Core Committers: Use this line as a base for the props when committing in SVN:

Props adamsilverstein, westonruter, dmsnell.

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub or WordPress.org user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

@github-actions

Copy link
Copy Markdown

Test using WordPress Playground

The changes in this pull request can previewed and tested using a WordPress Playground instance.

WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Some things to be aware of

  • All changes will be lost when closing a tab with a Playground instance.
  • All changes will be lost when refreshing the page.
  • A fresh instance is created each time the link below is clicked.
  • Every time this pull request is updated, a new ZIP file containing all changes is created. If changes are not reflected in the Playground instance,
    it's possible that the most recent build failed, or has not completed. Check the list of workflow runs to be sure.

For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation.

Test this pull request with WordPress Playground.

@westonruter westonruter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A couple nits. Also sending up a Claude review momentarily.

@westonruter westonruter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🤖 Comment by Claude Opus 5.5

A medium-effort review of wp_kses_sanitize_srcset() turned up one tokenizer mismatch with the HTML spec that lets a disallowed URL through, plus some simplification opportunities. Each was reproduced against this branch:

'a.jpg 1x(,)/?,javascript:alert(1) 2x'  → returned unchanged
'a.jpg 1x(,)z,javascript:alert(1) 2x'   → 'a.jpg 1x('
'a.jpg 1x(,)z, b.jpg 2x'                → unchanged (correct)

The practical impact is limited, since browsers do not execute javascript: URLs in image candidates, but the sanitizer and the browser end up seeing different URLs, which defeats the function's contract. Details are in the inline comments.

Comment thread src/wp-includes/kses.php Resolved
Comment thread src/wp-includes/kses.php Resolved
Comment thread src/wp-includes/kses.php Resolved
Comment thread src/wp-includes/kses.php Resolved
Comment thread src/wp-includes/kses.php Resolved
Declare return types on the test methods and data providers and a type
on the allowed protocols property, as suggested in review.

See #29807.
The HTML srcset parser treats a comma between `(` and `)` in the
descriptors as part of the descriptor, so ending candidates at the first
comma let the sanitizer and the browser disagree on the URLs: a value
like `a.jpg 1x(,)/?,javascript:alert(1) 2x` came back unchanged, and
rebuilding could truncate allowed candidates.

Track parentheses while scanning descriptors, and replace the restart
and rebuild pass with a single pass that collects kept candidates.

See #29807.
@adamsilverstein

Copy link
Copy Markdown
Member Author

Thanks @westonruter, the parens one was a real miss. Pushed fixes in 144732e and the typing nits in 77ce137.

Claude worked through the review items, notes below:

Commas inside descriptor parentheses - fixed. The descriptor scan now treats a comma between ( and ) as part of the descriptor, and an unclosed ( runs to the end of the value, matching the spec's "in parens" state. All three suggested cases are now tests, plus a.jpg 1x(, javascript:alert(1) 2x (kept, one candidate) and javascript:alert(1) 1x(, a.jpg 2x (removed, nothing left).

Single pass - done as suggested: the loop collects $kept, flags $dropped, and returns $dropped ? implode( ', ', $kept ) : $srcset. That removes the restart, the $checked_until bookkeeping and the double check of the failing candidate. An all-allowed value still comes back as the input string.

Strict scheme test instead of wp_kses_bad_protocol() - left as is. The /? heuristic is only a problem when the tokenizer hands it the wrong string, and with the parens fix the URLs it sees are the ones the browser sees. A browser scheme can only hold [a-z0-9+.-] before the colon, so a / before the first colon means no scheme to the browser either. Keeping the shared check also keeps srcset consistent with how KSES treats src and href, including the control character stripping, which a ^[a-z][a-z0-9+.-]*: test would have to reproduce to avoid letting a leading control character slip a javascript: past it. Happy to revisit if you see a case where they still disagree.

Types - applied the native return and property types. PHPStan at level 10 on kses.php and the test file reports nothing on the new lines, and --group kses passes locally (562 tests).

@dmsnell dmsnell left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

while reading through this I stumbled upon a part of the spec that makes me wonder if our security threats match what we’re applying. the javascript: scheme appears inert inside srcset, but that’s based on some wording in the spec and an ad-hoc test in Chrome, Safari, and Firefox

Comment thread src/wp-includes/kses.php Outdated
* following the HTML specification's srcset parsing algorithm, so a comma only
* separates candidates when it ends a URL or its descriptors. A comma inside a URL,
* as produced by image CDN resizers, belongs to the URL, and one inside parentheses
* in the descriptors belongs to the descriptors.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The comma descriptions might be clearer as Example: code snippets in the docblock, with explanatory comments if necessary.

/**
 *
 * Example:
 *
 *     // The first comma is part of the URL.
 *     '/?id=4,15 2x` === wp_kses_sanitize_srcset( '/?id=4,15 2x, ,' );
 * 
 *     // The first comma is part of the descriptor.
 *     '/atat.png 2,x` === wp_kses_sanitize_srcset( '/atat.png 2,x, ,' );
 */

I don’t know the spec as well as you, and I know that the parseable values are broader than the allowable values (e.g. the descriptor should be only numbers plus x or w, but parses parentheses and all sorts of other characters), so my example is probably wrong in some way, and definitely not representative, but I think these pictures can clarify a lot for readers

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

good idea, we could give several representative examples.

Comment thread src/wp-includes/kses.php Outdated
*
* Each URL is checked with {@see wp_kses_bad_protocol()}. A candidate whose URL that
* check would change is removed in full, descriptors included, because stripping a
* scheme and keeping the rest would rewrite the URL rather than remove it, and

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

stripping a scheme and keeping the rest would rewrite the URL rather than remove it

this reads a bit unclear to me. do we not modify other URLs through wp_kses_bad_protocol()? I am definitely in favor of rejecting invalid values outright, but I can’t follow the goals with this comment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

i can try to clarify it, its saying: each url in the srcset is checked with wp_kses_bad_protocol and if the result is changed (eg it removed something) the url itself is removed from the srcset.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

How about:

Each URL is checked with {@see wp_kses_bad_protocol()}. Any urls that change are removed from the srcset. As in {@see esc_url()}, a URL starting with / cannot carry a scheme and is kept as is.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

if the result is changed (eg it removed something) the url itself is removed from the srcset.

this is the part I was confused about, because I thought the purpose of wp_kses_bad_protocol() was to sanitize URLs. that is, other places in Core accept modified values.

I see now that some places in Core also reject it if not identical to the input, which is preferable.

What about, instead of “any URLs that change are removed,” we specify tighter?

Each URL is checked with {@see wp_kses_bad_protocol()}, and if that sanitization would produce a different URL, it is rejected and its entire image candidate string is removed from the srcset.

Comment thread src/wp-includes/kses.php Outdated
* Each URL is checked with {@see wp_kses_bad_protocol()}. A candidate whose URL that
* check would change is removed in full, descriptors included, because stripping a
* scheme and keeping the rest would rewrite the URL rather than remove it, and
* descriptors left behind would be read as the next candidate's URL. As in

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This might just be me, but I would think this behavior is obvious, or is possibly clearer with less elaboration.

/**
 *
 * Entire image candidate strings are removed when they contain problematic URLs.
 * 
 */

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yes, there is a bit of repetition here, I'll clean it up.

Comment thread src/wp-includes/kses.php Outdated
* {@see WP_HTML_Tag_Processor::get_attribute()}, not raw HTML containing character
* references. The returned value is decoded text too; callers writing it back into
* HTML must escape it. When every candidate is allowed, the input is returned
* unchanged. Otherwise the remaining candidates are rejoined with `, `.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Some basic examples here would be helpful. Not even tricky edge cases, but just a show of the behavior.

It’s probably also wise to not differentiate unchanged inputs. We did that for some HTML API stuff and then walked back on it. While it’s nice to preserve inputs, in the KSES domain, normalization can be more valuable than preservation.

I’m thinking specifically of inputs such as those containing extra whitespace. It’s benign according to the spec, but if we are performing a sanitizing function, then it’s also good to think of all of the downstream code which might be doing something silly like explode( ', ', $srcset );

For normative srcset values the principle holds: the output will be the reference-equal string passed into it, but that’s not a contract we make for callers. In fact, that gives us the freedom to say “everything that comes out of here will be more like developers expect it to be” as long as we don’t change the semantics (e.g. no output will contain empty image candidate strings like ,, or , ,)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

makes sense! thanks for the guidance.

public function data_allowed_values_are_returned_unchanged(): array {
return array(
'empty value' => array( '' ),
'whitespace only' => array( " \t\n" ),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this is an example where I think we could reasonably say that the return value should be normalized to an empty string

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

👍🏼

'decimal density descriptors' => array( 'image-1x.jpg 1x, image-1.5x.jpg 1.5x, image-2x.jpg 2x' ),
'no descriptor on the last candidate' => array( 'small.jpg 300w, medium.jpg 600w, large.jpg' ),
'no whitespace after the comma' => array( 'image1.jpg 1x,image2.jpg 2x' ),
'extra whitespace is preserved' => array( ' image1.jpg 1x , image2.jpg 2x ' ),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

w.r.t. normalization, if we were to do that, this would be image1.jpg 1x, image2.jpg 2x on output

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I agree we should normalize the whitespace

'newlines are preserved' => array( "image1.jpg 1x,\nimage2.jpg 2x" ),
'commas inside a URL belong to the URL' => array( 'http://localhost/test.png,big 1x, http://localhost/test.png,medium 2x' ),
'CDN resizer URLs with commas' => array( 'https://resizer.example/cdn-cgi/image/format=auto,onerror=redirect,quality=80,width=412,height=275,dpr=1,fit=crop,gravity=0.5x0.5/https://bucket.example/photo.jpg 412w, https://resizer.example/cdn-cgi/image/format=auto,quality=80,width=824,height=550/https://bucket.example/photo.jpg 824w' ),
'CDN resizer URL without descriptor' => array( 'https://cdn.example/image/format=auto,quality=80/img.jpg 400w, https://cdn.example/image/format=auto,quality=80/img-large.jpg' ),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

it would be helpful somewhere to pass a URL containing syntax characters to show that these are raw-in/raw-out, maybe in another test function. an example I can think of is /image-service?yolo=meme&size=large 2x, and this would have to use assertSame() and not assertEquivalentHTML() because we’re comparing plaintext, not HTML

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Sure, will add!

Comment thread src/wp-includes/kses.php
$candidate = substr( $srcset, $candidate_at, $at - $candidate_at );
} else {
$candidate = $url;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

with this framed as a sanitizer for srcset, do you think it’s worth going a bit further on the normalization aspect, given that the allowable values are reasonably limited?

  • drop empty URLs. maybe it already does this via wp_kses_bad_protocol(), but would ,,,, as a srcset be rejected? I think so, but would be nice to verify
  • descriptor may be [0-9]+w or -?(?:[0-9]+)?(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?x

referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted.

this makes me wonder, do we know for sure that there is a security risk inherent in srcset? Safari, Firefox, and Chrome all reject this:

<img src="https://s.wp.com/i/atat.png" srcset="javascript:alert(1) 600w">

Firefox shows no error, but Chrome and Safari both show an error in the dev tools indicating that the URL or scheme or format is not allowed.

@adamsilverstein adamsilverstein Oct 28, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

drop empty URLs. maybe it already does this via wp_kses_bad_protocol(), but would ,,,, as a srcset be rejected? I think so, but would be nice to verify

I think so, I'll add a test to verify.

do we know for sure that there is a security risk inherent in srcset? Safari, Firefox, and Chrome all reject this

Good question. My assumption was we would want the same sort of sanitization as esc_url for (each url in) srcset. I thought these two resources would be treated the same and have the same inherent security risks. That may not be correct - I'll research further to confirm what the exact security risk is for urls and srcset and how/if it would be exploited.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for pushing on this, it made me go check what browsers actually do instead of assuming.

I had Claude dig through the specs and a few other sanitizers, here is the summary:

Short version: javascript: is inert in srcset for the same reason it is inert in src, so the case for checking it is policy consistency rather than script execution.

Fetch's scheme fetch only handles about, blob, data, file and HTTP(S) and returns a network error for anything else, which is the console error Chrome and Safari show. The same step applies to img src. The browser-native Sanitizer API goes further and only strips javascript: from navigating attributes (a/area href, form action, formaction), leaving img src alone entirely, and modern Angular's sanitizer has a test asserting that srcset="/foo.png 400px, javascript:evil() 23px" passes through untouched. See https://fetch.spec.whatwg.org/#scheme-fetch and https://github.com/web-platform-tests/wpt/blob/master/sanitizer-api/sanitizer-javascript-url.html

So the reasons to keep the check are the same ones that keep it on src today:

  • wp_allowed_protocols() is a content policy, not an execution guard. img src="data:..." is stripped in post context now, and browsers do load data: candidates from srcset, so an unchecked srcset would be a way around that. AngularJS shipped exactly this gap as CVE-2024-8372 (scored 4.3, content spoofing via "bypass image source restrictions", not XSS). See https://nvd.nist.gov/vuln/detail/CVE-2024-8372
  • Plenty of JS copies candidate URLs into src or href: Picturefill does img.src = bestCandidate.url, lightboxes commonly pick the largest candidate for the link, and feeds, email clients and apps render post content with their own rules. Sanitizers that treat srcset carefully (JustHTML, the .NET HtmlSanitizer, the AngularJS fix) check each candidate; DOMPurify runs its URI regex over the whitespace-stripped whole value, which in practice only checks the first one.

On the normalization points: ,,,, currently comes back unchanged (verified on the branch), as does a.jpg 1x,, b.jpg 2x. Both are parse errors in the spec, and always rejoining with , fixes them along with the whitespace cases. Descriptor validation seems worth leaving out of this PR: browsers already drop a candidate whose descriptor fails to parse (a.jpg 0w is a parse error and never becomes a candidate), the parse rules are looser than the valid syntax (1.x parses, -1x is rejected as not greater than zero, h is only allowed next to w), and the note on #6184 was that validating descriptors raises questions about syntax-valid but semantically wrong values.

Normalization and the extra tests are pushed in b04ba88. Does that framing match your read of the risk, and would you want descriptor validation as a follow up?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this was an honest question on what you consider worthwhile to sanitize.

that Claude assessment corresponds to my reading of the spec. makes me wonder why we are removing javascript: schemes from IMG src if it’s also benign. 🙃

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

its a reasonable question.

i guess the only convincing reason besides developer expectations I see is if we want to protect some older browsers that don't sanitize correctly, or other places/contexts you might copy the image to, like an email or chat app. It might be good to try to reproduce those vectors and measure the effort of sanitization as well. There is also the cost of trying to convince developers not sanitizing their URLs is just fine after so many years of teaching them the opposite.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

that’s all true, but if we’re adding complexity to guard against attacks in browsers we don’t support, we also run the risk of introducing new vectors of attack we hadn’t considered.

I’m not sure how we could copy/paste the srcset URLs into other apps, but you can use my clipboard viewer to help inspect it (not a replacement for testing the copy/paste into the other apps).

the important thing with the clipboard viewer is that you want to paste into it without any other copy/pastes in between, as the browser will tend to send out a multi-part paste object, and if you do something like paste through a terminal or other app it might lose one or more of the parts.

when I select your GitHub avatar and paste it in there, this is what it shows. I did not test with any unwanted URL patterns. I often see pastes with the image data embedded as a data URI

Screenshot 2026-10-28 at 6 08 21 PM

Returning the input unchanged when every candidate is allowed let values
the HTML parser treats as parse errors, such as `,,,,` or `a.jpg 1x,,
b.jpg 2x`, pass through verbatim. Rejoin the kept candidates with `, `
in every case, so empty candidates and surrounding whitespace never
reach the output and callers get a single predictable shape.

Add examples to the docblock, drop the repeated explanation of why a
candidate is removed whole, and add tests for separator normalization,
URL syntax characters passing through untouched, and whitespace ending
a URL before a scheme can form.

See #29807.

Claude-Session: https://claude.ai/code/session_018vwYjRp3dvMdHs8fzQbqqN
State that a URL is rejected when sanitizing it would produce a different
URL, and show the comma rules as examples instead of prose, as suggested
in review. Note why the comparison ignores case.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants