Skip to content

Commit 5d8ef65

Browse files
authored
fix(daemon): explain unsafe service publication failures (#132279)
* fix(daemon): explain service publication authority failures Replace free-form definition mutation details with typed, redacted reasons and shared recovery guidance for install and start/restart repair. Keep all ownership checks and stable update-recovery denial prefixes unchanged. Cover unsafe directory failure and permission-repair recovery without config or service publication before denial or SecretRef bypass afterward. Fixes #132278. * test(daemon): assert typed system ownership diagnostics
1 parent cce893e commit 5d8ef65

12 files changed

Lines changed: 288 additions & 129 deletions

‎docs/cli/gateway.md‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,28 @@ Named profiles must also use the native service identity derived from `OPENCLAW_
154154

155155
On Linux, `openclaw gateway install --force` refuses a sealed systemd service
156156
definition, or one whose write authority cannot be verified, before changing
157-
configuration, authentication tokens, or service files. Ask the privileged deployment owner to repair or replace the definition.
157+
configuration, authentication tokens, or service files. The error keeps its
158+
`SERVICE_DEFINITION_SEALED` or `SERVICE_DEFINITION_UNKNOWN` prefix and adds a
159+
reason tag and next action, without printing private paths, config, environment values,
160+
or underlying inspection errors.
161+
162+
For `[unsafe-permissions]`, inspect the named artifact category locally. The
163+
service directory is `~/.config/systemd/user`; on a fresh install, its nearest
164+
existing ancestor may be `~/.config`. The service state directory belongs to the
165+
selected profile. Check directory metadata, not file contents:
166+
167+
```bash
168+
ls -ld ~/.config ~/.config/systemd ~/.config/systemd/user
169+
```
170+
171+
Missing directories are normal on a fresh install. After confirming the affected
172+
path is yours and is not intentionally shared, remove group/other write access
173+
with `chmod go-w <path>` and retry the same command. Mode `0700` is appropriate
174+
for private directories. Do not recursively chmod, take ownership of system
175+
paths, or use `sudo`/`--force` to bypass the check. Foreign-owned files and sealed
176+
mounts require the deployment owner; inspection failures require restoring
177+
filesystem or native service-manager access first.
178+
158179
Type-wide `service.d` defaults are inspected as shared read-only inputs and do
159180
not require write access. Root-owned selected units and unit-specific drop-ins
160181
remain protected.

‎src/cli/daemon-cli/install.integration.test.ts‎

Lines changed: 78 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ import { makeTempWorkspace } from "../../test-helpers/workspace.js";
1717
import { captureEnv } from "../../test-utils/env.js";
1818
import { createCliRuntimeCapture } from "../test-runtime-capture.js";
1919

20-
const { runtimeLogs, defaultRuntime, resetRuntimeCapture } = createCliRuntimeCapture();
20+
const { runtimeLogs, runtimeErrors, defaultRuntime, resetRuntimeCapture } =
21+
createCliRuntimeCapture();
2122
const busctl = vi.hoisted(() =>
2223
vi.fn<typeof import("../../daemon/systemd-exec.js").execBusctlUser>(),
2324
);
@@ -180,6 +181,69 @@ describe("runDaemonInstall integration", () => {
180181
expect(joined).toContain("MISSING_GATEWAY_TOKEN");
181182
});
182183

184+
it.each([true, false])(
185+
"explains unsafe publication permissions and recovers without bypassing SecretRefs (json=%s)",
186+
async (json) => {
187+
const fixture = await fs.realpath(
188+
await fs.mkdtemp(path.join(tempHome, "private-path-canary-")),
189+
);
190+
const ancestor = path.join(fixture, ".config");
191+
const config = {
192+
gateway: {
193+
auth: {
194+
mode: "token",
195+
token: { source: "env", provider: "default", id: "MISSING_GATEWAY_TOKEN" },
196+
},
197+
},
198+
};
199+
await fs.mkdir(ancestor);
200+
await fs.chmod(ancestor, 0o777);
201+
await fs.writeFile(configPath, JSON.stringify(config));
202+
clearConfigCache();
203+
busctl.mockResolvedValue({
204+
code: 1,
205+
termination: "exit",
206+
stdout: "",
207+
stderr: "Call failed: Unit openclaw-gateway.service not found.",
208+
});
209+
const env = { ...process.env, HOME: fixture, OPENCLAW_SYSTEMD_UNIT: "openclaw-gateway" };
210+
serviceMock.readCommand.mockImplementation((_env, options) =>
211+
readSystemdServiceExecStart(env, options),
212+
);
213+
serviceMock.readDefinitionMutationCapability.mockImplementation(() =>
214+
readSystemdDefinitionMutationCapability(env),
215+
);
216+
const before = await snapshotConfig();
217+
try {
218+
await expect(runDaemonInstall({ json, force: true })).rejects.toThrow("__exit__:1");
219+
expect(await snapshotConfig()).toEqual(before);
220+
expect(await fs.readdir(ancestor)).toEqual([]);
221+
expect(serviceMock.install).not.toHaveBeenCalled();
222+
const output = [...runtimeLogs, ...runtimeErrors].join("\n");
223+
expect(output).toContain("SERVICE_DEFINITION_UNKNOWN");
224+
expect(output).toContain("unsafe-permissions");
225+
expect(output).toContain("service directory");
226+
expect(output).toContain("group/world-writable");
227+
expect(output).toContain("chmod go-w");
228+
expect(output).not.toContain("private-path-canary");
229+
expect(output).not.toContain("MISSING_GATEWAY_TOKEN");
230+
231+
await fs.chmod(ancestor, 0o700);
232+
resetRuntimeCapture();
233+
await expect(runDaemonInstall({ json, force: true })).rejects.toThrow("__exit__:1");
234+
const recovered = [...runtimeLogs, ...runtimeErrors].join("\n");
235+
expect(recovered).not.toContain("SERVICE_DEFINITION_UNKNOWN");
236+
expect(recovered).toContain("SecretRef is configured but unresolved");
237+
expect((await readJson(configPath)).gateway).toEqual({ ...config.gateway, mode: "local" });
238+
expect(await fs.readdir(ancestor)).toEqual([]);
239+
expect(serviceMock.install).not.toHaveBeenCalled();
240+
} finally {
241+
await fs.chmod(ancestor, 0o700);
242+
await fs.rm(fixture, { recursive: true, force: true });
243+
}
244+
},
245+
);
246+
183247
it.each(["fragment", "drop-in"])(
184248
"blocks a root-owned manager %s before config or token writes",
185249
async (kind) => {
@@ -349,19 +413,19 @@ describe("runDaemonInstall integration", () => {
349413
it.each([
350414
{
351415
name: "gateway.mode is missing",
352-
capability: { kind: "sealed" as const, detail: "unit definition is owned by root" },
416+
capability: { kind: "sealed" as const, reason: "foreign-owner" as const },
353417
config: { gateway: { auth: { mode: "token", token: "existing-token" } } },
354418
marker: "SERVICE_DEFINITION_SEALED",
355419
},
356420
{
357421
name: "the gateway token is missing",
358-
capability: { kind: "sealed" as const, detail: "unit definition is owned by root" },
422+
capability: { kind: "sealed" as const, reason: "foreign-owner" as const },
359423
config: { gateway: { mode: "local", auth: { mode: "token" } } },
360424
marker: "SERVICE_DEFINITION_SEALED",
361425
},
362426
{
363427
name: "gateway.mode is missing and definition authority is unknown",
364-
capability: { kind: "unknown" as const, detail: "unit definition cannot be inspected" },
428+
capability: { kind: "unknown" as const, reason: "inspection-failed" as const },
365429
config: { gateway: { auth: { mode: "token" } } },
366430
marker: "SERVICE_DEFINITION_UNKNOWN",
367431
},
@@ -370,7 +434,7 @@ describe("runDaemonInstall integration", () => {
370434
async ({ capability, config, marker }) => {
371435
await fs.writeFile(configPath, JSON.stringify(config, null, 2));
372436
clearConfigCache();
373-
serviceMock.readDefinitionMutationCapability.mockResolvedValueOnce(capability as never);
437+
serviceMock.readDefinitionMutationCapability.mockResolvedValueOnce(capability);
374438
const before = await snapshotConfig();
375439

376440
await expect(runDaemonInstall({ json: true, force: true })).rejects.toThrow("__exit__:1");
@@ -437,8 +501,8 @@ describe("runDaemonInstall integration", () => {
437501
serviceMock.isLoaded.mockResolvedValue(true);
438502
serviceMock.readDefinitionMutationCapability.mockResolvedValue({
439503
kind: "sealed",
440-
detail: "unit definition is owned by root",
441-
} as never);
504+
reason: "foreign-owner",
505+
});
442506
serviceMock.readCommand.mockResolvedValue(await createInstalledServiceCommand());
443507

444508
await runDaemonInstall({ json: true });
@@ -462,8 +526,8 @@ describe("runDaemonInstall integration", () => {
462526
} as never);
463527
serviceMock.readDefinitionMutationCapability.mockResolvedValueOnce({
464528
kind: "sealed",
465-
detail: "unit definition is owned by root",
466-
} as never);
529+
reason: "foreign-owner",
530+
});
467531
const before = await snapshotConfig();
468532

469533
await expect(runDaemonInstall({ json: true })).rejects.toThrow("__exit__:1");
@@ -482,11 +546,10 @@ describe("runDaemonInstall integration", () => {
482546
programArguments: ["openclaw", "gateway", "run"],
483547
environment: { OPENCLAW_STATE_DIR: effectiveStateDir },
484548
} as never);
485-
serviceMock.readDefinitionMutationCapability.mockImplementationOnce(
486-
async (args) =>
487-
(args?.environment?.OPENCLAW_STATE_DIR === effectiveStateDir
488-
? { kind: "sealed", detail: "effective state is owned by root" }
489-
: { kind: "writable" }) as never,
549+
serviceMock.readDefinitionMutationCapability.mockImplementationOnce(async (args) =>
550+
args?.environment?.OPENCLAW_STATE_DIR === effectiveStateDir
551+
? { kind: "sealed", reason: "foreign-owner" }
552+
: { kind: "writable" },
490553
);
491554
const before = await snapshotConfig();
492555

@@ -522,6 +585,7 @@ describe("runDaemonInstall integration", () => {
522585
} else {
523586
serviceMock.readDefinitionMutationCapability.mockResolvedValueOnce({
524587
kind,
588+
reason: kind === "sealed" ? "foreign-owner" : "inspection-failed",
525589
detail: secret,
526590
} as never);
527591
}

‎src/cli/daemon-cli/install.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -199,12 +199,9 @@ export async function runDaemonInstall(opts: DaemonInstallOptions) {
199199
for (const environment of [effectiveServiceEnv, installEnv]) {
200200
const capability = await service
201201
.readDefinitionMutationCapability?.({ env: process.env, environment })
202-
.catch(() => ({ kind: "unknown" as const, detail: "" }));
203-
if (capability && capability.kind !== "writable") {
204-
assertServiceDefinitionWritable({
205-
kind: capability.kind,
206-
detail: "Service definition cannot be safely modified.",
207-
});
202+
.catch(() => ({ kind: "unknown", reason: "inspection-failed" }) as const);
203+
if (capability) {
204+
assertServiceDefinitionWritable(capability);
208205
}
209206
}
210207
return true;

‎src/cli/daemon-cli/start-repair.test.ts‎

Lines changed: 42 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -146,14 +146,36 @@ describe("repairLoadedGatewayServiceForStart", () => {
146146
vi.unstubAllEnvs();
147147
});
148148

149-
it.each(["sealed", "unknown"] as const)(
150-
"denies definition repair before config or token work when authority is %s",
151-
async (kind) => {
149+
it.each([
150+
{
151+
kind: "sealed",
152+
reason: "foreign-owner",
153+
artifact: "service-file",
154+
guidance: "deployment owner",
155+
},
156+
{
157+
kind: "unknown",
158+
reason: "unsafe-permissions",
159+
artifact: "service-directory",
160+
guidance: "chmod go-w",
161+
},
162+
{
163+
kind: "unknown",
164+
reason: "inspection-failed",
165+
artifact: "service-file",
166+
guidance: "Inspect service definition access",
167+
},
168+
] as const)(
169+
"explains $reason without exposing raw details or doing config/token work",
170+
async ({ guidance, ...capability }) => {
152171
const install = vi.fn();
153172
const service = {
154173
install,
155174
isLoaded: vi.fn(async () => true),
156-
readDefinitionMutationCapability: vi.fn(async () => ({ kind, detail: "protected" })),
175+
readDefinitionMutationCapability: vi.fn(async () => ({
176+
...capability,
177+
detail: "repair-inspection-secret-canary",
178+
})),
157179
};
158180
const state: GatewayServiceState = {
159181
installed: true,
@@ -165,15 +187,22 @@ describe("repairLoadedGatewayServiceForStart", () => {
165187
environment: { HOME: "/home/openclaw" },
166188
},
167189
};
168-
await expect(
169-
repairLoadedGatewayServiceForStart({
170-
service,
171-
state,
172-
issues: [{ code: "missing-program", message: "missing" }],
173-
json: true,
174-
stdout: process.stdout,
175-
}),
176-
).rejects.toThrow(`SERVICE_DEFINITION_${kind.toUpperCase()}`);
190+
const params = {
191+
service,
192+
state,
193+
issues: [{ code: "missing-program" as const, message: "missing" }],
194+
json: true,
195+
stdout: process.stdout,
196+
};
197+
for (const action of ["start", "restart"] as const) {
198+
const repair =
199+
action === "restart"
200+
? repairLoadedGatewayServiceForStart({ ...params, action })
201+
: repairLoadedGatewayServiceForStart(params);
202+
await expect(repair).rejects.toThrow(`SERVICE_DEFINITION_${capability.kind.toUpperCase()}`);
203+
await expect(repair).rejects.toThrow(guidance);
204+
await expect(repair).rejects.not.toThrow("secret-canary");
205+
}
177206
expect(readConfigFileSnapshotForWriteMock).not.toHaveBeenCalled();
178207
expect(resolveGatewayInstallTokenMock).not.toHaveBeenCalled();
179208
expect(install).not.toHaveBeenCalled();

‎src/cli/daemon-cli/start-repair.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -153,12 +153,9 @@ export async function repairLoadedGatewayServiceForStart(
153153
// Repair can persist a generated token; check definition authority before planning it.
154154
const capability = await params.service
155155
.readDefinitionMutationCapability?.({ env: process.env, environment: params.state.env })
156-
.catch(() => ({ kind: "unknown" as const, detail: "" }));
157-
if (capability && capability.kind !== "writable") {
158-
assertServiceDefinitionWritable({
159-
kind: capability.kind,
160-
detail: "Service definition cannot be safely modified.",
161-
});
156+
.catch(() => ({ kind: "unknown", reason: "inspection-failed" }) as const);
157+
if (capability) {
158+
assertServiceDefinitionWritable(capability);
162159
}
163160
if (
164161
hasGatewayServiceLauncherOverride(params.state.command) ||

‎src/cli/update-cli/update-command-service.integration.test.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ beforeEach(async () => {
200200
});
201201
mocks.handoff.mockReturnValue({ ok: true, value: Promise.resolve(true) });
202202
mocks.events = [];
203-
mocks.capability.mockResolvedValue({ kind: "sealed", detail: "operator-owned definition" });
203+
mocks.capability.mockResolvedValue({ kind: "sealed", reason: "foreign-owner" });
204204
mocks.command.mockResolvedValue({
205205
programArguments: [
206206
process.execPath,
@@ -288,7 +288,9 @@ describe("preserved update activation with real version guards", () => {
288288
environment: { HOME: root, MANAGED_VALUE: "revalidated" },
289289
});
290290
mocks.capability.mockResolvedValue(
291-
late ? { kind: "writable" } : { kind: denial, detail: "owner denial" },
291+
late
292+
? { kind: "writable" }
293+
: { kind: denial, reason: denial === "sealed" ? "foreign-owner" : "inspection-failed" },
292294
);
293295
const before = await maybeStopManagedServiceBeforeMutableUpdate({
294296
updateInstallKind: mode === "git" ? "git" : "package",
@@ -300,7 +302,10 @@ describe("preserved update activation with real version guards", () => {
300302
const repair = vi.spyOn(startRepair, "repairLoadedGatewayServiceForStart");
301303
mocks.child.mockImplementation(async (args) => {
302304
if (args.includes("install")) {
303-
mocks.capability.mockResolvedValue({ kind: denial, detail: "late owner denial" });
305+
mocks.capability.mockResolvedValue({
306+
kind: denial,
307+
reason: denial === "sealed" ? "foreign-owner" : "inspection-failed",
308+
});
304309
if (outcome === "uninspectable") {
305310
mocks.command.mockRejectedValue(new Error("manager inspection failed"));
306311
} else if (outcome === "foreign") {
@@ -762,7 +767,7 @@ describe("preserved update activation with real version guards", () => {
762767
"fresh restart keeps the preserved launcher even when authority is %s",
763768
async (kind) => {
764769
mocks.capability.mockResolvedValue(
765-
kind === "sealed" ? { kind, detail: "operator-owned definition" } : { kind },
770+
kind === "sealed" ? { kind, reason: "foreign-owner" } : { kind },
766771
);
767772
await expect(runDaemonRestart({ json: true, preserveDefinition: true })).resolves.toBe(true);
768773
expect(mocks.restart).toHaveBeenCalledOnce();

0 commit comments

Comments
 (0)