Skip to content

Commit 6135b0e

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 62f5420 commit 6135b0e

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
@@ -896,16 +896,40 @@ protected function addOption($options, string $target, ?bool $explicitReporting
896896
{
897897
// Ensure we have an array to work with...
898898
if (is_string($this->{$target})) {
899-
$this->{$target} = [$this->{$target} => $this->reportOnly];
899+
$this->{$target} = $this->stringToOptions($this->{$target});
900+
} elseif (! is_array($this->{$target})) {
901+
$this->{$target} = [];
900902
}
901903

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

904906
foreach ($options as $option) {
905-
$this->{$target}[$option] = $explicitReporting ?? $this->reportOnly;
907+
$this->{$target}[trim((string) $option)] = $explicitReporting ?? $this->reportOnly;
906908
}
907909
}
908910

911+
/**
912+
* Converts a string directive value into an array of options.
913+
*
914+
* @return array<string, bool>
915+
*/
916+
private function stringToOptions(string $values): array
917+
{
918+
$valueStr = trim($values);
919+
920+
if ($valueStr === '') {
921+
return ['' => $this->reportOnly];
922+
}
923+
924+
$options = [];
925+
926+
foreach (preg_split('/\s+/', $valueStr) as $val) {
927+
$options[$val] = $this->reportOnly;
928+
}
929+
930+
return $options;
931+
}
932+
909933
/**
910934
* Scans the body of the request message and replaces any nonce
911935
* placeholders with actual nonces, that we'll then add to our
@@ -1030,14 +1054,20 @@ protected function buildHeaders(ResponseInterface $response)
10301054
*/
10311055
protected function addToHeader(string $name, $values = null)
10321056
{
1057+
if ($values === null) {
1058+
return;
1059+
}
1060+
10331061
if (is_string($values)) {
1034-
$values = [$values => $this->reportOnly];
1062+
$values = $this->stringToOptions($values);
10351063
}
10361064

10371065
$sources = [];
10381066
$reportSources = [];
10391067

10401068
foreach ($values as $value => $reportOnly) {
1069+
$value = (string) $value;
1070+
10411071
if (
10421072
in_array($value, $this->validSources, true)
10431073
|| str_starts_with($value, 'nonce-')
@@ -1056,10 +1086,18 @@ protected function addToHeader(string $name, $values = null)
10561086
}
10571087

10581088
if ($sources !== []) {
1089+
if (count($sources) > 1) {
1090+
$sources = array_values(array_filter($sources, static fn ($s): bool => $s !== ''));
1091+
}
1092+
10591093
$this->tempHeaders[$name] = implode(' ', $sources);
10601094
}
10611095

10621096
if ($reportSources !== []) {
1097+
if (count($reportSources) > 1) {
1098+
$reportSources = array_values(array_filter($reportSources, static fn ($s): bool => $s !== ''));
1099+
}
1100+
10631101
$this->reportOnlyHeaders[$name] = implode(' ', $reportSources);
10641102
}
10651103
}

‎tests/system/HTTP/ContentSecurityPolicyTest.php‎

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

803+
#[PreserveGlobalState(false)]
804+
#[RunInSeparateProcess]
805+
public function testSandboxEmptyFlagThenFlags(): void
806+
{
807+
$this->csp->reportOnly(false);
808+
$this->csp->addSandbox('');
809+
$this->csp->addSandbox('allow-scripts');
810+
$this->assertTrue($this->work());
811+
812+
$header = $this->getHeaderEmitted('Content-Security-Policy');
813+
$this->assertIsString($header);
814+
$this->assertContains('sandbox allow-scripts', $this->getCspDirectives($header));
815+
}
816+
817+
#[PreserveGlobalState(false)]
818+
#[RunInSeparateProcess]
819+
public function testAddOptionWithSpaceSeparatedString(): void
820+
{
821+
$config = new CSPConfig();
822+
$config->baseURI = 'self example.com';
823+
824+
$csp = new ContentSecurityPolicy($config);
825+
826+
$response = new Response(config(App::class));
827+
$response->pretend(true);
828+
829+
$csp->addBaseURI('another.com');
830+
$csp->finalize($response);
831+
832+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
833+
$this->assertContains("base-uri 'self' example.com another.com", $directives);
834+
}
835+
836+
#[PreserveGlobalState(false)]
837+
#[RunInSeparateProcess]
838+
public function testAddOptionWithEmptyStringTarget(): void
839+
{
840+
$config = new CSPConfig();
841+
$config->baseURI = '';
842+
843+
$csp = new ContentSecurityPolicy($config);
844+
845+
$response = new Response(config(App::class));
846+
$response->pretend(true);
847+
848+
$csp->addBaseURI('example.com');
849+
$csp->finalize($response);
850+
851+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
852+
$this->assertContains('base-uri example.com', $directives);
853+
}
854+
855+
#[PreserveGlobalState(false)]
856+
#[RunInSeparateProcess]
857+
public function testAddOptionNumericString(): void
858+
{
859+
$this->csp->addBaseURI('0');
860+
$this->assertTrue($this->work());
861+
862+
$header = $this->getHeaderEmitted('Content-Security-Policy');
863+
$this->assertIsString($header);
864+
$this->assertContains('base-uri 0', $this->getCspDirectives($header));
865+
}
866+
867+
#[PreserveGlobalState(false)]
868+
#[RunInSeparateProcess]
869+
public function testConfiguredBareSandboxWithAddSandboxNoop(): void
870+
{
871+
$config = new CSPConfig();
872+
$config->sandbox = '';
873+
874+
$csp = new ContentSecurityPolicy($config);
875+
876+
$response = new Response(config(App::class));
877+
$response->pretend(true);
878+
879+
$csp->addSandbox([]);
880+
$csp->finalize($response);
881+
882+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
883+
$this->assertContains('sandbox', $directives);
884+
}
885+
886+
#[PreserveGlobalState(false)]
887+
#[RunInSeparateProcess]
888+
public function testAddFrameAncestorEmptyString(): void
889+
{
890+
$this->csp->addFrameAncestor('');
891+
$this->assertTrue($this->work());
892+
893+
$header = $this->getHeaderEmitted('Content-Security-Policy');
894+
$this->assertIsString($header);
895+
$this->assertContains('frame-ancestors', $this->getCspDirectives($header));
896+
}
897+
898+
#[PreserveGlobalState(false)]
899+
#[RunInSeparateProcess]
900+
public function testSandboxMixedModeEnforcedAndReportOnly(): void
901+
{
902+
$this->csp->addSandbox('', false);
903+
$this->csp->addSandbox('allow-scripts', true);
904+
$this->assertTrue($this->work());
905+
906+
$enforced = $this->getHeaderEmitted('Content-Security-Policy');
907+
$this->assertIsString($enforced);
908+
$this->assertContains('sandbox', $this->getCspDirectives($enforced));
909+
910+
$reportOnly = $this->getHeaderEmitted('Content-Security-Policy-Report-Only');
911+
$this->assertIsString($reportOnly);
912+
$this->assertContains('sandbox allow-scripts', $this->getCspDirectives($reportOnly));
913+
}
914+
915+
#[PreserveGlobalState(false)]
916+
#[RunInSeparateProcess]
917+
public function testOptionMovedBetweenReportingModesPreservesEmptyMarker(): void
918+
{
919+
$this->csp->addSandbox('', false);
920+
$this->csp->addSandbox('allow-scripts', false);
921+
$this->csp->addSandbox('allow-scripts', true);
922+
923+
$this->csp->addFrameAncestor('', false);
924+
$this->csp->addFrameAncestor('https://example.com', false);
925+
$this->csp->addFrameAncestor('https://example.com', true);
926+
927+
$this->assertTrue($this->work());
928+
929+
$enforced = $this->getHeaderEmitted('Content-Security-Policy');
930+
$this->assertIsString($enforced);
931+
$enforcedDirectives = $this->getCspDirectives($enforced);
932+
$this->assertContains('sandbox', $enforcedDirectives);
933+
$this->assertContains('frame-ancestors', $enforcedDirectives);
934+
$this->assertNotContains('sandbox allow-scripts', $enforcedDirectives);
935+
$this->assertNotContains('frame-ancestors https://example.com', $enforcedDirectives);
936+
937+
$reportOnly = $this->getHeaderEmitted('Content-Security-Policy-Report-Only');
938+
$this->assertIsString($reportOnly);
939+
$reportOnlyDirectives = $this->getCspDirectives($reportOnly);
940+
$this->assertContains('sandbox allow-scripts', $reportOnlyDirectives);
941+
$this->assertContains('frame-ancestors https://example.com', $reportOnlyDirectives);
942+
}
943+
944+
#[PreserveGlobalState(false)]
945+
#[RunInSeparateProcess]
946+
public function testConfiguredEmptyDirectivesEmitted(): void
947+
{
948+
$config = new CSPConfig();
949+
$config->sandbox = '';
950+
$config->frameAncestors = '';
951+
$config->formAction = '';
952+
$config->fontSrc = '';
953+
$config->connectSrc = '';
954+
955+
$csp = new ContentSecurityPolicy($config);
956+
957+
$response = new Response(config(App::class));
958+
$response->pretend(true);
959+
960+
$csp->finalize($response);
961+
962+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
963+
$this->assertContains('sandbox', $directives);
964+
$this->assertContains('frame-ancestors', $directives);
965+
$this->assertContains('form-action', $directives);
966+
$this->assertContains('font-src', $directives);
967+
$this->assertContains('connect-src', $directives);
968+
}
969+
970+
#[PreserveGlobalState(false)]
971+
#[RunInSeparateProcess]
972+
public function testConfiguredEmptyFormActionWithAddFormActionNoop(): void
973+
{
974+
$config = new CSPConfig();
975+
$config->formAction = '';
976+
977+
$csp = new ContentSecurityPolicy($config);
978+
979+
$response = new Response(config(App::class));
980+
$response->pretend(true);
981+
982+
$csp->addFormAction([]);
983+
$csp->finalize($response);
984+
985+
$directives = $this->getCspDirectives($response->getHeaderLine('Content-Security-Policy'));
986+
$this->assertContains('form-action', $directives);
987+
}
988+
989+
#[PreserveGlobalState(false)]
990+
#[RunInSeparateProcess]
991+
public function testClearDirectiveThenAddEmptySource(): void
992+
{
993+
$this->csp->clearDirective('form-action');
994+
$this->csp->addFormAction('');
995+
$this->csp->clearDirective('connect-src');
996+
$this->csp->addConnectSrc('');
997+
$this->assertTrue($this->work());
998+
999+
$header = $this->getHeaderEmitted('Content-Security-Policy');
1000+
$this->assertIsString($header);
1001+
$directives = $this->getCspDirectives($header);
1002+
$this->assertContains('form-action', $directives);
1003+
$this->assertContains('connect-src', $directives);
1004+
}
1005+
1006+
#[PreserveGlobalState(false)]
1007+
#[RunInSeparateProcess]
1008+
public function testAddEmptySourceToFontSrc(): void
1009+
{
1010+
$this->csp->addFontSrc('');
1011+
$this->assertTrue($this->work());
1012+
1013+
$header = $this->getHeaderEmitted('Content-Security-Policy');
1014+
$this->assertIsString($header);
1015+
$directives = $this->getCspDirectives($header);
1016+
$this->assertContains('font-src', $directives);
1017+
}
1018+
1019+
#[PreserveGlobalState(false)]
1020+
#[RunInSeparateProcess]
1021+
public function testRedundantEmptySourceFilteredWhenOtherSourcesPresent(): void
1022+
{
1023+
// connectSrc defaults to 'self'
1024+
$this->csp->addConnectSrc('');
1025+
$this->assertTrue($this->work());
1026+
1027+
$header = $this->getHeaderEmitted('Content-Security-Policy');
1028+
$this->assertIsString($header);
1029+
$directives = $this->getCspDirectives($header);
1030+
$this->assertContains("connect-src 'self'", $directives);
1031+
$this->assertNotContains('connect-src', $directives);
1032+
}
1033+
8031034
#[PreserveGlobalState(false)]
8041035
#[RunInSeparateProcess]
8051036
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
- **Commands:** Fixed a bug where generator commands did not sort the imports of a template with CRLF line endings.
3939
- **Format:** Fixed ``XMLFormatter`` so that an array key that becomes empty after sanitization no longer triggers a ``ValueError``; the fallback tag name ``item`` 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``.
4040
- **Helpers:** Fixed a regression in v4.7.5 where ``set_value()`` threw a ``TypeError`` when the default value was not a string or an array, such as an integer, a float, ``null``, or a ``Stringable`` object. Such values are now converted to a string.
41+
- **HTTP:** Fixed a bug in ``ContentSecurityPolicy`` where a numeric source such as ``'0'`` threw a ``TypeError``, and a space-separated directive string in ``Config\\ContentSecurityPolicy`` was emitted as one unquoted source.
4142
- **HTTP:** Fixed a bug in ``ContentSecurityPolicy::setDefaultSrc()`` where passing an array of URIs resulted in an invalid ``'Array'`` directive.
4243
- **HTTP:** Fixed stale ``$_REQUEST`` values after ``SiteURIFactory`` normalizes GET parameters, so ``Validation::withRequest()`` reads the normalized values while unrelated REQUEST entries are preserved.
4344
- **HTTP:** Fixed a bug where ``IncomingRequest::isSecure()`` did not recognize ``https`` in the ``X-Forwarded-Proto`` header from a trusted proxy when the value contained uppercase letters or surrounding whitespace, or was represented as a single-element array.

0 commit comments

Comments
 (0)