diff --git a/bin/lib/core.js b/bin/lib/core.js index ae07dff..098481a 100644 --- a/bin/lib/core.js +++ b/bin/lib/core.js @@ -15,18 +15,6 @@ class Logger { this.levels = { error: 0, warn: 1, info: 2, debug: 3 }; this.currentLevelPriority = this.levels[this.level] ?? this.levels.info; this.logStream = null; - this.initConsoleLogging(); - } - - initConsoleLogging() { - if (DEBUG) { - this.logStream = fs.createWriteStream('playwright-server.log', { flags: 'a' }); - const originalConsoleLog = console.log; - console.log = (d) => { - this.logStream.write(new Date().toISOString() + ' - ' + d + '\n'); - originalConsoleLog(d); - }; - } } shouldLog(level) { @@ -39,16 +27,10 @@ class Logger { if (!this.shouldLog(level)) return; const timestamp = new Date().toISOString(); let logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`; - if (data) { - if (typeof data === 'object') { - try { - logMessage += `\n${JSON.stringify(data, null, 2)}`; - } catch (e) { - logMessage += ` [Object: ${String(data)}]`; - } - } else { - logMessage += ` ${data}`; - } + if (data && typeof data === 'object') { + const fields = ['action', 'method', 'requestId', 'pageId', 'contextId', 'browserId', 'serverId', 'routeId', 'ownerId', 'pid', 'type', 'reason']; + data = Object.fromEntries(Object.entries(data).filter(([key]) => fields.includes(key))); + logMessage += `\n${JSON.stringify(data, null, 2)}`; } logMessage += '\n'; try { @@ -378,6 +360,6 @@ class RouteUtils { const logger = new Logger(); module.exports = { - logger, ErrorHandler, LspFraming, sendFramedResponse, + Logger, logger, ErrorHandler, LspFraming, sendFramedResponse, CommandRegistry, NavigationRedirects, BaseHandler, PromiseUtils, FrameUtils, RouteUtils, }; diff --git a/src/Browser/BrowserBuilder.php b/src/Browser/BrowserBuilder.php index 2e0316d..ec4e4a2 100644 --- a/src/Browser/BrowserBuilder.php +++ b/src/Browser/BrowserBuilder.php @@ -17,7 +17,6 @@ use Playwright\Configuration\PlaywrightConfig; use Playwright\Exception\MissingDependencyException; use Playwright\Exception\PlaywrightException; -use Playwright\Transport\Sanitizer; use Playwright\Transport\TransportInterface; use Psr\Log\LoggerInterface; @@ -116,10 +115,8 @@ public function launch(): BrowserInterface ], $this->config->toContextOptions()); } - // Launch options can carry proxy credentials, so never log them raw. $this->logger->info('Launching browser', [ 'browser' => $this->browserType, - 'options' => Sanitizer::sanitizeParams($this->launchOptions), ]); $response = $this->transport->send([ @@ -177,8 +174,6 @@ private function connectToBrowserServer(string $wsEndpoint, array $options, arra { $this->logger->info('Connecting to browser server', [ 'browser' => $this->browserType, - 'wsEndpoint' => Sanitizer::sanitizeUrl($wsEndpoint), - 'options' => Sanitizer::sanitizeParams($options), ]); $payload = [ @@ -230,8 +225,6 @@ public function connectOverCDP(string $endpointURL, array $options = []): Browse { $this->logger->info('Connecting over CDP', [ 'browser' => $this->browserType, - 'endpointURL' => Sanitizer::sanitizeUrl($endpointURL), - 'options' => Sanitizer::sanitizeParams($options), ]); $response = $this->transport->send([ diff --git a/src/Frame/Frame.php b/src/Frame/Frame.php index 5d5f5a7..c34de4d 100644 --- a/src/Frame/Frame.php +++ b/src/Frame/Frame.php @@ -33,6 +33,7 @@ use Playwright\Page\Options\WaitForNavigationOptions; use Playwright\Page\Options\WaitForUrlOptions; use Playwright\Page\PageInterface; +use Playwright\Transport\MetadataLogger; use Playwright\Transport\TransportInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; @@ -48,7 +49,7 @@ public function __construct( ?LoggerInterface $logger = null, private readonly ?PageInterface $page = null, ) { - $this->logger = $logger ?? new NullLogger(); + $this->logger = MetadataLogger::wrap($logger ?? new NullLogger()); } public function __toString(): string diff --git a/src/Frame/FrameLocator.php b/src/Frame/FrameLocator.php index e11dc6c..8562298 100644 --- a/src/Frame/FrameLocator.php +++ b/src/Frame/FrameLocator.php @@ -18,6 +18,7 @@ use Playwright\Locator\LocatorInterface; use Playwright\Locator\RoleSelectorBuilder; use Playwright\Page\PageInterface; +use Playwright\Transport\MetadataLogger; use Playwright\Transport\TransportInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; @@ -33,7 +34,7 @@ public function __construct( ?LoggerInterface $logger = null, private readonly ?PageInterface $page = null, ) { - $this->logger = $logger ?? new NullLogger(); + $this->logger = MetadataLogger::wrap($logger ?? new NullLogger()); } public function locator(string $selector): LocatorInterface diff --git a/src/Locator/Locator.php b/src/Locator/Locator.php index 4cdd738..c77f086 100644 --- a/src/Locator/Locator.php +++ b/src/Locator/Locator.php @@ -53,7 +53,7 @@ use Playwright\Locator\Options\WaitForOptions; use Playwright\Page\PageInterface; use Playwright\Screenshot\ScreenshotComparison; -use Playwright\Transport\Sanitizer; +use Playwright\Transport\MetadataLogger; use Playwright\Transport\TransportInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; @@ -81,7 +81,7 @@ public function __construct( array $options = [], private readonly ?PageInterface $page = null, ) { - $this->logger = $logger ?? new NullLogger(); + $this->logger = MetadataLogger::wrap($logger ?? new NullLogger()); $this->options = $options; if ($selector instanceof SelectorChain) { $this->selectorChain = $selector; @@ -515,7 +515,6 @@ public function setInputFiles(string|array $files, array|SetInputFilesOptions $o $this->logger->error('Failed to set input files on locator', [ 'selector' => (string) $this->selectorChain, 'files' => $fileArray, - 'error' => Sanitizer::sanitizeParams($e->getMessage()), 'exceptionType' => $e::class, ]); throw $e; @@ -819,7 +818,6 @@ private function sendCommand(string $action, array $params = []): array $errorMessage = is_string($error) ? $error : 'Unknown locator error'; $this->logger->error('Locator command failed', [ 'action' => $action, - 'error' => Sanitizer::sanitizeParams($errorMessage), ]); throw new PlaywrightException($errorMessage); diff --git a/src/Page/Page.php b/src/Page/Page.php index 136e098..2daa668 100644 --- a/src/Page/Page.php +++ b/src/Page/Page.php @@ -82,6 +82,7 @@ use Playwright\Screencast\ScreencastInterface; use Playwright\Screenshot\ScreenshotComparison; use Playwright\Screenshot\ScreenshotHelper; +use Playwright\Transport\MetadataLogger; use Playwright\Transport\Sanitizer; use Playwright\Transport\TransportInterface; use Playwright\Video\Video; @@ -131,7 +132,7 @@ public function __construct( private readonly PlaywrightConfig $config, ?LoggerInterface $logger = null, ) { - $this->logger = $logger ?? $config->logger ?? new NullLogger(); + $this->logger = MetadataLogger::wrap($logger ?? $config->logger ?? new NullLogger()); $this->keyboard = new Keyboard($this->transport, $this->pageId); $this->mouse = new Mouse($this->transport, $this->pageId); @@ -382,7 +383,6 @@ public function goto(string $url, array|GotoOptions $options = []): ?ResponseInt } catch (\Throwable $e) { $this->logger->error('Failed to navigate to URL', [ 'url' => $logUrl, - 'error' => Sanitizer::sanitizeParams($e->getMessage()), 'exceptionType' => $e::class, ]); throw $e; @@ -421,7 +421,6 @@ public function screenshot(?string $path = null, array|ScreenshotOptions $option } catch (\Throwable $e) { $this->logger->error('Failed to take screenshot', [ 'path' => $finalPath, - 'error' => Sanitizer::sanitizeParams($e->getMessage()), 'exceptionType' => $e::class, ]); throw $e; @@ -505,7 +504,6 @@ public function pdf(?string $path = null, array|PdfOptions $options = []): strin } catch (\Throwable $e) { $this->logger->error('Failed to generate PDF', [ 'path' => $finalPath, - 'error' => Sanitizer::sanitizeParams($e->getMessage()), 'exceptionType' => $e::class, ]); @@ -852,7 +850,7 @@ private function sendCommand(string $action, array $params = []): array $error = $response['error']; if (!is_array($error)) { $message = is_string($error) ? $error : 'Unknown error'; - $this->logger->error('Playwright server error (non-structured)', ['error' => Sanitizer::sanitizeParams($error)]); + $this->logger->error('Playwright server error (non-structured)', ['pageId' => $this->pageId]); if (str_contains($message, 'Timeout')) { throw new TimeoutException($message); } @@ -867,7 +865,7 @@ private function sendCommand(string $action, array $params = []): array $message = 'Unknown error'; } - $this->logger->error('Playwright server error', ['error' => Sanitizer::sanitizeParams($error)]); + $this->logger->error('Playwright server error', ['pageId' => $this->pageId]); if (str_contains($message, 'Target page, context or browser has been closed')) { throw new PlaywrightException('Browser context has been closed'); @@ -1430,7 +1428,6 @@ public function setInputFiles(string $selector, array $files, array|SetInputFile $this->logger->error('Failed to set input files', [ 'selector' => $selector, 'files' => $files, - 'error' => Sanitizer::sanitizeParams($e->getMessage()), 'exceptionType' => $e::class, ]); throw $e; diff --git a/src/PlaywrightClient.php b/src/PlaywrightClient.php index 4388549..a957d70 100644 --- a/src/PlaywrightClient.php +++ b/src/PlaywrightClient.php @@ -74,7 +74,7 @@ public function webkit(): BrowserBuilder public function launchServer(string $browser, array $options = []): BrowserServerInterface { $this->connect(); - $this->logger->debug('Launching browser server', ['browser' => $browser, 'options' => $options]); + $this->logger->debug('Launching browser server', ['browser' => $browser]); $response = $this->transport->send([ 'action' => 'launchServer', diff --git a/src/Transport/JsonRpc/JsonRpcTransport.php b/src/Transport/JsonRpc/JsonRpcTransport.php index 6c58672..7661e2a 100644 --- a/src/Transport/JsonRpc/JsonRpcTransport.php +++ b/src/Transport/JsonRpc/JsonRpcTransport.php @@ -264,7 +264,7 @@ public function send(array $message): array return $this->client->sendRaw($message, $timeoutMs); } catch (\Throwable $e) { $this->logger->error('JSON-RPC send failed', [ - 'error' => $e->getMessage(), + 'exceptionType' => $e::class, 'action' => $message['action'] ?? 'unknown', ]); throw $e; @@ -339,7 +339,7 @@ public function sendAsync(array $message): void $this->sendAsyncMessage($message); } catch (\Throwable $e) { $this->logger->warning('JSON-RPC sendAsync failed', [ - 'error' => $e->getMessage(), + 'exceptionType' => $e::class, 'method' => $message['action'] ?? 'unknown', ]); } diff --git a/src/Transport/JsonRpc/ProcessJsonRpcClient.php b/src/Transport/JsonRpc/ProcessJsonRpcClient.php index 94ae10f..4e99348 100644 --- a/src/Transport/JsonRpc/ProcessJsonRpcClient.php +++ b/src/Transport/JsonRpc/ProcessJsonRpcClient.php @@ -82,7 +82,8 @@ protected function sendAndReceive(array $request, ?float $deadline): array $framedMessage = LspFraming::encode($json); $this->logger->debug('Sending JSON-RPC request to process', [ - 'json' => $json, + 'action' => $request['action'] ?? $request['method'] ?? null, + 'requestId' => $requestId, 'pid' => $this->process->getPid(), ]); @@ -140,7 +141,7 @@ private function readProcessOutput(): void $stderr = $this->process->getIncrementalErrorOutput(); $this->process->clearErrorOutput(); if ('' !== $stderr) { - $this->logger->warning('Process stderr', ['stderr' => Sanitizer::sanitizeString($stderr)]); + $this->logger->warning('Process stderr', ['bytes' => strlen($stderr)]); } $this->processAndDispatchMessages(); @@ -172,7 +173,7 @@ private function dispatchMessage(string $messageContent): void return; } - $this->logger->warning('Received non-array JSON from process', ['message' => $messageContent]); + $this->logger->warning('Received non-array JSON from process'); return; } @@ -228,7 +229,6 @@ private function dispatchMessage(string $messageContent): void return; } $this->logger->warning('Failed to parse JSON from process', [ - 'message' => $messageContent, 'error' => $e->getMessage(), ]); } diff --git a/src/Transport/MetadataLogger.php b/src/Transport/MetadataLogger.php new file mode 100644 index 0000000..97c0e8f --- /dev/null +++ b/src/Transport/MetadataLogger.php @@ -0,0 +1,43 @@ + $context */ + public function log($level, string|\Stringable $message, array $context = []): void + { + $this->logger->log($level, $message, array_intersect_key($context, array_flip(self::FIELDS))); + } +} diff --git a/tests/Integration/Bridge/DiagnosticsBridgeTest.php b/tests/Integration/Bridge/DiagnosticsBridgeTest.php new file mode 100644 index 0000000..d1ecb9c --- /dev/null +++ b/tests/Integration/Bridge/DiagnosticsBridgeTest.php @@ -0,0 +1,32 @@ +setTimeout(30); + $process->run(); + + $this->assertSame(0, $process->getExitCode(), $process->getOutput().$process->getErrorOutput()); + } +} diff --git a/tests/Integration/Bridge/diagnostics.test.cjs b/tests/Integration/Bridge/diagnostics.test.cjs new file mode 100644 index 0000000..a261e9c --- /dev/null +++ b/tests/Integration/Bridge/diagnostics.test.cjs @@ -0,0 +1,26 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { mkdtempSync, readFileSync, rmSync } = require('node:fs'); +const { tmpdir } = require('node:os'); +const path = require('node:path'); +const { Logger } = require('../../../bin/lib/core'); + +test('diagnostics keep command metadata and omit arbitrary payloads', () => { + const directory = mkdtempSync(path.join(tmpdir(), 'playwright-log-')); + try { + const logger = new Logger(); + logger.enabled = true; + logger.logPath = path.join(directory, 'dispatch.log'); + logger.info('Dispatching command', { + action: 'locator.fill', requestId: 1, value: 'fill-secret', + error: 'Call log: Authorization: header-secret', + url: 'https://user:password@example.test?token=url-secret', + callbackResult: { cookies: [{ name: 'session', value: 'cookie-secret' }] }, + }); + const log = readFileSync(logger.logPath, 'utf8'); + assert.match(log, /locator.fill/); + for (const secret of ['fill-secret', 'header-secret', 'url-secret', 'cookie-secret', 'password']) assert.equal(log.includes(secret), false); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/tests/Integration/Browser/BrowserBuilderTest.php b/tests/Integration/Browser/BrowserBuilderTest.php index 47560b9..cfdf71f 100644 --- a/tests/Integration/Browser/BrowserBuilderTest.php +++ b/tests/Integration/Browser/BrowserBuilderTest.php @@ -248,7 +248,7 @@ public function itDoesNotLogTheProxyPassword(): void $logger->expects($this->once()) ->method('info') ->with('Launching browser', $this->callback(static function (array $context): bool { - return '[REDACTED]' === $context['options']['proxy']['password']; + return ['browser' => 'chromium'] === $context; })); $transport = $this->createMock(TransportInterface::class); diff --git a/tests/Unit/Browser/BrowserBuilderConnectTest.php b/tests/Unit/Browser/BrowserBuilderConnectTest.php index 370b675..6616110 100644 --- a/tests/Unit/Browser/BrowserBuilderConnectTest.php +++ b/tests/Unit/Browser/BrowserBuilderConnectTest.php @@ -35,7 +35,7 @@ public function testConnectKeepsEndpointCredentialsOutOfTheLog(): void $this->builder($logger, $sent)->connect(self::WS_ENDPOINT); $context = $logger->records[0]['context']; - $this->assertSame('ws://[REDACTED]@127.0.0.1:9222/devtools', $context['wsEndpoint']); + $this->assertArrayNotHasKey('wsEndpoint', $context); $this->assertStringNotContainsString('s3cr3t', json_encode($logger->records) ?: ''); } @@ -47,7 +47,8 @@ public function testConnectKeepsSensitiveOptionsOutOfTheLog(): void $this->builder($logger, $sent)->connect(self::WS_ENDPOINT, ['headers' => ['authorization' => 'Bearer t0ken']]); $context = $logger->records[0]['context']; - $this->assertSame('[REDACTED]', $context['options']['headers']['authorization']); + $this->assertArrayNotHasKey('options', $context); + $this->assertStringNotContainsString('t0ken', json_encode($logger->records) ?: ''); } public function testConnectSendsTheEndpointAndOptionsUnchanged(): void @@ -69,7 +70,7 @@ public function testConnectOverCdpKeepsEndpointCredentialsOutOfTheLog(): void $this->builder($logger, $sent)->connectOverCDP(self::CDP_ENDPOINT); $context = $logger->records[0]['context']; - $this->assertSame('http://[REDACTED]@127.0.0.1:9222/', $context['endpointURL']); + $this->assertArrayNotHasKey('endpointURL', $context); $this->assertStringNotContainsString('s3cr3t', json_encode($logger->records) ?: ''); } @@ -81,7 +82,8 @@ public function testConnectOverCdpKeepsSensitiveOptionsOutOfTheLog(): void $this->builder($logger, $sent)->connectOverCDP(self::CDP_ENDPOINT, ['headers' => ['authorization' => 'Bearer t0ken']]); $context = $logger->records[0]['context']; - $this->assertSame('[REDACTED]', $context['options']['headers']['authorization']); + $this->assertArrayNotHasKey('options', $context); + $this->assertStringNotContainsString('t0ken', json_encode($logger->records) ?: ''); } public function testConnectOverCdpSendsTheEndpointAndOptionsUnchanged(): void diff --git a/tests/Unit/Frame/FrameLocatorTest.php b/tests/Unit/Frame/FrameLocatorTest.php index 9bc339f..240e736 100644 --- a/tests/Unit/Frame/FrameLocatorTest.php +++ b/tests/Unit/Frame/FrameLocatorTest.php @@ -70,12 +70,8 @@ public function testFirst(): void $expectedSelector = $this->initialSelector.' >> nth=0'; $this->logger ->expects($this->once()) - ->method('debug') - ->with('Creating nth frame locator', [ - 'frameSelector' => $this->initialSelector, - 'index' => 0, - 'newSelector' => $expectedSelector, - ]); + ->method('log') + ->with('debug', 'Creating nth frame locator', ['index' => 0]); $newLocator = $this->frameLocator->first(); @@ -89,12 +85,8 @@ public function testLast(): void $expectedSelector = $this->initialSelector.' >> nth=-1'; $this->logger ->expects($this->once()) - ->method('debug') - ->with('Creating nth frame locator', [ - 'frameSelector' => $this->initialSelector, - 'index' => -1, - 'newSelector' => $expectedSelector, - ]); + ->method('log') + ->with('debug', 'Creating nth frame locator', ['index' => -1]); $newLocator = $this->frameLocator->last(); @@ -108,12 +100,8 @@ public function testNth(int $index, string $expectedSelector): void { $this->logger ->expects($this->once()) - ->method('debug') - ->with('Creating nth frame locator', [ - 'frameSelector' => $this->initialSelector, - 'index' => $index, - 'newSelector' => $expectedSelector, - ]); + ->method('log') + ->with('debug', 'Creating nth frame locator', ['index' => $index]); $newLocator = $this->frameLocator->nth($index); @@ -140,12 +128,8 @@ public function testFrameLocator(): void $this->logger ->expects($this->once()) - ->method('debug') - ->with('Creating nested frame locator', [ - 'parentFrameSelector' => $this->initialSelector, - 'childSelector' => $childSelector, - 'newSelector' => $expectedSelector, - ]); + ->method('log') + ->with('debug', 'Creating nested frame locator', []); $newLocator = $this->frameLocator->frameLocator($childSelector); diff --git a/tests/Unit/Locator/LocatorTest.php b/tests/Unit/Locator/LocatorTest.php index 7abe50d..d88fd11 100644 --- a/tests/Unit/Locator/LocatorTest.php +++ b/tests/Unit/Locator/LocatorTest.php @@ -1256,7 +1256,7 @@ public function testGetFrameSelector(): void * Rebinds $this->locator to the '.items' selector used by the filter and * combinator tests, which need a different base selector than setUp(). */ - public function testFailedSetInputFilesLogsTheSanitizedErrorAndExceptionType(): void + public function testFailedSetInputFilesLogsMetadataAndExceptionType(): void { $logger = new TestLogger(); $locator = new Locator($this->transport, 'page1', 'input[type=file]', null, $logger); @@ -1273,7 +1273,7 @@ public function testFailedSetInputFilesLogsTheSanitizedErrorAndExceptionType(): $errors = array_values(array_filter($logger->records, static fn (array $record): bool => 'error' === $record['level'])); $this->assertCount(1, $errors); $this->assertSame('Failed to set input files on locator', $errors[0]['message']); - $this->assertSame('Upload failed: Bearer [REDACTED]', $errors[0]['context']['error']); + $this->assertArrayNotHasKey('error', $errors[0]['context']); $this->assertSame(PlaywrightException::class, $errors[0]['context']['exceptionType']); $this->assertArrayNotHasKey('exception', $errors[0]['context']); } diff --git a/tests/Unit/Page/PageTest.php b/tests/Unit/Page/PageTest.php index 0923497..6d9c983 100644 --- a/tests/Unit/Page/PageTest.php +++ b/tests/Unit/Page/PageTest.php @@ -29,6 +29,7 @@ use Playwright\Exception\ProtocolErrorException; use Playwright\Exception\RuntimeException; use Playwright\Exception\TimeoutException; +use Playwright\Frame\Frame; use Playwright\Frame\FrameInterface; use Playwright\Input\KeyboardInterface; use Playwright\Input\MouseInterface; @@ -86,12 +87,12 @@ public function testNavigationUsesTheConfiguredLoggerWithoutExposingCredentials( $this->assertTrue($logger->hasInfoThatContains('Successfully navigated')); $log = json_encode($logger->records, JSON_THROW_ON_ERROR); - $this->assertStringContainsString('token=[REDACTED]', $log); + $this->assertStringNotContainsString('token=', $log); $this->assertStringNotContainsString('example-navigation-secret', $log); } #[DataProvider('locatorFactories')] - public function testLocatorsLogANativeFailureOnceWithTheConfiguredLogger(callable $createLocator): void + public function testLocatorsLogFailureMetadataOnceWithTheConfiguredLogger(callable $createLocator): void { $logger = new TestLogger(); $page = new Page($this->transport, $this->context, 'page-id', new PlaywrightConfig(logger: $logger)); @@ -107,12 +108,12 @@ public function testLocatorsLogANativeFailureOnceWithTheConfiguredLogger(callabl } finally { $errors = array_values(array_filter($logger->records, static fn (array $record): bool => 'error' === $record['level'])); $this->assertCount(1, $errors); - $this->assertSame('Playwright action failed: Bearer [REDACTED]', $errors[0]['context']['error']); + $this->assertArrayNotHasKey('error', $errors[0]['context']); } } #[DataProvider('failingFileOperations')] - public function testFailedFileOperationsLogTheSanitizedErrorAndExceptionType(callable $operation, string $logMessage): void + public function testFailedFileOperationsLogMetadataAndExceptionType(callable $operation, string $logMessage): void { $logger = new TestLogger(); $page = new Page($this->transport, $this->context, 'page-id', new PlaywrightConfig(logger: $logger)); @@ -131,7 +132,7 @@ public function testFailedFileOperationsLogTheSanitizedErrorAndExceptionType(cal static fn (array $record): bool => 'error' === $record['level'] && $logMessage === $record['message'], )); $this->assertCount(1, $errors); - $this->assertSame('Operation failed: Bearer [REDACTED]', $errors[0]['context']['error']); + $this->assertArrayNotHasKey('error', $errors[0]['context']); $this->assertSame(PlaywrightException::class, $errors[0]['context']['exceptionType']); $this->assertArrayNotHasKey('exception', $errors[0]['context']); $this->assertStringNotContainsString('example-file-secret', json_encode($logger->records, JSON_THROW_ON_ERROR)); @@ -1752,4 +1753,19 @@ public function testVideoRejectsAMalformedResponse(): void $this->page->video(); } + + public function testFrameSelectorsAndPdfTemplatesStayOutOfDiagnostics(): void + { + $logger = new TestLogger(); + $frame = new Frame($this->transport, 'page-id', 'iframe[src="https://example.test?token=frame-canary"]', $logger); + $frame->locator('input'); + $this->transport->method('send')->willReturn([]); + $page = new Page($this->transport, $this->context, 'page-id', new PlaywrightConfig(logger: $logger)); + $page->pdf(sys_get_temp_dir().'/playwright-canary.pdf', ['headerTemplate' => 'pdf-canary', 'displayHeaderFooter' => true]); + $logs = json_encode($logger->records, JSON_THROW_ON_ERROR); + + $this->assertNotEmpty($logger->records); + $this->assertStringNotContainsString('frame-canary', $logs); + $this->assertStringNotContainsString('pdf-canary', $logs); + } } diff --git a/tests/Unit/Transport/JsonRpc/ProcessJsonRpcClientTest.php b/tests/Unit/Transport/JsonRpc/ProcessJsonRpcClientTest.php index 8ab194a..e0826c2 100644 --- a/tests/Unit/Transport/JsonRpc/ProcessJsonRpcClientTest.php +++ b/tests/Unit/Transport/JsonRpc/ProcessJsonRpcClientTest.php @@ -178,7 +178,8 @@ public function testProcessStderrIsLoggedSanitized(): void $warnings = array_values(array_filter($this->logger->records, static fn (array $record): bool => 'warning' === $record['level'])); $this->assertCount(1, $warnings); $this->assertSame('Process stderr', $warnings[0]['message']); - $this->assertStringNotContainsString('example-credential', $warnings[0]['context']['stderr']); + $this->assertArrayNotHasKey('stderr', $warnings[0]['context']); + $this->assertSame(strlen('Authorization: Bearer example-credential'), $warnings[0]['context']['bytes']); } public function testInputStreamWriteFailureThrowsNetworkException(): void @@ -285,4 +286,15 @@ public function testReadProcessOutputClearsBuffersAcrossMultiplePolls(): void $readProcessOutput->invoke($client); $readProcessOutput->invoke($client); } + + public function testRequestValuesAreOmittedFromDiagnostics(): void + { + $this->mockProcess->method('getIncrementalOutput')->willReturn(LspFraming::encode('{"requestId":1,"success":true}')); + $this->client->sendRaw(['action' => 'locator.fill', 'requestId' => 1, 'value' => 'short-secret-value']); + + $logs = json_encode($this->logger->records, JSON_THROW_ON_ERROR); + + $this->assertStringNotContainsString('short-secret-value', $logs); + $this->assertStringContainsString('locator.fill', $logs); + } }