Skip to content

Instantly share code, notes, and snippets.

@codesoda
Created June 13, 2014 01:22
Show Gist options
  • Save codesoda/ccd5f34a6ed1fd4c9a68 to your computer and use it in GitHub Desktop.
Save codesoda/ccd5f34a6ed1fd4c9a68 to your computer and use it in GitHub Desktop.
go away utf8 invalid byte sequence
# config/applications.rb
config.middleware.use "Utf8Sanitizer::Middleware"
# lib/utf8_sanitizer.rb
module Utf8Sanitizer
class Middleware
SANITIZE_ENV_KEYS = %w(
HTTP_REFERER
PATH_INFO
REQUEST_URI
REQUEST_PATH
QUERY_STRING
)
def initialize(app)
@app = app
end
def call(env)
SANITIZE_ENV_KEYS.each do |key|
string = env[key].to_s
valid = URI.decode(string).force_encoding('UTF-8').valid_encoding?
# Don't accept requests with invalid byte sequence
return [ 400, { }, [ 'Bad request' ] ] unless valid
end
@app.call(env)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment