diff --git a/docs/examples/drag-and-drop.php b/docs/examples/drag-and-drop.php index c882a252..fd611fbc 100644 --- a/docs/examples/drag-and-drop.php +++ b/docs/examples/drag-and-drop.php @@ -129,8 +129,8 @@ '); // Take initial screenshot -$page->screenshot('/tmp/drag-drop-initial.png'); -echo "Initial screenshot saved: /tmp/drag-drop-initial.png\n"; +$screenshotPath = $page->screenshotAuto('drag-drop-initial'); +echo "Initial screenshot saved: $screenshotPath\n"; // Example 1: Basic drag and drop echo "Performing basic drag and drop...\n"; @@ -138,8 +138,8 @@ $dropZone = $page->locator('#dropzone1'); $draggableItem->dragTo($dropZone); -$page->screenshot('/tmp/drag-drop-after-item1.png'); -echo "Screenshot after dragging item1: /tmp/drag-drop-after-item1.png\n"; +$screenshotPath = $page->screenshotAuto('drag-drop-after-item1'); +echo "Screenshot after dragging item1: $screenshotPath\n"; // Example 2: Drag with specific positions echo "Performing drag with specific source and target positions...\n"; @@ -150,8 +150,8 @@ 'sourcePosition' => ['x' => 50, 'y' => 50], // Center of source element 'targetPosition' => ['x' => 100, 'y' => 100], // Center of target element ]); -$page->screenshot('/tmp/drag-drop-after-item2.png'); -echo "Screenshot after dragging item2 with positions: /tmp/drag-drop-after-item2.png\n"; +$screenshotPath = $page->screenshotAuto('drag-drop-after-item2'); +echo "Screenshot after dragging item2 with positions: $screenshotPath\n"; // Example 3: Force drag (bypass actionability checks) echo "Performing forced drag and drop...\n"; @@ -161,8 +161,8 @@ 'force' => true, 'timeout' => 5000, ]); -$page->screenshot('/tmp/drag-drop-after-item3.png'); -echo "Screenshot after forced drag of item3: /tmp/drag-drop-after-item3.png\n"; +$screenshotPath = $page->screenshotAuto('drag-drop-after-item3'); +echo "Screenshot after forced drag of item3: $screenshotPath\n"; // Example 4: Verify drop results echo "Verifying drop results...\n"; @@ -176,17 +176,12 @@ echo "Drop Zone 2 contains $zone2Count items\n"; // Take final screenshot -$page->screenshot('/tmp/drag-drop-final.png'); -echo "Final screenshot saved: /tmp/drag-drop-final.png\n"; +$screenshotPath = $page->screenshotAuto('drag-drop-final'); +echo "Final screenshot saved: $screenshotPath\n"; // Cleanup $page->close(); $browser->close(); echo "\nDrag and drop examples completed successfully!\n"; -echo "Screenshots saved in /tmp/ directory:\n"; -echo "- drag-drop-initial.png\n"; -echo "- drag-drop-after-item1.png\n"; -echo "- drag-drop-after-item2.png\n"; -echo "- drag-drop-after-item3.png\n"; -echo "- drag-drop-final.png\n"; +echo "Screenshots saved in the configured screenshot directory.\n"; diff --git a/docs/guide/core-concepts.md b/docs/guide/core-concepts.md index afa1ac00..075d60a7 100644 --- a/docs/guide/core-concepts.md +++ b/docs/guide/core-concepts.md @@ -94,3 +94,7 @@ $signInButton->click(); By understanding and using these four core concepts, you can build powerful, reliable, and maintainable browser automation scripts and tests. + +## Private browser output + +Automatic screenshots and PDFs use a private, randomly named temporary directory unless `screenshotDir` is configured. Generated names include the hostname, without URL credentials, paths, query parameters, or fragments. `pdfContent()` returns bytes directly without creating a temporary file. diff --git a/docs/guide/handling-authentication.md b/docs/guide/handling-authentication.md index 2bb7b01e..7bc1e3b7 100644 --- a/docs/guide/handling-authentication.md +++ b/docs/guide/handling-authentication.md @@ -123,3 +123,7 @@ class ProfilePageTest extends AuthenticatedTestCase * Use **UI Login** when you are specifically testing the login, password-reset, or logout features. * Use **Reusing Authentication State** for all other tests that require an authenticated user. It will make your test suite significantly faster and more stable. + +## Saved state + +Storage-state exports are written atomically with owner-only file permissions. Store them in a private directory, exclude them from version control, and remove them when the sessions are no longer needed. Filesystem access controls on Windows must also restrict access to the owning account. diff --git a/src/API/APIRequestContext.php b/src/API/APIRequestContext.php index e1bba0fa..a07bf597 100644 --- a/src/API/APIRequestContext.php +++ b/src/API/APIRequestContext.php @@ -14,6 +14,7 @@ namespace Playwright\API; +use Playwright\Browser\StorageStateFile; use Playwright\Exception\ProtocolErrorException; use Playwright\Tracing\Tracing; use Playwright\Tracing\TracingInterface; @@ -137,7 +138,7 @@ public function storageState(?string $path = null): array $response = $this->transport->send([ 'action' => 'api.storageState', 'contextId' => $this->contextId, - 'path' => $path, + 'path' => null, ]); $storageState = $response['storageState'] ?? null; @@ -152,6 +153,10 @@ public function storageState(?string $path = null): array } } + if (null !== $path) { + StorageStateFile::save($path, $result); + } + return $result; } diff --git a/src/Browser/BrowserContext.php b/src/Browser/BrowserContext.php index 32cf4097..e92a2572 100644 --- a/src/Browser/BrowserContext.php +++ b/src/Browser/BrowserContext.php @@ -494,7 +494,7 @@ public function storageState(?string $path = null): array $response = $this->transport->send([ 'action' => 'context.storageState', 'contextId' => $this->contextId, - 'options' => $path ? ['path' => $path] : [], + 'options' => [], ]); if (!is_array($response['storageState'])) { @@ -508,6 +508,10 @@ public function storageState(?string $path = null): array } } + if (null !== $path) { + StorageStateFile::save($path, $storageState); + } + return $storageState; } diff --git a/src/Browser/StorageState.php b/src/Browser/StorageState.php index f2b6c558..4f988775 100644 --- a/src/Browser/StorageState.php +++ b/src/Browser/StorageState.php @@ -114,15 +114,7 @@ public function toArray(): array public function saveToFile(string $filePath): void { - $directory = \dirname($filePath); - if (!\is_dir($directory) && !\mkdir($directory, 0755, true) && !\is_dir($directory)) { - throw new RuntimeException(\sprintf('Failed to create directory: %s', $directory)); - } - - $result = \file_put_contents($filePath, $this->toJson(JSON_PRETTY_PRINT)); - if (false === $result) { - throw new RuntimeException(\sprintf('Failed to write storage state file: %s', $filePath)); - } + StorageStateFile::save($filePath, $this->toArray()); } public function isEmpty(): bool diff --git a/src/Browser/StorageStateFile.php b/src/Browser/StorageStateFile.php new file mode 100644 index 00000000..721ed826 --- /dev/null +++ b/src/Browser/StorageStateFile.php @@ -0,0 +1,67 @@ + $state */ + public static function save(string $path, array $state): void + { + $json = json_encode($state, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR); + $parent = dirname($path); + + if (!is_dir($parent) && !mkdir($parent, 0700, true) && !is_dir($parent)) { + throw new RuntimeException(sprintf('Failed to create directory: %s', $parent)); + } + + $directory = PrivateDirectory::create($parent); + $temporary = $directory.DIRECTORY_SEPARATOR.'state.json'; + + try { + self::write($temporary, $json); + + if (!rename($temporary, $path)) { + throw new RuntimeException(sprintf('Failed to save storage state file: %s', $path)); + } + } finally { + if (file_exists($temporary)) { + unlink($temporary); + } + + rmdir($directory); + } + } + + private static function write(string $path, string $json): void + { + $stream = fopen($path, 'xb'); + + if (false === $stream) { + throw new RuntimeException('Failed to create storage state file.'); + } + + try { + if (!chmod($path, 0600) || strlen($json) !== fwrite($stream, $json)) { + throw new RuntimeException('Failed to write private storage state file.'); + } + } finally { + fclose($stream); + } + } +} diff --git a/src/Configuration/PlaywrightConfig.php b/src/Configuration/PlaywrightConfig.php index 2c3977c1..6222e24d 100644 --- a/src/Configuration/PlaywrightConfig.php +++ b/src/Configuration/PlaywrightConfig.php @@ -15,6 +15,7 @@ namespace Playwright\Configuration; use Playwright\Browser\BrowserType; +use Playwright\Filesystem\PrivateDirectory; use Psr\Log\LoggerInterface; /** @@ -75,7 +76,7 @@ public function getScreenshotDirectory(): string return $this->screenshotDir; } - return rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'playwright'; + return PrivateDirectory::artifacts(); } /** diff --git a/src/Filesystem/PrivateDirectory.php b/src/Filesystem/PrivateDirectory.php new file mode 100644 index 00000000..253c96a5 --- /dev/null +++ b/src/Filesystem/PrivateDirectory.php @@ -0,0 +1,39 @@ +getPdfDirectory(); - ScreenshotHelper::ensureDirectoryExists($directory); + $response = $this->sendCommand('pdf', ['options' => $options->toArray()]); + $binary = $response['binary'] ?? null; - $tempPath = tempnam($directory, 'pw_pdf_'); - if (false === $tempPath) { - throw new RuntimeException('Failed to allocate a temporary PDF file.'); + if (!is_string($binary)) { + throw new ProtocolErrorException('Invalid PDF content response', 0); } - // Remove the placeholder so Playwright can create the file fresh. - @unlink($tempPath); + $content = base64_decode($binary, true); - try { - $this->pdf($tempPath, $options); - - $content = file_get_contents($tempPath); - if (false === $content) { - throw new RuntimeException('Unable to read generated PDF content.'); - } - - return $content; - } finally { - if (file_exists($tempPath)) { - @unlink($tempPath); - } + if (false === $content) { + throw new ProtocolErrorException('Invalid PDF content encoding', 0); } + + return $content; } /** diff --git a/src/Screenshot/ScreenshotHelper.php b/src/Screenshot/ScreenshotHelper.php index 9c1a686a..7126fc74 100644 --- a/src/Screenshot/ScreenshotHelper.php +++ b/src/Screenshot/ScreenshotHelper.php @@ -74,7 +74,14 @@ public static function generateFilename(string $url, string $directory, string $ */ public static function slugifyUrl(string $url, int $maxLength = 40): string { - $slug = preg_replace('#^(https?://)?(www\.)?#i', '', $url); + $host = parse_url($url, PHP_URL_HOST); + + return self::slugifyName(is_string($host) ? $host : '', $maxLength); + } + + public static function slugifyName(string $name, int $maxLength = 40): string + { + $slug = preg_replace('#^www\.#i', '', $name); if (null === $slug) { $slug = 'invalid-url'; } diff --git a/tests/Integration/Page/ScreenshotIntegrationTest.php b/tests/Integration/Page/ScreenshotIntegrationTest.php index 2cb8f08f..7f8b16b7 100644 --- a/tests/Integration/Page/ScreenshotIntegrationTest.php +++ b/tests/Integration/Page/ScreenshotIntegrationTest.php @@ -224,14 +224,15 @@ public function itGeneratesUniqueFilenames(): void } #[Test] - public function itHandlesDifferentUrlsInFilenames(): void + public function itUsesTheHostnameWithoutTheUrlPathInFilenames(): void { $this->page->goto($this->routeUrl('/page2.html')); $screenshotPath = $this->page->screenshot(); $basename = basename($screenshotPath); - $this->assertStringContainsString('page2', $basename); + $this->assertStringContainsString('localhost', $basename); + $this->assertStringNotContainsString('page2', $basename); $this->assertFileExists($screenshotPath); $this->assertPngFileIsValid($screenshotPath); } diff --git a/tests/Unit/API/APIRequestContextTest.php b/tests/Unit/API/APIRequestContextTest.php index 13a93d6a..afb58bc8 100644 --- a/tests/Unit/API/APIRequestContextTest.php +++ b/tests/Unit/API/APIRequestContextTest.php @@ -170,11 +170,18 @@ public function testStorageStateReturnsCookiesAndOrigins(): void ->with([ 'action' => 'api.storageState', 'contextId' => 'context_1', - 'path' => '/tmp/state.json', + 'path' => null, ]) ->willReturn(['storageState' => $state]); - $this->assertSame($state, $this->context->storageState('/tmp/state.json')); + $path = sys_get_temp_dir().'/playwright-api-state-'.bin2hex(random_bytes(8)).'.json'; + + try { + $this->assertSame($state, $this->context->storageState($path)); + $this->assertSame($state, json_decode((string) file_get_contents($path), true)); + } finally { + @unlink($path); + } } public function testStorageStateRejectsAnInvalidResponse(): void diff --git a/tests/Unit/Browser/BrowserContextTest.php b/tests/Unit/Browser/BrowserContextTest.php index ade5d00d..9b2f1c92 100644 --- a/tests/Unit/Browser/BrowserContextTest.php +++ b/tests/Unit/Browser/BrowserContextTest.php @@ -399,12 +399,19 @@ public function testStorageState(): void ->with([ 'action' => 'context.storageState', 'contextId' => 'context_1', - 'options' => ['path' => '/tmp/state.json'], + 'options' => [], ]) ->willReturn(['storageState' => $expectedState]); - $result = $this->context->storageState('/tmp/state.json'); - $this->assertEquals($expectedState, $result); + $path = sys_get_temp_dir().'/playwright-state-'.bin2hex(random_bytes(8)).'.json'; + + try { + $result = $this->context->storageState($path); + $this->assertEquals($expectedState, $result); + $this->assertSame($expectedState, json_decode((string) file_get_contents($path), true)); + } finally { + @unlink($path); + } } public function testStorageStateWithoutPath(): void diff --git a/tests/Unit/Browser/StorageStateFileTest.php b/tests/Unit/Browser/StorageStateFileTest.php new file mode 100644 index 00000000..cf97e41b --- /dev/null +++ b/tests/Unit/Browser/StorageStateFileTest.php @@ -0,0 +1,79 @@ +markTestSkipped('POSIX file modes and symlinks are required.'); + } + + $directory = PrivateDirectory::create(sys_get_temp_dir()); + $target = $directory.'/target.json'; + $path = $directory.'/state.json'; + $previousMask = umask(0); + $state = ['cookies' => [], 'origins' => [], 'futureField' => ['preserved' => true]]; + + try { + file_put_contents($target, 'unchanged'); + symlink($target, $path); + StorageStateFile::save($path, $state); + clearstatcache(); + + $this->assertFalse(is_link($path)); + $this->assertSame('unchanged', file_get_contents($target)); + $this->assertSame(0600, fileperms($path) & 0777); + $this->assertSame($state, json_decode((string) file_get_contents($path), true)); + + chmod($path, 0666); + StorageStateFile::save($path, $state); + clearstatcache(); + $this->assertSame(0600, fileperms($path) & 0777); + } finally { + umask($previousMask); + unlink($path); + unlink($target); + rmdir($directory); + } + } + + public function testNewParentDirectoriesArePrivate(): void + { + $directory = PrivateDirectory::create(sys_get_temp_dir()); + $parent = $directory.'/new'; + + try { + StorageStateFile::save($parent.'/state.json', []); + $this->assertSame([], json_decode((string) file_get_contents($parent.'/state.json'), true)); + + if (DIRECTORY_SEPARATOR !== '\\') { + $this->assertSame(0700, fileperms($parent) & 0777); + } + } finally { + @unlink($parent.'/state.json'); + @rmdir($parent); + rmdir($directory); + } + } +} diff --git a/tests/Unit/Configuration/PlaywrightConfigTest.php b/tests/Unit/Configuration/PlaywrightConfigTest.php index bbb44469..89cfe5bb 100644 --- a/tests/Unit/Configuration/PlaywrightConfigTest.php +++ b/tests/Unit/Configuration/PlaywrightConfigTest.php @@ -25,6 +25,21 @@ #[CoversClass(BrowserType::class)] class PlaywrightConfigTest extends TestCase { + public function testDefaultArtifactDirectoryIsPrivateAndStableWithinTheProcess(): void + { + $config = new PlaywrightConfig(); + $directory = $config->getScreenshotDirectory(); + + $this->assertDirectoryExists($directory); + $this->assertFalse(is_link($directory)); + $this->assertSame($directory, (new PlaywrightConfig())->getScreenshotDirectory()); + $this->assertNotSame(sys_get_temp_dir().DIRECTORY_SEPARATOR.'playwright', $directory); + + if (DIRECTORY_SEPARATOR !== '\\') { + $this->assertSame(0700, fileperms($directory) & 0777); + } + } + #[Test] public function itCanBeInstantiatedWithDefaults(): void { diff --git a/tests/Unit/Page/PageTest.php b/tests/Unit/Page/PageTest.php index 0923497f..4fd3e08a 100644 --- a/tests/Unit/Page/PageTest.php +++ b/tests/Unit/Page/PageTest.php @@ -1077,7 +1077,7 @@ public function testPdfUsesProvidedPath(): void $this->assertSame($expectedPath, $result); } - public function testPdfContentReturnsBinaryAndCleansUpTempFile(): void + public function testPdfContentReturnsBinaryWithoutWritingAFile(): void { $transport = $this->createMock(TransportInterface::class); $context = $this->createMock(BrowserContextInterface::class); @@ -1092,11 +1092,9 @@ public function testPdfContentReturnsBinaryAndCleansUpTempFile(): void ->method('send') ->willReturnCallback(function (array $payload) use ($pdfBytes): array { $this->assertSame('page.pdf', $payload['action']); - $path = $payload['options']['path'] ?? null; - $this->assertIsString($path); - file_put_contents($path, $pdfBytes); + $this->assertArrayNotHasKey('path', $payload['options']); - return []; + return ['binary' => base64_encode($pdfBytes)]; }); $page = new Page($transport, $context, 'page-unit', $config); diff --git a/tests/Unit/Screenshot/ScreenshotHelperTest.php b/tests/Unit/Screenshot/ScreenshotHelperTest.php index 0ad03eb6..c99d93bc 100644 --- a/tests/Unit/Screenshot/ScreenshotHelperTest.php +++ b/tests/Unit/Screenshot/ScreenshotHelperTest.php @@ -49,14 +49,14 @@ public static function provideUrls(): array { return [ ['https://example.com', 'example-com'], - ['https://www.github.com/user/repo', 'github-com-user-repo'], - ['http://api.service.com/v1/users?id=123', 'api-service-com-v1-users-id-123'], - ['https://sub.domain.co.uk/path/file.html', 'sub-domain-co-uk-path-file-html'], - ['invalid-chars!@#$%^&*()', 'invalid-chars'], + ['https://www.github.com/user/repo', 'github-com'], + ['http://api.service.com/v1/users?id=123', 'api-service-com'], + ['https://sub.domain.co.uk/path/file.html', 'sub-domain-co-uk'], + ['invalid-chars!@#$%^&*()', 'screenshot'], ['!@#$%^&*()', 'screenshot'], ['', 'screenshot'], ['https://sub.domain.co.uk/path/file.html', 'sub-domain', 11], - ['https://example.com/very-long-path-that-exceeds-the-maximum-length-limit', 'example-com-very-lon', 20], + ['https://alice:password@example.com/private-token?key=query-secret#fragment-secret', 'example-com'], ]; } @@ -67,7 +67,7 @@ public function testGenerateFilename(): void $basename = basename($filename); $this->assertMatchesRegularExpression( - '/^\d{8}_\d{6}_\d{3}_github-com-user-repo\.png$/', + '/^\d{8}_\d{6}_\d{3}_github-com\.png$/', $basename );