Skip to content

Commit

Permalink
feat: do not allow JSON request bodies that are not Objects or Arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
bethesque committed Dec 12, 2022
1 parent 8ed8224 commit 3d91728
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/pact_broker/api/resources/base_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,17 @@ def params(options = {})
return options[:default] if options.key?(:default) && request_body.empty?

symbolize_names = !options.key?(:symbolize_names) || options[:symbolize_names]
if symbolize_names
parsed_params = if symbolize_names
@params_with_symbol_keys ||= JSON.parse(request_body, { symbolize_names: true }.merge(PACT_PARSING_OPTIONS)) #Not load! Otherwise it will try to load Ruby classes.
else
@params_with_string_keys ||= JSON.parse(request_body, { symbolize_names: false }.merge(PACT_PARSING_OPTIONS)) #Not load! Otherwise it will try to load Ruby classes.
end

if !parsed_params.is_a?(Hash) && !parsed_params.is_a?(Array)
raise "Expected JSON Object in request body but found #{parsed_params.class.name}"
end

parsed_params
rescue StandardError => e
raise InvalidJsonError.new(e.message)
end
Expand Down
25 changes: 25 additions & 0 deletions spec/lib/pact_broker/api/resources/base_resource_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,31 @@ def process_post
end
end

context "when a JSON string value is provided" do
let(:body_string) { "".to_json }

it "raises an error, but maybe change this later if this should be allowed currently no resources accept strings" do
expect { subject.params }.to raise_error InvalidJsonError
end
end

context "when a JSON number value is provided" do
let(:body_string) { 1.to_json }

it "raises an error, but maybe change this later if this should be allowed currently no resources accept numbers" do
expect { subject.params }.to raise_error InvalidJsonError
end
end

context "when a JSON array value is provided" do
let(:body_string) { [].to_json }

it "allows this only because, for historical reasons, the pact publishing endpoint allows publishing contracts as arrays" do
# possibly from when the very very first pact format was just an array of interactions, with no top level object
expect(subject.params).to eq []
end
end

context "when symbolize_names is not set" do
it "symbolizes the names" do
expect(subject.params.keys).to eq [:foo]
Expand Down

0 comments on commit 3d91728

Please sign in to comment.