Skip to content

Commit

Permalink
Validate content-type of internal calls
Browse files Browse the repository at this point in the history
  • Loading branch information
RobinDaugherty committed Sep 15, 2020
1 parent 8e8e796 commit 446c192
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
9 changes: 9 additions & 0 deletions lib/better_errors/middleware.rb
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ def internal_call(env, opts)
body = JSON.parse(request.body.read)
return invalid_csrf_token_json_response unless request.cookies[CSRF_TOKEN_COOKIE_NAME] == body['csrfToken']

return not_acceptable_json_response unless request.content_type == 'application/json'

response = @error_page.send("do_#{opts[:method]}", body)
[200, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(response)]]
end
Expand Down Expand Up @@ -200,5 +202,12 @@ def invalid_csrf_token_json_response
"or something went wrong.",
)]]
end

def not_acceptable_json_response
[406, { "Content-Type" => "application/json; charset=utf-8" }, [JSON.dump(
error: "Request not acceptable",
explanation: "The internal request did not match an acceptable content type.",
)]]
end
end
end
29 changes: 24 additions & 5 deletions spec/better_errors/middleware_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -356,11 +356,30 @@ def initialize(message, original_exception = nil)
request_env["HTTP_COOKIE"] = "BetterErrors-CSRF-Token=csrfToken123"
end

it 'returns the HTML content' do
expect(error_page).to receive(:do_variables).and_return(html: "<content>")
expect(json_body).to match(
'html' => '<content>',
)
context 'when the Content-Type of the request is application/json' do
before do
request_env['CONTENT_TYPE'] = 'application/json'
end

it 'returns JSON containing the HTML content' do
expect(error_page).to receive(:do_variables).and_return(html: "<content>")
expect(json_body).to match(
'html' => '<content>',
)
end
end

context 'when the Content-Type of the request is application/json' do
before do
request_env['HTTP_CONTENT_TYPE'] = 'application/json'
end

it 'returns a JSON error' do
expect(json_body).to match(
'error' => 'Request not acceptable',
'explanation' => /did not match an acceptable content type/,
)
end
end
end

Expand Down

0 comments on commit 446c192

Please sign in to comment.