Skip to content

Commit 708b922

Browse files
committed
Request, HttpExtension: added sameSite protection (enabled by default)
1 parent 5e1deeb commit 708b922

3 files changed

Lines changed: 46 additions & 0 deletions

File tree

src/Bridges/HttpDI/HttpExtension.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ class HttpExtension extends Nette\DI\CompilerExtension
2828
'cspReportOnly' => [], // Content-Security-Policy-Report-Only
2929
'featurePolicy' => [], // Feature-Policy
3030
'cookieSecure' => 'auto', // true|false|auto Whether the cookie is available only through HTTPS
31+
'sameSiteProtection' => true, // activates Request::isSameSite() protection
3132
];
3233

3334
/** @var bool */
@@ -127,6 +128,10 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
127128
$initialize->addBody('$this->getService(?)->setHeader(?, ?);', [$this->prefix('response'), $key, $value]);
128129
}
129130
}
131+
132+
if (!empty($config['sameSiteProtection'])) {
133+
$initialize->addBody('$this->getService(?)->setCookie(...?);', [$this->prefix('response'), ['nette-samesite', '1', 0, '/', null, null, true, 'Strict']]);
134+
}
130135
}
131136

132137

src/Http/Request.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,15 @@ public function isSecured(): bool
227227
}
228228

229229

230+
/**
231+
* Is the request sent from the same origin?
232+
*/
233+
public function isSameSite(): bool
234+
{
235+
return isset($this->cookies['nette-samesite']);
236+
}
237+
238+
230239
/**
231240
* Is AJAX request?
232241
*/
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Bridges\HttpDI\HttpExtension;
6+
use Nette\DI;
7+
use Tester\Assert;
8+
9+
10+
require __DIR__ . '/../bootstrap.php';
11+
12+
if (PHP_SAPI === 'cli') {
13+
Tester\Environment::skip('Headers are not testable in CLI mode');
14+
}
15+
16+
17+
$compiler = new DI\Compiler;
18+
$compiler->addExtension('http', new HttpExtension);
19+
20+
// protection is enabled by default
21+
eval($compiler->compile());
22+
23+
$container = new Container;
24+
$container->initialize();
25+
26+
$headers = headers_list();
27+
Assert::contains(
28+
PHP_VERSION_ID >= 70300
29+
? 'Set-Cookie: nette-samesite=1; path=/; HttpOnly; SameSite=Strict'
30+
: 'Set-Cookie: nette-samesite=1; path=/; SameSite=Strict; HttpOnly',
31+
$headers
32+
);

0 commit comments

Comments
 (0)