Skip to content

Commit ef44eab

Browse files
authored
fix(cli): guard state writes against gateway split-brain (#134403)
Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent ae24725 commit ef44eab

17 files changed

Lines changed: 752 additions & 10 deletions

‎docs/cli/channels.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,8 @@ If your config was already in a mixed state (named accounts present and top-leve
169169

170170
## Login and logout (interactive)
171171

172+
Before `channels add` or `channels login` writes local credentials or configuration, OpenClaw compares the selected CLI state/config paths with the local Gateway or its installed service. A proven mismatch stops before the write. A remote Gateway or an authenticated path that cannot be verified produces a warning instead.
173+
172174
```bash
173175
openclaw channels login --channel whatsapp
174176
openclaw channels logout --channel whatsapp

‎docs/cli/configure.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ Use `openclaw onboard` or `openclaw setup` for the full guided first-run journey
1717

1818
## Options
1919

20+
Before `openclaw configure` changes local credentials or configuration, OpenClaw compares the selected CLI state/config paths with the local Gateway or its installed service. A proven mismatch stops before the write. A remote Gateway or an authenticated path that cannot be verified produces a warning instead.
21+
2022
`--section <section>`: repeatable section filter. Available sections:
2123

2224
`workspace`, `model`, `web`, `gateway`, `daemon`, `channels`, `plugins`, `skills`, `health`

‎docs/cli/models.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ Manages `agents.defaults.model.fallbacks`. `openclaw models image-fallbacks list
155155

156156
## Auth profiles
157157

158+
Before a `models auth` command changes the local auth store, OpenClaw compares the selected CLI state/config paths with the local Gateway or its installed service. A proven mismatch stops before the write. A remote Gateway or an authenticated path that cannot be verified produces a warning instead.
159+
158160
```bash
159161
openclaw models auth add
160162
openclaw models auth list [--provider <id>] [--json]

‎src/cli/cli-process-child.test-helpers.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,17 @@ export async function runCliProcessChild(params: {
4949
nodeArgs: string[];
5050
env: NodeJS.ProcessEnv;
5151
cwd?: string;
52+
input?: string;
5253
onStdout?: (stdout: string) => void;
5354
timeoutMs?: number;
5455
}): Promise<CliProcessChildResult> {
5556
const timeoutMs = params.timeoutMs ?? CLI_PROCESS_DEADLOCK_GUARD_MS;
5657
const child = spawn(process.execPath, params.nodeArgs, {
5758
cwd: params.cwd ?? path.resolve("."),
5859
env: params.env,
59-
stdio: ["ignore", "pipe", "pipe"],
60+
stdio: ["pipe", "pipe", "pipe"],
6061
});
62+
child.stdin.end(params.input);
6163
child.stdout.setEncoding("utf8");
6264
child.stderr.setEncoding("utf8");
6365
let stdout = "";

‎src/cli/command-catalog.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ type CliRoutedCommandId =
4343

4444
export type CliCommandPathPolicy = {
4545
configGuard: CliConfigGuardPolicy;
46+
stateStoreGuard: "run" | "skip";
4647
loadPlugins: CliCommandPluginLoadPolicy;
4748
pluginRegistry: CliPluginRegistryPolicy;
4849
ownsProtocolStdout: boolean;
@@ -186,7 +187,10 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
186187
exact: true,
187188
policy: { loadPlugins: "never" },
188189
},
189-
{ commandPath: ["configure"], policy: { configGuard: "skip", loadPlugins: "never" } },
190+
{
191+
commandPath: ["configure"],
192+
policy: { configGuard: "skip", stateStoreGuard: "run", loadPlugins: "never" },
193+
},
190194
{
191195
commandPath: ["config"],
192196
exact: true,
@@ -346,6 +350,7 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
346350
},
347351
route: { id: "models-status" },
348352
},
353+
{ commandPath: ["models", "auth"], policy: { stateStoreGuard: "run" } },
349354
{
350355
commandPath: ["models", "list"],
351356
exact: true,
@@ -643,8 +648,9 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
643648
{
644649
commandPath: ["channels", "add"],
645650
exact: true,
646-
policy: { loadPlugins: "never", networkProxy: "bypass" },
651+
policy: { stateStoreGuard: "run", loadPlugins: "never", networkProxy: "bypass" },
647652
},
653+
{ commandPath: ["channels", "login"], exact: true, policy: { stateStoreGuard: "run" } },
648654
{
649655
commandPath: ["channels", "logs"],
650656
exact: true,

‎src/cli/command-path-policy.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99

1010
const DEFAULT_EXPECTED_POLICY: CliCommandPathPolicy = {
1111
configGuard: "run",
12+
stateStoreGuard: "skip",
1213
loadPlugins: "never",
1314
pluginRegistry: { scope: "all" },
1415
ownsProtocolStdout: false,
@@ -59,6 +60,25 @@ function expectConfigGuardResolver(
5960
}
6061

6162
describe("command-path-policy", () => {
63+
it.each([
64+
{ commandPath: ["configure"] },
65+
{ commandPath: ["models", "auth"] },
66+
{ commandPath: ["models", "auth", "paste-token"] },
67+
{ commandPath: ["channels", "add"] },
68+
{ commandPath: ["channels", "login"] },
69+
])("guards local state writes for $commandPath", ({ commandPath }) => {
70+
expect(resolveCliCommandPathPolicy(commandPath).stateStoreGuard).toBe("run");
71+
});
72+
73+
it.each([
74+
{ commandPath: ["models", "list"] },
75+
{ commandPath: ["channels", "status"] },
76+
{ commandPath: ["config", "set"] },
77+
{ commandPath: ["onboard"] },
78+
])("does not broaden the state-store guard to $commandPath", ({ commandPath }) => {
79+
expect(resolveCliCommandPathPolicy(commandPath).stateStoreGuard).toBe("skip");
80+
});
81+
6282
it("resolves status policy with shared startup semantics", () => {
6383
expectResolvedPolicy(["status"], {
6484
configGuard: "skip",
@@ -150,6 +170,7 @@ describe("command-path-policy", () => {
150170
pluginRegistry: { scope: "configured-channels" },
151171
});
152172
expectResolvedPolicy(["channels", "login"], {
173+
stateStoreGuard: "run",
153174
loadPlugins: "always",
154175
pluginRegistry: { scope: "configured-channels" },
155176
});
@@ -158,6 +179,7 @@ describe("command-path-policy", () => {
158179
pluginRegistry: { scope: "configured-channels" },
159180
});
160181
expectResolvedPolicy(["channels", "add"], {
182+
stateStoreGuard: "run",
161183
loadPlugins: "never",
162184
pluginRegistry: { scope: "configured-channels" },
163185
networkProxy: "bypass",
@@ -379,6 +401,7 @@ describe("command-path-policy", () => {
379401
});
380402
expectResolvedPolicy(["configure"], {
381403
configGuard: "skip",
404+
stateStoreGuard: "run",
382405
loadPlugins: "never",
383406
});
384407
expectResolvedPolicy(["config"], {

‎src/cli/command-path-policy.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { resolveParentAwareCommandPath } from "./parent-command-path.js";
1212

1313
const DEFAULT_CLI_COMMAND_PATH_POLICY: CliCommandPathPolicy = {
1414
configGuard: "run",
15+
stateStoreGuard: "skip",
1516
loadPlugins: "never",
1617
pluginRegistry: { scope: "all" },
1718
ownsProtocolStdout: false,

‎src/cli/gateway-backed-exit.test-helpers.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,37 @@ export async function startGatewayStabilityRpcServer(
237237
return { authTokens, calls, url: `ws://${host}:${address.port}` };
238238
}
239239

240+
export async function startStateDirStatusGateway(target: {
241+
stateDir: string;
242+
configPath: string;
243+
}): Promise<{ url: string }> {
244+
const wss = new WebSocketServer({ host: "127.0.0.1", port: 0 });
245+
activeServers.add(wss);
246+
wss.on("connection", (ws) => {
247+
sendMinimalGatewayConnectChallenge(ws);
248+
ws.on("message", (data) => {
249+
const frame = parseMinimalGatewayRequestFrame(data);
250+
if (frame.type !== "req" || !frame.id) {
251+
return;
252+
}
253+
if (frame.method === "connect") {
254+
sendMinimalGatewayResponse(
255+
ws,
256+
frame.id,
257+
buildMinimalGatewayHelloOkPayload({ methods: ["status"], snapshot: target }),
258+
);
259+
return;
260+
}
261+
if (frame.method === "status") {
262+
sendMinimalGatewayResponse(ws, frame.id, { status: "ok" });
263+
}
264+
});
265+
});
266+
await once(wss, "listening");
267+
const address = wss.address() as AddressInfo;
268+
return { url: `ws://127.0.0.1:${address.port}` };
269+
}
270+
240271
/** Mock Gateway that answers one agent turn with the requested terminal status. */
241272
export async function startAgentTurnGateway(params: {
242273
status: "ok" | "error";
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { Command } from "commander";
2+
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { CliGatewayStateDirOutcome } from "../state-dir-gateway-check.js";
4+
5+
const mocks = vi.hoisted(() => ({
6+
action: vi.fn(),
7+
check: vi.fn<() => Promise<CliGatewayStateDirOutcome>>(async () => ({ kind: "allow" })),
8+
debug: vi.fn(),
9+
ensureBootstrap: vi.fn(async () => {}),
10+
}));
11+
12+
vi.mock("../state-dir-gateway-check.js", () => ({ checkCliGatewayStateDir: mocks.check }));
13+
vi.mock("../../logger.js", () => ({ logDebug: mocks.debug }));
14+
vi.mock("../../runtime.js", () => ({
15+
defaultRuntime: {
16+
log: vi.fn(),
17+
error: vi.fn(),
18+
writeStdout: vi.fn(),
19+
writeJson: vi.fn(),
20+
exit: vi.fn(),
21+
},
22+
}));
23+
vi.mock("../command-execution-startup.js", () => ({
24+
applyCliExecutionStartupPresentation: vi.fn(async () => {}),
25+
ensureCliExecutionBootstrap: mocks.ensureBootstrap,
26+
resolveCliExecutionStartupContext: ({ commandPath }: { commandPath: string[] }) => ({
27+
commandPath,
28+
startupPolicy: { skipConfigGuard: true },
29+
}),
30+
}));
31+
32+
let program: Command;
33+
let originalArgv: string[];
34+
35+
beforeAll(async () => {
36+
const { registerPreActionHooks } = await import("./preaction.js");
37+
program = new Command().name("openclaw");
38+
program.command("configure").action(mocks.action);
39+
registerPreActionHooks(program, "test");
40+
});
41+
42+
beforeEach(() => {
43+
originalArgv = [...process.argv];
44+
vi.clearAllMocks();
45+
process.argv = ["node", "openclaw", "configure"];
46+
});
47+
48+
afterEach(() => {
49+
process.argv = originalArgv;
50+
});
51+
52+
describe("state-store preAction guard", () => {
53+
it("refuses before bootstrap and action", async () => {
54+
mocks.check.mockResolvedValueOnce({ kind: "refuse", message: "state stores differ" });
55+
56+
await expect(program.parseAsync(process.argv)).rejects.toThrow("state stores differ");
57+
58+
expect(mocks.check).toHaveBeenCalledWith({ command: "openclaw configure" });
59+
expect(mocks.ensureBootstrap).not.toHaveBeenCalled();
60+
expect(mocks.action).not.toHaveBeenCalled();
61+
});
62+
63+
it("allows the action when inspection fails", async () => {
64+
mocks.check.mockRejectedValueOnce(new Error("inspection failed"));
65+
66+
await expect(program.parseAsync(process.argv)).resolves.toBe(program);
67+
68+
expect(mocks.debug).toHaveBeenCalledWith("state-store guard unavailable: inspection failed");
69+
expect(mocks.action).toHaveBeenCalledOnce();
70+
});
71+
});

‎src/cli/program/preaction.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
resolveCliExecutionStartupContext,
1414
} from "../command-execution-startup.js";
1515
import { inheritOptionFromParent } from "../command-options.js";
16+
import { resolveCliCommandPathPolicy } from "../command-path-policy.js";
1617
import { applyResolvedCommandOutputMode } from "../json-output-mode.js";
1718
import { isModelsPlainMachineOutput } from "../models-output-mode.js";
1819
import {
@@ -113,6 +114,27 @@ function isGatewayRunAction(actionCommand: Command): boolean {
113114
);
114115
}
115116

117+
async function runStateStoreGuard(commandPath: string[]): Promise<void> {
118+
if (resolveCliCommandPathPolicy(commandPath).stateStoreGuard !== "run") {
119+
return;
120+
}
121+
let outcome: import("../state-dir-gateway-check.js").CliGatewayStateDirOutcome;
122+
try {
123+
const { checkCliGatewayStateDir } = await import("../state-dir-gateway-check.js");
124+
outcome = await checkCliGatewayStateDir({ command: `openclaw ${commandPath.join(" ")}` });
125+
} catch (error) {
126+
const { formatErrorMessage } = await import("../../infra/errors.js");
127+
const { logDebug } = await import("../../logger.js");
128+
logDebug(`state-store guard unavailable: ${formatErrorMessage(error)}`);
129+
return;
130+
}
131+
if (outcome.kind === "warn") {
132+
defaultRuntime.log(outcome.message);
133+
} else if (outcome.kind === "refuse") {
134+
throw new Error(outcome.message);
135+
}
136+
}
137+
116138
/** Register global pre-action bootstrap hooks for every non-help command invocation. */
117139
export function registerPreActionHooks(program: Command, programVersion: string) {
118140
program.hook("preAction", async (_thisCommand, actionCommand) => {
@@ -156,6 +178,7 @@ export function registerPreActionHooks(program: Command, programVersion: string)
156178
if (isGuidedConfigAction(actionCommand) || isGuidedConfigCommandPath(commandPath)) {
157179
return;
158180
}
181+
await runStateStoreGuard(commandPath);
159182
if (startupPolicy.skipConfigGuard) {
160183
// Config validation and plugin activation are independent startup policies.
161184
// A cold config read must not suppress a plugin runtime explicitly required by the command.

0 commit comments

Comments
 (0)