Class: ActionDispatch::HostAuthorization

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

Overview

This middleware guards from DNS rebinding attacks by explicitly permitting the hosts a request can be sent to.

When a request comes to an unauthorized host, the response_app application will be executed and rendered. If no response_app is given, a default one will run, which responds with 403 Forbidden.

Defined Under Namespace

Classes: Permissions

Constant Summary collapse

DEFAULT_RESPONSE_APP =
-> env do
  request = Request.new(env)

  format = request.xhr? ? "text/plain" : "text/html"
  template = DebugView.new(host: request.host)
  body = template.render(template: "rescues/blocked_host", layout: "rescues/layout")

  [403, {
    "Content-Type" => "#{format}; charset=#{Response.default_charset}",
    "Content-Length" => body.bytesize.to_s,
  }, [body]]
end

Instance Method Summary collapse

Constructor Details

#initialize(app, hosts, response_app = nil) ⇒ HostAuthorization

Returns a new instance of HostAuthorization.



70
71
72
73
74
# File 'lib/action_dispatch/middleware/host_authorization.rb', line 70

def initialize(app, hosts, response_app = nil)
  @app = app
  @permissions = Permissions.new(hosts)
  @response_app = response_app || DEFAULT_RESPONSE_APP
end

Instance Method Details

#call(env) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/action_dispatch/middleware/host_authorization.rb', line 76

def call(env)
  return @app.call(env) if @permissions.empty?

  request = Request.new(env)

  if authorized?(request)
    mark_as_authorized(request)
    @app.call(env)
  else
    @response_app.call(env)
  end
end