Logging ActionDispatch::HostAuthorization 503 responses

When testing webhooks integration using ngrok on a new Rails 6 app, I couldn’t figure out why 403 response were returned in ngrok, and nothing was logged in the server logs.

I ended up learning about the new HostAuthorization middleware included in Rails 6 and the need for specifying hosts in the app config when different from localhost.

In some cases where you don’t have access to html/text response from the server, like the one I experienced, I think it would be good to log it using the Rails.logger. HostAuthorization calls a default response app when host is not whitelisted, logging could happen there:


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”)

Logging details about the reason of the 403

Rails.logger.error(“Host host.com not included in host lists. Please add it to your config”)

[403, {

"Content-Type" => "#{format}; charset=#{Response.default_charset}",

"Content-Length" => body.bytesize.to_s,

}, [body]]


Interested in feedback from the community!