Skip to content

Commit 895b691

Browse files
fix(daemon): refuse duplicate launchd gateway managers (#97285)
* fix(daemon): block duplicate launchd owners Co-authored-by: Harjoth Khara <[email protected]> * fix(ci): satisfy launchd docs and lint gates * fix(ci): remove unused launchd exports * docs: refresh gateway map --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 9155d90 commit 895b691

25 files changed

Lines changed: 1372 additions & 154 deletions

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3714,6 +3714,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
37143714
- H2: Multiple gateways (same host)
37153715
- H2: Remote access
37163716
- H2: Supervision and service lifecycle
3717+
- H3: Existing system LaunchDaemons
37173718
- H2: Dev profile quick path
37183719
- H2: Protocol quick reference (operator view)
37193720
- H2: Operational checks

‎docs/gateway/doctor.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,7 @@ That stages grounded durable candidates into the short-term dreaming store while
584584
- `openclaw doctor --fix` applies recommended fixes without prompts (`--repair` is an alias).
585585
- `openclaw doctor --fix --force` overwrites custom supervisor configs.
586586
- `OPENCLAW_SERVICE_REPAIR_POLICY=external` keeps doctor read-only for gateway service lifecycle. It still reports service health and runs non-service repairs, but skips service install/start/restart/bootstrap, supervisor config rewrites, and legacy service cleanup because an external supervisor owns that lifecycle.
587+
- On macOS, a same-label system LaunchDaemon blocks user LaunchAgent install, start, restart, and bootstrap repair. Doctor reports the system owner and stops service recovery; `--force` does not bypass this ownership boundary. See [Existing system LaunchDaemons](/gateway#existing-system-launchdaemons).
587588
- On Linux, doctor does not rewrite command/entrypoint metadata while the matching systemd gateway unit is active. It also ignores inactive non-legacy extra gateway-like units during the duplicate-service scan so companion service files do not create cleanup noise.
588589
- If token auth requires a token and `gateway.auth.token` is SecretRef-managed, doctor service install/repair validates the SecretRef but does not persist resolved plaintext token values into supervisor service environment metadata.
589590
- Doctor detects managed `.env`/SecretRef-backed service environment values that older LaunchAgent, systemd, or Windows Scheduled Task installs embedded inline and rewrites the service metadata so those values load from the runtime source instead of the supervisor definition.

‎docs/gateway/index.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,19 @@ On macOS, `gateway stop` uses `launchctl bootout` by default. This removes the L
205205

206206
LaunchAgent labels are `ai.openclaw.gateway` (default) or `ai.openclaw.<profile>` (named profile). `openclaw doctor` audits and repairs service config drift.
207207

208+
### Existing system LaunchDaemons
209+
210+
OpenClaw installs and manages a per-user LaunchAgent. It does not install or manage system LaunchDaemons. If a custom LaunchDaemon already uses the same gateway label, OpenClaw refuses to write, start, restart, or repair a user LaunchAgent because two `KeepAlive` managers can repeatedly restart the same gateway.
211+
212+
The ownership check reads `launchctl print system/<label>` and also checks installed plists under `/Library/LaunchDaemons`. It fails closed when system ownership cannot be verified, and `--force` does not bypass it. `openclaw gateway status` reports a loaded same-label system job; add `--deep` to scan installed system service files.
213+
214+
Choose one lifecycle owner before retrying:
215+
216+
- To keep the custom system LaunchDaemon, remove any competing user LaunchAgent and set `OPENCLAW_SERVICE_REPAIR_POLICY=external` when running Doctor so it remains diagnostic-only for service lifecycle.
217+
- To return to the supported user LaunchAgent, unload the system job with `sudo launchctl bootout system/<label>`, remove or relocate its actual plist, sign in to the macOS desktop as the target user, then run `openclaw gateway install`.
218+
219+
For the default profile, `<label>` is `ai.openclaw.gateway`. Named profiles use `ai.openclaw.<profile>`.
220+
208221
</Tab>
209222

210223
<Tab title="Linux (systemd user)">

‎src/cli/daemon-cli/launchd-recovery.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
33

44
const launchAgentPlistExists = vi.hoisted(() => vi.fn());
55
const repairLaunchAgentBootstrap = vi.hoisted(() => vi.fn());
6+
const assertNoSystemLaunchDaemonOwnership = vi.hoisted(() => vi.fn());
67

78
vi.mock("../../daemon/launchd.js", () => ({
89
formatLaunchAgentGuiSessionError: (params: {
@@ -17,6 +18,13 @@ vi.mock("../../daemon/launchd.js", () => ({
1718
launchAgentPlistExists: (env: Record<string, string | undefined>) => launchAgentPlistExists(env),
1819
repairLaunchAgentBootstrap: (args: { env?: Record<string, string | undefined> }) =>
1920
repairLaunchAgentBootstrap(args),
21+
resolveLaunchAgentLabel: (env: Record<string, string | undefined>) =>
22+
env.OPENCLAW_LAUNCHD_LABEL ?? "ai.openclaw.gateway",
23+
}));
24+
25+
vi.mock("../../daemon/launchd-system.js", () => ({
26+
assertNoSystemLaunchDaemonOwnership: (label: string) =>
27+
assertNoSystemLaunchDaemonOwnership(label),
2028
}));
2129

2230
let recoverInstalledLaunchAgent: typeof import("./launchd-recovery.js").recoverInstalledLaunchAgent;
@@ -29,6 +37,8 @@ describe("recoverInstalledLaunchAgent", () => {
2937
beforeEach(() => {
3038
launchAgentPlistExists.mockReset();
3139
repairLaunchAgentBootstrap.mockReset();
40+
assertNoSystemLaunchDaemonOwnership.mockReset();
41+
assertNoSystemLaunchDaemonOwnership.mockResolvedValue(undefined);
3242
launchAgentPlistExists.mockResolvedValue(false);
3343
repairLaunchAgentBootstrap.mockResolvedValue({ ok: true, status: "repaired" });
3444
});
@@ -38,13 +48,15 @@ describe("recoverInstalledLaunchAgent", () => {
3848

3949
await expect(recoverInstalledLaunchAgent({ result: "started" })).resolves.toBeNull();
4050
expect(launchAgentPlistExists).not.toHaveBeenCalled();
51+
expect(assertNoSystemLaunchDaemonOwnership).not.toHaveBeenCalled();
4152
});
4253

4354
it("returns null when the LaunchAgent plist is missing", async () => {
4455
vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
4556
launchAgentPlistExists.mockResolvedValue(false);
4657

4758
await expect(recoverInstalledLaunchAgent({ result: "started" })).resolves.toBeNull();
59+
expect(assertNoSystemLaunchDaemonOwnership).toHaveBeenCalledWith("ai.openclaw.gateway");
4860
expect(repairLaunchAgentBootstrap).not.toHaveBeenCalled();
4961
});
5062

@@ -87,4 +99,34 @@ describe("recoverInstalledLaunchAgent", () => {
8799
"requires a logged-in macOS GUI session",
88100
);
89101
});
102+
103+
it("surfaces system ownership even when no user LaunchAgent plist exists", async () => {
104+
vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
105+
launchAgentPlistExists.mockResolvedValue(false);
106+
assertNoSystemLaunchDaemonOwnership.mockRejectedValue(
107+
new Error("System LaunchDaemon system/ai.openclaw.gateway owns this label"),
108+
);
109+
110+
await expect(recoverInstalledLaunchAgent({ result: "started" })).rejects.toThrow(
111+
"System LaunchDaemon system/ai.openclaw.gateway owns this label",
112+
);
113+
expect(launchAgentPlistExists).not.toHaveBeenCalled();
114+
});
115+
116+
it.each(["system-launchdaemon-conflict", "system-launchdaemon-unverifiable"] as const)(
117+
"preserves typed %s bootstrap failures",
118+
async (status) => {
119+
vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
120+
launchAgentPlistExists.mockResolvedValue(true);
121+
repairLaunchAgentBootstrap.mockResolvedValue({
122+
ok: false,
123+
status,
124+
detail: "system ownership recovery guidance",
125+
});
126+
127+
await expect(recoverInstalledLaunchAgent({ result: "restarted" })).rejects.toThrow(
128+
"system ownership recovery guidance",
129+
);
130+
},
131+
);
90132
});

‎src/cli/daemon-cli/launchd-recovery.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import { assertNoSystemLaunchDaemonOwnership } from "../../daemon/launchd-system.js";
12
// macOS LaunchAgent recovery helper for daemon lifecycle commands.
23
import {
34
formatLaunchAgentGuiSessionError,
45
launchAgentPlistExists,
56
repairLaunchAgentBootstrap,
7+
resolveLaunchAgentLabel,
68
} from "../../daemon/launchd.js";
79

810
const LAUNCH_AGENT_RECOVERY_MESSAGE =
@@ -27,6 +29,10 @@ export async function recoverInstalledLaunchAgent<
2729
return null;
2830
}
2931
const env = params.env ?? (process.env as Record<string, string | undefined>);
32+
// Check host-wide ownership even when no user plist exists. Otherwise start
33+
// and restart would report "not installed" for a gateway already supervised
34+
// by a same-label system LaunchDaemon.
35+
await assertNoSystemLaunchDaemonOwnership(resolveLaunchAgentLabel(env));
3036
const plistExists = await launchAgentPlistExists(env).catch(() => false);
3137
if (!plistExists) {
3238
return null;
@@ -36,6 +42,12 @@ export async function recoverInstalledLaunchAgent<
3642
status: "bootstrap-failed" as const,
3743
}));
3844
if (!repaired.ok) {
45+
if (
46+
repaired.status === "system-launchdaemon-conflict" ||
47+
repaired.status === "system-launchdaemon-unverifiable"
48+
) {
49+
throw new Error(repaired.detail);
50+
}
3951
if (repaired.status === "gui-session-unavailable") {
4052
const actionHint =
4153
params.result === "started" ? "openclaw gateway start" : "openclaw gateway restart";
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// Update restart handoff tests cover system-domain ownership checks at execution time.
2+
import { execFile } from "node:child_process";
3+
import fs from "node:fs/promises";
4+
import os from "node:os";
5+
import path from "node:path";
6+
import { promisify } from "node:util";
7+
import { afterEach, describe, expect, it } from "vitest";
8+
import { prepareRestartScript } from "./restart-helper.js";
9+
10+
const execFileAsync = promisify(execFile);
11+
12+
describe("macOS update restart system ownership", () => {
13+
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
14+
const originalGetuid = process.getuid;
15+
16+
afterEach(() => {
17+
if (originalPlatformDescriptor) {
18+
Object.defineProperty(process, "platform", originalPlatformDescriptor);
19+
}
20+
process.getuid = originalGetuid;
21+
});
22+
23+
it("refuses the detached handoff before user activation when a system owner appears", async () => {
24+
Object.defineProperty(process, "platform", {
25+
...originalPlatformDescriptor,
26+
value: "darwin",
27+
});
28+
process.getuid = () => 501;
29+
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-restart-system-"));
30+
const fakeBinDir = path.join(tmpDir, "bin");
31+
const stateDir = path.join(tmpDir, "state");
32+
const activationMarker = path.join(tmpDir, "activation-ran");
33+
await fs.mkdir(fakeBinDir, { recursive: true });
34+
await fs.writeFile(path.join(fakeBinDir, "sleep"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
35+
await fs.writeFile(
36+
path.join(fakeBinDir, "launchctl"),
37+
`#!/bin/sh
38+
if [ "$1" = "print" ] && [ "$2" = "system/ai.openclaw.gateway" ]; then
39+
exit 0
40+
fi
41+
printf activated > "$ACTIVATION_MARKER"
42+
exit 0
43+
`,
44+
{ mode: 0o755 },
45+
);
46+
47+
try {
48+
const scriptPath = await prepareRestartScript({
49+
OPENCLAW_PROFILE: "default",
50+
HOME: path.join(tmpDir, "home"),
51+
OPENCLAW_STATE_DIR: stateDir,
52+
});
53+
if (!scriptPath) {
54+
throw new Error("expected restart script path");
55+
}
56+
let exitCode: number | null = null;
57+
try {
58+
await execFileAsync("/bin/sh", [scriptPath], {
59+
env: {
60+
...process.env,
61+
ACTIVATION_MARKER: activationMarker,
62+
PATH: `${fakeBinDir}:${process.env.PATH ?? ""}`,
63+
},
64+
});
65+
} catch (error) {
66+
const code = (error as { code?: unknown }).code;
67+
exitCode = typeof code === "number" ? code : null;
68+
}
69+
const log = await fs.readFile(path.join(stateDir, "logs", "gateway-restart.log"), "utf8");
70+
71+
expect(exitCode).toBe(78);
72+
await expect(fs.access(activationMarker)).rejects.toMatchObject({ code: "ENOENT" });
73+
expect(log).toContain("openclaw restart blocked source=update");
74+
expect(log).toContain("loaded system LaunchDaemon system/ai.openclaw.gateway");
75+
} finally {
76+
await fs.rm(tmpDir, { recursive: true, force: true });
77+
}
78+
});
79+
});

‎src/cli/update-cli/restart-helper.test.ts‎

Lines changed: 24 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -139,9 +139,21 @@ case "$1" in
139139
esac
140140
exit 0
141141
`,
142+
systemOwnership: "absent" | "loaded" = "absent",
142143
) {
143144
const launchctlPath = path.join(fakeBinDir, "launchctl");
144-
await fs.writeFile(launchctlPath, content, { mode: 0o755 });
145+
const body = content.replace(/^#!\/bin\/sh\r?\n/, "");
146+
await fs.writeFile(
147+
launchctlPath,
148+
`#!/bin/sh
149+
if [ "$1" = "print" ]; then
150+
case "$2" in
151+
system/*) ${systemOwnership === "loaded" ? "exit 0" : "printf 'Could not find service\\n' >&2; exit 113"} ;;
152+
esac
153+
fi
154+
${body}`,
155+
{ mode: 0o755 },
156+
);
145157
}
146158

147159
async function writeFakeSleep(fakeBinDir: string) {
@@ -634,30 +646,13 @@ exit 0
634646
await expect(fs.readFile(markerPath, "utf-8")).resolves.toBe("ran");
635647
});
636648

637-
it("logs custom macOS launchd labels without shell expansion", async () => {
649+
it("rejects custom macOS launchd labels with shell metacharacters", async () => {
638650
Object.defineProperty(process, "platform", { value: "darwin" });
639651
process.getuid = () => 501;
640-
const tmpDir = await makeTempDir("openclaw-restart-helper-");
641-
const fakeBinDir = path.join(tmpDir, "bin");
642-
const stateDir = path.join(tmpDir, "state");
643-
await fs.mkdir(fakeBinDir, { recursive: true });
644-
await writeFakeSleep(fakeBinDir);
645-
await writeFakeLaunchctl(fakeBinDir);
646-
647-
const { scriptPath } = await prepareAndReadScript({
648-
OPENCLAW_LAUNCHD_LABEL: "ai.openclaw.$(echo injected)",
649-
HOME: path.join(tmpDir, "home"),
650-
OPENCLAW_STATE_DIR: stateDir,
651-
});
652652

653-
const result = await executeScript(scriptPath, {
654-
PATH: `${fakeBinDir}:${process.env.PATH ?? ""}`,
655-
});
656-
const log = await fs.readFile(path.join(stateDir, "logs", "gateway-restart.log"), "utf-8");
657-
658-
expect(result.code).toBeNull();
659-
expect(log).toContain("target=ai.openclaw.$(echo injected)");
660-
expect(log).not.toContain("target=ai.openclaw.injected");
653+
await expect(
654+
prepareRestartScript({ OPENCLAW_LAUNCHD_LABEL: "ai.openclaw.$(echo injected)" }),
655+
).resolves.toBeNull();
661656
});
662657

663658
it("uses OPENCLAW_LAUNCHD_LABEL override on macOS", async () => {
@@ -1029,17 +1024,16 @@ Write-Output "OPENCLAW_RESTART_POLICY_OK"
10291024
await cleanupScript(scriptPath);
10301025
});
10311026

1032-
it("shell-escapes the label in the plist path on macOS", async () => {
1027+
it("rejects a launchd label that the lifecycle path cannot use", async () => {
10331028
Object.defineProperty(process, "platform", { value: "darwin" });
10341029
process.getuid = () => 501;
10351030

1036-
const { scriptPath, content } = await prepareAndReadScript({
1037-
HOME: "/Users/testuser",
1038-
OPENCLAW_LAUNCHD_LABEL: "ai.openclaw.it's-a-test",
1039-
});
1040-
// The plist path must also shell-escape the label to prevent injection
1041-
expect(content).toContain("ai.openclaw.it'\\''s-a-test.plist");
1042-
await cleanupScript(scriptPath);
1031+
await expect(
1032+
prepareRestartScript({
1033+
HOME: "/Users/testuser",
1034+
OPENCLAW_LAUNCHD_LABEL: "ai.openclaw.it's-a-test",
1035+
}),
1036+
).resolves.toBeNull();
10431037
});
10441038

10451039
it("rejects unsafe batch profile names on Windows", async () => {

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

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ import { normalizeOptionalString } from "@openclaw/normalization-core/string-coe
77
import { DEFAULT_GATEWAY_PORT } from "../../config/paths.js";
88
import { quoteCmdScriptArg } from "../../daemon/cmd-argv.js";
99
import {
10-
resolveGatewayLaunchAgentLabel,
1110
resolveGatewaySystemdServiceName,
1211
resolveGatewayWindowsTaskName,
1312
} from "../../daemon/constants.js";
13+
import { resolveLaunchAgentLabel } from "../../daemon/launchd-label.js";
14+
import { renderSystemLaunchDaemonOwnershipShellProbe } from "../../daemon/launchd-system.js";
1415
import { resolveGatewayTaskScriptPath } from "../../daemon/paths.js";
1516
import {
1617
renderPosixRestartLogSetup,
@@ -45,14 +46,6 @@ function resolveSystemdUnit(env: NodeJS.ProcessEnv): string {
4546
return `${resolveGatewaySystemdServiceName(env.OPENCLAW_PROFILE)}.service`;
4647
}
4748

48-
function resolveLaunchdLabel(env: NodeJS.ProcessEnv): string {
49-
const override = normalizeOptionalString(env.OPENCLAW_LAUNCHD_LABEL);
50-
if (override) {
51-
return override;
52-
}
53-
return resolveGatewayLaunchAgentLabel(env.OPENCLAW_PROFILE);
54-
}
55-
5649
function resolveWindowsTaskName(env: NodeJS.ProcessEnv): string {
5750
const override = env.OPENCLAW_WINDOWS_TASK_NAME?.trim();
5851
if (override) {
@@ -187,7 +180,7 @@ rmdir "$script_dir" 2>/dev/null || true
187180
exit "$status"
188181
`;
189182
} else if (platform === "darwin") {
190-
const label = resolveLaunchdLabel(env);
183+
const label = resolveLaunchAgentLabel(env);
191184
const escaped = shellEscape(label);
192185
// Fallback to 501 if getuid is not available (though it should be on macOS)
193186
const uid = process.getuid ? process.getuid() : 501;
@@ -197,6 +190,7 @@ exit "$status"
197190
const plistPath = path.join(home, "Library", "LaunchAgents", `${label}.plist`);
198191
const escapedPlistPath = shellEscape(plistPath);
199192
const logSetup = renderPosixRestartLogSetup({ ...process.env, ...env });
193+
const systemOwnershipProbe = renderSystemLaunchDaemonOwnershipShellProbe(label);
200194
filename = `openclaw-restart-${timestamp}.sh`;
201195
scriptContent = `#!/bin/sh
202196
# Standalone restart script — survives parent process termination.
@@ -207,14 +201,18 @@ sleep 1
207201
# is temporarily unavailable.
208202
${logSetup}
209203
printf '[%s] openclaw restart attempt source=update target=%s\\n' "$(date -u +%FT%TZ)" '${shellEscapeRestartLogValue(label)}' >&2
204+
${systemOwnershipProbe}
210205
# Try kickstart first (works when the service is still registered).
211206
# If it fails (e.g. after bootout), clear any persisted disabled state,
212207
# then re-register via bootstrap. Bootstrap loads RunAtLoad agents, so the
213208
# fallback must not immediately kickstart -k the freshly spawned gateway.
214209
# The final status is captured
215210
# before self-cleanup so a genuine failure remains observable.
216211
status=0
217-
if ! launchctl kickstart -k 'gui/${uid}/${escaped}'; then
212+
if [ -n "$openclaw_system_launchd_conflict" ]; then
213+
status=78
214+
printf '[%s] openclaw restart blocked source=update reason=%s\n' "$(date -u +%FT%TZ)" "$openclaw_system_launchd_detail" >&2
215+
elif ! launchctl kickstart -k 'gui/${uid}/${escaped}'; then
218216
launchctl enable 'gui/${uid}/${escaped}'
219217
if launchctl bootstrap 'gui/${uid}' '${escapedPlistPath}'; then
220218
status=0

0 commit comments

Comments
 (0)