-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSensitiveDataProcessor.php
More file actions
93 lines (83 loc) · 2.55 KB
/
SensitiveDataProcessor.php
File metadata and controls
93 lines (83 loc) · 2.55 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
<?php
/**
* This file is part of Zepgram\Rest\Model
*
* @package Zepgram\Rest\Logger
* @file ObfuscateSensitiveData.php
* @date 11 24 2024 21:03
*
* @author Benjamin Calef <zepgram@gmail.com>
* @copyright 2024 Zepgram Copyright (c) (https://github.com/zepgram)
* @license MIT License
**/
declare(strict_types=1);
namespace Zepgram\Rest\Logger;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;
class SensitiveDataProcessor implements ProcessorInterface
{
private $sensitiveKeyPattern;
public function __construct(
private array $sensitiveKeys = [],
private array $overrideSensitiveKeys = [],
private string $redactionPlaceholder = '***REDACTED***',
private ?bool $isEnabled = null,
) {
$defaultSensitiveKeys = [
'password',
'username',
'user',
'token',
'key',
'secret',
'hash',
'hmac',
'sha',
'sign',
'authorization',
'jwt',
'access',
'auth',
'sso',
'passphrase',
'ssh',
'pin',
'cvv',
'ccv',
'cvc',
'card'
];
$this->isEnabled = $isEnabled ?? (getenv('MAGE_MODE') === 'production');
$this->sensitiveKeys = array_unique(array_merge($defaultSensitiveKeys, $sensitiveKeys));
$this->sensitiveKeys = $this->overrideSensitiveKeys ?: $this->sensitiveKeys;
$this->sensitiveKeyPattern = '/' . implode('|', array_map('preg_quote', $this->sensitiveKeys)) . '/i';
}
public function __invoke(LogRecord $record): LogRecord
{
if (!$this->isEnabled) {
return $record;
}
return $record->with(
context: $this->redactSensitiveData($record->context),
extra: $this->redactSensitiveData($record->extra)
);
}
private function redactSensitiveData(mixed $data): mixed
{
if (is_array($data)) {
foreach ($data as $key => &$value) {
if (is_array($value)) {
$value = $this->redactSensitiveData($value);
} elseif ($key && is_string($key) && $this->isSensitiveKey($key)) {
$value = $this->redactionPlaceholder;
}
}
return $data;
}
return $data;
}
private function isSensitiveKey(string $key): bool
{
return preg_match($this->sensitiveKeyPattern, $key) === 1;
}
}