Skip to content

Latest commit

 

History

History
238 lines (161 loc) · 14.4 KB

preview-testing.md

File metadata and controls

238 lines (161 loc) · 14.4 KB

Test GitHub Next PR previews with Playwright

This runbook explains how maintainers let a coding agent verify live GitHub Next pull-request previews in a real browser, including GitHub sign-in, without ever putting passwords into the repository or exposing them to the model.

GitHub Next runs an external Coolify deployment setup that builds a preview URL for each trusted pull request and posts a bot comment when ready. Repository CI builds and tests the app image, while Coolify manages those preview deployments. This guide is a maintainer security workflow, not a prerequisite for self-hosting Chopin.

The workflow works with any agent harness that can run a local Playwright MCP server, pass an environment variable to it, keep a persistent browser profile, restrict individual tools, and separate the coordinator's conversation history from the browser agent's history.

How authentication works

Browser verification relies on two separate sessions:

  • GitHub session: belongs to a dedicated low-privilege test account and lives in Playwright's persistent browser profile across restarts.
  • Chopin session: stored in an HttpOnly cookie scoped to one preview hostname and one server process. Each new PR preview completes a fresh GitHub OAuth sign-in, and redeploying the preview clears the old Chopin session.

The first sign-in usually asks for a password and may trigger a GitHub device check, email code, 2FA, or passkey prompt. Subsequent previews normally reuse the saved GitHub session and redirect straight back into Chopin.

Playwright MCP 0.0.78 substitutes secret names from an external file when filling fields with browser_type or browser_fill_form, and redacts those values from text tool output. Treat redaction as a safety net, not your primary security boundary.

Security boundary

Once signed in, a preview deployment receives a real GitHub App user token. Only sign in to reviewed, trusted pull requests from the main repository. Never authenticate against a fork or unreviewed commits.

Use a dedicated, disposable GitHub test account with strict limits:

  • Unique password and no access to real repositories or organizations.
  • Write access to exactly one disposable sandbox repository.
  • No personal tokens, SSH keys, GitHub Apps, billing access, or organization roles.
  • Access to a GitHub App installation scoped exclusively to that single sandbox repository.

That repository restriction is the real security boundary. Choosing one repository inside the Chopin UI does not limit what the underlying GitHub token can reach.

Never put a TOTP seed, passkey, recovery code, email password, or session cookie into the Playwright secrets file. Complete second-factor prompts interactively if GitHub asks.

Separate provenance checks from browser testing

Run the workflow with two separate agent sessions so untrusted web content never mixes with privileged repository tools:

  1. Provenance coordinator: has git, authenticated gh, jq, and read access to the repo, with no browser access and no access to login secrets. It verifies the PR, exact head commit, trusted Coolify bot comment, preview URL, and deployment order.
  2. Browser worker: receives only the validated preview URL, expected commit/app markers, and test scope. It has only the restricted Playwright browser tools (backed by the secret file) and zero access to shells, files, gh, Chopin MCP, HTTP fetch, or code editing.

Even if both agents share one host process, keeping separate conversation histories and strict tool allowlists prevents browser output from triggering privileged actions. Pass only pass/fail results, status codes, and screenshot paths back to the coordinator. If a harness cannot lock down the browser worker's tools, do not give it the secret file.

Deployment prerequisites

The preview GitHub App must allow the preview callback URL and be installed on the sandbox repository. Either register exact preview callback URLs or create a dedicated preview-only App with wildcard callbacks restricted to the narrowest preview domain (never reuse a production App or broad organization domain with wildcards). See Authentication and Remote development for App configuration details.

In Coolify's Preview deployments environment, configure:

APP_ORIGIN=https://${SERVICE_FQDN_APP}
GITHUB_APP_SLUG=<preview-app-slug>
GITHUB_APP_CLIENT_ID=<preview-app-client-id>
GITHUB_APP_CLIENT_SECRET=<preview-app-client-secret>
GITHUB_ALLOWED_USERS=<test-account-login>
SESSION_ENCRYPTION_KEY=<preview-only-64-hex-character-key>

