Skip to content

Commit 250ef01

Browse files
lidge-junkerthans
andauthored
fix(cli): preserve default bind identity for guarded stops (#8221)
Carries #8182 by @kerthans. Fixes #8181. Co-authored-by: kerthans <112744990+kerthans@users.noreply.github.com>
1 parent aec37c1 commit 250ef01

21 files changed

Lines changed: 388 additions & 47 deletions

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,12 @@ unreadable command line in the approved proxy's supervision chain (or surviving
152152
stopped manager) leaves wrapper ownership unknown, so the guarded stop cannot report success.
153153
Missing or unreadable evidence blocks the guarded stop.
154154

155+
New runtime records include the bound hostname. For older records that omit it, a guarded
156+
stop accepts the discovered default loopback address only when the remaining approval and
157+
ownership checks agree. An omitted hostname cannot independently prove the listener's bind
158+
scope. When the record contains a hostname, it must match the approved value exactly;
159+
wildcard and loopback binds remain distinct.
160+
155161
### `ocx restart`
156162

157163
When this CLI is newer than an attested standalone POSIX proxy, restart can stop the old
@@ -318,6 +324,33 @@ restart the proxy using the intended current installation; for a background serv
318324
or resolve `PATH` to the intended installation. These diagnostics do not repair the service or
319325
change whether requests are allowed.
320326

327+
If an update restart reports a blank hostname in the runtime record, it leaves the proxy running.
328+
Use `ocx status` and `ocx service status` as clues, not proof of ownership or the actual bind.
329+
Once ownership is verified, for a service use the owning installation's `ocx service restart`;
330+
for Desktop, use the app; for a foreground proxy, use its terminal. A standalone proxy started by `ocx ensure` may be
331+
detached and have no terminal:
332+
333+
1. Independently verify the process identity, installation, home, supervisor and actual listening
334+
address and port. Use OS process and listener inspection with sufficient permissions; check
335+
IPv4, IPv6 and wildcard listeners as applicable. A PID alone can be reused, and missing or
336+
incomplete inspection results do not prove ownership or absence. For example, on macOS or
337+
Linux where `lsof` is available, `ps -p <pid> -o pid=,ppid=,args=` and
338+
`lsof -nP -iTCP:<port> -sTCP:LISTEN` provide process and listener clues. They do not by
339+
themselves establish the home, supervisor, or complete visibility; use the appropriate OS
340+
tools and permissions to verify those separately.
341+
2. Only if those facts are verified and forced termination is acceptable, the owner can run
342+
`ocx stop` from the owning installation and home. It tries a graceful stop first, but may
343+
fall back to forced termination if that fails; it can also refuse, including when the blank
344+
hostname prevents guarded ownership verification. Do not bypass a refusal.
345+
3. Independently confirm the identified process has exited, no supervisor will restart it,
346+
and the intended address and port are free. A successful stop or a status result alone is
347+
not proof of all three. Once confirmed, run `ocx start` from the intended installation and
348+
home with the intended bind and port settings; a successful start regenerates the record.
349+
350+
If any check is incomplete, the stop fails or is refused, or forced termination is unacceptable,
351+
stop and ask the owner or administrator to investigate. Do not edit the runtime record or kill
352+
unrelated processes. Retry the update restart if needed after the new proxy is running.
353+
321354
Identical version strings and the `unknown` / `0.0.0` placeholders suppress the warning, as does
322355
an absent proxy version. Doctor does not report placeholders as a confirmed match. Different
323356
strings still produce a neutral warning when they cannot be strictly parsed as SemVer or differ

‎docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,11 @@ ocx start --socks5-off
3838

3939
### `ocx restart`
4040

