Skip to content

Instantly share code, notes, and snippets.

@madwork
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madwork/a49b85463e0fb31650bf to your computer and use it in GitHub Desktop.
Save madwork/a49b85463e0fb31650bf to your computer and use it in GitHub Desktop.
Utf8 Sanitizer Middleware
# Utf8Sanitizer
# Rack/Ruby on Rails: ArgumentError: invalid byte sequence in UTF-8
# raise 400 error
# http://dev.mensfeld.pl/2014/03/rack-argument-error-invalid-byte-sequence-in-utf-8/
class Utf8Sanitizer
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment