Skip to content

Commit 624bf9b

Browse files
sawanobolympalmer
authored andcommitted
return 400 bad request when failed parse as json (#134)
1 parent 1b9e47b commit 624bf9b

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

lib/rack/contrib/post_body_content_type_parser.rb

+5
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,12 @@ def call(env)
3434
env.update(FORM_HASH => JSON.parse(body, :create_additions => false), FORM_INPUT => env[POST_BODY])
3535
end
3636
@app.call(env)
37+
rescue JSON::ParserError
38+
bad_request('failed to parse body as JSON')
3739
end
3840

41+
def bad_request(body = 'Bad Request')
42+
[ 400, { 'Content-Type' => 'text/plain', 'Content-Length' => body.size.to_s }, [body] ]
43+
end
3944
end
4045
end

test/spec_rack_post_body_content_type_parser.rb

+19-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
params = params_for_request '{"key":"value"}', "application/json; charset=utf-8"
1616
params['key'].must_equal "value"
1717
end
18-
18+
1919
specify "should parse 'application/json' requests with empty body" do
2020
params = params_for_request "", "application/json"
2121
params.must_equal({})
@@ -33,14 +33,31 @@
3333
result.must_be_empty
3434
end
3535

36+
describe "contradiction between body and type" do
37+
def assert_failed_to_parse_as_json(response)
38+
response.wont_equal nil
39+
status, headers, body = response
40+
status.must_equal 400
41+
body.must_equal ["failed to parse body as JSON"]
42+
end
43+
44+
specify "should return bad request with invalid JSON" do
45+
test_body = '"bar":"foo"}'
46+
env = Rack::MockRequest.env_for "/", {:method => "POST", :input => test_body, "CONTENT_TYPE" => 'application/json'}
47+
app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, Rack::Request.new(env).POST] }
48+
response = Rack::PostBodyContentTypeParser.new(app).call(env)
49+
50+
assert_failed_to_parse_as_json(response)
51+
end
52+
end
3653
end
3754

3855
def params_for_request(body, content_type)
3956
env = Rack::MockRequest.env_for "/", {:method => "POST", :input => body, "CONTENT_TYPE" => content_type}
4057
app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, Rack::Request.new(env).POST] }
4158
Rack::PostBodyContentTypeParser.new(app).call(env).last
4259
end
43-
60+
4461
rescue LoadError => e
4562
# Missing dependency JSON, skipping tests.
4663
STDERR.puts "WARN: Skipping Rack::PostBodyContentTypeParser tests (json not installed)"

0 commit comments

Comments
 (0)