Skip to content

Commit 3fbbfb9

Browse files
committed
fix: normalize string values and keys in ContentSecurityPolicy::addOption()
- Normalize space-separated and empty strings into array options via stringToOptions() - Cast numeric string array keys back to string to prevent TypeError under strict types - Preserve empty source lists as deny-all directives across all directives - Retain empty markers when other options move between reporting modes - Add comprehensive regression tests for config and runtime directives
1 parent b74fff9 commit 3fbbfb9

3 files changed

Lines changed: 273 additions & 3 deletions

File tree

‎system/HTTP/ContentSecurityPolicy.php‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -878,16 +878,40 @@ protected function addOption($options, string $target, ?bool $explicitReporting
878878
{
879879
// Ensure we have an array to work with...
880880
if (is_string($this->{$target})) {
881-
$this->{$target} = [$this->{$target} => $this->reportOnly];
881+
$this->{$target} = $this->stringToOptions($this->{$target});
882+
} elseif (! is_array($this->{$target})) {
883+
$this->{$target} = [];
882884
}
883885

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

886888
foreach ($options as $option) {
887-
$this->{$target}[$option] = $explicitReporting ?? $this->reportOnly;
889+
$this->{$target}[trim((string) $option)] = $explicitReporting ?? $this->reportOnly;
888890
}
889891
}
890892

893+
/**
894+
* Converts a string directive value into an array of options.
895+
*
896+
* @return array<string, bool>
897+
*/
898+
private function stringToOptions(string $values): array
899+
{
900+
$valueStr = trim($values);
901+
902+
if ($valueStr === '') {
903+
return ['' => $this->reportOnly];
904+
}
905+
906+
$options = [];
907+
908+
foreach (preg_split('/\s+/', $valueStr) as $val) {
909+
$options[$val] = $this->reportOnly;
910+
}
911+
912+
return $options;
913+
}
914+
891915
/**
892916
* Scans the body of the request message and replaces any nonce
893917
* placeholders with actual nonces, that we'll then add to our
@@ -1012,14 +1036,20 @@ protected function buildHeaders(ResponseInterface $response)
10121036
*/
10131037
protected function addToHeader(string $name, $values = null)
10141038
{
1039+
if ($values === null) {
1040+
return;
1041+
}
1042+
10151043
if (is_string($values)) {
1016-
$values = [$values => $this->reportOnly];
1044+
$values = $this->stringToOptions($values);
10171045
}
10181046

10191047
$sources = [];
10201048
$reportSources = [];
10211049

10221050
foreach ($values as $value => $reportOnly) {
1051+
$value = (string) $value;
1052+
10231053
if (
10241054
in_array($value, $this->validSources, true)
10251055
|| str_starts_with($value, 'nonce-')
@@ -1038,10 +1068,18 @@ protected function addToHeader(string $name, $values = null)
10381068
}
10391069

10401070
if ($sources !== []) {
1071+
if (count($sources) > 1) {
1072+
$sources = array_values(array_filter($sources, static fn ($s): bool => $s !== ''));
1073+
}
1074+
10411075
$this->tempHeaders[$name] = implode(' ', $sources);
10421076
}
10431077

10441078
if ($reportSources !== []) {
1079+
if (count($reportSources) > 1) {
1080+
$reportSources = array_values(array_filter($reportSources, static fn ($s): bool => $s !== ''));
1081+
}
1082+
10451083
$this->reportOnlyHeaders[$name] = implode(' ', $reportSources);
10461084
}
10471085
}

‎tests/system/HTTP/ContentSecurityPolicyTest.php‎

Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -756,6 +756,237 @@ public function testSandboxFlags(): void
756756
$this->assertContains('sandbox allow-popups allow-top-navigation', $this->getCspDirectives($header));
757757
}
758758

759+
#[PreserveGlobalState(false)]
760+
#[RunInSeparateProcess]
761+
public function testSandboxEmptyFlagThenFlags(): void
762+
{
763+
$this->csp->reportOnly(false);
764+
$this->csp->addSandbox('');
765+
$this->csp->addSandbox('allow-scripts');
766+
$this->assertTrue($this->work());
767+
768+
$header = $this->getHeaderEmitted('Content-Security-Policy');
769+
$this->assertIsString($header);
770+
$this->assertContains('sandbox allow-scripts', $this->getCspDirectives($header));
771+
}
772+
773+
#[PreserveGlobalState(false)]
774+
#[RunInSeparateProcess]
775+
public function testAddOptionWithSpaceSeparatedString(): void
776+
{
777+
$config = new CSPConfig();
778+
$config->baseURI = 'self example.com';
779+
780+
$csp = new ContentSecurityPolicy($config);
781+
782+
$response = new Response(config(App::class));
783+
$response->pretend(true);
784+
785+
$csp->addBaseURI('another.com');
786+
$csp->finalize($response);
787+
788+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
789+
$this->assertContains("base-uri 'self' example.com another.com", $directives);
790+
}
791+
792+
#[PreserveGlobalState(false)]
793+
#[RunInSeparateProcess]
794+
public function testAddOptionWithEmptyStringTarget(): void
795+
{
796+
$config = new CSPConfig();
797+
$config->baseURI = '';
798+
799+
$csp = new ContentSecurityPolicy($config);
800+
801+
$response = new Response(config(App::class));
802+
$response->pretend(true);
803+
804+
$csp->addBaseURI('example.com');
805+
$csp->finalize($response);
806+
807+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
808+
$this->assertContains('base-uri example.com', $directives);
809+
}
810+
811+
#[PreserveGlobalState(false)]
812+
#[RunInSeparateProcess]
813+
public function testAddOptionNumericString(): void
814+
{
815+
$this->csp->addBaseURI('0');
816+
$this->assertTrue($this->work());
817+
818+
$header = $this->getHeaderEmitted('Content-Security-Policy');
819+
$this->assertIsString($header);
820+
$this->assertContains('base-uri 0', $this->getCspDirectives($header));
821+
}
822+
823+
#[PreserveGlobalState(false)]
824+
#[RunInSeparateProcess]
825+
public function testConfiguredBareSandboxWithAddSandboxNoop(): void
826+
{
827+
$config = new CSPConfig();
828+
$config->sandbox = '';
829+
830+
$csp = new ContentSecurityPolicy($config);
831+
832+
$response = new Response(config(App::class));
833+
$response->pretend(true);
834+
835+
$csp->addSandbox([]);
836+
$csp->finalize($response);
837+
838+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
839+
$this->assertContains('sandbox', $directives);
840+
}
841+
842+
#[PreserveGlobalState(false)]
843+
#[RunInSeparateProcess]
844+
public function testAddFrameAncestorEmptyString(): void
845+
{
846+
$this->csp->addFrameAncestor('');
847+
$this->assertTrue($this->work());
848+
849+
$header = $this->getHeaderEmitted('Content-Security-Policy');
850+
$this->assertIsString($header);
851+
$this->assertContains('frame-ancestors', $this->getCspDirectives($header));
852+
}
853+
854+
#[PreserveGlobalState(false)]
855+
#[RunInSeparateProcess]
856+
public function testSandboxMixedModeEnforcedAndReportOnly(): void
857+
{
858+
$this->csp->addSandbox('', false);
859+
$this->csp->addSandbox('allow-scripts', true);
860+
$this->assertTrue($this->work());
861+
862+
$enforced = $this->getHeaderEmitted('Content-Security-Policy');
863+
$this->assertIsString($enforced);
864+
$this->assertContains('sandbox', $this->getCspDirectives($enforced));
865+
866+
$reportOnly = $this->getHeaderEmitted('Content-Security-Policy-Report-Only');
867+
$this->assertIsString($reportOnly);
868+
$this->assertContains('sandbox allow-scripts', $this->getCspDirectives($reportOnly));
869+
}
870+
871+
#[PreserveGlobalState(false)]
872+
#[RunInSeparateProcess]
873+
public function testOptionMovedBetweenReportingModesPreservesEmptyMarker(): void
874+
{
875+
$this->csp->addSandbox('', false);
876+
$this->csp->addSandbox('allow-scripts', false);
877+
$this->csp->addSandbox('allow-scripts', true);
878+
879+
$this->csp->addFrameAncestor('', false);
880+
$this->csp->addFrameAncestor('https://example.com', false);
881+
$this->csp->addFrameAncestor('https://example.com', true);
882+
883+
$this->assertTrue($this->work());
884+
885+
$enforced = $this->getHeaderEmitted('Content-Security-Policy');
886+
$this->assertIsString($enforced);
887+
$enforcedDirectives = $this->getCspDirectives($enforced);
888+
$this->assertContains('sandbox', $enforcedDirectives);
889+
$this->assertContains('frame-ancestors', $enforcedDirectives);
890+
$this->assertNotContains('sandbox allow-scripts', $enforcedDirectives);
891+
$this->assertNotContains('frame-ancestors https://example.com', $enforcedDirectives);
892+
893+
$reportOnly = $this->getHeaderEmitted('Content-Security-Policy-Report-Only');
894+
$this->assertIsString($reportOnly);
895+
$reportOnlyDirectives = $this->getCspDirectives($reportOnly);
896+
$this->assertContains('sandbox allow-scripts', $reportOnlyDirectives);
897+
$this->assertContains('frame-ancestors https://example.com', $reportOnlyDirectives);
898+
}
899+
900+
#[PreserveGlobalState(false)]
901+
#[RunInSeparateProcess]
902+
public function testConfiguredEmptyDirectivesEmitted(): void
903+
{
904+
$config = new CSPConfig();
905+
$config->sandbox = '';
906+
$config->frameAncestors = '';
907+
$config->formAction = '';
908+
$config->fontSrc = '';
909+
$config->connectSrc = '';
910+
911+
$csp = new ContentSecurityPolicy($config);
912+
913+
$response = new Response(config(App::class));
914+
$response->pretend(true);
915+
916+
$csp->finalize($response);
917+
918+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
919+
$this->assertContains('sandbox', $directives);
920+
$this->assertContains('frame-ancestors', $directives);
921+
$this->assertContains('form-action', $directives);
922+
$this->assertContains('font-src', $directives);
923+
$this->assertContains('connect-src', $directives);
924+
}
925+
926+
#[PreserveGlobalState(false)]
927+
#[RunInSeparateProcess]
928+
public function testConfiguredEmptyFormActionWithAddFormActionNoop(): void
929+
{
930+
$config = new CSPConfig();
931+
$config->formAction = '';
932+
933+
$csp = new ContentSecurityPolicy($config);
934+
935+
$response = new Response(config(App::class));
936+
$response->pretend(true);
937+
938+
$csp->addFormAction([]);
939+
$csp->finalize($response);
940+
941+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
942+
$this->assertContains('form-action', $directives);
943+
}
944+
945+
#[PreserveGlobalState(false)]
946+
#[RunInSeparateProcess]
947+
public function testClearDirectiveThenAddEmptySource(): void
948+
{
949+
$this->csp->clearDirective('form-action');
950+
$this->csp->addFormAction('');
951+
$this->csp->clearDirective('connect-src');
952+
$this->csp->addConnectSrc('');
953+
$this->assertTrue($this->work());
954+
955+
$header = $this->getHeaderEmitted('Content-Security-Policy');
956+
$this->assertIsString($header);
957+
$directives = $this->getCspDirectives($header);
958+
$this->assertContains('form-action', $directives);
959+
$this->assertContains('connect-src', $directives);
960+
}
961+
962+
#[PreserveGlobalState(false)]
963+
#[RunInSeparateProcess]
964+
public function testAddEmptySourceToFontSrc(): void
965+
{
966+
$this->csp->addFontSrc('');
967+
$this->assertTrue($this->work());
968+
969+
$header = $this->getHeaderEmitted('Content-Security-Policy');
970+
$this->assertIsString($header);
971+
$directives = $this->getCspDirectives($header);
972+
$this->assertContains('font-src', $directives);
973+
}
974+
975+
#[PreserveGlobalState(false)]
976+
#[RunInSeparateProcess]
977+
public function testRedundantEmptySourceFilteredWhenOtherSourcesPresent(): void
978+
{
979+
// connectSrc defaults to 'self'
980+
$this->csp->addConnectSrc('');
981+
$this->assertTrue($this->work());
982+
983+
$header = $this->getHeaderEmitted('Content-Security-Policy');
984+
$this->assertIsString($header);
985+
$directives = $this->getCspDirectives($header);
986+
$this->assertContains("connect-src 'self'", $directives);
987+
$this->assertNotContains('connect-src', $directives);
988+
}
989+
759990
#[PreserveGlobalState(false)]
760991
#[RunInSeparateProcess]
761992
public function testUpgradeInsecureRequests(): void

‎user_guide_src/source/changelogs/v4.7.6.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ Bugs Fixed
3838
is used instead. Values that cannot be converted to a string, such as objects
3939
not implementing ``Stringable``, now throw a ``FormatException`` instead of a
4040
fatal ``Error``.
41+
- **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.
4142
- **Security:** Fixed a bug where a valid JSON request body that is not an object
4243
(for example a JSON array) was corrupted after CSRF verification when the
4344
token was sent via the ``X-CSRF-TOKEN`` header.

0 commit comments

Comments
 (0)