From de6759a7f2120182edeb377a4313f397371cb812 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:52:03 +0900 Subject: [PATCH] fix(claude): use bounded regular files for connection status and previews --- src/claude/connection-projection.ts | 11 +++-- src/claude/desktop-first-party.ts | 5 ++- src/claude/first-party-preview.ts | 15 +++++-- src/claude/intercept/settings-no-proxy.ts | 17 +++++-- src/claude/intercept/settings.ts | 22 ++++++--- src/lib/bounded-file-read.ts | 26 ++++++++--- structure/clients/connections.md | 12 +++-- .../claude-first-party-preview.test.ts | 9 ++++ tests/lib/bounded-file-read.test.ts | 9 ++++ tests/server/connection-status-routes.test.ts | 45 ++++++++++++++++++- 10 files changed, 141 insertions(+), 30 deletions(-) diff --git a/src/claude/connection-projection.ts b/src/claude/connection-projection.ts index 1d23955dc93..539c52a4a5b 100644 --- a/src/claude/connection-projection.ts +++ b/src/claude/connection-projection.ts @@ -17,7 +17,7 @@ import { inspectDesktopFirstParty, observeClaudeDesktopMode, resolveClaudeDeskto import { previewClaudeFirstPartySettings } from "./first-party-preview"; import { firstPartyDesired, firstPartyProxyStatus } from "./first-party-settings"; import { claudeInterceptEnabled } from "./intercept/runtime"; -import { claudeSettingsFileState } from "./intercept/settings"; +import { claudeSettingsFileState, MAX_STATUS_SETTINGS_BYTES } from "./intercept/settings"; export interface ClaudeConnectionInput { live: OcxConfig; @@ -31,7 +31,8 @@ export interface ClaudeConnectionInput { function claudeCodeRow(input: ClaudeConnectionInput, dir: string, source: "default" | "extra", ordinal?: number): ConnectionView { const { live } = input; - const options = { claudeConfigDir: dir, ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; + const options = { claudeConfigDir: dir, settingsReadLimit: MAX_STATUS_SETTINGS_BYTES, + ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; const settingsPath = join(dir, "settings.json"); const fileState = claudeSettingsFileState(dir); if (fileState === "unsafe") { @@ -84,7 +85,8 @@ function claudeCodeRow(input: ClaudeConnectionInput, dir: string, source: "defau function claudeDesktopRow(input: ClaudeConnectionInput): ConnectionView { const { live } = input; - const options = input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}; + const options = { settingsReadLimit: MAX_STATUS_SETTINGS_BYTES, + ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; const wanted = claudeDesktopIntegrationEnabled(live); const observation = observeClaudeDesktopMode(live, options); const mode = resolveClaudeDesktopMode(live, observation); @@ -97,7 +99,8 @@ function claudeDesktopRow(input: ClaudeConnectionInput): ConnectionView { case "broken": case "unsafe": observed = "unknown"; break; case "standard": case "no_owned_state": { const settings = mode === "first-party" ? inspectDesktopFirstParty(live, options).settings : null; - observed = settings && (settings.kind === "applied" || settings.kind === "stale") ? "proxy" : "native"; + observed = settings?.kind === "unreadable" ? "unknown" + : settings?.kind === "applied" || settings?.kind === "stale" ? "proxy" : "native"; break; } default: { diff --git a/src/claude/desktop-first-party.ts b/src/claude/desktop-first-party.ts index 88f1106f25c..e4d0568d11f 100644 --- a/src/claude/desktop-first-party.ts +++ b/src/claude/desktop-first-party.ts @@ -152,6 +152,8 @@ export interface DesktopFirstPartyInspection { export interface DesktopFirstPartyOptions { opencodexConfigDir?: string; claudeConfigDir?: string; + /** Read-only projections cap settings bytes and validate the opened descriptor. */ + settingsReadLimit?: number; } /** Prepare rollback before replacing a gateway, without changing settings. */ @@ -176,7 +178,8 @@ export function inspectDesktopFirstParty( // so an owned env can never match the empty credential — it classifies stale, and a real // apply is what refreshes it. const target = firstPartyTarget(config, opencodexConfigDir, readClaudeInterceptProxyToken(opencodexConfigDir) ?? ""); - const settings = inspectClaudeInterceptSettings(target.env, options.claudeConfigDir); + const settings = inspectClaudeInterceptSettings(target.env, options.claudeConfigDir, + { maxBytes: options.settingsReadLimit }); return { interceptEnabled: claudeInterceptEnabled(config), proxyPort: target.proxyPort, diff --git a/src/claude/first-party-preview.ts b/src/claude/first-party-preview.ts index 607d242f8a3..0eb05a85e31 100644 --- a/src/claude/first-party-preview.ts +++ b/src/claude/first-party-preview.ts @@ -23,7 +23,7 @@ import { claudeFirstPartyTransition } from "./first-party-transition"; import { claudeInterceptCaCertPath } from "./intercept/local-ca"; import { readClaudeInterceptProxyToken } from "./intercept/proxy-auth"; import { claudeInterceptEnabled } from "./intercept/runtime"; -import { claudeInterceptProxyUrl, claudeSettingsFileState, isClaudeInterceptProxyUrl, readClaudeSettingsEnv } from "./intercept/settings"; +import { claudeInterceptProxyUrl, claudeSettingsFileState, isClaudeInterceptProxyUrl, MAX_STATUS_SETTINGS_BYTES, readClaudeSettingsEnv } from "./intercept/settings"; import { mergeClaudeInterceptNoProxy, noProxyMergeable, readNoProxyReceipt } from "./intercept/settings-no-proxy"; export type SettingsChangeKind = "add" | "update" | "remove"; @@ -60,6 +60,8 @@ export interface FirstPartyPreviewInput { } const MANAGED_KEYS = ["HTTPS_PROXY", "NODE_EXTRA_CA_CERTS"] as const; +// A receipt stores both the old and written NO_PROXY strings, plus its JSON fields. +const MAX_PREVIEW_RECEIPT_BYTES = 2 * MAX_STATUS_SETTINGS_BYTES + 1024; function change(key: string, kind: SettingsChangeKind): FirstPartySettingsChange { return { file: "settings.json", key: `env.${key}`, change: kind }; @@ -67,7 +69,7 @@ function change(key: string, kind: SettingsChangeKind): FirstPartySettingsChange export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): FirstPartyPreview { const { live, persisted, enabled } = input; - const options = input.options ?? {}; + const options = { ...input.options, settingsReadLimit: MAX_STATUS_SETTINGS_BYTES }; const dir = options.claudeConfigDir ?? claudeConfigDir(); const path = join(dir, "settings.json"); const refuse = (reason: FirstPartyPreviewRefusal): FirstPartyPreview => ({ ok: false, enabled, reason, path }); @@ -90,7 +92,7 @@ export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): const reconciled: OcxConfig = { ...live, claudeCode: nextBlock }; const desired = firstPartyDesired(reconciled, observeClaudeDesktopMode(reconciled, options)); - const read = readClaudeSettingsEnv(dir); + const read = readClaudeSettingsEnv(dir, { maxBytes: MAX_STATUS_SETTINGS_BYTES }); if (read.kind === "unreadable") return refuse("unreadable"); const env = read.kind === "env" ? read.env : {}; @@ -101,7 +103,12 @@ export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): if (typeof ca !== "string" || ca.trim() !== ownedCa) return accept([]); const changes = [change("NODE_EXTRA_CA_CERTS", "remove")]; if (isClaudeInterceptProxyUrl(env.HTTPS_PROXY)) changes.push(change("HTTPS_PROXY", "remove")); - const receipt = readNoProxyReceipt(dir); + let receipt; + try { + receipt = readNoProxyReceipt(dir, MAX_PREVIEW_RECEIPT_BYTES); + } catch { // no-excuse-ok: catch -- a bounded read failure leaves the restoration undetermined. + return refuse("unreadable"); + } if (receipt && env.NO_PROXY === receipt.written) { const restored = receipt.hadKey ? receipt.previous : undefined; if (restored === undefined) changes.push(change("NO_PROXY", "remove")); diff --git a/src/claude/intercept/settings-no-proxy.ts b/src/claude/intercept/settings-no-proxy.ts index d82210c38f2..9d88267172a 100644 --- a/src/claude/intercept/settings-no-proxy.ts +++ b/src/claude/intercept/settings-no-proxy.ts @@ -1,6 +1,7 @@ import { readFileSync, unlinkSync } from "node:fs"; import { join } from "node:path"; import { atomicWriteFile } from "../../config/atomic-write"; +import { readBoundedRegularFileSync } from "../../lib/bounded-file-read"; import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard"; /** @@ -98,11 +99,21 @@ export function setNoProxyReceiptIoForTests(io: Partial): () => void } /** The receipt, or null when it is missing or malformed (both mean: no provenance). */ -export function readNoProxyReceipt(configDir: string): NoProxyReceipt | null { +export function readNoProxyReceipt(configDir: string, maxBytes?: number): NoProxyReceipt | null { + const path = noProxyReceiptPath(configDir); + let raw: string; + try { + raw = maxBytes === undefined ? readFileSync(path, "utf8") + : readBoundedRegularFileSync(path, maxBytes, { followFinalSymlink: true }).toString("utf8"); + } catch (error) { + // The preview cannot predict a restoration from a receipt it could not safely read. + if (maxBytes !== undefined && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + return null; + } let parsed: unknown; try { - parsed = JSON.parse(readFileSync(noProxyReceiptPath(configDir), "utf8")); - } catch { // no-excuse-ok: catch -- a missing or corrupt receipt is the no-provenance state. + parsed = JSON.parse(raw); + } catch { // no-excuse-ok: catch -- a corrupt receipt is the no-provenance state. return null; } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; diff --git a/src/claude/intercept/settings.ts b/src/claude/intercept/settings.ts index 0b44b6e091d..a32b84c206e 100644 --- a/src/claude/intercept/settings.ts +++ b/src/claude/intercept/settings.ts @@ -1,6 +1,7 @@ import { mkdirSync, readFileSync, statSync } from "node:fs"; import { dirname, join } from "node:path"; import { atomicWriteFile } from "../../config/atomic-write"; +import { readBoundedRegularFileSync } from "../../lib/bounded-file-read"; import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard"; import { claudeConfigDir } from "../auth-detect"; import { invalidateClaudeCodeServedCatalog } from "./cli-catalog"; @@ -70,15 +71,20 @@ export type ClaudeInterceptSettingsState = | { kind: "unreadable"; path: string }; type SettingsDoc = Record & { env?: Record }; +interface SettingsReadOptions { maxBytes?: number } function settingsPath(configDir: string): string { return join(configDir, "settings.json"); } -function readSettings(path: string): { doc: SettingsDoc } | { error: "missing" | "unreadable" } { +function readSettings( + path: string, + options: SettingsReadOptions = {}, +): { doc: SettingsDoc } | { error: "missing" | "unreadable" } { let raw: string; try { - raw = readFileSync(path, "utf8"); + raw = options.maxBytes === undefined ? readFileSync(path, "utf8") + : readBoundedRegularFileSync(path, options.maxBytes, { followFinalSymlink: true }).toString("utf8"); } catch (error) { // no-excuse-ok: catch -- an absent settings file is the fresh-install state. return { error: (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unreadable" }; } @@ -100,7 +106,7 @@ export type ClaudeSettingsEnvRead = | { kind: "unreadable" } | { kind: "env"; env: Readonly> }; -const MAX_STATUS_SETTINGS_BYTES = 1024 * 1024; +export const MAX_STATUS_SETTINGS_BYTES = 1024 * 1024; /** * Read-only status guard for a settings.json a status GET is about to read: `unsafe` for a @@ -118,8 +124,11 @@ export function claudeSettingsFileState(configDir = claudeConfigDir()): "missing } /** Read-only: the settings.json env block the writers below start from. Never writes. */ -export function readClaudeSettingsEnv(configDir = claudeConfigDir()): ClaudeSettingsEnvRead { - const read = readSettings(settingsPath(configDir)); +export function readClaudeSettingsEnv( + configDir = claudeConfigDir(), + options: SettingsReadOptions = {}, +): ClaudeSettingsEnvRead { + const read = readSettings(settingsPath(configDir), options); if ("error" in read) return { kind: read.error }; return { kind: "env", env: { ...envRecord(read.doc) } }; } @@ -142,9 +151,10 @@ function setOrDelete(env: Record, key: string, value: unknown): export function inspectClaudeInterceptSettings( expected: ClaudeInterceptEnv, configDir = claudeConfigDir(), + options: SettingsReadOptions = {}, ): ClaudeInterceptSettingsState { const path = settingsPath(configDir); - const read = readSettings(path); + const read = readSettings(path, options); if ("error" in read) return read.error === "missing" ? { kind: "absent" } : { kind: "unreadable", path }; const env = envRecord(read.doc); const proxy = env.HTTPS_PROXY; diff --git a/src/lib/bounded-file-read.ts b/src/lib/bounded-file-read.ts index f37045d0b2c..31543b81530 100644 --- a/src/lib/bounded-file-read.ts +++ b/src/lib/bounded-file-read.ts @@ -1,18 +1,30 @@ -import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs"; +import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, statSync } from "node:fs"; import { sameFileIdentity } from "./file-identity"; const MAX_BOUNDED_READ_BYTES = 64 * 1024 * 1024; const READ_CHUNK_BYTES = 64 * 1024; -export function readBoundedRegularFileSync(path: string, limit: number): Buffer { +export interface BoundedRegularFileReadOptions { + /** Follow the final symlink while still requiring its opened target to be bounded regular data. */ + followFinalSymlink?: boolean; +} + +export function readBoundedRegularFileSync( + path: string, + limit: number, + options: BoundedRegularFileReadOptions = {}, +): Buffer { if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_BOUNDED_READ_BYTES) { throw new RangeError("invalid bounded file read limit"); } const windows = process.platform === "win32"; - const flags = constants.O_RDONLY | (windows ? 0 : constants.O_NONBLOCK | constants.O_NOFOLLOW); - const entryBefore = windows ? lstatSync(path, { bigint: true }) : undefined; - if (entryBefore && (entryBefore.isSymbolicLink() || !entryBefore.isFile())) { + const followFinalSymlink = options.followFinalSymlink === true; + const posixFlags = constants.O_NONBLOCK | (followFinalSymlink ? 0 : constants.O_NOFOLLOW); + const flags = constants.O_RDONLY | (windows ? 0 : posixFlags); + const inspectEntry = followFinalSymlink ? statSync : lstatSync; + const entryBefore = windows || followFinalSymlink ? inspectEntry(path, { bigint: true }) : undefined; + if (entryBefore && !entryBefore.isFile()) { throw new Error("not a regular file"); } const fd = openSync(path, flags); @@ -40,8 +52,8 @@ export function readBoundedRegularFileSync(path: string, limit: number): Buffer if (length > limit) throw new Error("file exceeds byte limit"); if (entryBefore) { - const entryAfter = lstatSync(path, { bigint: true }); - if (entryAfter.isSymbolicLink() || !entryAfter.isFile() || !sameFileIdentity(opened, entryAfter)) { + const entryAfter = inspectEntry(path, { bigint: true }); + if (!entryAfter.isFile() || !sameFileIdentity(opened, entryAfter)) { throw new Error("file entry changed while reading"); } } diff --git a/structure/clients/connections.md b/structure/clients/connections.md index 5cde8d43e37..f2f2f09b954 100644 --- a/structure/clients/connections.md +++ b/structure/clients/connections.md @@ -59,10 +59,14 @@ prefix becomes `~`, a drive letter stays, and only the fixed directory and file and Claude use are shown; any other segment (a user name, account id or token used as a folder name) becomes `…`, and an extra home is identified by `homeOrdinal` instead of its path. No setting value, token or email is returned; an unexpected failure answers a fixed `connections_failed` body. Reads are -bounded: at most 16 extra homes (`MAX_EXTRA_CLAUDE_CONFIG_DIRS`), a `settings.json` that is not a -regular file of at most 1 MiB is never opened (`claudeSettingsFileState`; the row reads `unknown` and -the preview refuses `unreadable`), and the Codex profile goes through the same bounded reader as -config.toml. The Codex +bounded: at most 16 extra homes (`MAX_EXTRA_CLAUDE_CONFIG_DIRS`), and status/preview settings reads +validate and size-cap the opened descriptor at 1 MiB, with nonblocking opens on POSIX, then parse only +those bounded bytes. A final symlink remains compatible with Claude Code when its opened target is a +regular file; a FIFO, device, directory, oversized file or unsafe replacement reads `unknown` in the +row and makes the preview refuse `unreadable`. The switch-off preview applies the same descriptor +checks to the optional NO_PROXY receipt, allowing space for both stored values and its JSON fields. +The Codex profile goes through the same bounded reader +as config.toml. The Codex toggle envelopes in `native-integration-routes.ts` carry `connections: "/api/connections"`. CLI verb: owed. The route registry declares it `deferred-verb` with owner "proxy catch-up 020 diff --git a/tests/claude-integration/claude-first-party-preview.test.ts b/tests/claude-integration/claude-first-party-preview.test.ts index 9b55c2cf4e3..0a103551251 100644 --- a/tests/claude-integration/claude-first-party-preview.test.ts +++ b/tests/claude-integration/claude-first-party-preview.test.ts @@ -151,6 +151,15 @@ describe("enabling CLI first-party", () => { }); describe("turning CLI first-party off", () => { + test("a missing receipt is optional and an oversized receipt makes the preview unreadable", () => { + writeEnv({ NODE_EXTRA_CA_CERTS: claudeInterceptCaCertPath(root) }); + const config = cfg({ cli: true, desktopMode: "gateway" }); + const input = { live: config, persisted: config, enabled: false, options: options() }; + expect(previewClaudeFirstPartySettings(input).ok).toBe(true); + writeFileSync(join(claudeHome, "opencodex-no-proxy.json"), "{}".padEnd(2 * 1024 * 1024 + 1025)); + expect(previewClaudeFirstPartySettings(input)).toMatchObject({ ok: false, reason: "unreadable" }); + }); + test("a CLI-only env is removed, restoring NO_PROXY from its receipt", () => { expect(realSwitch(cfg({ desktopMode: "gateway" }), cfg({ desktopMode: "gateway" }), true).ok).toBe(true); const on = cfg({ cli: true, desktopMode: "gateway" }); diff --git a/tests/lib/bounded-file-read.test.ts b/tests/lib/bounded-file-read.test.ts index 6d1706f87bb..3607277c1e4 100644 --- a/tests/lib/bounded-file-read.test.ts +++ b/tests/lib/bounded-file-read.test.ts @@ -117,6 +117,15 @@ describe("readBoundedRegularFileSync", () => { expect(() => readBoundedRegularFileSync(link, 64)).toThrow(); }); + test.skipIf(!canCreateFileSymlink())("follows a final symlink only when requested", () => { + const path = join(root, "target.json"); + writeFileSync(path, "fixture"); + const link = join(root, "linked.json"); + symlinkSync(path, link, "file"); + expect(readBoundedRegularFileSync(link, 64, { followFinalSymlink: true }).toString("utf8")) + .toBe("fixture"); + }); + test.skipIf(process.platform === "win32")("rejects a FIFO without blocking", () => { const fifo = join(root, "input.pipe"); const created = spawnSync("mkfifo", [fifo], { timeout: 2_000 }); diff --git a/tests/server/connection-status-routes.test.ts b/tests/server/connection-status-routes.test.ts index a5fc13c12be..e33e15d6bde 100644 --- a/tests/server/connection-status-routes.test.ts +++ b/tests/server/connection-status-routes.test.ts @@ -7,7 +7,8 @@ */ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; +import * as fs from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { handleManagementAPI } from "../../src/server/management-api"; @@ -313,12 +314,54 @@ describe("security bounds", () => { expect(row).toMatchObject({ observed: "unknown", owner: "unknown", driftReasons: [] }); }); + test("the connection and preview routes inspect ordinary settings through bounded file descriptors", async () => { + const extra = join(root, "extra-read"); + const settings = [claudeHome, extra].map(dir => { + mkdirSync(dir, { recursive: true }); + const path = join(dir, "settings.json"); + writeFileSync(path, "{}"); + return path; + }); + const config = baseConfig({ claudeCode: { extraConfigDirs: [extra] } } as Partial); + const opens = spyOn(fs, "openSync"); + const reads = spyOn(fs, "readFileSync"); + try { + const views = await connections(config); + expect(views.find(row => row.homeSource === "extra")?.observed).toBe("native"); + for (const path of settings) expect(opens.mock.calls.some(([file]) => file === path)).toBe(true); + opens.mockClear(); + const preview = await dispatch(config, "/api/claude-code/first-party/preview?enabled=false"); + expect(preview!.status).toBe(200); + expect(opens.mock.calls.some(([file]) => file === settings[0])).toBe(true); + expect(reads.mock.calls.some(([file]) => settings.some(path => path === file))).toBe(false); + } finally { + reads.mockRestore(); + opens.mockRestore(); + } + }); + + test.skipIf(process.platform === "win32")("a symlinked regular settings.json keeps Claude-compatible routing", async () => { + const extra = join(root, "linked-home"); + const target = join(root, "linked-settings.json"); + mkdirSync(extra, { recursive: true }); + writeFileSync(target, JSON.stringify({ env: { + HTTPS_PROXY: "http://proxy.corp:8080", NODE_EXTRA_CA_CERTS: "/corp/ca.pem", + } })); + symlinkSync(target, join(extra, "settings.json")); + const config = baseConfig({ claudeCode: { extraConfigDirs: [extra] } } as Partial); + const row = (await connections(config)).find(view => view.homeSource === "extra")!; + expect(row).toMatchObject({ observed: "foreign", owner: "external", driftReasons: [] }); + }); + test("an oversized default settings.json makes the preview refuse instead of reading it", async () => { mkdirSync(claudeHome, { recursive: true }); writeFileSync(join(claudeHome, "settings.json"), `{"pad":"${"x".repeat(1024 * 1024 + 16)}"}`); const response = await dispatch(baseConfig(), "/api/claude-code/first-party/preview?enabled=true"); expect(response!.status).toBe(500); expect(await response!.json()).toMatchObject({ code: "unreadable" }); + mkdirSync(join(root, "library"), { recursive: true }); + const views = await connections(baseConfig({ claudeCode: { desktopMode: "first-party" } })); + expect(views.find(row => row.client === "claude-desktop")).toMatchObject({ observed: "unknown", owner: "unknown" }); }); test("registered homes are capped", async () => {