Skip to content
Closed
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
1 change: 1 addition & 0 deletions packages/void/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@
"@cloudflare/config": "0.20.0",
"@cloudflare/sandbox": "^0.12.9",
"@cloudflare/vite-plugin": "1.54.7",
"@cloudflare/workers-auth": "0.9.4",
"@cloudflare/workers-types": "catalog:",
"@napi-rs/keyring": "2.0.0",
"@void/deploy-cloudflare": "workspace:*",
Expand Down
52 changes: 16 additions & 36 deletions packages/void/src/cli/cf-compat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,24 @@
* process translates them to the pinned cf CLI. It never invokes Wrangler.
*/
import { spawnSync } from 'node:child_process';
import {
copyFileSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { fileURLToPath } from 'node:url';
import { readBuildOutput } from '@cloudflare/build-output-utils';
import { parse } from 'jsonc-parser';
import { dirname, join, resolve } from 'pathslash';
import { EnvHttpProxyAgent, fetch as httpFetch } from 'undici';
import { prepareCfBuildOutput } from './cf-build-output.ts';
import { persistCfKeyringPreference, readCfSessionCredential } from './cf-session.ts';

type Result = { status: number; stdout: string; stderr: string };
type Json = Record<string, unknown>;

const cf = join(dirname(fileURLToPath(import.meta.resolve('cf/package.json'))), 'bin', 'cf');
const args = process.argv.slice(2);
// This dedicated transport process uses the same encrypted OAuth store for
// login, deployment, and ancillary API calls. API-token overrides still win.
process.env.CLOUDFLARE_AUTH_USE_KEYRING = 'true';

function cfEnvironment(): NodeJS.ProcessEnv {
// The pinned bin otherwise delegates to any cf installed by the project.
Expand Down Expand Up @@ -416,37 +413,17 @@ async function sessionCredential(): Promise<{ type: 'oauth' | 'api_token'; token
if (state.authenticated !== true || state.tokenValid !== true) {
return null;
}
if (typeof state.authSource !== 'string' || !state.authSource.startsWith('OAuth token')) {
return null;
}
// cf's encrypted store is authoritative. Reading the path from whoami would
// fail after cf migrates and deletes the old plaintext credential file.
const dist = join(dirname(fileURLToPath(import.meta.resolve('cf/package.json'))), 'dist');
const entry = readdirSync(dist).find((name) => /^cf-[^/]+\.mjs$/.test(name));
if (!entry) {
throw new Error('The bundled Cloudflare credential reader is unavailable.');
}
const module = (await import(pathToFileURL(join(dist, entry)).href)) as {
t?: (options: { logger: Record<string, (...args: Array<unknown>) => void> }) => {
readAuthCredentials: () => unknown;
};
};
if (typeof module.t !== 'function') {
throw new Error('The bundled Cloudflare credential reader is unavailable.');
}
const noop = () => {};
const stored = module
.t({ logger: { debug: noop, info: noop, log: noop, warn: noop, error: noop } })
.readAuthCredentials();
const credential = stored && typeof stored === 'object' ? (stored as Json) : null;
return credential && typeof credential.oauth_token === 'string' && credential.oauth_token
? { type: 'oauth', token: credential.oauth_token }
: null;
const credential = readCfSessionCredential(process.cwd(), state);
return credential ? { type: 'oauth', token: credential } : null;
}

async function auth(): Promise<Result> {
if (args[0] === 'login') {
return runInteractiveCf(['auth', 'login', '--force']);
const loggedIn = runInteractiveCf(['auth', 'login', '--force']);
if (loggedIn.status === 0) {
persistCfKeyringPreference(process.cwd());
}
return loggedIn;
}
if (args[0] === 'logout') {
return runCf(['auth', 'logout']);
Expand All @@ -464,6 +441,9 @@ async function auth(): Promise<Result> {
'Cloudflare authentication is required.',
);
}
if (String(identity.authSource).startsWith('OAuth token from ')) {
persistCfKeyringPreference(process.cwd());
}
return result(
0,
JSON.stringify({
Expand Down
58 changes: 58 additions & 0 deletions packages/void/src/cli/cf-session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import {
createCfAuth,
createCfProfileStore,
setKeyringPreference,
} from '@cloudflare/workers-auth/cf';

const logger = {
debug() {},
info() {},
log() {},
warn() {},
error() {},
};

function session(root: string) {
const auth = createCfAuth({
logger,
userAgent: 'void',
prompt: async () => {
throw new Error('Cloudflare session reads cannot prompt.');
},
select: async () => {
throw new Error('Cloudflare session reads cannot prompt.');
},
isNoDefaultValueProvidedError: () => false,
});
auth.setProfile(createCfProfileStore({ logger }).resolve({ cwd: root }));
return auth;
}

/** Borrow only the profile just verified by cf, including its encrypted store. */
export function readCfSessionCredential(
root: string,
identity: Record<string, unknown>,
): string | null {
if (identity.authenticated !== true || identity.tokenValid !== true) {
return null;
}
const auth = session(root);
if (identity.authSource !== `OAuth token from ${auth.getCredentialStore().path()}`) {
return null;
}
const token = auth.readAuthCredentials()?.oauth_token;
if (typeof token === 'string' && token.length > 0) {
persistCfKeyringPreference(root);
}
return typeof token === 'string' && token.length > 0 ? token : null;
}

/** Keep subsequent cf logins on the encrypted profile adopted by Void. */
export function persistCfKeyringPreference(root: string): void {
const auth = session(root);
if (
!setKeyringPreference(true, { logger, getCredentialStore: auth.getCredentialStore }).enabled
) {
throw new Error('Cloudflare encrypted credential storage is unavailable.');
}
}
161 changes: 82 additions & 79 deletions packages/void/test/unit/cf-compat.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { execFile } from 'node:child_process';
import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { createServer, request as httpRequest } from 'node:http';
import type { AddressInfo } from 'node:net';
import { connect } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { expect, it } from 'vite-plus/test';
import { resolveWranglerArgv } from '../../src/cli/preset.ts';

Expand Down Expand Up @@ -64,94 +64,97 @@ it('clears Worker Cron Triggers through the pinned account API', async () => {
}
}, 30_000);

it('reads OAuth credentials through cf instead of using the whoami source as a file path', async () => {
const directory = mkdtempSync(join(tmpdir(), 'void-cf-clear-crons-oauth-'));
const server = createServer((request, response) => {
expect(request.headers.authorization).toBe('Bearer synthetic-oauth-token');
request.resume();
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify({ success: true, result: { schedules: [] } }));
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
try {
const configPath = join(directory, 'wrangler.json');
const cfDist = join(dirname(fileURLToPath(import.meta.resolve('cf/package.json'))), 'dist');
const cfModule = readdirSync(cfDist).find((name) => /^cf-[^/]+\.mjs$/.test(name));
if (!cfModule) {
throw new Error('The pinned Cloudflare auth module is missing.');
}
const preload = join(directory, 'mock-cf.mjs');
writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
writeFileSync(
preload,
`import child from 'node:child_process';
it.each(['clear-crons'])(
'uses encrypted browser credentials for %s',
async (operation) => {
const directory = mkdtempSync(join(tmpdir(), 'void-cf-clear-crons-oauth-'));
const server = createServer((request, response) => {
expect(request.headers.authorization).toBe('Bearer synthetic-oauth-token');
request.resume();
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify({ success: true, result: { schedules: [] } }));
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
try {
const configPath = join(directory, 'wrangler.json');
const preload = join(directory, 'mock-cf.mjs');
writeFileSync(
configPath,
JSON.stringify({ name: 'test-worker', account_id: 'test-account' }),
);
writeFileSync(
preload,
`import child from 'node:child_process';
import os from 'node:os';
import { syncBuiltinESMExports } from 'node:module';
os.homedir = () => process.env.VOID_TEST_HOME;
syncBuiltinESMExports();
process.env.CLOUDFLARE_AUTH_USE_KEYRING = 'false';
const cf = await import(${JSON.stringify(pathToFileURL(join(cfDist, cfModule)).href)});
const noop = () => {};
cf.t({ logger: { debug: noop, info: noop, log: noop, warn: noop, error: noop } })
.writeAuthCredentials({ oauth_token: 'synthetic-oauth-token' });
import { setKeyProviderFactoryForTesting } from ${JSON.stringify(import.meta.resolve('@cloudflare/workers-auth'))};
import { createCfAuth } from ${JSON.stringify(import.meta.resolve('@cloudflare/workers-auth/cf'))};
let key;
setKeyProviderFactoryForTesting(() => ({ getKey: () => key, setKey: (value) => { key = value; }, deleteKey: () => { key = undefined; }, describe: () => 'synthetic provider' }));
const logger = { debug() {}, info() {}, log() {}, warn() {}, error() {} };
const auth = createCfAuth({ logger, userAgent: 'void-test', prompt: async () => '', select: async () => '', isNoDefaultValueProvidedError: () => false });
auth.writeAuthCredentials({ oauth_token: 'synthetic-oauth-token', refresh_token: 'synthetic-refresh', expiration_time: new Date(Date.now() + 3600000).toISOString(), scopes: [] });
const credentialPath = auth.getCredentialStore().path();
child.spawnSync = (_binary, args, options) => {
if (args[1] !== 'auth' || args[2] !== 'whoami' || options.env.CLOUDFLARE_AUTH_USE_KEYRING !== 'true') {
return { status: 1, stdout: '', stderr: 'Wrong authentication source.' };
}
// Keep this synthetic test independent of the host OS keyring. The cf
// subprocess still has to receive the keyring pin.
return { status: 0, stdout: JSON.stringify({ authenticated: true, tokenValid: true, authSource: 'OAuth token from encrypted store' }), stderr: '' };
return { status: 0, stdout: JSON.stringify({ authenticated: true, tokenValid: true, authSource: 'OAuth token from ' + credentialPath }), stderr: '' };
};
syncBuiltinESMExports();
`,
);
const entry = join(import.meta.dirname, '..', '..', 'src', 'cli', 'cf-compat.ts');
const output = await new Promise<{ status: number; stderr: string }>((resolve) => {
execFile(
process.execPath,
[
'--import',
pathToFileURL(preload).href,
entry,
'triggers',
'clear-crons',
'-c',
configPath,
'--name',
'test-worker',
],
{
cwd: directory,
encoding: 'utf8',
timeout: 20_000,
env: {
PATH: process.env.PATH,
SYSTEMROOT: process.env.SYSTEMROOT,
WINDIR: process.env.WINDIR,
CI: 'true',
HOME: directory,
USERPROFILE: directory,
XDG_CONFIG_HOME: join(directory, '.config'),
APPDATA: join(directory, 'AppData', 'Roaming'),
LOCALAPPDATA: join(directory, 'AppData', 'Local'),
CLOUDFLARE_AUTH_USE_KEYRING: 'true',
CLOUDFLARE_ACCOUNT_ID: 'test-account',
CLOUDFLARE_API_BASE_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}/client/v4`,
VOID_TEST_HOME: directory,
},
},
(error, _stdout, stderr) => resolve({ status: error ? 1 : 0, stderr }),
);
});
expect(output.status, output.stderr).toBe(0);
} finally {
await new Promise<void>((resolve) => {
server.close(() => resolve());
server.closeAllConnections();
});
rmSync(directory, { recursive: true, force: true });
}
}, 30_000);
const entry = join(import.meta.dirname, '..', '..', 'src', 'cli', 'cf-compat.ts');
const output = await new Promise<{ status: number; stderr: string }>((resolve) => {
execFile(
process.execPath,
[
'--import',
pathToFileURL(preload).href,
entry,
'triggers',
operation,
'-c',
configPath,
'--name',
'test-worker',
],
{
cwd: directory,
encoding: 'utf8',
timeout: 20_000,
env: {
PATH: process.env.PATH,
SYSTEMROOT: process.env.SYSTEMROOT,
WINDIR: process.env.WINDIR,
CI: 'true',
CLOUDFLARE_AUTH_USE_KEYRING: 'true',
CLOUDFLARE_ACCOUNT_ID: 'test-account',
CLOUDFLARE_API_BASE_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}/client/v4`,
HOME: directory,
USERPROFILE: directory,
XDG_CONFIG_HOME: join(directory, '.config'),
APPDATA: join(directory, 'AppData', 'Roaming'),
LOCALAPPDATA: join(directory, 'AppData', 'Local'),
VOID_TEST_HOME: directory,
},
},
(error, _stdout, stderr) => resolve({ status: error ? 1 : 0, stderr }),
);
});
expect(output.status, output.stderr).toBe(0);
} finally {
await new Promise<void>((resolve) => {
server.close(() => resolve());
server.closeAllConnections();
});
rmSync(directory, { recursive: true, force: true });
}
},
30_000,
);

it('reports an absent cf session as authentication failure', async () => {
const directory = mkdtempSync(join(tmpdir(), 'void-cf-no-auth-'));
Expand Down
Loading
Loading