diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c34125f..f6f4e3d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -28,6 +28,32 @@ jobs: - name: Check the package contents run: npm pack --dry-run + compat: + # Loads the example's tests with the oldest supported and other Playwright versions. Fixtures + # are checked when the tests load, so this catches fixtures a version does not have. + needs: test + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + playwright: ['1.49.1', '1.56.1', 'latest'] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm pack + - name: List the example's tests with @playwright/test ${{ matrix.playwright }} + working-directory: examples/basic + env: + TESTINGBOT_KEY: dummy + TESTINGBOT_SECRET: dummy + run: | + npm install --no-save @playwright/test@${{ matrix.playwright }} ../../testingbot-playwright-*.tgz + npx playwright test --list + e2e: # Runs the example project on TestingBot. Needs the TESTINGBOT_KEY / TESTINGBOT_SECRET secrets, # which are not available to pull requests from forks. @@ -56,9 +82,23 @@ jobs: - name: Run the example on TestingBot if: env.TESTINGBOT_KEY != '' && env.TESTINGBOT_SECRET != '' working-directory: examples/basic - env: - TESTINGBOT_BUILD: github-${{ github.run_id }} run: | npm install npm install --no-save ../../testingbot-playwright-*.tgz - npx playwright test + npx playwright test --trace on --reporter=list,json,html + env: + TESTINGBOT_BUILD: github-${{ github.run_id }} + PLAYWRIGHT_JSON_OUTPUT_NAME: results.json + PLAYWRIGHT_HTML_OPEN: never + - name: Check that no report or trace contains the credentials + if: env.TESTINGBOT_KEY != '' && env.TESTINGBOT_SECRET != '' + working-directory: examples/basic + run: | + leaks=0 + for f in $(find test-results playwright-report results.json testingbot-sessions.json -type f 2>/dev/null); do + case "$f" in *.zip) content=$(unzip -p "$f") ;; *) content=$(cat "$f") ;; esac + for value in "$TESTINGBOT_KEY" "$TESTINGBOT_SECRET"; do + if printf '%s' "$content" | grep -aqF "$value"; then echo "::error::$f contains TestingBot credentials"; leaks=1; fi + done + done + exit $leaks diff --git a/README.md b/README.md index e3be5df..811a12d 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ TestingBot sessions: - **Opting out.** A project with `use: { testingbot: false }` is left alone and runs locally. You can also pin a project to a browser with `use: { testingbot: { browserName: 'chrome', browserVersion: '120', platform: 'WIN10' } }`. - **Build.** All sessions of a run are grouped in one build: `TESTINGBOT_BUILD` if set, otherwise a generated `playwright ` name. Pass `build: 'my build'` or `build: false`. - **Reporter.** The TestingBot reporter is added after your reporters. Pass `reporter: { outputFile: 'testingbot.json' }` to also write the sessions as JSON (useful in CI), or `reporter: false` to leave it out. -- **`connectOptions`.** Each project also gets `use.connectOptions`, so the `browser` fixture of plain `@playwright/test` connects to TestingBot as well (one session per worker, without status reporting). +- **Credentials stay out of reports and traces.** Playwright copies each project's `use` into its reports, and records the parameters of `connect` in traces. The config therefore holds no credentials: the fixtures of this package add them when they connect, in a way the trace does not record. The `browser` fixture is replaced too, so tests that call `browser.newContext()` share the worker's TestingBot session. ### Options @@ -170,13 +170,13 @@ const browser = await chromium.connect(getConnectUrl({ })) ``` -Use `toPlaywrightBrowserName('edge')` (`chromium`) to pick the browser type, and `runExecutor(page, { action: 'setSessionStatus', arguments: { passed: true } })` to send the result. `startTunnel()` and `stopTunnel()` start and stop a tunnel. +The URL contains your credentials, so keep it out of `playwright.config` (`use.connectOptions`): Playwright writes that into its reports and traces. Use `toPlaywrightBrowserName('edge')` (`chromium`) to pick the browser type, and `runExecutor(page, { action: 'setSessionStatus', arguments: { passed: true } })` to send the result. `startTunnel()` and `stopTunnel()` start and stop a tunnel. ## Limitations - In the default session-per-test mode the `context` fixture is provided by this package. The context options from `use` are applied (viewport, locale, `baseURL`, `storageState`, ...), but Playwright's own `video` option is not: TestingBot records video itself (`tbOptions: { screenrecorder: true }`). Traces and screenshots work as usual. -- Tests that use the `browser` fixture directly (`browser.newContext()`) use the per-worker session from `connectOptions` and get no status. -- Tests must import `test` from `@testingbot/playwright` for names and status. With `test` from `@playwright/test` the tests still run on TestingBot, one session per worker, without names or status. +- Tests that use the `browser` fixture directly (`browser.newContext()`) share one session per worker, which gets no status. +- Tests must import `test` from `@testingbot/playwright`. With `test` from `@playwright/test`, TestingBot refuses the connection with `Missing key or secret`, since the config holds no credentials. ## Development diff --git a/examples/basic/.gitignore b/examples/basic/.gitignore index 24fb7c0..23c9893 100644 --- a/examples/basic/.gitignore +++ b/examples/basic/.gitignore @@ -3,3 +3,4 @@ test-results/ playwright-report/ testingbot-sessions.json package-lock.json +results.json diff --git a/src/capabilities.ts b/src/capabilities.ts index 181c99f..b6e11f3 100644 --- a/src/capabilities.ts +++ b/src/capabilities.ts @@ -106,16 +106,17 @@ export function buildCapabilities(options: ConnectUrlOptions = {}, includeCreden } /** - * Returns the WebSocket URL to pass to `browserType.connect()` or to - * `use.connectOptions.wsEndpoint` in `playwright.config`. + * Returns the WebSocket URL to pass to `browserType.connect()`. It contains your credentials: + * do not put it in `playwright.config` (`use.connectOptions`), where Playwright copies it into + * traces and reports. `withTestingBot()` and the `test` of this package handle that for you. * * ```ts * const browser = await chromium.connect(getConnectUrl({ browserName: 'chrome', platform: 'WIN11', name: 'My test' })) * ``` */ -export function getConnectUrl(options: ConnectUrlOptions = {}): string { +export function getConnectUrl(options: ConnectUrlOptions = {}, includeCredentials = true): string { const endpoint = options.endpoint ?? options.env?.TESTINGBOT_PLAYWRIGHT_ENDPOINT ?? process.env.TESTINGBOT_PLAYWRIGHT_ENDPOINT ?? DEFAULT_ENDPOINT - const capabilities = buildCapabilities(options, true) + const capabilities = buildCapabilities(options, includeCredentials) const separator = endpoint.includes('?') ? '&' : '?' return `${endpoint}${separator}capabilities=${encodeURIComponent(JSON.stringify(capabilities))}` } diff --git a/src/config.ts b/src/config.ts index d602f14..8fbdb55 100644 --- a/src/config.ts +++ b/src/config.ts @@ -140,8 +140,10 @@ export function withTestingBot(config: PlaywrightTestConfig + remoteConnecting?: Promise local?: Promise } @@ -45,8 +45,14 @@ type PlaywrightApi = Pick { const type = playwright[toPlaywrightBrowserName(browserName)] + const run = () => type.connect(wsEndpoint, timeout ? { timeout } : undefined) try { - return await type.connect(wsEndpoint, timeout ? { timeout } : undefined) + // The connect URL carries the credentials, and Playwright Test records the parameters of every + // API call in the trace (and so in the HTML report). Calls inside an internal API zone are not + // recorded. `_wrapApiCall` is private: 1.49-1.52 take a boolean, later versions `{ internal }`; + // an object is truthy for the former. Without it, connect normally. + const wrap = (type as unknown as { _wrapApiCall?: (fn: typeof run, options: unknown) => Promise })._wrapApiCall + return typeof wrap === 'function' ? await wrap.call(type, run, { internal: true }) : await run() } catch (error) { const credentials = findCredentials() const err = error as Error @@ -55,6 +61,16 @@ async function connect(playwright: PlaywrightApi, browserName: string, wsEndpoin } } +/** The shared session of a worker (`sessionPerTest: false`, and the `browser` fixture). */ +function workerSession(playwright: PlaywrightApi, state: WorkerState, testingbot: TestingBotProjectOptions, projectName: string, parallelIndex: number): Promise { + state.remoteConnecting ??= connect( + playwright, + testingbot.browserName ?? 'chrome', + getConnectUrl({ ...testingbot, name: testingbot.name ?? `${projectName} (worker ${parallelIndex})` }) + ).then((browser) => (state.remote ??= { browser, results: [] })) + return state.remoteConnecting +} + async function markSession(browser: Browser, name: string | undefined, result: { passed: boolean; reason?: string } | undefined, context?: BrowserContext): Promise { if (!browser.isConnected()) return undefined const { page, cleanup } = await pageForExecutor(browser, context) @@ -85,7 +101,14 @@ async function markSession(browser: Browser, name: string | undefined, result: { * session (named after the test) and its pass/fail status is sent to TestingBot. * Projects without the `testingbot` option run locally as usual. */ -export const test = base.extend({ +// `_combinedContextOptions` is Playwright Test's own (private) fixture with the context options of +// `use`, merged with `contextOptions`. It exists, test-scoped, in every supported version. +const playwrightTest = base as unknown as TestType< + PlaywrightTestArgs & PlaywrightTestOptions & { _combinedContextOptions: BrowserContextOptions }, + PlaywrightWorkerArgs & PlaywrightWorkerOptions +> + +export const test = playwrightTest.extend({ testingbot: [undefined, { option: true, scope: 'worker' }], _testingbotWorker: [ @@ -104,6 +127,22 @@ export const test = base.extend { + if (testingbot) { + await use((await workerSession(playwright, _testingbotWorker, testingbot, workerInfo.project.name, workerInfo.parallelIndex)).browser) + return + } + _testingbotWorker.local ??= connectOptions + ? playwright[browserName].connect(connectOptions.wsEndpoint, connectOptions) + : playwright[browserName].launch({ headless, channel, ...launchOptions }) + await use(await _testingbotWorker.local) + }, + { scope: 'worker', timeout: 0 } + ], + testingbotSession: [ async ({ testingbot }, use) => { await use({ remote: !!testingbot }) @@ -122,67 +161,15 @@ export const test = base.extend { - const explicit: BrowserContextOptions = { - acceptDownloads, - bypassCSP, - clientCertificates, - colorScheme, - deviceScaleFactor, - extraHTTPHeaders, - forcedColors, - geolocation, - hasTouch, - httpCredentials: httpCredentials as BrowserContextOptions['httpCredentials'], - ignoreHTTPSErrors, - isMobile, - javaScriptEnabled, - locale, - offline, - permissions, - proxy, - reducedMotion, - screen, - serviceWorkers, - storageState, - timezoneId, - userAgent, - viewport, - baseURL - } - const options: BrowserContextOptions = { ...contextOptions } - for (const [key, value] of Object.entries(explicit)) { - if (value !== undefined) (options as Record)[key] = value - } + // Playwright merges `contextOptions` with the context options from `use` (viewport, locale, + // baseURL, ...) in this fixture. Asking for the options one by one breaks on Playwright + // versions that lack one of them (forcedColors, reducedMotion, contrast, ...). + const options: BrowserContextOptions = { ...(_combinedContextOptions ?? {}) } // Local project: behave like Playwright Test, one browser per worker. if (!testingbot) { @@ -201,14 +188,10 @@ export const test = base.extend { expect(use(chrome).testingbot).toEqual({ build: 'b1', browserName: 'chrome', browserVersion: 'latest', platform: 'WIN11', tbOptions: {} }) expect(use(safari).testingbot.tbOptions).toEqual({ screenrecorder: true }) const caps = decodeCapabilities(use(chrome).connectOptions.wsEndpoint) - expect(caps).toMatchObject({ browserName: 'chrome', platform: 'WIN11', 'tb:options': { key: KEY, secret: SECRET, build: 'b1', name: 'chrome@latest:WIN11' } }) + expect(caps).toMatchObject({ browserName: 'chrome', platform: 'WIN11', 'tb:options': { build: 'b1', name: 'chrome@latest:WIN11' } }) + // Playwright copies `use` into reports and traces, so the config holds no credentials. + expect(JSON.stringify(config)).not.toContain(SECRET) + expect(JSON.stringify(config)).not.toContain(KEY) }) it('never puts credentials in the testingbot option or metadata', () => {