Skip to content

Instantly share code, notes, and snippets.

@sparrovv
Last active December 14, 2015 19:48
Show Gist options
  • Save sparrovv/5138869 to your computer and use it in GitHub Desktop.
Save sparrovv/5138869 to your computer and use it in GitHub Desktop.
Ensure no invalid UTF8 chars in user data
class UTF8Validator
class InvalidUTF8Character < Exception; end
VALIDATE_ENV_KEYS = [
"QUERY_STRING",
"REQUEST_PATH",
"REQUEST_URI",
"rack.request.form_vars" # POST data
]
def initialize(app)
@app = app
end
def call(env)
validate_env(env)
@app.call(env)
rescue InvalidUTF8Character
Rails.logger.info 'Invalid UTF-8 character - return 400'
[400, {'Content-Type' => 'text/html'}, ["400"]]
end
def validate_env(env)
VALIDATE_ENV_KEYS.each do |key|
next unless value = env[key]
validate(URI.decode(value))
end
end
def validate(string)
return unless string.is_a? String
utf8_string = string.dup.force_encoding('utf-8')
raise InvalidUTF8Character unless utf8_string.valid_encoding?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment