Class: StrictRequestUri

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

Overview

Sometimes junk gets appended to the URLs clicked in e-mails. This junk then gets sent by browsers undecoded, and causes Unicode-related exceptions when the full request URI or path is rebuilt for ActionDispatch.

We can fix this by iteratively removing bytes from the end of the URL until it becomes parseable.

We do however answer to those URLs with a 400 to indicate clients that those requests are not welcome. This also allows us to tell the users that they are using a URL which is in fact not really valid.

Constant Summary collapse

VERSION =
'1.0.2'

Instance Method Summary collapse

Constructor Details

#initialize(app, &error_page_rack_app) ⇒ StrictRequestUri

Inits the middleware. The optional proc should be a Rack application that will render the error page. To make a controller render that page, use <ControllerClass>.action()

use RequestUriCleanup do | env |
    ErrorsController.action(:invalid_request).call(env)
end


22
23
24
25
26
27
28
29
# File 'lib/strict_request_uri.rb', line 22

def initialize(app, &error_page_rack_app)
  @app = app
  @error_page_app = if error_page_rack_app
    error_page_rack_app
  else
    ->(env) { [400, {'Content-Type' => 'text/plain'}, ['Invalid request URI']] }
  end
end

Instance Method Details

#call(env) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/strict_request_uri.rb', line 31

def call(env)
  # Compose the original URL, taking care not to treat it as UTF8.
  # Do not use Rack::Request since it is not really needed for this
  # (and _might be doing something with strings that we do not necessarily want).
  # For instance, Rack::Request does regexes when you ask it for the REQUEST_URI
  tainted_url = reconstruct_original_url(env)
  return @app.call(env) if string_parses_to_url?(tainted_url)
  
  # At this point we know the URL is fishy.
  referer = to_utf8(env['HTTP_REFERER'] || '(unknown)')
  env['rack.errors'].puts("Invalid URL received from referer #{referer}") if env['rack.errors']
  
  # Save the original URL so that the error page can use it
  env['strict_uri.original_invalid_url'] = tainted_url
  env['strict_uri.proposed_fixed_url'] = 
    truncate_bytes_at_end_until_parseable(tainted_url)
  
  # Strictly speaking, the parts we are going to put into QUERY_STRING and PATH_INFO
  # should _only_ be used for rendering the error page, and that's it.
  # 
  # We can therefore wipe them clean.
  env['PATH_INFO'] = '/invalid-url'
  env['QUERY_STRING'] = ''
  
  # And render the error page using the provided error app.
  @error_page_app.call(env)
end