Skip to content

Commit

Permalink
Fix Grape allowing invalid headers to be set
Browse files Browse the repository at this point in the history
Fixes ruby-grape#2334

Ensure all header values are strings according to the Rack spec.

* Convert header values to strings using `to_s` in the `header` method in `lib/grape/dsl/headers.rb`.
* Emit a warning if the header value is not a string in the `header` method in `lib/grape/dsl/headers.rb`.
* Add tests in `spec/grape/dsl/headers_spec.rb` to verify that non-string header values are converted to strings and warnings are emitted.

---

For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/ruby-grape/grape/issues/2334?shareId=XXXX-XXXX-XXXX-XXXX).
  • Loading branch information
SlakrHakr committed Nov 4, 2024
1 parent 0477baf commit 82bfb3b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/grape/dsl/headers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ module Headers
# 4. Delete a specifc header key-value pair
def header(key = nil, val = nil)
if key
val ? header[key.to_s] = val : header.delete(key.to_s)
if val
unless val.is_a?(String)
warn "Header value for '#{key}' is not a string. Converting to string."
end
header[key.to_s] = val.to_s
else
header.delete(key.to_s)
end
else
@header ||= Grape::Util::Header.new
end
Expand Down
13 changes: 13 additions & 0 deletions spec/grape/dsl/headers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,17 @@
end
end
end

context 'when non-string headers are set' do
describe '#header' do
it 'converts non-string header values to strings' do
subject.header('integer key', 123)
expect(subject.header['integer key']).to eq '123'
end

it 'emits a warning if the header value is not a string' do
expect { subject.header('integer key', 123) }.to output("Header value for 'integer key' is not a string. Converting to string.\n").to_stderr
end
end
end
end

0 comments on commit 82bfb3b

Please sign in to comment.