Skip to content

Commit 8548064

Browse files
committed
Identify Void in Cloudflare deployment requests
1 parent 63479f4 commit 8548064

6 files changed

Lines changed: 72 additions & 5 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { readFileSync } from 'node:fs';
2+
import { join } from 'pathslash';
3+
import { getPackageDir } from './agents.ts';
4+
5+
let voidUserAgent: string | undefined;
6+
let cfCliVersion: string | undefined;
7+
8+
export function getVoidUserAgent(): string {
9+
if (voidUserAgent === undefined) {
10+
const pkg = JSON.parse(readFileSync(join(getPackageDir(), 'package.json'), 'utf8'));
11+
voidUserAgent = `void/${pkg.version}`;
12+
}
13+
return voidUserAgent;
14+
}
15+
16+
/** cf prepends `cf-cli/` to CLI_VERSION for both API requests and uploads. */
17+
export function getCfCliVersion(): string {
18+
// Scope this override to cf's child environment; never change Void's process.env.
19+
// Resolve the installed dependency rather than inheriting a caller's test override.
20+
if (cfCliVersion === undefined) {
21+
const pkg = JSON.parse(readFileSync(new URL(import.meta.resolve('cf/package.json')), 'utf8'));
22+
cfCliVersion = `${pkg.version} ${getVoidUserAgent()}`;
23+
}
24+
return cfCliVersion;
25+
}

‎packages/void/src/cli/cf-version-api.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import mime from 'mime';
1414
import { extname, join, relative } from 'pathslash';
1515
import type { CfBuildOutput } from './cf-build-output.ts';
1616
import { record as object } from './cf-config-migrate.ts';
17+
import { getVoidUserAgent } from './cf-user-agent.ts';
1718

