diff --git a/README.md b/README.md index 12f96252..40bb01e9 100644 --- a/README.md +++ b/README.md @@ -503,6 +503,13 @@ a message. Read a line from the stream up to the maximum allowed buffer length. +## `GuzzleHttp\Psr7\Utils::redactUserInfo` + +`public static function redactUserInfo(UriInterface $uri): UriInterface` + +Redact the password in the user info part of a URI. + + ## `GuzzleHttp\Psr7\Utils::streamFor` `public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface` diff --git a/src/Utils.php b/src/Utils.php index b81dab35..fd5bf7ee 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -250,6 +250,21 @@ public static function readLine(StreamInterface $stream, ?int $maxLength = null) return $buffer; } + + /** + * Redact the password in the user info part of a URI. + */ + public static function redactUserInfo(UriInterface $uri): UriInterface + { + $userInfo = $uri->getUserInfo(); + + if (false !== ($pos = \strpos($userInfo, ':'))) { + return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***'); + } + + return $uri; + } + /** * Create a new stream based on the input type. * diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index 704010e1..3f3fd770 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -154,6 +154,15 @@ public function testReadsLineUntilEmptyStringReturnedFromRead(): void self::assertSame('h', Psr7\Utils::readLine($s)); } + public function testRedactUserInfo(): void + { + $uri = new Psr7\Uri('http://my_user:secretPass@localhost/'); + + $redactedUri = Psr7\Utils::redactUserInfo($uri); + + self::assertSame('http://my_user:***@localhost/', (string) $redactedUri); + } + public function testCalculatesHash(): void { $s = Psr7\Utils::streamFor('foobazbar');