How can trusted host patterns be set dynamically? I'm working on a site which uses the Groups module that will allow users to create groups on the site. The site will then allow for users to point custom domain names at the site, with the content for their group being available at that domain.

I've got this set up, except for the trusted host patterns. At the moment I have to manually add the domains to $settings['trusted_host_patterns'] in settings.php. I do not want to have to handle this manually however and would like to set these trusted host patterns dynamically based on domain names stored in a field in the database.

I've been looking at DrupalKernel::initializeSettings(), and I've found that it does not appear any method exists to override the settings:

// Initialize our list of trusted HTTP Host headers to protect against
// header attacks.
$host_patterns = Settings::get('trusted_host_patterns', []);
if (PHP_SAPI !== 'cli' &amp;&amp; !empty($host_patterns)) {
  if (static::setupTrustedHosts($request, $host_patterns) === FALSE) {
    throw new BadRequestHttpException('The provided host name is not valid for this server.');
  }
}


So I'm thinking maybe I could use a kernel event, adding trusted host patterns to the settings before the trusted host patterns are called, but I'm starting to think I may be out of luck, due to trusted hosts being set before the database connection is initialized, meaning I won't be able to set trusted host patterns from DB variables.

Does anyone have an ideas of how to get around this?
By design you can't access the database from a non trusted host within Drupal. The kernel checks the trusted host patterns when the settings are read from file, but without the settings you don't have the credentials to open the database connection. 

There are a lot of ways to work around this. As mentioned in the comment by @NoSssweat you can write the trusted hosts to a file and include the file in settings.php. Or you can access the database from outside of Drupal and invoke this PHP script in settings.php. Or use a wildcard trusted host pattern matching all possible domains and then enhance security by adding a second check against the custom domain names in a kernel event subscriber when the database is available.