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

Rewind the body before reading and add safety around rewind #442

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
7 changes: 6 additions & 1 deletion lib/committee/request_unpacker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,12 @@ def parse_json(request)
return nil if request.request_method == "GET" && !@allow_get_body

return nil if request.body.nil?
rewind_body(request.body)
body = request.body.read
# if request body is empty, we just have empty params
return nil if body.length == 0

request.body.rewind
rewind_body(request.body)
hash = JSON.parse(body)
# We want a hash specifically. '42', 42, and [42] will all be
# decoded properly, but we can't use them here.
Expand All @@ -91,5 +92,9 @@ def parse_json(request)
end
self.class.indifferent_params(hash)
end

def rewind_body(body)
body.rewind if body.respond_to?(:rewind)
end
end
end
8 changes: 8 additions & 0 deletions test/request_unpacker_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@
assert_equal([{ "x" => "y" }, false], unpacker.unpack_request_params(request))
end

it "unpacks JSON on Content-Type: application/json if the body was not rewound first" do
env = { "CONTENT_TYPE" => "application/json", "rack.input" => StringIO.new('{"x":"y"}'), }
request = Rack::Request.new(env)
request.body.read
unpacker = Committee::RequestUnpacker.new
assert_equal([{ "x" => "y" }, false], unpacker.unpack_request_params(request))
end

it "unpacks JSON on Content-Type: application/vnd.api+json" do
env = { "CONTENT_TYPE" => "application/vnd.api+json", "rack.input" => StringIO.new('{"x":"y"}'), }
request = Rack::Request.new(env)
Expand Down