From e71d1ddf93bffb7f98911daa45fcbe53f4ebf962 Mon Sep 17 00:00:00 2001 From: Gauge Date: Fri, 4 Dec 2026 18:37:30 +0000 Subject: [PATCH 1/4] feat(server): serve only on a unix socket with OPENCODEX_UNIX_SOCKET (AGE-6145) With the env set to an absolute path (at most 104 bytes), `ocx start` binds only that unix socket (mode 0600; a stale socket is replaced, a non-socket is refused) and opens no TCP listener: Claude intercept gets requested port 0, the hub link listener is not started, and the CLI skips the liveness fence, port choice and TCP bind probes. Refused beside the unauthenticated loopback listener or hub.managementIngress. Unset: unchanged. Cache/quota impact: none; no routing, account, retry or cache-key code touched. Co-Authored-By: Claude Opus 5.5 (1M context) --- FORK-DELTA.md | 1 + src/cli/index.ts | 7 +- src/server/index.ts | 8 +- src/server/index/optional-listeners.ts | 6 +- src/server/index/unix-socket-only.ts | 69 ++++++++++++++ tests/server/unix-socket-only.test.ts | 126 +++++++++++++++++++++++++ 6 files changed, 209 insertions(+), 8 deletions(-) create mode 100644 src/server/index/unix-socket-only.ts create mode 100644 tests/server/unix-socket-only.test.ts diff --git a/FORK-DELTA.md b/FORK-DELTA.md index 62d312871be..3e34ebc5c79 100644 --- a/FORK-DELTA.md +++ b/FORK-DELTA.md @@ -25,6 +25,7 @@ Working ledgers (per case, with commands and evidence) were kept outside the rep - **Observability**: the gated usage line (`8ca6f61ec5`) and the privacy-bounded refusal-shape log (`fae0ae4736`). Analytics `physicalBreakdown` and `redAlerts` plus the physical-attempt accounting used by summaries, health, the lab and route explainability. `p` Anthropic account labels (`326bdfd7f7`), `comboTargetAdvanced`, cache TTL attribution, the `codex-account-retry` kind, and request-incompatible route traces. - **Providers and state**: the `xai-apikey` identity (`de6381aa3b`), lower-only response-store environment bounds (`db4cf5cbef`), credit-journal expiry (`326e1a77b7`, co-authored by Gauge), Kimi `usages` precedence (`aa80674b33`), quota explanation (`af51f855b4`), the 20-minute Antigravity paste window (`d6d040ed32`), a 60-second API-key 429 cap, `.27` plan vocabulary for hosted `?quota=1`, and `--code` as an alias of `--headless`. - **Claude ingress**: hosted exact `count_tokens` (pin-respecting; the `.27` bug that counted on an unpinned pool account is fixed). `prompt_cache_key` on session and parent session. The 5-minute cache default in hosted mode. Image 413 shrink on the native lane. Native-only client tools are refused before send. +- **Unix-socket-only serving** (AGE-6145): with `OPENCODEX_UNIX_SOCKET=`, `ocx start` serves only on that socket (mode 0600, a stale socket is replaced, a non-socket at the path is refused) and opens no TCP listener: no Claude intercept (requested port 0), no hub link listener, no liveness fence, port choice or TCP bind probes. It refuses to start beside `unauthenticatedLoopbackListener` or `hub.managementIngress`. Why: several companies' OCX processes share one loopback inside a Fargate task, and OCX asks no key on loopback, so a TCP port would let one company call another's. Unset, behaviour is unchanged. No routing, account, retry or cache-key code is touched. ## Replaced by upstream (do not reapply) diff --git a/src/cli/index.ts b/src/cli/index.ts index 9e8a34ec936..2b74bc8f349 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -103,6 +103,7 @@ import { redactUrlForLog } from "../lib/redact"; import { dispatchCommand, decideBusyPreferredPort, decideStartExitTeardown, decideStartWithLiveOwner, startupLeftCodexNativeLine } from "./dispatch"; import { probeOwnerPastRestartParent, takeRestartHandoffMarkers } from "./restart-handoff"; import { AuxiliaryListenerBindError, findAvailablePort, isAddrInUse, PortUnavailableError, shouldPersistSelectedPort, waitForPortAvailable } from "../server/ports"; +import { unixSocketOnlyPath } from "../server/index/unix-socket-only"; import { findLiveProxy, proveLiveProxyOwnedByHome, @@ -529,7 +530,7 @@ async function handleStart(options: { block?: boolean } = {}) { } // Recovery rechecked liveness under its lease. This fence owns the bind decision: an // updater may have stopped the old runtime and acquired this lease for replacement. - const fencedLive = await findLiveProxy(START_OWNERSHIP_LIVENESS); + const unixSocketPath = unixSocketOnlyPath(), fencedLive = unixSocketPath !== undefined ? null : await findLiveProxy(START_OWNERSHIP_LIVENESS); // AGE-6145: unix-only mode opens and probes no TCP port if (fencedLive) { const decision = decideStartWithLiveOwner({ livePort: fencedLive.port, @@ -552,7 +553,7 @@ async function handleStart(options: { block?: boolean } = {}) { // Port selection is check-then-bind. The lease prevents every cooperating start or // updater from turning that check into a different ownership decision. - let port = await chooseListenPort(requestedPort, { sibling: siblingStart }); + let port = unixSocketPath !== undefined ? requestedPort ?? loadConfig().port ?? 10100 : await chooseListenPort(requestedPort, { sibling: siblingStart }); // unix mode: the port is only a label raiseWindowsProxyPriority(); const serverModule = await import("../server"); const readinessGate = createReadinessGate(); @@ -583,7 +584,7 @@ async function handleStart(options: { block?: boolean } = {}) { console.error(`❌ ${err.message}`); throw new StartCommandExit(1); } - if (err instanceof AuxiliaryListenerBindError || !isAddrInUse(err) || attempt >= 2) throw err; + if (unixSocketPath !== undefined || err instanceof AuxiliaryListenerBindError || !isAddrInUse(err) || attempt >= 2) throw err; if (requestedPort !== undefined) { console.log(`⚠️ Port ${port} was taken while starting; waiting to retry the same port...`); const hostname = config.hostname ?? "127.0.0.1"; diff --git a/src/server/index.ts b/src/server/index.ts index 4c35abbeea3..b17c14393cc 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -203,7 +203,7 @@ import { } from "../lib/local-management-attestation"; import { createReadinessGate, type ReadinessGate } from "./readiness"; import { createServeOptions, type ServerIngress } from "./index/serve-options"; -import { createOptionalListenerSet, LINK_INGRESS_HOSTNAME } from "./index/optional-listeners"; +import { createOptionalListenerSet, LINK_INGRESS_HOSTNAME, serveOnUnixSocket, unixSocketOnlyPathFor } from "./index/optional-listeners"; import { matchVideoRoute } from "../lib/video-routes"; import { createPackageTreeIntegrityGuardForServer } from "./index/package-tree-guard"; import { inspectStartupOwnership, logProxyEndpoints, resolveInboundBodyLimitWithWarning, setStartupCacheInvalidationWrite, warnAgentTaskRecoveryStartup, warnPlaintextV2AgentMessagesStartup, type StartServerDeps } from "./index/startup-warnings"; @@ -350,7 +350,7 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe // fixed: the kernel loopback bind is the trust boundary that permits Tailscale identity headers. const managementIngress = config.runtimeRole === "hub" ? config.hub?.managementIngress : undefined; const managementIngressPort = managementIngress?.enabled ? managementIngress.port : null; - + const unixSocketPath = unixSocketOnlyPathFor(config); // AGE-6145: validated before any bind; serves only on the socket /** * Which listener a request arrived on, expressed as the only thing that differs: the bind * address the auth and CORS decisions should see. @@ -688,7 +688,7 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe get remoteWorkspaceStopping() { return remoteWorkspaceStopping; }, }); - server = spendLedgerLifecycle.track(Bun.serve({ ...serveOptions, port: listenPort, hostname: bindHost })); + server = spendLedgerLifecycle.track(unixSocketPath !== undefined ? serveOnUnixSocket(unixSocketPath, unix => Bun.serve({ ...serveOptions, unix })) : Bun.serve({ ...serveOptions, port: listenPort, hostname: bindHost })); // Both binds are one startup transaction (#1102). If the loopback bind fails after the // public one succeeded, leaving the public listener up would strand it: the CLI's port // retry would read the failure as a public-port conflict and pick a different port, @@ -731,7 +731,7 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe } } configureInboundBodyBudget(config.maxConcurrentInboundBodyBytes); - optionalListeners.start({ config, publicPort: server.port ?? listenPort, requestedPort: listenPort, startProxy: deps.startClaudeInterceptProxy, + optionalListeners.start({ config, publicPort: server.port ?? listenPort, requestedPort: unixSocketPath !== undefined ? 0 : listenPort, skipLinkListener: unixSocketPath !== undefined, startProxy: deps.startClaudeInterceptProxy, maxRequestBodySize: inboundBodyLimitBytes, dispatch: (req, requestServer) => serveOptions.fetch(req, requestServer), websocket: serveOptions.websocket, linkPolicy }); } catch (error) { unregisterQuotaAutoRefresh?.(); diff --git a/src/server/index/optional-listeners.ts b/src/server/index/optional-listeners.ts index 25dc13d979b..d3c3d82c0dd 100644 --- a/src/server/index/optional-listeners.ts +++ b/src/server/index/optional-listeners.ts @@ -33,11 +33,15 @@ export { LINK_INGRESS_HOSTNAME } from "./link-listener"; import type { ServerIngress } from "./serve-options"; import { linkHomeFeatures } from "../../remote/features"; +export { serveOnUnixSocket, unixSocketOnlyPathFor } from "./unix-socket-only"; + export interface OptionalListenerStartContext { startProxy?: typeof import("../../claude/intercept/connect-proxy").startConnectProxy; config: OcxConfig; publicPort: number; requestedPort?: number; + /** Unix-socket-only serving: the hub link listener binds TCP, so it is never started. */ + skipLinkListener?: boolean; maxRequestBodySize: number; dispatch: (req: Request, server: Server) => Promise; /** The shared Responses WebSocket handler and the hub-link policy, for the link WebSocket. */ @@ -198,7 +202,7 @@ export function createOptionalListenerSet(linkDeps: LinkListenerDeps = {}, start(ctx) { activeConfig = ctx.config; localControl.start({ config: ctx.config, publicPort: ctx.publicPort, dispatch: ctx.dispatch }); - linkListener.start({ dispatch: ctx.dispatch, maxRequestBodySize: ctx.maxRequestBodySize, + if (ctx.skipLinkListener !== true) linkListener.start({ dispatch: ctx.dispatch, maxRequestBodySize: ctx.maxRequestBodySize, connectionGeneration: linkId => supervisor.connectionGeneration?.(linkId), homeFeatures: () => linkHomeFeatures(activeConfig), ...(ctx.websocket && ctx.linkPolicy ? { responsesWebsocket: { diff --git a/src/server/index/unix-socket-only.ts b/src/server/index/unix-socket-only.ts new file mode 100644 index 00000000000..ef1c69ce094 --- /dev/null +++ b/src/server/index/unix-socket-only.ts @@ -0,0 +1,69 @@ +import { chmodSync, lstatSync, unlinkSync } from "node:fs"; +import { isAbsolute } from "node:path"; +import type { OcxConfig } from "../../types"; + +/** + * Unix-socket-only serving (AGE-6145). Several companies' OCX processes share one loopback inside + * a Fargate task, each as its own Linux user, and OCX asks no key on a loopback bind, so a TCP + * port would let one company call another's OCX. With this env set, `ocx start` serves ONLY on + * this socket path and opens no TCP listener. The socket file's mode (0600) is the access control. + */ +export const UNIX_SOCKET_ENV = "OPENCODEX_UNIX_SOCKET"; + +/** sockaddr_un.sun_path is 104 bytes on macOS/BSD and 108 on Linux; the smaller bound is the contract. */ +export const UNIX_SOCKET_PATH_MAX_BYTES = 104; + +/** The configured socket path, undefined when the env is unset or empty. Throws on a path that cannot bind. */ +export function unixSocketOnlyPath(env: NodeJS.ProcessEnv = process.env): string | undefined { + const path = env[UNIX_SOCKET_ENV]; + if (path === undefined || path === "") return undefined; + if (!isAbsolute(path)) throw new Error(`${UNIX_SOCKET_ENV} must be an absolute path`); + if (Buffer.byteLength(path) > UNIX_SOCKET_PATH_MAX_BYTES) { + throw new Error(`${UNIX_SOCKET_ENV} must be at most ${UNIX_SOCKET_PATH_MAX_BYTES} bytes`); + } + return path; +} + +/** `unixSocketOnlyPath` for a server start: also refuses the config that would add a TCP listener, before any bind. */ +export function unixSocketOnlyPathFor(config: OcxConfig): string | undefined { + const path = unixSocketOnlyPath(); + if (path !== undefined) assertUnixSocketOnlyCompatible(config); + return path; +} + +/** The unauthenticated loopback listener and the hub management ingress are TCP: refuse before any bind. */ +export function assertUnixSocketOnlyCompatible(config: OcxConfig): void { + if (config.unauthenticatedLoopbackListener?.enabled === true) { + throw new Error(`${UNIX_SOCKET_ENV} cannot be combined with unauthenticatedLoopbackListener (it is a TCP listener)`); + } + if (config.runtimeRole === "hub" && config.hub?.managementIngress?.enabled) { + throw new Error(`${UNIX_SOCKET_ENV} cannot be combined with hub.managementIngress (it is a TCP listener)`); + } +} + +/** Remove a stale socket left by a dead process. Anything that is not a socket (file, symlink, dir) is refused, never unlinked. */ +export function removeStaleUnixSocket(path: string): void { + let stat: ReturnType; + try { stat = lstatSync(path); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + throw error; + } + if (!stat.isSocket()) throw new Error(`${UNIX_SOCKET_ENV} path exists and is not a socket: ${path}`); + unlinkSync(path); +} + +/** + * Bind `path` as the only listener: replace a stale socket, serve with `unix` (no port, no hostname), + * then chmod 0600. A chmod failure stops the server before rethrowing so nothing is left bound. + * The private parent directory closes the bind-to-chmod window. + */ +export function serveOnUnixSocket( + path: string, serve: (unix: string) => S, +): S { + removeStaleUnixSocket(path); + const server = serve(path); + try { chmodSync(path, 0o600); } + catch (error) { void server.stop(true); throw error; } + return server; +} diff --git a/tests/server/unix-socket-only.test.ts b/tests/server/unix-socket-only.test.ts new file mode 100644 index 00000000000..995febd643a --- /dev/null +++ b/tests/server/unix-socket-only.test.ts @@ -0,0 +1,126 @@ +/** + * AGE-6145: with OPENCODEX_UNIX_SOCKET set, `ocx start` serves only on that unix socket and opens no + * TCP listener, so companies sharing one loopback cannot reach each other's OCX. These cases start a + * real server (as server-startup-codex-off.test.ts does) and prove the bind, the stale-socket rules, + * the path rules and the refusal beside the TCP-only loopback listener. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { connect } from "node:net"; +import { existsSync, lstatSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { startServer, waitForFailedStartRollback } from "../../src/server"; +import { UNIX_SOCKET_ENV, unixSocketOnlyPath } from "../../src/server/index/unix-socket-only"; +import { installIsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const baseConfig = { + providers: { fixture: { adapter: "openai-chat", baseUrl: "http://127.0.0.1:1/v1", allowPrivateNetwork: true } }, + defaultProvider: "fixture", port: 0, hostname: "127.0.0.1", + clientIntegrations: { codex: false }, checkForUpdates: false, + syncResumeHistory: false, claudeCode: { intercept: { enabled: false } }, +} as const; + +let home: string; +let dir: string; +let codex: ReturnType; +let priorHome: string | undefined; +let priorSocket: string | undefined; + +beforeEach(() => { + priorHome = process.env.OPENCODEX_HOME; + priorSocket = process.env[UNIX_SOCKET_ENV]; + home = mkdtempSync(join(tmpdir(), "ocx-unix-only-")); + dir = mkdtempSync(join(tmpdir(), "ocx-sock-")); + codex = installIsolatedCodexHome("ocx-unix-only-client-"); + process.env.OPENCODEX_HOME = home; +}); + +afterEach(() => { + codex.restore(); + if (priorHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = priorHome; + if (priorSocket === undefined) delete process.env[UNIX_SOCKET_ENV]; else process.env[UNIX_SOCKET_ENV] = priorSocket; + removeTreeWithRetry(home); + removeTreeWithRetry(dir); +}); + +/** A refused start must leave nothing to clean up; wait for any rollback the failed start began. */ +async function startRefused(): Promise { + try { startServer(0); } catch (error) { await waitForFailedStartRollback(error); return error; } + throw new Error("startServer was expected to refuse"); +} + +const tcpRefused = (port: number): Promise => new Promise(resolve => { + const socket = connect({ host: "127.0.0.1", port }); + socket.once("connect", () => { socket.destroy(); resolve(false); }); + socket.once("error", () => resolve(true)); +}); + +describe("unix-socket-only serving", () => { + test("binds the unix path, answers /healthz there, and opens no TCP listener", async () => { + const label = 48731; + const path = join(dir, "ocx.sock"); + saveConfig({ ...baseConfig, port: label }); + process.env[UNIX_SOCKET_ENV] = path; + const server = startServer(label); + try { + expect(server.port).toBeUndefined(); + expect(lstatSync(path).isSocket()).toBe(true); + expect(lstatSync(path).mode & 0o777).toBe(0o600); + const res = await fetch("http://localhost/healthz", { unix: path }); + expect(res.status).toBe(200); + expect(await tcpRefused(label)).toBe(true); + } finally { + await server.stop(true); + } + }); + + test("a stale socket file is replaced and a regular file or symlink is refused", async () => { + const path = join(dir, "ocx.sock"); + saveConfig(baseConfig); + process.env[UNIX_SOCKET_ENV] = path; + // A dead process leaves a socket file behind: bind in a child that exits without unlinking. + const bind = spawnSync("python3", ["-c", "import socket,sys;socket.socket(socket.AF_UNIX).bind(sys.argv[1])", path]); + expect(bind.status).toBe(0); + expect(lstatSync(path).isSocket()).toBe(true); + const server = startServer(0); + try { + expect((await fetch("http://localhost/healthz", { unix: path })).status).toBe(200); + } finally { + await server.stop(true); + } + + for (const make of [ + (p: string) => writeFileSync(p, "keep me"), + (p: string) => symlinkSync(join(dir, "elsewhere"), p), + ]) { + const blocked = join(dir, `blocked-${Math.random().toString(36).slice(2)}.sock`); + make(blocked); + process.env[UNIX_SOCKET_ENV] = blocked; + expect(String(await startRefused())).toContain("not a socket"); + expect(existsSync(blocked) || lstatSync(blocked).isSymbolicLink()).toBe(true); + } + }); + + test("a relative or over-long path is refused before any bind", async () => { + saveConfig(baseConfig); + process.env[UNIX_SOCKET_ENV] = "relative/ocx.sock"; + expect(String(await startRefused())).toContain("absolute"); + const tooLong = join(dir, "x".repeat(110)); + process.env[UNIX_SOCKET_ENV] = tooLong; + expect(String(await startRefused())).toContain("at most 104 bytes"); + expect(existsSync(tooLong)).toBe(false); + expect(unixSocketOnlyPath({ [UNIX_SOCKET_ENV]: "" })).toBeUndefined(); + }); + + test("refuses to start beside the unauthenticated loopback listener, binding nothing", async () => { + const path = join(dir, "ocx.sock"); + saveConfig({ ...baseConfig, unauthenticatedLoopbackListener: { enabled: true, port: 48732 } }); + process.env[UNIX_SOCKET_ENV] = path; + expect(String(await startRefused())).toContain("unauthenticatedLoopbackListener"); + expect(existsSync(path)).toBe(false); + expect(await tcpRefused(48732)).toBe(true); + }); +}); From d59ce76dc598adf53e936ed84d3fb17f5ac74a38 Mon Sep 17 00:00:00 2001 From: Gauge Date: Fri, 4 Dec 2026 18:42:04 +0000 Subject: [PATCH 2/4] fix(server): unix-socket-only refuses a fixed Claude intercept port (it would open TCP) (AGE-6145) Co-Authored-By: Claude Opus 5.5 (1M context) --- src/server/index/unix-socket-only.ts | 6 +++++- tests/server/unix-socket-only.test.ts | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/server/index/unix-socket-only.ts b/src/server/index/unix-socket-only.ts index ef1c69ce094..b6ab769d0f0 100644 --- a/src/server/index/unix-socket-only.ts +++ b/src/server/index/unix-socket-only.ts @@ -31,8 +31,12 @@ export function unixSocketOnlyPathFor(config: OcxConfig): string | undefined { return path; } -/** The unauthenticated loopback listener and the hub management ingress are TCP: refuse before any bind. */ +/** The unauthenticated loopback listener, the hub management ingress and a fixed Claude intercept port are TCP: refuse before any bind. */ export function assertUnixSocketOnlyCompatible(config: OcxConfig): void { + // Requested port 0 keeps the intercept off only while no fixed port is configured (claude-intercept-lifecycle.ts). + if (typeof config.claudeCode?.intercept?.port === "number") { + throw new Error(`${UNIX_SOCKET_ENV} cannot be combined with claudeCode.intercept.port (it is a TCP listener)`); + } if (config.unauthenticatedLoopbackListener?.enabled === true) { throw new Error(`${UNIX_SOCKET_ENV} cannot be combined with unauthenticatedLoopbackListener (it is a TCP listener)`); } diff --git a/tests/server/unix-socket-only.test.ts b/tests/server/unix-socket-only.test.ts index 995febd643a..88f857c64a9 100644 --- a/tests/server/unix-socket-only.test.ts +++ b/tests/server/unix-socket-only.test.ts @@ -123,4 +123,13 @@ describe("unix-socket-only serving", () => { expect(existsSync(path)).toBe(false); expect(await tcpRefused(48732)).toBe(true); }); + + test("refuses a fixed Claude intercept port, which would open TCP, binding nothing", async () => { + const path = join(dir, "ocx.sock"); + saveConfig({ ...baseConfig, claudeCode: { intercept: { port: 48733 } } } as any); + process.env[UNIX_SOCKET_ENV] = path; + expect(String(await startRefused())).toContain("claudeCode.intercept.port"); + expect(existsSync(path)).toBe(false); + expect(await tcpRefused(48733)).toBe(true); + }); }); From fe74fe95f5b799deb36b526c703cfb7ada9c6081 Mon Sep 17 00:00:00 2001 From: Gauge Date: Fri, 4 Dec 2026 18:42:16 +0000 Subject: [PATCH 3/4] docs(fork-delta): unix-socket-only also refuses a fixed intercept port (AGE-6145) Co-Authored-By: Claude Opus 5.5 (1M context) --- FORK-DELTA.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FORK-DELTA.md b/FORK-DELTA.md index 3e34ebc5c79..d9f56ce5fb7 100644 --- a/FORK-DELTA.md +++ b/FORK-DELTA.md @@ -25,7 +25,7 @@ Working ledgers (per case, with commands and evidence) were kept outside the rep - **Observability**: the gated usage line (`8ca6f61ec5`) and the privacy-bounded refusal-shape log (`fae0ae4736`). Analytics `physicalBreakdown` and `redAlerts` plus the physical-attempt accounting used by summaries, health, the lab and route explainability. `p` Anthropic account labels (`326bdfd7f7`), `comboTargetAdvanced`, cache TTL attribution, the `codex-account-retry` kind, and request-incompatible route traces. - **Providers and state**: the `xai-apikey` identity (`de6381aa3b`), lower-only response-store environment bounds (`db4cf5cbef`), credit-journal expiry (`326e1a77b7`, co-authored by Gauge), Kimi `usages` precedence (`aa80674b33`), quota explanation (`af51f855b4`), the 20-minute Antigravity paste window (`d6d040ed32`), a 60-second API-key 429 cap, `.27` plan vocabulary for hosted `?quota=1`, and `--code` as an alias of `--headless`. - **Claude ingress**: hosted exact `count_tokens` (pin-respecting; the `.27` bug that counted on an unpinned pool account is fixed). `prompt_cache_key` on session and parent session. The 5-minute cache default in hosted mode. Image 413 shrink on the native lane. Native-only client tools are refused before send. -- **Unix-socket-only serving** (AGE-6145): with `OPENCODEX_UNIX_SOCKET=`, `ocx start` serves only on that socket (mode 0600, a stale socket is replaced, a non-socket at the path is refused) and opens no TCP listener: no Claude intercept (requested port 0), no hub link listener, no liveness fence, port choice or TCP bind probes. It refuses to start beside `unauthenticatedLoopbackListener` or `hub.managementIngress`. Why: several companies' OCX processes share one loopback inside a Fargate task, and OCX asks no key on loopback, so a TCP port would let one company call another's. Unset, behaviour is unchanged. No routing, account, retry or cache-key code is touched. +- **Unix-socket-only serving** (AGE-6145): with `OPENCODEX_UNIX_SOCKET=`, `ocx start` serves only on that socket (mode 0600, a stale socket is replaced, a non-socket at the path is refused) and opens no TCP listener: no Claude intercept (requested port 0), no hub link listener, no liveness fence, port choice or TCP bind probes. It refuses to start beside `unauthenticatedLoopbackListener`, `hub.managementIngress` or a fixed `claudeCode.intercept.port`. Why: several companies' OCX processes share one loopback inside a Fargate task, and OCX asks no key on loopback, so a TCP port would let one company call another's. Unset, behaviour is unchanged. No routing, account, retry or cache-key code is touched. ## Replaced by upstream (do not reapply) From 737c5d85472eab5e834bb5a57466aeed276e6008 Mon Sep 17 00:00:00 2001 From: Gauge Date: Fri, 4 Dec 2026 18:53:24 +0000 Subject: [PATCH 4/4] fix(server): unix-socket-only sends nothing to a shared loopback port and binds a private socket (AGE-6145) Review findings: runtime Claude intercept start is refused (unix_socket_only) before any listener opens; OCX's own HTTP calls (claude-code state, advisor, routed describe, CLI management calls, direct local probes) go over the socket via selfFetch / directLocalHttpFetch; the socket is bound under umask 0177 in a parent directory that must be a real, own-uid, 0700 directory. Unset env: unchanged. Cache/quota impact: none; no routing, account, retry or cache-key code is touched. Co-Authored-By: Claude Opus 5.5 (1M context) --- FORK-DELTA.md | 2 +- src/advisor/consult.ts | 4 +- src/claude/gateway-cache.ts | 3 +- src/claude/intercept/runtime.ts | 2 +- src/cli/account-api.ts | 3 +- src/cli/claude.ts | 4 +- src/cli/debug.ts | 13 +- src/cli/index.ts | 4 +- src/cli/observe-stream.ts | 3 +- src/cli/runtime-api.ts | 3 +- src/cli/sync-link-status.ts | 3 +- src/lib/local-chat-completion.ts | 4 +- src/server/direct-local-http.ts | 12 +- .../index/claude-intercept-lifecycle.ts | 3 + src/server/index/unix-socket-only.ts | 56 ++++++++- .../management/claude-intercept-routes.ts | 2 + tests/server/unix-socket-only.test.ts | 113 +++++++++++++++++- 17 files changed, 208 insertions(+), 26 deletions(-) diff --git a/FORK-DELTA.md b/FORK-DELTA.md index d9f56ce5fb7..301e5f6d9b9 100644 --- a/FORK-DELTA.md +++ b/FORK-DELTA.md @@ -25,7 +25,7 @@ Working ledgers (per case, with commands and evidence) were kept outside the rep - **Observability**: the gated usage line (`8ca6f61ec5`) and the privacy-bounded refusal-shape log (`fae0ae4736`). Analytics `physicalBreakdown` and `redAlerts` plus the physical-attempt accounting used by summaries, health, the lab and route explainability. `p` Anthropic account labels (`326bdfd7f7`), `comboTargetAdvanced`, cache TTL attribution, the `codex-account-retry` kind, and request-incompatible route traces. - **Providers and state**: the `xai-apikey` identity (`de6381aa3b`), lower-only response-store environment bounds (`db4cf5cbef`), credit-journal expiry (`326e1a77b7`, co-authored by Gauge), Kimi `usages` precedence (`aa80674b33`), quota explanation (`af51f855b4`), the 20-minute Antigravity paste window (`d6d040ed32`), a 60-second API-key 429 cap, `.27` plan vocabulary for hosted `?quota=1`, and `--code` as an alias of `--headless`. - **Claude ingress**: hosted exact `count_tokens` (pin-respecting; the `.27` bug that counted on an unpinned pool account is fixed). `prompt_cache_key` on session and parent session. The 5-minute cache default in hosted mode. Image 413 shrink on the native lane. Native-only client tools are refused before send. -- **Unix-socket-only serving** (AGE-6145): with `OPENCODEX_UNIX_SOCKET=`, `ocx start` serves only on that socket (mode 0600, a stale socket is replaced, a non-socket at the path is refused) and opens no TCP listener: no Claude intercept (requested port 0), no hub link listener, no liveness fence, port choice or TCP bind probes. It refuses to start beside `unauthenticatedLoopbackListener`, `hub.managementIngress` or a fixed `claudeCode.intercept.port`. Why: several companies' OCX processes share one loopback inside a Fargate task, and OCX asks no key on loopback, so a TCP port would let one company call another's. Unset, behaviour is unchanged. No routing, account, retry or cache-key code is touched. +- **Unix-socket-only serving** (AGE-6145): with `OPENCODEX_UNIX_SOCKET=`, `ocx start` serves only on that socket (mode 0600, a stale socket is replaced, a non-socket at the path is refused) and opens no TCP listener: no Claude intercept (requested port 0), no hub link listener, no liveness fence, port choice or TCP bind probes. It refuses to start beside `unauthenticatedLoopbackListener`, `hub.managementIngress` or a fixed `claudeCode.intercept.port`. Why: several companies' OCX processes share one loopback inside a Fargate task, and OCX asks no key on loopback, so a TCP port would let one company call another's. Unset, behaviour is unchanged. No routing, account, retry or cache-key code is touched. In this mode the socket is created 0600 under umask 0177 inside a private (0700, own-uid, non-symlink) parent directory, runtime Claude intercept starts are refused (`unix_socket_only`), and OCX's own calls to its API (`selfFetch`, `directLocalHttpFetch`) go over the socket instead of the shared loopback port. ## Replaced by upstream (do not reapply) diff --git a/src/advisor/consult.ts b/src/advisor/consult.ts index c7f75d6163a..753a5022a5f 100644 --- a/src/advisor/consult.ts +++ b/src/advisor/consult.ts @@ -19,6 +19,8 @@ */ import type { OcxConfig } from "../types"; import { localInferenceDestination, selfFetchAdmissionToken, type LocalInferenceDestination } from "../lib/local-destinations"; +import { selfFetch } from "../server/index/unix-socket-only"; + import { cancelBodyOnAbort } from "../lib/abort"; import { advisorBackoffMs } from "./failure-backoff"; import { sidecarEnter } from "../lib/sidecar-tracker"; @@ -299,7 +301,7 @@ export async function consultAdvisor( try { policyRegistration = registerAdvisorAdmissionPolicy(admissionPolicy ?? captureAdmissionPolicy(config, undefined, admissionScope), linkedSignal.signal); headers[ADVISOR_ADMISSION_POLICY_HEADER] = policyRegistration.token; - const res = await fetch(`${baseUrlOverride ?? advisorBaseUrl(config)}/v1/chat/completions`, { + const res = await selfFetch(`${baseUrlOverride ?? advisorBaseUrl(config)}/v1/chat/completions`, { method: "POST", headers, body: JSON.stringify(requestBody), diff --git a/src/claude/gateway-cache.ts b/src/claude/gateway-cache.ts index fd341cb36e8..321011be1eb 100644 --- a/src/claude/gateway-cache.ts +++ b/src/claude/gateway-cache.ts @@ -17,6 +17,7 @@ import { mkdirSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { localAdmissionToken, localInferenceDestination } from "../lib/local-destinations"; +import { selfFetch } from "../server/index/unix-socket-only"; import { assertNotRealClaudeConfigUnderTest } from "../lib/test-home-guard"; import type { OcxConfig } from "../types"; @@ -117,7 +118,7 @@ export async function fetchGatewayModels( // ?ids=cli pins the readable claude-ocx id family deterministically (audit 051 // #5): the cache prewrite must not depend on UA sniffing. - const res = await (options.fetchImpl ?? fetch)(`${baseUrl}/v1/models?limit=1000&ids=cli`, { + const res = await (options.fetchImpl ?? (typeof portOrTarget === "number" ? selfFetch : fetch))(`${baseUrl}/v1/models?limit=1000&ids=cli`, { headers, signal: AbortSignal.timeout(options.timeoutMs ?? 3_000), }); diff --git a/src/claude/intercept/runtime.ts b/src/claude/intercept/runtime.ts index 90a35659726..0ae2e6190aa 100644 --- a/src/claude/intercept/runtime.ts +++ b/src/claude/intercept/runtime.ts @@ -46,7 +46,7 @@ const PICKER_AUTHORITY_ERROR_CODES = new Set([ export { CLAUDE_INTERCEPT_PORT_OFFSET, claudeInterceptEnabled, claudeInterceptProxyPort, claudePickerProxyPort } from "./port-policy"; -export type ClaudeInterceptOutcome = { ok: true; state: ClaudeInterceptState } | { ok: false; reason: "disabled" | "client_role" | "ephemeral_port" | "port_in_use" | "stopped" | "failed"; port?: number; message?: string }; +export type ClaudeInterceptOutcome = { ok: true; state: ClaudeInterceptState } | { ok: false; reason: "disabled" | "client_role" | "unix_socket_only" | "ephemeral_port" | "port_in_use" | "stopped" | "failed"; port?: number; message?: string }; export interface ClaudeInterceptState { pickerReason?: "port_in_use" | "failed" | null; diff --git a/src/cli/account-api.ts b/src/cli/account-api.ts index 2d425de7179..8eb95f914be 100644 --- a/src/cli/account-api.ts +++ b/src/cli/account-api.ts @@ -1,3 +1,4 @@ +import { selfFetch } from "../server/index/unix-socket-only"; import { configuredAnthropicInstance, isAnthropicOAuthInstance } from "../providers/anthropic-instance"; import { parseQuotaFailureCode, parseQuotaUnknownReason, type QuotaFailureCode, type QuotaUnknownReason, type ProviderQuota, type AccountQuotaMode } from "../providers/quota-types"; import { parseWeeklyWindowConflicts, type WeeklyWindowConflict } from "../codex/quota-window-conflict"; @@ -155,7 +156,7 @@ export async function apiJson( options: { signal?: AbortSignal; redirect?: RequestRedirect } = {}, ): Promise { if (baseUrl === LINK_HOME_BASE) return linkHomeApiJson(deps, method, path); - const fetchImpl = deps.fetchImpl ?? fetch; + const fetchImpl = deps.fetchImpl ?? selfFetch; // AGE-6145: admin token goes over the unix socket in unix-socket-only mode try { const res = await fetchImpl(`${baseUrl}${path}`, { method, diff --git a/src/cli/claude.ts b/src/cli/claude.ts index 891dd526431..d15655055d6 100644 --- a/src/cli/claude.ts +++ b/src/cli/claude.ts @@ -20,6 +20,8 @@ import { isProxyAdmissionSecret } from "../server/auth-cors"; import { findLiveProxy } from "../server/proxy-liveness"; import type { OcxConfig } from "../types"; import { configuredAdminToken } from "../lib/admin-secrets"; +import { selfFetch } from "../server/index/unix-socket-only"; + import { localAdmissionToken, localInferenceDestination, localLoopbackInferencePorts, localManagementOrigin } from "../lib/local-destinations"; import { PROXY_MARKER, ownAdmissionTokens, defaultAuthDetectDeps, detectClaudeAuth, resolveClaudeKeychainPresence, type AuthDetectDeps } from "../claude/auth-detect"; import { resolveClaudeAuthMode } from "../claude/auth-mode"; @@ -465,7 +467,7 @@ export async function fetchClaudeCodeState(config: OcxConfig, port: number, time const headers = new Headers(); const token = configuredAdminToken(); if (token) headers.set("x-opencodex-api-key", token); - const res = await fetch(`${localManagementOrigin(config, port)}/api/claude-code?view=launch`, { + const res = await selfFetch(`${localManagementOrigin(config, port)}/api/claude-code?view=launch`, { // AGE-6145: over the unix socket in unix-socket-only mode headers, signal: AbortSignal.timeout(timeoutMs), }); diff --git a/src/cli/debug.ts b/src/cli/debug.ts index 88a7386447e..7ffced5bff7 100644 --- a/src/cli/debug.ts +++ b/src/cli/debug.ts @@ -1,3 +1,4 @@ +import { selfFetch } from "../server/index/unix-socket-only"; import { findLiveProxy, probeHostname } from "../server/proxy-liveness"; import { DEBUG_ENV, type DebugSettingsView } from "../lib/debug-settings"; import { runningProxyUpdateHeaders } from "../oauth/login-cli"; @@ -24,7 +25,7 @@ async function requireLiveProxy() { async function fetchDebugSettings(): Promise { const live = await requireLiveProxy(); try { - const res = await fetch(`http://${probeHostname(live.hostname)}:${live.port}/api/debug`, { + const res = await selfFetch(`http://${probeHostname(live.hostname)}:${live.port}/api/debug`, { headers: runningProxyUpdateHeaders(), }); if (!res.ok) { @@ -40,7 +41,7 @@ async function fetchDebugSettings(): Promise { async function putDebugSettings(body: Record): Promise { const live = await requireLiveProxy(); - const res = await fetch(`http://${probeHostname(live.hostname)}:${live.port}/api/debug`, { + const res = await selfFetch(`http://${probeHostname(live.hostname)}:${live.port}/api/debug`, { method: "PUT", headers: runningProxyUpdateHeaders(), body: JSON.stringify(body), @@ -84,7 +85,7 @@ async function printProviderLogs(follow: boolean): Promise { let after = 0; try { - const res = await fetch(`${base}?limit=500`, { headers: runningProxyUpdateHeaders() }); + const res = await selfFetch(`${base}?limit=500`, { headers: runningProxyUpdateHeaders() }); if (!res.ok) { console.error(`Failed to read debug logs (${res.status})`); process.exit(1); @@ -102,7 +103,7 @@ async function printProviderLogs(follow: boolean): Promise { while (true) { await new Promise(resolve => setTimeout(resolve, 1000)); try { - const res = await fetch(`${base}?after=${after}&limit=500`, { headers: runningProxyUpdateHeaders() }); + const res = await selfFetch(`${base}?after=${after}&limit=500`, { headers: runningProxyUpdateHeaders() }); if (!res.ok) continue; const entries = await res.json() as { seq: number; line: string }[]; for (const entry of entries) console.log(entry.line); @@ -119,7 +120,7 @@ async function printUsageLogs(follow: boolean): Promise { let after = 0; try { - const res = await fetch(`${base}?limit=500`, { headers: runningProxyUpdateHeaders() }); + const res = await selfFetch(`${base}?limit=500`, { headers: runningProxyUpdateHeaders() }); if (!res.ok) { console.error(`Failed to read usage debug logs (${res.status})`); process.exit(1); @@ -138,7 +139,7 @@ async function printUsageLogs(follow: boolean): Promise { while (true) { await new Promise(resolve => setTimeout(resolve, 1000)); try { - const res = await fetch(`${base}?after=${after}&limit=500`, { headers: runningProxyUpdateHeaders() }); + const res = await selfFetch(`${base}?after=${after}&limit=500`, { headers: runningProxyUpdateHeaders() }); if (!res.ok) continue; const entries = await res.json() as { seq: number; line: string }[]; for (const entry of entries) console.log(entry.line); diff --git a/src/cli/index.ts b/src/cli/index.ts index 2b74bc8f349..99e7bcfe1a0 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -103,7 +103,7 @@ import { redactUrlForLog } from "../lib/redact"; import { dispatchCommand, decideBusyPreferredPort, decideStartExitTeardown, decideStartWithLiveOwner, startupLeftCodexNativeLine } from "./dispatch"; import { probeOwnerPastRestartParent, takeRestartHandoffMarkers } from "./restart-handoff"; import { AuxiliaryListenerBindError, findAvailablePort, isAddrInUse, PortUnavailableError, shouldPersistSelectedPort, waitForPortAvailable } from "../server/ports"; -import { unixSocketOnlyPath } from "../server/index/unix-socket-only"; +import { unixSocketOnlyActive, unixSocketOnlyPath } from "../server/index/unix-socket-only"; import { findLiveProxy, proveLiveProxyOwnedByHome, @@ -761,7 +761,7 @@ async function handleStart(options: { block?: boolean } = {}) { // #7423: routing an update kept in place for this proxy is ours once the startup sync published. if (!siblingStart && startupSync.published) completeUpdateTeardownHandover(pid => isProcessAlive(pid) && isLikelyOcxProcess(pid)); await refreshOwnedRaycastCatalog(config, port); - if (!cleaned && !shuttingDown) healthSentinel = startServiceHealthSentinel(config); // after startup reconciliation; never mid-boot or mid-drain + if (!cleaned && !shuttingDown && !unixSocketOnlyActive()) healthSentinel = startServiceHealthSentinel(config); // AGE-6145: it probes /healthz over TCP; after startup reconciliation; never mid-boot or mid-drain // #1046: one warning per startup, after BOTH writes. The server's cache // invalidation happens first and the catalog sync second, so the mtime is only // final here — and neither write site warns on its own, or a boot that hits diff --git a/src/cli/observe-stream.ts b/src/cli/observe-stream.ts index 21890cba0ea..0742fa31b67 100644 --- a/src/cli/observe-stream.ts +++ b/src/cli/observe-stream.ts @@ -1,4 +1,5 @@ /** Bounded, serial observation of fixed management read surfaces. */ +import { selfFetch } from "../server/index/unix-socket-only"; import { readBoundedResponseBytes } from "../lib/bounded-body"; import { runningProxyUpdateHeaders } from "../oauth/login-cli"; import { findLiveProxy, type LiveProxy } from "../server/proxy-liveness"; @@ -112,7 +113,7 @@ export async function withObserveStream( const timer = setTimeout(abort, timeoutMs); try { signal.throwIfAborted(); - const responsePromise = (deps.fetchImpl ?? fetch)(`${origin}${path}?${query}`, { + const responsePromise = (deps.fetchImpl ?? selfFetch)(`${origin}${path}?${query}`, { method: "GET", headers: runningProxyUpdateHeaders(), credentials: "omit", redirect: "error", signal: request.signal, }); // A test transport or late fetch may settle after abort. Release its body too. diff --git a/src/cli/runtime-api.ts b/src/cli/runtime-api.ts index e05f6bd1cc1..685d1856d19 100644 --- a/src/cli/runtime-api.ts +++ b/src/cli/runtime-api.ts @@ -9,6 +9,7 @@ * - 다른 대안 대신 이 방식을 선택한 이유: GUI/CLI의 검증 규칙이 갈라지지 않고 fallback port도 안전하게 찾는다. * - 장점, 단점 및 영향: 동작 일관성이 높아지는 대신 live 관리 명령은 실행 중인 proxy가 필요하다. */ +import { selfFetch } from "../server/index/unix-socket-only"; import { findLiveProxy, probeHostname, type LivenessIo, type LiveProxy } from "../server/proxy-liveness"; import { runningProxyUpdateHeaders } from "../oauth/login-cli"; import { terminalSafeText } from "../lib/terminal-safe-text"; @@ -213,7 +214,7 @@ export async function runtimeRequest( } const headers = runningProxyUpdateHeaders(); for (const [key, value] of new Headers(init.headers).entries()) headers.set(key, value); - const fetchImpl = deps.fetchImpl ?? fetch; + const fetchImpl = deps.fetchImpl ?? selfFetch; // AGE-6145: admin token goes over the unix socket in unix-socket-only mode let response: Response; try { response = await fetchImpl(`${baseUrl}${path.startsWith("/") ? path : `/${path}`}`, { ...init, headers }); diff --git a/src/cli/sync-link-status.ts b/src/cli/sync-link-status.ts index e3dfd2fc613..6c390652ed0 100644 --- a/src/cli/sync-link-status.ts +++ b/src/cli/sync-link-status.ts @@ -1,3 +1,4 @@ +import { selfFetch } from "../server/index/unix-socket-only"; import { runningProxyUpdateHeaders } from "../oauth/login-cli"; import { runtimeBaseUrl, RuntimeApiError } from "./runtime-api"; import { validateStatus, type LinkStatusPayload } from "./link"; @@ -28,7 +29,7 @@ export async function readHomeLinkStatus(deadlineMs = 5000, deps: { if (!base) throw new LinkStatusError("home-runtime-not-running"); let response: Response; // wp2: children=1 adds each row's child block (activity, active job); an older Home ignores the query. - try { response = await (deps.fetchImpl ?? fetch)(`${base}/api/link/status?children=1`, { headers: (deps.headers ?? runningProxyUpdateHeaders)(), signal: controller.signal }); } + try { response = await (deps.fetchImpl ?? selfFetch)(`${base}/api/link/status?children=1`, { headers: (deps.headers ?? runningProxyUpdateHeaders)(), signal: controller.signal }); } catch (cause) { throw new LinkStatusError("home-link-status-unavailable", { cause }); } if (response.status === 401 || response.status === 403) throw new LinkStatusError("home-link-status-unauthorized"); if (!response.ok) throw new LinkStatusError("home-link-status-unavailable"); diff --git a/src/lib/local-chat-completion.ts b/src/lib/local-chat-completion.ts index 5a87947ae46..5b8354e22a3 100644 --- a/src/lib/local-chat-completion.ts +++ b/src/lib/local-chat-completion.ts @@ -21,6 +21,8 @@ import { sidecarEnter } from "./sidecar-tracker"; import { internalCallCapability } from "./local-internal-call-capability"; import { registerAdvisorAdmissionPolicy, SIDECAR_ADMISSION_POLICY_HEADER, SIDECAR_INTERNAL_CAPABILITY_HEADER } from "../server/advisor-admission-scope"; import { configuredPort } from "../server/auth-cors"; +import { selfFetch } from "../server/index/unix-socket-only"; + import type { CapturedAdmissionPolicy } from "../types/admission-policy"; export type LocalChatConfig = Pick; @@ -90,7 +92,7 @@ export async function postLocalChatCompletion(request: LocalChatCompletionReques registration = registerAdvisorAdmissionPolicy(request.admissionPolicy, linkedSignal.signal); headers[SIDECAR_ADMISSION_POLICY_HEADER] = registration.token; headers[SIDECAR_INTERNAL_CAPABILITY_HEADER] = internalCallCapability(); - const res = await fetch(`${request.baseUrlOverride ?? localChatCompletionBaseUrl(config)}/v1/chat/completions`, { + const res = await selfFetch(`${request.baseUrlOverride ?? localChatCompletionBaseUrl(config)}/v1/chat/completions`, { method: "POST", headers, body: JSON.stringify({ ...request.body, stream: false }), diff --git a/src/server/direct-local-http.ts b/src/server/direct-local-http.ts index 5cce0bba1b8..cbba05f28a1 100644 --- a/src/server/direct-local-http.ts +++ b/src/server/direct-local-http.ts @@ -1,4 +1,5 @@ import net, { type Socket } from "node:net"; +import { unixSocketOnlyPath } from "./index/unix-socket-only"; const DIRECT_LOCAL_HTTP_MAX_BYTES = 8 * 1024 * 1024; const DIRECT_LOCAL_HTTP_TIMEOUT_MS = 10_000; @@ -241,6 +242,13 @@ function parseResponse(bytes: Buffer): Response { }); } +/** A socket path nothing has bound reports ENOENT; as "nothing is listening" it must read as a refusal, like a free TCP port. */ +function connectUnixSocket(path: string): Socket { + const socket = net.createConnection({ path }); + socket.once("error", error => { if ((error as NodeJS.ErrnoException).code === "ENOENT") (error as NodeJS.ErrnoException).code = "ECONNREFUSED"; }); + return socket; +} + /** * Fetch one bodyless local HTTP GET or POST over a direct TCP connection. * @@ -346,7 +354,9 @@ export async function directLocalHttpFetch( settleAfterClose(error); }; - socket = (io.connect ?? ((host, selectedPort) => net.createConnection({ + // AGE-6145: in unix-socket-only mode a local request goes over the socket, never to a shared loopback TCP port. + const unixPath = io.connect ? undefined : unixSocketOnlyPath(); + socket = (io.connect ?? ((host, selectedPort) => unixPath !== undefined ? connectUnixSocket(unixPath) : net.createConnection({ host, port: selectedPort, autoSelectFamily: true, diff --git a/src/server/index/claude-intercept-lifecycle.ts b/src/server/index/claude-intercept-lifecycle.ts index b67ad17ed48..4c2e4d3157c 100644 --- a/src/server/index/claude-intercept-lifecycle.ts +++ b/src/server/index/claude-intercept-lifecycle.ts @@ -1,6 +1,7 @@ import type { Server } from "bun"; import type { OcxConfig } from "../../types"; import { getConfigDir } from "../../config/paths"; +import { unixSocketOnlyActive } from "./unix-socket-only"; import { discardPickerCaKey } from "../../claude/intercept/picker-ca"; import type { PickerRouteInput } from "../../claude/intercept/picker-models"; import { observeClaudeDesktopMode, type ClaudeDesktopModeObservation } from "../../claude/desktop-first-party"; @@ -85,6 +86,8 @@ export function createClaudeInterceptLifecycle(): ClaudeInterceptLifecycle const run = async (): Promise => { // Legacy key cleanup is independent of listener eligibility, including on-demand retries. try { discardPickerCaKey(opts.configDir ?? getConfigDir()); } catch { /* best-effort; retried on the next attempt */ } + // AGE-6145: the CONNECT proxy, TLS and picker listeners are TCP on a loopback shared with other companies. + if (unixSocketOnlyActive()) return { ok: false, reason: "unix_socket_only" }; if (opts.config.runtimeRole === "client") return { ok: false, reason: "client_role" }; if (!claudeInterceptEnabled(opts.config)) return { ok: false, reason: "disabled" }; if (opts.requestedPort === 0 && typeof opts.config.claudeCode?.intercept?.port !== "number") diff --git a/src/server/index/unix-socket-only.ts b/src/server/index/unix-socket-only.ts index b6ab769d0f0..30d184926de 100644 --- a/src/server/index/unix-socket-only.ts +++ b/src/server/index/unix-socket-only.ts @@ -1,5 +1,5 @@ import { chmodSync, lstatSync, unlinkSync } from "node:fs"; -import { isAbsolute } from "node:path"; +import { dirname, isAbsolute } from "node:path"; import type { OcxConfig } from "../../types"; /** @@ -24,6 +24,26 @@ export function unixSocketOnlyPath(env: NodeJS.ProcessEnv = process.env): string return path; } +/** True when the env asks for unix-socket-only mode. Never throws, so a refusal path can test it before any path rule runs. */ +export function unixSocketOnlyActive(env: NodeJS.ProcessEnv = process.env): boolean { + const path = env[UNIX_SOCKET_ENV]; + return path !== undefined && path !== ""; +} + +/** + * fetch for a call OCX makes to its OWN HTTP API. With the env set the call goes over the unix socket + * (URL rewritten to http://localhost, path and query kept): a loopback TCP port is shared between + * companies, so a credential or prompt sent there could reach another company's process. With the env + * unset this is plain fetch with the same arguments. + */ +export const selfFetch = ((input: string | URL | Request, init?: RequestInit): Promise => { + const socket = unixSocketOnlyPath(); + if (socket === undefined) return fetch(input, init); + const url = new URL(input instanceof Request ? input.url : String(input)); + const target = `http://localhost${url.pathname}${url.search}`; + return fetch(input instanceof Request ? new Request(target, input) : target, { ...init, unix: socket } as RequestInit); +}) as typeof fetch; + /** `unixSocketOnlyPath` for a server start: also refuses the config that would add a TCP listener, before any bind. */ export function unixSocketOnlyPathFor(config: OcxConfig): string | undefined { const path = unixSocketOnlyPath(); @@ -57,16 +77,42 @@ export function removeStaleUnixSocket(path: string): void { unlinkSync(path); } +type ParentStat = { isSymbolicLink(): boolean; isDirectory(): boolean; uid: number; mode: number }; + +/** + * The socket's parent must be a real directory (not a symlink), owned by this user, with no group or other + * permission, so no other Linux user can reach the socket whatever its own mode is. Throws before any bind. + */ +export function assertPrivateSocketParent( + path: string, + io: { lstat?: (dir: string) => ParentStat; uid?: number | undefined } = {}, +): void { + const dir = dirname(path); + const uid = "uid" in io ? io.uid : process.getuid?.(); + let stat: ParentStat; + try { stat = (io.lstat ?? lstatSync)(dir); } + catch (error) { + throw new Error(`${UNIX_SOCKET_ENV} parent directory is not usable: ${dir} (${(error as NodeJS.ErrnoException).code ?? "error"})`); + } + if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`${UNIX_SOCKET_ENV} parent must be a real directory, not a symlink: ${dir}`); + if (uid !== undefined && stat.uid !== uid) throw new Error(`${UNIX_SOCKET_ENV} parent directory is not owned by this user: ${dir}`); + if ((stat.mode & 0o077) !== 0) throw new Error(`${UNIX_SOCKET_ENV} parent directory must allow no group or other access (mode 0700): ${dir}`); +} + /** - * Bind `path` as the only listener: replace a stale socket, serve with `unix` (no port, no hostname), - * then chmod 0600. A chmod failure stops the server before rethrowing so nothing is left bound. - * The private parent directory closes the bind-to-chmod window. + * Bind `path` as the only listener: check the parent directory, replace a stale socket, serve with `unix` + * (no port, no hostname) under umask 0177 so the socket is created 0600, then chmod 0600 as well. A chmod + * failure stops the server before rethrowing so nothing is left bound. */ export function serveOnUnixSocket( path: string, serve: (unix: string) => S, ): S { + assertPrivateSocketParent(path); removeStaleUnixSocket(path); - const server = serve(path); + const priorUmask = process.umask(0o177); + let server: S; + try { server = serve(path); } + finally { process.umask(priorUmask); } try { chmodSync(path, 0o600); } catch (error) { void server.stop(true); throw error; } return server; diff --git a/src/server/management/claude-intercept-routes.ts b/src/server/management/claude-intercept-routes.ts index 2d34aeac7aa..4a803ff3c32 100644 --- a/src/server/management/claude-intercept-routes.ts +++ b/src/server/management/claude-intercept-routes.ts @@ -1,5 +1,6 @@ import type { ManagementContext } from "./context"; import { jsonResponse } from "../auth-cors"; +import { unixSocketOnlyActive } from "../index/unix-socket-only"; import { claudeInterceptEnabled, getClaudeInterceptState, type ClaudeInterceptOutcome } from "../../claude/intercept/runtime"; /** Local management authority only; data-plane credentials never grant this capability. */ @@ -9,6 +10,7 @@ export function interceptStartRefusal(ctx: ManagementContext): Response | null { } export async function ensureManagementClaudeIntercept(ctx: ManagementContext): Promise { + if (unixSocketOnlyActive()) return { ok: false, reason: "unix_socket_only" }; // AGE-6145: its listeners are TCP; refuse before anything opens if (ctx.config.runtimeRole === "client") return { ok: false, reason: "client_role" }; if (!claudeInterceptEnabled(ctx.config)) return { ok: false, reason: "disabled" }; if (ctx.deps.ensureClaudeIntercept) return ctx.deps.ensureClaudeIntercept(); diff --git a/tests/server/unix-socket-only.test.ts b/tests/server/unix-socket-only.test.ts index 88f857c64a9..c7c2cdc904e 100644 --- a/tests/server/unix-socket-only.test.ts +++ b/tests/server/unix-socket-only.test.ts @@ -7,12 +7,18 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { spawnSync } from "node:child_process"; import { connect } from "node:net"; -import { existsSync, lstatSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { saveConfig } from "../../src/config"; import { startServer, waitForFailedStartRollback } from "../../src/server"; -import { UNIX_SOCKET_ENV, unixSocketOnlyPath } from "../../src/server/index/unix-socket-only"; +import { createClaudeInterceptLifecycle } from "../../src/server/index/claude-intercept-lifecycle"; +import { directLocalHttpFetch } from "../../src/server/direct-local-http"; +import { isConnectionRefused } from "../../src/server/proxy-liveness"; +import { ensureManagementClaudeIntercept } from "../../src/server/management/claude-intercept-routes"; +import { + assertPrivateSocketParent, selfFetch, serveOnUnixSocket, UNIX_SOCKET_ENV, unixSocketOnlyPath, +} from "../../src/server/index/unix-socket-only"; import { installIsolatedCodexHome } from "../helpers/isolated-codex-home"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -132,4 +138,107 @@ describe("unix-socket-only serving", () => { expect(existsSync(path)).toBe(false); expect(await tcpRefused(48733)).toBe(true); }); + + test("refuses a socket parent with group or other bits, a symlinked parent, or one owned by another user", async () => { + saveConfig(baseConfig); + const loose = join(dir, "loose"); + mkdirSync(loose); + chmodSync(loose, 0o770); + process.env[UNIX_SOCKET_ENV] = join(loose, "ocx.sock"); + expect(String(await startRefused())).toContain("no group or other access"); + expect(existsSync(join(loose, "ocx.sock"))).toBe(false); + + const real = join(dir, "real"); + mkdirSync(real, { mode: 0o700 }); + const link = join(dir, "link"); + symlinkSync(real, link); + process.env[UNIX_SOCKET_ENV] = join(link, "ocx.sock"); + expect(String(await startRefused())).toContain("not a symlink"); + expect(existsSync(join(real, "ocx.sock"))).toBe(false); + + process.env[UNIX_SOCKET_ENV] = join(dir, "missing", "ocx.sock"); + expect(String(await startRefused())).toContain("parent directory is not usable"); + + // The uid check is simulated: a private directory that another user owns. + const owned = { isSymbolicLink: () => false, isDirectory: () => true, uid: 4242, mode: 0o40700 }; + expect(() => assertPrivateSocketParent(join(dir, "x.sock"), { lstat: () => owned, uid: 1000 })).toThrow("not owned by this user"); + expect(() => assertPrivateSocketParent(join(dir, "x.sock"), { lstat: () => owned, uid: 4242 })).not.toThrow(); + expect(() => assertPrivateSocketParent(join(dir, "x.sock"))).not.toThrow(); + }); + + test("the socket is created 0600 by the bind itself, whatever the process umask, and the umask is restored", () => { + const path = join(dir, "umask.sock"); + const priorUmask = process.umask(0); + let modeAtBind = -1; + let server: ReturnType | undefined; + try { + server = serveOnUnixSocket(path, unix => { + const bound = Bun.serve({ fetch: () => new Response("ok"), unix }); + modeAtBind = lstatSync(path).mode & 0o777; // before the chmod that follows the bind + return bound; + }); + expect(modeAtBind).toBe(0o600); + expect(process.umask()).toBe(0); + } finally { + process.umask(priorUmask); + void server?.stop(true); + } + }); + + test("selfFetch reaches the server over the socket and sends nothing to the TCP label port", async () => { + const path = join(dir, "ocx.sock"); + saveConfig({ ...baseConfig, port: 0 }); + process.env[UNIX_SOCKET_ENV] = path; + // Another company's process listening on the shared loopback label port. + let decoyHits = 0; + const decoy = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => { decoyHits++; return new Response("decoy"); } }); + const server = startServer(decoy.port!); + try { + const viaSelf = await selfFetch(`http://127.0.0.1:${decoy.port}/healthz?x=1`, { headers: { "x-opencodex-api-key": "admin-secret" } }); + expect(viaSelf.status).toBe(200); + expect(await viaSelf.text()).not.toBe("decoy"); + expect((await directLocalHttpFetch(`http://127.0.0.1:${decoy.port}/healthz`)).status).toBe(200); + expect(decoyHits).toBe(0); + } finally { + await server.stop(true); + await decoy.stop(true); + } + }); + + test("a missing socket reads as nothing listening, like a free TCP port", async () => { + process.env[UNIX_SOCKET_ENV] = join(dir, "absent.sock"); + const error = await directLocalHttpFetch("http://127.0.0.1:48734/healthz").then(() => null, caught => caught); + expect(isConnectionRefused(error)).toBe(true); + }); + + test("with the env unset selfFetch is plain fetch to the URL", async () => { + delete process.env[UNIX_SOCKET_ENV]; + const seen: string[] = []; + const target = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: req => { seen.push(new URL(req.url).pathname + new URL(req.url).search); return new Response("tcp"); } }); + try { + const res = await selfFetch(`http://127.0.0.1:${target.port}/api/x?y=2`); + expect(await res.text()).toBe("tcp"); + expect(seen).toEqual(["/api/x?y=2"]); + } finally { await target.stop(true); } + }); + + test("runtime Claude intercept ensure() refuses in unix mode and opens nothing", async () => { + process.env[UNIX_SOCKET_ENV] = join(dir, "ocx.sock"); + const live = { ...baseConfig, claudeCode: { enabled: true, intercept: { port: 48735 } } } as any; + const lifecycle = createClaudeInterceptLifecycle(); + let binds = 0; + lifecycle.start({ config: live, publicPort: 48735, requestedPort: 48735, configDir: home, dispatch: async () => new Response(), + startProxy: async () => { binds++; throw new Error("must not bind"); } }); + try { + expect(await lifecycle.ensure()).toEqual({ ok: false, reason: "unix_socket_only" }); + expect(binds).toBe(0); + expect(await tcpRefused(48735)).toBe(true); + expect(await tcpRefused(48835)).toBe(true); + // The management route refuses before it consults the lifecycle or any injected state. + let routed = 0; + const outcome = await ensureManagementClaudeIntercept({ config: live, deps: { ensureClaudeIntercept: async () => { routed++; return { ok: false, reason: "failed" }; } } } as any); + expect(outcome).toEqual({ ok: false, reason: "unix_socket_only" }); + expect(routed).toBe(0); + } finally { await lifecycle.stop(); } + }); });