From 8baa5e15c0862049757c8baa5bf9daba5eb793dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Ostroluck=C3=BD?= Date: Wed, 13 May 2020 23:50:40 +0200 Subject: [PATCH] Omit binary body in FullHttpMessageFormatter Goes in line with CurlCommandFormatter. Makes this formatter safer to use --- CHANGELOG.md | 2 ++ .../FullHttpMessageFormatterSpec.php | 21 +++++++++++++++++++ src/Formatter/FullHttpMessageFormatter.php | 18 +++++++++------- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a29df8..246ff76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## Unreleased +- Omitted binary body in FullHttpMessageFormatter. `[binary stream omitted]` will be shown instead. + ### Added - New Header authentication method for arbitrary header authentication. diff --git a/spec/Formatter/FullHttpMessageFormatterSpec.php b/spec/Formatter/FullHttpMessageFormatterSpec.php index a1c4588..af45c7f 100644 --- a/spec/Formatter/FullHttpMessageFormatterSpec.php +++ b/spec/Formatter/FullHttpMessageFormatterSpec.php @@ -227,4 +227,25 @@ function it_does_not_format_no_seekable_response(ResponseInterface $response, St STR; $this->formatResponse($response)->shouldReturn($expectedMessage); } + + function it_omits_body_with_null_bytes(RequestInterface $request, StreamInterface $stream) + { + $this->beConstructedWith(1); + + $stream->isSeekable()->willReturn(true); + $stream->rewind()->shouldBeCalled(); + $stream->__toString()->willReturn("\0"); + $request->getBody()->willReturn($stream); + $request->getMethod()->willReturn('GET'); + $request->getRequestTarget()->willReturn('/foo'); + $request->getProtocolVersion()->willReturn('1.1'); + $request->getHeaders()->willReturn([]); + + $expectedMessage = <<formatRequest($request)->shouldReturn($expectedMessage); + } } diff --git a/src/Formatter/FullHttpMessageFormatter.php b/src/Formatter/FullHttpMessageFormatter.php index 0495802..d252d64 100644 --- a/src/Formatter/FullHttpMessageFormatter.php +++ b/src/Formatter/FullHttpMessageFormatter.php @@ -76,20 +76,24 @@ public function formatResponse(ResponseInterface $response) */ private function addBody(MessageInterface $request, $message) { + $message .= "\n"; $stream = $request->getBody(); if (!$stream->isSeekable() || 0 === $this->maxBodyLength) { // Do not read the stream - return $message."\n"; + return $message; } - if (null === $this->maxBodyLength) { - $message .= "\n".$stream->__toString(); - } else { - $message .= "\n".mb_substr($stream->__toString(), 0, $this->maxBodyLength); + $data = $stream->__toString(); + $stream->rewind(); + + if (preg_match('/[\x00-\x1F\x7F]/', $data)) { + return $message.'[binary stream omitted]'; } - $stream->rewind(); + if (null === $this->maxBodyLength) { + return $message.$data; + } - return $message; + return $message.mb_substr($data, 0, $this->maxBodyLength); } }