-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDirectivesNormalizer.php
More file actions
78 lines (70 loc) · 3.06 KB
/
DirectivesNormalizer.php
File metadata and controls
78 lines (70 loc) · 3.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
declare(strict_types=1);
namespace Flowpack\ContentSecurityPolicy\Helpers;
use Flowpack\ContentSecurityPolicy\Exceptions\DirectivesNormalizerException;
use Psr\Log\LoggerInterface;
/**
* Helper to support normalization of directives from different formats.
* The old format supported yaml lists. Now key-value pairs should be used for directives.
* In the future we will deprecate the list format!
*
* We also cleanup of empty directives and entries here before further processing.
*/
final class DirectivesNormalizer
{
/**
* @param array<string, ?array<string|int, string|bool>> $directives
* @return string[][]
* @throws DirectivesNormalizerException
*/
public static function normalize(array $directives, LoggerInterface $logger): array
{
$result = [];
// directives e.g. script-src:
foreach ($directives as $directive => $values) {
if (!is_array($values) || count($values) === 0) {
continue;
}
$normalizedValues = [];
$firstKeyType = null;
// values e.g. 'self', 'unsafe-inline' OR key-value pairs e.g. example.com: true
foreach ($values as $key => $value) {
if ($firstKeyType === null) {
$firstKeyType = gettype($key);
} else {
if (gettype($key) !== $firstKeyType) {
// we do not allow mixed key types -> this should be marked as an error in the IDE as well
// as Flow should throw an exception here. But just to be sure, we add this check.
throw new DirectivesNormalizerException(
'Directives must be defined as a list OR an object.'
);
}
}
if (is_int($key) && is_string($value) && trim($value) !== '') {
// old configuration format using list
$normalizedValues[] = $value;
$logger->warning(
'Using list format for CSP directives is deprecated and will be removed in future versions. Please use key-value pairs with boolean values instead.'
);
} elseif (is_string($key)) {
// new configuration format using key-value pairs
if (is_bool($value)) {
if ($value === true && trim($key) !== '') {
$normalizedValues[] = $key;
}
continue;
}
// We chose a format similar to NodeType constraints yaml configuration.
throw new DirectivesNormalizerException(
'When using keys in your yaml, the values must be boolean.'
);
}
}
if ($normalizedValues !== []) {
// we also clean up empty directives here
$result[$directive] = $normalizedValues;
}
}
return $result;
}
}