Class: RackEncodingScrubber

Inherits:
Object
  • Object
show all
Defined in:
lib/rack_encoding_scrubber.rb

Constant Summary collapse

REGEX_UTF =
/%u00\h{0,2}/
REGEX_MB =
/%[a-fA-F]\h/

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ RackEncodingScrubber

Returns a new instance of RackEncodingScrubber.



6
7
8
# File 'lib/rack_encoding_scrubber.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
# File 'lib/rack_encoding_scrubber.rb', line 10

def call(env)
  encode env
  @app.call(env)
end

#encode(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rack_encoding_scrubber.rb', line 15

def encode(env)
  request_method = env['REQUEST_METHOD']
  if request_method == 'GET'
    %w[QUERY_STRING REQUEST_PATH PATH_INFO QUERY_STRING REQUEST_URI ORIGINAL_FULLPATH].each do |header|
      if h = env[header]
        if h["%u00"]
          h.gsub!(REGEX_UTF, "")
        end
        if h[REGEX_MB] # check for byte
          tmp = CGI.unescape(h).force_encoding('utf-8')
          if !tmp.valid_encoding?
            env[header] = CGI.escape(tmp.scrub(''))
            if %w[REQUEST_PATH PATH_INFO REQUEST_URI].include? header
              env[header].gsub! '%2F', '/'
            end
          end
        end
      end
    end
  end
end