class ActionDispatch::HostAuthorization

This middleware guards from DNS rebinding attacks by explicitly permitting the hosts a request can be sent to, and is passed the options set in config.host_authorization.

Requests can opt-out of Host Authorization with exclude:

config.host_authorization = { exclude: ->(request) { request.path =~ /healthcheck/ } }

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+.

Constants

DEFAULT_RESPONSE_APP

Public Class Methods

new(app, hosts, deprecated_response_app = nil, exclude: nil, response_app: nil) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 74
    def initialize(app, hosts, deprecated_response_app = nil, exclude: nil, response_app: nil)
      @app = app
      @permissions = Permissions.new(hosts)
      @exclude = exclude

      unless deprecated_response_app.nil?
        ActiveSupport::Deprecation.warn(<<-MSG.squish)
          `action_dispatch.hosts_response_app` is deprecated and will be ignored in Rails 6.2.
          Use the Host Authorization `response_app` setting instead.
        MSG

        response_app ||= deprecated_response_app
      end

      @response_app = response_app || DEFAULT_RESPONSE_APP
    end

Public Instance Methods

call(env) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 91
def call(env)
  return @app.call(env) if @permissions.empty?

  request = Request.new(env)

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

Private Instance Methods

authorized?(request) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 105
def authorized?(request)
  valid_host = /
    \A
    (?<host>[a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])
    (:\d+)?
    \z
  /x

  origin_host = valid_host.match(
    request.get_header("HTTP_HOST").to_s.downcase)
  forwarded_host = valid_host.match(
    request.x_forwarded_host.to_s.split(/,\s?/).last)

  origin_host && @permissions.allows?(origin_host[:host]) && (
    forwarded_host.nil? || @permissions.allows?(forwarded_host[:host]))
end
excluded?(request) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 122
def excluded?(request)
  @exclude && @exclude.call(request)
end
mark_as_authorized(request) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 126
def mark_as_authorized(request)
  request.set_header("action_dispatch.authorized_host", request.host)
end