1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Middleware; |
4
|
|
|
|
5
|
|
|
use Psr7Middlewares\Middleware; |
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use ParagonIE\CSPBuilder\CSPBuilder; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Middleware to add the Content-Security-Policy header to the responses. |
12
|
|
|
*/ |
13
|
|
|
class Csp |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var CSPBuilder |
17
|
|
|
*/ |
18
|
|
|
private $csp; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Set CSPBuilder. |
22
|
|
|
* |
23
|
|
|
* @param array|null $policies |
24
|
|
|
*/ |
25
|
|
|
public function __construct(array $policies = null) |
26
|
|
|
{ |
27
|
|
|
if ($policies === null) { |
28
|
|
|
$policies = [ |
29
|
|
|
'script-src' => ['self' => true], |
30
|
|
|
'object-src' => ['self' => true], |
31
|
|
|
'frame-ancestors' => ['self' => true], |
32
|
|
|
]; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$this->csp = new CSPBuilder($policies); |
36
|
|
|
|
37
|
|
|
return $this; |
|
|
|
|
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Add a source to our allow whitelist. |
42
|
|
|
* |
43
|
|
|
* @param string $directive |
44
|
|
|
* @param string $path |
45
|
|
|
* |
46
|
|
|
* @return self |
47
|
|
|
*/ |
48
|
|
|
public function addSource($directive, $path) |
49
|
|
|
{ |
50
|
|
|
$this->csp->addSource($directive, $path); |
51
|
|
|
|
52
|
|
|
return $this; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Add a directive if it doesn't already exist |
57
|
|
|
* If it already exists, do nothing. |
58
|
|
|
* |
59
|
|
|
* @param string $directive |
60
|
|
|
* @param mixed $value |
61
|
|
|
* |
62
|
|
|
* @return self |
63
|
|
|
*/ |
64
|
|
|
public function addDirective($directive, $value) |
65
|
|
|
{ |
66
|
|
|
$this->csp->addDirective($directive, $value); |
67
|
|
|
|
68
|
|
|
return $this; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Whether or not support old browsers (e.g. safari). |
73
|
|
|
* |
74
|
|
|
* @param bool $support |
75
|
|
|
* |
76
|
|
|
* @return self |
77
|
|
|
*/ |
78
|
|
|
public function supportOldBrowsers($support = true) |
79
|
|
|
{ |
80
|
|
|
if ($support) { |
81
|
|
|
$this->csp->enableOldBrowserSupport(); |
82
|
|
|
} else { |
83
|
|
|
$this->csp->disableOldBrowserSupport(); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
return $this; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* Execute the middleware. |
91
|
|
|
* |
92
|
|
|
* @param ServerRequestInterface $request |
93
|
|
|
* @param ResponseInterface $response |
94
|
|
|
* @param callable $next |
95
|
|
|
* |
96
|
|
|
* @return ResponseInterface |
97
|
|
|
*/ |
98
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
99
|
|
|
{ |
100
|
|
|
$this->csp->compile(); |
101
|
|
|
|
102
|
|
|
$response = $this->csp->injectCSPHeader($response); |
103
|
|
|
|
104
|
|
|
return $next($request, $response); |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|