-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestLogger.php
More file actions
224 lines (194 loc) · 6.41 KB
/
Copy pathRequestLogger.php
File metadata and controls
224 lines (194 loc) · 6.41 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
<?php
declare(strict_types=1);
namespace ADT\FancyAdmin\Model;
use ADT\FancyAdmin\Model\Security\SecurityUser;
use DateTimeImmutable;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Exception;
use Nette\Application\Response;
use Nette\Application\Responses\FileResponse;
use Nette\Application\UI\Presenter;
use Nette\Utils\Json;
use Nette\Utils\JsonException;
use Throwable;
use Tracy\Debugger;
use Tracy\ILogger;
final class RequestLogger
{
public static bool $logResponse = false;
public static ?int $apiKeyId = null;
/**
* Klíče (case-insensitive), jejichž hodnota se v logu nahradí `***`.
* Porovnává se jako substring, takže např. 'password' pokryje i 'passwordConfirm'.
*
* @var list<string>
*/
public static array $sensitiveKeys = [
'password',
'passwd',
'secret',
'token',
'authorization',
'api_key',
'apikey',
'pin',
];
private const string MASK = '***';
/** @var array<string, mixed> Vlastní projektové sloupce pro tabulku `request_log` */
private static array $extraLogData = [];
public function __construct(
private readonly array $dbParams,
private readonly SecurityUser $securityUser,
) {
}
/**
* Přidá vlastní sloupec do logu requestu (tabulka `request_log`).
*
* Volej kdykoliv během zpracování requestu (typicky v presenteru), např.:
* RequestLogger::addValue('device_id', $deviceId);
*
* Systémové sloupce (created_at, method, url, ip, code, response_time,
* identity_id, api_key_id) nelze přepsat – slouží pouze k PŘIDÁVÁNÍ.
*/
public static function addValue(string $column, mixed $value): void
{
self::$extraLogData[$column] = $value;
}
public function logRequest(Presenter $presenter, Response $response): void
{
if (!self::$apiKeyId && !$this->securityUser->isLoggedIn()) {
return;
}
try {
$this->doLogRequest($presenter, $response);
} catch (Throwable $e) {
Debugger::log('RequestLogger selhal: ' . $e->getMessage(), ILogger::CRITICAL);
}
}
/**
* @throws JsonException
* @throws Exception
* @throws \Exception
*/
private function doLogRequest(Presenter $presenter, Response $response): void
{
if (json_validate($presenter->getHttpRequest()->getRawBody())) {
$raw_data_text = null;
$raw_data_json = Json::decode($presenter->getHttpRequest()->getRawBody(), forceArrays: true);
} else {
$raw_data_json = null;
$raw_data_text = $presenter->getHttpRequest()->getRawBody();
}
if (self::$logResponse) {
if (!$response instanceof FileResponse) {
ob_start();
$response->send($presenter->getHttpRequest(), $presenter->getHttpResponse());
$response = ob_get_clean();
if (json_validate($response)) {
$response_text = null;
$response_json = Json::decode($response, forceArrays: true);
} else {
$response_text = $response;
$response_json = null;
}
} else {
$response_text = null;
$response_json = null;
}
} else {
$response_text = null;
$response_json = null;
}
$headers = $presenter->getHttpRequest()->getHeaders();
unset($headers['authorization']);
unset($headers['x-api-key']);
$connection = DriverManager::getConnection($this->dbParams);
// Systémové sloupce mají díky `+` vždy přednost – extra data (viz addValue())
// mohou pouze PŘIDÁVAT vlastní sloupce, ne přepsat defaultní logování.
$connection->insert('request_log', [
'created_at' => new DateTimeImmutable()->format('Y-m-d H:i:s.u'),
'method' => $presenter->getHttpRequest()->getMethod(),
'url' => $presenter->getHttpRequest()->getUrl()->getBaseUrl() . ltrim($presenter->getHttpRequest()->getUrl()->getPath(), '/'),
'ip' => $presenter->getHttpRequest()->getRemoteAddress(),
'code' => $presenter->getHttpResponse()->getCode(),
'response_time' => (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']),
'identity_id' => $this->securityUser->isLoggedIn() ? $this->securityUser->getId() : null,
'api_key_id' => self::$apiKeyId,
] + self::$extraLogData);
$requestLogId = $connection->lastInsertId();
$connection->insert('request_log_body', [
'request_log_id' => $requestLogId,
'headers' => $headers ? Json::encode($this->normalizeData($headers)) : null,
'params' => $_GET ? Json::encode($this->normalizeData($_GET)) : null,
'post_data' => $_POST ? Json::encode($this->normalizeData($_POST)) : null,
'raw_data_json' => $raw_data_json ? Json::encode($this->normalizeData($raw_data_json)) : null,
'raw_data_text' => $this->normalizeData($raw_data_text),
'response_json' => $response_json ? Json::encode($this->normalizeData($response_json)) : null,
'response_text' => $this->normalizeData($response_text),
]);
}
private function normalizeData($data)
{
if (empty($data)) {
return null;
}
if (is_array($data)) {
$output = [];
foreach ($data as $key => $value) {
$normalizedKey = is_string($key) ? $this->normalizeString($key) : $key;
$output[$normalizedKey] = $this->isSensitiveKey($normalizedKey)
? self::MASK
: $this->normalizeData($value); // Rekurze
}
return $output;
}
if (is_string($data)) {
if (strlen($data) >= 255 && $this->isBase64Encoded($data)) {
return 'md5:' . md5($data);
}
return $this->normalizeString($data);
}
// Ostatní případy (např. scalar typy) – vracíme beze změny
return $data;
}
/**
* Je klíč citlivý? (case-insensitive substring match proti self::$sensitiveKeys)
*/
private function isSensitiveKey(int|string $key): bool
{
if (!is_string($key)) {
return false;
}
$key = mb_strtolower($key);
foreach (self::$sensitiveKeys as $sensitiveKey) {
if (str_contains($key, mb_strtolower($sensitiveKey))) {
return true;
}
}
return false;
}
private function normalizeString(string $value): string
{
// Neplatné UTF-8 (např. z útočných requestů) nahradíme náhradním znakem,
// aby šlo hodnotu uložit i serializovat do JSONu bez výjimky
if (!mb_check_encoding($value, 'UTF-8')) {
$value = mb_scrub($value, 'UTF-8');
}
return $this->removeControlCharacters($value);
}
private function isBase64Encoded(string $string): bool
{
$decoded = base64_decode($string, true);
if ($decoded !== false) {
if (base64_encode($decoded) === $string) {
return true;
}
}
return false;
}
private function removeControlCharacters(string $input): string
{
// Odebereme všechny znaky s ASCII hodnotou < 32 kromě \n (10), \r (13) a \t (9)
return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u', '', $input);
}
}