Skip to content

Commit

Permalink
Delegate Rack::Utils.escape_html to CGI.escapeHTML to improve perform…
Browse files Browse the repository at this point in the history
…ance. (#2099)
  • Loading branch information
JunichiIto committed Jul 30, 2023
1 parent 444dc8a commit 1939a54
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 23 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ All notable changes to this project will be documented in this file. For info on
### SPEC Changes

- `rack.input` is now optional. ([#1997](https://github.com/rack/rack/pull/1997), [@ioquatix])
- `Rack::Utils.escape_html` doesn't escape forward slash (`/`) now. ([#2097](https://github.com/rack/rack/pull/2097), [@JunichiIto])
- `Rack::Utils.escape_html` is now delegated to `CGI.escapeHTML`. `'` is escaped to `#39;` instead of `#x27;`. (decimal vs hexadecimal) ([#2099](https://github.com/rack/rack/pull/2099), [@JunichiIto])

### Changed

Expand Down
15 changes: 2 additions & 13 deletions lib/rack/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
require 'set'
require 'tempfile'
require 'time'
require 'cgi/escape'

require_relative 'query_parser'
require_relative 'mime'
Expand Down Expand Up @@ -174,20 +175,8 @@ def best_q_match(q_value_header, available_mimes)
matches&.first
end

ESCAPE_HTML = {
"&" => "&",
"<" => "&lt;",
">" => "&gt;",
"'" => "&#x27;",
'"' => "&quot;"
}

ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys)

# Escape ampersands, brackets and quotes to their HTML/XML entities.
def escape_html(string)
string.to_s.gsub(ESCAPE_HTML_PATTERN, ESCAPE_HTML)
end
define_method(:escape_html, CGI.method(:escapeHTML))

def select_best_encoding(available_encodings, accept_encoding)
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Expand Down
11 changes: 2 additions & 9 deletions test/spec_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -475,17 +475,10 @@ def initialize(*)
Rack::Utils.escape_html("f&o").must_equal "f&amp;o"
Rack::Utils.escape_html("f<o").must_equal "f&lt;o"
Rack::Utils.escape_html("f>o").must_equal "f&gt;o"
Rack::Utils.escape_html("f'o").must_equal "f&#x27;o"
Rack::Utils.escape_html("f'o").must_equal "f&#39;o"
Rack::Utils.escape_html('f"o').must_equal "f&quot;o"
Rack::Utils.escape_html("<foo></foo>").must_equal "&lt;foo&gt;&lt;/foo&gt;"
end

it "escape html entities even on MRI when it's bugged" do
test_escape = lambda do
Rack::Utils.escape_html("\300<").must_equal "\300&lt;"
end

test_escape.must_raise ArgumentError
Rack::Utils.escape_html("\300<").must_equal "\300&lt;"
end

it "escape html entities in unicode strings" do
Expand Down

0 comments on commit 1939a54

Please sign in to comment.