Class: HandleInvalidPercentEncodingRequests::Middleware

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

Overview

Rack Middleware inserted before the request that detects an encoding error and returns an appropriate response.

Instance Method Summary collapse

Constructor Details

#initialize(app, stdout = STDOUT) ⇒ Middleware

Returns a new instance of Middleware.



27
28
29
30
# File 'lib/handle_invalid_percent_encoding_requests/middleware.rb', line 27

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

Instance Method Details

#call(env) ⇒ Object

Called by Rack when a request comes through



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/handle_invalid_percent_encoding_requests/middleware.rb', line 33

def call(env)
  # 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 InvalidPercentEncodingErrorMatcher,
       InvalidByteSequenceErrorMatcher,
       NullByteErrorMatcher => e

  @logger.info "Bad request. Returning 400 due to #{e.class.name} " \
               "#{e.message.inspect} from request with env " \
               "#{request.inspect}"
  error_response
end