Skip to content

Commit

Permalink
Fail if the key path is empty. (#57)
Browse files Browse the repository at this point in the history
We should fail on input like `=foo` as the key path is ambiguous.
  • Loading branch information
ioquatix authored Jul 7, 2024
1 parent ad0c267 commit cc5501f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/protocol/http/url.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,13 @@ def self.scan(string)
end

def self.split(name)
name.scan(/([^\[]+)|(?:\[(.*?)\])/).flatten!.compact!
name.scan(/([^\[]+)|(?:\[(.*?)\])/)&.tap do |parts|
parts.flatten!
parts.compact!
end
end

# Assign a value to a nested hash.
def self.assign(keys, value, parent)
top, *middle = keys

Expand Down Expand Up @@ -95,6 +99,10 @@ def self.decode(string, maximum = 8, symbolize_keys: false)
self.scan(string) do |name, value|
keys = self.split(name)

if keys.empty?
raise ArgumentError, "Invalid key path: #{name.inspect}!"
end

if keys.size > maximum
raise ArgumentError, "Key length exceeded limit!"
end
Expand Down
6 changes: 6 additions & 0 deletions test/protocol/http/url.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@
Protocol::HTTP::URL.decode("a[b][c][d][e][f][g][h][i]=10")
end.to raise_exception(ArgumentError, message: be =~ /Key length exceeded/)
end

it "fails with missing key" do
expect do
Protocol::HTTP::URL.decode("=foo")
end.to raise_exception(ArgumentError, message: be =~ /Invalid key/)
end
end

with '.unescape' do
Expand Down

0 comments on commit cc5501f

Please sign in to comment.