diff --git a/.github/workflows/private-laptop-bridge-smoke-init.yml b/.github/workflows/private-laptop-bridge-smoke-init.yml new file mode 100644 index 0000000000..afc10c4151 --- /dev/null +++ b/.github/workflows/private-laptop-bridge-smoke-init.yml @@ -0,0 +1,40 @@ +name: Initialize empty private laptop bridge smoke Worker + +on: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: private-laptop-bridge-smoke-init + cancel-in-progress: false + +jobs: + initialize: + if: github.repository == 'developing-today/code' && github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' + # Configure this environment out of band with required reviewers and main-only + # rules. This workflow cannot verify or create those GitHub environment rules. + environment: cloudflare-smoke-bootstrap + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + fetch-depth: 1 + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24.22.0 + - name: Run offline bootstrap contract tests + run: node --test --test-reporter=spec pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs + - name: Create only the fixed empty Worker and verify it read-only + env: + # Both values must be provisioned as protected environment secrets; + # neither is a dispatch input or checked-in account/zone data. + CF_SMOKE_INIT_APPROVED_ACCOUNT_ID: ${{ secrets.CF_SMOKE_INIT_APPROVED_ACCOUNT_ID }} + CF_SMOKE_INIT_EXPECTED_ZONE_IDS: ${{ secrets.CF_SMOKE_INIT_EXPECTED_ZONE_IDS }} + CF_SMOKE_INIT_WRITE_TOKEN: ${{ secrets.CF_SMOKE_INIT_WRITE_TOKEN }} + CF_SMOKE_INIT_READ_TOKEN: ${{ secrets.CF_SMOKE_INIT_READ_TOKEN }} + run: node pm-stack/private-laptop-bridge/bootstrap-smoke.mjs diff --git a/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs b/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs new file mode 100644 index 0000000000..8bc4789df7 --- /dev/null +++ b/pm-stack/private-laptop-bridge/bootstrap-smoke.mjs @@ -0,0 +1,250 @@ +#!/usr/bin/env node +// Create the smoke Worker metadata object only. No script/version/deployment, +// routes, domains, workers.dev setting changes, or settings updates are made. + +export const API = 'https://api.cloudflare.com/client/v4'; +export const ACCOUNT_SUFFIX = 'cbfa'; +export const WORKER_NAME = 'private-laptop-bridge-smoke'; +const PAGE_SIZE = 50; +const VERSION_PAGE_SIZE = 100; + +export const CREATE_BODY = Object.freeze({ + name: WORKER_NAME, + logpush: false, + observability: Object.freeze({ enabled: false }), + subdomain: Object.freeze({ enabled: false, previews_enabled: false }), +}); + +function fail(message) { throw new Error(message); } + +function parseExpectedZoneIds(value) { + let ids = value; + if (typeof ids === 'string') { + try { ids = JSON.parse(ids); } catch { fail('approved zone inventory configuration is invalid'); } + } + if (!Array.isArray(ids) || ids.some(id => typeof id !== 'string' || !/^[a-f0-9]{32}$/i.test(id))) { + fail('approved zone inventory configuration is missing or invalid'); + } + if (new Set(ids.map(id => id.toLowerCase())).size !== ids.length) fail('approved zone inventory contains duplicate IDs'); + return ids.map(id => id.toLowerCase()).sort(); +} + +export function validateInputs({ approvedAccountId, writeToken, readToken, expectedZoneIds }) { + if (!/^[a-f0-9]{32}$/i.test(approvedAccountId ?? '') || !approvedAccountId.toLowerCase().endsWith(ACCOUNT_SUFFIX)) { + fail('approved account configuration is missing or invalid'); + } + if (typeof writeToken !== 'string' || writeToken.length < 20) fail('bootstrap write credential is missing'); + if (typeof readToken !== 'string' || readToken.length < 20) fail('bootstrap read-only credential is missing'); + if (writeToken === readToken) fail('bootstrap read and write credentials must be distinct'); + return { approvedAccountId, expectedZoneIds: parseExpectedZoneIds(expectedZoneIds) }; +} + +function parseEnvelope(response, payload) { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) fail('Cloudflare returned an invalid response'); + if (!response.ok || payload.success !== true) { + const status = response.status; + fail(status === 401 || status === 403 + ? `Cloudflare authorization denied (HTTP ${status})` + : `Cloudflare API request failed (HTTP ${status})`); + } + if (!Object.hasOwn(payload, 'result')) fail('Cloudflare response omitted result'); + return payload.result; +} + +async function requestWithInfo(fetchImpl, url, token, { method = 'GET', body, allowWorkerNotFound = false } = {}) { + let response; + try { + response = await fetchImpl(url, { + method, + headers: { + authorization: `Bearer ${token}`, + accept: 'application/json', + ...(body === undefined ? {} : { 'content-type': 'application/json' }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + redirect: 'error', + signal: AbortSignal.timeout(15_000), + }); + } catch { + fail('Cloudflare API request failed before a verified response; do not retry creation automatically'); + } + + let payload; + try { payload = await response.json(); } catch { fail(`Cloudflare returned invalid JSON (HTTP ${response.status})`); } + if (response.status === 404 && allowWorkerNotFound) { + let requestedUrl; + try { requestedUrl = new URL(url); } catch { fail('Cloudflare Worker lookup URL is invalid'); } + const exactEndpoint = requestedUrl.origin === new URL(API).origin && + new RegExp(`^${new URL(API).pathname}/accounts/[a-f0-9]{32}/workers/workers/${WORKER_NAME}$`, 'i').test(requestedUrl.pathname) && + requestedUrl.search === '' && requestedUrl.hash === ''; + const exactResponseUrl = !response.url || response.url === url; + if (method === 'GET' && exactEndpoint && exactResponseUrl && payload?.success === false && + (!Object.hasOwn(payload, 'result') || payload.result === null) && Array.isArray(payload.errors) && payload.errors.length === 1 && + payload.errors[0]?.code === 10007) { + return { absent: true, resultInfo: payload.result_info }; + } + } + return { result: parseEnvelope(response, payload), resultInfo: payload.result_info }; +} + +async function request(fetchImpl, accountId, token, path, options = {}) { + return requestWithInfo(fetchImpl, `${API}/accounts/${encodeURIComponent(accountId)}${path}`, token, options); +} + +function assertWorker(worker) { + if (!worker || typeof worker !== 'object' || Array.isArray(worker)) fail('Worker readback is missing or malformed'); + if (worker.name !== WORKER_NAME || !/^[a-f0-9]{32}$/i.test(worker.id ?? '')) fail('Worker identity does not match the fixed smoke target'); + if (worker.logpush !== false || worker.observability?.enabled !== false) fail('Worker telemetry metadata is not explicitly disabled'); + if (worker.subdomain?.enabled !== false || worker.subdomain?.previews_enabled !== false) fail('Worker public subdomain or preview URL is enabled'); + if (!Object.hasOwn(worker, 'deployed_on') || worker.deployed_on !== null) fail('Worker already has or may have a deployment'); + if (!worker.references || !Array.isArray(worker.references.domains) || worker.references.domains.length !== 0) fail('Worker has a custom domain or domain state could not be verified'); + return worker; +} + +async function listAll(fetchImpl, accountId, readToken, pathname, pageSize, params = {}) { + const all = []; + let expectedTotal; + for (let page = 1; page <= 100; page += 1) { + const query = new URLSearchParams({ ...params, page: String(page), per_page: String(pageSize) }); + const { result, resultInfo } = await request(fetchImpl, accountId, readToken, `${pathname}?${query}`); + if (!Array.isArray(result)) fail('Cloudflare list response was not an array'); + all.push(...result); + if (!resultInfo || !Number.isInteger(resultInfo.total_pages) || resultInfo.total_pages < 0 || resultInfo.total_pages > 100 || + !Number.isInteger(resultInfo.total_count) || resultInfo.total_count < 0) { + fail('Cloudflare pagination metadata is missing or invalid'); + } + if (expectedTotal === undefined) expectedTotal = resultInfo.total_count; + if (resultInfo.total_count !== expectedTotal) fail('Cloudflare list changed during pagination'); + if (resultInfo.total_pages === 0 && page === 1 && expectedTotal === 0 && all.length === 0) return all; + if (resultInfo.total_pages < page) fail('Cloudflare pagination metadata is missing or invalid'); + if (page >= resultInfo.total_pages) { + if (all.length !== expectedTotal) fail('Cloudflare list did not return its complete item count'); + return all; + } + } + fail('Cloudflare pagination exceeded the hard page bound'); +} + +async function listZones(fetchImpl, accountId, readToken, expectedZoneIds) { + const all = []; + let expectedTotal; + let expectedPages; + for (let page = 1; page <= 100; page += 1) { + const query = new URLSearchParams({ + 'account.id': accountId, + type: 'full,partial,secondary,internal', + page: String(page), + per_page: String(PAGE_SIZE), + }); + // Keep result_info for complete pagination proof. + const url = `${API}/zones?${query}`; + const { result, resultInfo } = await requestWithInfo(fetchImpl, url, readToken); + if (!Array.isArray(result)) fail('Cloudflare zone response was not an array'); + if (result.length > PAGE_SIZE) fail('Cloudflare zone page exceeded the requested bound'); + const pageIds = new Set(all.map(zone => zone.id.toLowerCase())); + for (const zone of result) { + if (typeof zone?.id !== 'string' || !/^[a-f0-9]{32}$/i.test(zone.id) || zone?.account?.id?.toLowerCase() !== accountId.toLowerCase()) { + fail('Cloudflare zone inventory contains an invalid owner or ID'); + } + const id = zone.id.toLowerCase(); + if (pageIds.has(id)) { + fail('Cloudflare zone inventory contains a duplicate ID'); + } + pageIds.add(id); + } + all.push(...result); + if (!resultInfo || resultInfo.page !== page || resultInfo.per_page !== PAGE_SIZE || + !Number.isInteger(resultInfo.total_pages) || resultInfo.total_pages < 0 || resultInfo.total_pages > 100 || + !Number.isInteger(resultInfo.total_count) || resultInfo.total_count !== expectedZoneIds.length || + (resultInfo.total_count > 0 && resultInfo.total_pages !== Math.ceil(resultInfo.total_count / PAGE_SIZE)) || + (resultInfo.count !== undefined && resultInfo.count !== result.length)) { + fail('Cloudflare zone pagination metadata is missing or invalid'); + } + if (expectedTotal === undefined) expectedTotal = resultInfo.total_count; + if (expectedPages === undefined) expectedPages = resultInfo.total_pages; + if (resultInfo.total_count !== expectedTotal || resultInfo.total_pages !== expectedPages) fail('Cloudflare zone inventory changed during pagination'); + if ((resultInfo.total_pages === 0 || resultInfo.total_pages === 1) && page === 1 && expectedTotal === 0 && all.length === 0) return all; + if (resultInfo.total_pages < page) fail('Cloudflare zone pagination metadata is missing or invalid'); + if (page >= resultInfo.total_pages) { + if (all.length !== expectedTotal) fail('Cloudflare zone inventory is incomplete'); + return all; + } + } + fail('Cloudflare zone pagination exceeded the hard page bound'); +} + +async function assertNoRoutes(fetchImpl, accountId, readToken, expectedZoneIds) { + const zones = await listZones(fetchImpl, accountId, readToken, expectedZoneIds); + const seen = new Set(); + for (const zone of zones) { + if (typeof zone?.id !== 'string' || !/^[a-f0-9]{32}$/i.test(zone.id) || zone?.account?.id?.toLowerCase() !== accountId.toLowerCase()) { + fail('Cloudflare zone inventory contains an invalid owner or ID'); + } + const zoneId = zone.id.toLowerCase(); + if (seen.has(zoneId)) fail('Cloudflare zone inventory contains a duplicate ID'); + seen.add(zoneId); + const { result } = await requestWithInfo(fetchImpl, `${API}/zones/${encodeURIComponent(zone.id)}/workers/routes`, readToken); + if (!Array.isArray(result)) fail('Cloudflare route response was not an array'); + if (result.some(route => route?.script === WORKER_NAME)) fail('A Cloudflare route already targets the smoke Worker'); + } + const actualIds = [...seen].sort(); + if (actualIds.length !== expectedZoneIds.length || actualIds.some((id, index) => id !== expectedZoneIds[index])) { + fail('Cloudflare zone inventory does not match the approved full-account inventory'); + } +} + +async function assertNoVersionsAndDeployments(fetchImpl, accountId, readToken, workerId) { + const versions = await listAll(fetchImpl, accountId, readToken, `/workers/workers/${encodeURIComponent(workerId)}/versions`, VERSION_PAGE_SIZE); + if (versions.length !== 0) fail('Smoke Worker already has a version; no upload or deployment was attempted'); + const { result, resultInfo } = await request(fetchImpl, accountId, readToken, `/workers/scripts/${encodeURIComponent(WORKER_NAME)}/deployments?page=1&per_page=100`); + if (!result || typeof result !== 'object' || Array.isArray(result) || !Object.hasOwn(result, 'deployments') || + !Array.isArray(result.deployments) || result.deployments.length !== 0 || + (resultInfo?.total_count !== undefined && resultInfo.total_count !== 0)) { + fail('Smoke Worker deployment history is non-empty or unverifiable'); + } +} + +async function readWorker(fetchImpl, accountId, readToken) { + const response = await request(fetchImpl, accountId, readToken, `/workers/workers/${encodeURIComponent(WORKER_NAME)}`, { allowWorkerNotFound: true }); + return response.absent ? null : assertWorker(response.result); +} + +export async function bootstrapSmoke({ approvedAccountId, writeToken, readToken, expectedZoneIds, fetchImpl = fetch }) { + const approved = validateInputs({ approvedAccountId, writeToken, readToken, expectedZoneIds }); + const accountId = approved.approvedAccountId; + + const before = await readWorker(fetchImpl, accountId, readToken); + if (before) { + await assertNoRoutes(fetchImpl, accountId, readToken, approved.expectedZoneIds); + await assertNoVersionsAndDeployments(fetchImpl, accountId, readToken, before.id); + return 'already-present'; + } + + // The complete account route inventory is checked immediately before the + // only write. Any read/scope/pagination error exits before creation. + await assertNoRoutes(fetchImpl, accountId, readToken, approved.expectedZoneIds); + const created = await request(fetchImpl, accountId, writeToken, '/workers/workers', { method: 'POST', body: CREATE_BODY }); + assertWorker(created.result); + + // Re-read using the read-only token, never the create credential. + const after = await readWorker(fetchImpl, accountId, readToken); + if (!after || after.id !== created.result.id) fail('Created Worker identity does not match read-only provider readback'); + await assertNoRoutes(fetchImpl, accountId, readToken, approved.expectedZoneIds); + await assertNoVersionsAndDeployments(fetchImpl, accountId, readToken, after.id); + return 'created'; +} + +if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) { + try { + const status = await bootstrapSmoke({ + approvedAccountId: process.env.CF_SMOKE_INIT_APPROVED_ACCOUNT_ID, + expectedZoneIds: process.env.CF_SMOKE_INIT_EXPECTED_ZONE_IDS, + writeToken: process.env.CF_SMOKE_INIT_WRITE_TOKEN, + readToken: process.env.CF_SMOKE_INIT_READ_TOKEN, + }); + console.log(`Smoke Worker init preflight passed (${status}); no code or deployment was uploaded.`); + } catch (error) { + console.error(error instanceof Error ? error.message : 'Smoke Worker initialization failed'); + process.exitCode = 1; + } +} diff --git a/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs b/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs new file mode 100644 index 0000000000..3212f17bf5 --- /dev/null +++ b/pm-stack/private-laptop-bridge/bootstrap-smoke.test.mjs @@ -0,0 +1,262 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { bootstrapSmoke, CREATE_BODY, WORKER_NAME } from './bootstrap-smoke.mjs'; + +const accountId = `${'a'.repeat(28)}cbfa`; +const zoneId = '1'.repeat(32); +const expectedZoneIds = [zoneId]; +const writeToken = 'synthetic-write-token-000000'; +const readToken = 'synthetic-read-token-0000000'; +const workerId = '0123456789abcdef0123456789abcdef'; +const safeWorker = () => ({ + id: workerId, + name: WORKER_NAME, + logpush: false, + observability: { enabled: false }, + subdomain: { enabled: false, previews_enabled: false }, + deployed_on: null, + references: { domains: [] }, +}); +const ok = (result, result_info = { total_pages: 1, page: 1, per_page: 50, total_count: Array.isArray(result) ? result.length : 0 }) => + new Response(JSON.stringify({ success: true, result, ...(result_info === undefined ? {} : { result_info }) }), { status: 200 }); +const okNoInfo = result => new Response(JSON.stringify({ success: true, result }), { status: 200 }); +const missing = (code = 10007, message = 'Worker not found.', { result = undefined, includeResult = false, status = 404, responseUrl } = {}) => { + const body = { success: false, errors: [{ code, message }] }; + if (includeResult) body.result = result; + const response = new Response(JSON.stringify(body), { status }); + if (responseUrl !== undefined) Object.defineProperty(response, 'url', { value: responseUrl }); + return response; +}; + +function fixture({ worker = null, createdWorker = safeWorker(), route = null, zones = [{ id: zoneId, account: { id: accountId } }], zoneResultInfo, zonePages, versions = [], versionResultInfo, deployments = [], deploymentResultInfo, deploymentNoInfo = false, createResult = null, authFailure = false, writeAuthFailure = false, missingCode = 10007, missingMessage = 'Worker not found.', missingResult, includeMissingResult = false, missingResponseUrl, zoneFailure = false } = {}) { + const state = { worker, createdWorker, route, zones, zoneResultInfo, zonePages, versions, versionResultInfo, deployments, deploymentResultInfo, deploymentNoInfo, createResult, authFailure, writeAuthFailure, missingCode, missingMessage, missingResult, includeMissingResult, missingResponseUrl, zoneFailure, calls: [] }; + const fetchImpl = async (url, init = {}) => { + const parsed = new URL(url); + const method = init.method ?? 'GET'; + const token = init.headers?.authorization; + state.calls.push({ url: parsed, method, token, body: init.body ? JSON.parse(init.body) : undefined }); + if (state.authFailure && token === `Bearer ${readToken}`) { + return new Response(JSON.stringify({ success: false, errors: [{ code: 10000, message: 'Authentication error' }] }), { status: 403 }); + } + if (state.writeAuthFailure && method === 'POST' && token === `Bearer ${writeToken}`) { + return new Response(JSON.stringify({ success: false, errors: [{ code: 10000, message: 'Authentication error' }] }), { status: 403 }); + } + if (parsed.pathname === '/client/v4/zones') { + if (state.zoneFailure) return missing(10007, 'Not found'); + if (state.zonePages) { + const page = Number(parsed.searchParams.get('page')); + const result = state.zonePages[page - 1] ?? []; + return ok(result, { total_pages: state.zonePages.length, page, per_page: 50, total_count: state.zonePages.flat().length, count: result.length }); + } + return ok(state.zones, state.zoneResultInfo); + } + if (parsed.pathname.endsWith('/workers/routes')) return ok(state.route ? [state.route] : []); + if (parsed.pathname.endsWith(`/workers/workers/${WORKER_NAME}`) && method === 'GET') { + return state.worker ? ok(state.worker, undefined) : missing(state.missingCode, state.missingMessage, { result: state.missingResult, includeResult: state.includeMissingResult, responseUrl: state.missingResponseUrl }); + } + if (parsed.pathname.endsWith('/workers/workers') && method === 'POST') { + state.worker = state.createdWorker; + return ok(state.createResult ?? state.createdWorker, undefined); + } + if (parsed.pathname.endsWith(`/workers/workers/${workerId}/versions`)) return ok(state.versions, state.versionResultInfo); + if (parsed.pathname.endsWith(`/workers/scripts/${WORKER_NAME}/deployments`)) { + if (state.deploymentNoInfo) return okNoInfo({ deployments: state.deployments }); + return ok({ deployments: state.deployments }, state.deploymentResultInfo ?? { total_pages: 1, page: 1, per_page: 100, total_count: state.deployments.length }); + } + throw new Error(`unexpected synthetic request ${method} ${parsed.pathname}`); + }; + return { state, fetchImpl }; +} + +function run({ fetchImpl, ...overrides }) { + return bootstrapSmoke({ approvedAccountId: accountId, expectedZoneIds, writeToken, readToken, fetchImpl, ...overrides }); +} + +test('missing target creates exactly one metadata-only Worker and verifies exposure read-only', async () => { + const { state, fetchImpl } = fixture(); + assert.equal(await run({ fetchImpl }), 'created'); + const writes = state.calls.filter(call => call.method !== 'GET'); + assert.equal(writes.length, 1); + assert.equal(writes[0].method, 'POST'); + assert.equal(writes[0].token, `Bearer ${writeToken}`); + assert.deepEqual(writes[0].body, CREATE_BODY); + assert.ok(state.calls.filter(call => call.method === 'GET').every(call => call.token === `Bearer ${readToken}`)); + assert.equal(state.calls.some(call => call.url.pathname.includes('/scripts/') && call.method !== 'GET'), false); +}); + +test('same protected configuration is idempotent for an existing safe target', async () => { + const { state, fetchImpl } = fixture({ worker: safeWorker() }); + assert.equal(await run({ fetchImpl }), 'already-present'); + assert.equal(state.calls.some(call => call.method === 'POST'), false); +}); + +test('full account identity and expected zone inventory are mandatory protected config', async () => { + const { state, fetchImpl } = fixture(); + const wrongAccount = `${'b'.repeat(28)}beef`; + await assert.rejects(run({ fetchImpl, approvedAccountId: wrongAccount }), error => { + assert.match(error.message, /approved account configuration/); + assert.equal(error.message.includes(wrongAccount), false); + return true; + }); + await assert.rejects(run({ fetchImpl, expectedZoneIds: undefined }), /approved zone inventory/); + await assert.rejects(run({ fetchImpl, expectedZoneIds: 'not-json' }), /approved zone inventory/); + assert.equal(state.calls.length, 0); +}); + +test('read and write credentials must be different before any request', async () => { + const { state, fetchImpl } = fixture(); + await assert.rejects(run({ fetchImpl, readToken: writeToken }), /must be distinct/); + assert.equal(state.calls.length, 0); +}); + +test('missing credentials fail before any network request', async () => { + const { state, fetchImpl } = fixture(); + await assert.rejects(run({ fetchImpl, writeToken: '' }), /write credential is missing/); + await assert.rejects(run({ fetchImpl, readToken: '' }), /read-only credential is missing/); + assert.equal(state.calls.length, 0); +}); + +test('only the documented Worker-specific 404 means absent', async () => { + for (const options of [ + { missingMessage: 'The worker resource does not exist for this account.' }, + { missingMessage: 'Not found', includeMissingResult: true, missingResult: null }, + ]) { + const actual = fixture(options); + assert.equal(await run({ fetchImpl: actual.fetchImpl }), 'created'); + assert.equal(actual.state.calls.filter(call => call.method === 'POST').length, 1); + } + + for (const denied of [ + fixture({ missingCode: 10000, missingMessage: 'Resource not found' }), + fixture({ missingCode: '10007', missingMessage: 'Worker not found' }), + fixture({ includeMissingResult: true, missingResult: {} }), + fixture({ missingMessage: 'Worker not found', missingResponseUrl: 'https://api.cloudflare.com/client/v4/accounts/aaaaaaaaaaaaaaaaaaaaaaaaaaaacbfa/workers/workers/other' }), + fixture({ zoneFailure: true }), + ]) { + await assert.rejects(run({ fetchImpl: denied.fetchImpl })); + assert.equal(denied.state.calls.some(call => call.method === 'POST'), false); + } + + const html = fixture(); + const htmlFetch = html.fetchImpl; + html.fetchImpl = async (url, init) => new URL(url).pathname.endsWith(`/workers/workers/${WORKER_NAME}`) + ? new Response('not found', { status: 404, headers: { 'content-type': 'text/html' } }) + : htmlFetch(url, init); + await assert.rejects(run({ fetchImpl: html.fetchImpl }), /invalid JSON/); + assert.equal(html.state.calls.some(call => call.method === 'POST'), false); +}); + +test('read and create authorization failures stop without retry', async () => { + const deniedRead = fixture({ authFailure: true }); + await assert.rejects(run({ fetchImpl: deniedRead.fetchImpl }), /authorization denied/); + assert.equal(deniedRead.state.calls.some(call => call.method === 'POST'), false); + + const deniedWrite = fixture({ writeAuthFailure: true }); + await assert.rejects(run({ fetchImpl: deniedWrite.fetchImpl }), /authorization denied/); + assert.equal(deniedWrite.state.calls.filter(call => call.method === 'POST').length, 1); +}); + +test('zone scan requires owner, unique IDs and exact full-account inventory', async t => { + const cases = [ + { zones: [{ id: zoneId, account: { id: 'f'.repeat(32) } }], expected: /owner or ID/ }, + { zones: [{ id: zoneId, account: { id: accountId } }, { id: zoneId, account: { id: accountId } }], expected: /duplicate ID/ }, + { zones: [], expected: /pagination metadata/ }, + { zones: [{ id: zoneId, account: { id: accountId } }], zoneResultInfo: { total_pages: 1, page: 2, per_page: 50, total_count: 1 }, expected: /pagination metadata/ }, + { zones: [{ id: '2'.repeat(32), account: { id: accountId } }], expected: /does not match the approved/ }, + ]; + for (const item of cases) { + await t.test(item.expected.source, async () => { + const f = fixture({ zones: item.zones, zoneResultInfo: item.zoneResultInfo }); + await assert.rejects(run({ fetchImpl: f.fetchImpl }), item.expected); + assert.equal(f.state.calls.some(call => call.method === 'POST'), false); + }); + } +}); + +test('complete multi-page route inventory is compared to protected zone IDs', async () => { + const ids = Array.from({ length: 51 }, (_, index) => index.toString(16).padStart(32, '0')); + const zones = ids.map(id => ({ id, account: { id: accountId } })); + const f = fixture({ zonePages: [zones.slice(0, 50), zones.slice(50)] }); + assert.equal(await run({ fetchImpl: f.fetchImpl, expectedZoneIds: ids }), 'created'); + const zoneRequests = f.state.calls.filter(call => call.url.pathname === '/client/v4/zones'); + assert.equal(zoneRequests.length, 4); // two complete scans: before and after create +}); + +test('known zero-zone inventory is accepted only when explicitly configured', async () => { + const f = fixture({ zones: [], zoneResultInfo: { total_pages: 0, page: 1, per_page: 50, total_count: 0 } }); + assert.equal(await bootstrapSmoke({ approvedAccountId: accountId, expectedZoneIds: [], writeToken, readToken, fetchImpl: f.fetchImpl }), 'created'); + assert.equal(f.state.calls.some(call => call.method === 'POST'), true); +}); + +test('wrong target or unsafe existing Worker fails without edits', async t => { + const wrong = safeWorker(); wrong.name = 'some-other-worker'; + const badTarget = fixture({ worker: wrong }); + await assert.rejects(run({ fetchImpl: badTarget.fetchImpl }), /identity does not match/); + assert.equal(badTarget.state.calls.some(call => call.method === 'POST'), false); + + for (const change of [ + w => { w.subdomain.enabled = true; }, + w => { w.subdomain.previews_enabled = true; }, + w => { w.deployed_on = '2026-11-23T00:00:00Z'; }, + w => { w.references.domains = [{ hostname: 'example.invalid' }]; }, + ]) { + const worker = safeWorker(); change(worker); + const f = fixture({ worker }); + await t.test('unsafe Worker state', async () => { + await assert.rejects(run({ fetchImpl: f.fetchImpl })); + assert.equal(f.state.calls.some(call => call.method === 'POST'), false); + }); + } +}); + +test('route conflict and incomplete pagination block creation', async () => { + const routed = fixture({ route: { id: 'route', pattern: 'example.invalid/*', script: WORKER_NAME } }); + await assert.rejects(run({ fetchImpl: routed.fetchImpl }), /route already targets/); + assert.equal(routed.state.calls.some(call => call.method === 'POST'), false); + + const incomplete = fixture({ zoneResultInfo: { total_pages: 1, page: 1, per_page: 50, total_count: 2 } }); + await assert.rejects(run({ fetchImpl: incomplete.fetchImpl }), /pagination metadata/); + assert.equal(incomplete.state.calls.some(call => call.method === 'POST'), false); +}); + +test('create response identity mismatch stops after its single write', async () => { + const mismatch = safeWorker(); mismatch.id = 'ffffffffffffffffffffffffffffffff'; + const f = fixture({ createResult: mismatch, createdWorker: safeWorker() }); + await assert.rejects(run({ fetchImpl: f.fetchImpl }), /Created Worker identity/); + assert.equal(f.state.calls.filter(call => call.method === 'POST').length, 1); +}); + +test('empty deployment list is explicit evidence; missing list or conflicting metadata is denied', async t => { + const empty = fixture({ worker: safeWorker(), deploymentNoInfo: true }); + assert.equal(await run({ fetchImpl: empty.fetchImpl }), 'already-present'); + + for (const response of [ + { result: {}, result_info: { total_count: 0 } }, + { result: { deployments: [] }, result_info: { total_count: 1 } }, + { result: { deployments: [{ id: 'deployed' }] }, result_info: undefined }, + ]) { + await t.test('non-empty or unverifiable deployment history', async () => { + const f = fixture({ worker: safeWorker() }); + const original = f.fetchImpl; + f.fetchImpl = async (url, init) => { + if (new URL(url).pathname.endsWith(`/workers/scripts/${WORKER_NAME}/deployments`)) { + return response.result_info === undefined ? okNoInfo(response.result) : ok(response.result, response.result_info); + } + return original(url, init); + }; + await assert.rejects(run({ fetchImpl: f.fetchImpl }), /deployment history/); + assert.equal(f.state.calls.some(call => call.method === 'POST'), false); + }); + } +}); + +test('zero versions and deployment history are required', async () => { + const { state, fetchImpl } = fixture({ worker: safeWorker() }); + assert.equal(await run({ fetchImpl }), 'already-present'); + assert.ok(state.calls.some(call => call.url.pathname.endsWith('/versions'))); + assert.ok(state.calls.some(call => call.url.pathname.endsWith('/deployments'))); + + const withVersion = fixture({ worker: safeWorker(), versions: [{ id: 'synthetic-version' }] }); + await assert.rejects(run({ fetchImpl: withVersion.fetchImpl }), /already has a version/); + assert.equal(withVersion.state.calls.some(call => call.method === 'POST'), false); +});