Skip to content
Open
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
57 changes: 55 additions & 2 deletions system/HTTP/ContentSecurityPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -878,14 +878,43 @@ protected function addOption($options, string $target, ?bool $explicitReporting
{
// Ensure we have an array to work with...
if (is_string($this->{$target})) {
$this->{$target} = [$this->{$target} => $this->reportOnly];
$targetValue = trim($this->{$target});

$this->{$target} = [];

if ($targetValue !== '') {
foreach (preg_split('/\s+/', $targetValue) as $opt) {
$this->{$target}[$opt] = $this->reportOnly;
}
} elseif (in_array($target, ['sandbox', 'frameAncestors'], true)) {
$this->{$target}[''] = $this->reportOnly;
}
} elseif (! is_array($this->{$target})) {
$this->{$target} = [];
}

$options = is_array($options) ? $options : [$options];

foreach ($options as $option) {
$option = (string) $option;

if ($option === '' && ! in_array($target, ['sandbox', 'frameAncestors'], true)) {
continue;
}

$this->{$target}[$option] = $explicitReporting ?? $this->reportOnly;
}

if (in_array($target, ['sandbox', 'frameAncestors'], true) && isset($this->{$target}[''])) {
$emptyReportOnly = $this->{$target}[''];

foreach ($this->{$target} as $val => $reportOnly) {
if ($val !== '' && $reportOnly === $emptyReportOnly) {
unset($this->{$target}['']);
break;
}
}
}
}

/**
Expand Down Expand Up @@ -1013,13 +1042,29 @@ protected function buildHeaders(ResponseInterface $response)
protected function addToHeader(string $name, $values = null)
{
if (is_string($values)) {
$values = [$values => $this->reportOnly];
$valueStr = trim($values);

if ($valueStr === '') {
if (! in_array($name, ['sandbox', 'frame-ancestors'], true)) {
return;
}

$values = ['' => $this->reportOnly];
} else {
$values = [];

foreach (preg_split('/\s+/', $valueStr) as $val) {
$values[$val] = $this->reportOnly;
}
}
}

$sources = [];
$reportSources = [];

foreach ($values as $value => $reportOnly) {
$value = (string) $value;

if (
in_array($value, $this->validSources, true)
|| str_starts_with($value, 'nonce-')
Expand All @@ -1038,10 +1083,18 @@ protected function addToHeader(string $name, $values = null)
}

if ($sources !== []) {
if (count($sources) > 1) {
$sources = array_values(array_filter($sources, static fn ($s): bool => $s !== ''));
}

$this->tempHeaders[$name] = implode(' ', $sources);
}

if ($reportSources !== []) {
if (count($reportSources) > 1) {
$reportSources = array_values(array_filter($reportSources, static fn ($s): bool => $s !== ''));
}

$this->reportOnlyHeaders[$name] = implode(' ', $reportSources);
}
}
Expand Down
132 changes: 132 additions & 0 deletions tests/system/HTTP/ContentSecurityPolicyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,138 @@ public function testSandboxFlags(): void
$this->assertContains('sandbox allow-popups allow-top-navigation', $this->getCspDirectives($header));
}

#[PreserveGlobalState(false)]
#[RunInSeparateProcess]
public function testSandboxEmptyFlagThenFlags(): void
{
$this->csp->reportOnly(false);
$this->csp->addSandbox('');
$this->csp->addSandbox('allow-scripts');
$this->assertTrue($this->work());

$header = $this->getHeaderEmitted('Content-Security-Policy');
$this->assertIsString($header);
$this->assertContains('sandbox allow-scripts', $this->getCspDirectives($header));
}

#[PreserveGlobalState(false)]
#[RunInSeparateProcess]
public function testAddOptionWithSpaceSeparatedString(): void
{
$config = new CSPConfig();
$config->baseURI = 'self example.com';

$csp = new ContentSecurityPolicy($config);

$response = new Response(config(App::class));
$response->pretend(true);

$csp->addBaseURI('another.com');
$csp->finalize($response);

$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
$this->assertContains("base-uri 'self' example.com another.com", $directives);
}

#[PreserveGlobalState(false)]
#[RunInSeparateProcess]
public function testAddOptionWithEmptyStringTarget(): void
{
$config = new CSPConfig();
$config->baseURI = '';

$csp = new ContentSecurityPolicy($config);

$response = new Response(config(App::class));
$response->pretend(true);

$csp->addBaseURI('example.com');
$csp->finalize($response);

$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
$this->assertContains('base-uri example.com', $directives);
}

#[PreserveGlobalState(false)]
#[RunInSeparateProcess]
public function testAddOptionNumericString(): void
{
$this->csp->addBaseURI('0');
$this->assertTrue($this->work());

$header = $this->getHeaderEmitted('Content-Security-Policy');
$this->assertIsString($header);
$this->assertContains('base-uri 0', $this->getCspDirectives($header));
}

#[PreserveGlobalState(false)]
#[RunInSeparateProcess]
public function testConfiguredBareSandboxWithAddSandboxNoop(): void
{
$config = new CSPConfig();
$config->sandbox = '';

$csp = new ContentSecurityPolicy($config);

$response = new Response(config(App::class));
$response->pretend(true);

$csp->addSandbox([]);
$csp->finalize($response);

$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
$this->assertContains('sandbox', $directives);
}

#[PreserveGlobalState(false)]
#[RunInSeparateProcess]
public function testAddFrameAncestorEmptyString(): void
{
$this->csp->addFrameAncestor('');
$this->assertTrue($this->work());

$header = $this->getHeaderEmitted('Content-Security-Policy');
$this->assertIsString($header);
$this->assertContains('frame-ancestors', $this->getCspDirectives($header));
}

#[PreserveGlobalState(false)]
#[RunInSeparateProcess]
public function testSandboxMixedModeEnforcedAndReportOnly(): void
{
$this->csp->addSandbox('', false);
$this->csp->addSandbox('allow-scripts', true);
$this->assertTrue($this->work());

$enforced = $this->getHeaderEmitted('Content-Security-Policy');
$this->assertIsString($enforced);
$this->assertContains('sandbox', $this->getCspDirectives($enforced));

$reportOnly = $this->getHeaderEmitted('Content-Security-Policy-Report-Only');
$this->assertIsString($reportOnly);
$this->assertContains('sandbox allow-scripts', $this->getCspDirectives($reportOnly));
}

#[PreserveGlobalState(false)]
#[RunInSeparateProcess]
public function testConfiguredEmptyDirectivesEmitted(): void
{
$config = new CSPConfig();
$config->sandbox = '';
$config->frameAncestors = '';

$csp = new ContentSecurityPolicy($config);

$response = new Response(config(App::class));
$response->pretend(true);

$csp->finalize($response);

$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
$this->assertContains('sandbox', $directives);
$this->assertContains('frame-ancestors', $directives);
}

#[PreserveGlobalState(false)]
#[RunInSeparateProcess]
public function testUpgradeInsecureRequests(): void
Expand Down
1 change: 1 addition & 0 deletions user_guide_src/source/changelogs/v4.7.6.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Bugs Fixed
is used instead. Values that cannot be converted to a string, such as objects
not implementing ``Stringable``, now throw a ``FormatException`` instead of a
fatal ``Error``.
- **HTTP:** Fixed a bug in ``ContentSecurityPolicy::addOption()`` where converting string directive values to array keys resulted in invalid entries for empty strings, unquoted values for space-separated lists, and ``TypeError`` for numeric strings.
- **Security:** Fixed a bug where a valid JSON request body that is not an object
(for example a JSON array) was corrupted after CSRF verification when the
token was sent via the ``X-CSRF-TOKEN`` header.
Expand Down
Loading