Important notes for Coolify previews:

  • GITHUB_ALLOWED_USERS must be set as a runtime variable (it is checked ahead of any configured GITHUB_ALLOWED_ORGANIZATIONS or GITHUB_ALLOWED_TEAMS).

  • Generate a dedicated preview SESSION_ENCRYPTION_KEY with openssl rand -hex 32; never share the production key with PR code.

  • Coolify builds the container from the PR branch, but expands compose.yaml using the production branch. Keep preview-overridable variables in compose.yaml as direct ${NAME} references (not ${NAME:-default}), and merge Compose changes before testing a PR that depends on them.

  • Confirm the preview server's startup log prints at least one admitted user:

    auth: github (restricted: 1 users, ... organizations, ... teams)
    

Install operator tools

The provenance phase needs Git, an authenticated GitHub CLI (gh), jq, and Bash or zsh:

git --version
gh auth status
jq --version

The gh login only needs read access to githubnext/chopin to inspect PRs and Coolify comments. Never pass its token to the browser worker.

Configure Playwright MCP

This repository pins @playwright/mcp@0.0.78 so secret substitution and tool names behave identically across harnesses.

Install Chrome

Install Chrome once on the machine running Playwright MCP:

bunx @playwright/mcp@0.0.78 install-browser chrome

If Chrome is missing, the first browser call fails with Chromium distribution 'chrome' is not found.

Complete first-time login visibly

On Linux without a DISPLAY, Playwright MCP runs headless. Headless mode handles username and password fields, but device approval, 2FA, or passkeys require a visible browser.

To bootstrap the persistent profile once:

  • Start a visible (headed) MCP session pointing at the same workspace or --user-data-dir, complete GitHub verification, close it, and reuse that profile for future headless runs; or
  • Use Playwright MCP's Chrome/Edge extension mode with a dedicated clean browser profile (never your daily browser profile with personal tabs or cookies).

If GitHub shows a second-factor challenge and no visible browser is available, stop rather than weakening the test account's security.

Create the external secret file

Store the test account credentials outside every Git repository, for example at ~/.config/chopin/preview-playwright.env:

CHOPIN_PREVIEW_GITHUB_USERNAME="test-account-login"
CHOPIN_PREVIEW_GITHUB_PASSWORD="unique-test-account-password"
CHOPIN_PREVIEW_GITHUB_APP_NAME="expected-preview-app-name"
CHOPIN_PREVIEW_REPOSITORY="owner/sandbox-repository"

Lock down its permissions so only your user can read it:

chmod 600 ~/.config/chopin/preview-playwright.env

Never commit this file, place it inside a checkout, print it with a tool, or paste its values into a chat prompt. Including CHOPIN_PREVIEW_REPOSITORY lets the workflow reject any unexpected repository.

Register the local MCP server

Configure your harness to start Playwright MCP over stdio with these exact settings:

transport:   stdio
command:     bunx
arguments:   @playwright/mcp@0.0.78 --browser chrome
environment: PLAYWRIGHT_MCP_SECRETS_FILE=/absolute/path/to/preview-playwright.env

Do not pass --isolated, which would discard the saved GitHub session after every run. Because only one browser process can lock a profile at a time, give concurrent harnesses separate --user-data-dir folders outside the repository.

Standard mcpServers JSON example:

{
	"mcpServers": {
		"playwright": {
			"command": "bunx",
			"args": ["@playwright/mcp@0.0.78", "--browser", "chrome"],
			"env": {
				"PLAYWRIGHT_MCP_SECRETS_FILE": "/absolute/path/to/preview-playwright.env"
			}
		}
	}
}

Restrict browser tools

Block these Playwright tools for any agent backed by the secret file:

browser_drop
browser_evaluate
browser_file_upload
browser_network_request
browser_run_code_unsafe

Check whether your harness prefixes tool names (for example playwright_browser_evaluate). Arbitrary JS execution and raw network inspection can bypass string redaction, and file upload or drop tools could leak workspace .env files to a remote page.

Also block browser_snapshot, browser_console_messages, and browser_network_requests unless your harness blocks their optional filename parameter, because Playwright MCP 0.0.78 allows filename to write files inside the workspace even when filesystem tools are disabled. Use browser_find and action summaries instead.

