Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[HttpFoundation][FrameworkBundle] Add BinaryFileResponse::setXSendfileHeader() and corresponding config option to help configure upload acceleration #58162

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

Closed
Closed
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
2 changes: 2 additions & 0 deletions 2 src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ CHANGELOG
* Deprecate making `cache.app` adapter taggable, use the `cache.app.taggable` adapter instead
* Enable `json_decode_detailed_errors` in the default serializer context in debug mode by default when `seld/jsonlint` is installed
* Register `Symfony\Component\Serializer\NameConverter\SnakeCaseToCamelCaseNameConverter` as a service named `serializer.name_converter.snake_case_to_camel_case` if available
* Add support for `SYMFONY_TRUSTED_PROXIES`, `SYMFONY_TRUSTED_HEADERS`, `SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER` and `SYMFONY_TRUSTED_HOSTS` env vars
OskarStark marked this conversation as resolved.
Show resolved Hide resolved
* Add option `framework.x_sendfile_header` to configure the name of the header that should be used for file uploads acceleration, if supported by the web-server

7.1
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,11 @@ 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('x_sendfile_header')
->info('The name of the header that should be used for file uploads acceleration, if supported by the web-server.')
->defaultValue('%env(default::SYMFONY_X_SENDFILE_HEADER)%')
->end()
->scalarNode('ide')->defaultValue($this->debug ? '%env(default::SYMFONY_IDE)%' : null)->end()
->booleanNode('test')->end()
Expand All @@ -108,26 +112,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 @@ -312,14 +312,15 @@ 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.x_sendfile_header', $config['x_sendfile_header']);
$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 @@ -3103,25 +3104,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
4 changes: 4 additions & 0 deletions 4 src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@
if ($this->container->hasParameter('kernel.trust_x_sendfile_type_header') && $this->container->getParameter('kernel.trust_x_sendfile_type_header')) {
BinaryFileResponse::trustXSendfileTypeHeader();
}

if ($this->container->hasParameter('kernel.x_sendfile_header') && $header = $this->container->getParameter('kernel.x_sendfile_header')) {
BinaryFileResponse::setXSendfileHeader($header);

Check failure on line 111 in src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php:111:52: InvalidArgument: Argument 1 of Symfony\Component\HttpFoundation\BinaryFileResponse::setXSendfileHeader expects string, but UnitEnum|non-empty-array<array-key, mixed>|non-empty-scalar provided (see https://psalm.dev/004)

Check failure on line 111 in src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php:111:52: InvalidArgument: Argument 1 of Symfony\Component\HttpFoundation\BinaryFileResponse::setXSendfileHeader expects string, but UnitEnum|non-empty-array<array-key, mixed>|non-empty-scalar provided (see https://psalm.dev/004)
}
}

public function build(ContainerBuilder $container): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -704,19 +704,17 @@ 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)%',
'x_sendfile_header' => '%env(default::SYMFONY_X_SENDFILE_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
4 changes: 2 additions & 2 deletions 4 src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/error-handler": "^6.4|^7.0",
"symfony/event-dispatcher": "^6.4|^7.0",
"symfony/http-foundation": "^6.4|^7.0",
"symfony/http-kernel": "^6.4|^7.0",
"symfony/http-foundation": "^7.2",
"symfony/http-kernel": "^7.2",
"symfony/polyfill-mbstring": "~1.0",
"symfony/filesystem": "^7.1",
"symfony/finder": "^6.4|^7.0",
Expand Down
14 changes: 12 additions & 2 deletions 14 src/Symfony/Component/HttpFoundation/BinaryFileResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
class BinaryFileResponse extends Response
{
protected static bool $trustXSendfileTypeHeader = false;
protected static ?string $xSendfileHeader = null;

protected File $file;
protected ?\SplTempFileObject $tempFileObject = null;
Expand Down Expand Up @@ -208,9 +209,10 @@ public function prepare(Request $request): static
$this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none');
}

if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
$type = self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type') ? $request->headers->get('X-Sendfile-Type') : self::$xSendfileHeader;

if (null !== $type) {
// Use X-Sendfile, do not send any content.
$type = $request->headers->get('X-Sendfile-Type');
$path = $this->file->getRealPath();
// Fall back to scheme://path for stream wrapped locations.
if (false === $path) {
Expand Down Expand Up @@ -370,6 +372,14 @@ public static function trustXSendfileTypeHeader(): void
self::$trustXSendfileTypeHeader = true;
}

/**
* Trust X-Sendfile header and the likes.
*/
public static function setXSendfileHeader(string $name): void
{
self::$xSendfileHeader = $name;
}

/**
* If this is set to true, the file will be unlinked after the request is sent
* Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
Expand Down
1 change: 1 addition & 0 deletions 1 src/Symfony/Component/HttpFoundation/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ CHANGELOG
* Add optional `$requests` parameter to `RequestStack::__construct()`
* Add optional `$v4Bytes` and `$v6Bytes` parameters to `IpUtils::anonymize()`
* Add `PRIVATE_SUBNETS` as a shortcut for private IP address ranges to `Request::setTrustedProxies()`
* Add `BinaryFileResponse::setXSendfileHeader()`

7.1
---
Expand Down
1 change: 1 addition & 0 deletions 1 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 25 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)
}

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 19 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
Morty Proxy This is a proxified and sanitized view of the page, visit original site.