From f2bcf865432a1470c30de3519df780a5b39cf9a2 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Fri, 12 Apr 2024 10:06:19 +0200 Subject: [PATCH] Don't use a mutable constant as Rack response A common gotcha in Rack API is to return a constant as a response. Another middleware higher in the stack may mutate the header hash to add some user specific things (.e.g `Set-Cookie`) and this state then leak across requests. In the case of `rack-utf8-sanitizer`, the risk is limited because it's likely to be among the very first middlewares, but it's still best not to do this. --- lib/rack/utf8_sanitizer.rb | 3 +-- test/test_utf8_sanitizer.rb | 10 ++++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/rack/utf8_sanitizer.rb b/lib/rack/utf8_sanitizer.rb index c5b7dd0..e36185d 100644 --- a/lib/rack/utf8_sanitizer.rb +++ b/lib/rack/utf8_sanitizer.rb @@ -7,7 +7,6 @@ module Rack class UTF8Sanitizer StringIO = ::StringIO - BAD_REQUEST = [400, { "Content-Type" => "text/plain" }, ["Bad Request"]] NULL_BYTE_REGEX = /\x00/.freeze class NullByteInString < StandardError; end @@ -28,7 +27,7 @@ def call(env) begin env = sanitize(env) rescue EOFError - return BAD_REQUEST + return [400, { "Content-Type" => "text/plain" }, ["Bad Request"]] end @app.call(env) end diff --git a/test/test_utf8_sanitizer.rb b/test/test_utf8_sanitizer.rb index cb055c8..e3f4f87 100644 --- a/test/test_utf8_sanitizer.rb +++ b/test/test_utf8_sanitizer.rb @@ -219,6 +219,16 @@ def read @response_env.should == [400, {"Content-Type"=>"text/plain"}, ["Bad Request"]] end + it "Bad Request response can safety be mutated" do + @rack_input = BrokenIO.new + response_env = @app.(request_env) + response_env.should == [400, {"Content-Type"=>"text/plain"}, ["Bad Request"]] + response_env[1]["Set-Cookie"] = "you_are_admin" + + response_env = @app.(request_env) + response_env[1]["Set-Cookie"].should == nil + end + it "sanitizes StringIO rack.input" do input = "foo=bla&quux=bar" @rack_input = StringIO.new input