diff --git a/src/Debug/SentryLogHandler.php b/src/Debug/SentryLogHandler.php index 094808b8..e4d9a467 100644 --- a/src/Debug/SentryLogHandler.php +++ b/src/Debug/SentryLogHandler.php @@ -23,10 +23,12 @@ public function setClient(ClientInterface $client):void { /** @param array $context */ public function handle(string $level, string $message, array $context = []):void { + // Anonymous PHP class names contain null bytes that log storage can reject. + $message = str_replace("\0", "␀", $message); // Context is deliberately excluded: arbitrary values can contain secrets. $this->pending []= [ "level" => strtoupper($level), - "message" => substr($message, 0, 8192), + "message" => mb_strcut($message, 0, 8192, "UTF-8"), "timestamp" => microtime(true), ]; if(count($this->pending) >= self::BATCH_SIZE) { diff --git a/test/phpunit/Debug/SentryLogHandlerTest.php b/test/phpunit/Debug/SentryLogHandlerTest.php index 0904f9c8..0417240c 100644 --- a/test/phpunit/Debug/SentryLogHandlerTest.php +++ b/test/phpunit/Debug/SentryLogHandlerTest.php @@ -16,6 +16,38 @@ use RuntimeException; class SentryLogHandlerTest extends TestCase { + #[\PHPUnit\Framework\Attributes\DataProvider("logMessages")] + public function testNullBytesAreReplacedBeforeMessagesAreBounded(string $message, string $expected):void { + $client = self::createMock(ClientInterface::class); + $client->method("getOptions")->willReturn(new Options()); + $client->expects(self::once())->method("captureEvent")->willReturnCallback( + function(Event $event) use ($expected):EventId { + self::assertSame($expected, $event->getLogs()[0]->getBody()); + self::assertStringNotContainsString("\0", $event->getLogs()[0]->getBody()); + return $event->getId(); + }, + ); + $handler = new SentryLogHandler(); + $handler->setClient($client); + $handler->handle("ERROR", $message); + $handler->flush(); + } + + /** @return array */ + public static function logMessages():array { + $exception = new class("CSRF Token not found") extends RuntimeException {}; + $message = get_class($exception) . ": " . $exception->getMessage(); + return [ + "anonymous exception" => [$message, str_replace("\0", "␀", $message)], + "multiple null bytes" => ["\0before\0after\0", "␀before␀after␀"], + "ordinary message" => ["Ordinary message", "Ordinary message"], + "literal escape" => ["Already escaped \\0", "Already escaped \\0"], + "symbol stays unchanged" => ["Visible ␀ marker", "Visible ␀ marker"], + "symbol crossing byte limit" => [str_repeat("a", 8191) . "\0", str_repeat("a", 8191)], + "expanded message stays bounded" => [str_repeat("\0", 8192), str_repeat("␀", 2730)], + ]; + } + #[\PHPUnit\Framework\Attributes\DataProvider("unavailableClients")] public function testUnavailableDeliveryFallsBackOnceWithoutContext(string $failure):void { $handler = new SentryLogHandler();