Authenticate Vercel preview CI tests with automation bypass (#4878)

This commit is contained in:
Peter White
2026-12-02 18:20:03 +01:00
committed by GitHub
parent 7d687b8202
commit 6e39000057
9 changed files with 297 additions and 7 deletions
+8 -3
View File
@@ -145,7 +145,8 @@ jobs:
runs-on: ubuntu-latest
name: Visual Testing v2
needs: deploy-v2-vercel
if: ${{ !cancelled() && needs.deploy-v2-vercel.result == 'success' }}
# Skip on forks so PR head test code never receives the project-wide bypass secret.
if: ${{ !cancelled() && needs.deploy-v2-vercel.result == 'success' && !(github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.fork) }}
timeout-minutes: 15
steps:
- name: Checkout
@@ -165,6 +166,7 @@ jobs:
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: v2-vercel
VERCEL_AUTOMATION_BYPASS_SECRET: ${{ secrets.VERCEL_AUTOMATION_BYPASS_SECRET }}
visual-testing-v2-cloudflare:
runs-on: ubuntu-latest
name: Visual Testing v2 (Cloudflare)
@@ -193,7 +195,7 @@ jobs:
runs-on: ubuntu-latest
name: Visual Testing Customers v2
needs: deploy-v2-vercel
if: ${{ !cancelled() && needs.deploy-v2-vercel.result == 'success' }}
if: ${{ !cancelled() && needs.deploy-v2-vercel.result == 'success' && !(github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.fork) }}
timeout-minutes: 30
steps:
- name: Checkout
@@ -213,6 +215,7 @@ jobs:
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
ARGOS_BUILD_NAME: customers-v2-vercel
VERCEL_AUTOMATION_BYPASS_SECRET: ${{ secrets.VERCEL_AUTOMATION_BYPASS_SECRET }}
# Style recalc depends on the client bundle, not the host, so this runs here only and
# not in the Cloudflare job. Kept out of `e2e-customers`, which is a visual suite.
@@ -223,6 +226,7 @@ jobs:
env:
BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
VERCEL_AUTOMATION_BYPASS_SECRET: ${{ secrets.VERCEL_AUTOMATION_BYPASS_SECRET }}
# Runs on failure too: a blown style budget is exactly when the numbers are worth seeing.
- name: Build style invalidation report
@@ -289,7 +293,7 @@ jobs:
runs-on: ubuntu-latest
name: Browserless Testing v2 (Vercel)
needs: deploy-v2-vercel
if: ${{ !cancelled() && needs.deploy-v2-vercel.result == 'success' }}
if: ${{ !cancelled() && needs.deploy-v2-vercel.result == 'success' && !(github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.fork) }}
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -306,6 +310,7 @@ jobs:
env:
BASE_URL: ${{needs.deploy-v2-vercel.outputs.deployment-url}}
SITE_BASE_URL: ${{ needs.deploy-v2-vercel.outputs.deployment-url }}/url/
VERCEL_AUTOMATION_BYPASS_SECRET: ${{ secrets.VERCEL_AUTOMATION_BYPASS_SECRET }}
# browserless-testing-v2-cloudflare:
# runs-on: ubuntu-latest
# name: Browserless Testing v2 (Cloudflare)
+1
View File
@@ -28,6 +28,7 @@ screenshots/
/playwright-report/
/blob-report/
/playwright/.cache/
/playwright/.auth/
# Generated public files
/public/~gitbook/static/*
+53
View File
@@ -0,0 +1,53 @@
import { request } from '@playwright/test';
import path from 'node:path';
import { getVercelProtectionBypassHeaders } from '../tests/utils';
/**
* Storage state holding the Vercel protection bypass cookie, loaded into every browser context.
*/
export const VERCEL_BYPASS_STORAGE_STATE = path.join(
__dirname,
'../playwright/.auth/vercel-bypass.json'
);
/**
* Whether the run goes through Vercel Deployment Protection with an automation bypass secret.
*/
export function isVercelProtectionBypassEnabled() {
return Boolean(process.env.VERCEL_AUTOMATION_BYPASS_SECRET && process.env.BASE_URL);
}
/**
* Exchange the bypass secret for a cookie scoped to the deployment's host. Browsers then send it
* only to that host, while a global header would also go to every third-party resource a page loads.
*/
export default async function globalSetup() {
const baseUrl = process.env.BASE_URL;
if (!baseUrl || !isVercelProtectionBypassEnabled()) {
return;
}
const context = await request.newContext();
try {
// No redirects: the deployment may redirect to another origin, which must not get the secret.
const response = await context.get(baseUrl, {
headers: {
...getVercelProtectionBypassHeaders(baseUrl),
'x-vercel-set-bypass-cookie': 'true',
},
maxRedirects: 0,
});
const state = await context.storageState({ path: VERCEL_BYPASS_STORAGE_STATE });
const host = new URL(baseUrl).hostname;
if (state.cookies.length === 0) {
console.warn(
`Vercel protection bypass: no cookie set for ${host} (status ${response.status()})`
);
} else {
console.log(`Vercel protection bypass: cookie set for ${host}`);
}
} finally {
await context.dispose();
}
}
+1 -1
View File
@@ -137,7 +137,7 @@
"e2e-customers": "playwright test e2e/customers.spec.ts --project=chromium",
"e2e-style-perf": "playwright test e2e/style-perf.spec.ts --project=chromium --reporter=list",
"unit": "bun run generate:assets && bun test {src,packages,openNext} --preload ./tests/preload-bun.ts",
"e2e-browserless": "bun test ./tests/",
"e2e-browserless": "bun test ./tests/ --preload ./tests/preload-browserless.ts",
"typecheck": "tsc --noEmit"
},
"browserslist": [
+13 -1
View File
@@ -1,7 +1,18 @@
import { defineConfig, devices } from '@playwright/test';
import { VERCEL_BYPASS_STORAGE_STATE, isVercelProtectionBypassEnabled } from './e2e/global-setup';
let storageState: string | undefined;
let trace: 'off' | 'on-first-retry' = 'on-first-retry';
if (isVercelProtectionBypassEnabled()) {
storageState = VERCEL_BYPASS_STORAGE_STATE;
// Traces record Cookie headers and Argos uploads them publicly.
trace = 'off';
}
export default defineConfig({
testDir: './e2e',
globalSetup: './e2e/global-setup.ts',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
@@ -38,8 +49,9 @@ export default defineConfig({
},
],
use: {
trace: 'on-first-retry',
trace,
screenshot: 'only-on-failure',
storageState,
contextOptions: {
reducedMotion: 'reduce',
},
@@ -0,0 +1,3 @@
import { withVercelProtectionBypass } from './utils';
globalThis.fetch = withVercelProtectionBypass(globalThis.fetch);
+94
View File
@@ -1,5 +1,37 @@
import { GitBookAPI } from '@gitbook/api';
const VERCEL_PROTECTION_BYPASS_HEADER = 'x-vercel-protection-bypass';
const MAX_REDIRECTS = 20;
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
/**
* Headers that let automation through Vercel Deployment Protection. Empty unless the secret is set
* and the URL is on the deployment under test, so the secret never reaches another origin.
*/
export function getVercelProtectionBypassHeaders(url: string | URL): Record<string, string> {
const secret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;
const baseUrl = process.env.BASE_URL;
if (!secret || !baseUrl) {
return {};
}
if (new URL(url).origin !== new URL(baseUrl).origin) {
return {};
}
return { [VERCEL_PROTECTION_BYPASS_HEADER]: secret };
}
/**
* Wrap a fetch implementation to send the Vercel protection bypass header to the deployment under
* test. Redirects are followed one hop at a time, because fetch keeps custom headers when it
* follows a redirect to another origin.
*/
export function withVercelProtectionBypass(baseFetch: typeof fetch): typeof fetch {
return (input: RequestInfo | URL, init?: RequestInit) =>
fetchWithBypass(baseFetch, new Request(input, init), 0);
}
/**
* Get the base URL of the deployment to test.
*/
@@ -70,3 +102,65 @@ export async function getSiteAPIToken(url: string) {
return data;
}
async function fetchWithBypass(
baseFetch: typeof fetch,
request: Request,
redirectCount: number
): Promise<Response> {
const bypassHeaders = getVercelProtectionBypassHeaders(request.url);
if (Object.keys(bypassHeaders).length === 0) {
return baseFetch(request);
}
const headers = new Headers(request.headers);
for (const [name, value] of Object.entries(bypassHeaders)) {
headers.set(name, value);
}
if (request.redirect !== 'follow') {
return baseFetch(new Request(request, { headers }));
}
const replay = request.clone();
const response = await baseFetch(new Request(request, { headers, redirect: 'manual' }));
const location = response.headers.get('location');
if (!REDIRECT_STATUSES.has(response.status) || !location) {
return response;
}
if (redirectCount >= MAX_REDIRECTS) {
throw new TypeError(`Too many redirects fetching ${request.url}`);
}
const nextURL = new URL(location, request.url);
const nextHeaders = new Headers(replay.headers);
if (nextURL.origin !== new URL(request.url).origin) {
nextHeaders.delete('authorization');
nextHeaders.delete('cookie');
nextHeaders.delete('proxy-authorization');
}
let method = replay.method;
if (
(response.status === 303 && method !== 'HEAD') ||
((response.status === 301 || response.status === 302) && method === 'POST')
) {
method = 'GET';
nextHeaders.delete('content-type');
nextHeaders.delete('content-length');
nextHeaders.delete('content-encoding');
nextHeaders.delete('content-language');
nextHeaders.delete('content-location');
}
let body: ArrayBuffer | undefined;
if (method !== 'GET' && method !== 'HEAD') {
body = await replay.arrayBuffer();
}
return fetchWithBypass(
baseFetch,
new Request(nextURL, { method, headers: nextHeaders, body, signal: replay.signal }),
redirectCount + 1
);
}
@@ -0,0 +1,118 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
import { withVercelProtectionBypass } from './utils';
const SECRET = 'test-bypass-secret';
type Echo = {
origin: string;
method: string;
body: string;
bypass: string | null;
authorization: string | null;
cookie: string | null;
};
describe('Vercel protection bypass', () => {
let deployment: ReturnType<typeof Bun.serve>;
let thirdParty: ReturnType<typeof Bun.serve>;
let savedEnv: { BASE_URL?: string; VERCEL_AUTOMATION_BYPASS_SECRET?: string };
const bypassFetch = withVercelProtectionBypass(fetch);
beforeAll(() => {
thirdParty = Bun.serve({ port: 0, fetch: echo });
deployment = Bun.serve({
port: 0,
fetch: (request) => {
const url = new URL(request.url);
if (url.pathname === '/to-third-party') {
return Response.redirect(new URL('/echo', thirdParty.url).href, 302);
}
if (url.pathname === '/to-same-origin') {
return Response.redirect(new URL('/echo', url).href, 307);
}
return echo(request);
},
});
});
afterAll(() => {
deployment.stop(true);
thirdParty.stop(true);
});
beforeEach(() => {
savedEnv = {
BASE_URL: process.env.BASE_URL,
VERCEL_AUTOMATION_BYPASS_SECRET: process.env.VERCEL_AUTOMATION_BYPASS_SECRET,
};
process.env.BASE_URL = deployment.url.href;
process.env.VERCEL_AUTOMATION_BYPASS_SECRET = SECRET;
});
afterEach(() => {
for (const [name, value] of Object.entries(savedEnv)) {
if (value === undefined) {
delete process.env[name];
} else {
process.env[name] = value;
}
}
});
it('sends the secret to the deployment, across a same-origin redirect', async () => {
const response = await bypassFetch(new URL('/to-same-origin', deployment.url), {
method: 'POST',
body: 'payload',
});
expect(await readEcho(response)).toEqual({
origin: deployment.url.origin,
method: 'POST',
body: 'payload',
bypass: SECRET,
authorization: null,
cookie: null,
});
});
it('never sends the secret or caller credentials to another origin, even through a redirect', async () => {
const direct = await bypassFetch(new URL('/echo', thirdParty.url));
expect((await readEcho(direct)).bypass).toBeNull();
const redirected = await bypassFetch(new URL('/to-third-party', deployment.url), {
headers: {
authorization: 'Bearer visitor-token',
cookie: 'session=abc',
},
});
expect(await readEcho(redirected)).toMatchObject({
origin: thirdParty.url.origin,
bypass: null,
authorization: null,
cookie: null,
});
});
it('sends nothing when the secret is not set', async () => {
delete process.env.VERCEL_AUTOMATION_BYPASS_SECRET;
const response = await bypassFetch(new URL('/echo', deployment.url));
expect((await readEcho(response)).bypass).toBeNull();
});
});
async function readEcho(response: Response) {
return (await response.json()) as Echo;
}
async function echo(request: Request) {
return Response.json({
origin: new URL(request.url).origin,
method: request.method,
body: await request.text(),
bypass: request.headers.get('x-vercel-protection-bypass'),
authorization: request.headers.get('authorization'),
cookie: request.headers.get('cookie'),
} satisfies Echo);
}
+6 -2
View File
@@ -40,12 +40,16 @@
// Run end-to-end tests
"e2e": {
"dependsOn": ["^e2e"],
"env": ["BASE_URL", "SITE_BASE_URL"]
"cache": false,
"env": ["BASE_URL", "SITE_BASE_URL"],
"passThroughEnv": ["VERCEL_AUTOMATION_BYPASS_SECRET"]
},
// Run end-to-end tests for customers
"e2e-customers": {
"dependsOn": ["^e2e-customers"],
"env": ["BASE_URL", "SITE_BASE_URL"]
"cache": false,
"env": ["BASE_URL", "SITE_BASE_URL"],
"passThroughEnv": ["VERCEL_AUTOMATION_BYPASS_SECRET"]
},
// Start the package in development mode for v2
"dev": {