Skip to content
This repository
Browse code

JSONP: Always escape U+2028 and U+2029

  • Loading branch information...
commit 24f3da12ea7f763826d0166591a45eba2d9bfce5 1 parent 3f004dd
Magnus Holm judofyr authored

Showing 2 changed files with 21 additions and 2 deletions. Show diff stats Hide diff stats

  1. +11 1 lib/rack/contrib/jsonp.rb
  2. +10 1 test/spec_rack_jsonp.rb
12 lib/rack/contrib/jsonp.rb
@@ -75,7 +75,17 @@ def valid_callback?(callback)
75 75 # since JSON is returned as a full string.
76 76 #
77 77 def pad(callback, response, body = "")
78   - response.each{ |s| body << s.to_s }
  78 + response.each do |s|
  79 + # U+2028 and U+2029 are allowed inside strings in JSON (as all literal
  80 + # Unicode characters) but JavaScript defines them as newline
  81 + # seperators. Because no literal newlines are allowed in a string, this
  82 + # causes a ParseError in the browser. We work around this issue by
  83 + # replacing them with the escaped version. This should be safe because
  84 + # according to the JSON spec, these characters are *only* valid inside
  85 + # a string and should therefore not be present any other places.
  86 + body << s.to_s.gsub("\u2028", '\u2028').gsub("\u2029", '\u2029')
  87 + end
  88 +
79 89 ["#{callback}(#{body})"]
80 90 end
81 91
11 test/spec_rack_jsonp.rb
@@ -51,6 +51,15 @@
51 51 headers = Rack::JSONP.new(app).call(request)[1]
52 52 headers['Content-Type'].should.equal('application/javascript')
53 53 end
  54 +
  55 + specify "should not allow literal U+2028 or U+2029" do
  56 + test_body = "{\"bar\":\"\u2028 and \u2029\"}"
  57 + callback = 'foo'
  58 + app = lambda { |env| [200, {'Content-Type' => 'application/json'}, [test_body]] }
  59 + request = Rack::MockRequest.env_for("/", :params => "foo=bar&callback=#{callback}")
  60 + body = Rack::JSONP.new(app).call(request).last
  61 + body.join.should.not.match(/\u2028|\u2029/)
  62 + end
54 63
55 64 context "but is empty" do
56 65 specify "should " do
@@ -122,4 +131,4 @@ def assert_bad_request(response)
122 131 body.should.equal [test_body]
123 132 end
124 133
125   -end
  134 +end

0 comments on commit 24f3da1

Please sign in to comment.
Something went wrong with that request. Please try again.