1
|
|
|
<?php |
2
|
|
|
namespace Ubiquity\security\csp; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Manage Content Security Policies. |
6
|
|
|
* Ubiquity\security\csp$ContentSecurityManager |
7
|
|
|
* This class is part of Ubiquity |
8
|
|
|
* |
9
|
|
|
* @author jc |
10
|
|
|
* @version 1.0.0 |
11
|
|
|
* |
12
|
|
|
*/ |
13
|
|
|
class ContentSecurityManager { |
14
|
|
|
|
15
|
|
|
private static NonceGenerator $nonceGenerator; |
16
|
|
|
|
17
|
|
|
private static array $csp = []; |
18
|
|
|
|
19
|
|
|
private static bool $reportOnly; |
20
|
|
|
|
21
|
|
|
public static function start(string $nonceGeneratorClass = null, bool $reportOnly = false, ?callable $onNonce = null) { |
22
|
|
|
$nonceGeneratorClass ??= NonceGenerator::class; |
23
|
|
|
self::$nonceGenerator = new $nonceGeneratorClass($onNonce); |
24
|
|
|
self::$reportOnly = $reportOnly; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public static function getNonce(string $name) { |
28
|
|
|
return self::$nonceGenerator->getNonce($name); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public static function isStarted(): bool { |
32
|
|
|
return isset(self::$nonceGenerator); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public static function addCsp(?bool $reportOnly = null): ContentSecurity { |
36
|
|
|
return self::$csp[] = new ContentSecurity($reportOnly ?? self::$reportOnly); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public static function clearCsp() { |
40
|
|
|
self::$csp = []; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public static function defaultUbiquity(?bool $reportOnly = null): ContentSecurity { |
44
|
|
|
return self::$csp[] = ContentSecurity::defaultUbiquity()->reportOnly($reportOnly); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public static function addHeadersToResponse(?bool $reportOnly = null): void { |
48
|
|
|
$reportOnly ??= self::$reportOnly; |
49
|
|
|
foreach (self::$csp as $csp) { |
50
|
|
|
$csp->addHeaderToResponse($reportOnly); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @return NonceGenerator |
56
|
|
|
*/ |
57
|
|
|
public static function getNonceGenerator(): NonceGenerator { |
58
|
|
|
return self::$nonceGenerator; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return array |
63
|
|
|
*/ |
64
|
|
|
public static function getCsp(): array { |
65
|
|
|
return self::$csp; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return bool |
71
|
|
|
*/ |
72
|
|
|
public static function isReportOnly(): bool { |
73
|
|
|
return self::$reportOnly; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
|