Repository navigation
Expand file tree
/
Copy pathSensitiveDataRedactor.php
More file actions
335 lines (301 loc) · 10.7 KB
/
Copy pathSensitiveDataRedactor.php
File metadata and controls
335 lines (301 loc) · 10.7 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
<?php
declare(strict_types=1);
namespace PHPForge\Debug\Helper;
use InvalidArgumentException;
use PHPForge\Debug\Exception\Message;
use SensitiveParameter;
use function array_fill_keys;
use function array_map;
use function get_object_vars;
use function is_array;
use function is_object;
use function is_string;
use function preg_match;
use function str_starts_with;
use function strtolower;
/**
* Replaces values whose array keys match configured exact names, prefixes, or PCRE patterns.
*/
final class SensitiveDataRedactor
{
/**
* Common credential and session fields that must never be persisted by default.
*
* @var list<string>
*/
public const array DEFAULT_KEYS = [
'access_token',
'accessToken',
'api_key',
'apiKey',
'authorization',
'auth_key',
'authKey',
'aws_secret_access_key',
'client_secret',
'clientSecret',
'cookie',
'csrf_token',
'csrfToken',
'database_url',
'db_password',
'http_authorization',
'http_cookie',
'password',
'password_hash',
'password_reset_token',
'passwd',
'php_auth_pw',
'proxy-authorization',
'redirect_http_authorization',
'refresh_token',
'refreshToken',
'secret',
'session_id',
'set-cookie',
'token',
'verification_token',
'x-api-key',
'x-auth-token',
'x-csrf-token',
];
/**
* Segment-aware defaults for environment-style credential keys.
*
* Separators are required around credential words so safe keys such as `tokenizer` and `passwordless` remain
* visible. Passing an explicit empty pattern list opts out.
*
* @var list<string>
*/
public const array DEFAULT_PATTERNS = [
'~(?:^|[_\-.])(?:password|passwd|secret|token|api[_-]?key|private[_-]?key|credential)(?:$|[_\-.])~i',
];
/**
* Replacement written in place of a sensitive value.
*/
public const string PLACEHOLDER = '[redacted]';
/**
* Replacement written where the depth or node budget stops traversal.
*/
public const string TRUNCATED = '[truncated]';
/**
* Nesting depth beyond which nested arrays are replaced by {@see TRUNCATED}.
*/
private const int MAX_DEPTH = 10;
/**
* Maximum entries visited per `redact()` call before traversal stops with {@see TRUNCATED}.
*/
private const int MAX_NODES = 10000;
/**
* Returns whether a key matches a configured exact name, literal prefix, or PCRE pattern.
*
* @param string $key Original key to inspect. Exact names and literal prefixes ignore case; PCRE patterns retain
* their own case-sensitivity modifiers.
* @param list<string> $sensitiveKeys Exact key names to inspect.
* @param list<string> $sensitiveKeyPrefixes Literal key prefixes to inspect case-insensitively.
* @param list<string>|null $sensitiveKeyPatterns PCRE patterns applied to the complete original key. `null` uses
* defaults only with the default exact-key list; `[]` explicitly disables patterns.
*
* @return bool `true` when the key matches any configured rule; `false` otherwise.
*/
public static function isSensitiveKey(
string $key,
array $sensitiveKeys = self::DEFAULT_KEYS,
array $sensitiveKeyPrefixes = [],
array|null $sensitiveKeyPatterns = null,
): bool {
[$keyMap, $prefixes, $patterns] = self::rules($sensitiveKeys, $sensitiveKeyPrefixes, $sensitiveKeyPatterns);
return self::matches($key, $keyMap, $prefixes, $patterns);
}
/**
* Resolves the pattern list a redaction rule set applies, preserving exact-list override behavior.
*
* An explicit list wins. Otherwise {@see DEFAULT_PATTERNS} applies only alongside the unmodified
* {@see DEFAULT_KEYS} list, so a custom exact-key list never inherits the segment-aware defaults.
*
* @param list<string> $keys Configured exact key names.
* @param list<string>|null $patterns Configured PCRE patterns, or `null` to resolve the defaults.
*
* @return list<string> Patterns applied to complete original keys.
*/
public static function patterns(array $keys, array|null $patterns): array
{
return $patterns ?? ($keys === self::DEFAULT_KEYS ? self::DEFAULT_PATTERNS : []);
}
/**
* Redacts configured keys case-insensitively throughout a bounded nested array.
*
* @template TKey of array-key
*
* @param array<TKey, mixed> $value Value tree to sanitize.
* @param list<string> $sensitiveKeys Exact key names to redact.
* @param list<string> $sensitiveKeyPrefixes Literal key prefixes to redact case-insensitively.
* @param list<string>|null $sensitiveKeyPatterns PCRE patterns applied to complete original keys. `null` uses
* defaults only with the default exact-key list; `[]` explicitly disables patterns.
*
* @return array<TKey, mixed> Sanitized tree with keys and non-sensitive values preserved.
*/
public static function redact(
#[SensitiveParameter]
array $value,
array $sensitiveKeys = self::DEFAULT_KEYS,
array $sensitiveKeyPrefixes = [],
array|null $sensitiveKeyPatterns = null,
): array {
$nodes = 0;
[$keyMap, $prefixes, $patterns] = self::rules($sensitiveKeys, $sensitiveKeyPrefixes, $sensitiveKeyPatterns);
return self::walk($value, $keyMap, $prefixes, $patterns, 0, $nodes);
}
/**
* Normalizes configured keys into a case-insensitive lookup map.
*
* @param list<string> $sensitiveKeys Exact key names to normalize.
*
* @return array<string, true> Normalized key lookup.
*/
private static function keyMap(array $sensitiveKeys): array
{
return array_fill_keys(array_map(strtolower(...), $sensitiveKeys), true);
}
/**
* Returns whether the key matches any normalized redaction rule.
*
* @param string $key Original key to inspect.
* @param array<string, true> $sensitiveKeys
* @param list<string> $sensitiveKeyPrefixes
* @param list<string> $sensitiveKeyPatterns
*
* @return bool `true` when the key matches any normalized rule; `false` otherwise.
*/
private static function matches(
string $key,
array $sensitiveKeys,
array $sensitiveKeyPrefixes,
array $sensitiveKeyPatterns,
): bool {
$normalizedKey = strtolower($key);
if (isset($sensitiveKeys[$normalizedKey])) {
return true;
}
foreach ($sensitiveKeyPrefixes as $prefix) {
if (str_starts_with($normalizedKey, $prefix)) {
return true;
}
}
foreach ($sensitiveKeyPatterns as $pattern) {
if (preg_match($pattern, $key) === 1) {
return true;
}
}
return false;
}
/**
* Normalizes literal key prefixes and rejects an empty match-all prefix.
*
* @param list<string> $prefixes
*
* @return list<string>
*/
private static function prefixes(array $prefixes): array
{
foreach ($prefixes as $prefix) {
if ($prefix === '') {
throw new InvalidArgumentException(
Message::SENSITIVE_KEY_PREFIX_EMPTY->getMessage(),
);
}
}
return array_map(strtolower(...), $prefixes);
}
/**
* Normalizes and validates the redaction configuration shared by the public entry points.
*
* @param list<string> $sensitiveKeys Exact key names to redact.
* @param list<string> $sensitiveKeyPrefixes Literal key prefixes to redact case-insensitively.
* @param list<string>|null $sensitiveKeyPatterns PCRE patterns applied to complete original keys.
*
* @return array{array<string, true>, list<string>, list<string>} Normalized key map, prefixes, and patterns.
*/
private static function rules(
array $sensitiveKeys,
array $sensitiveKeyPrefixes,
array|null $sensitiveKeyPatterns,
): array {
$prefixes = self::prefixes($sensitiveKeyPrefixes);
$patterns = self::patterns($sensitiveKeys, $sensitiveKeyPatterns);
self::validatePatterns($patterns);
return [self::keyMap($sensitiveKeys), $prefixes, $patterns];
}
/**
* Rejects invalid PCRE configuration before walking a potentially large value tree.
*
* @param list<string> $patterns
*/
private static function validatePatterns(array $patterns): void
{
foreach ($patterns as $pattern) {
if ($pattern === '' || @preg_match($pattern, '') === false) {
throw new InvalidArgumentException(
Message::SENSITIVE_KEY_PATTERN_INVALID->getMessage($pattern),
);
}
}
}
/**
* @template TKey of array-key
*
* Redacts one nesting level, tracking depth and the shared node budget.
*
* @param array<TKey, mixed> $value
* @param array<string, true> $sensitiveKeys
* @param list<string> $sensitiveKeyPrefixes
* @param list<string> $sensitiveKeyPatterns
* @param int $depth Current nesting level.
* @param int $nodes Entries visited so far, shared across the whole traversal.
*
* @return array<TKey, mixed>
*/
private static function walk(
#[SensitiveParameter]
array $value,
array $sensitiveKeys,
array $sensitiveKeyPrefixes,
array $sensitiveKeyPatterns,
int $depth,
int &$nodes,
): array {
$redacted = [];
foreach ($value as $key => $item) {
++$nodes;
if ($nodes > self::MAX_NODES) {
$redacted[$key] = self::TRUNCATED;
break;
}
if (
is_string($key)
&& self::matches($key, $sensitiveKeys, $sensitiveKeyPrefixes, $sensitiveKeyPatterns)
) {
$redacted[$key] = self::PLACEHOLDER;
continue;
}
if (is_object($item)) {
$item = get_object_vars($item);
}
if (is_array($item) && $depth >= self::MAX_DEPTH) {
$redacted[$key] = self::TRUNCATED;
continue;
}
$redacted[$key] = is_array($item)
? self::walk(
$item,
$sensitiveKeys,
$sensitiveKeyPrefixes,
$sensitiveKeyPatterns,
$depth + 1,
$nodes,
)
: $item;
}
return $redacted;
}
}