Skip to content

Commit 111ac60

Browse files
committed
fix(cli): keep direct-client launches on their own listener proof
A direct client's ownership proof comes from its machine listener, while Codex dials the hub URL, so comparing the two always withheld the client credential. Bind the proof origin to the destination only for standalone installations; direct clients still require a proven local runtime and keep their connection-state and loopback checks.
1 parent 85c0931 commit 111ac60

4 files changed

Lines changed: 18 additions & 6 deletions

File tree

‎docs-site/src/content/docs/reference/cli/agents.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -990,7 +990,7 @@ Alternatively, supply the key yourself, for example by exporting `OPENCODEX_API_
990990

991991
Use `--` before a single-word prompt so it cannot select an unknown Codex subcommand.
992992

993-
Automatic credentials also require a fresh ownership proof from the exact HTTP origin in the managed Codex provider configuration. A running proxy on a different port or loopback address does not authorize that destination. Direct clients use their saved server URL for this comparison. If the destinations differ, the launcher withholds the automatic token and leaves routing unchanged.
993+
Automatic credentials also require a fresh ownership proof from this installation's running listener. For a standalone proxy, the proof must come from the exact HTTP origin in the managed Codex provider configuration; a running proxy on a different port or loopback address does not authorize that destination. A direct client proves its own machine listener and keeps its saved server URL checks, because the server it dials is a different installation. Without a matching proof, the launcher withholds the automatic token and leaves routing unchanged.
994994

995995
The machine configuration namespace must also prevent other users from creating missing system files. An unprotected Windows ProgramData/OpenAI/Codex namespace withholds automatic credentials; the launcher does not create it. macOS accepts deny-only and read-only allow ACLs, but refuses any allow entry granting write, append, delete, attribute/security changes or ownership changes, even after a deny entry. Unknown tags and inspection errors refuse.
996996

‎src/cli/codex-launch-auth.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,16 +64,20 @@ export function codexCredentialDestinationIsTrusted(home: string, systemNamespac
6464
if (diagnostics.error || diagnostics.source === "fallback") return refuse("installationConfig");
6565
const cfg = diagnostics.config;
6666
let target = standaloneCodexRoutingTarget(cfg.port, cfg);
67+
// A direct client's proof comes from its own machine listener, never from the hub it
68+
// dials, so only a standalone destination can be compared with the proven origin.
69+
let destinationIsProvenListener = true;
6770
if (cfg.runtimeRole === "client") {
6871
// Direct clients bind to persisted connection state; link clients use an authless relay.
6972
const connection = readClientConnectionState();
7073
if (connection.kind !== "connected" || connection.value.transport === "link") return refuse("connection");
7174
target = validateCodexRoutingTarget({ baseUrl: `${connection.value.serverUrl}/v1`, requiresAdmissionToken: true, tokenEnv: "OPENCODEX_API_AUTH_TOKEN" });
75+
destinationIsProvenListener = false;
7276
}
7377
const url = new URL(target.baseUrl);
7478
if (!target.requiresAdmissionToken) return refuse("admission");
7579
if (url.protocol !== "http:" || !["127.0.0.1", "[::1]"].includes(url.hostname)) return refuse("loopback");
76-
if (!codexRuntimeAttestationMatchesTarget(target.baseUrl, runtimeAttestation)) return refuse("destination");
80+
if (destinationIsProvenListener && !codexRuntimeAttestationMatchesTarget(target.baseUrl, runtimeAttestation)) return refuse("destination");
7781
const content = readBoundedCodexConfig(join(home, "config.toml"));
7882
if (content === null) return refuse("configRead");
7983
const config = Bun.TOML.parse(content) as Record<string, unknown>;

‎structure/cli-management.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Same-file project aliases additionally require ownership/ACL inspection of the l
3434

3535
For fresh credentials, the launcher resolves a native literal `CODEX_HOME` once and passes the canonical absolute directory both to the destination verifier and to the child. Missing, unreadable or non-directory homes and ambiguous Windows home casing withhold credentials. Any nonempty inherited HTTP(S)/ALL proxy variable, matched case-insensitively, suppresses token reads irrespective of NO_PROXY; denied and inherited-token launches preserve their environment. Successful injection adds both allowed loopback IPs to identical child NO_PROXY/no_proxy values while preserving prior bypass entries, covering default OS proxy discovery. Configured `features.respect_system_proxy` and feature-changing argv suppress loading because system-selected routes can ignore bypasses.
3636

37-
`src/cli/codex-launcher.ts` implements `ocx codex` without rewriting routing. Native/foreign routes pass through; local/unknown routes attempt startup and warn on failure. Fast paths skip startup/token loading. A matched wrapper uses its backing directly. Unknown state, including a throwing inspector, requires a separate bypass check via `src/cli/codex-launch-command.ts`; managed Windows CMD wrappers require complete generated-template equality before the selected absolute path executes with bypass. Obsolete, unreadable or ambiguous wrappers and lookup errors refuse launch without exception contents. A missing executable instead reports the Codex install hint, including on help/version fast paths. This content check does not establish Windows backing provenance or prevent concurrent replacement. Before loading a fresh service token, the ensured listener must prove possession of this home's runtime-record attestation secret for its exact pid and port; a public health marker or failed ensure never authorizes credential loading. The successful proof retains an immutable origin snapshot using the actual probe address (including recovery probe overrides). That origin must match the final provider destination after resolving standalone configuration or persisted direct-client state; IPv4 and IPv6 recipients remain distinct. A mismatched or missing proof withholds the token before the key file is read, without rewriting routing. `src/cli/codex-launch-auth.ts` separately requires a parsed managed transport block matching this installation's loopback listener or persisted local client connection; names/comments alone grant no token. Profiles, distinct project layers scanned through the filesystem root, destination-changing argv and environment overrides prevent automatic loading. An existing ancestor config is excluded only when its realpath matches the home config; a different file or failed identity resolution refuses. Token-file overrides and management-token collisions remain refused; user exports are preserved. No token enters argv or diagnostics.
37+
`src/cli/codex-launcher.ts` implements `ocx codex` without rewriting routing. Native/foreign routes pass through; local/unknown routes attempt startup and warn on failure. Fast paths skip startup/token loading. A matched wrapper uses its backing directly. Unknown state, including a throwing inspector, requires a separate bypass check via `src/cli/codex-launch-command.ts`; managed Windows CMD wrappers require complete generated-template equality before the selected absolute path executes with bypass. Obsolete, unreadable or ambiguous wrappers and lookup errors refuse launch without exception contents. A missing executable instead reports the Codex install hint, including on help/version fast paths. This content check does not establish Windows backing provenance or prevent concurrent replacement. Before loading a fresh service token, the ensured listener must prove possession of this home's runtime-record attestation secret for its exact pid and port; a public health marker or failed ensure never authorizes credential loading. The successful proof retains an immutable origin snapshot using the actual probe address (including recovery probe overrides). For a standalone installation that origin must match the final provider destination; IPv4 and IPv6 recipients remain distinct. A direct client's proof comes from its machine listener, so its persisted hub URL is not compared with the proven origin and keeps the connection-state and loopback checks instead. A mismatched or missing proof withholds the token before the key file is read, without rewriting routing. `src/cli/codex-launch-auth.ts` separately requires a parsed managed transport block matching this installation's loopback listener or persisted local client connection; names/comments alone grant no token. Profiles, distinct project layers scanned through the filesystem root, destination-changing argv and environment overrides prevent automatic loading. An existing ancestor config is excluded only when its realpath matches the home config; a different file or failed identity resolution refuses. Token-file overrides and management-token collisions remain refused; user exports are preserved. No token enters argv or diagnostics.
3838

3939
The `codex` namespace forwards all help arguments unchanged; `ocx help codex` retains wrapper help. It skips root shim repair so the routing-aware launcher owns the handoff. Every handoff, including help/version and passthrough, awaits the [execution trust contract](clients/chatgpt-desktop.md#codex-app-execution-trust) for the selected backing and spawns the returned invocation. On macOS, CLI handoffs verify any enclosing `.app` at the canonical target location, including renamed bundles and symlink targets; nested apps retain the outer bundle root. Fast paths bypass startup and credential loading, not executable validation. The hidden `internal codex-exec-target` helper returns a single verified path for the generated app-server launcher; its strict `--bundle-root` mode retains the discovered root independent of bundle name and refuses malformed roots without falling back to generic classification. It skips root shim auto-repair even on malformed arguments, and stays outside public capability discovery.
4040
Forwarded `-c`/`--config` and `-p`/`--profile` overrides make effective routing unverified for automatic service-token injection. They retain original argv and user-exported credentials but never load a new token from disk. Single-word prompts require `--` so they cannot select an unknown native subcommand. Missing system files also require a protected namespace: the closest existing directory must prevent another user from creating the missing layer, and its ancestors must prevent replacement. A normal Windows ProgramData directory that grants Users directory creation cannot authorize an absent OpenAI/Codex namespace; the launcher withholds credentials without creating or changing that directory. macOS opens each validated entry without following its final link (O_SYMLINK for the link entry itself), keeps dev/ino as bigint and requires descriptor dev/ino/type to match its original lstat, and reads its ACL with acl_get_fd_np. Only NULL with immediately captured ENOENT on this descriptor query means no extended ACL; open/stat/identity/close failures and every other NULL/error refuse. Every opened descriptor closes in finally. For a present ACL it validates and enumerates every entry through the documented -1/EINVAL terminator. Deny-only and read-only allow entries are accepted; any allow granting write/add-file, append/add-subdirectory, delete, delete-child, attribute, extended-attribute, security or ownership mutation refuses regardless of earlier denies. Unknown tags and FFI/enumeration failures refuse. Forced managed-preference checks remain mandatory. Pure policy and Darwin-gated native ACL coverage lives in `tests/codex-integration/codex-launcher-darwin-acl.test.ts`; modeled IO regressions for all three walks live in `tests/codex-integration/codex-launcher-darwin-identity.test.ts`. Tests model a protected empty machine namespace inside their private fixture; they do not modify real system configuration. Windows fixtures probe ancestor ownership before positive assertions; an unavailable protected location requires a proved ownership refusal and an explicit skip reason. Negative mutations and no-token/zero-read assertions execute even with unsafe ancestors; credential-file negatives bypass destination verification independently. Native checks use production defaults.

‎tests/codex-integration/codex-launcher-endpoint.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,16 +146,24 @@ function configurationFixture(client: boolean, run: (home: string) => void) {
146146
}
147147
}
148148

149-
for (const client of [false, true]) codexLaunchOwnershipTest(`${client ? "direct client" : "standalone"} binds proof to the final provider destination`, () => {
149+
// A direct client's proof comes from its machine listener (12200), never from the hub it dials (12199).
150+
for (const client of [false, true]) codexLaunchOwnershipTest(`${client ? "direct client requires its own listener proof" : "standalone binds proof to the final provider destination"}`, () => {
150151
configurationFixture(client, home => {
151152
for (const port of [12199, 12200]) {
152153
let reads = 0;
153154
const result = buildCodexPrivateFixtureLaunchEnv({ CODEX_HOME: home }, {
154155
routingKind: "opencodex-local", runtimeAttestation: { origin: `http://127.0.0.1:${port}` },
155156
serviceToken: () => { reads++; return token; },
156157
});
157-
expect(reads).toBe(port === 12199 ? 1 : 0);
158-
expect(result.OPENCODEX_API_AUTH_TOKEN).toBe(port === 12199 ? token : undefined);
158+
const injected = client || port === 12199;
159+
expect(reads).toBe(injected ? 1 : 0);
160+
expect(result.OPENCODEX_API_AUTH_TOKEN).toBe(injected ? token : undefined);
161+
}
162+
for (const runtimeAttestation of [null, undefined]) {
163+
let reads = 0;
164+
const result = buildCodexPrivateFixtureLaunchEnv({ CODEX_HOME: home }, { routingKind: "opencodex-local", runtimeAttestation, serviceToken: () => { reads++; return token; } });
165+
expect(reads).toBe(0);
166+
expect(result.OPENCODEX_API_AUTH_TOKEN).toBeUndefined();
159167
}
160168
writeFileSync(join(home, "managed_config.toml"), "");
161169
let reads = 0;

0 commit comments

Comments
 (0)