Skip to content

Commit

Permalink
Rewind the body before reading and add safety around rewind
Browse files Browse the repository at this point in the history
  • Loading branch information
renatolond committed Feb 5, 2025
1 parent d35ecf1 commit ad2c310
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
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

0 comments on commit ad2c310

Please sign in to comment.