Skip to content
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
9 changes: 8 additions & 1 deletion src/Bridges/HttpDI/HttpExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
}

if (!empty($config['csp'])) {
$reportOnly = false;

if (array_key_exists('reportOnly', $config['csp'])) {
$reportOnly = $config['csp']['reportOnly'];
unset($config['csp']['reportOnly']);
}

$value = '';
foreach ($config['csp'] as $type => $policy) {
$value .= $type;
Expand All @@ -109,7 +116,7 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
["'nonce", "'nonce-", $value]
);
}
$headers['Content-Security-Policy'] = $value;
$headers['Content-Security-Policy' . ($reportOnly ? '-Report-Only' : '')] = $value;
}

foreach ($headers as $key => $value) {
Expand Down
49 changes: 49 additions & 0 deletions tests/Http.DI/HttpExtension.reportOnly.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

/**
* Test: HttpExtension.
*/

declare(strict_types=1);

use Nette\Bridges\HttpDI\HttpExtension;
use Nette\DI;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';

if (PHP_SAPI === 'cli') {
Tester\Environment::skip('Headers are not testable in CLI mode');
}


$compiler = new DI\Compiler;
$compiler->addExtension('http', new HttpExtension);
$loader = new DI\Config\Loader;
$config = $loader->load(Tester\FileMock::create(<<<'EOD'
http:
csp:
reportOnly: true
default-src: "'self' https://example.com"
report-uri: https://example.com/report
EOD
, 'neon'));

eval($compiler->addConfig($config)->compile());

$container = new Container;
$container->initialize();

$headers = headers_list();

Assert::contains("Content-Security-Policy-Report-Only: default-src 'self' https://example.com; report-uri https://example.com/report;", $headers);


echo ' '; @ob_flush(); flush();

Assert::true(headers_sent());

Assert::exception(function () use ($container) {
$container->initialize();
}, Nette\InvalidStateException::class, 'Cannot send header after %a%');