Alan
Alan

Reputation: 1680

How do I add a host to my permitted rails hosts dynamically?

I need to dynamically add a permitted host to my Rails 6 application during runtime.

I've managed to append to Rails.application.config.hosts at runtime, but I'm still receiving an error Blocked host. Rails appears to ignore the hosts added to Rails.application.config.hosts that are added outside of application.rb and initializers.

Looking at host_authorization.rb, I can't see an obvious way of asking it to listen to new hosts.

My Reasoning:

User's can programmatically create their own 'shop' on our platform, which adds a new 'tenant' (apartment gem) to our multi-tenanted application We also allow them to point their own domains to our application.

However, in order to allow traffic from their custom domain, we currently would require a manual application restart if we stick with the default whitelisted domains.

I know I could use a workaround, and just set the hosts to whitelist everything (Rails.application.config.hosts = nil), but we need to keep the platform secure and automated.

Upvotes: 7

Views: 2475

Answers (1)

inopinatus
inopinatus

Reputation: 3779

The items in config.hosts are documented as compared using the === operator, which means we may include a lambda in that array, and thus make dynamic checking possible.

For the sake of an example, let's say we're returning a global permit-list from MyApp.all_permitted_domains. Then in config/application.rb we might write:

config.hosts << ->(host) {
  MyApp.all_permitted_domains.include?(host)
}

Note however that in this case the additional processing normally performed on host authorization (such as handling port numbers, or the special case of a leading ".") is not included. If you need that behaviour too, review the sanitize_hosts method in that host_authorization.rb source file for how.

Upvotes: 3

Related Questions