From 511e1e1b23d34d7cd91304cba815a971d3c16fa3 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 15:45:10 +0800 Subject: [PATCH 1/2] fix(platform): remove scan copies on uninstall Uninstall removed the security scanner controller, gate, container applications and images, but left the runtime-copy dispatch namespace `void-security-copies-`, the copy sandbox Worker `void-security-copy-sandbox-`, and any D1, KV or R2 store a failed scan left. The API's hourly sweep stops with the platform, so nothing removed them afterwards. Found while uninstalling a live test install. Uninstall now deletes them after the controller: the namespace (with any copy still in it), the prefixed stores, then the sandbox. A sandbox that does not carry this installation's owner marker is kept and reported. Co-Authored-By: Claude Opus 5.5 --- docs/reference/cli/platform-security.md | 2 +- packages/void/src/cli/platform-management.ts | 2 +- .../void/src/cli/platform-security-audits.ts | 95 ++++++++++++- .../unit/platform-security-audits.test.ts | 126 ++++++++++++++++++ 4 files changed, 220 insertions(+), 5 deletions(-) create mode 100644 packages/void/test/unit/platform-security-audits.test.ts diff --git a/docs/reference/cli/platform-security.md b/docs/reference/cli/platform-security.md index d6d0dd7eb..7378c121a 100644 --- a/docs/reference/cli/platform-security.md +++ b/docs/reference/cli/platform-security.md @@ -17,7 +17,7 @@ void platform upgrade [id] --security-audits void platform repair [id] --security-audits ``` -This allows the feature and nothing more. No project is scanned until you set a scan mode. The runtime token needs the Containers permissions that the token page lists. Uninstalling the platform also deletes the scanner, its container applications, and the scanner images it copied. +This allows the feature and nothing more. No project is scanned until you set a scan mode. The runtime token needs the Containers permissions that the token page lists. Uninstalling the platform also deletes the scanner, its container applications, its scan copies, and the scanner images it copied. Then check the account and choose a mode: diff --git a/packages/void/src/cli/platform-management.ts b/packages/void/src/cli/platform-management.ts index f95e0aa7e..987e6b4bd 100644 --- a/packages/void/src/cli/platform-management.ts +++ b/packages/void/src/cli/platform-management.ts @@ -1313,7 +1313,7 @@ export async function uninstallPlatform( : []), ...(securityAudits ? [ - 'Delete the security scanner Worker, its container applications, and the scanner images it copied.', + 'Delete the security scanner Worker, its container applications, its scan copies, and the scanner images it copied.', ] : []), purgeResources diff --git a/packages/void/src/cli/platform-security-audits.ts b/packages/void/src/cli/platform-security-audits.ts index 5a4f8c68d..53053596b 100644 --- a/packages/void/src/cli/platform-security-audits.ts +++ b/packages/void/src/cli/platform-security-audits.ts @@ -41,6 +41,11 @@ export interface SecurityScannerNames { worker: string; application: string; gate: string; + /** The runtime copies' dispatch namespace and its outbound Worker (API M30). */ + copyNamespace: string; + copySandbox: string; + /** Every copy's script and D1, KV and R2 store name starts with it. */ + copyPrefix: string; engines: { 'engine-a': SecurityScannerEngineNames; 'engine-c': SecurityScannerEngineNames }; } @@ -57,6 +62,9 @@ export function securityScannerNames(installationId: string): SecurityScannerNam worker: `void-security-scanner-${suffix}`, application: `void-security-scanner-${suffix}`, gate: `void-security-scanner-gate-${suffix}`, + copyNamespace: `void-security-copies-${suffix}`, + copySandbox: `void-security-copy-sandbox-${suffix}`, + copyPrefix: `void-sec-copy-${suffix}-`, engines: { 'engine-a': engine('engine-a'), 'engine-c': engine('engine-c') }, }; } @@ -89,7 +97,12 @@ async function deleteIfPresent(client: ScannerClient, path: string): Promise client.request(path, { method: 'DELETE' })); } -type Deleted = 'gate' | 'container application' | 'controller' | 'scanner images'; +type Deleted = + | 'gate' + | 'container application' + | 'controller' + | 'runtime copies' + | 'scanner images'; export type SecurityScannerTeardown = Readonly<{ /** Cloudflare objects removed, in order. */ @@ -198,10 +211,80 @@ async function deleteScannerImages( return removed; } +const COPY_PAGE = 100; + +/** + * The copy namespace (Cloudflare deletes any copy still in it), the stores a failed scan + * left (the API's hourly sweep stops with the platform), then the copy sandbox, the + * namespace's outbound Worker. Run after the controller, the only Worker that binds them. + * The sandbox carries the ownership marker; the rest is named per installation, like the images. + */ +async function deleteRuntimeCopies( + client: ScannerClient, + account: string, + names: SecurityScannerNames, + marker: string, + controllerExists: boolean, + kept: Array, +): Promise { + const base = `/accounts/${account}`; + // As for the images: with no controller, a token without the right is not a failure. + const read = (path: string) => optional(() => client.request(path), !controllerExists); + const sandboxPath = `${base}/workers/scripts/${names.copySandbox}`; + const sandbox = await read<{ bindings: ReadonlyArray }>(`${sandboxPath}/settings`); + if (sandbox && plainText(sandbox.bindings) !== marker) { + kept.push(`security copy sandbox ${names.copySandbox}`); + return false; + } + const mine = (name: unknown): name is string => + typeof name === 'string' && name.startsWith(names.copyPrefix); + const pages = async (path: string, take: (row: Row) => string | undefined) => { + const found: Array = []; + for (let page = 1; page <= 50; page++) { + const rows = (await read>(`${path}per_page=${COPY_PAGE}&page=${page}`)) ?? []; + found.push(...rows.flatMap((row) => take(row) ?? [])); + if (rows.length < COPY_PAGE) { + break; + } + } + return found; + }; + const namespacePath = `${base}/workers/dispatch/namespaces/${names.copyNamespace}`; + const namespace = await read(namespacePath); + const prefix = encodeURIComponent(names.copyPrefix); + const stores = [ + ...(await pages<{ uuid?: unknown; name?: unknown }>( + `${base}/d1/database?name=${prefix}&`, + (row) => + mine(row.name) && typeof row.uuid === 'string' ? `d1/database/${row.uuid}` : undefined, + )), + ...(await pages<{ id?: unknown; title?: unknown }>(`${base}/storage/kv/namespaces?`, (row) => + mine(row.title) && typeof row.id === 'string' ? `storage/kv/namespaces/${row.id}` : undefined, + )), + ...( + ( + await read<{ buckets?: Array<{ name?: unknown }> }>( + `${base}/r2/buckets?name_contains=${prefix}&per_page=1000`, + ) + )?.buckets ?? [] + ).flatMap((bucket) => (mine(bucket.name) ? [`r2/buckets/${bucket.name}`] : [])), + ]; + if (namespace !== undefined) { + await deleteIfPresent(client, namespacePath); + } + for (const store of stores) { + await deleteIfPresent(client, `${base}/${store}`); + } + if (sandbox) { + await deleteIfPresent(client, sandboxPath); + } + return namespace !== undefined || stores.length > 0 || sandbox !== undefined; +} + /** * Uninstall: the gate first (nothing can call in), then the container applications, the - * controller Worker and the engine images. Each must carry this installation's ownership - * marker; one that is not ours is left alone and reported. + * controller Worker, the runtime copies and the engine images. A Worker or application must + * carry this installation's ownership marker; one that is not ours is left alone and reported. */ export async function deletePlatformSecurityScanner( client: ScannerClient, @@ -269,6 +352,9 @@ export async function deletePlatformSecurityScanner( for (const application of found) { kept.push(`security scanner container application ${application.name}`); } + if (await deleteRuntimeCopies(client, account, names, marker, false, kept)) { + deleted.push('runtime copies'); + } if ( await deleteScannerImages(client, registryFetch, manifest.account.id, repositories, false) ) { @@ -304,6 +390,9 @@ export async function deletePlatformSecurityScanner( } await deleteIfPresent(client, workerPath); deleted.push('controller'); + if (await deleteRuntimeCopies(client, account, names, marker, true, kept)) { + deleted.push('runtime copies'); + } if (await deleteScannerImages(client, registryFetch, manifest.account.id, repositories, true)) { deleted.push('scanner images'); } diff --git a/packages/void/test/unit/platform-security-audits.test.ts b/packages/void/test/unit/platform-security-audits.test.ts new file mode 100644 index 000000000..9a8db5b6c --- /dev/null +++ b/packages/void/test/unit/platform-security-audits.test.ts @@ -0,0 +1,126 @@ +import { createHash } from 'node:crypto'; +import type { PlatformInstallationManifest } from '@void/platform'; +import { describe, expect, it } from 'vite-plus/test'; +import { PlatformCloudflareApiError } from '../../src/cli/platform-cloudflare.ts'; +import { + deletePlatformSecurityScanner, + securityScannerNames, +} from '../../src/cli/platform-security-audits.ts'; + +const ID = 'inst-test'; +const SUFFIX = createHash('sha256') + .update(`void-security-scanner:${ID}`) + .digest('hex') + .slice(0, 12); +const ACCOUNT = '/accounts/acct'; +const MARKER = JSON.stringify({ protocol: 1, installation: ID }); +const manifest = { + id: ID, + account: { id: 'acct' }, + deployment: { capabilities: { securityAudits: true }, resources: { dispatchNamespace: 'users' } }, +} as unknown as PlatformInstallationManifest; +const owner = (text: string) => ({ + bindings: [{ type: 'plain_text', name: '__VOID_SECURITY_SCANNER_OWNER', text }], +}); + +/** Answers GETs from `reads` (else `missing(path)`, 404 by default); records the rest. */ +function fakeClient(reads: Record, missing = (_path: string) => 404) { + const calls: Array = []; + const client = { + async request(path: string, init?: RequestInit): Promise { + const method = init?.method ?? 'GET'; + if (method !== 'GET') { + calls.push(`${method} ${path}`); + return {} as T; + } + if (path in reads) { + return reads[path] as T; + } + throw new PlatformCloudflareApiError('missing', missing(path), path); + }, + }; + return { client, calls }; +} + +describe('security scanner uninstall', () => { + const names = securityScannerNames(ID); + const sandbox = `${ACCOUNT}/workers/scripts/void-security-copy-sandbox-${SUFFIX}`; + const namespace = `${ACCOUNT}/workers/dispatch/namespaces/void-security-copies-${SUFFIX}`; + const prefix = `void-sec-copy-${SUFFIX}-`; + + it('derives the copy names the API creates', () => { + expect([names.copyNamespace, names.copySandbox, names.copyPrefix]).toEqual([ + `void-security-copies-${SUFFIX}`, + `void-security-copy-sandbox-${SUFFIX}`, + prefix, + ]); + }); + + it('removes the copy namespace, leftover copy stores and the sandbox after the controller', async () => { + const controller = `${ACCOUNT}/workers/scripts/${names.worker}`; + const { client, calls } = fakeClient({ + [`${controller}/settings`]: owner(MARKER), + [`${sandbox}/settings`]: owner(MARKER), + [namespace]: { namespace_name: names.copyNamespace }, + [`${ACCOUNT}/d1/database?name=${encodeURIComponent(prefix)}&per_page=100&page=1`]: [ + { uuid: 'd1-copy', name: `${prefix}scan1-a1-d0` }, + { uuid: 'd1-app', name: 'app-db' }, + ], + [`${ACCOUNT}/storage/kv/namespaces?per_page=100&page=1`]: [ + { id: 'kv-copy', title: `${prefix}scan1-a1-k0` }, + ], + [`${ACCOUNT}/r2/buckets?name_contains=${encodeURIComponent(prefix)}&per_page=1000`]: { + buckets: [{ name: `${prefix}scan1-a1-r0` }], + }, + ...Object.fromEntries( + [ + names.application, + names.engines['engine-a'].application, + names.engines['engine-c'].application, + ].map((name) => [ + `${ACCOUNT}/containers/applications?name=${encodeURIComponent(name)}`, + [], + ]), + ), + }); + + const result = await deletePlatformSecurityScanner(client, manifest, async () => { + throw new Error('no registry call expected'); + }); + + expect(result).toEqual({ deleted: ['controller', 'runtime copies'], kept: [] }); + expect(calls.filter((call) => call.startsWith('DELETE'))).toEqual([ + `DELETE ${controller}`, + `DELETE ${namespace}`, + `DELETE ${ACCOUNT}/d1/database/d1-copy`, + `DELETE ${ACCOUNT}/storage/kv/namespaces/kv-copy`, + `DELETE ${ACCOUNT}/r2/buckets/${prefix}scan1-a1-r0`, + `DELETE ${sandbox}`, + ]); + }); + + it('keeps a copy sandbox another installation owns, and its namespace', async () => { + const { client, calls } = fakeClient({ + [`${sandbox}/settings`]: owner('{"protocol":1,"installation":"other"}'), + [namespace]: {}, + }); + + const result = await deletePlatformSecurityScanner(client, manifest); + + expect(result.kept).toEqual([`security copy sandbox ${names.copySandbox}`]); + expect(calls.filter((call) => call.startsWith('DELETE'))).toEqual([]); + }); + + it('treats a token without Containers or storage rights as nothing to remove when the scanner was never created', async () => { + const denied = ['/containers/', '/d1/', '/storage/', '/r2/']; + const { client, calls } = fakeClient({}, (path) => + denied.some((part) => path.includes(part)) ? 403 : 404, + ); + + await expect(deletePlatformSecurityScanner(client, manifest)).resolves.toEqual({ + deleted: [], + kept: [], + }); + expect(calls.filter((call) => call.startsWith('DELETE'))).toEqual([]); + }); +}); From f561d268fdc42f9bd5916a2840c69c11ec24ced1 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 15:51:44 +0800 Subject: [PATCH 2/2] fix(platform): empty scan-copy R2 buckets before deleting them Cloudflare deletes only an empty bucket, and a copy bucket may hold what the scanned app wrote, which would stop uninstall partway. Co-Authored-By: Claude Opus 5.5 --- .../void/src/cli/platform-security-audits.ts | 31 +++++++++++-------- .../unit/platform-security-audits.test.ts | 8 +++-- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/packages/void/src/cli/platform-security-audits.ts b/packages/void/src/cli/platform-security-audits.ts index 53053596b..a7a3e69f4 100644 --- a/packages/void/src/cli/platform-security-audits.ts +++ b/packages/void/src/cli/platform-security-audits.ts @@ -25,7 +25,7 @@ export function assertPlatformSecurityAuditsSupported( const OWNER_BINDING = '__VOID_SECURITY_SCANNER_OWNER'; const PROTOCOL = 1; -type ScannerClient = Pick; +type ScannerClient = Pick; type Binding = { type: string; name: string; text?: string; namespace_id?: string }; @@ -215,19 +215,20 @@ const COPY_PAGE = 100; /** * The copy namespace (Cloudflare deletes any copy still in it), the stores a failed scan - * left (the API's hourly sweep stops with the platform), then the copy sandbox, the + * left (the API's hourly sweep stops with the platform; a copy bucket may hold what the + * scanned app wrote, and only an empty bucket can be deleted), then the copy sandbox, the * namespace's outbound Worker. Run after the controller, the only Worker that binds them. * The sandbox carries the ownership marker; the rest is named per installation, like the images. */ async function deleteRuntimeCopies( client: ScannerClient, - account: string, + accountId: string, names: SecurityScannerNames, marker: string, controllerExists: boolean, kept: Array, ): Promise { - const base = `/accounts/${account}`; + const base = `/accounts/${encodeURIComponent(accountId)}`; // As for the images: with no controller, a token without the right is not a failure. const read = (path: string) => optional(() => client.request(path), !controllerExists); const sandboxPath = `${base}/workers/scripts/${names.copySandbox}`; @@ -252,6 +253,13 @@ async function deleteRuntimeCopies( const namespacePath = `${base}/workers/dispatch/namespaces/${names.copyNamespace}`; const namespace = await read(namespacePath); const prefix = encodeURIComponent(names.copyPrefix); + const buckets = ( + ( + await read<{ buckets?: Array<{ name?: unknown }> }>( + `${base}/r2/buckets?name_contains=${prefix}&per_page=1000`, + ) + )?.buckets ?? [] + ).flatMap((bucket) => (mine(bucket.name) ? [bucket.name] : [])); const stores = [ ...(await pages<{ uuid?: unknown; name?: unknown }>( `${base}/d1/database?name=${prefix}&`, @@ -261,17 +269,14 @@ async function deleteRuntimeCopies( ...(await pages<{ id?: unknown; title?: unknown }>(`${base}/storage/kv/namespaces?`, (row) => mine(row.title) && typeof row.id === 'string' ? `storage/kv/namespaces/${row.id}` : undefined, )), - ...( - ( - await read<{ buckets?: Array<{ name?: unknown }> }>( - `${base}/r2/buckets?name_contains=${prefix}&per_page=1000`, - ) - )?.buckets ?? [] - ).flatMap((bucket) => (mine(bucket.name) ? [`r2/buckets/${bucket.name}`] : [])), + ...buckets.map((bucket) => `r2/buckets/${bucket}`), ]; if (namespace !== undefined) { await deleteIfPresent(client, namespacePath); } + for (const bucket of buckets) { + await client.emptyR2Bucket(accountId, bucket); + } for (const store of stores) { await deleteIfPresent(client, `${base}/${store}`); } @@ -352,7 +357,7 @@ export async function deletePlatformSecurityScanner( for (const application of found) { kept.push(`security scanner container application ${application.name}`); } - if (await deleteRuntimeCopies(client, account, names, marker, false, kept)) { + if (await deleteRuntimeCopies(client, manifest.account.id, names, marker, false, kept)) { deleted.push('runtime copies'); } if ( @@ -390,7 +395,7 @@ export async function deletePlatformSecurityScanner( } await deleteIfPresent(client, workerPath); deleted.push('controller'); - if (await deleteRuntimeCopies(client, account, names, marker, true, kept)) { + if (await deleteRuntimeCopies(client, manifest.account.id, names, marker, true, kept)) { deleted.push('runtime copies'); } if (await deleteScannerImages(client, registryFetch, manifest.account.id, repositories, true)) { diff --git a/packages/void/test/unit/platform-security-audits.test.ts b/packages/void/test/unit/platform-security-audits.test.ts index 9a8db5b6c..ea42a925c 100644 --- a/packages/void/test/unit/platform-security-audits.test.ts +++ b/packages/void/test/unit/platform-security-audits.test.ts @@ -38,6 +38,9 @@ function fakeClient(reads: Record, missing = (_path: string) => } throw new PlatformCloudflareApiError('missing', missing(path), path); }, + async emptyR2Bucket(_account: string, bucket: string): Promise { + calls.push(`EMPTY ${bucket}`); + }, }; return { client, calls }; } @@ -56,7 +59,7 @@ describe('security scanner uninstall', () => { ]); }); - it('removes the copy namespace, leftover copy stores and the sandbox after the controller', async () => { + it('removes the copy namespace, leftover copy stores (buckets emptied first) and the sandbox after the controller', async () => { const controller = `${ACCOUNT}/workers/scripts/${names.worker}`; const { client, calls } = fakeClient({ [`${controller}/settings`]: owner(MARKER), @@ -89,9 +92,10 @@ describe('security scanner uninstall', () => { }); expect(result).toEqual({ deleted: ['controller', 'runtime copies'], kept: [] }); - expect(calls.filter((call) => call.startsWith('DELETE'))).toEqual([ + expect(calls.filter((call) => !call.startsWith('POST'))).toEqual([ `DELETE ${controller}`, `DELETE ${namespace}`, + `EMPTY ${prefix}scan1-a1-r0`, `DELETE ${ACCOUNT}/d1/database/d1-copy`, `DELETE ${ACCOUNT}/storage/kv/namespaces/kv-copy`, `DELETE ${ACCOUNT}/r2/buckets/${prefix}scan1-a1-r0`,