Skip to content

Commit 8e7b633

Browse files
authored
Merge pull request #2126 from lidge-jun/fix/service-definition-secret-mode
fix(service): write service definitions owner-only, they can carry a proxy credential
2 parents fbc6f26 + 52f85f6 commit 8e7b633

5 files changed

Lines changed: 217 additions & 10 deletions

File tree

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# 140 — final audit of the merged stack, and what it caught
2+
3+
Run after #2116/#2117/#2118/#2121 landed on `dev`. Verdict: **fail**, and the
4+
reason was not one of the four fixes.
5+
6+
## What the audit confirmed
7+
8+
- The proxy-env leak is genuinely dead. The auditor re-ran the five affected
9+
suites from a clean `git archive origin/dev` — 236 pass / 0 fail — **and then
10+
re-ran them without `--isolate`**, the exact single-process condition that
11+
produced the original 73 failures. Still green. That second run is the one
12+
that matters; the first only proves isolation hides it.
13+
- #2121's gate reason cannot fire on the turn-drain path.
14+
- Escaping holds across all three builders under newline, quote and `%`
15+
injection.
16+
- Full suite on `dev` head `fbc6f26a2`: **13,501 pass / 0 fail**, run on
17+
`ssh lidge`.
18+
19+
## What it caught — P1, and it is real
20+
21+
#2107 baked the proxy environment into the installed service definition. A proxy
22+
URL routinely carries `user:password`, so that change quietly made those files
23+
credential-bearing. They were still written with a bare `writeFileSync`.
24+
25+
Measured, not assumed: umask 022, `writeFileSync` with no mode → **0644**.
26+
27+
The precedent was already in the same file and was not followed — the service
28+
API token (`service.ts:387`) and the install state (`:190`) both write
29+
`{ mode: 0o600 }` plus a `chmodSync`. The repo also has an explicit convention
30+
against leaking this exact value: `collectProxyEnv` reports proxy presence as a
31+
boolean so the URL never escapes, pinned by a `doctor` test asserting the
32+
serialized rows never contain `"secret"`.
33+
34+
So the change wrote a credential to a world-readable file in a codebase that
35+
already treats 0600 as the standard for precisely this data.
36+
37+
**The uncomfortable part is procedural.** #2116's own body disclosed the risk
38+
and offered to gate on redaction. That question was never adjudicated — the PR
39+
merged at `REVIEW_REQUIRED` with only bot comments. `AGENTS.md` requires
40+
explicit security review for credential handling. Disclosing a risk in a PR body
41+
is not the same as discharging it, and self-merging past your own open question
42+
is how a known risk becomes a shipped one.
43+
44+
### The fix
45+
46+
One `writeServiceDefinitionFile()` for the plist, the unit, and the Windows
47+
scheduler assets: `{ mode: 0o600 }` plus `chmodSync`, plus the Windows ACL.
48+
49+
The explicit `chmodSync` is not belt-and-braces. `mode` applies only at
50+
creation, so an install over a definition an earlier version left at 0644 would
51+
keep the loose mode — and that is the realistic upgrade path, not a hypothetical.
52+
53+
Red-driven: with the mode argument removed, the three new assertions report
54+
`644` against an expected `600`.
55+
56+
## P2 — the untestable builder was left untested
57+
58+
`buildWindowsServiceScript` was the only one of the three builders with no proxy
59+
assertion, and the reason is instructive: the only way to reach it was to assign
60+
`process.env`, which is the exact pattern whose leak this stack had just removed.
61+
The refactor fixed the leak where a test existed and left the untestable builder
62+
untested.
63+
64+
It now takes the resolved entries like the other two, with a regression covering
65+
the canonical-name rule.
66+
67+
## P2 — the new fix reintroduced the same structural class
68+
69+
`reportedFenceReasons` in #2121 is process-lifetime module state — structurally
70+
the same hazard as the proxy leak, one abstraction away. Whichever file
71+
constructs the error first consumes the one-shot warn, so a later file asserting
72+
on it would see nothing and **pass vacuously**.
73+
74+
Current suites pass in both file orders, so this was latent rather than live. The
75+
reset is now documented as an order-sensitive contract and its caller resets on
76+
both sides.
77+
78+
## P3 — pin-to-line comments were already wrong at merge
79+
80+
`auth-context.ts:326` (actual: 357/363/370), `lifecycle.ts:180`,
81+
`native-profile-startup.ts:138-139` (actual: 142-143) and `:311` (actual: 315).
82+
Replaced with symbol names, which do not drift when a file moves.
83+
84+
## The honest gap that remains
85+
86+
No commit in this stack has a green cross-platform CI run of its own — the runs
87+
were cancelled by successive force-pushes, and `dev`'s own run was still in
88+
flight. Both Windows-specific behaviors this stack shipped are unverified on
89+
Windows: the Windows proxy path had no test until now, and `owner-unavailable` —
90+
the branch #2108 most needs named — is a Windows icacls path asserted nowhere in
91+
the suite.
92+
93+
Stating it rather than filing it as done.
94+
95+
## The lesson worth keeping
96+
97+
An audit that only re-runs what the author ran finds nothing. This one found the
98+
P1 by asking a question the author never asked — *what mode is that file?* — and
99+
then measuring it instead of reasoning about it.
100+

