Skip to content

Commit db99669

Browse files
committed
fix(cli): require the client listener role for direct-client proofs
A direct client's credential could be authorized by any listener of the same home that answered the ownership challenge. Carry the proven listener's client role into the proof and refuse direct-client injection without it.
1 parent d16472f commit db99669

4 files changed

Lines changed: 19 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 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.
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 must prove its own client machine listener (another listener of the same installation does not count) 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: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ import { codexHasOtherTokenConsumers, codexTokenConfigShapeIsSafe } from "./code
1212
import { codexLaunchHomeIsOwned, codexLaunchProjectAliasIsOwned, codexLaunchSystemNamespaceIsSafe } from "./codex-launch-ownership";
1313
import type { CodexTokenRefusal, CodexTokenRefusalReporter } from "./codex-launch-diagnostics";
1414

15-
export type CodexRuntimeAttestation = Readonly<{ origin: string }>;
15+
/** role is the listener's self-reported role for the same pid/port the challenge proved. */
16+
export type CodexRuntimeAttestation = Readonly<{ origin: string; role?: "client" }>;
1617

1718
/** Retain the exact dial endpoint that answered the ownership challenge, not just its verdict. */
1819
export async function attestCodexRuntime(
@@ -22,7 +23,8 @@ export async function attestCodexRuntime(
2223
const snapshot = Object.freeze({ ...live });
2324
try {
2425
const origin = new URL(`http://${probeHostname(snapshot.probeHostname ?? snapshot.hostname)}:${snapshot.port}`).origin;
25-
return await prove(snapshot) === "proven" ? Object.freeze({ origin }) : null;
26+
if (await prove(snapshot) !== "proven") return null;
27+
return Object.freeze(snapshot.role === "client" ? { origin, role: "client" as const } : { origin });
2628
} catch { return null; }
2729
}
2830

@@ -72,6 +74,9 @@ export function codexCredentialDestinationIsTrusted(home: string, systemNamespac
7274
const connection = readClientConnectionState();
7375
if (connection.kind !== "connected" || connection.value.transport === "link") return refuse("connection");
7476
target = validateCodexRoutingTarget({ baseUrl: `${connection.value.serverUrl}/v1`, requiresAdmissionToken: true, tokenEnv: "OPENCODEX_API_AUTH_TOKEN" });
77+
// Only this home's client machine listener may vouch for a direct client; a leftover
78+
// standalone or hub listener from the same home proves the home, not the client.
79+
if (runtimeAttestation?.role !== "client") return refuse("destination");
7580
destinationIsProvenListener = false;
7681
}
7782
const url = new URL(target.baseUrl);

‎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). 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.
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; the proof must come from a listener that reports the client role, so a leftover standalone or hub listener of the same home does not qualify. 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: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ describe("Codex runtime endpoint binding", () => {
5050
}
5151
});
5252

53+
test("a proof keeps the client role only when the proven listener reported it", async () => {
54+
expect(await attestCodexRuntime({ ...live, role: "client" }, async () => "proven")).toEqual({ origin, role: "client" });
55+
expect(await attestCodexRuntime({ ...live, role: "hub" }, async () => "proven")).toEqual({ origin });
56+
expect(await attestCodexRuntime(live, async () => "proven")).toEqual({ origin });
57+
expect(await attestCodexRuntime({ ...live, role: "client" }, async () => "unproven")).toBeNull();
58+
});
59+
5360
test("direct-client destination matching is independent of the local machine port", () => {
5461
const local = standaloneCodexRoutingTarget(12200, { hostname: "0.0.0.0" });
5562
const direct = validateCodexRoutingTarget({ baseUrl: `${origin}/v1`, requiresAdmissionToken: true, tokenEnv: "OPENCODEX_API_AUTH_TOKEN" });
@@ -152,14 +159,15 @@ for (const client of [false, true]) codexLaunchOwnershipTest(`${client ? "direct
152159
for (const port of [12199, 12200]) {
153160
let reads = 0;
154161
const result = buildCodexPrivateFixtureLaunchEnv({ CODEX_HOME: home }, {
155-
routingKind: "opencodex-local", runtimeAttestation: { origin: `http://127.0.0.1:${port}` },
162+
routingKind: "opencodex-local", runtimeAttestation: { origin: `http://127.0.0.1:${port}`, ...(client ? { role: "client" as const } : {}) },
156163
serviceToken: () => { reads++; return token; },
157164
});
158165
const injected = client || port === 12199;
159166
expect(reads).toBe(injected ? 1 : 0);
160167
expect(result.OPENCODEX_API_AUTH_TOKEN).toBe(injected ? token : undefined);
161168
}
162-
for (const runtimeAttestation of [null, undefined]) {
169+
// A same-home listener that is not the client machine listener cannot vouch for a direct client.
170+
for (const runtimeAttestation of [null, undefined, ...(client ? [{ origin: "http://127.0.0.1:12200" }] : [])]) {
163171
let reads = 0;
164172
const result = buildCodexPrivateFixtureLaunchEnv({ CODEX_HOME: home }, { routingKind: "opencodex-local", runtimeAttestation, serviceToken: () => { reads++; return token; } });
165173
expect(reads).toBe(0);

0 commit comments

Comments
 (0)