Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape \u2028 and \u2029 for 1.8 #44

Merged
merged 4 commits into from
Dec 10, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion lib/rack/contrib/jsonp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ class JSONP
VALID_JS_VAR = /[a-zA-Z_$][\w$]*/
VALID_CALLBACK = /\A#{VALID_JS_VAR}(?:\.?#{VALID_JS_VAR})*\z/

# These hold the Unicode characters \u2028 and \u2029.
#
# They are defined in constants for Ruby 1.8 compatibility.
#
# In 1.8
# "\u2028" # => "u2028"
# "\u2029" # => "u2029"
# In 1.9
# "\342\200\250" # => "\u2028"
# "\342\200\251" # => "\u2029"
U2028, U2029 = ("\u2028" == 'u2028') ? ["\342\200\250", "\342\200\251"] : ["\u2028", "\u2029"]

def initialize(app)
@app = app
end
Expand Down Expand Up @@ -83,7 +95,7 @@ def pad(callback, response, body = "")
# replacing them with the escaped version. This should be safe because
# according to the JSON spec, these characters are *only* valid inside
# a string and should therefore not be present any other places.
body << s.to_s.gsub("\u2028", '\u2028').gsub("\u2029", '\u2029')
body << s.to_s.gsub(U2028, '\u2028').gsub(U2029, '\u2029')
end

["#{callback}(#{body})"]
Expand Down
12 changes: 10 additions & 2 deletions test/spec_rack_jsonp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,20 @@
end

specify "should not allow literal U+2028 or U+2029" do
test_body = "{\"bar\":\"\u2028 and \u2029\"}"
test_body = unless "\u2028" == 'u2028'
"{\"bar\":\"\u2028 and \u2029\"}"
else
"{\"bar\":\"\342\200\250 and \342\200\251\"}"
end
callback = 'foo'
app = lambda { |env| [200, {'Content-Type' => 'application/json'}, [test_body]] }
request = Rack::MockRequest.env_for("/", :params => "foo=bar&callback=#{callback}")
body = Rack::JSONP.new(app).call(request).last
body.join.should.not.match(/\u2028|\u2029/)
unless "\u2028" == 'u2028'
body.join.should.not.match(/\u2028|\u2029/)
else
body.join.should.not.match(/\342\200\250|\342\200\251/)
end
end

context "but is empty" do
Expand Down