Skip to content

[FrameworkBundle][HttpKernel] Add support for SYMFONY_TRUSTED_PROXIES, SYMFONY_TRUSTED_HEADERS, SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER and SYMFONY_TRUSTED_HOSTS env vars #58161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ CHANGELOG
* Deprecate `session.sid_length` and `session.sid_bits_per_character` config options
* Add the ability to use an existing service as a lock/semaphore resource
* Add support for configuring multiple serializer instances via the configuration
* Add support for `SYMFONY_TRUSTED_PROXIES`, `SYMFONY_TRUSTED_HEADERS`, `SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER` and `SYMFONY_TRUSTED_HOSTS` env vars

7.1
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->end()
->scalarNode('trust_x_sendfile_type_header')
->info('Set true to enable support for xsendfile in binary file responses.')
->defaultFalse()
->defaultValue('%env(bool:default::SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER)%')
->end()
->scalarNode('ide')->defaultValue($this->debug ? '%env(default::SYMFONY_IDE)%' : null)->end()
->booleanNode('test')->end()
Expand All @@ -108,26 +108,23 @@ public function getConfigTreeBuilder(): TreeBuilder
->prototype('scalar')->end()
->end()
->arrayNode('trusted_hosts')
->beforeNormalization()->ifString()->then(fn ($v) => [$v])->end()
->beforeNormalization()->ifString()->then(static fn ($v) => $v ? [$v] : [])->end()
->prototype('scalar')->end()
->defaultValue(['%env(default::SYMFONY_TRUSTED_HOSTS)%'])
->end()
->variableNode('trusted_proxies')
->beforeNormalization()
->ifTrue(fn ($v) => 'private_ranges' === $v || 'PRIVATE_SUBNETS' === $v)
->then(fn () => IpUtils::PRIVATE_SUBNETS)
->end()
->defaultValue(['%env(default::SYMFONY_TRUSTED_PROXIES)%'])
->end()
->arrayNode('trusted_headers')
->fixXmlConfig('trusted_header')
->performNoDeepMerging()
->defaultValue(['x-forwarded-for', 'x-forwarded-port', 'x-forwarded-proto'])
->beforeNormalization()->ifString()->then(fn ($v) => $v ? array_map('trim', explode(',', $v)) : [])->end()
->enumPrototype()
->values([
'forwarded',
'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-forwarded-port', 'x-forwarded-prefix',
])
->end()
->beforeNormalization()->ifString()->then(static fn ($v) => $v ? [$v] : [])->end()
->prototype('scalar')->end()
->defaultValue(['%env(default::SYMFONY_TRUSTED_HEADERS)%'])
->end()
->scalarNode('error_controller')
->defaultValue('error_controller')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,14 +313,14 @@ public function load(array $configs, ContainerBuilder $container): void

$container->setParameter('kernel.http_method_override', $config['http_method_override']);
$container->setParameter('kernel.trust_x_sendfile_type_header', $config['trust_x_sendfile_type_header']);
$container->setParameter('kernel.trusted_hosts', $config['trusted_hosts']);
$container->setParameter('kernel.trusted_hosts', [0] === array_keys($config['trusted_hosts']) ? $config['trusted_hosts'][0] : $config['trusted_hosts']);
$container->setParameter('kernel.default_locale', $config['default_locale']);
$container->setParameter('kernel.enabled_locales', $config['enabled_locales']);
$container->setParameter('kernel.error_controller', $config['error_controller']);

if (($config['trusted_proxies'] ?? false) && ($config['trusted_headers'] ?? false)) {
$container->setParameter('kernel.trusted_proxies', $config['trusted_proxies']);
$container->setParameter('kernel.trusted_headers', $this->resolveTrustedHeaders($config['trusted_headers']));
$container->setParameter('kernel.trusted_proxies', \is_array($config['trusted_proxies']) && [0] === array_keys($config['trusted_proxies']) ? $config['trusted_proxies'][0] : $config['trusted_proxies']);
$container->setParameter('kernel.trusted_headers', [0] === array_keys($config['trusted_headers']) ? $config['trusted_headers'][0] : $config['trusted_headers']);
}

if (!$container->hasParameter('debug.file_link_format')) {
Expand Down Expand Up @@ -3114,25 +3114,6 @@ private function registerHtmlSanitizerConfiguration(array $config, ContainerBuil
}
}

private function resolveTrustedHeaders(array $headers): int
{
$trustedHeaders = 0;

foreach ($headers as $h) {
$trustedHeaders |= match ($h) {
'forwarded' => Request::HEADER_FORWARDED,
'x-forwarded-for' => Request::HEADER_X_FORWARDED_FOR,
'x-forwarded-host' => Request::HEADER_X_FORWARDED_HOST,
'x-forwarded-proto' => Request::HEADER_X_FORWARDED_PROTO,
'x-forwarded-port' => Request::HEADER_X_FORWARDED_PORT,
'x-forwarded-prefix' => Request::HEADER_X_FORWARDED_PREFIX,
default => 0,
};
}

return $trustedHeaders;
}

