Skip to content

Commit

Permalink
Handle nil in Rack::Utils.escape_html
Browse files Browse the repository at this point in the history
This previously worked but unintentionally changed in #2099. 
This previously called `to_s` which made this accept almost anything (but especially `nil`)

Co-authored-by: Jeremy Evans <code@jeremyevans.net>
  • Loading branch information
Earlopain and jeremyevans committed Jun 12, 2024
1 parent 9ca3d90 commit d40896d
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. For info on

## Unreleased


### Fixed

- Fix passing non-strings to `Rack::Utils.escape_html`. ([#2202](https://github.com/rack/rack/pull/2202), [@earlopain])

### Added

- Introduce `Rack::VERSION` constant. ([#2199](https://github.com/rack/rack/pull/2199), [@ioquatix])
Expand Down
15 changes: 12 additions & 3 deletions lib/rack/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
require 'set'
require 'tempfile'
require 'time'
require 'cgi/escape'
require 'erb'

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

# Escape ampersands, brackets and quotes to their HTML/XML entities.
define_method(:escape_html, CGI.method(:escapeHTML))
# Introduced in ERB 4.0. ERB::Escape is an alias for ERB::Utils which
# doesn't get monkey-patched by rails
if defined?(ERB::Escape) && ERB::Escape.instance_method(:html_escape)
define_method(:escape_html, ERB::Escape.instance_method(:html_escape))
else
require 'cgi/escape'
# Escape ampersands, brackets and quotes to their HTML/XML entities.
def escape_html(string)
CGI.escapeHTML(string.to_s)
end
end

def select_best_encoding(available_encodings, accept_encoding)
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Expand Down
5 changes: 5 additions & 0 deletions test/spec_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,11 @@ def initialize(*)
Rack::Utils.escape_html("☃").must_equal "☃"
end

it 'escape_html handles non-strings' do
Rack::Utils.escape_html(nil).must_equal ""
Rack::Utils.escape_html(123).must_equal "123"
end

it "figure out which encodings are acceptable" do
helper = lambda do |a, b|
Rack::Request.new(Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => a))
Expand Down

0 comments on commit d40896d

Please sign in to comment.