Skip to content

Commit

Permalink
Avoid calling String#strip on invalid Strings
Browse files Browse the repository at this point in the history
Use case: some servers have been known to serve files with
Content-Types like “video/mp4; charset=utf-8”, which HTTParty dutifully
tells ruby is a UTF-8 string.  However, before the Parser can decide
that MP4 is not a format it is capable of parsing, the response body is
tested for emptiness … after whitespace is stripped.

Since the String isn’t actually a valid UTF-8 String, this raises an
ArgumentError.  This patch fixes that error by avoiding the call on
Strings that are not validly encoded.
  • Loading branch information
pvande committed Sep 19, 2015
1 parent 87af97f commit 45a3537
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/httparty/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ def initialize(body, format)
# @return [Object] the parsed body
# @return [nil] when the response body is nil, an empty string, spaces only or "null"
def parse
return nil if body.nil? || body.strip.empty? || body == "null"
return nil if body.nil?
return nil if body == "null"
return nil if body.valid_encoding? && body.strip.empty?
if supports_format?
parse_supported_format
else
Expand Down
6 changes: 6 additions & 0 deletions spec/httparty/parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,12 @@ class MyParser < HTTParty::Parser
allow(@parser).to receive_messages(body: " ")
expect(@parser.parse).to be_nil
end

it "does not raise exceptions for bodies with invalid encodings" do
allow(@parser).to receive_messages(body: "\x80")
allow(@parser).to receive_messages(supports_format?: false)
expect(@parser.parse).to_not be_nil
end
end

describe "#supports_format?" do
Expand Down

0 comments on commit 45a3537

Please sign in to comment.