Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference/cli/platform-security.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 1 addition & 1 deletion packages/void/src/cli/platform-management.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
102 changes: 98 additions & 4 deletions packages/void/src/cli/platform-security-audits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function assertPlatformSecurityAuditsSupported(
const OWNER_BINDING = '__VOID_SECURITY_SCANNER_OWNER';
const PROTOCOL = 1;

type ScannerClient = Pick<PlatformCloudflareClient, 'request'>;
type ScannerClient = Pick<PlatformCloudflareClient, 'request' | 'emptyR2Bucket'>;

type Binding = { type: string; name: string; text?: string; namespace_id?: string };

Expand All @@ -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 };
}

Expand All @@ -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') },
};
}
Expand Down Expand Up @@ -89,7 +97,12 @@ async function deleteIfPresent(client: ScannerClient, path: string): Promise<voi
await optional(() => 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. */
Expand Down Expand Up @@ -198,10 +211,85 @@ 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; 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,
accountId: string,
names: SecurityScannerNames,
marker: string,
controllerExists: boolean,
kept: Array<string>,
): Promise<boolean> {
const base = `/accounts/${encodeURIComponent(accountId)}`;
// As for the images: with no controller, a token without the right is not a failure.
const read = <T>(path: string) => optional(() => client.request<T>(path), !controllerExists);
const sandboxPath = `${base}/workers/scripts/${names.copySandbox}`;
const sandbox = await read<{ bindings: ReadonlyArray<Binding> }>(`${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 <Row>(path: string, take: (row: Row) => string | undefined) => {
const found: Array<string> = [];
for (let page = 1; page <= 50; page++) {
const rows = (await read<Array<Row>>(`${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<unknown>(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}&`,
(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,
)),
...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}`);
Comment thread
Brooooooklyn marked this conversation as resolved.
Resolved
}
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,
Expand Down Expand Up @@ -269,6 +357,9 @@ export async function deletePlatformSecurityScanner(
for (const application of found) {
kept.push(`security scanner container application ${application.name}`);
}
if (await deleteRuntimeCopies(client, manifest.account.id, names, marker, false, kept)) {
deleted.push('runtime copies');
}
if (
await deleteScannerImages(client, registryFetch, manifest.account.id, repositories, false)
) {
Expand Down Expand Up @@ -304,6 +395,9 @@ export async function deletePlatformSecurityScanner(
}
await deleteIfPresent(client, workerPath);
deleted.push('controller');
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)) {
deleted.push('scanner images');
}
Expand Down
130 changes: 130 additions & 0 deletions packages/void/test/unit/platform-security-audits.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
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<string, unknown>, missing = (_path: string) => 404) {
const calls: Array<string> = [];
const client = {
async request<T>(path: string, init?: RequestInit): Promise<T> {
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);
},
async emptyR2Bucket(_account: string, bucket: string): Promise<void> {
calls.push(`EMPTY ${bucket}`);
},
};
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 (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),
[`${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('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`,
`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([]);
});
});