Skip to content

Instantly share code, notes, and snippets.

@hooopo
Forked from eirc/clean_cookies.rb
Created November 29, 2012 04:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hooopo/4166751 to your computer and use it in GitHub Desktop.
Save hooopo/4166751 to your computer and use it in GitHub Desktop.
# Rack middleware that drops non properly encoded cookies that would hurt the ActionDispatch::Cookies middleware.
#
# This is actually a hotfix for issues
# * https://github.com/rack/rack/issues/225
# * https://github.com/rails/rails/issues/2622
module CleanCookies
# Tests whether a string may be decoded as a form component
def decodable?(string)
URI.decode_www_form_component(string)
true
rescue ArgumentError => e
/^invalid %-encoding \(.*\)$/.match(e.message) ? false : raise
end
module_function :decodable?
# Tests whether a cookie is clean, that is its key and value may be decoded as a form components
def clean?(cookie)
key, value = cookie.split('=', 2)
decodable?(key) && decodable?(value)
end
module_function :clean?
class Rack
def initialize(app)
@app = app
end
def call(env)
if env['HTTP_COOKIE']
clean_cookies, dirty_cookies = [], []
# Split cookies into clean and dirty
env['HTTP_COOKIE'].split(/[;,] */n).each do |cookie|
if CleanCookies::clean?(cookie)
clean_cookies << cookie
else
dirty_cookies << cookie
end
end
# Keep only clean cookies
env['HTTP_COOKIE'] = clean_cookies.join('; ')
# Inform about dropped dirty cookies
unless dirty_cookies.empty?
env['rack.errors'].puts "Ignoring dirty cookies: #{dirty_cookies.inspect}"
end
end
# Carry on
@app.call(env)
end
end
end
# Automatically insert self in a Rails 3 middleware stack
if defined?(Rails.configuration) && Rails.configuration.respond_to?(:middleware)
Rails.configuration.middleware.insert_before ActionDispatch::Cookies, CleanCookies::Rack
end
@hooopo
Copy link
Author

hooopo commented Nov 29, 2012

查看cookie引起的500数量:grep "cannot parse Cookie header" log/production.log |wc -l

@hooopo
Copy link
Author

hooopo commented Nov 29, 2012

aa = "%u60A8%u597D%uFF0C%u8BF7%u95EE%u6709%u4EC0%u4E48%u53EF%u4EE5%u5E2E%u5230%u60A8%uFF1F%u8BF7%u9009%u62E9%u60A8%u8981%u54A8%u8BE2%u7684%u5BA2%u670D%uFF01"

unescape(aa)
=> "您好,请问有什么可以帮到您?请选择您要咨询的客服!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment