Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/TraceMiddleware.php

raw symbols SCIP
1 <?php
2 namespace Aws;
3
4 use Aws\Api\Service;
5 use Aws\Exception\AwsException;
6 use GuzzleHttp\Promise\RejectedPromise;
7 use Psr\Http\Message\RequestInterface;
8 use Psr\Http\Message\ResponseInterface;
9 use Psr\Http\Message\StreamInterface;
10 use RecursiveArrayIterator;
11 use RecursiveIteratorIterator;
12
13 /**
14 * Traces state changes between middlewares.
15 */
16 class TraceMiddleware
17 {
18 private $prevOutput;
19 private $prevInput;
20 private $config;
21 /** @var Service */
22 private $service;
23
24 private static $authHeaders = [
25 'X-Amz-Security-Token' => '[TOKEN]',
26 ];
27
28 private static $authStrings = [
29 // S3Signature
30 '/AWSAccessKeyId=[A-Z0-9]{20}&/i' => 'AWSAccessKeyId=[KEY]&',
31 // SignatureV4 Signature and S3Signature
32 '/Signature=.+/i' => 'Signature=[SIGNATURE]',
33 // SignatureV4 access key ID
34 '/Credential=[A-Z0-9]{20}\//i' => 'Credential=[KEY]/',
35 // S3 signatures
36 '/AWS [A-Z0-9]{20}:.+/' => 'AWS AKI[KEY]:[SIGNATURE]',
37 // STS Presigned URLs
38 '/X-Amz-Security-Token=[^&]+/i' => 'X-Amz-Security-Token=[TOKEN]',
39 // Crypto *Stream Keys
40 '/\["key.{27,36}Stream.{9}\]=>\s+.{7}\d{2}\) "\X{16,64}"/U' => '["key":[CONTENT KEY]]',
41 ];
42
43 /**
44 * Configuration array can contain the following key value pairs.
45 *
46 * - logfn: (callable) Function that is invoked with log messages. By
47 * default, PHP's "echo" function will be utilized.
48 * - stream_size: (int) When the size of a stream is greater than this
49 * number, the stream data will not be logged. Set to "0" to not log any
50 * stream data.
51 * - scrub_auth: (bool) Set to false to disable the scrubbing of auth data
52 * from the logged messages.
53 * - http: (bool) Set to false to disable the "debug" feature of lower
54 * level HTTP adapters (e.g., verbose curl output).
55 * - auth_strings: (array) A mapping of authentication string regular
56 * expressions to scrubbed strings. These mappings are passed directly to
57 * preg_replace (e.g., preg_replace($key, $value, $debugOutput) if
58 * "scrub_auth" is set to true.
59 * - auth_headers: (array) A mapping of header names known to contain
60 * sensitive data to what the scrubbed value should be. The value of any
61 * headers contained in this array will be replaced with the if
62 * "scrub_auth" is set to true.
63 */
64 public function __construct(array $config = [], ?Service $service = null)
65 {
66 $this->config = $config + [
67 'logfn' => function ($value) { echo $value; },
68 'stream_size' => 524288,
69 'scrub_auth' => true,
70 'http' => true,
71 'auth_strings' => [],
72 'auth_headers' => [],
73 ];
74
75 $this->config['auth_strings'] += self::$authStrings;
76 $this->config['auth_headers'] += self::$authHeaders;
77 $this->service = $service;
78 }
79
80 public function __invoke($step, $name)
81 {
82 $this->prevOutput = $this->prevInput = [];
83
84 return function (callable $next) use ($step, $name) {
85 return function (
86 CommandInterface $command,
87 $request = null
88 ) use ($next, $step, $name) {
89 $this->createHttpDebug($command);
90 $start = microtime(true);
91 $this->stepInput([
92 'step' => $step,
93 'name' => $name,
94 'request' => $this->requestArray($request),
95 'command' => $this->commandArray($command)
96 ]);
97
98 return $next($command, $request)->then(
99 function ($value) use ($step, $name, $command, $start) {
100 $this->flushHttpDebug($command);
101 $this->stepOutput($start, [
102 'step' => $step,
103 'name' => $name,
104 'result' => $this->resultArray($value),
105 'error' => null
106 ]);
107 return $value;
108 },
109 function ($reason) use ($step, $name, $start, $command) {
110 $this->flushHttpDebug($command);
111 $this->stepOutput($start, [
112 'step' => $step,
113 'name' => $name,
114 'result' => null,
115 'error' => $this->exceptionArray($reason)
116 ]);
117 return new RejectedPromise($reason);
118 }
119 );
120 };
121 };
122 }
123
124 private function stepInput($entry)
125 {
126 static $keys = ['command', 'request'];
127 $this->compareStep($this->prevInput, $entry, '-> Entering', $keys);
128 $this->write("\n");
129 $this->prevInput = $entry;
130 }
131
132 private function stepOutput($start, $entry)
133 {
134 static $keys = ['result', 'error'];
135 $this->compareStep($this->prevOutput, $entry, '<- Leaving', $keys);
136 $totalTime = microtime(true) - $start;
137 $this->write(" Inclusive step time: " . $totalTime . "\n\n");
138 $this->prevOutput = $entry;
139 }
140
141 private function compareStep(array $a, array $b, $title, array $keys)
142 {
143 $changes = [];
144 foreach ($keys as $key) {
145 $av = isset($a[$key]) ? $a[$key] : null;
146 $bv = isset($b[$key]) ? $b[$key] : null;
147 $this->compareArray($av, $bv, $key, $changes);
148 }
149 $str = "\n{$title} step {$b['step']}, name '{$b['name']}'";
150 $str .= "\n" . str_repeat('-', strlen($str) - 1) . "\n\n ";
151 $str .= $changes
152 ? implode("\n ", str_replace("\n", "\n ", $changes))
153 : 'no changes';
154 $this->write($str . "\n");
155 }
156
157 private function commandArray(CommandInterface $cmd)
158 {
159 return [
160 'instance' => spl_object_hash($cmd),
161 'name' => $cmd->getName(),
162 'params' => $this->getRedactedArray($cmd)
163 ];
164 }
165
166 private function requestArray($request = null)
167 {
168 return !$request instanceof RequestInterface
169 ? []
170 : array_filter([
171 'instance' => spl_object_hash($request),
172 'method' => $request->getMethod(),
173 'headers' => $this->redactHeaders($request->getHeaders()),
174 'body' => $this->streamStr($request->getBody()),
175 'scheme' => $request->getUri()->getScheme(),
176 'port' => $request->getUri()->getPort(),
177 'path' => $request->getUri()->getPath(),
178 'query' => $request->getUri()->getQuery(),
179 ]);
180 }
181
182 private function responseArray(?ResponseInterface $response = null)
183 {
184 return !$response ? [] : [
185 'instance' => spl_object_hash($response),
186 'statusCode' => $response->getStatusCode(),
187 'headers' => $this->redactHeaders($response->getHeaders()),
188 'body' => $this->streamStr($response->getBody())
189 ];
190 }
191
192 private function resultArray($value)
193 {
194 return $value instanceof ResultInterface
195 ? [
196 'instance' => spl_object_hash($value),
197 'data' => $value->toArray()
198 ] : $value;
199 }
200
201 private function exceptionArray($e)
202 {
203 if (!($e instanceof \Exception)) {
204 return $e;
205 }
206
207 $result = [
208 'instance' => spl_object_hash($e),
209 'class' => get_class($e),
210 'message' => $e->getMessage(),
211 'file' => $e->getFile(),
212 'line' => $e->getLine(),
213 'trace' => $e->getTraceAsString(),
214 ];
215
216 if ($e instanceof AwsException) {
217 $result += [
218 'type' => $e->getAwsErrorType(),
219 'code' => $e->getAwsErrorCode(),
220 'requestId' => $e->getAwsRequestId(),
221 'statusCode' => $e->getStatusCode(),
222 'result' => $this->resultArray($e->getResult()),
223 'request' => $this->requestArray($e->getRequest()),
224 'response' => $this->responseArray($e->getResponse()),
225 ];
226 }
227
228 return $result;
229 }
230
231 private function compareArray($a, $b, $path, array &$diff)
232 {
233 if ($a === $b) {
234 return;
235 }
236
237 if (is_array($a)) {
238 $b = (array) $b;
239 $keys = array_unique(array_merge(array_keys($a), array_keys($b)));
240 foreach ($keys as $k) {
241 if (!array_key_exists($k, $a)) {
242 $this->compareArray(null, $b[$k], "{$path}.{$k}", $diff);
243 } elseif (!array_key_exists($k, $b)) {
244 $this->compareArray($a[$k], null, "{$path}.{$k}", $diff);
245 } else {
246 $this->compareArray($a[$k], $b[$k], "{$path}.{$k}", $diff);
247 }
248 }
249 } elseif ($a !== null && $b === null) {
250 $diff[] = "{$path} was unset";
251 } elseif ($a === null && $b !== null) {
252 $diff[] = sprintf("%s was set to %s", $path, $this->str($b));
253 } else {
254 $diff[] = sprintf("%s changed from %s to %s", $path, $this->str($a), $this->str($b));
255 }
256 }
257
258 private function str($value)
259 {
260 if (is_scalar($value)) {
261 return (string) $value;
262 }
263
264 if ($value instanceof \Exception) {
265 $value = $this->exceptionArray($value);
266 }
267
268 ob_start();
269 var_dump($value);
270 return ob_get_clean();
271 }
272
273 private function streamStr(StreamInterface $body)
274 {
275 return $body->getSize() < $this->config['stream_size']
276 ? (string) $body
277 : 'stream(size=' . $body->getSize() . ')';
278 }
279
280 private function createHttpDebug(CommandInterface $command)
281 {
282 if ($this->config['http'] && !isset($command['@http']['debug'])) {
283 $command['@http']['debug'] = fopen('php://temp', 'w+');
284 }
285 }
286
287 private function flushHttpDebug(CommandInterface $command)
288 {
289 if ($res = $command['@http']['debug']) {
290 if (is_resource($res)) {
291 rewind($res);
292 $this->write(stream_get_contents($res));
293 fclose($res);
294 }
295 $command['@http']['debug'] = null;
296 }
297 }
298
299 private function write($value)
300 {
301 if ($this->config['scrub_auth']) {
302 foreach ($this->config['auth_strings'] as $pattern => $replacement) {
303 $value = preg_replace_callback(
304 $pattern,
305 function ($matches) use ($replacement) {
306 return $replacement;
307 },
308 $value
309 );
310 }
311 }
312
313 call_user_func($this->config['logfn'], $value);
314 }
315
316 private function redactHeaders(array $headers)
317 {
318 if ($this->config['scrub_auth']) {
319 $headers = $this->config['auth_headers'] + $headers;
320 }
321
322 return $headers;
323 }
324
325 /**
326 * @param CommandInterface $cmd
327 * @return array
328 */
329 private function getRedactedArray(CommandInterface $cmd)
330 {
331 if (!isset($this->service["shapes"])) {
332 return $cmd->toArray();
333 }
334 $shapes = $this->service["shapes"];
335 $cmdArray = $cmd->toArray();
336 $iterator = new RecursiveIteratorIterator(
337 new RecursiveArrayIterator($cmdArray),
338 RecursiveIteratorIterator::SELF_FIRST
339 );
340 foreach ($iterator as $parameter => $value) {
341 if (isset($shapes[$parameter]['sensitive']) &&
342 $shapes[$parameter]['sensitive'] === true
343 ) {
344 $redactedValue = is_string($value) ? "[{$parameter}]" : ["[{$parameter}]"];
345 $currentDepth = $iterator->getDepth();
346 for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {
347 $subIterator = $iterator->getSubIterator($subDepth);
348 $subIterator->offsetSet(
349 $subIterator->key(),
350 ($subDepth === $currentDepth
351 ? $redactedValue
352 : $iterator->getSubIterator(($subDepth+1))->getArrayCopy()
353 )
354 );
355 }
356 }
357 }
358 return $iterator->getArrayCopy();
359 }
360 }