‎src/codex/auth-context.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,15 @@ function reportNativeMainFenceReason(reason: NativeMainStartupBlockReason): void
161161
);
162162
}
163163

164-
/** Test-only: the dedup above is module state, so a second test would otherwise observe nothing. */
164+
/**
165+
* Test-only reset for the dedup set above.
166+
*
167+
* The dedup is process-lifetime module state, so it is order-sensitive across test files
168+
* sharing one Bun process: whichever file constructs this error first consumes the one-shot
169+
* warn, and a later file asserting on it would see nothing and pass vacuously. Any test that
170+
* asserts on the warn must call this first — an `afterEach` in the asserting file is not
171+
* enough on its own, because the consuming file may not be the asserting one.
172+
*/
165173
export function __resetNativeMainFenceReasonLog(): void {
166174
reportedFenceReasons.clear();
167175
}

‎src/service.ts‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1541,7 +1541,11 @@ function taskXmlRunLevelAcceptable(principal: string): boolean {
15411541
return value === "leastprivilege" || value === "highestavailable";
15421542
}
15431543

1544-
export function buildWindowsServiceScript(entry = cliEntry(), port = resolveServiceListenPort()): string {
1544+
export function buildWindowsServiceScript(
1545+
entry = cliEntry(),
1546+
port = resolveServiceListenPort(),
1547+
proxyEnv: { name: string; value: string }[] = resolvedProxyEnv(),
1548+
): string {
15451549
// Provenance rides along with the entry: a second durableBunRuntime() call here could
15461550
// resolve differently from the binary the caller actually baked.
15471551
const { bun, bunRuntimeSource, cli } = entry;
@@ -1559,7 +1563,7 @@ export function buildWindowsServiceScript(entry = cliEntry(), port = resolveServ
15591563
windowsBatchSet("CODEX_HOME", process.env.CODEX_HOME?.trim(), "path"),
15601564
windowsBatchSet("CODEX_SQLITE_HOME", currentCodexSqliteHomeAbsolute("windows"), "path"),
15611565
windowsBatchSet("OPENCODEX_HOME", process.env.OPENCODEX_HOME?.trim(), "path"),
1562-
...resolvedProxyEnv().map(({ name, value }) => windowsBatchSet(name, value)),
1566+
...proxyEnv.map(({ name, value }) => windowsBatchSet(name, value)),
15631567
windowsBatchSet("OCX_API_TOKEN_FILE", serviceApiTokenFilePath(), "path"),
15641568
windowsBatchSet("OCX_SERVICE_LOG", serviceLogPath(), "path"),
15651569
windowsBatchSet("OCX_BUN", bun, "path"),
@@ -1881,7 +1885,7 @@ function installLaunchd(): void {
18811885
// Capture this BEFORE writing: the write below makes the plist exist unconditionally,
18821886
// so a post-write existsSync would call every fresh install an "installed" service.
18831887
const wasInstalled = existsSync(p);
1884-
writeFileSync(p, buildPlist(), "utf8");
1888+
writeServiceDefinitionFile(p, buildPlist(), "utf8");
18851889
// Best-effort: an absent job is fine here, and a failed unload is caught by the
18861890
// load verification below with a better message than a raw unload error.
18871891
runLaunchctl(["unload", p]);
@@ -1944,6 +1948,27 @@ function uninstallLaunchd(): void {
19441948
if (existsSync(p)) unlinkSync(p);
19451949
}
19461950

1951+
/**
1952+
* Write a service definition with owner-only permissions.
1953+
*
1954+
* These files carry the outbound proxy environment (#2107), and a proxy URL routinely
1955+
* carries `user:password`. `writeFileSync` without a mode lands at 0644 under the default
1956+
* umask, so the credential would be world-readable on a shared host. Every other
1957+
* secret-bearing write in this file already uses 0600 — the service API token and the
1958+
* install state — and a service definition holding a proxy credential belongs in the same
1959+
* class.
1960+
*
1961+
* The explicit `chmodSync` is not redundant: `mode` only applies when the file is
1962+
* created, so an install over a definition left at 0644 by an earlier version would keep
1963+
* the loose mode. On Windows the POSIX bits are advisory, so the real ACL is applied
1964+
* there the same way the token file does it.
1965+
*/
1966+
export function writeServiceDefinitionFile(path: string, content: string, encoding: "utf8" | "utf16le"): void {
1967+
writeFileSync(path, content, { encoding, mode: 0o600 });
1968+
try { chmodSync(path, 0o600); } catch { /* best-effort; the Windows ACL below is authoritative */ }
1969+
if (process.platform === "win32") hardenSecretPath(path, { required: false });
1970+
}
1971+
19471972
// ── Windows (Task Scheduler) ──
19481973
/**
19491974
* In-place service-asset write that tolerates the transient EBUSY/EPERM/EACCES Windows
@@ -1952,7 +1977,7 @@ function uninstallLaunchd(): void {
19521977
function writeServiceAssetWithRetry(path: string, content: string, encoding: "utf8" | "utf16le"): void {
19531978
for (let attempt = 0; ; attempt++) {
19541979
try {
1955-
writeFileSync(path, content, encoding);
1980+
writeServiceDefinitionFile(path, content, encoding);
19561981
return;
19571982
} catch (err) {
19581983
const code = (err as NodeJS.ErrnoException).code;
@@ -2520,7 +2545,7 @@ function installSystemd(): void {
25202545
recordOwnedConfigPath(getConfigDir(), serviceStatePath());
25212546
if (!existsSync(getConfigDir())) mkdirSync(getConfigDir(), { recursive: true });
25222547
writeServiceApiTokenFile();
2523-
writeFileSync(unitPath(), buildUnit(), "utf8");
2548+
writeServiceDefinitionFile(unitPath(), buildUnit(), "utf8");
25242549
sh("systemctl --user daemon-reload");
25252550
sh(`systemctl --user enable ${TASK}`);
25262551
sh(`systemctl --user restart ${TASK}`);

‎tests/codex-auth-context.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1355,6 +1355,12 @@ describe("cooldown error surface", () => {
13551355
// instead of remapping to Anthropic 529), and headers never survive to /api/logs, so stdout is
13561356
// the only surface that reaches every path this fence fires on.
13571357
describe("native-main fence names its gate reason", () => {
1358+
// Reset on BOTH sides: an afterEach only protects tests that run after this file, and the
1359+
// dedup is module state shared with every other file in the same process.
1360+
beforeEach(() => {
1361+
__resetNativeMainFenceReasonLog();
1362+
});
1363+
13581364
afterEach(() => {
13591365
__resetNativeMainFenceReasonLog();
13601366
});
@@ -1394,7 +1400,7 @@ describe("native-main fence names its gate reason", () => {
13941400
}
13951401
});
13961402

1397-
// auth-context.ts:326 throws the same error for the turn-drain fence (lifecycle.ts:180), which
1403+
// The claimMainProfile() site throws the same error for the turn-drain fence, which
13981404
// is NOT the startup gate: the snapshot there reads `ready`. Inventing a reason for it would
13991405
// send the next reboot report chasing a startup gate that never closed.
14001406
test("the turn-drain fence stays silent instead of borrowing a startup reason", () => {

‎tests/service.test.ts‎

Lines changed: 71 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import { afterEach, describe, expect, spyOn, test } from "bun:test";
2-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { isAbsolute, join, posix, win32 } from "node:path";
55
import * as serviceModule from "../src/service";
66
import { saveConfig } from "../src/config";
77
import { windowsEnvIndirectBatchValue } from "../src/lib/win-paths";
88
import { assertServiceAuthEnvironment, assertServiceEnvironmentMatchesInstall, bakedServicePathsDiagnostic, confirmServiceServing, launchdListenPort, systemdListenPort, buildPlist, buildUnit, buildWindowsLauncherVbs, buildWindowsSchtasksCreateArgs, buildWindowsSchtasksCreateArgsForXml, buildWindowsServiceScript, buildWindowsTaskXml, deriveWindowsServiceDiagnostic, installFreshWindowsSchedulerSafely, installServiceSafely, launchctlLoadFailed, launchdJobMatchesPlist, normalizeServiceSubcommand, parseServiceInstallState, prepareServiceInstall, readWindowsSchedulerXmlState, registerFreshWindowsSchedulerTask, removeNativeWindowsServiceForScheduler, repairService, resolveServiceListenPort, runLaunchctl, serviceLogPath, serviceStartableFromTray, serviceStatusReport, serviceRetryCommand, serviceStatusSummary, systemdNeedsDaemonReload, windowsListenPort, winswListenPort, startLaunchd, windowsTaskRegistrationHealthy } from "../src/service";
99
import type { ServiceDiagnostic } from "../src/service";
10-
import { resolvedProxyEnv } from "../src/service";
10+
import { resolvedProxyEnv, writeServiceDefinitionFile } from "../src/service";
1111
import { buildWinswXml } from "../src/lib/winsw";
1212
import { CONFIG_OWNER_FILE, CONFIG_UNINSTALL_MANIFEST, recordOwnedConfigPath, removeOwnedConfigState } from "../src/lib/config-ownership";
1313
import { serviceApiTokenFilePath } from "../src/lib/service-secrets";
@@ -157,6 +157,23 @@ describe("systemd service unit", () => {
157157
expect(unit).not.toContain("http_proxy=");
158158
});
159159

160+
test("the Windows wrapper bakes proxy env the same way the unit and plist do (#2107)", () => {
161+
// This builder was the only one of the three with no proxy assertion, because the only way
162+
// to reach it was to assign process.env — the pattern that leaked HTTP_PROXY across files.
163+
const script = buildWindowsServiceScript(
164+
{ bun: "C:\\OpenCodex\\bun.exe", bunRuntimeSource: "bundled", cli: "C:\\OpenCodex\\cli.ts" },
165+
10100,
166+
resolvedProxyEnv({ HTTP_PROXY: "http://127.0.0.1:7890", no_proxy: "localhost" }),
167+
);
168+
169+
expect(script).toContain("HTTP_PROXY=http://127.0.0.1:7890");
170+
// Lower-case spellings are baked under the canonical name, never both.
171+
expect(script).toContain("NO_PROXY=localhost");
172+
expect(script).not.toContain("no_proxy=");
173+
expect(script).not.toContain("HTTPS_PROXY=");
174+
});
175+
176+
160177
test("preserves custom Codex and OpenCodex homes", () => {
161178
const oldCodexHome = process.env.CODEX_HOME;
162179
const oldCodexSqliteHome = process.env.CODEX_SQLITE_HOME;
@@ -199,7 +216,9 @@ describe("systemd service unit", () => {
199216
expect(startSystemd).toContain("ocx service install");
200217
expect(startSystemd).toContain("process.exit(1)");
201218

202-
const writeAt = installSystemd.indexOf('writeFileSync(unitPath(), buildUnit(), "utf8")');
219+
// The write goes through writeServiceDefinitionFile so the unit lands 0600: it can carry a
220+
// proxy credential (#2107). What this test pins is the ORDER — write, then reload.
221+
const writeAt = installSystemd.indexOf('writeServiceDefinitionFile(unitPath(), buildUnit(), "utf8")');
203222
const reloadAt = installSystemd.indexOf("systemctl --user daemon-reload");
204223
const enableAt = installSystemd.indexOf("systemctl --user enable");
205224
const restartAt = installSystemd.indexOf("systemctl --user restart");
@@ -2152,3 +2171,52 @@ describe("service serving confirmation", () => {
21522171
});
21532172
});
21542173
});
2174+
2175+
// #2107 baked the outbound proxy environment into the installed service definition, and a
2176+
// proxy URL routinely carries user:password. That made these files credential-bearing, so
2177+
// they must not be written at the umask default.
2178+
describe("service definitions are not world-readable", () => {
2179+
const modeOf = (path: string): string => (statSync(path).mode & 0o777).toString(8);
2180+
2181+
test("a freshly written definition is owner-only", () => {
2182+
const dir = mkdtempSync(join(tmpdir(), "ocx-service-mode-"));
2183+
try {
2184+
const path = join(dir, "unit");
2185+
writeServiceDefinitionFile(path, buildUnit(resolvedProxyEnv({ HTTP_PROXY: "http://u:[email protected]:7890" })), "utf8");
2186+
2187+
expect(modeOf(path)).toBe("600");
2188+
// The credential is still written — this test pins who can read it, not that it is absent.
2189+
expect(readFileSync(path, "utf8")).toContain("u:[email protected]");
2190+
} finally {
2191+
rmSync(dir, { recursive: true, force: true });
2192+
}
2193+
});
2194+
2195+
test("an install over a loose definition from an older version tightens it", () => {
2196+
// `mode` applies only on creation, so a reinstall would otherwise leave 0644 standing.
2197+
const dir = mkdtempSync(join(tmpdir(), "ocx-service-mode-"));
2198+
try {
2199+
const path = join(dir, "plist");
2200+
writeFileSync(path, "stale", { encoding: "utf8", mode: 0o644 });
2201+
expect(modeOf(path)).toBe("644");
2202+
2203+
writeServiceDefinitionFile(path, buildPlist(resolvedProxyEnv({})), "utf8");
2204+
2205+
expect(modeOf(path)).toBe("600");
2206+
} finally {
2207+
rmSync(dir, { recursive: true, force: true });
2208+
}
2209+
});
2210+
2211+
test("utf16le scheduler assets take the same mode", () => {
2212+
const dir = mkdtempSync(join(tmpdir(), "ocx-service-mode-"));
2213+
try {
2214+
const path = join(dir, "task.xml");
2215+
writeServiceDefinitionFile(path, "\uFEFF<Task />", "utf16le");
2216+
2217+
expect(modeOf(path)).toBe("600");
2218+
} finally {
2219+
rmSync(dir, { recursive: true, force: true });
2220+
}
2221+
});
2222+
});

0 commit comments

Comments
 (0)