From c3922841c560c3342040989229b46c93d67f2493 Mon Sep 17 00:00:00 2001 From: Lee DeBoom <31224301+SlakrHakr@users.noreply.github.com> Date: Mon, 4 Nov 2024 17:25:36 -0600 Subject: [PATCH] Fix Grape allowing invalid headers to be set Fixes #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). --- lib/grape/dsl/headers.rb | 9 ++++++++- spec/grape/dsl/headers_spec.rb | 13 +++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/lib/grape/dsl/headers.rb b/lib/grape/dsl/headers.rb index a02bdd588e..710edaa9ee 100644 --- a/lib/grape/dsl/headers.rb +++ b/lib/grape/dsl/headers.rb @@ -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 diff --git a/spec/grape/dsl/headers_spec.rb b/spec/grape/dsl/headers_spec.rb index 1502176bd9..042e94e776 100644 --- a/spec/grape/dsl/headers_spec.rb +++ b/spec/grape/dsl/headers_spec.rb @@ -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