Skip to content

Commit ae21f3c

Browse files
fix(daemon): skip unlabeled launchd plists (#119091)
1 parent 7aa3642 commit ae21f3c

4 files changed

Lines changed: 295 additions & 30 deletions

File tree

‎.agents/skills/openclaw-live-updater/scripts/update-main.mjs‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1036,18 +1036,25 @@ export function assertNoSystemLaunchDaemonOwnership(label, dependencies = {}) {
10361036
}
10371037
for (const entry of entries.filter((candidate) => candidate.endsWith(".plist")).toSorted()) {
10381038
const plistPath = path.join(SYSTEM_LAUNCH_DAEMON_DIR, entry);
1039-
const result = run(
1040-
"/usr/bin/plutil",
1041-
["-extract", "Label", "raw", "-o", "-", "--", plistPath],
1042-
{ encoding: "utf8" },
1043-
);
1039+
const result = run("/usr/bin/plutil", ["-convert", "json", "-o", "-", "--", plistPath], {
1040+
encoding: "utf8",
1041+
});
10441042
if (result.status !== 0) {
10451043
throw new UpdateInvariantError(
10461044
"gateway_system_launchdaemon_unverifiable",
10471045
`could not inspect system LaunchDaemon plist ${plistPath}`,
10481046
);
10491047
}
1050-
if (String(result.stdout).trim() === label) {
1048+
let plist;
1049+
try {
1050+
plist = JSON.parse(String(result.stdout));
1051+
} catch {
1052+
throw new UpdateInvariantError(
1053+
"gateway_system_launchdaemon_unverifiable",
1054+
`could not inspect system LaunchDaemon plist ${plistPath}`,
1055+
);
1056+
}
1057+
if (plist?.Label === label) {
10511058
throw new UpdateInvariantError(
10521059
"gateway_system_launchdaemon_conflict",
10531060
`System LaunchDaemon plist ${plistPath} already owns the managed Gateway label`,

‎src/daemon/launchd-system.test.ts‎

Lines changed: 111 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
// System launchd ownership tests cover loaded, installed, and unverifiable states.
2+
import { execFileSync } from "node:child_process";
3+
import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
4+
import path from "node:path";
25
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
37

48
const state = vi.hoisted(() => ({
59
launchctl: { stdout: "", stderr: "Could not find service", code: 113 },
610
files: new Map<string, string>(),
711
accessErrors: new Map<string, string>(),
812
readdirError: "",
9-
plutilLabels: new Map<string, string>(),
13+
plutilValues: new Map<string, unknown>(),
14+
plutilErrors: new Map<string, string>(),
1015
}));
1116

1217
function fsError(code: string, target: string): NodeJS.ErrnoException {
@@ -57,10 +62,10 @@ vi.mock("./launchd-exec.js", () => ({
5762
const execFileUtf8 = vi.hoisted(() =>
5863
vi.fn(async (_command: string, args: string[]) => {
5964
const target = args.at(-1) ?? "";
60-
const label = state.plutilLabels.get(target);
61-
return label
62-
? { stdout: `${label}\n`, stderr: "", code: 0 }
63-
: { stdout: "", stderr: "missing Label", code: 1 };
65+
const error = state.plutilErrors.get(target);
66+
return error
67+
? { stdout: "", stderr: error, code: 1 }
68+
: { stdout: JSON.stringify(state.plutilValues.get(target) ?? {}), stderr: "", code: 0 };
6469
}),
6570
);
6671

@@ -72,6 +77,57 @@ import {
7277
renderSystemLaunchDaemonOwnershipShellProbe,
7378
} from "./launchd-system.js";
7479

80+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
81+
const hostPlatform = process.platform;
82+
83+
function runRenderedProbe(plistName: string, plistMode: "unlabeled" | "same-label" | "malformed") {
84+
const root = tempDirs.make("openclaw-launchd-probe-");
85+
const daemonsDir = path.join(root, "daemons");
86+
const binDir = path.join(root, "bin");
87+
mkdirSync(daemonsDir);
88+
mkdirSync(binDir);
89+
writeFileSync(path.join(daemonsDir, plistName), `${plistMode}\n`);
90+
const plutilShim = path.join(binDir, "plutil");
91+
writeFileSync(
92+
plutilShim,
93+
`#!/bin/sh
94+
mode=$1
95+
for last; do :; done
96+
fixture=$(cat "$last")
97+
if [ "$mode" = "-extract" ]; then
98+
if [ "$fixture" = "same-label" ]; then
99+
printf '%s\\n' "ai.openclaw.gateway"
100+
exit 0
101+
fi
102+
printf '%s\\n' "No value at that key path: Label" >&2
103+
exit 1
104+
fi
105+
if [ "$mode" = "-lint" ] && [ "$fixture" != "malformed" ]; then
106+
exit 0
107+
fi
108+
exit 1
109+
`,
110+
{ mode: 0o700 },
111+
);
112+
const launchctlShim = path.join(binDir, "launchctl");
113+
writeFileSync(
114+
launchctlShim,
115+
'#!/bin/sh\nprintf "%s\\n" "Could not find service" >&2\nexit 113\n',
116+
{ mode: 0o700 },
117+
);
118+
chmodSync(plutilShim, 0o700);
119+
chmodSync(launchctlShim, 0o700);
120+
const script = renderSystemLaunchDaemonOwnershipShellProbe("ai.openclaw.gateway")
121+
.replaceAll("/Library/LaunchDaemons", daemonsDir)
122+
.replaceAll("/usr/bin/plutil", plutilShim)
123+
.concat('printf "conflict=%s\\n" "$openclaw_system_launchd_conflict"\n');
124+
const shell = hostPlatform === "darwin" ? "/bin/sh" : "/bin/bash";
125+
return execFileSync(shell, ["-c", script], {
126+
encoding: "utf8",
127+
env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ""}` },
128+
}).match(/^conflict=(.*)$/m)?.[1];
129+
}
130+
75131
describe("system LaunchDaemon ownership", () => {
76132
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
77133

@@ -81,7 +137,8 @@ describe("system LaunchDaemon ownership", () => {
81137
state.files.clear();
82138
state.accessErrors.clear();
83139
state.readdirError = "";
84-
state.plutilLabels.clear();
140+
state.plutilValues.clear();
141+
state.plutilErrors.clear();
85142
if (originalPlatformDescriptor) {
86143
Object.defineProperty(process, "platform", {
87144
...originalPlatformDescriptor,
@@ -120,7 +177,7 @@ describe("system LaunchDaemon ownership", () => {
120177
it("detects the canonical unloaded plist by its structural Label", async () => {
121178
const plistPath = "/Library/LaunchDaemons/ai.openclaw.gateway.plist";
122179
state.files.set(plistPath, "bplist00-binary-payload");
123-
state.plutilLabels.set(plistPath, "ai.openclaw.gateway");
180+
state.plutilValues.set(plistPath, { Label: "ai.openclaw.gateway" });
124181

125182
await expect(inspectSystemLaunchDaemonOwnership("ai.openclaw.gateway")).resolves.toEqual({
126183
status: "installed",
@@ -135,7 +192,7 @@ describe("system LaunchDaemon ownership", () => {
135192
plistPath,
136193
"<plist><dict><key>Label</key><string>ai.openclaw.gateway</string></dict></plist>",
137194
);
138-
state.plutilLabels.set(plistPath, "ai.openclaw.gateway");
195+
state.plutilValues.set(plistPath, { Label: "ai.openclaw.gateway" });
139196

140197
const ownership = await inspectSystemLaunchDaemonOwnership("ai.openclaw.gateway");
141198

@@ -149,7 +206,7 @@ describe("system LaunchDaemon ownership", () => {
149206
plistPath,
150207
"<plist><dict><key>EnvironmentVariables</key><dict><key>Label</key><string>nested</string></dict><key>Label</key><string>ai.openclaw.gateway</string></dict></plist>",
151208
);
152-
state.plutilLabels.set(plistPath, "ai.openclaw.gateway");
209+
state.plutilValues.set(plistPath, { Label: "ai.openclaw.gateway" });
153210

154211
await expect(inspectSystemLaunchDaemonOwnership("ai.openclaw.gateway")).resolves.toMatchObject({
155212
status: "installed",
@@ -160,26 +217,54 @@ describe("system LaunchDaemon ownership", () => {
160217
it("uses native plutil for binary and non-XML plist formats", async () => {
161218
const plistPath = "/Library/LaunchDaemons/binary-openclaw.plist";
162219
state.files.set(plistPath, "bplist00-binary-payload");
163-
state.plutilLabels.set(plistPath, "ai.openclaw.gateway");
220+
state.plutilValues.set(plistPath, { Label: "ai.openclaw.gateway" });
164221

165222
const ownership = await inspectSystemLaunchDaemonOwnership("ai.openclaw.gateway");
166223

167224
expect(ownership).toMatchObject({ status: "installed", plistPath });
168225
expect(execFileUtf8).toHaveBeenCalledWith("/usr/bin/plutil", [
169-
"-extract",
170-
"Label",
171-
"raw",
226+
"-convert",
227+
"json",
172228
"-o",
173229
"-",
174230
"--",
175231
plistPath,
176232
]);
177233
});
178234

235+
it("skips a valid plist without a string Label and detects a later owner", async () => {
236+
const unrelated = "/Library/LaunchDaemons/com.google.keystone.daemon.plist";
237+
const owner = "/Library/LaunchDaemons/vendor-openclaw.plist";
238+
state.files.set(unrelated, "<plist><dict><key>RunAtLoad</key><true/></dict></plist>");
239+
state.plutilValues.set(unrelated, { RunAtLoad: true });
240+
state.files.set(owner, "<plist/>");
241+
state.plutilValues.set(owner, { Label: "ai.openclaw.gateway" });
242+
243+
await expect(inspectSystemLaunchDaemonOwnership("ai.openclaw.gateway")).resolves.toEqual({
244+
status: "installed",
245+
serviceTarget: "system/ai.openclaw.gateway",
246+
plistPath: owner,
247+
});
248+
expect(execFileUtf8).toHaveBeenCalledTimes(2);
249+
});
250+
251+
it("treats a valid non-string Label as unable to own the gateway label", async () => {
252+
const unrelated = "/Library/LaunchDaemons/com.vendor.numeric-label.plist";
253+
state.files.set(unrelated, "<plist/>");
254+
state.plutilValues.set(unrelated, { Label: 42 });
255+
256+
await expect(inspectSystemLaunchDaemonOwnership("ai.openclaw.gateway")).resolves.toEqual({
257+
status: "absent",
258+
serviceTarget: "system/ai.openclaw.gateway",
259+
});
260+
expect(execLaunchctl).toHaveBeenCalledTimes(2);
261+
});
262+
179263
it("fails closed on an unreadable noncanonical vendor plist", async () => {
180264
const unrelated = "/Library/LaunchDaemons/com.vendor.locked.plist";
181265
state.files.set(unrelated, "<plist/>");
182266
state.accessErrors.set(unrelated, "EACCES");
267+
state.plutilErrors.set(unrelated, "Operation not permitted");
183268

184269
await expect(inspectSystemLaunchDaemonOwnership("ai.openclaw.gateway")).resolves.toEqual({
185270
status: "unverifiable",
@@ -240,6 +325,9 @@ describe("system LaunchDaemon ownership", () => {
240325
expect(script).toContain(
241326
'/usr/bin/plutil -extract Label raw -o - -- "$openclaw_system_launchd_plist"',
242327
);
328+
expect(script).toContain(
329+
'/usr/bin/plutil -lint -- "$openclaw_system_launchd_plist" >/dev/null 2>&1',
330+
);
243331
expect(script).toContain(
244332
"/usr/bin/find \"$openclaw_system_launchd_dir\" -mindepth 1 -maxdepth 1 -name '*.plist' -print0",
245333
);
@@ -251,4 +339,14 @@ describe("system LaunchDaemon ownership", () => {
251339
);
252340
expect(script).not.toContain("|| true");
253341
});
342+
343+
it("executes the rendered probe across unlabeled, same-label, and malformed plists", () => {
344+
expect(runRenderedProbe("com.google.keystone.daemon.plist", "unlabeled")).toBe("");
345+
expect(runRenderedProbe("vendor-openclaw.plist", "same-label")).toContain(
346+
"vendor-openclaw.plist",
347+
);
348+
expect(runRenderedProbe("com.vendor.broken.plist", "malformed")).toContain(
349+
"com.vendor.broken.plist",
350+
);
351+
});
254352
});

‎src/daemon/launchd-system.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ if [ -z "$openclaw_system_launchd_conflict" ]; then
7878
openclaw_system_launchd_conflict="$openclaw_system_launchd_plist"
7979
openclaw_system_launchd_detail="installed same-label system LaunchDaemon plist $openclaw_system_launchd_plist"
8080
break
81+
elif /usr/bin/plutil -lint -- "$openclaw_system_launchd_plist" >/dev/null 2>&1; then
82+
continue
8183
else
8284
openclaw_system_launchd_conflict="$openclaw_system_launchd_plist"
8385
openclaw_system_launchd_detail="could not inspect system LaunchDaemon plist $openclaw_system_launchd_plist: $openclaw_system_launchd_plist_label"
@@ -111,25 +113,32 @@ fi
111113

112114
type LaunchDaemonPlistLabelResult =
113115
| { status: "ok"; label: string }
116+
| { status: "unlabeled" }
114117
| { status: "missing" }
115118
| { status: "unverifiable"; detail: string };
116119

117120
/** Reads the top-level Label through the native parser for XML and binary plists. */
118121
export async function readLaunchDaemonPlistLabel(
119122
plistPath: string,
120123
): Promise<LaunchDaemonPlistLabelResult> {
121-
const extracted = await execFileUtf8(PLUTIL_PATH, [
122-
"-extract",
123-
"Label",
124-
"raw",
124+
const converted = await execFileUtf8(PLUTIL_PATH, [
125+
"-convert",
126+
"json",
125127
"-o",
126128
"-",
127129
"--",
128130
plistPath,
129131
]);
130-
const label = extracted.stdout.trim();
131-
if (extracted.code === 0 && label) {
132-
return { status: "ok", label };
132+
if (converted.code === 0) {
133+
try {
134+
const plist = JSON.parse(converted.stdout) as { Label?: unknown } | null;
135+
const label = plist?.Label;
136+
return typeof label === "string" && label.length > 0
137+
? { status: "ok", label }
138+
: { status: "unlabeled" };
139+
} catch (error) {
140+
return { status: "unverifiable", detail: formatUnknownError(error) };
141+
}
133142
}
134143
try {
135144
await fs.access(plistPath);
@@ -141,7 +150,7 @@ export async function readLaunchDaemonPlistLabel(
141150
}
142151
return {
143152
status: "unverifiable",
144-
detail: formatLaunchctlResultDetail(extracted) || "plutil did not return a Label",
153+
detail: formatLaunchctlResultDetail(converted) || "plutil could not decode the plist",
145154
};
146155
}
147156

0 commit comments

Comments
 (0)