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
10 changes: 1 addition & 9 deletions cli/crates/cli/src/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,8 @@ pub fn sign_in(
fn run(pending: &PendingDeviceLogin, no_browser: bool, stop: &Arc<AtomicBool>) -> Result<()> {
let engine = resolve_codex_command()?;
let mut command = Command::new(engine);
for (key, _) in std::env::vars_os() {
let name = key.to_string_lossy();
if name.starts_with("CODEX_") || name.starts_with("OPENAI_") || name == "NODE_OPTIONS" {
command.env_remove(key);
}
}
let mut child = command
let mut child = multi_codex_core::process::isolated_codex_home(&mut command, &pending.codex_home)
.args(["login", "--device-auth"])
.env("CODEX_HOME", &pending.codex_home)
.env("CODEX_SQLITE_HOME", &pending.codex_home)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
Expand Down
15 changes: 8 additions & 7 deletions cli/crates/core/src/extension_accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ impl AuthRecognizer for BundledRecognizer {
tempfile::tempdir().map_err(|_| "Could not prepare credential validation")?;
profiles::write_private_file(&directory.path().join("auth.json"), auth.as_bytes())?;
profiles::write_codex_config(directory.path())?;
let output = crate::process::background(&mut std::process::Command::new(&self.0))
.args(["login", "status"])
.env("CODEX_HOME", directory.path())
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_API_KEY")
.output()
.map_err(|_| "The Codex extension's bundled engine could not validate the account")?;
let mut command = std::process::Command::new(&self.0);
let output = crate::process::background(crate::process::isolated_codex_home(
&mut command,
directory.path(),
))
.args(["login", "status"])
.output()
.map_err(|_| "The Codex extension's bundled engine could not validate the account")?;
if output.status.success() {
Ok(())
} else {
Expand Down
62 changes: 62 additions & 0 deletions cli/crates/core/src/process.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
//! Bound external desktop helpers so a disconnected compositor cannot hang a launch.
use std::ffi::OsStr;
use std::io::Read;
use std::path::Path;
use std::process::{Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant};

pub(crate) fn is_codex_override(key: &OsStr) -> bool {
let name = key.to_string_lossy().to_ascii_uppercase();
name.starts_with("CODEX_")
|| name.starts_with("OPENAI_")
|| matches!(name.as_str(), "NODE_OPTIONS" | "ELECTRON_RUN_AS_NODE")
}

/// Run Codex with the account's own credentials, provider and storage paths.
pub fn isolated_codex_home<'a>(command: &'a mut Command, home: &Path) -> &'a mut Command {
let overrides: Vec<_> = std::env::vars_os()
.map(|(key, _)| key)
.chain(command.get_envs().map(|(key, _)| key.to_owned()))
.filter(|key| is_codex_override(key))
.collect();
for key in overrides {
command.env_remove(key);
}
command
.env_remove("NODE_OPTIONS")
.env_remove("ELECTRON_RUN_AS_NODE")
.env("CODEX_HOME", home)
.env("CODEX_SQLITE_HOME", home)
}

pub fn background(command: &mut Command) -> &mut Command {
#[cfg(windows)]
{
Expand All @@ -13,6 +39,42 @@ pub fn background(command: &mut Command) -> &mut Command {
command
}

#[cfg(test)]
mod isolation_tests {
use super::*;

#[test]
fn private_codex_command_uses_only_its_account_environment() {
let home = Path::new("synthetic-account");
let mut command = Command::new("codex-fixture");
for key in [
"OPENAI_API_KEY",
"OPENAI_BASE_URL",
"CODEX_API_KEY",
"codex_provider_fixture",
"NODE_OPTIONS",
"ELECTRON_RUN_AS_NODE",
] {
command.env(key, "inert-fixture");
}
command.env("CODEX_HOME", "other-account");
command.env("CODEX_SQLITE_HOME", "other-database");
command.env("LANG", "C");
let configured: std::collections::BTreeMap<_, _> = isolated_codex_home(&mut command, home)
.get_envs()
.filter_map(|(key, value)| value.map(|value| (key, value)))
.collect();
assert_eq!(
configured,
std::collections::BTreeMap::from([
(OsStr::new("CODEX_HOME"), home.as_os_str()),
(OsStr::new("CODEX_SQLITE_HOME"), home.as_os_str()),
(OsStr::new("LANG"), OsStr::new("C")),
])
);
}
}

#[cfg(all(test, windows))]
mod windows_tests {
use super::*;
Expand Down
23 changes: 7 additions & 16 deletions cli/crates/core/src/profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,8 @@ impl AuthRecognizer for CodexCliRecognizer {

let codex = resolve_codex_command()?;
let output = crate::process::output(
Command::new(codex)
.args(["login", "status"])
.env("CODEX_HOME", temp.path()),
crate::process::isolated_codex_home(&mut Command::new(codex), temp.path())
.args(["login", "status"]),
Duration::from_secs(20),
)
.map_err(|_| "Codex CLI could not validate the account within 20 seconds".to_string())?;
Expand Down Expand Up @@ -2181,7 +2180,7 @@ fn cli_arguments(codex: &Path, home: &Path, workspace: &Path) -> Vec<String> {
]);
removed.extend(env::vars_os().filter_map(|(key, _)| {
let name = key.to_string_lossy();
(name.starts_with("CODEX_") || name.starts_with("OPENAI_") || name.starts_with("VSCODE_"))
(crate::process::is_codex_override(&key) || name.starts_with("VSCODE_"))
.then(|| name.into_owned())
}));
let mut args = vec!["/usr/bin/env".into()];
Expand Down Expand Up @@ -2563,19 +2562,16 @@ fn build_vscode_command_with(
#[cfg(target_os = "macos")]
let code = native_code.as_deref().unwrap_or(code);
let mut command = Command::new(code);
command
crate::process::isolated_codex_home(&mut command, codex_home)
.arg("--new-window")
.arg("--user-data-dir")
.arg(vscode_home)
.arg("--extensions-dir")
.arg(extensions_dir)
.arg(workspace)
.env("CODEX_HOME", codex_home)
.env("CODEX_SQLITE_HOME", codex_home)
.env_remove("VSCODE_IPC_HOOK_CLI")
.env_remove("VSCODE_PID")
.env_remove("VSCODE_CWD")
.env_remove("ELECTRON_RUN_AS_NODE");
.env_remove("VSCODE_CWD");
#[cfg(target_os = "macos")]
command
.env_remove("VSCODE_ESM_ENTRYPOINT")
Expand All @@ -2594,16 +2590,11 @@ fn build_standalone_command(
// data explicitly. Never forward this request to an unscoped global app.
for (key, _) in env::vars_os() {
let name = key.to_string_lossy();
if name.starts_with("CODEX_") || name.starts_with("OPENAI_") || name.starts_with("VSCODE_")
{
if name.starts_with("VSCODE_") {
command.env_remove(key);
}
}
command
.env_remove("NODE_OPTIONS")
.env_remove("ELECTRON_RUN_AS_NODE")
.env("CODEX_HOME", codex_home)
.env("CODEX_SQLITE_HOME", codex_home)
crate::process::isolated_codex_home(&mut command, codex_home)
.env("CODEX_ELECTRON_USER_DATA_PATH", desktop_home)
.arg(format!("--user-data-dir={}", desktop_home.display()))
.current_dir(workspace)
Expand Down
6 changes: 2 additions & 4 deletions cli/crates/core/src/usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,9 @@ fn read_with_command(
checked_at: DateTime<Utc>,
) -> Result<ProfileLimits> {
let mut child = crate::process::spawn(
Command::new(codex)
// Keep token refreshes in the profile's durable home.
crate::process::isolated_codex_home(&mut Command::new(codex), codex_home)
.args(["app-server", "--stdio"])
// Use the profile's durable home so a token refreshed by Codex is not discarded with a
// temporary directory. Each Multi Codex profile already has its own isolated CODEX_HOME.
.env("CODEX_HOME", codex_home)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped()),
Expand Down
11 changes: 5 additions & 6 deletions extension/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,8 @@ export class CodexBridge {
constructor(readonly config: BridgeConfig, readonly frontend: JsonLines, args: string[], private existing?: ExistingBackend) {
if (config.sharedChats && existing) throw new Error('Shared chats require a managed private backend; live attachment cannot enforce writer handoff.');
this.engineArgs = args;
const env: NodeJS.ProcessEnv = config.sharedChats ? privateBackendEnvironment(config.sessionHome) : { ...process.env, CODEX_HOME: config.sessionHome,
CODEX_SQLITE_HOME: config.sharedChats ? config.sessionHome : config.historyHome ?? config.sessionHome };
delete env.OPENAI_API_KEY; delete env.CODEX_API_KEY; delete env.ELECTRON_RUN_AS_NODE;
const historyHome = config.sharedChats ? config.sessionHome : config.historyHome;
const env = privateBackendEnvironment(config.sessionHome, process.env, historyHome);
this.backend = existing?.child ?? spawnExecutable(config.engine, args, { env, cwd: config.workspace, stdio: ['pipe', 'pipe', 'pipe'] });
// Codex diagnostics can contain workspace and account data. Never mirror them into VS Code logs.
if (!existing) this.backend.stderr.resume();
Expand Down Expand Up @@ -350,9 +349,9 @@ export class CodexBridge {
const nextHome = join(this.config.sessionHome, '..', randomUUID());
await prepareSessionHome(join(this.config.dataRoot, 'profiles', profileId, 'codex-home'), nextHome, { sharedChats: true });
this.config.sessionHome = nextHome;
const env = privateBackendEnvironment(nextHome);
delete env.OPENAI_API_KEY; delete env.CODEX_API_KEY; delete env.ELECTRON_RUN_AS_NODE;
this.backend = spawnExecutable(this.config.engine, this.engineArgs, { env, cwd: this.config.workspace });
this.backend = spawnExecutable(this.config.engine, this.engineArgs, {
env: privateBackendEnvironment(nextHome), cwd: this.config.workspace,
});
this.backend.stderr.resume();
this.backendLines = new JsonLines(this.backend.stdout, this.backend.stdin);
this.backendRpc = new RpcPeer(this.backendLines);
Expand Down
5 changes: 2 additions & 3 deletions extension/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { AccountClient, type Account } from './accounts';
import { BridgeClient } from './client';
import { JsonLines, RpcPeer } from './protocol';
import { withAccountBackend } from './worker';
import { privateBackendEnvironment } from './startup';
import { CodexBridge } from './bridge';
import { findCodexBackend, tapBackend } from './stdio-tap';
import { bundledEnginePath } from './platform';
Expand Down Expand Up @@ -292,9 +293,7 @@ export async function activate(context: vscode.ExtensionContext) {
}
const directory = join(runtimeRoot, 'logins', randomUUID()); await mkdir(directory, { recursive: true, mode: 0o700 });
await writeFile(join(directory, 'config.toml'), 'cli_auth_credentials_store = "file"\n[analytics]\nenabled = false\n', { mode: 0o600 });
const loginEnvironment: NodeJS.ProcessEnv = { ...process.env, CODEX_HOME: directory, CODEX_SQLITE_HOME: directory };
delete loginEnvironment.OPENAI_API_KEY; delete loginEnvironment.CODEX_API_KEY; delete loginEnvironment.ELECTRON_RUN_AS_NODE;
const child = spawnExecutable(engine, ['app-server'], { env: loginEnvironment });
const child = spawnExecutable(engine, ['app-server'], { env: privateBackendEnvironment(directory) });
child.stderr.resume(); const lines = new JsonLines(child.stdout, child.stdin); const rpc = new RpcPeer(lines, 'login:');
try {
await rpc.request('initialize', { clientInfo: { name: 'multi_codex_login', version: extensionVersion } }); lines.send({ method: 'initialized' });
Expand Down
8 changes: 4 additions & 4 deletions extension/src/startup.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { chmod, copyFile, mkdir, readFile, symlink, writeFile } from 'node:fs/promises';
import { isAbsolute, join } from 'node:path';

export function privateBackendEnvironment(home: string, inherited = process.env): NodeJS.ProcessEnv {
const env = Object.fromEntries(Object.entries(inherited).filter(([key]) => !/^(?:OPENAI_|CODEX_)/i.test(key)));
delete env.ELECTRON_RUN_AS_NODE; delete env.NODE_OPTIONS;
return { ...env, CODEX_HOME: home, CODEX_SQLITE_HOME: home };
export function privateBackendEnvironment(home: string, inherited = process.env, historyHome = home): NodeJS.ProcessEnv {
const env = Object.fromEntries(Object.entries(inherited).filter(([key]) =>
!/^(?:OPENAI_|CODEX_)|^(?:ELECTRON_RUN_AS_NODE|NODE_OPTIONS)$/i.test(key)));
return { ...env, CODEX_HOME: home, CODEX_SQLITE_HOME: historyHome };
}

/** The launch home can be a desktop account; it is separate from shared account storage. */
Expand Down
5 changes: 2 additions & 3 deletions extension/src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { extensionVersion } from './version';
import { spawnExecutable, terminateExecutable } from './native';
import { JsonLines, RpcPeer } from './protocol';
import { privateBackendEnvironment } from './startup';

export async function withAccountBackend<T>(engine: string, home: string, action: (rpc: RpcPeer) => Promise<T>): Promise<T> {
const env: NodeJS.ProcessEnv = { ...process.env, CODEX_HOME: home, CODEX_SQLITE_HOME: home };
delete env.OPENAI_API_KEY; delete env.CODEX_API_KEY; delete env.ELECTRON_RUN_AS_NODE;
const child = spawnExecutable(engine, ['app-server'], { env });
const child = spawnExecutable(engine, ['app-server'], { env: privateBackendEnvironment(home) });
child.stderr.resume(); const lines = new JsonLines(child.stdout, child.stdin); const rpc = new RpcPeer(lines, 'worker:');
child.on('error', () => rpc.close()); child.on('exit', () => rpc.close());
try {
Expand Down
22 changes: 20 additions & 2 deletions extension/tests/bridge.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,37 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { createRequire } from 'node:module';
const { controlEndpoint, spawnExecutable, CodexBridge, JsonLines, RpcPeer, BridgeClient } = createRequire(import.meta.url)('../dist/core.cjs');
async function setup(t) {
async function setup(t, historyHome) {
const root = await mkdtemp(join(tmpdir(), 'mc-bridge-test-'));
const engine = resolve('tests/fixtures/fake-engine.mjs'); const helper = resolve('tests/fixtures/fake-accounts.mjs');
await chmod(engine, 0o755); await chmod(helper, 0o755); await mkdir(join(root, 'home'));
const input = new PassThrough(); const output = new PassThrough();
const bridge = new CodexBridge({ engine, helper, dataRoot: root, globalHome: root, sessionHome: join(root, 'home'), socket: controlEndpoint(root.replace(/[^a-zA-Z0-9]/g, '')), token: 'private-test-token', workspace: root }, new JsonLines(input, output), ['app-server']);
const bridge = new CodexBridge({ engine, helper, dataRoot: root, globalHome: root, sessionHome: join(root, 'home'), historyHome, socket: controlEndpoint(root.replace(/[^a-zA-Z0-9]/g, '')), token: 'private-test-token', workspace: root }, new JsonLines(input, output), ['app-server']);
const peer = new RpcPeer(new JsonLines(output, input), 'frontend:');
await bridge.listen(); await peer.request('initialize'); input.write(JSON.stringify({ method: 'initialized' }) + '\n');
const client = await BridgeClient.connect(bridge.config.socket, bridge.config.token);
t.after(async () => { client.dispose(); peer.close(); await bridge.dispose(); await rm(root, { recursive: true, force: true }); });
return { bridge, client, peer };
}
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
test('isolated backend removes inherited provider overrides and keeps its configured history', async t => {
const keys = ['OPENAI_BASE_URL', 'CODEX_PROVIDER_FIXTURE', 'NODE_OPTIONS'];
const previous = keys.map(key => process.env[key]);
const marker = '--no-warnings';
for (const key of keys) process.env[key] = marker;
const historyHome = resolve('tests/fixtures');
const { bridge, peer } = await (async () => {
try { return await setup(t, historyHome); }
finally {
for (const [index, key] of keys.entries()) {
if (previous[index] === undefined) delete process.env[key];
else process.env[key] = previous[index];
}
}
})();
assert.deepEqual(await peer.request('fixture/environment', { marker }), { inheritedOverride: false });
assert.deepEqual(await peer.request('fixture/homes'), { home: bridge.config.sessionHome, history: historyHome });
});
test('shared account handoff stops the old backend and keeps account files and histories private', async t => {
const root = await mkdtemp(join(tmpdir(), 'mc-shared-handoff-'));
const { syntheticAuth } = await import('./fixtures/local-service.mjs');
Expand Down
3 changes: 3 additions & 0 deletions extension/tests/fixtures/fake-engine.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ for await (const line of createInterface({ input: process.stdin })) {
result = { held: !!held };
} else if (message.method === 'fixture/homes') {
result = { home: process.env.CODEX_HOME, history: process.env.CODEX_SQLITE_HOME };
} else if (message.method === 'fixture/environment') {
result = { inheritedOverride: ['OPENAI_BASE_URL', 'CODEX_PROVIDER_FIXTURE', 'NODE_OPTIONS']
.some(key => process.env[key] === message.params?.marker) };
} else if (message.method === 'account/login/start') {
if (p.type === 'apiKey' && authMethod === 'chatgpt') { send({ id: message.id, error: { code: -1, message: 'External auth is active' } }); continue; }
if (mode === 'reject-all' || (mode === 'reject' && p.chatgptAccountId === 'synthetic-account-b')) { send({ id: message.id, error: { code: -1, message: 'Synthetic authentication failure' } }); continue; }
Expand Down
5 changes: 2 additions & 3 deletions tauri/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ use multi_codex_core::linux_desktops;
mod desktop_integration;
mod release_notes;
mod updater;
mod updater_policy;

pub use extension_accounts::{run_account_helper, run_bridge_launcher};

Expand Down Expand Up @@ -534,10 +535,8 @@ fn begin_device_login(
}
};
let mut child = process::spawn(
Command::new(codex)
process::isolated_codex_home(&mut Command::new(codex), &pending.codex_home)
.args(["login", "--device-auth"])
.env("CODEX_HOME", &pending.codex_home)
.env("CODEX_SQLITE_HOME", &pending.codex_home)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped()),
Expand Down
Loading
Loading