feat: generate marketing script hash policies and verify isolated Pages previews before scoped production uploads

This commit is contained in:
Matthew Meszaros
2026-10-31 19:53:03 +01:00
parent 72f375d4f5
commit 65b9c754f8
10 changed files with 418 additions and 1 deletions
@@ -0,0 +1,50 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
export function previewURL(deployments, project, branch, sha) {
const matches = deployments.filter(deployment => deployment.environment === 'preview'
&& deployment.deployment_trigger?.metadata?.branch === branch
&& deployment.deployment_trigger?.metadata?.commit_hash === sha
&& deployment.latest_stage?.name === 'deploy'
&& deployment.latest_stage?.status === 'success');
assert.equal(matches.length, 1, 'Require one successful preview for this run and commit');
const url = new URL(matches[0].url);
assert.equal(url.protocol, 'https:');
assert.ok(url.hostname.endsWith(`.${project}.pages.dev`), 'Require the configured Pages project');
assert.ok(!url.username && !url.password && url.pathname === '/' && !url.search && !url.hash);
return url;
}
export async function verifyPreview(url, policy, request = fetch, directory = new URL('../../site/dist/', import.meta.url)) {
for (const [path, status, type] of [
['/', 200, 'text/html'], ['/terms/', 200, 'text/html'], ['/privacy/', 200, 'text/html'],
['/marketing-csp-missing-page', 404, 'text/html'],
['/install.sh', 200, null], ['/cli.sh', 200, null],
]) {
const response = await request(new URL(path, url), { redirect: 'error', signal: AbortSignal.timeout(30000) });
assert.equal(response.status, status, `Unexpected preview status for ${path}`);
assert.equal(response.headers.get('content-security-policy'), policy, `Unexpected preview CSP for ${path}`);
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
if (type) assert.ok(response.headers.get('content-type')?.startsWith(type));
else assert.equal(await response.text(), await readFile(new URL(path.slice(1), directory), 'utf8'));
}
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const { CLOUDFLARE_ACCOUNT_ID: account, CLOUDFLARE_PAGES_PROJECT_NAME: project,
CLOUDFLARE_API_TOKEN: token, PREVIEW_BRANCH: branch, GITHUB_SHA: sha } = process.env;
assert.ok(account && project && token && branch && sha, 'Require preview deployment configuration');
const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${account}/pages/projects/${project}/deployments?env=preview&per_page=100`, {
headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(30000),
});
assert.ok(response.ok, `Pages deployment lookup returned ${response.status}`);
const data = await response.json();
assert.equal(data.success, true, 'Pages deployment lookup must succeed');
const url = previewURL(data.result, project, branch, sha);
const headers = await readFile(new URL('../../site/dist/_headers', import.meta.url), 'utf8');
const policies = [...headers.matchAll(/^\s+Content-Security-Policy: (.+)$/gm)];
assert.equal(policies.length, 1, 'Require one built policy');
await verifyPreview(url, policies[0][1]);
console.log('Marketing preview headers, routes and published installers verified');
}
@@ -0,0 +1,57 @@
import assert from 'node:assert/strict';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { test } from 'node:test';
import { previewURL, verifyPreview } from './pages-marketing-preview.mjs';
test('accepts only this run successful preview on the reviewed commit and project', () => {
const deployment = { environment: 'preview', url: 'https://abc.marketing.pages.dev',
deployment_trigger: { metadata: { branch: 'check-123', commit_hash: 'sha' } },
latest_stage: { name: 'deploy', status: 'success' } };
const select = value => previewURL([value], 'marketing', 'check-123', 'sha');
assert.equal(select(deployment).origin, 'https://abc.marketing.pages.dev');
for (const override of [
{ environment: 'production' }, { url: 'https://abc.other.pages.dev' },
{ latest_stage: { name: 'deploy', status: 'failure' } },
{ deployment_trigger: { metadata: { branch: 'other', commit_hash: 'sha' } } },
{ deployment_trigger: { metadata: { branch: 'check-123', commit_hash: 'old' } } },
]) assert.throws(() => select({ ...deployment, ...override }));
assert.throws(() => previewURL([deployment, deployment], 'marketing', 'check-123', 'sha'));
});
test('verifies page, error and byte-identical installer responses with the built policy', async () => {
const root = await mkdtemp(join(tmpdir(), 'marketing-preview-'));
try {
for (const file of ['install.sh', 'cli.sh']) await writeFile(join(root, file), `# ${file}\n`);
const paths = [];
const request = async url => {
paths.push(url.pathname);
const script = url.pathname.endsWith('.sh');
return new Response(script ? `# ${url.pathname.slice(1)}\n` : '<html>Page</html>', {
status: url.pathname.includes('missing-page') ? 404 : 200,
headers: { 'content-security-policy': 'policy', 'x-content-type-options': 'nosniff',
'content-type': script ? 'text/plain' : 'text/html; charset=utf-8' },
});
};
await verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`));
assert.deepEqual(paths, ['/', '/terms/', '/privacy/', '/marketing-csp-missing-page', '/install.sh', '/cli.sh']);
await writeFile(join(root, 'cli.sh'), 'different bytes');
await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`)));
} finally {
await rm(root, { recursive: true, force: true });
}
});
test('blocks promotion for absent or different policy, redirects and unexpected responses', async () => {
for (const response of [
new Response('', { status: 200 }),
new Response('', { status: 200, headers: { 'content-security-policy': 'other' } }),
new Response('', { status: 503 }),
]) await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async () => response));
await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async (url, options) => {
assert.equal(options.redirect, 'error');
throw new Error('redirect refused');
}), /redirect refused/);
});