diff --git a/docs/guide/platform/installation/prerequisites.md b/docs/guide/platform/installation/prerequisites.md index bdd2f4668..6d020c73c 100644 --- a/docs/guide/platform/installation/prerequisites.md +++ b/docs/guide/platform/installation/prerequisites.md @@ -73,7 +73,7 @@ Void does not require a particular database provider. Use an existing PostgreSQL 1. Create a fresh database or project dedicated to the platform, with no existing application tables. Use a database role that can create and manage its tables and schemas. 2. Open the provider's connection details and select the primary database. Use a direct connection or a session-mode pooler, not transaction pooling. The connection must work from both your computer and Cloudflare. -3. Copy the PostgreSQL connection URL, including the password and SSL settings, into your password manager. Paste only the URL—not a surrounding `psql` command—into Void's `PostgreSQL DATABASE_URL` prompt. +3. Copy the PostgreSQL connection URL, including the password and SSL settings, into your password manager. Paste only the URL—not a surrounding `psql` command—into Void's `PostgreSQL DATABASE_URL` prompt, as the provider gives it, including SSL settings such as `sslmode=verify-full`. A Hyperdrive that Void creates trusts only public certificate authorities, so if your database uses a private certificate authority, use a separately managed Hyperdrive, as described below. | Provider | Connection setup | | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | diff --git a/docs/guide/platform/installation/uninstall.md b/docs/guide/platform/installation/uninstall.md index bbb67066b..d0b46aa8d 100644 --- a/docs/guide/platform/installation/uninstall.md +++ b/docs/guide/platform/installation/uninstall.md @@ -31,7 +31,7 @@ void platform uninstall [id] --plan void platform uninstall [id] ``` -Uninstall blocks platform traffic, removes transient Queues, and records the resources left for you to review. By default, Workers, KV, R2, Hyperdrive, the dispatch namespace, and AI Gateway remain in your account. Adopted resources, external PostgreSQL, zones, DNS records, routes, custom domains, and Cloudflare Access resources are always retained. +Uninstall blocks platform traffic, removes Queues that no remaining platform Worker uses, and records the resources left for you to review. By default, Workers, the Queues they use, KV, R2, Hyperdrive, the dispatch namespace, and AI Gateway remain in your account. Adopted resources, external PostgreSQL, zones, DNS records, routes, custom domains, and Cloudflare Access resources are always retained. To also remove eligible data resources owned by the installer: @@ -39,7 +39,20 @@ To also remove eligible data resources owned by the installer: void platform uninstall [id] --purge-data ``` -Even with `--purge-data`, Void retains Workers, R2, AI Gateway, DNS records, routes, custom domains, Access resources, adopted resources, external PostgreSQL, and zones. Review those in the Cloudflare dashboard if you want to remove them. +Even with `--purge-data`, Void retains Workers, the Queues they use, R2, AI Gateway, DNS records, routes, custom domains, Access resources, adopted resources, external PostgreSQL, and zones. Review those in the Cloudflare dashboard if you want to remove them. + +### Remove retained resources + +Cloudflare refuses to delete a resource while a platform Worker still uses it. In the Cloudflare dashboard, remove what is left in this order, skipping anything already gone: + +1. Delete the platform DNS record, Worker routes, and custom domains. +2. Open each platform Queue and remove the platform API Worker from its consumers. +3. Delete the platform Workers. +4. Delete the platform Queues. +5. Delete the application Workers in the dispatch namespace, then delete the namespace. +6. Delete the platform KV namespaces and Hyperdrive configuration. +7. Empty the R2 bucket, then delete it. +8. Delete the AI Gateway. If installation configured Cloudflare Access, the uninstall plan lists its recorded applications and service tokens with their ownership and IDs. Review them in Zero Trust after uninstall. Remove installer-created resources only when nothing else uses them; resources connected from an existing company setup remain under their owner's control. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index fe6fe898e..87b54854e 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -866,11 +866,11 @@ An upgrade completes after the new Workers pass health checks. If rollout fails, `platform rollback` restores a compatible earlier runtime without reversing database migrations. Pass its files with `--runtime`. If the installed version is a custom build, also supply that version with `--from-runtime`. Void refuses targets that are incompatible with the current database or predate installed authentication, sandbox-drain, or ownership-aware usage protocols. A later `upgrade` can move forward again. -Uninstall verifies remote ownership before removing anything. Data resources are retained unless you pass `--purge-data`. Workers, R2, AI Gateway, DNS records, routes, custom domains, adopted resources, external PostgreSQL, and zones are always retained for manual review. +Uninstall verifies remote ownership before removing anything. Data resources are retained unless you pass `--purge-data`. Workers, the Queues they use, R2, AI Gateway, DNS records, routes, custom domains, adopted resources, external PostgreSQL, and zones are always retained for manual review. Resources that may have been shared or repurposed are retained for manual review. Platform traffic stays blocked. External PostgreSQL and its data are never deleted. -See [Disable and Uninstall](../guide/platform/installation/uninstall.md) for the full removal policy. +See [Disable and Uninstall](../guide/platform/installation/uninstall.md#remove-retained-resources) for the full removal policy and the cleanup order. ## Deploy diff --git a/packages/void/src/cli/platform-cloudflare.ts b/packages/void/src/cli/platform-cloudflare.ts index b15a1cb3a..8a6e5ea18 100644 --- a/packages/void/src/cli/platform-cloudflare.ts +++ b/packages/void/src/cli/platform-cloudflare.ts @@ -1128,7 +1128,7 @@ function parseDnsRecord(value: Record): CloudflareDnsRecord { export function parsePostgresConnectionString(value: string): { database: string; host: string; - mtls?: Readonly<{ sslmode: 'require' | 'verify-ca' | 'verify-full' }>; + mtls?: Readonly<{ sslmode: 'require' }>; password: string; port: number; user: string; @@ -1151,14 +1151,17 @@ export function parsePostgresConnectionString(value: string): { throw new Error('platform: DATABASE_URL has an invalid PostgreSQL port.'); } const sslmode = url.searchParams.get('sslmode'); - let mtls: Readonly<{ sslmode: 'require' | 'verify-ca' | 'verify-full' }> | undefined; + let mtls: Readonly<{ sslmode: 'require' }> | undefined; if (sslmode) { if (sslmode !== 'require' && sslmode !== 'verify-ca' && sslmode !== 'verify-full') { throw new Error( 'platform: Unsupported sslmode. Cloudflare Hyperdrive supports "require", "verify-ca", or "verify-full".', ); } - mtls = { sslmode }; + // Hyperdrive accepts its verify modes only with an uploaded CA certificate ID, which a + // connection URL cannot carry. `require` is Hyperdrive's TLS mode that validates the server + // certificate against public CAs; Void's own database connections still use the URL's mode. + mtls = { sslmode: 'require' }; } return { database, diff --git a/packages/void/src/cli/platform-installer.ts b/packages/void/src/cli/platform-installer.ts index 6e6336d2c..72d18e39a 100644 --- a/packages/void/src/cli/platform-installer.ts +++ b/packages/void/src/cli/platform-installer.ts @@ -85,6 +85,7 @@ import { import { hyperdriveOriginConfigHash, hyperdriveOriginFromConnectionString, + parsePostgresConnectionString, PlatformWorkerCustomDomainsChangedError, PlatformWorkerRoutesChangedError, type CloudflareNamedResource, @@ -1405,6 +1406,11 @@ export async function installPlatform( writeInstallationManifest(manifest); } assertRequiredPlatformSecrets(plan, manifest, secrets, !!dependencies.prepareAuthentication); + if (hyperdriveAction?.action === 'create') { + // Reject a URL Hyperdrive can never accept before the claim binds it to this installation. + parsePostgresConnectionString(secrets.databaseUrl); + assertVoidCreatedHyperdriveTrustsDatabase(secrets.databaseUrl); + } const pendingSecrets = secretCheckpoint(secrets, workerSecretUpdateIntent); writePendingInstallationSecrets(manifest, { ...pendingSecrets, @@ -2646,6 +2652,9 @@ export async function installPlatform( PLATFORM_DISABLED_VALUE, ); }, + // Traffic opens only after every Worker in this generation is + // verified against its own staged checkpoint, so none may be reused. + reuseMatchingVersion: false, runner: runPinnedPlatformWrangler, workerExisted: true, }); @@ -3482,6 +3491,20 @@ export function assertRequiredPlatformSecrets( } } +/** + * A Hyperdrive that Void creates validates the server against public certificate authorities + * only, so it cannot honor a private CA that the local database client would trust. + */ +function assertVoidCreatedHyperdriveTrustsDatabase(databaseUrl: string): void { + // Same last-value-wins rule as the local client; pg ignores an empty value. + const sslrootcert = new URL(databaseUrl).searchParams.getAll('sslrootcert').at(-1); + if (sslrootcert && sslrootcert !== 'system') { + throw new Error( + 'platform: A Hyperdrive created by Void trusts only public certificate authorities, so it cannot use the certificate authority in DATABASE_URL sslrootcert. If the database certificate comes from a public certificate authority, use sslrootcert=system. Otherwise create a separately managed Hyperdrive that trusts it, then select it with "Use an existing Hyperdrive" when you start a new installation, or set VOID_PLATFORM_HYPERDRIVE_ID, VOID_PLATFORM_HYPERDRIVE_ORIGIN_HOST, and VOID_PLATFORM_HYPERDRIVE_ORIGIN_USER.', + ); + } +} + /** Make pg's current strict TLS behavior explicit without rewriting saved connection details. */ export function platformDatabaseClientUrl(databaseUrl: string): string { let url: URL; @@ -3490,9 +3513,19 @@ export function platformDatabaseClientUrl(databaseUrl: string): string { } catch { return databaseUrl; } - // Match pg's last-value-wins query parsing and respect explicit libpq compatibility. + if (url.protocol !== 'postgres:' && url.protocol !== 'postgresql:') { + return databaseUrl; + } + // Match pg's last-value-wins query parsing. libpq reads `sslrootcert=system` as the system + // trust store and requires verify-full with it, while pg would open it as a file path. Node's + // default CAs with hostname verification give pg the same policy. + if (url.searchParams.getAll('sslrootcert').at(-1) === 'system') { + url.searchParams.delete('sslrootcert'); + url.searchParams.set('sslmode', 'verify-full'); + return url.toString(); + } + // Respect explicit libpq compatibility. if ( - (url.protocol !== 'postgres:' && url.protocol !== 'postgresql:') || url.searchParams.getAll('sslmode').at(-1) !== 'require' || url.searchParams.getAll('uselibpqcompat').at(-1) === 'true' ) { @@ -4283,6 +4316,8 @@ type PlatformWorkerDeploymentOptions = Readonly<{ publishRoutes: (workerName: string, patterns: ReadonlyArray) => Promise; removeCustomDomains: () => Promise; retainNewWorker: () => Promise; + /** False uploads a new version even when the active one has identical input. */ + reuseMatchingVersion?: boolean; runner: typeof runPlatformWrangler; workerExisted: boolean; }>; @@ -4508,6 +4543,7 @@ export async function deployPlatformWorker( const nextTriggers = readTriggerConfigFromObject(nextTraffic.wranglerConfig); const contentHash = secrets === null ? platformWorkerUploadFingerprint(config, options.managedRoutes) : null; + const reuseMatchingVersion = options.reuseMatchingVersion !== false; let previousTriggers = readTriggerConfigFromObject(previousTraffic.wranglerConfig); try { const configPath = join(directory, 'wrangler.json'); @@ -4606,7 +4642,7 @@ export async function deployPlatformWorker( ); } }; - if (options.workerExisted && contentHash && options.readCloudflare) { + if (options.workerExisted && contentHash && reuseMatchingVersion && options.readCloudflare) { let candidate: | { deploymentId: string; @@ -4703,6 +4739,7 @@ export async function deployPlatformWorker( previousDeploymentId = previousDeployment.id; if ( contentHash && + reuseMatchingVersion && previous.contentHash === contentHash && platformWorkerUploadFingerprint(config, options.managedRoutes) === contentHash ) { @@ -5225,6 +5262,7 @@ async function runPlatformWranglerAtApiBase( } type ConditionalWorkerCreateState = { + assetSessionStarted: boolean; attempted: boolean; conflictStatus: number | null; created: boolean; @@ -5278,8 +5316,11 @@ async function startConditionalWorkerCreateProxy( throw new Error('platform: Cloudflare API base URL must use HTTP or HTTPS.'); } const basePath = upstreamBase.pathname.replace(/\/+$/, ''); - const expectedPath = `${basePath}/accounts/${encodeURIComponent(accountId)}/workers/scripts/${encodeURIComponent(workerName)}`; + const accountPath = `${basePath}/accounts/${encodeURIComponent(accountId)}`; + const expectedPath = `${accountPath}/workers/scripts/${encodeURIComponent(workerName)}`; + const assetUploadPath = `${accountPath}/workers/assets/upload`; const state: ConditionalWorkerCreateState = { + assetSessionStarted: false, attempted: false, conflictStatus: null, created: false, @@ -5313,9 +5354,27 @@ async function startConditionalWorkerCreateProxy( ).test(incomingUrl.pathname); const isReadOnly = incoming.method === 'GET' || incoming.method === 'HEAD' || incoming.method === 'OPTIONS'; + // A Worker with static assets must register its asset manifest and upload + // the missing files before the script PUT that references them. Neither + // step attaches anything to a Worker; only the guarded create does. + const isAssetUploadSession = + incoming.method === 'POST' && + incomingUrl.pathname === `${expectedPath}/assets-upload-session` && + incomingUrl.search === ''; + const isAssetUpload = + incoming.method === 'POST' && + state.assetSessionStarted && + ((incomingUrl.pathname === assetUploadPath && incomingUrl.search === '?base64=true') || + (incomingUrl.search === '' && + incomingUrl.pathname.startsWith(`${assetUploadPath}/`) && + /^[0-9a-f]{32}$/.test(incomingUrl.pathname.slice(assetUploadPath.length + 1)))); if ( (isTopLevelWorkerUpload && !isConditionalCreate) || - (!isReadOnly && !isConditionalCreate && !state.created) + (!isReadOnly && + !isConditionalCreate && + !isAssetUploadSession && + !isAssetUpload && + !state.created) ) { state.rejectedMutation = `${incoming.method ?? 'UNKNOWN'} ${incomingUrl.pathname}${ incomingUrl.pathname === expectedPath && !supportedCreateQuery @@ -5335,6 +5394,9 @@ async function startConditionalWorkerCreateProxy( state.attempted = true; headers['if-none-match'] = '*'; } + if (isAssetUploadSession) { + state.assetSessionStarted = true; + } const upstreamUrl = new URL( `${incomingUrl.pathname}${incomingUrl.search}`, upstreamBase.origin, diff --git a/packages/void/src/cli/platform-management.ts b/packages/void/src/cli/platform-management.ts index 7a22a3b48..faf226d94 100644 --- a/packages/void/src/cli/platform-management.ts +++ b/packages/void/src/cli/platform-management.ts @@ -798,7 +798,7 @@ export async function uninstallPlatform( ? 'Delete safely identifiable installer-owned data (--purge-data); retain Workers, R2, AI Gateway, and external PostgreSQL for manual cleanup.' : 'Retain installer-owned data; external PostgreSQL is never deleted.'; note( - `Disable all platform traffic through installation-owned routing storage.\nRetain DNS records, routes, and custom domains for explicit dashboard cleanup.\nDelete installer-owned Queues.\n${dataMessage}\n${ + `Disable all platform traffic through installation-owned routing storage.\nRetain DNS records, routes, and custom domains for explicit dashboard cleanup.\nDelete installer-owned Queues unless a retained Worker still uses them.\n${dataMessage}\n${ createdZone ? `Keep zone ${createdZone.name} for explicit manual cleanup.` : 'Never delete the adopted application zone.' @@ -930,6 +930,15 @@ export async function uninstallPlatform( resourceDeletionPriority(left, deletionPriority) - resourceDeletionPriority(right, deletionPriority), ); + // Uninstall retains Workers, and Cloudflare refuses to delete a Queue that + // a Worker still binds. Delete Queues only once none of this installation's + // Workers exist, so a retained Worker keeps its bindings intact. + const queuesInUse = + hasRoutingCheckpoint && + resources.some( + (resource) => resource.kind === 'queue' && shouldDeleteResource(resource, retainData), + ) && + (await hasLiveInstallationWorker(client, next)); for (const resource of resources) { if (resource.state !== 'ready') { continue; @@ -944,7 +953,7 @@ export async function uninstallPlatform( await writeLifecycleCheckpoint(client, next); continue; } - if (resource.kind === 'dns-record' && !zone) { + if ((resource.kind === 'dns-record' && !zone) || (resource.kind === 'queue' && queuesInUse)) { next = updateResourceState(next, resource.key, 'retained'); await writeLifecycleCheckpoint(client, next); continue; @@ -1116,6 +1125,26 @@ function shouldDeleteResource(resource: InstallationResource, retainData: boolea return !(retainData && DATA_RESOURCE_KINDS.has(resource.kind)); } +async function hasLiveInstallationWorker( + client: Pick, + manifest: PlatformInstallationManifest, +): Promise { + const names = manifest.deployment.resources; + const installationWorkers = new Set([ + names.apiWorker, + names.proxyWorker, + names.emailGatewayWorker, + names.tailWorker, + names.dispatchWorker, + ...manifest.resources + .filter((resource) => resource.kind === 'worker') + .map((resource) => resource.name), + ]); + return (await client.listWorkerNames(manifest.account.id)).some((name) => + installationWorkers.has(name), + ); +} + function resourceDeletionPriority( resource: InstallationResource, priorities: Readonly>, diff --git a/packages/void/test/unit/platform-cloudflare.test.ts b/packages/void/test/unit/platform-cloudflare.test.ts index dc718d4d1..c88e5b92c 100644 --- a/packages/void/test/unit/platform-cloudflare.test.ts +++ b/packages/void/test/unit/platform-cloudflare.test.ts @@ -282,8 +282,14 @@ describe('platform Cloudflare client', () => { expect(methods).toEqual(['POST', 'GET']); }); - it('preserves supported PostgreSQL TLS modes in Hyperdrive requests', async () => { - let payload: unknown; + it.each([ + ['?sslmode=verify-full', { sslmode: 'require' }], + ['?sslmode=verify-full&sslrootcert=system', { sslmode: 'require' }], + ['?sslmode=verify-ca', { sslmode: 'require' }], + ['?sslmode=require', { sslmode: 'require' }], + ['', undefined], + ])('sends a Hyperdrive TLS mode Cloudflare accepts for %j', async (query, mtls) => { + let payload: Record = {}; const client = new PlatformCloudflareClient('token', { fetcher: async (_input, init) => { payload = JSON.parse(String(init?.body)); @@ -294,16 +300,38 @@ describe('platform Cloudflare client', () => { await client.createHyperdrive( 'account', 'void-db', - 'postgresql://user:secret@db.example.com/void?sslmode=verify-full', + `postgresql://user:secret@db.example.com/void${query}`, ); - expect(payload).toMatchObject({ - mtls: { sslmode: 'verify-full' }, - caching: { disabled: true }, - }); - expect(() => - parsePostgresConnectionString('postgresql://user:secret@db.example.com/void?sslmode=prefer'), - ).toThrow('Unsupported sslmode'); + expect(payload).toMatchObject({ caching: { disabled: true } }); + expect(payload.mtls).toEqual(mtls); + expect('mtls' in payload).toBe(mtls !== undefined); + }); + + it('keeps unsupported PostgreSQL TLS modes out of Hyperdrive requests', () => { + for (const sslmode of ['prefer', 'disable', 'allow']) { + expect(() => + parsePostgresConnectionString( + `postgresql://user:secret@db.example.com/void?sslmode=${sslmode}`, + ), + ).toThrow('Unsupported sslmode'); + } + }); + + it('fingerprints a Hyperdrive origin independently of the URL TLS mode', () => { + const base = 'postgresql://user:secret@db.example.com:5432/void'; + expect( + hyperdriveOriginConfigHash( + hyperdriveOriginFromConnectionString(`${base}?sslmode=verify-full`), + ), + ).toBe( + hyperdriveOriginConfigHash(hyperdriveOriginFromConnectionString(`${base}?sslmode=require`)), + ); + expect( + hyperdriveOriginConfigHash( + hyperdriveOriginFromConnectionString(`${base}?sslmode=verify-full&sslrootcert=system`), + ), + ).toBe(hyperdriveOriginConfigHash(hyperdriveOriginFromConnectionString(base))); }); it('reads and fingerprints a Hyperdrive origin without its password', async () => { diff --git a/packages/void/test/unit/platform-database-ssl.test.ts b/packages/void/test/unit/platform-database-ssl.test.ts index 9fb26e9fd..7e4111f7b 100644 --- a/packages/void/test/unit/platform-database-ssl.test.ts +++ b/packages/void/test/unit/platform-database-ssl.test.ts @@ -79,6 +79,49 @@ describe('platform PostgreSQL SSL mode', () => { expect(warning).not.toHaveBeenCalled(); }); + it.each([ + ['verify-full', '?sslmode=verify-full&sslrootcert=system'], + ['require', '?sslrootcert=system&sslmode=require'], + ['no sslmode', '?sslrootcert=system'], + ['libpq compatibility', '?sslmode=verify-full&sslrootcert=system&uselibpqcompat=true'], + ['a repeated root certificate', '?sslrootcert=%2Ftmp%2Froot.pem&sslrootcert=system'], + ])( + 'uses the system trust store with full verification for sslrootcert=system with %s', + (_name, query) => { + const original = `postgresql://owner:p%40ss@db.example.com:5432/postgres${query}&application_name=void`; + const actual = new URL(platformDatabaseClientUrl(original)); + expect(actual.searchParams.getAll('sslrootcert')).toEqual([]); + expect(actual.searchParams.getAll('sslmode')).toEqual(['verify-full']); + const expected = new URL(original); + for (const name of ['sslrootcert', 'sslmode']) { + actual.searchParams.delete(name); + expected.searchParams.delete(name); + } + expect(actual.toString()).toBe(expected.toString()); + }, + ); + + it.each([ + 'postgresql://owner:pw@db/platform?sslmode=verify-full&sslrootcert=%2Fetc%2Fssl%2Froot.pem', + 'postgresql://owner:pw@db/platform?sslmode=verify-full&sslrootcert=system&sslrootcert=%2Froot.pem', + 'postgresql://owner:pw@db/platform?sslmode=verify-full&sslrootcert=System', + ])('leaves other root certificate settings unchanged: %s', (url) => { + expect(platformDatabaseClientUrl(url)).toBe(url); + }); + + it('connects to a provider URL with sslrootcert=system using Node default CAs', async () => { + const warning = vi.spyOn(process, 'emitWarning').mockImplementation(() => {}); + const { Client } = await vi.importActual('pg'); + // Constructing a real pg client parses SSL options, but does not open a connection. + const client = new Client({ + connectionString: platformDatabaseClientUrl( + 'postgresql://owner:pw@db.example.com:5432/postgres?sslmode=verify-full&sslrootcert=system', + ), + }); + expect(client.ssl).toEqual({}); // Node TLS verification defaults remain enabled. + expect(warning).not.toHaveBeenCalled(); + }); + it.each([ ['database claim', claimPlatformDatabase], ['lifecycle lock', acquirePlatformDatabaseLifecycleLock], @@ -100,4 +143,18 @@ describe('platform PostgreSQL SSL mode', () => { expect(process.env.DATABASE_URL).toBe(original); expect(resolvePlatformInstallDatabaseUrl(checkpoint)).toBe(original); }); + + it('keeps sslrootcert=system in the saved URL while the claim client uses Node default CAs', async () => { + const original = + 'postgresql://owner:pw@db.example.com/postgres?sslmode=verify-full&sslrootcert=system'; + const checkpoint = { databaseUrl: original, databaseClaimState: 'claimed' }; + await expect( + claimPlatformDatabase(checkpoint.databaseUrl, 'installation', 'nonce'), + ).rejects.toThrow('Stopped before network access.'); + expect(mocks.pool).toHaveBeenCalledWith({ + connectionString: 'postgresql://owner:pw@db.example.com/postgres?sslmode=verify-full', + max: 1, + }); + expect(checkpoint.databaseUrl).toBe(original); + }); }); diff --git a/packages/void/test/unit/platform-install-cutover.test.ts b/packages/void/test/unit/platform-install-cutover.test.ts new file mode 100644 index 000000000..74f0512a4 --- /dev/null +++ b/packages/void/test/unit/platform-install-cutover.test.ts @@ -0,0 +1,447 @@ +import { randomUUID } from 'node:crypto'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { PlatformInstallationManifest } from '@void/platform'; +import { afterEach, beforeEach, expect, it, vi } from 'vite-plus/test'; +import { hyperdriveOriginFromConnectionString } from '../../src/cli/platform-cloudflare.ts'; +import { + createPlatformInstallationSecrets, + installPlatform, +} from '../../src/cli/platform-installer.ts'; +import { createPlatformInstallPlan } from '../../src/cli/platform-plan.ts'; +import { listInstallationManifests } from '../../src/cli/platform-registry.ts'; +import type { RunWrangler } from '../../src/cli/provision.ts'; + +// Runs the real Worker deploy, cutover checkpoint, and pre-traffic verification +// against a stateful in-memory Cloudflare account. Only the Wrangler process is +// replaced; the guarded create still goes through the conditional-create proxy. +const wrangler = vi.hoisted(() => ({ run: null as RunWrangler | null })); +vi.mock('../../src/cli/provision.ts', async (importOriginal) => ({ + ...(await importOriginal()), + createDefaultRunWrangler: () => (args: Array, opts: Parameters[1]) => + wrangler.run!(args, opts), +})); + +const TEST_PLATFORM_JWT_SECRET = 'test-only-platform-jwt-secret-material'; +const TEST_PLATFORM_PROJECT_SECRET_KEY = Buffer.alloc(32, 5).toString('base64'); +const directories: Array = []; +const servers: Array = []; + +beforeEach(() => { + process.env.VOID_PLATFORM_RECOVERY_KEY = Buffer.alloc(32, 7).toString('base64'); + const directory = mkdtempSync(join(tmpdir(), 'void-platform-install-cutover-')); + directories.push(directory); + process.env.VOID_PLATFORM_REGISTRY_DIR = directory; +}); + +afterEach(async () => { + wrangler.run = null; + delete process.env.VOID_PLATFORM_RECOVERY_KEY; + delete process.env.VOID_PLATFORM_REGISTRY_DIR; + for (const server of servers.splice(0)) { + await new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections(); + }); + } + for (const directory of directories.splice(0)) { + rmSync(directory, { force: true, recursive: true }); + } +}); + +type FakeVersion = { + annotations: Record; + id: string; + resources: { + bindings: Array<{ name: string; text: string; type: string }>; + script_runtime?: { migration_tag: string }; + }; +}; +type FakeDeployment = { + created_on: string; + id: string; + versions: Array<{ percentage: number; version_id: string }>; +}; + +async function createFakeCloudflare() { + const upstream = createServer((request, response) => { + request.resume(); + request.on('end', () => { + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end('{"success":true,"errors":[],"result":{}}'); + }); + }); + servers.push(upstream); + await new Promise((resolve) => upstream.listen(0, '127.0.0.1', resolve)); + const apiBaseUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}/client/v4`; + const workers = new Map< + string, + { deployments: Array; versions: Map } + >(); + const kv = new Map(); + const r2 = new Map(); + const named = new Map>(); + const commands: Array<{ args: Array; worker: string | null }> = []; + let clock = Date.parse('2026-10-01T00:00:00.000Z'); + let failBlockedCreate: string | null = null; + let failUpload: string | null = null; + + const flag = (args: Array, ...names: Array) => { + const index = args.findIndex((arg) => names.includes(arg)); + return index === -1 ? undefined : args[index + 1]; + }; + const configOf = (args: Array): Record | null => { + const path = flag(args, '--config', '-c'); + return path ? (JSON.parse(readFileSync(path, 'utf8')) as Record) : null; + }; + const workerOf = (args: Array) => + flag(args, '--name') ?? (configOf(args)?.name as string | undefined) ?? null; + const ok = (stdout = '') => ({ status: 0, stderr: '', stdout }); + const failed = (stderr: string) => ({ status: 1, stderr, stdout: '' }); + const storeVersion = (name: string, args: Array): FakeVersion => { + const config = configOf(args)!; + const vars = (config.vars ?? {}) as Record; + const migrations = Array.isArray(config.migrations) ? config.migrations : []; + const tag = (migrations.at(-1) as { tag?: string } | undefined)?.tag; + const version: FakeVersion = { + annotations: { 'workers/message': flag(args, '--message') ?? '' }, + id: randomUUID(), + resources: { + bindings: [ + { + name: 'PLATFORM_OWNERSHIP_MARKER', + text: vars.PLATFORM_OWNERSHIP_MARKER ?? '', + type: 'plain_text', + }, + ], + ...(tag ? { script_runtime: { migration_tag: tag } } : {}), + }, + }; + const worker = workers.get(name) ?? { deployments: [], versions: new Map() }; + worker.versions.set(version.id, version); + workers.set(name, worker); + return version; + }; + const activate = (name: string, versionId: string) => { + workers.get(name)!.deployments.unshift({ + created_on: new Date((clock += 1000)).toISOString(), + id: randomUUID(), + versions: [{ percentage: 100, version_id: versionId }], + }); + }; + + wrangler.run = async (args, opts) => { + const worker = workerOf(args); + commands.push({ args, worker }); + const command = `${args[0]} ${args[1] ?? ''}`.trim(); + if (args[0] === 'deploy') { + const base = `${opts.apiBaseUrl}/accounts/${opts.accountId}/workers/scripts/${worker}`; + if (failBlockedCreate === worker) { + failBlockedCreate = null; + await fetch(`${base}/unexpected-mutation`, { method: 'POST' }); + return failed('Mutation blocked until conditional Worker creation succeeds'); + } + const created = await fetch(`${base}?excludeScript=true`, { method: 'PUT', body: '{}' }); + if (!created.ok) { + return failed(`create failed (${created.status})`); + } + const version = storeVersion(worker!, args); + activate(worker!, version.id); + return ok(`Uploaded ${worker}\nCurrent Version ID: ${version.id}`); + } + if (command === 'versions upload') { + if (failUpload === worker) { + failUpload = null; + return failed('upload failed'); + } + const version = storeVersion(worker!, args); + return ok(`Worker Version ID: ${version.id}`); + } + if (command === 'versions deploy') { + const targets = args.slice(2).filter((arg) => /@\d+$/.test(arg)); + const entry = workers.get(worker!)!; + entry.deployments.unshift({ + created_on: new Date((clock += 1000)).toISOString(), + id: randomUUID(), + versions: targets.map((target) => { + const [versionId, percentage] = target.split('@'); + return { percentage: Number(percentage), version_id: versionId! }; + }), + }); + return ok(); + } + if (command === 'deployments list') { + const entry = workers.get(worker!); + return entry ? ok(JSON.stringify(entry.deployments)) : failed('Worker not found'); + } + if (command === 'deployments status') { + const latest = workers.get(worker!)?.deployments[0]; + return latest ? ok(JSON.stringify({ versions: latest.versions })) : failed('not found'); + } + if (command === 'versions view') { + const version = workers.get(worker!)?.versions.get(args[2]!); + return version ? ok(JSON.stringify(version)) : failed('version not found'); + } + if (command === 'triggers deploy') { + return ok(); + } + throw new Error(`Unexpected Wrangler command: ${args.join(' ')}`); + }; + + const create = + (kind: string) => + async (_account: string, name: string, ..._rest: Array) => { + const resources = named.get(kind) ?? new Map(); + named.set(kind, resources); + // AI Gateways are addressed by name. + const id = + resources.get(name) ?? (kind === 'ai-gateway' ? name : `${kind}-${resources.size}`); + resources.set(name, id); + return { + id, + name, + ...(kind === 'r2' ? { fingerprint: '2026-10-01T00:00:00.000Z' } : {}), + }; + }; + const list = (kind: string, name?: string) => + [...(named.get(kind) ?? new Map())] + .filter(([entry]) => name === undefined || entry === name) + .map(([entry, id]) => ({ + id, + name: entry, + ...(kind === 'r2' ? { fingerprint: '2026-10-01T00:00:00.000Z' } : {}), + })); + const plainTextBindings = async (_account: string, name: string) => { + const entry = workers.get(name); + const active = entry?.deployments[0]?.versions[0]?.version_id; + const version = active ? entry!.versions.get(active) : undefined; + return Object.fromEntries( + (version?.resources.bindings ?? []).map((binding) => [binding.name, binding.text]), + ); + }; + + const client = { + apiBaseUrl, + createAiGateway: create('ai-gateway'), + createDispatchNamespace: create('dispatch'), + createDnsRecord: async (): Promise => { + throw new Error('No DNS expected'); + }, + createHyperdrive: create('hyperdrive'), + createKvNamespace: create('kv'), + createQueue: create('queue'), + createR2Bucket: create('r2'), + createZone: async (): Promise => { + throw new Error('No zone expected'); + }, + deleteKvValue: async (_account: string, namespace: string, key: string) => { + kv.delete(`${namespace}/${key}`); + }, + disableHyperdriveCaching: async () => {}, + getHyperdriveConfig: async (_account: string, id: string) => ({ + cachingDisabled: true, + id, + name: list('hyperdrive').find((entry) => entry.id === id)!.name, + origin: hyperdriveOriginFromConnectionString(DATABASE_URL), + }), + getWorkerPlainTextBindings: plainTextBindings, + listWorkerDomains: async () => [], + listWorkerNames: async () => [...workers.keys()], + listWorkerRoutes: async () => [], + listWorkerServiceRoutes: async () => [], + publishWorkerCustomDomainsSafely: async () => {}, + publishWorkerRoutesSafely: async () => {}, + putKvValue: async (_account: string, namespace: string, key: string, value: string) => { + kv.set(`${namespace}/${key}`, value); + }, + putR2Object: async (_account: string, bucket: string, key: string, value: string) => { + r2.set(`${bucket}/${key}`, value); + }, + removeRoutes: async () => {}, + }; + const planningClient = { + findZone: async (): Promise => { + throw new Error('No zone expected'); + }, + findZoneForHostname: async () => null, + getKvValue: async (_account: string, namespace: string, key: string) => + kv.get(`${namespace}/${key}`) ?? null, + getR2Object: async (_account: string, bucket: string, key: string) => + r2.get(`${bucket}/${key}`) ?? null, + getWorkerPlainTextBindings: plainTextBindings, + getWorkersSubdomain: async () => 'workers-subdomain', + hasActiveCertificateForHostname: async () => true, + listAccounts: async () => [{ id: 'account', name: 'Account' }], + listAiGateways: async () => list('ai-gateway'), + listDispatchNamespaces: async () => list('dispatch'), + listDnsRecords: async () => [], + listHyperdriveConfigs: async () => list('hyperdrive'), + listKvNamespaces: async (_account: string, title?: string) => list('kv', title), + listQueues: async (_account: string, name: string) => list('queue', name), + listR2Buckets: async () => list('r2'), + listWorkerDomains: async () => [], + listWorkerNames: async () => [...workers.keys()], + listWorkerRoutes: async () => [], + }; + return { + client, + commands, + failBlockedCreate: (worker: string) => { + failBlockedCreate = worker; + }, + failUpload: (worker: string) => { + failUpload = worker; + }, + kv, + planningClient, + }; +} + +const DATABASE_URL = 'postgres://user:password@db.example.com/testing'; + +function installationSecrets() { + return createPlatformInstallationSecrets({ + bootstrapGitHubId: '583231', + bootstrapGitHubLogin: 'octocat', + cloudflareApiToken: 'test-token', + databaseUrl: DATABASE_URL, + githubClientId: 'id', + githubClientSecret: 'secret', + jwtSecret: TEST_PLATFORM_JWT_SECRET, + projectSecretKey: TEST_PLATFORM_PROJECT_SECRET_KEY, + r2AccessKeyId: 'id', + r2SecretAccessKey: 'secret', + }); +} + +function planInstallation( + cloud: Awaited>, + existing: PlatformInstallationManifest | null, +) { + return createPlatformInstallPlan( + cloud.planningClient, + { + accountId: 'account', + applicationDomain: '', + controlPlaneDomain: '', + dedicatedZone: false, + displayName: 'Testing', + installationSlug: 'testing', + workersDev: true, + zoneName: '', + }, + existing, + ); +} + +async function runInstall( + cloud: Awaited>, + existing: PlatformInstallationManifest | null, +) { + const plan = await planInstallation(cloud, existing); + return installPlatform(plan, installationSecrets(), existing, { + acquireDatabaseLifecycleLock: async () => + Object.assign(async () => {}, { + prepareSandboxDrain: async () => ({ + admissionProtocol: 3 as const, + generation: 'generation-1', + mirrorValue: JSON.stringify({ + completedAt: '2026-10-01T00:00:00.000Z', + generation: 'generation-1', + startedAt: '2026-10-01T00:00:00.000Z', + state: 'complete', + updatedAt: '2026-10-01T00:00:00.000Z', + version: 1, + }), + state: 'complete' as const, + }), + }), + claimDatabase: async () => {}, + client: cloud.client, + migrateDatabase: async () => {}, + revalidateBeforeWorkerDeploy: async () => {}, + verifyHealth: async () => {}, + }); +} + +function currentManifest(): PlatformInstallationManifest { + return listInstallationManifests(process.env.VOID_PLATFORM_REGISTRY_DIR!)[0]!; +} + +function workerStepKeys(manifest: PlatformInstallationManifest) { + return manifest.steps.map((step) => step.key).filter((key) => key.startsWith('worker-')); +} + +const WORKER_KEYS = ['api', 'proxy', 'emailGateway', 'tail', 'dispatch']; + +function stagedKeys(manifest: PlatformInstallationManifest, generation: number) { + const prefix = `worker-cutover:${generation}:staged:`; + return workerStepKeys(manifest) + .filter((key) => key.startsWith(prefix)) + .map((key) => key.slice(prefix.length)) + .sort(); +} + +it('stages a fresh immutable version of every Worker before enabling a fresh install', async () => { + const cloud = await createFakeCloudflare(); + + const result = await runInstall(cloud, null); + + expect(result.manifest.status).toBe('installed'); + expect(stagedKeys(result.manifest, 1)).toEqual([...WORKER_KEYS].sort()); + expect(stagedKeys(result.manifest, 2)).toEqual([...WORKER_KEYS].sort()); + expect(workerStepKeys(result.manifest)).toContain('worker-cutover:2:committed'); + // The tail Worker config is identical in both generations, yet it is still restaged. + const tail = result.manifest.deployment.resources.tailWorker; + expect( + cloud.commands + .filter((command) => command.worker === tail) + .map((command) => command.args.slice(0, 2).join(' ')) + .filter((command) => command.startsWith('deploy ') || command === 'versions upload'), + ).toEqual(['deploy --config', 'versions upload']); +}); + +it('enables traffic when resuming after the first Worker create was refused', async () => { + const cloud = await createFakeCloudflare(); + const plan = await planInstallation(cloud, null); + cloud.failBlockedCreate(plan.deployment.resources.apiWorker); + + await expect(runInstall(cloud, null)).rejects.toThrow('unexpected mutation'); + const failed = currentManifest(); + expect(failed.status).toBe('failed'); + expect(workerStepKeys(failed)).toEqual([]); + + const resumed = await runInstall(cloud, failed); + + expect(resumed.manifest.status).toBe('installed'); + expect(stagedKeys(resumed.manifest, 1)).toEqual([...WORKER_KEYS].sort()); + expect(stagedKeys(resumed.manifest, 2)).toEqual([...WORKER_KEYS].sort()); + expect(workerStepKeys(resumed.manifest)).toContain('worker-cutover:2:committed'); +}); + +it('retries a restored enabling generation with every Worker restaged', async () => { + const cloud = await createFakeCloudflare(); + const plan = await planInstallation(cloud, null); + // The tail Worker is created with a guarded deploy, so its first version + // upload is the enabling generation. Failing it leaves that generation restored. + cloud.failUpload(plan.deployment.resources.tailWorker); + + await expect(runInstall(cloud, null)).rejects.toThrow('upload failed'); + const failed = currentManifest(); + expect(failed.status).toBe('failed'); + expect(workerStepKeys(failed)).toEqual( + expect.arrayContaining(['worker-cutover:1:committed', 'worker-cutover:2:restored']), + ); + expect(stagedKeys(failed, 2)).not.toContain('tail'); + + const retried = await runInstall(cloud, failed); + + expect(retried.manifest.status).toBe('installed'); + // The staging generation still reuses an unchanged Worker version. + expect(stagedKeys(retried.manifest, 3)).not.toContain('tail'); + expect(stagedKeys(retried.manifest, 4)).toEqual([...WORKER_KEYS].sort()); + expect(workerStepKeys(retried.manifest)).toContain('worker-cutover:4:committed'); +}); diff --git a/packages/void/test/unit/platform-installer.test.ts b/packages/void/test/unit/platform-installer.test.ts index 4d13a3c4a..dae984566 100644 --- a/packages/void/test/unit/platform-installer.test.ts +++ b/packages/void/test/unit/platform-installer.test.ts @@ -31,6 +31,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test' import { hyperdriveOriginConfigHash, hyperdriveOriginFromConnectionString, + PlatformCloudflareClient, } from '../../src/cli/platform-cloudflare.ts'; import { acquirePlatformDatabaseLifecycleLockConnection, @@ -70,6 +71,7 @@ import { withoutCompletedPlatformWorkerMigrations, withoutPlatformWorkerTrafficAttachments, } from '../../src/cli/platform-installer.ts'; +import { resolvePlatformInstallDatabaseUrl } from '../../src/cli/platform-lifecycle.ts'; import { createPlatformInstallPlan, platformProvisionIntentHash, @@ -78,6 +80,7 @@ import { listInstallationManifests, promoteInstallationSecrets, readInstallationRecoverySecrets, + readPendingInstallationSecrets, writeInstallationManifest, writePendingInstallationSecrets, } from '../../src/cli/platform-registry.ts'; @@ -1218,6 +1221,289 @@ describe('platform installer', () => { } }); + it("forwards this Worker's asset upload session and uploads before the guarded create", async () => { + const hash = '0123456789abcdef0123456789abcdef'; + const requests: Array<{ + authorization: string | undefined; + ifNoneMatch: string | undefined; + request: string; + }> = []; + const upstream = createServer((request, response) => { + request.resume(); + request.on('end', () => { + requests.push({ + authorization: request.headers.authorization, + ifNoneMatch: request.headers['if-none-match'], + request: `${request.method} ${request.url}`, + }); + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end('{"success":true,"result":{"jwt":"token"}}'); + }); + }); + const upstreamOrigin = await listen(upstream); + try { + await expect( + withConditionalPlatformWorkerCreate( + 'account', + 'void-api', + async (apiBaseUrl) => { + // The order the bundled uploader uses for a new Worker with static assets. + const sequence: Array<[string, string, string]> = [ + ['GET', '/accounts/account/workers/services/void-api', 'secret-token'], + ['GET', '/accounts/account/workers/scripts/void-api/deployments', 'secret-token'], + [ + 'POST', + '/accounts/account/workers/scripts/void-api/assets-upload-session', + 'secret-token', + ], + ['POST', '/accounts/account/workers/assets/upload?base64=true', 'session-jwt'], + ['POST', `/accounts/account/workers/assets/upload/${hash}`, 'session-jwt'], + ['GET', '/accounts/account/workers/scripts/void-api/settings', 'secret-token'], + [ + 'PUT', + '/accounts/account/workers/scripts/void-api?excludeScript=true&bindings_inherit=strict', + 'secret-token', + ], + ['POST', '/accounts/account/workers/scripts/void-api/subdomain', 'secret-token'], + ]; + for (const [method, path, token] of sequence) { + const response = await fetch(`${apiBaseUrl}${path}`, { + ...(method === 'GET' ? {} : { body: 'payload' }), + headers: { Authorization: `Bearer ${token}` }, + method, + }); + expect(response.status, `${method} ${path}`).toBe(200); + } + return 'created'; + }, + `${upstreamOrigin}/client/v4`, + ), + ).resolves.toBe('created'); + expect(requests).toEqual([ + { + authorization: 'Bearer secret-token', + ifNoneMatch: undefined, + request: 'GET /client/v4/accounts/account/workers/services/void-api', + }, + { + authorization: 'Bearer secret-token', + ifNoneMatch: undefined, + request: 'GET /client/v4/accounts/account/workers/scripts/void-api/deployments', + }, + { + authorization: 'Bearer secret-token', + ifNoneMatch: undefined, + request: + 'POST /client/v4/accounts/account/workers/scripts/void-api/assets-upload-session', + }, + { + authorization: 'Bearer session-jwt', + ifNoneMatch: undefined, + request: 'POST /client/v4/accounts/account/workers/assets/upload?base64=true', + }, + { + authorization: 'Bearer session-jwt', + ifNoneMatch: undefined, + request: `POST /client/v4/accounts/account/workers/assets/upload/${hash}`, + }, + { + authorization: 'Bearer secret-token', + ifNoneMatch: undefined, + request: 'GET /client/v4/accounts/account/workers/scripts/void-api/settings', + }, + { + authorization: 'Bearer secret-token', + ifNoneMatch: '*', + request: + 'PUT /client/v4/accounts/account/workers/scripts/void-api?excludeScript=true&bindings_inherit=strict', + }, + { + authorization: 'Bearer secret-token', + ifNoneMatch: undefined, + request: 'POST /client/v4/accounts/account/workers/scripts/void-api/subdomain', + }, + ]); + } finally { + await close(upstream); + } + }); + + const assetSession = [ + 'POST', + '/accounts/account/workers/scripts/void-api/assets-upload-session', + ] as const; + it.each<{ + name: string; + before: ReadonlyArray; + blocked: readonly [string, string]; + }>([ + { + name: 'a session for another Worker', + before: [], + blocked: ['POST', '/accounts/account/workers/scripts/other-worker/assets-upload-session'], + }, + { + name: 'a session with a query', + before: [], + blocked: ['POST', '/accounts/account/workers/scripts/void-api/assets-upload-session?x=1'], + }, + { + name: 'a PUT on the session path', + before: [], + blocked: ['PUT', '/accounts/account/workers/scripts/void-api/assets-upload-session'], + }, + { + name: 'a DELETE on the session path', + before: [], + blocked: ['DELETE', '/accounts/account/workers/scripts/void-api/assets-upload-session'], + }, + { + name: 'a dispatch namespace session', + before: [], + blocked: [ + 'POST', + '/accounts/account/workers/dispatch/namespaces/ns/scripts/void-api/assets-upload-session', + ], + }, + { + name: 'a session under another account', + before: [], + blocked: ['POST', '/accounts/other/workers/scripts/void-api/assets-upload-session'], + }, + { + name: 'an upload before any session', + before: [], + blocked: ['POST', '/accounts/account/workers/assets/upload?base64=true'], + }, + { + name: 'an upload with base64=false', + before: [assetSession], + blocked: ['POST', '/accounts/account/workers/assets/upload?base64=false'], + }, + { + name: 'an upload with an extra query parameter', + before: [assetSession], + blocked: ['POST', '/accounts/account/workers/assets/upload?base64=true&x=1'], + }, + { + name: 'an upload with a short hash', + before: [assetSession], + blocked: ['POST', `/accounts/account/workers/assets/upload/${'a'.repeat(31)}`], + }, + { + name: 'an upload with an uppercase hash', + before: [assetSession], + blocked: ['POST', `/accounts/account/workers/assets/upload/${'A'.repeat(32)}`], + }, + { + name: 'an upload with a nested path', + before: [assetSession], + blocked: ['POST', '/accounts/account/workers/assets/upload/a/b'], + }, + { + name: 'an upload under another account', + before: [assetSession], + blocked: ['POST', '/accounts/other/workers/assets/upload?base64=true'], + }, + { + name: 'a version upload after a session', + before: [assetSession], + blocked: ['POST', '/accounts/account/workers/scripts/void-api/versions'], + }, + { + name: 'a subdomain change after a session', + before: [assetSession], + blocked: ['POST', '/accounts/account/workers/scripts/void-api/subdomain'], + }, + { + name: 'an unrelated account mutation after a session', + before: [assetSession], + blocked: ['POST', '/accounts/account/storage/kv/namespaces'], + }, + { + name: 'another Worker upload after a session', + before: [assetSession], + blocked: [ + 'PUT', + '/accounts/account/workers/scripts/other-worker?excludeScript=true&bindings_inherit=strict', + ], + }, + { + name: 'an unconditional create after a session', + before: [assetSession], + blocked: ['PUT', '/accounts/account/workers/scripts/void-api?excludeScript=false'], + }, + ])('blocks $name before the guarded create', async ({ before, blocked }) => { + let forwarded = 0; + const upstream = createServer((request, response) => { + forwarded++; + request.resume(); + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end('{"success":true,"result":{"jwt":"token"}}'); + }); + const origin = await listen(upstream); + try { + const result = withConditionalPlatformWorkerCreate( + 'account', + 'void-api', + async (base) => { + for (const [method, path] of before) { + const response = await fetch(`${base}${path}`, { body: 'payload', method }); + expect(response.status).toBe(200); + } + const [method, path] = blocked; + const response = await fetch(`${base}${path}`, { body: 'payload', method }); + expect(response.status).toBe(409); + }, + `${origin}/client/v4`, + ); + await expect(result).rejects.toThrow(`unexpected mutation ${blocked[0]}`); + expect(forwarded).toBe(before.length); + } finally { + await close(upstream); + } + }); + + it('reports a concurrent create after assets were uploaded', async () => { + const requests: Array = []; + const upstream = createServer((request, response) => { + request.resume(); + requests.push(`${request.method} ${request.url}`); + response.writeHead(request.method === 'PUT' ? 412 : 200, { + 'Content-Type': 'application/json', + }); + response.end( + request.method === 'PUT' + ? '{"success":false,"errors":[{"message":"already exists"}]}' + : '{"success":true,"result":{"jwt":"token"}}', + ); + }); + const origin = await listen(upstream); + try { + const failure = withConditionalPlatformWorkerCreate( + 'account', + 'void-api', + async (base) => { + for (const path of [ + '/accounts/account/workers/scripts/void-api/assets-upload-session', + '/accounts/account/workers/assets/upload?base64=true', + ]) { + await fetch(`${base}${path}`, { body: 'payload', method: 'POST' }); + } + await fetch( + `${base}/accounts/account/workers/scripts/void-api?excludeScript=true&bindings_inherit=strict`, + { body: 'worker bundle', method: 'PUT' }, + ); + }, + `${origin}/client/v4`, + ); + await expect(failure).rejects.toThrow('created concurrently (HTTP 412)'); + expect(requests.filter((request) => request.startsWith('PUT '))).toHaveLength(1); + } finally { + await close(upstream); + } + }); + it('accepts only an installer deployment with the expected predecessor', () => { const ours = { id: 'deployment-ours', @@ -3761,6 +4047,449 @@ describe('platform installer', () => { expect(listInstallationManifests(directory)[0]).toMatchObject({ status: 'failed' }); }); + it('rejects a database URL Hyperdrive cannot use before claiming the database', async () => { + const directory = mkdtempSync(join(tmpdir(), 'void-platform-preclaim-url-test-')); + directories.push(directory); + process.env.VOID_PLATFORM_REGISTRY_DIR = directory; + const plan = await createPlatformInstallPlan( + planningClient(), + { + accountId: 'account', + applicationDomain: 'apps.example.com', + controlPlaneDomain: '', + dedicatedZone: false, + displayName: 'Example', + installationSlug: 'example', + zoneName: 'example.com', + }, + null, + ); + expect(plan.actions.find((action) => action.key === 'hyperdrive')?.action).toBe('create'); + let claims = 0; + let locks = 0; + const unused = async () => ({ id: 'unused', name: 'unused' }); + + await expect( + installPlatform( + plan, + createPlatformInstallationSecrets({ + bootstrapGitHubId: '583231', + bootstrapGitHubLogin: 'octocat', + cloudflareApiToken: 'cf-token', + databaseUrl: 'postgres://user:password@db.example.com/void?sslmode=disable', + githubClientId: 'github-id', + githubClientSecret: 'github-secret', + jwtSecret: TEST_PLATFORM_JWT_SECRET, + projectSecretKey: TEST_PLATFORM_PROJECT_SECRET_KEY, + r2AccessKeyId: 'r2-id', + r2SecretAccessKey: 'r2-secret', + }), + null, + { + acquireDatabaseLifecycleLock: async () => { + locks++; + return acquireDatabaseLifecycleLock(); + }, + claimDatabase: async () => { + claims++; + }, + client: { + createAiGateway: unused, + createDispatchNamespace: unused, + createDnsRecord: async () => ({ + content: '100::', + id: 'unused', + name: 'unused', + proxied: true, + type: 'AAAA', + }), + createHyperdrive: unused, + createKvNamespace: unused, + createQueue: unused, + createR2Bucket: unused, + createZone: async () => ({ + id: 'unused', + name: 'unused', + nameServers: [], + status: 'active', + }), + putKvValue: async () => {}, + putR2Object: async () => {}, + }, + revalidateBeforeWorkerDeploy: async () => {}, + }, + ), + ).rejects.toThrow('Unsupported sslmode'); + + expect(claims).toBe(0); + expect(locks).toBe(0); + const manifest = listInstallationManifests(directory)[0]!; + expect(manifest).toMatchObject({ resources: [], status: 'planned' }); + const checkpoint = readPendingInstallationSecrets(manifest); + expect(checkpoint?.databaseClaimState).toBeUndefined(); + // The database is still unbound, so the operator can resume with a corrected URL. + const corrected = 'postgres://user:password@db.example.com/void?sslmode=require'; + process.env.VOID_PLATFORM_DATABASE_URL = corrected; + try { + expect(resolvePlatformInstallDatabaseUrl(checkpoint, manifest)).toBe(corrected); + } finally { + delete process.env.VOID_PLATFORM_DATABASE_URL; + } + }); + + it.each([ + 'postgres://user:password@db.example.com/void?sslmode=verify-full&sslrootcert=/etc/ssl/private-ca.pem', + 'postgres://user:password@db.example.com/void?sslmode=verify-full&sslrootcert=system&sslrootcert=/etc/ssl/private-ca.pem', + ])( + 'rejects a private certificate authority for a Void-created Hyperdrive before claiming the database: %s', + async (databaseUrl) => { + const directory = mkdtempSync(join(tmpdir(), 'void-platform-private-ca-test-')); + directories.push(directory); + process.env.VOID_PLATFORM_REGISTRY_DIR = directory; + const input = { + accountId: 'account', + applicationDomain: 'apps.example.com', + controlPlaneDomain: '', + dedicatedZone: false, + displayName: 'Example', + installationSlug: 'example', + zoneName: 'example.com', + }; + const plan = await createPlatformInstallPlan(planningClient(), input, null); + expect(plan.actions.find((action) => action.key === 'hyperdrive')?.action).toBe('create'); + const secrets = (url: string) => + createPlatformInstallationSecrets({ + bootstrapGitHubId: '583231', + bootstrapGitHubLogin: 'octocat', + cloudflareApiToken: 'cf-token', + databaseUrl: url, + githubClientId: 'github-id', + githubClientSecret: 'github-secret', + jwtSecret: TEST_PLATFORM_JWT_SECRET, + projectSecretKey: TEST_PLATFORM_PROJECT_SECRET_KEY, + r2AccessKeyId: 'r2-id', + r2SecretAccessKey: 'r2-secret', + }); + const hyperdriveRequests: Array> = []; + const cloudflare = new PlatformCloudflareClient('cf-token', { + fetcher: async (_input, init) => { + hyperdriveRequests.push(JSON.parse(String(init?.body))); + return Response.json({ + success: true, + result: { id: 'hyperdrive-id', name: plan.deployment.resources.hyperdrive }, + }); + }, + }); + const claimedUrls: Array = []; + const lockedUrls: Array = []; + let index = 0; + const create = async (_account: string, name: string) => ({ id: `id-${index++}`, name }); + const dependencies: TestInstallerDependencies = { + acquireDatabaseLifecycleLock: async (url) => { + lockedUrls.push(url); + return acquireDatabaseLifecycleLock(); + }, + claimDatabase: async (url) => { + claimedUrls.push(url); + }, + client: { + createAiGateway: create, + createDispatchNamespace: create, + createDnsRecord: async (_zone, name) => ({ + content: '100::', + id: `id-${index++}`, + name, + proxied: true, + type: 'AAAA', + }), + createHyperdrive: (account, name, connectionString) => + cloudflare.createHyperdrive(account, name, connectionString), + createKvNamespace: create, + createQueue: create, + createR2Bucket: create, + createZone: async () => { + throw new Error('existing zone must not be created'); + }, + putKvValue: async () => {}, + putR2Object: async () => {}, + }, + deployWorker: async () => { + throw new Error('stop after resources'); + }, + migrateDatabase: async () => {}, + revalidateBeforeWorkerDeploy: async () => {}, + }; + + const rejected = installPlatform(plan, secrets(databaseUrl), null, dependencies); + await expect(rejected).rejects.toThrow( + 'A Hyperdrive created by Void trusts only public certificate authorities', + ); + await expect(rejected).rejects.toThrow('Use an existing Hyperdrive'); + await expect(rejected).rejects.toThrow('VOID_PLATFORM_HYPERDRIVE_ID'); + + expect(claimedUrls).toEqual([]); + expect(lockedUrls).toEqual([]); + expect(hyperdriveRequests).toEqual([]); + const manifest = listInstallationManifests(directory)[0]!; + expect(manifest).toMatchObject({ resources: [], status: 'planned' }); + const checkpoint = readPendingInstallationSecrets(manifest); + expect(checkpoint?.databaseClaimState).toBeUndefined(); + + // The database is still unbound, so the same installation resumes with a corrected URL. + const corrected = + 'postgres://user:password@db.example.com/void?sslmode=verify-full&sslrootcert=system'; + process.env.VOID_PLATFORM_DATABASE_URL = corrected; + let resumedUrl: string; + try { + resumedUrl = resolvePlatformInstallDatabaseUrl(checkpoint, manifest); + } finally { + delete process.env.VOID_PLATFORM_DATABASE_URL; + } + expect(resumedUrl).toBe(corrected); + const resumedPlan = await createPlatformInstallPlan(planningClient(), input, manifest); + expect(resumedPlan.actions.find((action) => action.key === 'hyperdrive')?.action).toBe( + 'create', + ); + await expect( + installPlatform(resumedPlan, secrets(resumedUrl), manifest, dependencies), + ).rejects.toThrow('stop after resources'); + + expect(claimedUrls).toEqual([corrected]); + expect(lockedUrls).toEqual([corrected]); + expect(hyperdriveRequests).toHaveLength(1); + expect(hyperdriveRequests[0]).toMatchObject({ mtls: { sslmode: 'require' } }); + }, + ); + + it('accepts a private certificate authority for an externally managed Hyperdrive', async () => { + const directory = mkdtempSync(join(tmpdir(), 'void-platform-external-private-ca-test-')); + directories.push(directory); + process.env.VOID_PLATFORM_REGISTRY_DIR = directory; + const databaseUrl = + 'postgres://user:password@db.example.com/void?sslmode=verify-full&sslrootcert=/etc/ssl/private-ca.pem'; + const plan = await createPlatformInstallPlan( + { + ...planningClient(), + listHyperdriveConfigs: async () => [{ id: 'external-hyperdrive', name: 'managed-db' }], + }, + { + accountId: 'account', + applicationDomain: 'apps.example.com', + controlPlaneDomain: '', + dedicatedZone: false, + displayName: 'Example', + externalHyperdrive: { + id: 'external-hyperdrive', + name: 'managed-db', + host: 'db.example.com', + user: 'user', + }, + installationSlug: 'example', + zoneName: 'example.com', + }, + null, + ); + expect(plan.actions.find((action) => action.key === 'hyperdrive')?.action).toBe('adopt'); + const claimedUrls: Array = []; + const unused = async () => ({ id: 'unused', name: 'unused' }); + + await expect( + installPlatform( + plan, + createPlatformInstallationSecrets({ + bootstrapGitHubId: '583231', + bootstrapGitHubLogin: 'octocat', + cloudflareApiToken: 'cf-token', + databaseUrl, + githubClientId: 'github-id', + githubClientSecret: 'github-secret', + jwtSecret: TEST_PLATFORM_JWT_SECRET, + projectSecretKey: TEST_PLATFORM_PROJECT_SECRET_KEY, + r2AccessKeyId: 'r2-id', + r2SecretAccessKey: 'r2-secret', + }), + null, + { + acquireDatabaseLifecycleLock, + claimDatabase: async (url) => { + claimedUrls.push(url); + throw new Error('stop after claim'); + }, + client: { + createAiGateway: unused, + createDispatchNamespace: unused, + createDnsRecord: async () => ({ + content: '100::', + id: 'unused', + name: 'unused', + proxied: true, + type: 'AAAA', + }), + createHyperdrive: async () => { + throw new Error('an externally managed Hyperdrive must not be created'); + }, + createKvNamespace: unused, + createQueue: unused, + createR2Bucket: unused, + createZone: async () => ({ + id: 'unused', + name: 'unused', + nameServers: [], + status: 'active', + }), + putKvValue: async () => {}, + putR2Object: async () => {}, + }, + revalidateBeforeWorkerDeploy: async () => {}, + }, + ), + ).rejects.toThrow('stop after claim'); + + expect(claimedUrls).toEqual([databaseUrl]); + }); + + it('resumes a claimed verify-full database URL by creating Hyperdrive with its TLS mode', async () => { + const directory = mkdtempSync(join(tmpdir(), 'void-platform-verify-full-resume-test-')); + directories.push(directory); + process.env.VOID_PLATFORM_REGISTRY_DIR = directory; + const databaseUrl = 'postgresql://user:password@db.example.com:5432/void?sslmode=verify-full'; + const deployment = createPlatformDeploymentManifest({ + application: { baseDomain: 'apps.example.com', zoneName: 'example.com' }, + displayName: 'Example', + installationSlug: 'example', + }); + let manifest = createPlatformInstallationManifest({ + account: { id: 'account', name: 'Account' }, + createdAt: '2026-09-14T00:00:00.000Z', + deployment, + id: 'example-a1b2c3d4', + ownershipNonce: '0123456789abcdef0123456789abcdef', + platformVersion: '1.0.0', + }); + manifest = transitionInstallation(manifest, 'planned', '2026-09-14T00:00:01.000Z'); + manifest = transitionInstallation(manifest, 'provisioning', '2026-09-14T00:00:02.000Z'); + // The earlier attempt claimed the database and recorded its Hyperdrive intent, + // but Cloudflare rejected the create, so no Hyperdrive resource exists. + manifest = recordInstallationStep( + manifest, + { + completedAt: '2026-09-14T00:00:03.000Z', + key: 'provision-intent:hyperdrive', + resultHash: platformProvisionIntentHash( + manifest, + 'hyperdrive', + 'hyperdrive', + deployment.resources.hyperdrive, + ), + }, + '2026-09-14T00:00:03.000Z', + ); + manifest = transitionInstallation(manifest, 'failed', '2026-09-14T00:00:04.000Z'); + writeInstallationManifest(manifest); + writePendingInstallationSecrets(manifest, { databaseClaimState: 'claimed', databaseUrl }); + const resumedUrl = resolvePlatformInstallDatabaseUrl( + readPendingInstallationSecrets(manifest), + manifest, + ); + expect(resumedUrl).toBe(databaseUrl); + const plan = await createPlatformInstallPlan( + planningClient(), + { + accountId: 'account', + applicationDomain: 'apps.example.com', + controlPlaneDomain: '', + dedicatedZone: false, + displayName: 'Example', + installationSlug: 'example', + zoneName: 'example.com', + }, + manifest, + ); + expect(plan.actions.find((action) => action.key === 'hyperdrive')?.action).toBe('create'); + const hyperdriveRequests: Array> = []; + const cloudflare = new PlatformCloudflareClient('cf-token', { + fetcher: async (_input, init) => { + hyperdriveRequests.push(JSON.parse(String(init?.body))); + return Response.json({ + success: true, + result: { id: 'hyperdrive-id', name: deployment.resources.hyperdrive }, + }); + }, + }); + const claimedUrls: Array = []; + const lockedUrls: Array = []; + let index = 0; + const create = async (_account: string, name: string) => ({ id: `id-${index++}`, name }); + + await expect( + installPlatform( + plan, + createPlatformInstallationSecrets({ + bootstrapGitHubId: '583231', + bootstrapGitHubLogin: 'octocat', + cloudflareApiToken: 'cf-token', + databaseUrl: resumedUrl, + githubClientId: 'github-id', + githubClientSecret: 'github-secret', + jwtSecret: TEST_PLATFORM_JWT_SECRET, + projectSecretKey: TEST_PLATFORM_PROJECT_SECRET_KEY, + r2AccessKeyId: 'r2-id', + r2SecretAccessKey: 'r2-secret', + }), + manifest, + { + acquireDatabaseLifecycleLock: async (url) => { + lockedUrls.push(url); + return acquireDatabaseLifecycleLock(); + }, + claimDatabase: async (url) => { + claimedUrls.push(url); + }, + client: { + createAiGateway: create, + createDispatchNamespace: create, + createDnsRecord: async (_zone, name) => ({ + content: '100::', + id: `id-${index++}`, + name, + proxied: true, + type: 'AAAA', + }), + createHyperdrive: (account, name, connectionString) => + cloudflare.createHyperdrive(account, name, connectionString), + createKvNamespace: create, + createQueue: create, + createR2Bucket: create, + createZone: async () => { + throw new Error('existing zone must not be created'); + }, + putKvValue: async () => {}, + putR2Object: async () => {}, + }, + deployWorker: async () => { + throw new Error('stop after resources'); + }, + migrateDatabase: async () => {}, + revalidateBeforeWorkerDeploy: async () => {}, + }, + ), + ).rejects.toThrow('stop after resources'); + + expect(claimedUrls).toEqual([databaseUrl]); + expect(lockedUrls).toEqual([databaseUrl]); + expect(hyperdriveRequests).toHaveLength(1); + expect(hyperdriveRequests[0]).toMatchObject({ mtls: { sslmode: 'require' } }); + expect(hyperdriveRequests[0]!.mtls).not.toHaveProperty('ca_certificate_id'); + expect(listInstallationManifests(directory)[0]!.resources).toContainEqual( + expect.objectContaining({ + configHash: hyperdriveOriginConfigHash(hyperdriveOriginFromConnectionString(databaseUrl)), + id: 'hyperdrive-id', + key: 'hyperdrive', + state: 'ready', + }), + ); + }); + it('keeps a cutover unresolved when the current Worker rollback is incomplete', async () => { const directory = mkdtempSync(join(tmpdir(), 'void-platform-incomplete-rollback-test-')); directories.push(directory); diff --git a/packages/void/test/unit/platform-management.test.ts b/packages/void/test/unit/platform-management.test.ts index 4437a45e8..6203b89b2 100644 --- a/packages/void/test/unit/platform-management.test.ts +++ b/packages/void/test/unit/platform-management.test.ts @@ -149,7 +149,7 @@ function client(manifest: PlatformInstallationManifest) { const disabledWrites: Array = []; const deletedKvValues: Array = []; let removedRoutes = 0; - return { + const fake = { deleted, emptiedBuckets, preservedBucketKeys, @@ -160,7 +160,15 @@ function client(manifest: PlatformInstallationManifest) { get removedRoutes() { return removedRoutes; }, - deleteResource: async (_account: string, kind: string, id: string) => { + deleteResource: async (_account: string, kind: string, id: string): Promise => { + // Like Cloudflare, refuse to delete a Queue while a platform Worker + // still binds it. + const bindingWorker = (await fake.listWorkerNames())[0]; + if (kind === 'queue' && bindingWorker) { + throw new Error( + `Cloudflare API error: Cannot delete queue '${id}' that is still referenced by a binding in a Worker. Unbind queue '${id}' from the Workers '${bindingWorker}'; then try again. (HTTP 400)`, + ); + } deleted.push([kind, id]); }, deleteKvValue: async (_account: string, _namespace: string, key: string) => { @@ -258,6 +266,7 @@ function client(manifest: PlatformInstallationManifest) { removedRoutes++; }, }; + return fake; } function namedResources(manifest: PlatformInstallationManifest, kind: InstallationResourceKind) { @@ -785,7 +794,7 @@ describe('platform lifecycle management', () => { await uninstallPlatform(fake, manifest, uninstallArgs, { interactive: false, }); - expect(fake.deleted.map(([kind]) => kind).sort()).toEqual(['queue', 'queue']); + expect(fake.deleted).toEqual([]); expect(fake.deleted.some(([kind]) => kind === 'zone')).toBe(false); const result = listInstallationManifests()[0]!; expect(result.status).toBe('uninstalled'); @@ -875,7 +884,7 @@ describe('platform lifecycle management', () => { await uninstallPlatform(fake, manifest, uninstallArgs, { interactive: false }); - expect(fake.deleted.map(([kind]) => kind).sort()).toEqual(['queue', 'queue']); + expect(fake.deleted).toEqual([]); expect(listInstallationManifests()[0]?.status).toBe('uninstalled'); expect( listInstallationManifests()[0]?.resources.find( @@ -891,12 +900,12 @@ describe('platform lifecycle management', () => { await uninstallPlatform(fake, manifest, uninstallArgs, { interactive: false, }); - expect(fake.deleted.map(([kind]) => kind).sort()).toEqual(['queue', 'queue']); + expect(fake.deleted).toEqual([]); expect(fake.remoteWrites.map((value) => JSON.parse(value).status)).toContain('uninstalled'); const retained = listInstallationManifests()[0]!.resources.filter( (resource) => resource.state === 'retained', ); - expect(retained).toHaveLength(13); + expect(retained).toHaveLength(15); }); it('refuses automatic deletion of an installer-created zone', async () => { @@ -929,7 +938,8 @@ describe('platform lifecycle management', () => { interactive: false, }, ); - expect(fake.deleted).toHaveLength(7); + expect(fake.deleted).toHaveLength(5); + expect(fake.deleted.some(([kind]) => kind === 'queue')).toBe(false); expect(fake.deleted).not.toContainEqual(['ai-gateway', 'ai-gateway-id']); expect(fake.emptiedBuckets).toEqual([]); expect(fake.preservedBucketKeys).toEqual([]); @@ -1019,28 +1029,111 @@ describe('platform lifecycle management', () => { const first = client(manifest); const originalDelete = first.deleteResource; first.deleteResource = async (account, kind, id) => { - if (kind === 'queue') { + if (kind === 'dispatch-namespace') { throw new Error('temporary deletion failure'); } await originalDelete(account, kind, id); }; await expect( - uninstallPlatform(first, manifest, uninstallArgs, { - interactive: false, - }), + uninstallPlatform( + first, + manifest, + { ...uninstallArgs, purgeData: true }, + { interactive: false }, + ), ).rejects.toThrow('temporary deletion failure'); const checkpoint = listInstallationManifests()[0]!; expect(checkpoint.status).toBe('failed'); expect(checkpoint.resources.filter((resource) => resource.state === 'deleted')).toHaveLength(0); const second = client(checkpoint); - await uninstallPlatform(second, checkpoint, uninstallArgs, { - interactive: false, - }); + await uninstallPlatform( + second, + checkpoint, + { ...uninstallArgs, purgeData: true }, + { interactive: false }, + ); expect(second.deleted.filter(([kind]) => kind === 'worker')).toEqual([]); expect(listInstallationManifests()[0]?.status).toBe('uninstalled'); }); + it('retains Queues that retained Workers still use', async () => { + const manifest = installedManifest(); + persist(manifest); + const fake = client(manifest); + + await uninstallPlatform( + fake, + manifest, + { ...uninstallArgs, purgeData: true }, + { interactive: false }, + ); + + expect(fake.deleted.some(([kind]) => kind === 'queue')).toBe(false); + const result = listInstallationManifests()[0]!; + expect(result.status).toBe('uninstalled'); + expect( + result.resources + .filter((resource) => resource.kind === 'queue') + .map((resource) => resource.state), + ).toEqual(['retained', 'retained']); + }); + + it('finishes an uninstall that stopped on a Queue still bound to a retained Worker', async () => { + let manifest = installedManifest(); + manifest = transitionInstallation(manifest, 'uninstalling', '2026-09-14T00:00:03.000Z'); + manifest = transitionInstallation( + { + ...manifest, + resources: manifest.resources.map((resource) => + resource.kind === 'worker' ? { ...resource, state: 'retained' as const } : resource, + ), + }, + 'failed', + '2026-09-14T00:00:04.000Z', + ); + persist(manifest); + const fake = client(manifest); + fake.listWorkerNames = async () => + manifest.resources + .filter((resource) => resource.kind === 'worker') + .map((resource) => resource.name); + + await uninstallPlatform( + fake, + manifest, + { ...uninstallArgs, purgeData: true }, + { interactive: false }, + ); + + expect(fake.deleted.some(([kind]) => kind === 'queue')).toBe(false); + const result = listInstallationManifests()[0]!; + expect(result.status).toBe('uninstalled'); + expect( + result.resources + .filter((resource) => resource.kind === 'queue') + .map((resource) => resource.state), + ).toEqual(['retained', 'retained']); + }); + + it('deletes Queues once no installation Worker remains', async () => { + const installed = installedManifest(); + const manifest = { + ...installed, + resources: installed.resources.filter((resource) => resource.kind !== 'worker'), + }; + persist(manifest); + const fake = client(manifest); + + await uninstallPlatform(fake, manifest, uninstallArgs, { interactive: false }); + + expect(fake.deleted).toEqual([ + ['queue', 'cron-queue-id'], + ['queue', 'usage-queue-id'], + ]); + expect(listInstallationManifests()[0]?.status).toBe('uninstalled'); + }); + it('resumes a purge after the final routing checkpoint was ambiguously deleted', async () => { const manifest = installedManifest(); persist(manifest); diff --git a/packages/void/test/unit/platform-worker-reuse.test.ts b/packages/void/test/unit/platform-worker-reuse.test.ts index 1a2006131..57daed93a 100644 --- a/packages/void/test/unit/platform-worker-reuse.test.ts +++ b/packages/void/test/unit/platform-worker-reuse.test.ts @@ -29,6 +29,7 @@ async function attemptReuse(input: { directProofDeploymentDrift?: boolean; directReadFailure?: boolean; liveTriggers?: boolean; + reuseMatchingVersion?: boolean; secrets?: Record | null; triggerFailure?: boolean; lateVersionDrift?: boolean; @@ -181,6 +182,9 @@ async function attemptReuse(input: { ...(input.acquireUploadSlot ? { acquireUploadSlot: input.acquireUploadSlot } : {}), ...(input.directApi ? { readCloudflare } : {}), ...(input.onReadyForActivation ? { onReadyForActivation: input.onReadyForActivation } : {}), + ...(input.reuseMatchingVersion === undefined + ? {} + : { reuseMatchingVersion: input.reuseMatchingVersion }), ...(input.waitForPriorWorker ? { waitForPriorWorker: input.waitForPriorWorker } : {}), inspectNewWorker: async () => 'owned', managedRoutes: [], @@ -226,6 +230,17 @@ it('reconciles traffic without uploading an identical active Worker version', as expect(run.onTrafficPublished).toHaveBeenCalledOnce(); }); +it.each([{ directApi: false }, { directApi: true }])( + 'uploads a fresh version for identical input when reuse is disabled: %j', + async ({ directApi }) => { + const run = await attemptReuse({ directApi, reuseMatchingVersion: false }); + expect(String(run.error)).toContain('upload reached'); + expect(run.calls).toContain('versions upload'); + expect(run.calls).not.toContain('triggers deploy'); + expect(run.onTrafficPublished).not.toHaveBeenCalled(); + }, +); + it('uses direct Cloudflare reads for a verified matching version', async () => { const run = await attemptReuse({ directApi: true }); expect(run.error).toBeNull(); diff --git a/packages/void/test/unit/platform-worker-upload-contract.test.ts b/packages/void/test/unit/platform-worker-upload-contract.test.ts index 298e13697..0a4cefe05 100644 --- a/packages/void/test/unit/platform-worker-upload-contract.test.ts +++ b/packages/void/test/unit/platform-worker-upload-contract.test.ts @@ -1,9 +1,10 @@ import { execFile } from 'node:child_process'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { toSlash } from 'pathslash'; import { expect, it } from 'vite-plus/test'; import { withConditionalPlatformWorkerCreate } from '../../src/cli/platform-installer.ts'; import { resolveWranglerArgv } from '../../src/cli/preset.ts'; @@ -123,3 +124,177 @@ it('accepts the bundled uploader query while preserving the create-only precondi rmSync(directory, { recursive: true, force: true }); } }, 30_000); + +function unsignedJwt(payload: Record): string { + const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url'); + return `${encode({ alg: 'none' })}.${encode(payload)}.signature`; +} + +it.each([false, true])( + 'uploads static assets before the guarded create of a new Worker (single-file uploads: %s)', + async (singleAssetUploads) => { + const directory = mkdtempSync(join(tmpdir(), 'void-worker-assets-contract-')); + const sessionJwt = unsignedJwt({ + exp: Math.floor(Date.now() / 1000) + 3600, + ...(singleAssetUploads ? { wrangler_single_asset_uploads: true } : {}), + }); + const completionJwt = unsignedJwt({ exp: Math.floor(Date.now() / 1000) + 3600, done: true }); + const requests: Array<{ + authorization: string | undefined; + body: string; + precondition: string | undefined; + request: string; + }> = []; + // A local fake API with a synthetic credential; nothing can reach a real account. + const server = createServer((request, response) => { + const url = request.url ?? ''; + let body = ''; + request.setEncoding('utf8'); + request.on('data', (chunk: string) => { + body += chunk; + }); + request.on('end', () => { + requests.push({ + authorization: request.headers.authorization, + body, + precondition: request.headers['if-none-match'], + request: `${request.method} ${url}`, + }); + response.setHeader('Content-Type', 'application/json'); + const path = new URL(url, 'http://127.0.0.1').pathname; + if (request.method === 'POST' && path.endsWith('/assets-upload-session')) { + const { manifest } = JSON.parse(body) as { + manifest: Record; + }; + response.end( + JSON.stringify({ + success: true, + result: { + jwt: sessionJwt, + buckets: [Object.values(manifest).map((entry) => entry.hash)], + }, + }), + ); + } else if (request.method === 'POST' && path.includes('/workers/assets/upload')) { + response.writeHead(201); + response.end(JSON.stringify({ success: true, result: { jwt: completionJwt } })); + } else if (request.method === 'PUT') { + response.writeHead(412); + response.end( + JSON.stringify({ + success: false, + errors: [{ code: 1000, message: 'Simulated concurrent creation.' }], + }), + ); + } else { + response.writeHead(404); + response.end( + JSON.stringify({ + success: false, + errors: [{ code: 10007, message: 'Worker not found.' }], + }), + ); + } + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}/client/v4`; + try { + writeFileSync( + join(directory, 'worker.mjs'), + 'export default { fetch() { return new Response("local test"); } };', + ); + mkdirSync(join(directory, 'public')); + writeFileSync(join(directory, 'public', 'client.js'), 'console.log("admin");'); + const config = join(directory, 'wrangler.json'); + writeFileSync( + config, + JSON.stringify({ + name: 'void-contract', + account_id: 'account', + main: 'worker.mjs', + compatibility_date: '2026-02-24', + workers_dev: false, + preview_urls: false, + no_bundle: true, + assets: { directory: toSlash(join(directory, 'public')) }, + }), + ); + const [command, ...prefix] = resolveWranglerArgv(process.cwd()); + let output = ''; + const failure = await withConditionalPlatformWorkerCreate( + 'account', + 'void-contract', + async (apiBase) => { + await new Promise((resolve) => { + const child = execFile( + command!, + [ + ...prefix, + 'deploy', + '--config', + config, + '--strict', + '--experimental-provision=false', + '--experimental-auto-create=false', + '--autoconfig=false', + ], + { + cwd: directory, + encoding: 'utf8', + timeout: 20_000, + maxBuffer: 1024 * 1024, + env: { + PATH: process.env.PATH, + SYSTEMROOT: process.env.SYSTEMROOT, + WINDIR: process.env.WINDIR, + TMP: process.env.TMP, + TEMP: process.env.TEMP, + CI: 'true', + CLOUDFLARE_API_TOKEN: 'synthetic-token', + CLOUDFLARE_API_BASE_URL: apiBase, + WRANGLER_SEND_METRICS: 'false', + WRANGLER_LOG_PATH: join(directory, 'logs'), + }, + }, + (_error, stdout, stderr) => { + output = stdout + stderr; + resolve(); + }, + ); + child.stdin?.end(); + }); + }, + origin, + ).catch((error: unknown) => error); + const trace = output + '\n' + requests.map((entry) => entry.request).join('\n'); + expect(String(failure), trace).toContain('created concurrently (HTTP 412)'); + const mutations = requests.filter((entry) => !entry.request.startsWith('GET ')); + const hash = /upload\/([0-9a-f]{32})$/.exec(mutations[1]?.request ?? '')?.[1]; + expect( + mutations.map((entry) => entry.request), + trace, + ).toEqual([ + 'POST /client/v4/accounts/account/workers/scripts/void-contract/assets-upload-session', + singleAssetUploads + ? `POST /client/v4/accounts/account/workers/assets/upload/${hash}` + : 'POST /client/v4/accounts/account/workers/assets/upload?base64=true', + 'PUT /client/v4/accounts/account/workers/scripts/void-contract?excludeScript=true&bindings_inherit=strict', + ]); + expect(mutations.map((entry) => entry.authorization)).toEqual([ + 'Bearer synthetic-token', + `Bearer ${sessionJwt}`, + 'Bearer synthetic-token', + ]); + expect(mutations.map((entry) => entry.precondition)).toEqual([undefined, undefined, '*']); + expect(mutations[2]!.body).toContain(completionJwt); + } finally { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + server.closeAllConnections(); + }); + rmSync(directory, { recursive: true, force: true }); + } + }, + 30_000, +);