Skip to content

Commit e31de4a

Browse files
authored
fix(daemon): audit effective systemd properties (#128705)
1 parent e45e4ca commit e31de4a

4 files changed

Lines changed: 160 additions & 6 deletions

File tree

‎src/cli/daemon-cli/status.gather.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,7 @@ describe("gatherDaemonStatus", () => {
360360
deleteTestEnvValue("DAEMON_GATEWAY_PASSWORD");
361361
isDefaultInstallIdentity.mockReset().mockReturnValue(true);
362362
isGatewayExternallySupervised.mockReset().mockReturnValue(false);
363+
auditGatewayServiceConfig.mockClear();
363364
callGatewayStatusProbe.mockClear();
364365
resolveAdvertisedControlUiLinks.mockClear();
365366
resolveAdvertisedControlUiLinks.mockResolvedValue({
@@ -740,7 +741,7 @@ describe("gatherDaemonStatus", () => {
740741
expect((status.service.runtime as { detail?: string }).detail).toBe("19001");
741742
});
742743

743-
it("bounds both service-manager reads and still emits JSON after they time out", async () => {
744+
it("bounds all service-manager reads and still emits JSON after they time out", async () => {
744745
serviceIsLoaded.mockImplementationOnce(async (args?: { timeoutMs?: number }) => {
745746
if (args?.timeoutMs === undefined) {
746747
return await new Promise<boolean>(() => {});
@@ -762,6 +763,9 @@ describe("gatherDaemonStatus", () => {
762763

763764
expect(serviceIsLoaded).toHaveBeenCalledWith(expect.objectContaining({ timeoutMs: 100 }));
764765
expect(serviceReadRuntime).toHaveBeenCalledWith(expect.any(Object), { timeoutMs: 100 });
766+
expect(auditGatewayServiceConfig).toHaveBeenCalledWith(
767+
expect.objectContaining({ timeoutMs: 100 }),
768+
);
765769
expect(status.service.loadState).toEqual({
766770
status: "unknown",
767771
detail: "Error: systemctl is-enabled timed out",

‎src/cli/daemon-cli/status.gather.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,7 @@ export async function gatherDaemonStatus(
618618
auditGatewayServiceConfig({
619619
env: process.env,
620620
command,
621+
timeoutMs,
621622
}),
622623
)
623624
: { ok: true, issues: [] satisfies ServiceConfigAudit["issues"] };

‎src/daemon/service-audit.test.ts‎

Lines changed: 125 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
5-
import { describe, expect, it } from "vitest";
5+
import { beforeEach, describe, expect, it, vi } from "vitest";
66
import {
77
auditGatewayServiceConfig,
88
checkTokenDrift,
@@ -11,6 +11,21 @@ import {
1111
import { buildServiceEnvironment } from "./service-env.js";
1212
import type { GatewayServiceEnvironmentValueSource } from "./service-types.js";
1313

14+
const execSystemctlUser = vi.hoisted(() =>
15+
vi.fn<
16+
(
17+
env: NodeJS.ProcessEnv,
18+
args: string[],
19+
timeoutMs?: number,
20+
) => Promise<{ stdout: string; stderr: string; code: number }>
21+
>(),
22+
);
23+
24+
vi.mock("./systemd-exec.js", async (importOriginal) => ({
25+
...(await importOriginal<typeof import("./systemd-exec.js")>()),
26+
execSystemctlUser,
27+
}));
28+
1429
function buildMinimalServicePath(options: {
1530
platform: NodeJS.Platform;
1631
env: Record<string, string | undefined>;
@@ -65,9 +80,13 @@ function createGatewayAudit({
6580
});
6681
}
6782

68-
async function writeSystemdUnitForAudit(home: string, lines: string[]) {
83+
async function writeSystemdUnitForAudit(
84+
home: string,
85+
lines: string[],
86+
unitName = "openclaw-gateway.service",
87+
) {
6988
const unitDir = path.join(home, ".config", "systemd", "user");
70-
const unitPath = path.join(unitDir, "openclaw-gateway.service");
89+
const unitPath = path.join(unitDir, unitName);
7190
await fs.mkdir(unitDir, { recursive: true });
7291
await fs.writeFile(
7392
unitPath,
@@ -101,6 +120,11 @@ function expectTokenAudit(
101120
}
102121

103122
describe("auditGatewayServiceConfig", () => {
123+
beforeEach(() => {
124+
execSystemctlUser.mockReset();
125+
execSystemctlUser.mockResolvedValue({ stdout: "", stderr: "systemd unavailable", code: 1 });
126+
});
127+
104128
it("flags bun runtime", async () => {
105129
const audit = await auditGatewayServiceConfig({
106130
env: { HOME: "/tmp" },
@@ -500,6 +524,103 @@ describe("auditGatewayServiceConfig", () => {
500524
expectTokenAudit(audit, { embedded: true, mismatch: true });
501525
});
502526

527+
it.each([
528+
{
529+
name: "uses manager KillMode instead of the base unit",
530+
unit: [
531+
"After=network-online.target",
532+
"Wants=network-online.target",
533+
"RestartSec=5",
534+
"KillMode=control-group",
535+
],
536+
manager: [
537+
"KillMode=process",
538+
"RestartUSec=5s",
539+
"After=network-online.target",
540+
"Wants=network-online.target",
541+
],
542+
code: SERVICE_AUDIT_CODES.systemdKillModeProcessOrNone,
543+
expected: true,
544+
},
545+
{
546+
name: "uses manager RestartUSec instead of the base unit",
547+
unit: [
548+
"After=network-online.target",
549+
"Wants=network-online.target",
550+
"RestartSec=100ms",
551+
"KillMode=control-group",
552+
],
553+
manager: [
554+
"Wants=network-online.target",
555+
"KillMode=control-group",
556+
"RestartUSec=5s",
557+
"After=network-online.target",
558+
],
559+
code: SERVICE_AUDIT_CODES.systemdRestartSec,
560+
expected: false,
561+
},
562+
{
563+
name: "uses manager After dependencies absent from the base unit",
564+
unit: ["Wants=network-online.target", "RestartSec=5", "KillMode=control-group"],
565+
manager: [
566+
"RestartUSec=5s",
567+
"After=basic.target network-online.target",
568+
"KillMode=control-group",
569+
"Wants=network-online.target",
570+
],
571+
code: SERVICE_AUDIT_CODES.systemdAfterNetworkOnline,
572+
expected: false,
573+
},
574+
{
575+
name: "does not refill missing manager Wants from the base unit",
576+
unit: [
577+
"After=network-online.target",
578+
"Wants=network-online.target",
579+
"RestartSec=5",
580+
"KillMode=control-group",
581+
],
582+
manager: [
583+
"After=network-online.target",
584+
"RestartUSec=5s",
585+
"Wants=basic.target",
586+
"KillMode=control-group",
587+
],
588+
code: SERVICE_AUDIT_CODES.systemdWantsNetworkOnline,
589+
expected: true,
590+
},
591+
])("respects systemd manager authority: $name", async ({ unit, manager, code, expected }) => {
592+
const home = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-service-audit-manager-"));
593+
try {
594+
const unitName = "openclaw-audit.service";
595+
const env = { HOME: home, OPENCLAW_SYSTEMD_UNIT: unitName };
596+
await writeSystemdUnitForAudit(home, unit, unitName);
597+
execSystemctlUser.mockResolvedValueOnce({
598+
stdout: manager.join("\n"),
599+
stderr: "",
600+
code: 0,
601+
});
602+
603+
const audit = await auditGatewayServiceConfig({
604+
env,
605+
platform: "linux",
606+
timeoutMs: 321,
607+
command: {
608+
programArguments: ["/usr/bin/node", "gateway"],
609+
environment: { PATH: "/usr/bin:/bin" },
610+
},
611+
});
612+
613+
expect(hasIssue(audit, code)).toBe(expected);
614+
expect(execSystemctlUser).toHaveBeenCalledExactlyOnceWith(
615+
env,
616+
["show", unitName, "--no-page", "--property", "After,Wants,RestartUSec,KillMode"],
617+
321,
618+
);
619+
} finally {
620+
await fs.rm(home, { recursive: true, force: true });
621+
}
622+
});
623+
503624
it.each(["process", "none"])(
504625
`warns when KillMode is %s in explicit unit file`,
505626
async (killMode) => {
@@ -524,6 +645,7 @@ describe("auditGatewayServiceConfig", () => {
524645
(entry) => entry.code === SERVICE_AUDIT_CODES.systemdKillModeProcessOrNone,
525646
),
526647
).toBe(true);
648+
expect(execSystemctlUser).toHaveBeenCalledWith({ HOME: home }, expect.any(Array), 10_000);
527649
},
528650
);
529651

‎src/daemon/service-audit.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { POSIX_SHELL_WRAPPERS } from "../infra/shell-wrapper-resolution.js";
1111
import { parseTcpPort } from "../infra/tcp-port.js";
1212
import { resolveLaunchAgentPlistPath } from "./launchd.js";
1313
import { isBunRuntime, isNodeRuntime } from "./runtime-binary.js";
14+
import { parseKeyValueOutput } from "./runtime-parse.js";
1415
import {
1516
isSystemNodePath,
1617
isVersionManagedNodePath,
@@ -24,6 +25,8 @@ import {
2425
} from "./service-managed-env.js";
2526
import { isNonMinimalServicePathEntry, normalizeServicePathEntry } from "./service-path-policy.js";
2627
import type { GatewayServiceEnvironmentValueSource } from "./service-types.js";
28+
import { execSystemctlUser } from "./systemd-exec.js";
29+
import { resolveSystemdServiceName } from "./systemd-service-files.js";
2730
import { resolveSystemdUserUnitPath } from "./systemd.js";
2831

2932
export type GatewayServiceCommand = {
@@ -82,6 +85,7 @@ function hasGatewaySubcommand(programArguments?: string[]): boolean {
8285

8386
const POSIX_SERVICE_INLINE_COMMAND_FLAGS = new Set(["-c"]);
8487
const POSIX_SERVICE_SHELL_WRAPPERS: ReadonlySet<string> = POSIX_SHELL_WRAPPERS;
88+
const SYSTEMD_AUDIT_TIMEOUT_MS = 10_000;
8589

8690
function isOpaquePosixShellInlineCommand(programArguments: string[]): boolean {
8791
const executable = programArguments[0]?.trim();
@@ -176,6 +180,7 @@ function parseSystemdRestartSecSeconds(value: string): number | undefined {
176180
async function auditSystemdUnit(
177181
env: Record<string, string | undefined>,
178182
issues: ServiceConfigIssue[],
183+
timeoutMs?: number,
179184
) {
180185
const unitPath = resolveSystemdUserUnitPath(env);
181186
let content;
@@ -185,7 +190,28 @@ async function auditSystemdUnit(
185190
return;
186191
}
187192

188-
const parsed = parseSystemdUnit(content);
193+
// The manager owns merged drop-ins and dependency links. Fall back wholesale
194+
// to the base unit only when its bounded effective-state query fails.
195+
const manager = await execSystemctlUser(
196+
env,
197+
[
198+
"show",
199+
`${resolveSystemdServiceName(env)}.service`,
200+
"--no-page",
201+
"--property",
202+
"After,Wants,RestartUSec,KillMode",
203+
],
204+
timeoutMs && timeoutMs > 0 ? timeoutMs : SYSTEMD_AUDIT_TIMEOUT_MS,
205+
);
206+
const entries = manager.code === 0 ? parseKeyValueOutput(manager.stdout, "=") : undefined;
207+
const parsed = entries
208+
? {
209+
after: new Set(entries.after?.split(/\s+/).filter(Boolean)),
210+
wants: new Set(entries.wants?.split(/\s+/).filter(Boolean)),
211+
restartSec: entries.restartusec,
212+
killMode: entries.killmode,
213+
}
214+
: parseSystemdUnit(content);
189215
if (!parsed.after.has("network-online.target")) {
190216
issues.push({
191217
code: SERVICE_AUDIT_CODES.systemdAfterNetworkOnline,
@@ -582,6 +608,7 @@ export async function auditGatewayServiceConfig(params: {
582608
expectedManagedServiceEnvKeys?: Iterable<string>;
583609
expectedServicePath?: string;
584610
expectedPort?: number;
611+
timeoutMs?: number;
585612
}): Promise<ServiceConfigAudit> {
586613
const issues: ServiceConfigIssue[] = [];
587614
const platform = params.platform ?? process.platform;
@@ -599,7 +626,7 @@ export async function auditGatewayServiceConfig(params: {
599626
await auditGatewayRuntime(params.env, params.command, issues, platform);
600627

601628
if (platform === "linux") {
602-
await auditSystemdUnit(params.env, issues);
629+
await auditSystemdUnit(params.env, issues, params.timeoutMs);
603630
} else if (platform === "darwin") {
604631
await auditLaunchdPlist(params.env, issues);
605632
}

0 commit comments

Comments
 (0)