bdunagan

Brian Dunagan

September 18 2011
Sanitizing POST params in Rack

Rack is a handy way to get Ruby up and running on a web server, but it’s picky about input. Recently, I tried to post a URL with an ampersand (&) to a Rack instance, and because the URL contained an ampersand, Rack parsed the data wrong. It considers ampersands to be separating tokens.

When I can control the input, I can simply use percent encoding to escape the ampersand (%26). But for dealing with malformed input, Rack needs to rewrite the POST data before processing it.

# Escape the ampersand in the POST data.
rack_input = env["rack.input"].read
rack_input = rack_input.gsub("&","%26")
params = Rack::Utils.parse_query(rack_input, "&")
params["post_data"] = Rack::Utils.unescape(params["post_data"])
env["rack.input"] = StringIO.new(Rack::Utils.build_query(params))
# Parse the request.
req = Rack::Request.new(env)

Thanks to Pivotal Labs for the crucial bits of code.

Compiling PowerPC with LLVM GCC 4.2 in Xcode 4.1 on 10.7 Converting MySQL from LATIN1 to UTF8
LinkedIn GitHub Email