41-
執行 `stop` 後接 `ensure`:停止代理/服務、還原原生 Codex、在背景啟動代理,並將即時連接埠同步回 Codex。
41+
一般情況下,代理正在執行時,指令會向身分已驗證的特定 PID 與連接埠請求原地重新啟動,等待正常排空,並確認同一連接埠上出現不同的執行階段 PID。此路徑會保留受管路由與服務監督;若請求結果不確定,不會將其重試為獨立的停止與啟動。只有代理未執行時,才會回退至一般的 `ensure` 啟動。
42+
43+
若目前 CLI 比已驗證的獨立 POSIX 代理新,且符合嚴格的擁有權與監督條件,受保護的更新路徑會停止舊代理,確認其已停止後才從目前的安裝啟動新代理;此路徑不同於上述原地重新啟動。若資格或停止狀態無法確認,指令會回報失敗。條件與其他情況請參閱[重新啟動參考資料](/reference/cli/lifecycle/#ocx-restart)(英文)。
44+
45+
如果更新後的重新啟動回報執行階段紀錄中的主機名稱為空白,這次嘗試不會停止代理。請參閱[狀態與復原指引](/reference/cli/lifecycle/#status-and-health)(英文),先確認擁有權與實際綁定位址;若確認不完整,請洽擁有者或管理員。
4246

4347
### `ocx ensure`
4448

‎src/cli/index.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { getCodexHome } from "../codex/paths";
1313
import { admitUpdateRestartChild } from "./update-restart-child";
1414
import { HEALTH_SENTINEL_STANDALONE_ARG, startServiceHealthSentinel } from "../service/health-sentinel-launch";
1515
import { UpdateRestartRequired } from "./update-restart-candidate";
16-
import { describeUpdateRestartFailure, restartFromCurrentInstallation } from "./update-restart";
16+
import { reportUpdateRestartFailure, restartFromCurrentInstallation } from "./update-restart";
1717
import { findGuiDist } from "../server/gui-static";
1818
import { inspectGuiBundleFreshness, staleGuiBundleLines } from "../server/gui-freshness";
1919
// Best-effort recovery for runtime execution and spawned children if launched
@@ -606,7 +606,7 @@ async function handleStart(options: { block?: boolean } = {}) {
606606
writeRuntime: bound => { updateRestartChild?.check(bound.port, bound.config.hostname ?? ""); writeRuntimePort({
607607
pid: process.pid,
608608
port: bound.port,
609-
hostname: bound.config.hostname,
609+
hostname: bound.server.hostname,
610610
attestationSecret: bound.localAttestationSecret,
611611
command: currentServingCommand(),
612612
...siblingRuntimeField(),
@@ -984,7 +984,7 @@ async function handleProxyRestart(
984984
console.log(`🔄 Running proxy ${candidate.target.version} is older than this CLI (${candidate.cliVersion}); restarting it from the current installation...`);
985985
const update = await restartFromCurrentInstallation(candidate, deadlineAt, detachedStartEnvironment());
986986
if (update.ok) console.log(`✅ Proxy updated to ${update.live.version} (PID ${update.live.pid}).`);
987-
else console.error(`❌ ${describeUpdateRestartFailure(update.code, update.reason)} (${update.code})`);
987+
else reportUpdateRestartFailure(update);
988988
process.exitCode = update.ok ? 0 : 1;
989989
return update.ok;
990990
}

‎src/cli/stop-approval.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export interface GuardedStopSnapshot {
2727
* inspection probe -- it carries no path, command line, stderr, or token.
2828
*/
2929
export type TrackedRuntimeCheck =
30-
| { pid: number; port: number; hostname: string }
30+
| { pid: number; port: number; hostname: string | undefined }
3131
| { untracked: string }
3232
| null;
3333

@@ -145,7 +145,7 @@ export async function runApprovedStop(
145145
return approvalChanged(`the tracked runtime record could not be verified (${target.untracked})`);
146146
}
147147
if (target.pid !== expected.pid || target.port !== expected.port
148-
|| target.hostname !== expected.hostname) {
148+
|| (target.hostname === undefined ? expected.hostname !== "127.0.0.1" : target.hostname !== expected.hostname)) {
149149
return approvalChanged("the tracked runtime record changed");
150150
}
151151
if (manager.kind === "unknown") {

‎src/cli/system-restart-client.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,11 @@ export async function requestBoundSystemRestart(
164164
if (!sameRestartTarget(target, observed)) return rejected("restart_target_changed");
165165
if (skew.relation === "cli-newer") {
166166
if (!updateHome) return rejected("update_restart_home_unverified");
167+
try {
168+
if (JSON.stringify((deps.readUpdateHome ?? readUpdateRestartHome)()) !== JSON.stringify(updateHome)) {
169+
return rejected("update_restart_home_changed");
170+
}
171+
} catch { return rejected("update_restart_home_changed"); }
167172
const current = readRuntime(target.pid);
168173
if (!current || current.pid !== runtime.pid || current.port !== runtime.port
169174
|| current.hostname !== runtime.hostname || current.attestationSecret !== runtime.attestationSecret) {

‎src/cli/update-restart-child.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { existsSync } from "node:fs";
2+
import { isIP } from "node:net";
23
import { getRuntimePortPath, readRuntimePort } from "../config/process-state";
34
import { packageVersion } from "../lib/package-version";
45
import { parseStrictSemver } from "../lib/strict-semver";
@@ -10,12 +11,21 @@ export const UPDATE_RESTART_CHILD_ENV = "OCX_UPDATE_RESTART_CHILD";
1011
export interface UpdateRestartChildMarker { home: UpdateRestartHome; version: string; port: number; hostname: string; deadlineAt: number }
1112
export interface UpdateRestartChildGuard { check(port?: number, hostname?: string): void; complete(): void }
1213

13-
function parseMarker(raw: string): UpdateRestartChildMarker {
14+
function safeBindHost(host: string): boolean {
15+
if (!host || host.length > 255 || host !== host.trim()) return false;
16+
if (host.startsWith("[") || host.endsWith("]")) {
17+
return host.startsWith("[") && host.endsWith("]") && isIP(host.slice(1, -1)) === 6;
18+
}
19+
return isIP(host) !== 0 || /^(?:\*|0|(0+\.){3}0+)\.?$/.test(host);
20+
}
21+
22+
export function parseUpdateRestartMarker(raw: string): UpdateRestartChildMarker {
1423
if (raw.length > 8192) throw new Error("update_restart_child_marker_invalid");
1524
const value = JSON.parse(raw) as UpdateRestartChildMarker;
1625
if (!value || !Number.isSafeInteger(value.deadlineAt) || !Number.isInteger(value.port)
17-
|| typeof value.hostname !== "string" || value.port < 1 || value.port > 65535 || typeof value.version !== "string"
26+
|| typeof value.hostname !== "string" || !safeBindHost(value.hostname) || value.port < 1 || value.port > 65535 || typeof value.version !== "string"
1827
|| value.version === "0.0.0" || !parseStrictSemver(value.version) || !value.home
28+
|| !(value.home.diagnosedHostname === null || (typeof value.home.diagnosedHostname === "string" && safeBindHost(value.home.diagnosedHostname)))
1929
|| !Number.isSafeInteger(value.home.revision) || value.home.serviceRecord?.schema !== 1
2030
|| typeof value.home.serviceRecord.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.home.serviceRecord.digest)) throw new Error("update_restart_child_marker_invalid");
2131
for (const directory of [value.home.config, value.home.codex]) {
@@ -49,7 +59,7 @@ export function admitUpdateRestartChild(argv: string[], io: UpdateRestartChildIo
4959
if (raw === undefined) return undefined;
5060
delete env[UPDATE_RESTART_CHILD_ENV];
5161
delete env[OWNERSHIP_MUTATION_LEASE_TOKEN_ENV];
52-
const marker = parseMarker(raw);
62+
const marker = parseUpdateRestartMarker(raw);
5363
if (argv.length !== 3 || argv[0] !== "start" || argv[1] !== "--port" || argv[2] !== String(marker.port)) {
5464
throw new Error("update_restart_child_command_changed");
5565
}

‎src/cli/update-restart-home.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export interface UpdateRestartHome {
1818
codex: UpdateRestartDirectory;
1919
revision: number;
2020
serviceRecord: UpdateRestartServiceRecord;
21+
diagnosedHostname: string | null;
2122
}
2223

2324
export type UpdateRestartDirectoryStat = Pick<BigIntStats, "dev" | "ino" | "isDirectory">;
@@ -44,7 +45,9 @@ export function readUpdateRestartHome(deps: UpdateRestartHomeDeps = {}): UpdateR
4445
throw new Error("update_restart_owner_unverified");
4546
}
4647
const stat = deps.statDirectory ?? (path => statSync(path, { bigint: true }));
47-
return { config: physicalDirectory(getConfigDir(), stat), codex: physicalDirectory(currentCodexHome(), stat), revision: owner.revision, serviceRecord };
48+
const diagnostics = readConfigDiagnostics({ passive: true });
49+
if (diagnostics.error) throw new Error("update_restart_configuration_unverified");
50+
return { config: physicalDirectory(getConfigDir(), stat), codex: physicalDirectory(currentCodexHome(), stat), revision: owner.revision, serviceRecord, diagnosedHostname: diagnostics.config.hostname ?? null };
4851
}
4952

5053
export function assertUpdateRestartHome(expected: UpdateRestartHome, deadlineAt = Date.now() + 2000, deps: UpdateRestartHomeDeps = {}): void {
@@ -62,7 +65,7 @@ export function assertUpdateRestartHome(expected: UpdateRestartHome, deadlineAt
6265

6366
/** Read-only eligibility shared by parent pre-stop and child admission. */
6467
export function assertUpdateRestartConfiguration(hostname: string): void {
65-
const diagnostics = readConfigDiagnostics();
68+
const diagnostics = readConfigDiagnostics({ passive: true });
6669
if (readClientConnectionState().kind !== "disconnected" || diagnostics.error
67-
|| (diagnostics.config.hostname ?? "") !== hostname) throw new Error("update_restart_configuration_changed");
70+
|| (diagnostics.config.hostname === undefined ? hostname !== "127.0.0.1" : diagnostics.config.hostname !== hostname)) throw new Error("update_restart_configuration_changed");
6871
}

0 commit comments

Comments
 (0)