1819
type Json = Record<string, unknown>;
1920
export type CfCommand = (
@@ -402,6 +403,7 @@ async function apiResult(
402403
const response = await fetch(url, {
403404
method,
404405
headers: {
406+
'User-Agent': getVoidUserAgent(),
405407
Authorization: `Bearer ${token}`,
406408
...(body && !form ? { 'Content-Type': 'application/json' } : {}),
407409
},

‎packages/void/src/cli/cf-version-runner.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { isRecord as record } from '@void/deploy-core';
1313
import { dirname, join } from 'pathslash';
1414
import type { CfBuildOutput } from './cf-build-output.ts';
1515
import { migrateBuiltWranglerConfig } from './cf-config-migrate.ts';
16+
import { getCfCliVersion } from './cf-user-agent.ts';
1617
import {
1718
isSecretBindingType,
1819
uploadPinnedCloudflareVersion,
@@ -248,6 +249,7 @@ export function createCfCommand(options: {
248249
const env: NodeJS.ProcessEnv = {
249250
...options.env(options.accountId, options.apiBaseUrl),
250251
CF_DELEGATION: '1',
252+
CLI_VERSION: getCfCliVersion(),
251253
// Void owns the terminal UI. Keep cf's notices, progress, and telemetry out
252254
// of successful deploys; retain its complete output for error diagnosis.
253255
CF_QUIET: '1',

‎packages/void/src/cli/cloudflare-operation-process.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type { CloudflareOperation } from '@void/deploy-cloudflare';
1212
import { parse } from 'jsonc-parser';
1313
import { dirname, join, resolve } from 'pathslash';
1414
import { persistCfKeyringPreference, readCfSessionCredential } from './cf-session.ts';
15+
import { getCfCliVersion, getVoidUserAgent } from './cf-user-agent.ts';
1516
import {
1617
cloudflareDeviceCode,
1718
cloudflareVerificationUrl,
@@ -64,6 +65,7 @@ function cfEnvironment(): NodeJS.ProcessEnv {
6465
const env: NodeJS.ProcessEnv = {
6566
...process.env,
6667
CF_DELEGATION: '1',
68+
CLI_VERSION: getCfCliVersion(),
6769
CF_SEND_TELEMETRY: 'false',
6870
CF_NO_OSC_PROGRESS: '1',
6971
CLOUDFLARE_AUTH_USE_KEYRING: process.env.CLOUDFLARE_AUTH_USE_KEYRING,
@@ -480,13 +482,13 @@ async function apiHeaders(): Promise<Record<string, string>> {
480482
const key = process.env.CLOUDFLARE_API_KEY ?? process.env.CF_API_KEY;
481483
const email = process.env.CLOUDFLARE_EMAIL ?? process.env.CF_EMAIL;
482484
if (key && email) {
483-
return { 'X-Auth-Key': key, 'X-Auth-Email': email };
485+
return { 'User-Agent': getVoidUserAgent(), 'X-Auth-Key': key, 'X-Auth-Email': email };
484486
}
485487
const credential = await sessionCredential();
486488
if (!credential) {
487489
throw new Error('Cloudflare session bearer is unavailable.');
488490
}
489-
return { Authorization: `Bearer ${credential.token}` };
491+
return { 'User-Agent': getVoidUserAgent(), Authorization: `Bearer ${credential.token}` };
490492
}
491493

492494
async function withSecretFile(

‎packages/void/test/unit/cf-version-runner.test.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ const roots: Array<string> = [];
3939
const pinnedCfVersion = JSON.parse(
4040
readFileSync(fileURLToPath(import.meta.resolve('cf/package.json')), 'utf8'),
4141
).version as string;
42+
const voidVersion = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
43+
.version as string;
44+
const cfUserAgent = `cf-cli/${pinnedCfVersion} void/${voidVersion}`;
4245
// Each real cf subprocess loads cf's bundle before it does any work. That takes about half a
4346
// second when idle and several seconds on a busy machine, which can pass Vitest's 5s default.
4447
const REAL_CF_TIMEOUT_MS = process.platform === 'win32' ? 20_000 : 15_000;
@@ -49,8 +52,10 @@ it(
4952
const prepared = await output();
5053
const draft = voidSecretDraftVersion();
5154
const requests: Array<string> = [];
55+
const userAgents: Array<string | undefined> = [];
5256
const server = createServer((request, response) => {
5357
requests.push(request.url ?? '');
58+
userAgents.push(request.headers['user-agent']);
5459
request.resume();
5560
response.writeHead(200, { 'Content-Type': 'application/json' });
5661
response.end(JSON.stringify({ success: true, errors: [], messages: [], result: draft }));
@@ -67,6 +72,7 @@ it(
6772
SYSTEMROOT: process.env.SYSTEMROOT,
6873
WINDIR: process.env.WINDIR,
6974
CI: 'true',
75+
CLI_VERSION: 'inherited-version void/stale',
7076
CLOUDFLARE_API_TOKEN: 'synthetic-token',
7177
CLOUDFLARE_ACCOUNT_ID: 'test-account',
7278
CLOUDFLARE_API_BASE_URL: apiBaseUrl,
@@ -99,6 +105,7 @@ it(
99105
`/client/v4/accounts/test-account/workers/workers/void-test/versions/${draft.id}?include=modules`,
100106
]);
101107
expect(commands).toHaveLength(1);
108+
expect(userAgents).toEqual([cfUserAgent]);
102109
expect(commands[0]!.bounds).toMatchObject({ timeoutMs: 30_000, maxOutputBytes: 1024 * 1024 });
103110
expect(JSON.stringify(result)).not.toContain('synthetic-token');
104111
} finally {
@@ -208,8 +215,10 @@ it(
208215
async () => {
209216
const prepared = await output();
210217
const requests: Array<string> = [];
218+
const userAgents: Array<string | undefined> = [];
211219
const server = createServer((request, response) => {
212220
requests.push(request.url ?? '');
221+
userAgents.push(request.headers['user-agent']);
213222
request.resume();
214223
response.writeHead(404, { 'Content-Type': 'application/json' });
215224
response.end(
@@ -252,6 +261,7 @@ it(
252261
// cf deliberately omits the API code from this local error.
253262
expect(result.errorCode).toBeUndefined();
254263
expect(requests).toEqual(['/client/v4/accounts/account-id/workers/services/void-test']);
264+
expect(userAgents).toEqual([cfUserAgent]);
255265
} finally {
256266
prepared.dispose();
257267
await new Promise<void>((resolve, reject) =>
@@ -835,7 +845,12 @@ async function verifyPinnedUpload(atomic: boolean): Promise<void> {
835845
{ name: 'KEY', type: 'secret_key' },
836846
],
837847
});
838-
const requests: Array<{ url: string; body: string; authorization: string | undefined }> = [];
848+
const requests: Array<{
849+
url: string;
850+
body: string;
851+
authorization: string | undefined;
852+
userAgent: string | undefined;
853+
}> = [];
839854
let uploadedBatches = 0;
840855
const server = createServer(async (request, response) => {
841856
const chunks: Array<Buffer> = [];
@@ -846,6 +861,7 @@ async function verifyPinnedUpload(atomic: boolean): Promise<void> {
846861
url: request.url ?? '',
847862
body: Buffer.concat(chunks).toString('utf8'),
848863
authorization: request.headers.authorization,
864+
userAgent: request.headers['user-agent'],
849865
});
850866
response.writeHead(200, { 'Content-Type': 'application/json' });
851867
const path = request.url ?? '';
@@ -896,6 +912,9 @@ async function verifyPinnedUpload(atomic: boolean): Promise<void> {
896912
verifyUploader: () => true,
897913
});
898914
expect(uploaded.id).toBe('22222222-2222-4222-8222-222222222222');
915+
expect(requests.map(({ userAgent }) => userAgent)).toEqual(
916+
requests.map(() => `void/${voidVersion}`),
917+
);
899918
const upload = requests.find(({ url }) =>
900919
url.endsWith(atomic ? '/versions?deploy=true' : '/versions'),
901920
);
@@ -1919,16 +1938,23 @@ it(
19191938
JSON.stringify({ name: 'cf', version: '0.0.0', bin: { cf: 'fake.cjs' } }),
19201939
);
19211940
writeFileSync(join(local, 'fake.cjs'), 'console.log("UNPINNED_PROJECT_CF_EXECUTED");');
1941+
const env = {
1942+
PATH: process.env.PATH,
1943+
CI: 'true',
1944+
CLI_VERSION: 'inherited-version void/stale',
1945+
CLOUDFLARE_API_TOKEN: 'synthetic-token',
1946+
};
19221947
const command = createCfCommand({
19231948
accountId: 'test-account',
19241949
apiBaseUrl: 'https://api.cloudflare.com/client/v4',
19251950
verifyUploader: () => true,
1926-
env: () => ({ PATH: process.env.PATH, CI: 'true', CLOUDFLARE_API_TOKEN: 'synthetic-token' }),
1951+
env: () => env,
19271952
});
19281953
const result = await command(['--version'], { cwd: root, capture: true });
19291954
expect(result.status, result.stderr).toBe(0);
19301955
expect(result.stdout).not.toContain('UNPINNED_PROJECT_CF_EXECUTED');
1931-
expect(result.stdout).toContain(pinnedCfVersion);
1956+
expect(result.stdout.trim()).toBe(`${pinnedCfVersion} void/${voidVersion}`);
1957+
expect(env.CLI_VERSION).toBe('inherited-version void/stale');
19321958
},
19331959
REAL_CF_TIMEOUT_MS,
19341960
);

‎packages/void/test/unit/cloudflare-operation-process.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,19 @@ import {
1818
import { Buffer } from '../../src/cli/node-buffer.ts';
1919
import { resolveCloudflareOperationArgv } from '../../src/cli/preset.ts';
2020

21+
const voidVersion = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
22+
.version as string;
23+
const cfVersion = JSON.parse(readFileSync(new URL(import.meta.resolve('cf/package.json')), 'utf8'))
24+
.version as string;
25+
2126
it('requests immutable version source explicitly without loading or provisioning build output', async () => {
2227
const directory = mkdtempSync(join(tmpdir(), 'void-cf-secret-source-'));
2328
const draft = voidSecretDraftVersion();
2429
const requests: Array<string> = [];
30+
const userAgents: Array<string | undefined> = [];
2531
const server = createServer((request, response) => {
2632
requests.push(request.url ?? '');
33+
userAgents.push(request.headers['user-agent']);
2734
request.resume();
2835
response.writeHead(200, { 'Content-Type': 'application/json' });
2936
response.end(JSON.stringify({ success: true, errors: [], messages: [], result: draft }));
@@ -55,6 +62,7 @@ it('requests immutable version source explicitly without loading or provisioning
5562
SYSTEMROOT: process.env.SYSTEMROOT,
5663
WINDIR: process.env.WINDIR,
5764
CI: 'true',
65+
CLI_VERSION: 'inherited-version void/stale',
5866
CLOUDFLARE_API_TOKEN: 'synthetic-token',
5967
CLOUDFLARE_ACCOUNT_ID: 'test-account',
6068
CLOUDFLARE_API_BASE_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}/client/v4`,
@@ -70,6 +78,7 @@ it('requests immutable version source explicitly without loading or provisioning
7078
`/client/v4/accounts/test-account/workers/workers/test-worker/versions/${draft.id}?include=modules`,
7179
]);
7280
expect(captured).not.toContain('synthetic-token');
81+
expect(userAgents).toEqual([`cf-cli/${cfVersion} void/${voidVersion}`]);
7382
} finally {
7483
await new Promise<void>((resolve) => {
7584
server.close(() => resolve());
@@ -166,6 +175,7 @@ it.each(['clear-crons', 'clear-domains'])(
166175
`/client/v4/accounts/test-account/workers/scripts/test-worker/${operation === 'clear-crons' ? 'schedules' : 'domains/records'}`,
167176
);
168177
expect(request.headers.authorization).toBe('Bearer synthetic-token');
178+
expect(request.headers['user-agent']).toBe(`void/${voidVersion}`);
169179
let body = '';
170180
for await (const chunk of request) {
171181
body += chunk;

0 commit comments

Comments
 (0)