-
-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathRequestIntegration.php
More file actions
303 lines (253 loc) · 9.56 KB
/
RequestIntegration.php
File metadata and controls
303 lines (253 loc) · 9.56 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
<?php
declare(strict_types=1);
namespace Sentry\Integration;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UploadedFileInterface;
use Sentry\Event;
use Sentry\Exception\JsonException;
use Sentry\Options;
use Sentry\OptionsResolver;
use Sentry\SentrySdk;
use Sentry\State\Scope;
use Sentry\UserDataBag;
use Sentry\Util\JSON;
/**
* This integration collects information from the request and attaches them to
* the event.
*
* @author Stefano Arlandini <sarlandini@alice.it>
*/
final class RequestIntegration implements IntegrationInterface
{
/**
* This constant represents the size limit in bytes beyond which the body
* of the request is not captured when the `max_request_body_size` option
* is set to `small`.
*/
private const REQUEST_BODY_SMALL_MAX_CONTENT_LENGTH = 10 ** 3;
/**
* This constant represents the size limit in bytes beyond which the body
* of the request is not captured when the `max_request_body_size` option
* is set to `medium`.
*/
private const REQUEST_BODY_MEDIUM_MAX_CONTENT_LENGTH = 10 ** 4;
/**
* This constant is a map of maximum allowed sizes for each value of the
* `max_request_body_size` option.
*/
private const MAX_REQUEST_BODY_SIZE_OPTION_TO_MAX_LENGTH_MAP = [
'never' => 0,
'small' => self::REQUEST_BODY_SMALL_MAX_CONTENT_LENGTH,
'medium' => self::REQUEST_BODY_MEDIUM_MAX_CONTENT_LENGTH,
'always' => \PHP_INT_MAX,
];
/**
* This constant defines the default list of headers that may contain
* sensitive data and that will be sanitized if sending PII is disabled.
*/
private const DEFAULT_SENSITIVE_HEADERS = [
'Authorization',
'Cookie',
'Set-Cookie',
'X-Forwarded-For',
'X-Real-IP',
];
/**
* @var RequestFetcherInterface PSR-7 request fetcher
*/
private $requestFetcher;
/**
* @var array<string, mixed> The options
*/
private $options;
/**
* Constructor.
*
* @param RequestFetcherInterface|null $requestFetcher PSR-7 request fetcher
* @param array<string, mixed> $options The options
*/
public function __construct(?RequestFetcherInterface $requestFetcher = null, array $options = [])
{
$resolver = new OptionsResolver();
$this->configureOptions($resolver);
$this->requestFetcher = $requestFetcher ?? new RequestFetcher();
$this->options = $resolver->resolve($options);
}
/**
* {@inheritdoc}
*/
public function setupOnce(): void
{
Scope::addGlobalEventProcessor(function (Event $event): Event {
$client = SentrySdk::getClient();
$integration = $client->getIntegration(self::class);
if ($integration === null) {
return $event;
}
$this->processEvent($event, $client->getOptions());
return $event;
});
}
private function processEvent(Event $event, Options $options): void
{
$request = $this->requestFetcher->fetchRequest();
if ($request === null) {
return;
}
$requestData = [
'url' => (string) $request->getUri(),
'method' => $request->getMethod(),
];
if ($request->getUri()->getQuery()) {
$requestData['query_string'] = $request->getUri()->getQuery();
}
if ($options->shouldSendDefaultPii()) {
$serverParams = $request->getServerParams();
if (!empty($serverParams['REMOTE_ADDR'])) {
$user = $event->getUser();
$requestData['env']['REMOTE_ADDR'] = $serverParams['REMOTE_ADDR'];
if ($user === null) {
$user = UserDataBag::createFromUserIpAddress($serverParams['REMOTE_ADDR']);
} elseif ($user->getIpAddress() === null) {
$user->setIpAddress($serverParams['REMOTE_ADDR']);
}
$event->setUser($user);
}
$requestData['cookies'] = $request->getCookieParams();
$requestData['headers'] = $request->getHeaders();
} else {
$requestData['headers'] = $this->sanitizeHeaders($request->getHeaders());
}
$requestBody = $this->captureRequestBody($options, $request);
if (!empty($requestBody)) {
$requestData['data'] = $requestBody;
}
$event->setRequest($requestData);
}
/**
* Removes headers containing potential PII.
*
* @param array<array-key, string[]> $headers Array containing request headers
*
* @return array<string, string[]>
*/
private function sanitizeHeaders(array $headers): array
{
foreach ($headers as $name => $values) {
// Cast the header name into a string, to avoid errors on numeric headers
$name = (string) $name;
if (!\is_array($this->options['pii_sanitize_headers'])) {
break;
}
if (!\in_array(strtolower($name), $this->options['pii_sanitize_headers'], true)) {
continue;
}
foreach ($values as $headerLine => $headerValue) {
$headers[$name][$headerLine] = '[Filtered]';
}
}
return $headers;
}
/**
* Gets the decoded body of the request, if available. If the Content-Type
* header contains "application/json" then the content is decoded and if
* the parsing fails then the raw data is returned. If there are submitted
* fields or files, all of their information are parsed and returned.
*
* @param Options $options The options of the client
* @param ServerRequestInterface $request The server request
*
* @return mixed
*/
private function captureRequestBody(Options $options, ServerRequestInterface $request)
{
$maxRequestBodySize = $options->getMaxRequestBodySize();
$requestBodySize = (int) $request->getHeaderLine('Content-Length');
if (!$this->isRequestBodySizeWithinReadBounds($requestBodySize, $maxRequestBodySize)) {
return null;
}
$requestData = $request->getParsedBody();
$requestData = array_replace(
$this->parseUploadedFiles($request->getUploadedFiles()),
\is_array($requestData) ? $requestData : []
);
if (!empty($requestData)) {
return $requestData;
}
$requestBody = '';
$maxLength = self::MAX_REQUEST_BODY_SIZE_OPTION_TO_MAX_LENGTH_MAP[$maxRequestBodySize];
if ($maxLength > 0) {
$stream = $request->getBody();
while ($maxLength > 0 && !$stream->eof()) {
if ('' === $buffer = $stream->read(min($maxLength, self::REQUEST_BODY_MEDIUM_MAX_CONTENT_LENGTH))) {
break;
}
$requestBody .= $buffer;
$maxLength -= \strlen($buffer);
}
}
if ($request->getHeaderLine('Content-Type') === 'application/json') {
try {
return JSON::decode($requestBody);
} catch (JsonException $exception) {
// Fallback to returning the raw data from the request body
}
}
return $requestBody;
}
/**
* Create an array with the same structure as $uploadedFiles, but replacing
* each UploadedFileInterface with an array of info.
*
* @param array<string, mixed> $uploadedFiles The uploaded files info from a PSR-7 server request
*
* @return array<string, mixed>
*/
private function parseUploadedFiles(array $uploadedFiles): array
{
$result = [];
foreach ($uploadedFiles as $key => $item) {
if ($item instanceof UploadedFileInterface) {
$result[$key] = [
'client_filename' => $item->getClientFilename(),
'client_media_type' => $item->getClientMediaType(),
'size' => $item->getSize(),
];
} elseif (\is_array($item)) {
$result[$key] = $this->parseUploadedFiles($item);
} else {
throw new \UnexpectedValueException(\sprintf('Expected either an object implementing the "%s" interface or an array. Got: "%s".', UploadedFileInterface::class, \is_object($item) ? \get_class($item) : \gettype($item)));
}
}
return $result;
}
private function isRequestBodySizeWithinReadBounds(int $requestBodySize, string $maxRequestBodySize): bool
{
if ($requestBodySize <= 0) {
return false;
}
if ($maxRequestBodySize === 'never') {
return false;
}
if ($maxRequestBodySize === 'small' && $requestBodySize > self::REQUEST_BODY_SMALL_MAX_CONTENT_LENGTH) {
return false;
}
if ($maxRequestBodySize === 'medium' && $requestBodySize > self::REQUEST_BODY_MEDIUM_MAX_CONTENT_LENGTH) {
return false;
}
return true;
}
/**
* Configures the options of the client.
*
* @param OptionsResolver $resolver The resolver for the options
*/
private function configureOptions(OptionsResolver $resolver): void
{
$resolver->setAllowedTypes('pii_sanitize_headers', 'string[]');
$resolver->setNormalizer('pii_sanitize_headers', static function (array $value): array {
return array_map('strtolower', $value);
});
$resolver->setDefault('pii_sanitize_headers', self::DEFAULT_SENSITIVE_HEADERS);
}
}