Skip to content

Commit 6416bae

Browse files
authored
fix(gateway): audit managed service starts (#110497)
* fix(gateway): audit managed service starts * chore: drop changelog edit (release-only per repo policy) * test(gateway): align start routing mocks
1 parent e9f798e commit 6416bae

14 files changed

Lines changed: 317 additions & 44 deletions

‎src/cli/daemon-cli.coverage.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const resolveGatewayProgramArguments = vi.fn(async (_opts?: unknown) => ({
1414
const serviceInstall = vi.fn().mockResolvedValue(undefined);
1515
const serviceStage = vi.fn().mockResolvedValue(undefined);
1616
const serviceUninstall = vi.fn().mockResolvedValue(undefined);
17+
const serviceStart = vi.fn().mockResolvedValue({ outcome: "completed" });
1718
const serviceStop = vi.fn().mockResolvedValue(undefined);
1819
const serviceRestart = vi.fn().mockResolvedValue({ outcome: "completed" });
1920
const serviceIsLoaded = vi.fn().mockResolvedValue(false);
@@ -100,6 +101,7 @@ vi.mock("../daemon/service.js", async () => {
100101
stage: serviceStage,
101102
install: serviceInstall,
102103
uninstall: serviceUninstall,
104+
start: serviceStart,
103105
stop: serviceStop,
104106
restart: serviceRestart,
105107
isLoaded: serviceIsLoaded,
@@ -347,15 +349,15 @@ describe("daemon-cli coverage", () => {
347349

348350
it("starts and stops daemon (json output)", async () => {
349351
runtimeLogs.length = 0;
350-
serviceRestart.mockClear();
352+
serviceStart.mockClear();
351353
serviceStop.mockClear();
352354
serviceIsLoaded.mockResolvedValue(true);
353355
serviceReadRuntime.mockResolvedValueOnce({ status: "stopped" });
354356

355357
await runDaemonCommand(["daemon", "start", "--json"]);
356358
await runDaemonCommand(["daemon", "stop", "--json", "--force"]);
357359

358-
expect(serviceRestart).toHaveBeenCalledTimes(1);
360+
expect(serviceStart).toHaveBeenCalledTimes(1);
359361
expect(serviceStop).toHaveBeenCalledTimes(1);
360362
const jsonLines = runtimeLogs.filter((line) => line.trim().startsWith("{"));
361363
const parsed = jsonLines.map((line) => JSON.parse(line) as { action?: string; ok?: boolean });

‎src/cli/daemon-cli/lifecycle-core.config-guard.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ describe("runServiceStart config pre-flight (#35862)", () => {
223223

224224
await expect(runServiceStart(createServiceRunArgs())).rejects.toThrow("__exit__:1");
225225

226-
expect(service.restart).not.toHaveBeenCalled();
226+
expect(service.start).not.toHaveBeenCalled();
227227
expectLatestRuntimeJson({
228228
action: "start",
229229
ok: false,
@@ -239,7 +239,7 @@ describe("runServiceStart config pre-flight (#35862)", () => {
239239

240240
await expect(runServiceStart(createServiceRunArgs())).rejects.toThrow("__exit__:1");
241241

242-
expect(service.restart).not.toHaveBeenCalled();
242+
expect(service.start).not.toHaveBeenCalled();
243243
expectLatestRuntimeJson({
244244
action: "start",
245245
ok: false,
@@ -269,15 +269,15 @@ describe("runServiceStart config pre-flight (#35862)", () => {
269269
).rejects.toThrow("__exit__:1");
270270

271271
expect(onNotLoaded).not.toHaveBeenCalled();
272-
expect(service.restart).not.toHaveBeenCalled();
272+
expect(service.start).not.toHaveBeenCalled();
273273
});
274274

275275
it("proceeds with start when config is valid", async () => {
276276
setConfigSnapshot({ exists: true, valid: true });
277277

278278
await runServiceStart(createServiceRunArgs());
279279

280-
expect(service.restart).toHaveBeenCalledTimes(1);
280+
expect(service.start).toHaveBeenCalledTimes(1);
281281
});
282282
});
283283

‎src/cli/daemon-cli/lifecycle-core.test.ts‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -436,7 +436,7 @@ describe("runServiceRestart token drift", () => {
436436
expect(payload.result).toBe("started");
437437
expect(payload.message).toContain("re-bootstrapped");
438438
expect(payload.service?.loaded).toBe(true);
439-
expect(service.restart).not.toHaveBeenCalled();
439+
expect(service.start).not.toHaveBeenCalled();
440440
});
441441

442442
it("runs restart health checks after an unmanaged restart signal", async () => {
@@ -580,8 +580,8 @@ describe("runServiceRestart token drift", () => {
580580
expect(clearGatewayRestartIntentSync).toHaveBeenCalledOnce();
581581
});
582582

583-
it("emits scheduled when service start routes through a scheduled restart", async () => {
584-
service.restart.mockResolvedValue({ outcome: "scheduled" });
583+
it("emits scheduled when service start is deferred", async () => {
584+
service.start.mockResolvedValue({ outcome: "scheduled" });
585585

586586
await runServiceStart({
587587
serviceNoun: "Gateway",
@@ -596,7 +596,7 @@ describe("runServiceRestart token drift", () => {
596596
expect(payload.message).toBe("restart scheduled, gateway will restart momentarily");
597597
});
598598

599-
it("reports an already-running gateway without restarting it", async () => {
599+
it("reports an already-running gateway without starting it", async () => {
600600
service.readRuntime.mockResolvedValue({ status: "running", pid: 4242 });
601601

602602
await runServiceStart({
@@ -612,12 +612,12 @@ describe("runServiceRestart token drift", () => {
612612
result: "already-running",
613613
message: "Gateway service already running (pid 4242).",
614614
});
615-
expect(service.restart).not.toHaveBeenCalled();
615+
expect(service.start).not.toHaveBeenCalled();
616616
expect(appendGatewayLifecycleAudit).not.toHaveBeenCalled();
617617
});
618618

619619
it("audits a service start that actually mutates the gateway", async () => {
620-
service.restart.mockImplementationOnce(async (args?: GatewayServiceControlArgs) => {
620+
service.start.mockImplementationOnce(async (args?: GatewayServiceControlArgs) => {
621621
args?.onMutation?.({ mode: "kickstart" });
622622
return { outcome: "completed" };
623623
});
@@ -667,7 +667,7 @@ describe("runServiceRestart token drift", () => {
667667
});
668668

669669
it("captures service start warnings in json start output", async () => {
670-
service.restart.mockImplementationOnce(async (args?: GatewayServiceControlArgs) => {
670+
service.start.mockImplementationOnce(async (args?: GatewayServiceControlArgs) => {
671671
args?.warn?.(
672672
"Existing generated LaunchAgent env wrapper contains custom behavior and will be overwritten.",
673673
);
@@ -685,7 +685,7 @@ describe("runServiceRestart token drift", () => {
685685
expect(payload.warnings).toContain(
686686
"Existing generated LaunchAgent env wrapper contains custom behavior and will be overwritten.",
687687
);
688-
expect(service.restart).toHaveBeenCalledWith(
688+
expect(service.start).toHaveBeenCalledWith(
689689
expect.objectContaining({ warn: expect.any(Function) }),
690690
);
691691
});
@@ -719,7 +719,7 @@ describe("runServiceRestart token drift", () => {
719719
});
720720

721721
expect(repairLoadedService).toHaveBeenCalledTimes(1);
722-
expect(service.restart).not.toHaveBeenCalled();
722+
expect(service.start).not.toHaveBeenCalled();
723723
const payload = readJsonLog<{
724724
result?: string;
725725
message?: string;
@@ -749,12 +749,12 @@ describe("runServiceRestart token drift", () => {
749749
expect(payload.ok).toBe(false);
750750
expect(payload.error).toContain("service needs repair");
751751
expect(payload.hints).toEqual(["openclaw gateway install --force"]);
752-
expect(service.restart).not.toHaveBeenCalled();
752+
expect(service.start).not.toHaveBeenCalled();
753753
});
754754

755-
it("fails start when restarting a stopped installed service errors", async () => {
755+
it("fails start when starting a stopped installed service errors", async () => {
756756
service.isLoaded.mockResolvedValue(false);
757-
service.restart.mockRejectedValue(new Error("launchctl kickstart failed: permission denied"));
757+
service.start.mockRejectedValue(new Error("launchctl kickstart failed: permission denied"));
758758

759759
await expect(runServiceStart(createServiceRunArgs())).rejects.toThrow("__exit__:1");
760760

@@ -788,6 +788,6 @@ describe("runServiceRestart token drift", () => {
788788
(item) => item.kind === "install" && item.text === "openclaw gateway install",
789789
),
790790
).toBe(true);
791-
expect(service.restart).not.toHaveBeenCalled();
791+
expect(service.start).not.toHaveBeenCalled();
792792
});
793793
});

‎src/cli/daemon-cli/test-helpers/lifecycle-core-harness.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ type LifecycleServiceHarness = GatewayService & {
1212
stage: MockFn<GatewayService["stage"]>;
1313
install: MockFn<GatewayService["install"]>;
1414
uninstall: MockFn<GatewayService["uninstall"]>;
15+
start: MockFn<GatewayService["start"]>;
1516
stop: MockFn<GatewayService["stop"]>;
1617
isLoaded: MockFn<GatewayService["isLoaded"]>;
1718
readCommand: MockFn<GatewayService["readCommand"]>;
@@ -28,6 +29,7 @@ export const service: LifecycleServiceHarness = {
2829
stage: vi.fn(),
2930
install: vi.fn(),
3031
uninstall: vi.fn(),
32+
start: vi.fn(),
3133
stop: vi.fn(),
3234
isLoaded: vi.fn(),
3335
readCommand: vi.fn(),
@@ -43,6 +45,7 @@ export function resetLifecycleServiceMocks() {
4345
service.stage.mockReset();
4446
service.install.mockReset();
4547
service.uninstall.mockReset();
48+
service.start.mockReset();
4649
service.stop.mockReset();
4750
service.isLoaded.mockReset();
4851
service.readCommand.mockReset();
@@ -53,6 +56,7 @@ export function resetLifecycleServiceMocks() {
5356
service.readRuntime.mockResolvedValue({ status: "stopped" });
5457
service.stop.mockResolvedValue(undefined);
5558
service.uninstall.mockResolvedValue(undefined);
59+
service.start.mockResolvedValue({ outcome: "completed" });
5660
service.restart.mockResolvedValue({ outcome: "completed" });
5761
}
5862

‎src/daemon/launchd.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Launchd tests cover macOS service plist generation and command handling.
22
import { PassThrough } from "node:stream";
3+
import { expectDefined } from "@openclaw/normalization-core";
34
import { beforeEach, describe, expect, it, vi } from "vitest";
45
import { deleteTestEnvValue, setTestEnvValue } from "../test-utils/env.js";
56
import { GATEWAY_SERVICE_KIND, GATEWAY_SERVICE_MARKER } from "./constants.js";
@@ -19,6 +20,7 @@ import {
1920
repairLaunchAgentBootstrap,
2021
restartLaunchAgent,
2122
resolveLaunchAgentPlistPath,
23+
startLaunchAgent,
2224
stopLaunchAgent,
2325
} from "./launchd.js";
2426

@@ -1997,6 +1999,66 @@ describe("launchd install", () => {
19971999
expect(onMutation.mock.calls).toEqual([[{ mode: "enable" }], [{ mode: "kickstart" }]]);
19982000
});
19992001

2002+
it("starts a loaded LaunchAgent and audits before output", async () => {
2003+
const env = createDefaultLaunchdEnv();
2004+
const write = vi.fn();
2005+
const onMutation = vi.fn(({ mode }: { mode: string }) => {
2006+
if (mode === "kickstart") {
2007+
throw new Error("audit failed");
2008+
}
2009+
});
2010+
2011+
await expect(
2012+
startLaunchAgent({
2013+
env,
2014+
stdout: { write } as unknown as NodeJS.WritableStream,
2015+
onMutation,
2016+
}),
2017+
).resolves.toEqual({ outcome: "completed" });
2018+
2019+
const domain = typeof process.getuid === "function" ? `gui/${process.getuid()}` : "gui/501";
2020+
const serviceId = `${domain}/ai.openclaw.gateway`;
2021+
expect(state.launchctlCalls).toEqual([
2022+
["enable", serviceId],
2023+
["kickstart", serviceId],
2024+
]);
2025+
expect(onMutation.mock.calls).toEqual([[{ mode: "enable" }], [{ mode: "kickstart" }]]);
2026+
expect(
2027+
expectDefined(onMutation.mock.invocationCallOrder[1], "kickstart audit call order"),
2028+
).toBeLessThan(expectDefined(write.mock.invocationCallOrder[0], "start output call order"));
2029+
});
2030+
2031+
it("bootstraps an unloaded LaunchAgent and audits the successful mutation", async () => {
2032+
const env = createDefaultLaunchdEnv();
2033+
const onMutation = vi.fn();
2034+
state.kickstartError = "Could not find service";
2035+
state.kickstartFailuresRemaining = 1;
2036+
2037+
await startLaunchAgent({ env, stdout: new PassThrough(), onMutation });
2038+
2039+
const domain = typeof process.getuid === "function" ? `gui/${process.getuid()}` : "gui/501";
2040+
const serviceId = `${domain}/ai.openclaw.gateway`;
2041+
expect(state.launchctlCalls).toEqual([
2042+
["enable", serviceId],
2043+
["kickstart", serviceId],
2044+
["bootstrap", domain, resolveLaunchAgentPlistPath(env)],
2045+
]);
2046+
expect(onMutation.mock.calls).toEqual([[{ mode: "enable" }], [{ mode: "bootstrap" }]]);
2047+
});
2048+
2049+
it("audits enable but not kickstart when the later launch fails", async () => {
2050+
const env = createDefaultLaunchdEnv();
2051+
const onMutation = vi.fn();
2052+
state.kickstartError = "Input/output error";
2053+
state.kickstartFailuresRemaining = 1;
2054+
2055+
await expect(startLaunchAgent({ env, stdout: new PassThrough(), onMutation })).rejects.toThrow(
2056+
"launchctl kickstart failed: Input/output error",
2057+
);
2058+
2059+
expect(onMutation.mock.calls).toEqual([[{ mode: "enable" }]]);
2060+
});
2061+
20002062
it("audits kickstart before a later output failure", async () => {
20012063
const env = {
20022064
...createDefaultLaunchdEnv(),

‎src/daemon/launchd.ts‎

Lines changed: 58 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -608,12 +608,15 @@ async function bootstrapLaunchAgentOrThrow(params: {
608608
plistPath: string;
609609
actionHint: string;
610610
onMutation?: (mode: "enable" | "bootstrap") => void;
611+
skipEnable?: boolean;
611612
}) {
612613
// `disable` state survives bootout and plist rewrites; explicit start/repair
613614
// paths must clear it before asking launchd to load the job again.
614-
const enable = await execLaunchctl(["enable", params.serviceTarget]);
615-
if (enable.code === 0) {
616-
params.onMutation?.("enable");
615+
if (!params.skipEnable) {
616+
const enable = await execLaunchctl(["enable", params.serviceTarget]);
617+
if (enable.code === 0) {
618+
params.onMutation?.("enable");
619+
}
617620
}
618621
const boot = await execLaunchctl(["bootstrap", params.domain, params.plistPath]);
619622
if (boot.code === 0) {
@@ -1252,6 +1255,57 @@ async function ensureLaunchAgentLoadedAfterFailure(params: {
12521255
}
12531256
}
12541257

1258+
function createLaunchAgentMutationReporter(
1259+
onMutation: GatewayServiceControlArgs["onMutation"],
1260+
): (mode: string) => void {
1261+
return (mode) => {
1262+
try {
1263+
onMutation?.({ mode });
1264+
} catch {
1265+
// Audit observers are diagnostic; never interrupt service control.
1266+
}
1267+
};
1268+
}
1269+
1270+
export async function startLaunchAgent({
1271+
stdout,
1272+
env,
1273+
onMutation,
1274+
}: GatewayServiceControlArgs): Promise<GatewayServiceRestartResult> {
1275+
const serviceEnv = env ?? (process.env as GatewayServiceEnv);
1276+
const domain = resolveGuiDomain();
1277+
const label = resolveLaunchAgentLabel({ env: serviceEnv });
1278+
const plistPath = resolveLaunchAgentPlistPath(serviceEnv);
1279+
const serviceTarget = `${domain}/${label}`;
1280+
const reportMutation = createLaunchAgentMutationReporter(onMutation);
1281+
1282+
// Enable is an independent mutation; audit it even if the later launch fails.
1283+
const enable = await execLaunchctl(["enable", serviceTarget]);
1284+
const enabled = enable.code === 0;
1285+
if (enabled) {
1286+
reportMutation("enable");
1287+
}
1288+
1289+
const start = await execLaunchctl(["kickstart", serviceTarget]);
1290+
if (start.code === 0) {
1291+
reportMutation("kickstart");
1292+
} else if (isLaunchctlNotLoaded(start)) {
1293+
await bootstrapLaunchAgentOrThrow({
1294+
domain,
1295+
serviceTarget,
1296+
plistPath,
1297+
actionHint: "openclaw gateway start",
1298+
onMutation: reportMutation,
1299+
skipEnable: enabled,
1300+
});
1301+
} else {
1302+
throw new Error(`launchctl kickstart failed: ${start.stderr || start.stdout}`.trim());
1303+
}
1304+
1305+
writeLaunchAgentActionLine(stdout, "Started LaunchAgent", serviceTarget);
1306+
return { outcome: "completed" };
1307+
}
1308+
12551309
export async function restartLaunchAgent({
12561310
stdout,
12571311
env,
@@ -1263,13 +1317,7 @@ export async function restartLaunchAgent({
12631317
const label = resolveLaunchAgentLabel({ env: serviceEnv });
12641318
const plistPath = resolveLaunchAgentPlistPath(serviceEnv);
12651319
const serviceTarget = `${domain}/${label}`;
1266-
const reportMutation = (mode: string) => {
1267-
try {
1268-
onMutation?.({ mode });
1269-
} catch {
1270-
// Audit observers are diagnostic; never interrupt a multi-step restart.
1271-
}
1272-
};
1320+
const reportMutation = createLaunchAgentMutationReporter(onMutation);
12731321

12741322
// Restart requests issued from inside the managed gateway process tree need a
12751323
// detached handoff. A direct `kickstart -k` would terminate the caller before

‎src/daemon/node-service.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ export function resolveNodeService(): GatewayService {
6161
uninstall: async (args) => {
6262
return base.uninstall({ ...args, env: withNodeServiceEnv(args.env) });
6363
},
64+
start: async (args) => {
65+
return base.start({ ...args, env: withNodeServiceEnv(args.env ?? {}) });
66+
},
6467
stop: async (args) => {
6568
return base.stop({ ...args, env: withNodeServiceEnv(args.env ?? {}) });
6669
},

0 commit comments

Comments
 (0)