Class: Goldencobra::HandleInvalidPercentEncoding

Inherits:
Object
  • Object
show all
Defined in:
app/middleware/goldencobra/handle_invalid_percent_encoding.rb

Constant Summary collapse

DEFAULT_CONTENT_TYPE =
'text/html'
DEFAULT_CHARSET =
'utf-8'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, stdout = STDOUT) ⇒ HandleInvalidPercentEncoding

Returns a new instance of HandleInvalidPercentEncoding.



9
10
11
12
# File 'app/middleware/goldencobra/handle_invalid_percent_encoding.rb', line 9

def initialize(app, stdout=STDOUT)
  @app = app
  @logger = defined?(Rails.logger) ? Rails.logger : Logger.new(stdout)
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'app/middleware/goldencobra/handle_invalid_percent_encoding.rb', line 8

def logger
  @logger
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'app/middleware/goldencobra/handle_invalid_percent_encoding.rb', line 14

def call(env)
  begin
    # calling env.dup here prevents bad things from happening
    request = Rack::Request.new(env.dup)
    # calling request.params is sufficient to trigger the error
    # see https://github.com/rack/rack/issues/337#issuecomment-46453404
    request.params
    @app.call(env)
  rescue ArgumentError => e
    raise unless e.message =~ /invalid %-encoding/
    message = "BAD REQUEST: Returning 400 due to #{e.message} from request with env #{request.inspect}"
    logger.info message
    content_type = env['HTTP_ACCEPT'] || DEFAULT_CONTENT_TYPE
    status = 400
    body   = "Bad Request"
    return [
      status,
      {
        'Content-Type' => "#{content_type}; charset=#{DEFAULT_CHARSET}",
        'Content-Length' => body.bytesize.to_s
      },
      [body]
    ]
  end
end