Skip to content

Commit a3eb878

Browse files
authored
fix(cli): keep offline gateway RPCs read-only (#125102)
Gateway health, suspend, and resume now preserve shared SQLite state when the target is unreachable. Related: #101290 Follow-up to #123674
1 parent f77d2ec commit a3eb878

10 files changed

Lines changed: 179 additions & 63 deletions

‎src/cli/command-catalog.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,13 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
244244
route: { id: "gateway-status" },
245245
},
246246
{ commandPath: ["gateway", "call"], exact: true, policy: { networkProxy: "bypass" } },
247+
...["suspend", "resume"].map(
248+
(subcommand): CliCommandCatalogEntry => ({
249+
commandPath: ["gateway", subcommand],
250+
exact: true,
251+
policy: { configGuard: "validate", networkProxy: "bypass" },
252+
}),
253+
),
247254
{ commandPath: ["gateway", "diagnostics"], exact: true, policy: { networkProxy: "bypass" } },
248255
{ commandPath: ["gateway", "discover"], exact: true, policy: { networkProxy: "bypass" } },
249256
{

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,15 @@ describe("command-path-policy", () => {
125125
}
126126
});
127127

128+
it("keeps gateway suspension RPCs on non-observing config validation", () => {
129+
for (const subcommand of ["suspend", "resume"]) {
130+
expectResolvedPolicy(["gateway", subcommand], {
131+
configGuard: "validate",
132+
networkProxy: "bypass",
133+
});
134+
}
135+
});
136+
128137
it("applies exact overrides after broader channel plugin rules", () => {
129138
expectResolvedPolicy(["channels", "send"], {
130139
loadPlugins: "always",

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ describe("command-startup-policy", () => {
8181
["nodes", "remove"],
8282
["devices", "approve"],
8383
["devices", "remove"],
84+
["gateway", "suspend"],
85+
["gateway", "resume"],
8486
]) {
8587
expect(resolvePolicy({ commandPath })).toMatchObject({
8688
skipConfigGuard: false,

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

Lines changed: 120 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,14 @@ import {
2323
storeOriginDeviceToken,
2424
} from "../infra/device-auth-store.js";
2525
import { loadOrCreateDeviceIdentity } from "../infra/device-identity.js";
26-
import { openNodeSqliteDatabase, resolveImmutableSqliteFileUri } from "../infra/node-sqlite.js";
2726
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
2827
import { getFreePort } from "../test-utils/ports.js";
2928

3029
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
3130
const execFileAsync = promisify(execFile);
3231
const activeChildren = new Set<ChildProcessWithoutNullStreams>();
3332
const activeServers = new Set<WebSocketServer>();
33+
const UNREACHABLE_GATEWAY_URL = "ws://127.0.0.1:9";
3434

3535
afterEach(async () => {
3636
await Promise.all(
@@ -191,8 +191,6 @@ async function snapshotDirectoryContents(root: string): Promise<Record<string, s
191191
await visit(absolutePath);
192192
} else if (stat.isSymbolicLink()) {
193193
snapshot[relativePath] = `symlink:${await fs.readlink(absolutePath)}`;
194-
} else if (name === "openclaw.sqlite") {
195-
snapshot[relativePath] = "sqlite-database";
196194
} else {
197195
snapshot[relativePath] = `file:${createHash("sha256")
198196
.update(await fs.readFile(absolutePath))
@@ -204,34 +202,80 @@ async function snapshotDirectoryContents(root: string): Promise<Record<string, s
204202
return snapshot;
205203
}
206204

207-
function snapshotSqliteTables(databasePath: string): Record<string, string[]> {
208-
const database = openNodeSqliteDatabase(resolveImmutableSqliteFileUri(databasePath), {
209-
readOnly: true,
210-
});
205+
async function snapshotSharedStateArtifacts(stateDir: string): Promise<Record<string, string>> {
206+
const sharedStateDir = path.join(stateDir, "state");
211207
try {
212-
const tables = database
213-
.prepare("SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name")
214-
.all() as Array<{ name: string }>;
215-
return Object.fromEntries(
216-
tables.map(({ name }) => {
217-
const quotedName = `"${name.replaceAll('"', '""')}"`;
218-
const rows = database
219-
.prepare(`SELECT * FROM ${quotedName}`)
220-
.all()
221-
.map((row) =>
222-
JSON.stringify(row, (_key, value: unknown) =>
223-
typeof value === "bigint" ? value.toString() : value,
224-
),
225-
)
226-
.toSorted();
227-
return [name, rows];
228-
}),
229-
);
230-
} finally {
231-
database.close();
208+
return await snapshotDirectoryContents(sharedStateDir);
209+
} catch (error) {
210+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
211+
return {};
212+
}
213+
throw error;
232214
}
233215
}
234216

217+
async function prepareUnreachableGatewayCliFixture(params: {
218+
label: string;
219+
seeded: boolean;
220+
}): Promise<{ root: string; stateDir: string; configPath: string }> {
221+
const root = tempDirs.make(`openclaw-${params.label}-${params.seeded ? "seeded" : "absent"}-`);
222+
const stateDir = path.join(root, "state");
223+
const configPath = path.join(stateDir, "openclaw.json");
224+
await fs.mkdir(stateDir, { recursive: true });
225+
await fs.writeFile(
226+
configPath,
227+
JSON.stringify({
228+
gateway: {
229+
mode: "remote",
230+
auth: { mode: "none" },
231+
remote: { url: UNREACHABLE_GATEWAY_URL },
232+
},
233+
}),
234+
);
235+
if (params.seeded) {
236+
const stateEnv = {
237+
...process.env,
238+
HOME: root,
239+
OPENCLAW_HOME: root,
240+
OPENCLAW_STATE_DIR: stateDir,
241+
};
242+
const identity = loadOrCreateDeviceIdentity({ env: stateEnv });
243+
storeOriginDeviceToken({
244+
gatewayScope: gatewayOriginScope(UNREACHABLE_GATEWAY_URL),
245+
deviceId: identity.deviceId,
246+
role: "operator",
247+
token: "stored-device-token",
248+
scopes: ["operator.admin"],
249+
env: stateEnv,
250+
});
251+
closeOpenClawStateDatabaseForTest();
252+
}
253+
return { root, stateDir, configPath };
254+
}
255+
256+
function expectUnreachableGatewayTransportFailure(
257+
result: Awaited<ReturnType<typeof runIsolatedGatewayCli>>,
258+
output: "json" | "text",
259+
): void {
260+
expect(result).toMatchObject({ code: 1, signal: null });
261+
if (output === "json") {
262+
expect(result.stderr).toBe("");
263+
expect(JSON.parse(result.stdout)).toMatchObject({
264+
ok: false,
265+
error: {
266+
type: "gateway_transport_error",
267+
kind: "closed",
268+
message: expect.stringContaining("Gateway not reachable"),
269+
},
270+
gateway: { url: UNREACHABLE_GATEWAY_URL },
271+
});
272+
return;
273+
}
274+
expect(result.stderr).toContain("Gateway not reachable");
275+
expect(result.stderr).toContain(UNREACHABLE_GATEWAY_URL);
276+
expect(result.stderr).not.toContain("gateway timeout");
277+
}
278+
235279
async function runIsolatedGatewayCli(params: {
236280
args: string[];
237281
root: string;
@@ -294,6 +338,55 @@ async function runIsolatedGatewayCli(params: {
294338
}
295339

296340
describe("gateway-backed CLI process exit", () => {
341+
it.each([
342+
{
343+
label: "root-health-json",
344+
args: ["health", "--json", "--timeout", "250"],
345+
output: "json" as const,
346+
},
347+
{
348+
label: "gateway-health-text",
349+
args: ["gateway", "health", "--timeout", "250"],
350+
output: "text" as const,
351+
},
352+
{
353+
label: "gateway-health-json",
354+
args: ["gateway", "health", "--json", "--timeout", "250"],
355+
output: "json" as const,
356+
},
357+
{
358+
label: "gateway-suspend-json",
359+
args: ["gateway", "suspend", "--json", "--timeout", "250"],
360+
output: "json" as const,
361+
},
362+
{
363+
label: "gateway-resume-json",
364+
args: ["gateway", "resume", "suspension-1", "--json", "--timeout", "250"],
365+
output: "json" as const,
366+
},
367+
])(
368+
"leaves shared state byte-identical after unreachable $label",
369+
async ({ label, args, output }) => {
370+
const absent = await prepareUnreachableGatewayCliFixture({ label, seeded: false });
371+
expect(await snapshotSharedStateArtifacts(absent.stateDir)).toEqual({});
372+
373+
const absentResult = await runIsolatedGatewayCli({ ...absent, args });
374+
375+
expectUnreachableGatewayTransportFailure(absentResult, output);
376+
expect(await snapshotSharedStateArtifacts(absent.stateDir)).toEqual({});
377+
378+
const seeded = await prepareUnreachableGatewayCliFixture({ label, seeded: true });
379+
const before = await snapshotSharedStateArtifacts(seeded.stateDir);
380+
expect(Object.keys(before)).toContain("openclaw.sqlite");
381+
382+
const seededResult = await runIsolatedGatewayCli({ ...seeded, args });
383+
384+
expectUnreachableGatewayTransportFailure(seededResult, output);
385+
expect(await snapshotSharedStateArtifacts(seeded.stateDir)).toEqual(before);
386+
},
387+
60_000,
388+
);
389+
297390
it("dispatches node pairing mutations without opening the writable state database", async () => {
298391
const root = tempDirs.make("openclaw-node-pairing-cli-");
299392
const stateDir = path.join(root, "state");
@@ -350,9 +443,7 @@ describe("gateway-backed CLI process exit", () => {
350443
env: stateEnv,
351444
});
352445
closeOpenClawStateDatabaseForTest();
353-
const databasePath = path.join(stateDir, "state", "openclaw.sqlite");
354446
const before = await snapshotDirectoryContents(stateDir);
355-
const beforeTables = snapshotSqliteTables(databasePath);
356447

357448
const result = await runIsolatedGatewayCli({
358449
args: ["nodes", "approve", "request-1", "--json"],
@@ -365,7 +456,6 @@ describe("gateway-backed CLI process exit", () => {
365456
expect(JSON.parse(result.stdout)).toEqual({ approved: true });
366457
expect(gateway.calls).toEqual(["node.pair.list", "node.pair.approve"]);
367458
expect(await snapshotDirectoryContents(stateDir)).toEqual(before);
368-
expect(snapshotSqliteTables(databasePath)).toEqual(beforeTables);
369459
expect(
370460
loadOriginDeviceTokenReadOnly({
371461
gatewayScope: gatewayOriginScope(gateway.url),

‎src/cli/gateway-cli/health-route.test.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ describe("runGatewayHealthJsonRoute", () => {
1616
it("writes successful JSON without loading error-only dependencies", async () => {
1717
const runtime = createRuntime();
1818
const callGateway = vi.fn(async () => ({ ok: true, durationMs: 6 }));
19-
const readBestEffortConfig = vi.fn(async () => ({}));
19+
const readBestEffortHealthConfig = vi.fn(async () => ({}));
2020
const emitReachableGatewayAuthDiagnostic = vi.fn(async () => false);
2121
const formatGatewayAuthErrorJson = vi.fn();
2222
const formatGatewayClientRequestErrorJson = vi.fn();
@@ -29,7 +29,7 @@ describe("runGatewayHealthJsonRoute", () => {
2929
runtime as never,
3030
{
3131
callGateway,
32-
readBestEffortConfig,
32+
readBestEffortHealthConfig,
3333
emitReachableGatewayAuthDiagnostic: emitReachableGatewayAuthDiagnostic as never,
3434
formatGatewayAuthErrorJson: formatGatewayAuthErrorJson as never,
3535
formatGatewayClientRequestErrorJson: formatGatewayClientRequestErrorJson as never,
@@ -41,10 +41,10 @@ describe("runGatewayHealthJsonRoute", () => {
4141
"health",
4242
{ json: true, timeout: "10000" },
4343
undefined,
44-
{ defaultTimeoutMs: 10_000 },
44+
{ defaultTimeoutMs: 10_000, sharedStateMode: "read-only" },
4545
);
4646
expect(runtime.writeJson).toHaveBeenCalledWith({ ok: true, durationMs: 6 }, 2);
47-
expect(readBestEffortConfig).not.toHaveBeenCalled();
47+
expect(readBestEffortHealthConfig).not.toHaveBeenCalled();
4848
expect(emitReachableGatewayAuthDiagnostic).not.toHaveBeenCalled();
4949
expect(formatGatewayAuthErrorJson).not.toHaveBeenCalled();
5050
expect(formatGatewayClientRequestErrorJson).not.toHaveBeenCalled();
@@ -54,7 +54,7 @@ describe("runGatewayHealthJsonRoute", () => {
5454
it("projects a local port into the routed config", async () => {
5555
const runtime = createRuntime();
5656
const callGateway = vi.fn(async () => ({ ok: true }));
57-
const readBestEffortConfig = vi.fn(async () => ({
57+
const readBestEffortHealthConfig = vi.fn(async () => ({
5858
gateway: { auth: { mode: "token" as const } },
5959
}));
6060

@@ -64,7 +64,7 @@ describe("runGatewayHealthJsonRoute", () => {
6464
localPortOverride: 19083,
6565
},
6666
runtime as never,
67-
{ callGateway, readBestEffortConfig },
67+
{ callGateway, readBestEffortHealthConfig },
6868
);
6969

7070
expect(callGateway).toHaveBeenCalledWith(
@@ -76,7 +76,7 @@ describe("runGatewayHealthJsonRoute", () => {
7676
},
7777
}),
7878
undefined,
79-
{ defaultTimeoutMs: 10_000 },
79+
{ defaultTimeoutMs: 10_000, sharedStateMode: "read-only" },
8080
);
8181
});
8282

@@ -93,7 +93,7 @@ describe("runGatewayHealthJsonRoute", () => {
9393
runtime as never,
9494
{
9595
callGateway,
96-
readBestEffortConfig: vi.fn(async () => {
96+
readBestEffortHealthConfig: vi.fn(async () => {
9797
throw error;
9898
}),
9999
},
@@ -115,7 +115,7 @@ describe("runGatewayHealthJsonRoute", () => {
115115

116116
await runGatewayHealthJsonRoute({ rpc: { json: true, timeout: "10000" } }, runtime as never, {
117117
callGateway,
118-
readBestEffortConfig: async () => ({}),
118+
readBestEffortHealthConfig: async () => ({}),
119119
emitReachableGatewayAuthDiagnostic: vi.fn(async () => false) as never,
120120
formatGatewayAuthErrorJson: vi.fn(() => null) as never,
121121
formatGatewayClientRequestErrorJson: vi.fn(() => null) as never,
@@ -145,7 +145,7 @@ describe("runGatewayHealthJsonRoute", () => {
145145

146146
await runGatewayHealthJsonRoute({ rpc: { json: true, timeout: "10000" } }, runtime as never, {
147147
callGateway,
148-
readBestEffortConfig: async () => ({}),
148+
readBestEffortHealthConfig: async () => ({}),
149149
emitReachableGatewayAuthDiagnostic: vi.fn(async () => false) as never,
150150
formatGatewayAuthErrorJson: formatGatewayAuthErrorJson as never,
151151
formatGatewayClientRequestErrorJson: formatGatewayClientRequestErrorJson as never,

0 commit comments

Comments
 (0)