Skip to content

Keep URI escapes in an ASCII-compatible encoding - #150

Open
adityawrk wants to merge 2 commits into
ruby:masterfrom
adityawrk:fix/escape-wide-encoding
Open

adityawrk wants to merge 2 commits into
ruby:masterfrom
adityawrk:fix/escape-wide-encoding

Conversation

@adityawrk

@adityawrk adityawrk commented Nov 29, 2026 •

Copy link
Copy Markdown

Fixes #89.

escape and escape_uri_component percent-encode the raw bytes and then force the source encoding onto the result. For UTF-16LE, \\uFEFF becomes the bytes of %FF%FE but the string is tagged UTF-16LE, so it reads as three unrelated characters. unescape and unescape_uri_component then scan those bytes, and each ASCII character occupies two bytes, so %41 is never recognized.

The escaped result is now US-ASCII when the source encoding is not ASCII-compatible. Unescaping transcodes such a string to UTF-8 before looking for percent sequences. ASCII-compatible strings, including UTF-8, keep the encoding they had.

Before the change, CGI.escape_uri_component(\"\\uFEFF\".encode(Encoding::UTF_16LE)) was a UTF-16LE string (\"\\u4625\\u2546\\u4546\"), and unescaping \"%41\".encode(Encoding::UTF_16LE) returned that same wide string. After it, the escape is the US-ASCII string %FF%FE, and unescaping the wide %41 returns \"A\".

ruby -Ilib:test/lib -rhelper test/cgi/test_cgi_escape.rb: 443 tests, 538 assertions, 0 failures.

Escaping a UTF-16 string returned those bytes tagged as UTF-16, and
unescaping a UTF-16 percent string left the percent signs in place.
Percent-encoding a UTF-16 or UTF-32 string and then tagging the result
with that encoding made the escapes unreadable. The result is now
US-ASCII, and unescaping reads the percent sequences as characters.

This branch has not been deployed

No deployments
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.

Escaping/unescaping URIs and elements doesn't work for UTF-16/32

1 participant