Skip to content

Commit 446c192

Browse files
Validate content-type of internal calls
1 parent 8e8e796 commit 446c192

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

lib/better_errors/middleware.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,8 @@ def internal_call(env, opts)
156156
body = JSON.parse(request.body.read)
157157
return invalid_csrf_token_json_response unless request.cookies[CSRF_TOKEN_COOKIE_NAME] == body['csrfToken']
158158

159+
return not_acceptable_json_response unless request.content_type == 'application/json'
160+
159161
response = @error_page.send("do_#{opts[:method]}", body)
160162
[200, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(response)]]
161163
end
@@ -200,5 +202,12 @@ def invalid_csrf_token_json_response
200202
"or something went wrong.",
201203
)]]
202204
end
205+
206+
def not_acceptable_json_response
207+
[406, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(
208+
error: "Request not acceptable",
209+
explanation: "The internal request did not match an acceptable content type.",
210+
)]]
211+
end
203212
end
204213
end

spec/better_errors/middleware_spec.rb

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -356,11 +356,30 @@ def initialize(message, original_exception = nil)
356356
request_env["HTTP_COOKIE"] = "BetterErrors-CSRF-Token=csrfToken123"
357357
end
358358

359-
it 'returns the HTML content' do
360-
expect(error_page).to receive(:do_variables).and_return(html: "<content>")
361-
expect(json_body).to match(
362-
'html' => '<content>',
363-
)
359+
context 'when the Content-Type of the request is application/json' do
360+
before do
361+
request_env['CONTENT_TYPE'] = 'application/json'
362+
end
363+
364+
it 'returns JSON containing the HTML content' do
365+
expect(error_page).to receive(:do_variables).and_return(html: "<content>")
366+
expect(json_body).to match(
367+
'html' => '<content>',
368+
)
369+
end
370+
end
371+
372+
context 'when the Content-Type of the request is application/json' do
373+
before do
374+
request_env['HTTP_CONTENT_TYPE'] = 'application/json'
375+
end
376+
377+
it 'returns a JSON error' do
378+
expect(json_body).to match(
379+
'error' => 'Request not acceptable',
380+
'explanation' => /did not match an acceptable content type/,
381+
)
382+
end
364383
end
365384
end
366385

0 commit comments

Comments
 (0)