Allow screenshot capture only when visual verification is requested:

  • Save screenshots outside the checkout and only on validated preview pages (never on GitHub sign-in pages).
  • Visually inspect every screenshot before citing it, and caption only what is actually visible. Standard Playwright visibility checks can pass on opacity: 0 elements; for local regression tests, use element.checkVisibility({ checkOpacity: true }) when testing painted visibility.

Deny all non-browser tools (shell, files, gh, HTTP fetch, code execution, subagents, Chopin MCP) on the browser worker.

Load the operating instructions

The workflow rules live in .agents/skills/testing-pr-previews/SKILL.md. Confirm your harness discovers testing-pr-previews, or instruct both agents to read it before starting. For Claude Code (which reads user skills from ~/.claude/skills), symlink the canonical directory instead of copying it:

mkdir -p "$HOME/.claude/skills"
ln -s "$PWD/.agents/skills/testing-pr-previews" \
  "$HOME/.claude/skills/testing-pr-previews"

The skill enforces the full safety checklist: validating PR provenance and the Coolify bot comment, serializing pushes and deploys, verifying the test account before OAuth, checking secret substitution before submitting a password, and refusing extra repositories.

Harness notes

The checked-in opencode.json shows one complete setup for OpenCode V2:

  • Sets mcp.servers.playwright.codemode to false so allowed Playwright tools are exposed directly instead of hidden behind execute (which the browser worker denies).
  • Denies Playwright tools on regular coding agents while defining a restricted preview-browser agent (mode: "all") with default-deny permissions allowing only the safe Playwright tools, screenshots, and testing-pr-previews.
  • Reload configuration after edits with opencode reload.
  • Set CHOPIN_PREVIEW_SECRETS_FILE in the OpenCode server's launch environment (or a complete local MCP server override outside Git) before starting; setting it in a separate client shell does not update a running server.
  • Confirm Playwright shows as connected in /mcps before delegating, and verify the browser worker exposes direct browser tools with zero shell, file, fetch, or Chopin MCP access.

In other harnesses, set PLAYWRIGHT_MCP_SECRETS_FILE directly on the Playwright MCP server and create an equivalent restricted browser agent with its own isolated history.

Run the first smoke test

  1. Verify the test account and preview App still expose only the single sandbox repository.
  2. Confirm the PR head commit has been reviewed and trusted.
  3. Run the provenance phase to collect the validated preview URL, exact head commit, trusted bot comment timestamp, and allowed test scope.
  4. Start or delegate to the restricted preview-browser agent with only that metadata and whether persistent edits (such as creating a channel) are allowed.
  5. Complete any interactive GitHub device or 2FA challenge if prompted.
  6. Confirm the report lists the redacted test username, one writable sandbox repository, every check run, and any failures.

When filling the GitHub password form, check that the generated Playwright step references the secret key rather than a literal string:

await page.getByLabel("Password").fill(process.env["CHOPIN_PREVIEW_GITHUB_PASSWORD"]);

If you see the raw key name as a literal string instead, stop without submitting, fix the MCP environment, reload, and reconnect Playwright.

Troubleshooting

  • Playwright connects, but the browser worker sees no tools: Check that codemode: false is set on the Playwright MCP server, reload config, and wait for MCP initialization to finish.
  • Browser worker has coding or Chopin MCP tools: Verify its permissions start with deny-all and explicitly allow only testing-pr-previews and the safe Playwright tools.
  • GitHub prompts for device verification: Complete the one-time challenge; the persistent profile preserves the GitHub session afterward.
  • Callback says organization membership is temporarily unavailable: GITHUB_ALLOWED_USERS did not reach the preview container (startup log shows 0 users). Check Coolify's Preview runtime env and ensure compose.yaml on the production branch uses direct ${GITHUB_ALLOWED_USERS} references. See Organization admission.
  • Preview asks to sign in again after a redeploy: Sessions persist across deploys only when the preview database, SESSION_ENCRYPTION_KEY, APP_ORIGIN, and App client ID stay unchanged.
  • More than one repository appears: Stop immediately and restrict the test account and App installation back to the single sandbox repository.
  • Browser profile is locked: Close the competing browser process or configure a separate --user-data-dir per concurrent harness.
  • Coolify ready comment is older than the latest push: Do not sign in yet. Wait for the new deployment comment timestamp, or have an operator confirm the deployed commit.

References