public function getXsdValidationBasePath(): string|false
{
return \dirname(__DIR__).'/Resources/config/schema';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -704,19 +704,16 @@ protected static function getBundleDefaultConfig()
return [
'http_method_override' => false,
'handle_all_throwables' => true,
'trust_x_sendfile_type_header' => false,
'trust_x_sendfile_type_header' => '%env(bool:default::SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER)%',
'ide' => '%env(default::SYMFONY_IDE)%',
'default_locale' => 'en',
'enabled_locales' => [],
'set_locale_from_accept_language' => false,
'set_content_language_from_locale' => false,
'secret' => 's3cr3t',
'trusted_hosts' => [],
'trusted_headers' => [
'x-forwarded-for',
'x-forwarded-port',
'x-forwarded-proto',
],
'trusted_hosts' => ['%env(default::SYMFONY_TRUSTED_HOSTS)%'],
'trusted_proxies' => ['%env(default::SYMFONY_TRUSTED_PROXIES)%'],
'trusted_headers' => ['%env(default::SYMFONY_TRUSTED_HEADERS)%'],
'csrf_protection' => [
'enabled' => false,
],
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Remove `@internal` flag and add `@final` to `ServicesResetter`
* Add support for `SYMFONY_DISABLE_RESOURCE_TRACKING` env var
* Add support for configuring trusted proxies/headers/hosts via env vars

7.1
---
Expand Down
25 changes: 22 additions & 3 deletions src/Symfony/Component/HttpKernel/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@
$class = $this->getContainerClass();
$buildDir = $this->warmupDir ?: $this->getBuildDir();
$skip = $_SERVER['SYMFONY_DISABLE_RESOURCE_TRACKING'] ?? '';
$skip = filter_var($skip, \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) ?? explode(',', $skip);
$skip = filter_var($skip, \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) ?? explode(',', $skip);
$cache = new ConfigCache($buildDir.'/'.$class.'.php', $this->debug, null, \is_array($skip) && ['*'] !== $skip ? $skip : ($skip ? [] : null));

$cachePath = $cache->getPath();
Expand Down Expand Up @@ -745,11 +745,30 @@
$container = $this->container;

if ($container->hasParameter('kernel.trusted_hosts') && $trustedHosts = $container->getParameter('kernel.trusted_hosts')) {
Request::setTrustedHosts($trustedHosts);
Request::setTrustedHosts(\is_array($trustedHosts) ? $trustedHosts : preg_split('/\s*+,\s*+(?![^{]*})/', $trustedHosts));

Check failure on line 748 in src/Symfony/Component/HttpKernel/Kernel.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Component/HttpKernel/Kernel.php:748:117: InvalidArgument: Argument 2 of preg_split expects string, but UnitEnum|non-empty-scalar provided (see https://psalm.dev/004)

Check failure on line 748 in src/Symfony/Component/HttpKernel/Kernel.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Component/HttpKernel/Kernel.php:748:117: InvalidArgument: Argument 2 of preg_split expects string, but UnitEnum|non-empty-scalar provided (see https://psalm.dev/004)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this check that the parameter is a string before using preg_split on it ? Especially during booting, we need the code to be robust against unexpected parameter values (an old cache with an unsupported parameter might prevent you from running cache:clear in the prod environment)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't do it for the other parameters so I didn't bother

}

if ($container->hasParameter('kernel.trusted_proxies') && $container->hasParameter('kernel.trusted_headers') && $trustedProxies = $container->getParameter('kernel.trusted_proxies')) {
Request::setTrustedProxies(\is_array($trustedProxies) ? $trustedProxies : array_map('trim', explode(',', $trustedProxies)), $container->getParameter('kernel.trusted_headers'));
$trustedHeaders = $container->getParameter('kernel.trusted_headers');

if (\is_string($trustedHeaders)) {
$trustedHeaders = array_map('trim', explode(',', $trustedHeaders));
}

if (\is_array($trustedHeaders)) {
$trustedHeaderSet = 0;

foreach ($trustedHeaders as $header) {
if (!\defined($const = Request::class.'::HEADER_'.strtr(strtoupper($header), '-', '_'))) {
throw new \InvalidArgumentException(\sprintf('The trusted header "%s" is not supported.', $header));
}
$trustedHeaderSet |= \constant($const);
}
} else {
$trustedHeaderSet = $trustedHeaders ?? (Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO);
}

Request::setTrustedProxies(\is_array($trustedProxies) ? $trustedProxies : array_map('trim', explode(',', $trustedProxies)), $trustedHeaderSet);
}

return $container;
Expand Down
19 changes: 19 additions & 0 deletions src/Symfony/Component/HttpKernel/Tests/KernelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,25 @@ public function getContainerClass(): string
$this->assertMatchesRegularExpression('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*TestDebugContainer$/', $kernel->getContainerClass());
}

public function testTrustedParameters()
{
$kernel = new CustomProjectDirKernel(function (ContainerBuilder $container) {
$container->setParameter('kernel.trusted_hosts', '^a{2,3}.com$, ^b{2,}.com$');
$container->setParameter('kernel.trusted_proxies', 'a,b');
$container->setParameter('kernel.trusted_headers', 'x-forwarded-for');
});
$kernel->boot();

try {
$this->assertSame(['{^a{2,3}.com$}i', '{^b{2,}.com$}i'], Request::getTrustedHosts());
$this->assertSame(['a', 'b'], Request::getTrustedProxies());
$this->assertSame(Request::HEADER_X_FORWARDED_FOR, Request::getTrustedHeaderSet());
} finally {
Request::setTrustedHosts([]);
Request::setTrustedProxies([], 0);
}
}

/**
* Returns a mock for the BundleInterface.
*/
Expand Down
Loading